Search code examples
pythonfunctionuser-input

Trying to link my user name input and menu to my game function in python hangman


I'm trying to link my ask_for_name() and menu() functions to my play() function but where ever I place the function headings it doesn't seem to work or get called. The game starts up first and at the end of gameplay asks if you want to restart, yes or no, If you click no, it goes back to what I want at the beginning of my game, my user-input asking for name and the menu, press 1 to play the game and 2 for instructions. When I click 1 the game wont start and throws an error message, does anyone know what I'm missing here? I'm new to python and seem to keep going in circles with this problem, the code is mentioned below:

def ask_for_name():
while True:
    name = input(YELLOW_COLOR + "Please Enter Your Name:\n")
    
    if not name.isalpha():
        print("Name must be letters only\n")
    else:
        print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
        menu()
return name   


def menu():
"""
menu function which gives the user two options
- Press 1 to play or 2 for instructions
- only accepts valid keys or error message comes up
"""
while True:
    user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
    if user_input == "P":
        play()
    elif user_input == "I":
        print(
            "1.The computer will generate a random word and it's\n"
            "your task to guess the letters from the word.\n"
            "2.To guess, type a letter of your choice and hit enter.\n"
            "3.If you guess correctly, the letter will be revealed.\n"
            "4.If you guess incorrectly, you will lose a life and \n"
            " the Hangman will start to appear.\n"
            "5.You have 8 lives to guess the correct word.\n"

            "Good Luck!\n")
        enter_input = input("Press Enter to go back to the menu\n").upper()
        if enter_input == "":
            menu()
        else:
            print(RED_COLOR + "Oops look's like you pressed the wrong key!\n")
            
    else:
        print("Invalid Character, please try again!\n")



        
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False

def check_letter(letter, word):
global reveal
for i in range(0,len(word)):
    letter = word[i]
    if guess == letter:
        reveal[i] = guess
if '_' not in reveal:
    return True
else:
    return False


def restart_game():
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False

while not game_restart:
    restart = input("Would you like to play again?"
                    "Y/N").upper()
    try:
        if restart == "Y":
            game_restart = True

            play()

        elif restart == "N":
            game_restart = True
            print("\n")
            header()
            ask_for_name()
            menu()

        else:
            raise ValueError(
            "You must type in Y or N"
            )

    except ValueError as e:
        print("\n You must type in Y or N Please try again.\n")


def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")


while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()

if guess == word:
    game_is_won = True
    reveal = word
elif len(guess) == 1 and guess in word:
    game_is_won = check_letter(guess, word)
else:
    lives -= 1

if game_is_won:
    player_won()
    print("WELL DONE")
    
else:
    player_lost()
    print(f"YOU FAILED the word was: {word}")
    

restart_game()

Solution

  • Since there were portions of the game program missing, I filled in the missing bits with some placeholder functions. After trying out the game and seeing where it appeared to get stuck, I made some tweaks to it to make it function in the spirit of a hangman game. Following is the tweaked code for your analysis.

    import os
    
    word = "dog" #random.choice(WORDS)
    word = word.upper()
    reveal = list(len(word)*'_')
    lives = 8
    game_is_won = False
    hangman = []            # Added this so as to make the game work - temporary
    
    for g in range(0,8):
        hangman.append('-')
    
    def header():
        return
    
    def ask_for_name():
        while True:
            name = input("Please Enter Your Name:\n")
        
            if not name.isalpha():
                print("Name must be letters only\n")
            else:
                print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
                menu()
                break       # Added this to get out of the while loop
        return name   
    
    def menu():
        
        while True:
            user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
            if user_input == "P":
                lives = 8
                game_is_won = False
                break
            elif user_input == "I":
                print("1.The computer will generate a random word and it's\n"
                    "your task to guess the letters from the word.\n"
                    "2.To guess, type a letter of your choice and hit enter.\n"
                    "3.If you guess correctly, the letter will be revealed.\n"
                    "4.If you guess incorrectly, you will lose a life and \n"
                    " the Hangman will start to appear.\n"
                    "5.You have 8 lives to guess the correct word.\n"
      
                    "Good Luck!\n")
                enter_input = input("Press Enter to go back to the menu\n").upper()
                if enter_input == "":
                    pass
                    #menu()
                else:
                    print("Oops look's like you pressed the wrong key!\n")
                
            else:
                print("Invalid Character, please try again!\n")
    
    def check_letter(guess, word):
        global reveal
        for i in range(0,len(word)):
            letter = str(word[i])
            if guess == letter:
                reveal[i] = guess
        if '_' not in reveal:
            return True
        else:
            return False
    
    def restart_game():         # Added return of decision
        """
        Gives player option to restart, otherwise returns to menu
        """
        game_restart = False
    
        while not game_restart:
            restart = input("Would you like to play again?" "Y/N/Q ").upper()   # Added a quit option
            try:
                if restart == "Y":
                    return True
    
                elif restart == "N":
                    game_restart = True
                    print("\n")
                    header()
                    ask_for_name()
                    #menu()
                    return True
                    
                elif restart == "Q":
                    return False
    
                else:
                    raise ValueError("You must type in Y or N")
    
            except ValueError as e:
                print("\n You must type in Y or N Please try again.\n")
                
    def player_won():       # Added this to make the game work
        print("Yea!")
        return
        
    def player_lost():      # Added this to make the game work
        print("Boohoo")
        return
    
    def play():
        os.system("clear")
        header()
        print(hangman[8-lives])
        print(' '.join([str(e) for e in reveal]))
        print(f"You have {lives} lives")
        
    header()
    ask_for_name()
    
    while game_is_won == False and lives > 0:
        play()
        guess = input('Guess a letter or an entire word:')
        guess = guess.upper()
    
        if guess == word:
            game_is_won = True
            reveal = word
        elif len(guess) == 1 and guess in word:
            game_is_won = check_letter(guess, word)
        else:
            lives -= 1
    
        if game_is_won:
            player_won()
            print("WELL DONE")
        
        else:
            if lives <= 0:
                player_lost()
                print(f"YOU FAILED the word was: {word}")
            
        if game_is_won == True or lives <=0:        # Conditioned restart
            if restart_game() == True:
                game_is_won = False
                lives = 8
                reveal = list(len(word)*'_')
        
    

    The key bits were adjusting some of the "if" tests to allow for life decrements, prompting for a name, prompting the menu, and restarts.

    Here is a quick sample at the terminal.

    -
    _ _ _
    You have 8 lives
    Guess a letter or an entire word:Dog
    Yea!
    WELL DONE
    Would you like to play again?Y/N/Q Q
    

    Give those a try.