Skip to content

Instantly share code, notes, and snippets.

@UnrealFar
Last active June 30, 2024 11:51
Show Gist options
  • Save UnrealFar/12e93b9c9a4c7e0c87d59830943be3c1 to your computer and use it in GitHub Desktop.
Save UnrealFar/12e93b9c9a4c7e0c87d59830943be3c1 to your computer and use it in GitHub Desktop.
A simple console odd or even game in Python
from typing import Literal
import random
CONVERSIONS = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
}
DIFFICULTIES = {
"EASY": 5,
"MEDIUM": 3,
"HARD": 2,
}
name = input("Welcome to odd or even! Please enter your name: ")
# computer = 0; user = 1
print(f"\nHi {name}, lets start the game.")
class GameData:
def __init__(self):
self.batting = None
self.first = None
self.outs = [False, False]
self.runs = [0, 0]
self.uinps = {k: 0 for k in range(1, 11)}
gd = GameData()
def conv(s: str) -> int:
if s.isdigit():
return int(s)
s = s.lower()
for k, v in CONVERSIONS.items():
s = s.replace(k, v)
return int(s)
def oddoreven() -> Literal["ODD", "EVEN"]:
while True:
choice = input("Choose 'Odd' or 'Even': ").strip().upper()
if choice in ['ODD', 'EVEN']:
return choice
print("Invalid choice. Please choose 'Odd' or 'Even'.")
def get_uinp() -> int:
while True:
try:
uinp = conv(input("Enter a number between 1 and 10: "))
if 1 <= uinp <= 10:
gd.uinps[uinp] += 1
return uinp
print("Number must be between 1 and 10.")
except ValueError:
print("Invalid input. Please enter a number.")
def reset():
gd.outs = [False, False]
gd.runs = [0,0]
gd.first = None
gd.batting = None
gd.difficulty = None
def predict_uinp(batting=False) -> int:
weights = gd.uinps.values()
k = DIFFICULTIES[gd.difficulty]
if batting:
max_weight = max(weights)
return random.choice(random.choices(range(1, 11), weights=[max_weight - x for x in weights], k=k))
return random.choice(random.choices(range(1, 11), weights=weights, k=k))
def play():
while True:
if gd.batting == None:
difficulty = input("Choose difficulty level (Easy, Medium, Hard): ").upper().strip()
if difficulty not in ("EASY", "MEDIUM", "HARD"):
print("Invalid difficulty level. Please choose Easy, Medium or Hard.")
continue
gd.difficulty = difficulty
print("Toss time!\n")
uch = oddoreven()
odev = 0 if uch == "EVEN" else 1
uinp = get_uinp()
cinp = predict_uinp()
if (uinp + cinp) % 2 == odev:
print("You won the toss!")
bob = input("Do you want to bat or bowl? ").upper()
else:
print("Computer won the toss!")
bob = random.choice(("BAT","BOWL"))
if bob == "BOWL":
gd.first = 0
gd.batting = 0
print("Computer is now batting\n")
elif bob == "BAT":
gd.first = 1
gd.batting = 1
print("Your are now batting\n")
else:
print("Invalid choice!")
elif gd.batting == 1:
uinp = get_uinp()
cinp = predict_uinp()
print("Computer:", cinp)
if uinp == cinp:
print("\nYou are out!\n")
print(f"SCORE: {name}: {gd.runs[1]} \t Computer: {gd.runs[0]}\n")
gd.outs[1] = True
gd.batting = 0
else:
gd.runs[1] += uinp
if gd.first == 0 and gd.runs[1] > gd.runs[0]:
gd.outs[1] = True
elif gd.batting == 0:
uinp = get_uinp()
cinp = predict_uinp(batting=True)
print("Computer:", cinp)
if uinp == cinp:
print("\nComputer is out!\n")
print(f"SCORE: {name}: {gd.runs[1]} \t Computer: {gd.runs[0]}\n")
if gd.first == 0:
print(f"{gd.runs[0]+1} runs to win\n")
gd.outs[0] = True
gd.batting = 1
else:
gd.runs[0] += cinp
if gd.first == 1 and gd.runs[0] > gd.runs[1]:
gd.outs[0] = True
if False not in gd.outs:
if gd.runs[0] > gd.runs[1]:
print(f"SCORE: {name}: {gd.runs[1]} \t Computer: {gd.runs[0]}\n")
print(f"\nComputer has won by {gd.runs[0]-gd.runs[1]} runs!")
elif gd.runs[1] > gd.runs[0]:
print(f"SCORE: {name}: {gd.runs[1]} \t Computer: {gd.runs[0]}\n")
print(f"\nYou have won by {gd.runs[1]-gd.runs[0]} runs!")
else:
print("\nIts a draw!")
cont = input("\nStart new game? (Y/N): ").upper()
if cont in ("Y", "YES"):
reset()
elif cont in ("N", "NO"):
break
else:
"Invalid choice! Continuing.."
else:
if gd.batting == 1 and gd.outs[0] and gd.runs[1] > gd.runs[0]:
gd.outs[1] = True
elif gd.batting == 0 and gd.outs[1] and gd.runs[1] < gd.runs[0]:
gd.outs[0] = True
print("\nThanks for playing odd or even! Come back soon :)")
if __name__ == "__main__":
play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment