[Tutor] more rps

Wolfram Kraus kraus at hagen-partner.de
Tue Aug 15 09:01:57 CEST 2006


On 15.08.2006 08:42, Christopher Spears wrote:
> Here is the latest version of my Rock, Paper, Scissors
> game:
> 
> #!/usr/bin/python
> 
> import random
> random.seed()
> 
> class Human:
> 	def __init__(self):
> 		self.points = 0
> 		self.choice = " "
> 		
> 	def plays(self):
> 		fromUser = raw_input("Pick (R)ock, (P)aper, or
> (S)cissors! ")
> 		translate = {'r':'rock', 's':'scissors',
> 'p':'paper'} 
> 		try:
> 			self.choice = translate[fromUser.lower()]
> 		except KeyError:
> 			print 'Invalid Response'
> 	
> class Computer:
> 	def __init__(self):
> 		self.points = 0
> 		self.choice = " "
> 	
> 	def plays(self):
> 		comp_choice = random.randint(0,2)
> 		if comp_choice == 0:
> 			self.choice = 'rock'
> 		elif comp_choice == 1:
> 			self.choice = 'paper'
> 		else:
> 			self.choice = 'scissors'
> 			
> def compare_objects(human, computer):
> 	print "Human picked ", human.choice
> 	print "Computer picked", computer.choice
> 	results = { 'rock' : {'rock' : 'draw', 'paper': 0,
> 'scissors': 1},
> 		'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
> 0},
> 		'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
> 'draw'}
> 		}
> 		
> 	outcome = results[human.choice][computer.choice]
> 	if outcome == 0:
> 		print "Computer Wins!"
> 		computer.points = computer.points + 1
> 	elif outcome == 1:
> 		print "Human Wins!"
> 		human.points = human.points + 1
> 	else:
> 		print "Draw!"
> 		
> 
> if __name__ == "__main__":
> 	print "Welcome to Rock, Paper, Scissors!"
> 	final_points = raw_input("Play to how many points? ")
> 	human = Human()
> 	computer = Computer()
> 	while (human.points < final_points or computer.points
> < final_points):
> 		human.plays()
> 		computer.plays()
> 		compare_objects(human, computer)
> 		print "Score:\tHuman: ",human.points,"\tComputer:
> ",computer.points
> 	print "Game Over!"
> 	
> 	
> I actually figured out how to build the 2x2 matrix. 
> I'm quite proud of this.  Like all of my good ideas,
> the answer came to me in the shower. :-)
> 
> Unfortunately, my while loop doesn't seem to be
> working.  I've played around with it with no success. 
> Hints, anyone?
> 

Look at the type of human.points and final_points:

>>> final_points = raw_input("Play to how many points? ")
Play to how many points? 10
>>> type(final_points)
<type 'str'>
>>> 1 < final_points
True
>>> 100 < final_points
True
>>> 1000 < final_points
True

HTH,
Wolfram



More information about the Tutor mailing list