This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from collections import Counter | |
from enum import Enum, IntEnum, unique | |
@unique | |
class Outcome(Enum): | |
COMPUTER = 2 | |
TIED = 0 | |
PLAYER = 1 | |
@unique | |
class Choices(IntEnum): | |
ROCK = 1 | |
PAPER = 2 | |
SCISSORS = 3 | |
class Hand: | |
count = 0 | |
sequence: int | |
def __init__(self, player_guess: str, computer_guess: str): | |
if player_guess.upper() not in [choice.name for choice in Choices]: | |
raise ValueError(f"The value {player_guess!r} is invalid.") | |
self.player_guess = player_guess.upper() | |
self.computer_guess = computer_guess | |
self.outcome = Outcome((Choices[self.player_guess].value - Choices[self.computer_guess].value) % len(Choices)) | |
self.message = "Tied." | |
if self.outcome == Outcome.COMPUTER: | |
self.message = "Computer wins." | |
elif self.outcome == Outcome.PLAYER: | |
self.message = "Player wins." | |
self.sequence = Hand.count | |
Hand.count += 1 | |
def __str__(self): | |
return f"sequence={self.sequence}, " \ | |
f"player_guess={self.player_guess!r}, " \ | |
f"computer_guess={self.computer_guess!r}, " \ | |
f"outcome={self.outcome!r}, " | |
def __repr__(self): | |
return f"{self.__class__.__name__}" \ | |
f"(player_guess={self.player_guess!r}, " \ | |
f"computer_guess={self.computer_guess!r})" | |
BESTOF = 5 | |
game_history = [] | |
guess_options = [choice.name for choice in Choices] | |
while not any( | |
(count == BESTOF // 2 + 1 | |
for key, count in | |
(Counter([hand.outcome for hand in game_history]).items()) | |
if key != Outcome.TIED | |
) | |
): | |
computers_guess = random.choice(guess_options) | |
players_guess = random.choice(guess_options) # input("Make your guess: ") # | |
try: | |
game_history.append(Hand(players_guess, computers_guess)) | |
print(f"[{len(game_history)}]: You chose {players_guess!r}, the computer chose {computers_guess!r} - " | |
f"{game_history[-1].message}") | |
except ValueError as e: | |
print(e) | |
print(f"\n=======\nGame ends after {len(game_history)} hands. ") | |
print(f"There were {sum([True for hand in game_history if hand.outcome == Outcome.TIED])} ties, " | |
f"computer won {sum([True for hand in game_history if hand.outcome == Outcome.COMPUTER])} hands, " | |
f"you won {sum([True for hand in game_history if hand.outcome == Outcome.PLAYER])} hands.\n" | |
f"Result: {game_history[-1].message} ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment