Skip to content

Instantly share code, notes, and snippets.

@tmitzka
Created February 24, 2018 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmitzka/210cc205910d93e857d853009d8c4fce to your computer and use it in GitHub Desktop.
Save tmitzka/210cc205910d93e857d853009d8c4fce to your computer and use it in GitHub Desktop.
A game of Rock, Paper, Scissors against the computer.
#!/usr/bin/env python3
"""A game of Rock, Paper, Scissors against the computer."""
import random
import time
FORMS = ("Rock", "Paper", "Scissors")
class RockPaperScissors():
"""A classic game of Rock, Paper, Scissors."""
def __init__(self):
self.hands = {"You": "", "CPU": ""}
self.score = {"You": 0, "CPU": 0}
self.play_again = True
def __repr__(self):
return "Rock, Paper, Scissors: Player {} - CPU {}".format(
self.score["You"], self.score["CPU"]
)
@staticmethod
def choice_player():
"""Let the player choose a form, and return it."""
print("\nChoose your form:")
print("1 - {}".format(FORMS[0]))
print("2 - {}".format(FORMS[1]))
print("3 - {}\n".format(FORMS[2]))
number = ""
while (number not in "123") or (len(number) != 1):
number = input("Your choice (1/2/3): ")
return FORMS[int(number) - 1]
@staticmethod
def choice_cpu():
"""Choose a form for the computer, and return it."""
return random.choice(FORMS)
def decide(self):
"""Decide who wins."""
player = self.hands.values()[0]
player = self.hands.values()[1]
if ((player == FORMS[0] and cpu == FORMS[2]) or
(player == FORMS[1] and cpu == FORMS[0]) or
(player == FORMS[2] and cpu == FORMS[1])):
winner = rr
elif ((cpu == FORMS[0] and player == FORMS[2]) or
(cpu == FORMS[1] and player == FORMS[0]) or
(cpu == FORMS[2] and player == FORMS[1])):
winner = "CPU"
else:
winner = None
return winner
def play(self):
"""Start game loop, call game methods."""
print("Welcome to Rock, Paper, Scissors.")
time.sleep(2)
while self.play_again:
self.hands["You"] = self.choice_player()
self.hands["CPU"] = self.choice_cpu()
winner = self.decide()
time.sleep(2)
print("\nYou chose:", self.hands["You"])
print("CPU chose:", self.hands["CPU"])
if winner:
print("{} won!".format(winner))
self.score[winner] += 1
else:
print("It's a tie!")
time.sleep(2)
print("\nYou: {}".format(self.score["You"]))
print("CPU: {}".format(self.score["CPU"]))
answer = ""
while (answer not in ("y", "n")) or (len(answer) != 1):
answer = input("Play again? (y/n) ").lower()
if answer == "y":
self.play_again = True
else:
self.play_again = False
print("\nThanks for playing!")
def main():
"""Create game object and start its play() method."""
rps_game = RockPaperScissors()
rps_game.play()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment