gakonst icon

GuessTheNumber

gakonst | PRO | 12/10/17 03:07:47 PM UTC | 0 ⭐ | 259 👁️ | Never ⏰ | []
Python |

2.4 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python3
import random
import sys
 
### Strings
PICK_NUMBER     = '[-->] Pick a number between 1 and 100\n> '
NUMBER_BIGGER   = '[+] The hidden number is bigger'
NUMBER_SMALLER  = '[-] The hidden number is smaller'
WON_AFTER_TRIES = '[!] You found it after {} tries and won {} points'
PLAY_AGAIN_PROMPT  = '[!] Do you want to play again? [y/n]\n> '
INVALID_CHOICE  = '[-] Invalid choice. Try again'
ERROR           = '[-] Nope! Current tries: {}'
EXIT            = 'Exiting...'
MENU = '''
Welcome to 'Guess the Number'. The goal of the game is to find the random number the computer generates.
Press:
    1. Play
    2. Exit'''
 
def computer_number():
    return random.randint(1,100)
 
def number_input():
    choice = 0
    while not (1 <= choice <= 100):
        try: 
            choice = int(input(PICK_NUMBER))
            if (1 <= choice <= 100):
                break
        except ValueError:    
            print (INVALID_CHOICE)
            continue
        print(INVALID_CHOICE)
    return choice
 
def play_again():
    choice = input(PLAY_AGAIN_PROMPT)
    while choice.lower() not in ['y', 'n']:
        print(INVALID_CHOICE)
        choice = input(PLAY_AGAIN_PROMPT)
    if choice.lower() == 'n':
        print(EXIT)
        sys.exit()
 
def play_exit():
    choice = (input('> '))
    while choice not in ['1','2']:
        print(INVALID_CHOICE)
        choice = (input('> '))
    if int(choice) == 2:
        print (EXIT)
        sys.exit()
 
def main():
    # Loop infinitely, close only on ctrl+c or if user exits with predetermined commands
    while True:
        tries = 0
        print(MENU)
        # User input must be 1 to play, 2 to exit. All others are rejected
        
        play_exit()
 
        target = computer_number()
        # print ('Target is', target) # for debugging purposes
 
        choice = number_input()
 
        while (choice is not target):
            if choice > target:
                print (NUMBER_SMALLER)
            elif choice < target:
                print (NUMBER_BIGGER)
            tries += 1 # increment failed tries
            print (ERROR.format(tries))
            choice = number_input()
            
        print (WON_AFTER_TRIES.format( tries+1, 10 - (tries+1) ) )
 
        # print play again prompt, validate input
        play_again()
 
if __name__ == '__main__':
    sys.exit(main())

Comments