Mopps
Mopps

Reputation: 13

How do I make it so every time I play_again in my hangman game, a new word is generated?

Basically the title. I want my hangman game to generate a new random word from an imported file list every time I play again. However, when I do it it simply utilizes the same word as before. Here is the code.

import random

with open("English_Words", "r") as file:
    allText = file.read()
words = list(map(str, allText.split()))
word = random.choice(words)}

def play_again():
    print("Do you want to play again (Yes or No)")
    response = input(">").upper()
    if response.startswith("Y"):
        return True
    else:
        return False

def singleplayer():
    guessed = False
    word_completion = "_" * len(word)
    tries = 6
    guessed_letters = []
    while not guessed and tries > 0:
        print(word_completion)
        print(hangman_error(tries))
        print(guessed_letters)
        guess = input("Guess a letter:").lower()
        if guess in guessed_letters:
            print("You have already guessed that letter.")
        elif guess not in word:
            print("[INCORRECT] That letter is not in the word!")
            guessed_letters.append(guess)
            tries -= 1
            if tries == 0:
                print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
        elif guess in word:
            print("[CORRECT] That letter is in the word!")
            guessed_letters.append(guess)
            word_as_list = list(word_completion)
            indices = [i for i, letter in enumerate(word) if letter == guess]
            for index in indices:
                word_as_list[index] = guess
            word_completion = "".join(word_as_list)
            if "_" not in word_completion:
                guessed = True
            if tries == 0:
                print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
            if "_" not in word_completion:
                guessed = True
        if guessed:
            print("You win, the man was saved! The word was:" + str(word))

while True:
    singleplayer()
    if play_again():
        continue
    else:
        break

Upvotes: 0

Views: 42

Answers (1)

Zane Wilson
Zane Wilson

Reputation: 367

You need to call word = random.choice(words) inside of your singleplayer() function. Preferrably at the top, either right above or right below the guess = False line.

This way, you're program is going to call that random choice line everytime you call the singleplayer function.

def singleplayer():
    word = random.choice(words)
    guessed = False

Upvotes: 1

Related Questions