[Tutor] rockpaperscissors

alan.gauld@bt.com alan.gauld@bt.com
Mon Jan 27 08:54:01 2003


> I have enclosed some code for the game 'Rock, Paper, Scissors'. 


> 1. I'm sure that there must be a more elegant way of writing 
> this code,

Its not too bad given the size of the problem. You can of course 
build on all sorts of extra sophistication, but its gardly worth 
it IMHO.

> so any suggestions would be useful, if only for aesthetic purposes.

One area that might be more e;egant is to drive the results() function 
from a data structure:

# results is a dictionary of dictionaries
outcomes = ["Scissors cuts Paper", "Paper wraps Rock", "Rock smashes
Scissors"]
winners = ["Drawn game", "Computer won", "You won"]
results = { 1: { 2: outcomes[1] + winners[1],
                 3: outcomes[2] + winners[2] },
            2: { 1: outcomes[1] + winners[2],
                 3: outcomes[0] + winners[1]},
            3: { 1: outcomes[2] + winners[1],
                 2: outcomes[0] + winners[2]}
          }

Now your function just becomes a case of looking up the dictionary 
and printing the result. But its not that much prettier and only 
saves a tiny bit of maintenance effort.

> 2. I was wanting to include a way of counting the number of 
> wins for the computer and for the user. 

There are 3 outcomes - Computer Wins, User wins, or draw. 
You can return that from the return function by making the 
return value a tuple containing the result code and result 
string. 

Represent that with 0,1,2 - which coincidentally(!) are the 
indices of the winners string list above, making translation 
easy...

Then use a line in the loop like:

if result[0] == -1: draw += 1
elif result[0] == 0: computer += 1
else user += 1

HTH,

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/