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:
if human== "paper" and computer == "scissors":print("You lose")elif human== "paper" and computer == "stone":print("You win")elif human== "paper" and computer == "paper":print("Draw")elif human== "scissors" and computer == "paper":print("You win")elif human== "scissors" and computer == "stone":print("You lose")elif human== "scissors" and computer == "scissors":print("Draw")elif human== "stone" and computer == "scissors":print("You win")elif human== "stone" and computer == "paper":print("You lose")elif human== "stone" and computer == "stone":print("Draw")
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:
import randomhuman = input("Your choice? ")comp = random.randint(1,3)if comp==1:computer = "paper"elif comp==2:computer = "scissors"elif comp==3:computer = "stone"print("Computer choice: " + computer)if human== "paper" and computer == "scissors":print("You lose")elif human== "paper" and computer == "stone":print("You win")elif human== "paper" and computer == "paper":print("Draw")elif human== "scissors" and computer == "paper":print("You win")elif human== "scissors" and computer == "stone":print("You lose")elif human== "scissors" and computer == "scissors":print("Draw")elif human== "stone" and computer == "scissors":print("You win")elif human== "stone" and computer == "paper":print("You lose")elif human== "stone" and computer == "stone":print("Draw")else:print("Invalid input.")