This is my take on the guess the number game. The user has three attempts to guess the number chosen at random. The number is between 0 and 9, including. It tells the user to guess higher or lower and reveals the number if the game is lost.
Input that is not a number between 0 and 9, including, is not accepted and the cursor will remain on the same line.
Green is for win and red is for retry.
I have tested the code and it works correctly. Please have a go.
guess_the_number.py
"""The user has three attempts to guess what number was chosen at random"""
__all__ = []
import random
import string
from colorama import deinit, init
right_answer = random.choice(string.digits)
as_int = int(right_answer)
MSG_ANS = 'The answer was ' + right_answer
MSG_ASK = 'Guess the number (0-9) '
MSG_OK = '\033[92mCorrect!\033[0m'
MSG_TRY = '\033[91mTry again *\033[0m'
def ask(msg_wrong):
"""
One attempt
Non-digits are not accepted
Digits accepted are removed from the pool
and are not accepted in subsequent attempts
"""
global pool
cursor_up = '\033[A'
cursor_up_ask = cursor_up + ' '
while True:
answer = input(MSG_ASK)
if answer and answer in pool:
break
answer_sz = len(answer)
answer_sz = answer_sz * ' '
line = cursor_up_ask + answer_sz + cursor_up
print(line)
print()
print()
print(line, end='\r')
if answer == right_answer:
print(MSG_OK)
exit()
if msg_wrong == MSG_TRY:
i = int(answer)
if i > as_int:
hint = '>'
else:
hint = '<'
msg_wrong = msg_wrong.replace('*', hint)
print(msg_wrong)
pool = pool.replace(answer, '')
if __name__ == '__main__':
pool = string.digits
init()
ask(MSG_TRY)
ask(MSG_TRY)
ask(MSG_ANS)
deinit()