Can someone explain how this code works? (Rock, paper, scissors)


I have the following code:

choice = ['rock', 'scissors', 'paper']

# Game loop
while True:
    player1 = input("Player 1 - Rock, Paper, Scissors? ").lower()
    player2 = input("Player 2 - Rock, Paper, Scissors? ").lower()
    if choice.index(player1) == (choice.index(player2) + 1) % 3:
        print('Player 2 wins!')
    elif choice.index(player2) == (choice.index(player1) + 1) % 3:
        print('Player 1 wins!')
        print("Its a draw! Try again")

I’ve been trying to figure out how it works, but can’t get my head around +1 % 3 part. Can someone explain?
If you change the choice dictionary to

choice = ['rock', 'paper', 'scissors']

The code breaks, it doesn’t seem to work unless the dictionary is rock, scissors, paper.

Thanks in advance.

1 Like

for this to work, the list has to be in the right order (rock beat scissor, scissors beats paper and paper beats rock). You could have ['paper', 'rock', 'scissors'], that will also work

in other words, if you picked the first element, and the computer picks the next element (second) element in the list, you win

the only problem is to get from the last to the first element in the list, this is where the modulo operator comes in (%)

1 Like

When everything is working and you have it saved, that’s the time to go over the processes and see if they can be streamlined or simplified. It’s a good way to build up a knowledge base of approaches and be able to judge from experience which are more sound, effective and efficient.


checkForWin = {
    'rock': 'paper',
    'paper': 'scissors',
    'scissors': 'rock'
a = 'rock'
b = 'paper'
b === checkForWin[a]    // true