Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

python 3.x - Second loop, game not working and Sublime Text problems

I am working on a very simple 'game' where the player gets 5 guesses to guess a random number.

It's not done yet but I have run into a couple of problems.

This is the code that generates a random number and allows the player to guess

Relevant code:

def GuessLoopFunc(guess):
    import random
    import sys
    import time

    sum_guesses = 0

    rand_num = random.randrange(1, 21)
    print(rand_num) 
#This is just for test purposes to know the correct number and see what happens when I guess the correct number
    while True:

        if guess == rand_num:
            print("You got it right!")
            
        else:
            sum_guesses += 1
            if sum_guesses == 4:
                guess = input("That's incorrect...final guess: ")
                continue

            elif sum_guesses == 5:
                print("Oh no! You lost!")
                while True:
                    replay = input("Do you want to play again: ")
                    if replay == "yes" or replay == "Yes":
                        pass #Temporary while I figure out how to loop back to very start (new random number)
                    elif replay == "no" or replay == "No":
                        print("Goodbye")
                        break
                    else:
                        print("I do not understand what you mean...")
                        continue

                else:
                    guess = input("You got it wrong, guess again: ")
                    continue 

As you can see by the comments I made, I want the game the return to the very start of the program if the player indicates they want to play again (so they get a new random number.

Also, for some reason, the game doesn't register when the correct answer was given and keeps on telling the player that his answer was incorrect...this is the code of the game where the above module is called:

import sys
import random
import time
from GuessLoop import GuessLoopFunc

print("Hello! Welcome to the guess the number game!")
name_player = input("Please enter your name: ")
print("Hello " + str(name_player) + "!")
play = input("Are you ready to play? ")
if play == "Yes" or play == "yes":
    print("Great! Let's get started...")
elif play == "No" or play == "no":
    print("Too bad...")
    sys.exit()
else:
    print("I do not understand your response...")
    quit1 = input("Do you want to quit? ")
    if quit1 == "yes" or quit1 == "Yes":
        sys.exit()
    elif quit1 == "no" or quit1 == "No":
        print("Great! Let's get started!")
        
    else:
        print("I do not understand your response...quitting.")
        sys.exit()

print("I am going to think of think of a number between 1 and 20...")
print("You will get 5 guesses to guess the number...")

time.sleep(1)

print("Okay, I have a number in mind")
guess = input("What is your guess? ")

GuessLoopFunc(guess)

time.sleep(1)
sys.exit()

Finally, when I try to run the program in Sublime Text it doesn't run further than the "Please enter your name: " part. If I fill in my name and press enter, nothing happens...but no error message displays either. So I have resorted to testing the program in the Python IDLE every time, but it's a bit tedious...anyone know what's up.

question from:https://stackoverflow.com/questions/65857624/second-loop-game-not-working-and-sublime-text-problems

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your main problem is that you compare your userinput (a string) with a random number (integer) - they will never be the same as string != int.

Solution:

You need to convert the user input to a number via the int(text) function.

def getInt(text):
    while True:
        try: 
            n = input(text)
            return int(n)
        except ValueError:  # if the input is not a number try again
            print(f"{n} is not a number! Input a number")

....
guess = getInt("What is your guess?")  # now that is an int
....

You have lots of duplicate "yes/no" codeparts that you can streamline:

def YesNo(text):
    '''Ask 'test', returns True if 'yes' was answerd else False'''    
    while True:
        answer = input(text).strip().lower()
        if answer not in {"yes","no"}:
            print("Please answer 'yes' or 'no'")
            continue # loop until yes or no was answered
        return answer == "yes"

This reduces

quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
    sys.exit()
elif quit1 == "no" or quit1 == "No":
    print("Great! Let's get started!")

to

if YesNo("Do you want to quit? "):
    sys.exit()
else:
    pass # do somthing 

and use that in all yes/no questions.


To play again I would move the "Do you want to play again" question out of the game loop:

# do your name questioning and greeting here
# and then enter an endless loop that you break from if not playing again

while True:

    GuessLoopFunc()  # move the guess input inside the GuessLoopFunk as it has
                     # to be done 5 times anyhow. If you spend 5 guesses or
                     # guessed correctly, print some message and return to here
    if YesNo("Play again? "):
        continue
    else:
        break # or sys.exit()

To fix the sublime problem: Issue with Sublime Text 3's build system - can't get input from running program


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...