Skip to content

Instantly share code, notes, and snippets.

@ChekeGT
Created September 10, 2023 21:37
Show Gist options
  • Save ChekeGT/b8d7ad26ade4edc04c89ddf1d0e0c786 to your computer and use it in GitHub Desktop.
Save ChekeGT/b8d7ad26ade4edc04c89ddf1d0e0c786 to your computer and use it in GitHub Desktop.
A simple console rock paper and scissors game
"""The rock paper scissors game consists of the following
2 Players
Rock > Scissors
Paper > Rock
Scissors > Paper
I will build a game that replicates this behavior
"""
from os import system
from time import sleep
import random
def clear_and_pause():
sleep(1.5)
system('cls')
class WrongSelection(Exception):
"Raised when the user has selected a wrong choice"
pass
class Player(object):
def __init__(self, name, choice):
self.name = name
self.choice = choice
if self.choice not in ['r', 's', 'p']:
raise WrongSelection
def fight(self, player_2):
"""This option returns the winner"""
if self.choice == player_2.choice:
return 'Neither. It is a tie.'
if (self.choice == 'r' and player_2.choice == 's') or (self.choice == 'p' and player_2.choice == 'r') or (self.choice == 's' and player_2.choice == 'p'):
return self
else:
return player_2
def __str__(self):
return self.name
def create_player(machine=False):
if machine == True:
return Player('Machine', random.choice(['r','s','p']))
# If it is not a machine the function will follow
clear_and_pause()
name = input('Insert your name:')
option = input('''Insert your choice:
r) Rock
p) Paper
s) Scissors\n''').lower()
try:
return Player(name, option)
except WrongSelection:
clear_and_pause()
print(f'The option you selected is not valid, please try creating your character again.')
return create_player()
def menu():
print('This is a rock, paper, scissors game. Enjoy!!')
clear_and_pause()
while True:
clear_and_pause()
option = input("""Select your option from the following
1) Two player Mode
2) Player vs Machine Mode
3) Exit
""")
if option == '1':
# Player creation
player_1 = create_player()
player_2 = create_player()
# Players fight and the winner is returned.
winner = player_1.fight(player_2)
print(f'The winner of this match is: {winner}')
clear_and_pause()
elif option == '2':
player = create_player()
machine = create_player(machine=True)
winner = player.fight(machine)
print(f'The winner is: {winner}')
clear_and_pause()
elif option == '3':
print('Thanks for playing the game ;)')
break
else:
print('You have not selected a correct option, please do so.')
menu()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment