small program with strange behavior

Dan Stromberg strombrg at dcs.nac.uci.edu
Sat Nov 22 17:26:43 CET 2003


The below small program is giving strange behavior.  At the bottom of the code,
please find "this works" and "this doesn't work" comments.  Why does one
work and the other not?

TIA.

#!/usr/bin/python

import string

class move_class:
	bad = 'Invalid initializer'

	def __init__(self,str,rank_black,rank_white):
		self.text = str
		self.children = []
		self.rank_black = rank_black
		self.rank_white = rank_white
		if str[0:2] == 'B[':
			#if move_class.prior != '' and move_class.prior != 'W':
			#	raise move_class.bad
			if str[1:2] != '[' or str[4:5] != ']':
				raise move_class.bad
			self.letters = string.lower(str[2:4])
			move_class.prior = 'B'
			self.color = 'B'
			self.ranks=[rank_black]
		elif str[0:2] == 'W[':
			#if move_class.prior != 'B':
			#	raise move_class.bad
			if str[1:2] != '[' or str[4:5] != ']':
				raise move_class.bad
			self.letters = string.lower(str[2:4])
			#move_class.prior = 'W'
			self.color = 'W'
			self.ranks=[rank_white]
		else:
			raise move_class.bad
		self.strrow = self.letters[0:1]
		self.strcol = self.letters[1:2]
		trow = ord(self.strrow) - ord('a')
		if trow >= 11:
			trow = trow - 1
		self.row = trow
		tcol = ord(self.strcol) - ord('a')
		if tcol >= 11:
			tcol = tcol - 1
		self.col = tcol

	def rotate90(self):
		size=19
		self.row,self.col = self.col,size - self.row - 1

	def copy(self):
		newmove = move_class(self.text,self.rank_black,self.rank_white)
		return newmove

	def __str__(self):
		t = ''
		for i in self.ranks:
			t = t + str(i) + ' '
		return str(self.row)+','+str(self.col)+' '+str(self.color)+' '+\
			t

move=move_class('B[qp]',-4,-1)

newgame=[move]

for r in range(4):
	for move_no in range(0,len(newgame)):
		# this doesn't work
		newmove = newgame[move_no].copy()
		# this works
		#newmove = newgame[move_no]
		newmove.rotate90()
		newgame[move_no]=newmove
		print newgame[move_no]




More information about the Python-list mailing list