[Tutor] Rock, Paper, Scissors game
Peter Otten
__peter__ at web.de
Fri Jul 26 15:06:28 CEST 2013
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 would never have come up with this line, but I think it can be pictured as
follows:
Given the cycle
+-->rock-->paper-->scissors--+
| |
+---------------<------------+
and only one direction allowed the winning "weapon" is always the one
farther away from the loser, e. g.
rock vs paper
rock-->paper: 1 step
paper-->scissors-->rock: 2 steps
paper wins
rock vs rock:
0 steps both
tie
The modulo operator helps with determining this "directed distance" by
maintaining
-n == N-n
e. g.
-1 % 3 == 3 - 1 == 2
You could anecdotally test the above outline by adding more weapons. For
four weapons you should get ties between distinct weapons:
+-->rock-->paper-->scissors-->banana--+
| |
+---------------<---------------------+
rock vs scissors:
rock-->paper-->scissors: 2 steps
scissors-->banana-->rock: 2 steps
tie
You can modify the script to work with an arbitrary number of weapons by
replacing 3 with length(weapons) if you like.
> print "Player wins"
> else:
> print "CPU wins"
> else:
> print "tie!"
>
> Thanks.
More information about the Tutor
mailing list