Rock Paper Scissors
In this version of the two-player hand game also known as Rochambeau or jan-ken-pon, the player faces off against the computer. You can pick either rock, paper, or scissors. Rock beats scissors, scissors beats paper, and paper beats rock. This program adds some brief pauses for suspense.
rock_paper_scissors.py
1"""Rock, Paper, Scissors, by Al Sweigart al@inventwithpython.com
2The classic hand game of luck.
3This code is available at https://nostarch.com/big-book-small-python-programming
4Tags: short, game"""
5
6import random, time, sys
7
8print('''Rock, Paper, Scissors, by Al Sweigart al@inventwithpython.com
9- Rock beats scissors.
10- Paper beats rocks.
11- Scissors beats paper.
12''')
13
14# These variables keep track of the number of wins, losses, and ties.
15wins = 0
16losses = 0
17ties = 0
18
19while True: # Main game loop.
20 while True: # Keep asking until player enters R, P, S, or Q.
21 print('{} Wins, {} Losses, {} Ties'.format(wins, losses, ties))
22 print('Enter your move: (R)ock (P)aper (S)cissors or (Q)uit')
23 playerMove = input('> ').upper()
24 if playerMove == 'Q':
25 print('Thanks for playing!')
26 sys.exit()
27
28 if playerMove == 'R' or playerMove == 'P' or playerMove == 'S':
29 break
30 else:
31 print('Type one of R, P, S, or Q.')
32
33 # Display what the player chose:
34 if playerMove == 'R':
35 print('ROCK versus...')
36 playerMove = 'ROCK'
37 elif playerMove == 'P':
38 print('PAPER versus...')
39 playerMove = 'PAPER'
40 elif playerMove == 'S':
41 print('SCISSORS versus...')
42 playerMove = 'SCISSORS'
43
44 # Count to three with dramatic pauses:
45 time.sleep(0.5)
46 print('1...')
47 time.sleep(0.25)
48 print('2...')
49 time.sleep(0.25)
50 print('3...')
51 time.sleep(0.25)
52
53 # Display what the computer chose:
54 randomNumber = random.randint(1, 3)
55 if randomNumber == 1:
56 computerMove = 'ROCK'
57 elif randomNumber == 2:
58 computerMove = 'PAPER'
59 elif randomNumber == 3:
60 computerMove = 'SCISSORS'
61 print(computerMove)
62 time.sleep(0.5)
63
64 # Display and record the win/loss/tie:
65 if playerMove == computerMove:
66 print('It\'s a tie!')
67 ties = ties + 1
68 elif playerMove == 'ROCK' and computerMove == 'SCISSORS':
69 print('You win!')
70 wins = wins + 1
71 elif playerMove == 'PAPER' and computerMove == 'ROCK':
72 print('You win!')
73 wins = wins + 1
74 elif playerMove == 'SCISSORS' and computerMove == 'PAPER':
75 print('You win!')
76 wins = wins + 1
77 elif playerMove == 'ROCK' and computerMove == 'PAPER':
78 print('You lose!')
79 losses = losses + 1
80 elif playerMove == 'PAPER' and computerMove == 'SCISSORS':
81 print('You lose!')
82 losses = losses + 1
83 elif playerMove == 'SCISSORS' and computerMove == 'ROCK':
84 print('You lose!')
85 losses = losses + 1