Skip to content

Instantly share code, notes, and snippets.

@teward
Last active November 3, 2019 12:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teward/d303af90949b39a1f94dce84da973ac8 to your computer and use it in GitHub Desktop.
Save teward/d303af90949b39a1f94dce84da973ac8 to your computer and use it in GitHub Desktop.
import random
class RockPaperScissors:
"""
Class to handle an instance of a Rock-Paper-Scissors game
with unlimited rounds.
"""
def __init__(self):
"""
Initialize the variables for the class
"""
self.wins = 0
self.losses = 0
self.ties = 0
self.options = {'rock': 0, 'paper': 1, 'scissors': 2}
def random_choice(self):
"""
Chooses a choice randomly from the keys in self.options.
:returns: String containing the choice of the computer.
"""
return random.choice(list(self.options.keys()))
def check_win(self, player, opponent):
"""
Check if the player wins or loses.
:param player: Numeric representation of player choice from self.options
:param opponent: Numeric representation of computer choice from self.options
:return: Nothing, but will print whether win or lose.
"""
result = (player - opponent) % 3
if result == 0:
self.ties += 1
print("The game is a tie! You are a most worthy opponent!")
elif result == 1:
self.wins += 1
print("You win! My honor demands a rematch!")
elif result == 2:
self.losses += 1
print("Haha, I am victorious! Dare you challenge me again?")
def print_score(self):
"""
Prints a string reflecting the current player score.
:return: Nothing, just prints current score.
"""
print(f"You have {self.wins} wins, {self.losses} losses, and "
f"{self.ties} ties.")
def run_game(self):
"""
Plays a round of Rock-Paper-Scissors with the computer.
:return: Nothing
"""
while True:
userchoice = input("Choices are 'rock', 'paper', or 'scissors'.\n"
"Which do you choose? ").lower()
if userchoice not in self.options.keys():
print("Invalid input, try again!")
else:
break
opponent_choice = self.random_choice()
print(f"You've picked {userchoice}, and I picked {opponent_choice}.")
self.check_win(self.options[userchoice], self.options[opponent_choice])
if __name__ == "__main__":
game = RockPaperScissors()
while True:
game.run_game()
game.print_score()
while True:
continue_prompt = input('\nDo you wish to play again? (y/n): ').lower()
if continue_prompt == 'n':
print("You are weak!")
exit()
elif continue_prompt == 'y':
break
else:
print("Invalid input!\n")
continue
import random
class RockPaperScissors:
"""
Class to handle an instance of a Rock-Paper-Scissors game
with unlimited rounds.
"""
def __init__(self):
"""
Initialize the variables for the class
"""
# Wins are counted in self.wins
self.wins = 0
# Losses are counted in self.losses
self.losses = 0
# Ties are counted in self.ties
self.ties = 0
# The valid options for the RPS game are defined here as a dict.
# This is the equivalent of an enum in some languages which converts
# text-representation of something into a numeric value, and is
# critical for win/loss checking in the check_win function.
self.options = {'rock': 0, 'paper': 1, 'scissors': 2}
def random_choice(self):
"""
Chooses a choice randomly from the keys in self.options.
:returns: String containing the choice of the computer.
"""
return random.choice(list(self.options.keys()))
def check_win(self, player, opponent):
"""
Check if the player wins or loses.
:param player: Numeric representation of player choice from self.options
:param opponent: Numeric representation of computer choice from self.options
:return: Nothing, but will print whether win or lose.
"""
result = (player - opponent) % 3
if result == 0:
# Tie game, adjust self.ties count by one, and print
# the notice of a tie.
self.ties += 1
print("The game is a tie! You are a most worthy opponent!")
elif result == 1:
# Player won, adjust self.wins count by one and
# print a notice of a win.
self.wins += 1
print("You win! My honor demands a rematch!")
elif result == 2:
# Player lost, adjust self.losses count by one and
# print a notice of a loss.
self.losses += 1
print("Haha, I am victorious! Dare you challenge me again?")
def print_score(self):
"""
Prints a string reflecting the current player score.
:return: Nothing, just prints current score.
"""
# Uses f-strings to replace string contents rather than using
# straight string concatenation. Python >= 3.6 only.
print(f"You have {self.wins} wins, {self.losses} losses, and "
f"{self.ties} ties.")
def run_game(self):
"""
Plays a round of Rock-Paper-Scissors with the computer.
:return: Nothing
"""
# Get player choice, and don't stop until player provides a valid choice.
# Utilizes self.options.keys() to get valid choices, which we have
# already defined when we created the game (see __init__ function)
while True:
# We can do 'input().lower()' directly to get lowercase input from
# the user, which saves us redefining the variable again.
userchoice = input("Choices are 'rock', 'paper', or 'scissors'.\n"
"Which do you choose? ").lower()
if userchoice not in self.options.keys():
# If choice not in valid options, error and get input again.
print("Invalid input, try again!")
else:
# Valid input provided, so break this loop and continue with game.
break
# Opponent's choice is randomly decided by the random_choice() function
# in the game's class.
opponent_choice = self.random_choice()
# Now, we state what player and computer chose. Uses f-strings
# again, Python >= 3.6 only.
print(f"You've picked {userchoice}, and I picked {opponent_choice}.")
# Check who won, adjust score accordingly.
self.check_win(self.options[userchoice], self.options[opponent_choice])
if __name__ == "__main__":
# The game is now a class so we need an object to hold the 'instance' of the game
game = RockPaperScissors()
# Now, we just need to *run* the game, which we'll do in a loop here.
while True:
# This handles running the game and printing your score each round
game.run_game() # Runs the 'round' of the game.
game.print_score() # Prints the current score of the game.
# Now, we have to determine if we're playing another round.
while True:
# Get answer from user if we're doing another round.
continue_prompt = input('\nDo you wish to play again? (y/n): ').lower()
if continue_prompt == 'n':
# Quit the game.
print("You are weak!")
exit() # Just exit the program here since we're done playing.
elif continue_prompt == 'y':
# Breaks out of the prompt loop and play another round of RPS.
break
else:
print("Invalid input!\n")
# Keep going in the 'replay' prompt loop until valid input.
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment