Skip to content

Instantly share code, notes, and snippets.

@dmoney
Last active March 26, 2024 02:36
Show Gist options
  • Save dmoney/370387c0de18fd07726a1c2ae8fd29f7 to your computer and use it in GitHub Desktop.
Save dmoney/370387c0de18fd07726a1c2ae8fd29f7 to your computer and use it in GitHub Desktop.
PyGuess, a fun lil guessing game
## A fun lil guessing game.
import sys, random, time, os
try:
import rich, pyfiglet
except:
pass
MAX_GUESSES = 5
MAX_NUMBER = 20
if len(sys.argv) >= 2:
MAX_GUESSES = int(sys.argv[1])
def clear():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
def fancy_print(s):
try:
title = pyfiglet.figlet_format(s, font='nancyj-fancy')
rich.print(f'{title}')
except:
print(s.upper())
# delayed print, times are in seconds
def dprint(what, delay=1, after=0, inputting=False, end="\n"):
ret = None
try:
if delay:
time.sleep(delay)
if inputting:
ret = input(what)
else:
print(what, end=end)
if after:
time.sleep(after)
except KeyboardInterrupt:
dprint("\n\nOkay, thanks for playing!\n", delay=0, after=1.5)
clear()
sys.exit(0)
return ret
def get_guess(prompt):
INVALID_MSG = f"Invalid value! Enter an integer from 1 to {MAX_NUMBER}."
while True:
try:
guess = int(dprint(prompt, delay=1, inputting=True))
if guess not in range(1, MAX_NUMBER + 1):
print(INVALID_MSG)
else:
return guess
except ValueError:
print(INVALID_MSG)
def intro():
clear()
print('\n\n\n\n\n')
fancy_print(' PyGuess')
time.sleep(1.5)
clear()
dprint("\n\n\nThe game:")
dprint(f"\nGuess a number between 1 and {MAX_NUMBER}.", delay=1.5, after=1);
dprint(f"\nYou get {MAX_GUESSES} tries.", after=1)
def play():
intro()
result = ""
while result.strip().lower() != "q":
clear()
actual = random.choice(range(1, MAX_NUMBER + 1))
for i in range(MAX_GUESSES):
if i > 0:
if i < MAX_GUESSES - 1:
dprint(f"\nYou have {MAX_GUESSES - i} tries left.")
else:
dprint(f"\nLast try!")
guess = get_guess(f"\n\nENTER GUESS => ")
dprint("\nYour guess is ", delay=0, end="")
if guess == actual:
dprint(f"CORRECT!")
dprint(f"\nYou got it in {i + 1} tries!", after=2)
break
elif i < MAX_GUESSES - 1:
dprint(f"{'GREATER' if guess > actual else 'LESS'} than the number.")
if actual != guess:
dprint("INCORRECT!")
dprint(f"\nThe number was {actual}.")
dprint(f"\nYOU LOSE.", after=2)
result = dprint("\nPress ENTER to play again. Type Q to quit.\n\n", inputting=True)
play()
clear()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment