[Tutor] Rock, Paper, Scissors

John Fouhy john at fouhy.net
Fri Aug 11 02:02:50 CEST 2006


Hi Chris,

On 11/08/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>        def plays(self):
>                self.choice = raw_input("Pick (R)ock, (P)aper, or
> (S)cissors! ")
>                if self.choice == 'r':
>                        self.choice = 'rocks'
>                elif self.choice == 'p':
>                        self.choice = 'paper'
>                elif self.choice == 's':
>                        self.choice = 'scissors'
>                else:
>                        print "Invalid response"

A couple of comments here ---

Firstly, to me, 'self.choice' is the thing you want to save, which is
distinct from the user's input.  So, I would call the result of
raw_input something else.  eg:

    fromUser = raw_input("Pick (R)ock, (P)aper, or
(S)cissors! ")
    if fromUser == 'r':
        self.choice = 'rocks'
    # etc

Secondly, if the user enters 'R' (as you request), your program will
say "Invalid response", because 'R' != 'r'.  You can get around this
by saying:

    if fromUser.lower() == 'r':

Thirdly, a dictionary would make this much simpler.  Something like:

    translate = { 'r':'rock', 's':'scissors', 'p':'paper' }
    try:
        self.choice = translate[fromUser.lower()]
    except KeyError:
        print 'Invalid response.'
        # what else are you going to do?  what does self.choice become?

> def compare_objects(human, computer):
>        print "Human picked ", human.choice
>        print "Computer picked", computer.choice
>        if human.choice == computer.choice:
>                print "Draw!"
>        elif human.choice == 'rocks' and computer.choice ==
> 'paper':
>                print "Computer wins!"
>                computer.points = computer.points + 1
[...]

You can use a similar dictionary-based approach here.  You could use a
dictionary to make a data structure that expresses what beats what,
and then reduce your code to:

    if human.choice == computer.choice:
        print 'Draw!'
    elif # human beats computer
        print 'Human wins!'
    else:
        print 'Computer wins!'

HTH :-)

-- 
John.


More information about the Tutor mailing list