6. Exercise: Paper, Scissors, Stone game
Let's use what we have learn so far to build a simple game: Paper, Scissors, Stone.
First, we want to map out the logic of the game, which will help us build a series of if...elsif... statements. There can only be finite number of results, as shown below:
Human (you)
Computer
Result
Paper
Scissors
You lose
Paper
Stone
You win
Paper
Paper
Draw
Scissors
Paper
You win
Scissors
Stone
You lose
Scissors
Scissors
Draw
Stone
Scissors
You win
Stone
Paper
You lose
Stone
Stone
Draw
Now, we are ready to capture the above logic into a series of if...elsif... statements:
1
if human== "paper" and computer == "scissors":
2
print("You lose")
3
elif human== "paper" and computer == "stone":
4
print("You win")
5
elif human== "paper" and computer == "paper":
6
print("Draw")
7
elif human== "scissors" and computer == "paper":
8
print("You win")
9
elif human== "scissors" and computer == "stone":
10
print("You lose")
11
elif human== "scissors" and computer == "scissors":
12
print("Draw")
13
elif human== "stone" and computer == "scissors":
14
print("You win")
15
elif human== "stone" and computer == "paper":
16
print("You lose")
17
elif human== "stone" and computer == "stone":
18
print("Draw")
Copied!
You can also add a user input using input() function, randomized the computer choice using random.randin() function, as well as adding an else "end all" condition to improve the game:
1
import random
2
3
human = input("Your choice? ")
4
5
comp = random.randint(1,3)
6
if comp==1:
7
computer = "paper"
8
elif comp==2:
9
computer = "scissors"
10
elif comp==3:
11
computer = "stone"
12
print("Computer choice: " + computer)
13
14
if human== "paper" and computer == "scissors":
15
print("You lose")
16
elif human== "paper" and computer == "stone":
17
print("You win")
18
elif human== "paper" and computer == "paper":
19
print("Draw")
20
elif human== "scissors" and computer == "paper":
21
print("You win")
22
elif human== "scissors" and computer == "stone":
23
print("You lose")
24
elif human== "scissors" and computer == "scissors":
25
print("Draw")
26
elif human== "stone" and computer == "scissors":
27
print("You win")
28
elif human== "stone" and computer == "paper":
29
print("You lose")
30
elif human== "stone" and computer == "stone":
31
print("Draw")
32
else:
33
print("Invalid input.")
Copied!
Copy link