[Tutor] Programming the behavior of a set of domino

Bob Gailer bgailer at alum.rpi.edu
Fri Feb 23 23:13:07 CET 2007


Chung-hong Chan wrote:
> Hello,
>
> I am a newbie in computer programming and I am also not a native
> English Speaker. I love to play domino and I would like to program a
> simple domino game in python. Also a good opportunity for me to learn
> some computer programming.
> I need some help in my code which programming the behaviors of a set of domino.
> Here is the code, generally a modification of the code from the deck
> of card example in How to Think like a Computer Scientist.
>
> #!/usr/bin/python
> class domino:
>   
It is a convention in Python to capiatlize class names (e.g. class Domino)
> 	def __init__(self,a_end,b_end):
> 		self.a_end=a_end
> 		self.b_end=b_end
> 	def __str__(self):
> 		return ("["+str(self.a_end)+","+str(self.b_end)+"]")
> 	def __cmp__(self,other):
> 		if self.a_end==other.b_end and self.b_end==other.a_end:
> 			return 0
> 		return 1
>
> class deck:
> 	def __init__(self,set_type):
> 		self.dominoes = []
> 		self.set_type = set_type
> 		for a_end in range(self.set_type+1):
> 			for b_end in range(self.set_type+1):
> 				self.dominoes.append(domino(a_end,b_end))
> 	def print_deck(self):
> 		for domino in self.dominoes:
> 			print domino
> 	def deck_len(self):
> 		print len(self.dominoes)
>
>
> newdomino = deck(12)
> newdomino.print_deck()
> newdomino.deck_len()
>
> if domino(1,2)==domino(2,2):
> 	print "yes"
> else:
> 	print "no"
>
> each piece of domino have a_end and b_end. domino (1,2) and
> domino(2,1) is the same and thus one of them should be removed. Now,
> deck(12) will return 169 dominoes while the expected number of
> dominoes is 91. Even I wrote a __cmp__ method for domino, list
> membership (i.e. x in list) is not working because they are not a
> exact duplicates.
>   
To create only unique dominoes:

		for a_end in range(self.set_type+1):
			for b_end in range(a_end, self.set_type+1):
				self.dominoes.append(domino(a_end,b_end))

> Can anyone shed me some light to solve this problem?

-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list