[Tutor] rockpaperscissors
ahimsa
ahimsa@onetel.net.uk
Sun Jan 26 17:00:02 2003
Hey Gang
So many of you were very helpful last time around I wanted to pick your
brains on the following:
I have enclosed some code for the game 'Rock, Paper, Scissors'. The idea
for doing this in Python was drawn from Tim Wilson's lessons for the
Henry Sibley school ( http://isd197.org/sibley/cs/icp/ ), but I have run
aground on a couple of aspects:
1. I'm sure that there must be a more elegant way of writing this code,
so any suggestions would be useful, if only for aesthetic purposes.
2. I was wanting to include a way of counting the number of wins for the
computer and for the user. This might follow on 'naturally' from a more
elegant code lay-out, but I've tried as many ways as I can think of but
can't figure a way to get that in.
FWIW, I must say that playing around with Python is *great* fun - so
unless someone really objects or thinks it inappropriate (in which case,
please tell me) I'd like to continue to forward odd bits of programming
to this list for input and advice, suggestions, and so on.
Much obliged.
Anyway, here's the code (the type-setting will probably be messed up).
All the best
Andrew
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: begin
# Rock, Paper, Scissors:
print "Rock, Paper, Scissors"
# Initialisation phase:
import random # module import to randomise computer's
# selection
counter = 0 # game counter
def item( a ): # locally defined function to convert
if a == 1: # random.randrange( ) into user-friendly words
return "Rock"
elif a == 2:
return "Paper"
elif a == 3:
return "Scissors"
def results( b, c ): # locally defined function to output results
if b == c: # relative to computer's selection
return "That's a tie"
elif ( b == "Rock" and c == "Paper" ):
return "%s covers %s. Computer wins." % ( c, b )
elif ( b == "Rock" and c == "Scissors" ):
return "%s breaks %s. You win." % ( b, c )
elif ( b == "Paper" and c == "Rock" ):
return "%s covers %s. You win." % ( b, c )
elif ( b == "Paper" and c == "Scissors" ):
return "%s cut %s. Computer wins." % ( c, b )
elif ( b == "Scissors" and c == "Rock" ):
return "%s breaks %s. Computer wins." % ( c, b )
elif ( b == "Scissors" and c == "Paper" ):
return "%s cut %s. You win." % ( b, c )
# Processing phase:
while counter < 3: # only want to run the game three times
x = random.randrange( 1, 4 )
print
print "Rock (1), Paper (2), or Scissors (3)"
print
y = int( raw_input( "Make a selection: " ) ) # invite user's input
print "You selected %s and the Computer selected %s" % (item( y ),
item( x ) )
print results( item( y ), item( x )) # output results
counter += 1 # move counter up 1 'click'
print "Hit ENTER to return to the prompt" # basic way of exiting program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: end
--
________________________%%%%%%%%%%%%%%%%%____________________________
Proudly sent using Ximian Evolution 1.2.1 on a Linux Red Hat 8.0 box.