[Tutor] Rock, Paper, Scissors game

Dave Angel davea at davea.name
Fri Jul 26 14:20:35 CEST 2013


On 07/26/2013 07:22 AM, Saad Javed wrote:
> I'm trying to understand how this code works. I've commented the line
> that I can't seem to understand. How did the guy come up with this?
>
> #!/usr/bin/env python
>
> import random
>
> #rock > scissor > paper > rock
>
> WEAPONS = 'Rock', 'Paper', 'Scissors'
>
> for i in range(0, 3):
>    print "%d %s" % (i + 1, WEAPONS[i])
>
> player = int(input ("Choose from 1-3: ")) - 1
> cpu = random.choice(range(0, 3))
>
> print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu])
> if cpu != player:
>    if (player - cpu) % 3 < (cpu - player) % 3: #How does this line work?

I'm not sure what aspect of it you're puzzled about, but % is the modulo 
operator.  It produces the remainder upon integer division.  So we're 
effectively dividing by 3, and keeping only the remainder, which will be 
0, 1, or 2.

It will only be zero if cpu==player, but we've already tested that.  So 
the only two cases are 1 and 2.  A little experimenting will show you 
that if the first part( (player-cpu)%3 ) is 1, the second will be 2, and 
vice versa.

So the statement could be simplified to:

      if (player - cpu) % 3 == 1:

Now is it clear?


>      print "Player wins"
>    else:
>      print "CPU wins"
> else:
>    print "tie!"
>

BTW, that input statement should be raw_input, since you're running it 
on Python 2.x.


-- 
DaveA



More information about the Tutor mailing list