Mark As Completed Discussion

3. Rock, paper, scissors game

Games are fun to code in Python. Since it is the number one language for developing AI and ML apps, you can try yourself with any kind of game: chess, tic-tac-toe, snake, and so on.

We chose Rock, paper, and scissors as an example. This mini-game has four functions that this program requires so let us have an overview of each:

  • a random function: to generate rock, paper, or scissors
  • valid function: to check the validity of the move
  • result function: to declare the winner of the round
  • scorekeeper: to keep track of the score

The game asks the user to make the first move before it makes a move itself. Once the move is validated, the input is evaluated, and then a winner is decided by the result function and the score of the round is updated by the scorekeeper function.

PYTHON
1import random
2
3user_action = input("Enter a choice (rock, paper, scissors): ")
4possible_actions = ["rock", "paper", "scissors"]
5computer_action = random.choice(possible_actions)
6print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
7
8if user_action == computer_action:
9    print(f"Both players selected {user_action}. It's a tie!")
10elif user_action == "rock":
11    if computer_action == "scissors":
12        print("Rock smashes scissors! You win!")
13    else:
14        print("Paper covers rock! You lose.")
15elif user_action == "paper":
16    if computer_action == "rock":
17        print("Paper covers rock! You win!")
18    else:
19        print("Scissors cuts paper! You lose.")
20elif user_action == "scissors":
21    if computer_action == "paper":
22        print("Scissors cuts paper! You win!")
23    else:
24        print("Rock smashes scissors! You lose.")