Skip to content

Instantly share code, notes, and snippets.

@therealzanfar
Last active June 14, 2024 03:45
Show Gist options
  • Save therealzanfar/e812b0df417a139ab5737ad4071ffdde to your computer and use it in GitHub Desktop.
Save therealzanfar/e812b0df417a139ab5737ad4071ffdde to your computer and use it in GitHub Desktop.
Python Beginner Project Examples
"""Generic, Extensible Roshambo Game."""
import random
from enum import Enum
from typing import NamedTuple
class OptionDef(NamedTuple):
"""Details about a throw option."""
name: str
class Option(OptionDef, Enum):
"""Throw options."""
ROCK = OptionDef("Rock")
PAPER = OptionDef("Paper")
SCISSORS = OptionDef("Scissors")
LIZARD = OptionDef("Lizard")
SPOCK = OptionDef("Spock")
winners: dict[Option, dict[Option, str]] = {
Option.ROCK: {
Option.SCISSORS: "crushes",
Option.LIZARD: "smashes",
},
Option.PAPER: {
Option.ROCK: "covers",
Option.SPOCK: "disproves",
},
Option.SCISSORS: {
Option.PAPER: "cuts",
Option.LIZARD: "decapitates",
},
Option.LIZARD: {
Option.SPOCK: "poisons",
Option.PAPER: "eats",
},
Option.SPOCK: {
Option.SCISSORS: "smashes",
Option.ROCK: "vaporizes",
},
}
option_list = [o.name for o in Option]
option_string = ", ".join(option_list[:-1]) + ", or " + option_list[-1]
def ask_for_throw() -> Option | None:
"""Ask the player for a throw and return the corresponding Option."""
while True:
print("Choose your throw,")
print(f"{option_string}: ")
print("Or type 'q' to quit.")
player_choice = input("> ")
print()
player_throw: Option | None = None
for o in Option:
if o.name.casefold() == player_choice.casefold():
player_throw = o
break
if player_choice.casefold().startswith("q"):
return None
if player_throw is None:
print("That's not a valid throw. Try again.")
continue
# Valid choice
return player_throw
def main() -> None:
"""Game."""
player_score = 0
computer_score = 0
print(f"Welcome to {', '.join(option_list)}!")
while True:
print()
player_throw = ask_for_throw()
computer_throw = random.choice([o for o in Option]) # noqa: C416
print(f"Computer throws {computer_throw.name}.")
if player_throw is None:
break
if player_throw == computer_throw:
print("It's a tie!")
continue
if computer_throw in winners[player_throw]:
action = winners[player_throw][computer_throw]
print(f"{player_throw.name} {action} {computer_throw.name}.")
print("Player wins!")
player_score += 1
continue
# Otherwise, the computer wins
action = winners[computer_throw][player_throw]
print(f"{computer_throw.name} {action} {player_throw.name}.")
print("Computer wins!")
computer_score += 1
continue
# End of game
print("Thanks for playing!")
print(f"Final score: Player {player_score}, Computer {computer_score}.")
print()
if player_score > computer_score:
print("Player wins the game!")
elif computer_score > player_score:
print("Computer wins the game!")
else:
print("The game is a tie!")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment