shuaXII
shuaXII

Reputation: 1

How can I make my program restart depending on the user's response to a prompt?

My code is basically a command-line version of the game wordle. After the game ends I need it to ask the player if they want to keep playing. If they say yes the program should restart.

I have tried indenting all of my code and using def and while functions, but these options don't output anything. I don't know what else to try.

import random
from colorama import Fore, Back, Style
    
print("Guess My Word - Based on TextBasedWordle by DrVictor https://replit.com/@DrVictor/TextBasedWordle")
print("")
    
def processGuess(theAnswer, theGuess):
    position = 0
    clue = ""
    for letter in theGuess:
        if letter == theAnswer[position]:
            clue += u"\u2714 "
        elif letter in theAnswer:
            clue += Fore.YELLOW + u"\uFF0D " + Style.RESET_ALL
        else:
            clue += Fore.RED + u"\u274C " + Style.RESET_ALL
        position += 1
    print(clue)
    print("")
    return clue == u"\u2714 "u"\u2714 "u"\u2714 "u"\u2714 "u"\u2714 " # true if correct, false otherwise
    
# load words and store them into a list
word_list = []
word_file = open("target_words.txt")
for word in word_file:
    word_list.append(word.strip())
    
# pick a word
answer = random.choice(word_list)

num_of_guesses = 0
guessed_correctly = False
 
while num_of_guesses < 6 and not guessed_correctly:
  
    # get guess from user
    guess = input("Input a 5-letter word and press enter: ")
    print("You have guessed", guess)
    num_of_guesses += 1
    print(6 - num_of_guesses, "guesses remaining")
    
    # process guess
    guessed_correctly = processGuess(answer, guess)
    
# display end of game message
if guessed_correctly:
    print("Congratulations, you guessed the word correctly with", num_of_guesses, "guesses.")
else:
    print("You have used up all your guesses. The correct word was", answer)

Upvotes: -2

Views: 159

Answers (2)

user15257134
user15257134

Reputation:

I added a while loop with the main code, inside a try-except statement handling the KeyboardInterrupt exception, so the user can exit the program by hitting CTRL+C. I also added the possibility to have words with different lengths on the list, to be more fun :P. You can do some optimizations in the code but it's working well.

import random
from colorama import Fore, Back, Style
    
print("Guess My Word - Based on TextBasedWordle by DrVictor https://replit.com/@DrVictor/TextBasedWordle")
print("")
    
def processGuess(theAnswer, theGuess):
    position = 0
    clue = ""
    clue_max = ""

    for letter in theAnswer:
        clue_max += u"\u2714 "

    for letter in theGuess:
        if letter == theAnswer[position]:
            clue += u"\u2714 "
        elif letter in theAnswer:
            clue += Fore.YELLOW + u"\uFF0D " + Style.RESET_ALL
        else:
            clue += Fore.RED + u"\u274C " + Style.RESET_ALL
        position += 1
    print(clue)
    print("")
    return clue == clue_max # true if correct, false otherwise
    
# load words and store them into a list
word_list = []
word_file = open("target_words.txt")
for word in word_file:
    word_list.append(word.strip())


try:
    while True:
        # pick a word
        answer = random.choice(word_list)

        num_of_guesses = 0
        guessed_correctly = False
 
        
        while num_of_guesses < 6 and not guessed_correctly:
            # get guess from user
            guess = input("Input a {}-letter word and press enter: ".format(len(answer)))


            if len(guess) > len(answer):
                print("You have guessed {} but it has more letters than the answer, please try again.".format(guess))
                
            else:
                print("You have guessed {}.".format(guess))

                num_of_guesses += 1
                print(6 - num_of_guesses, "guesses remaining")
    
                # process guess
                guessed_correctly = processGuess(answer, guess)

        
        # display end of game message
        if guessed_correctly:
            print("Congratulations, you guessed the word correctly with", num_of_guesses, "guesses.")
        else:
            print("You have used up all your guesses. The correct word was", answer)


        play = input("You want to play again[y/n]? ")

        if play.lower() != "y":
            break

except KeyboardInterrupt:
    pass

Upvotes: 0

MichaelCG8
MichaelCG8

Reputation: 579

Put all of your game code into a function, for example def game():

Run the game by calling this in a while loop and after the game finishes ask if the player wants to continue. If they don't you can break from the while loop. If you don't break, the loop will run again.

Define a function called play_again() that asks the player if they want to play again and returns True if they do and False otherwise.

while True:
    game()
    if not play_again():
        break

Upvotes: 0

Related Questions