im making a Guess the number game but i have a problem:The user must guess a certain number, and if it exceeds that, the game ends and the user's status is determined,So I created a variable named sam and did this
sam = 0
And then I made a loop with while and said:
while sam < 10:
And then, every wrong guess will be added to sam, but the problem is that if you do something wrong, this will happen:
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>12 is lower
>>you lose
That is, it repeats a condition until sam exceeds 10 And I don't know what to do, my code:
from tkinter import *
sam = 0
def get_1():
global correct
correct = int(player1.get())
player1.pack_forget()
sumbit.pack_forget()
def Guess():
global sam
a = int(player_2.get())
while sam < 10:
if a == correct:
break
elif a > correct:
print(a,"is higher")
sam = 1
elif a < correct:
print(a,"is lower")
sam = 1
if a == correct:
print("you win")
else:
print("you lose")
app = Tk()
player1 = Entry(app,font=20)
app.minsize(300,300)
player1.pack()
player_2 = Entry(app,font=20)
player_2.pack()
sumbit = Button(app,font=10,text="player 1 sumbit",command=get_1)
sumbit.pack()
guss = Button(app,text="player 2 guess number",font=20,command=Guess)
guss.pack()
app.mainloop()
CodePudding user response:
Writing GUI programs requires a different mindset than writing non-GUI programs. A loop like the one you created is not appropriate for a GUI. The way GUIs work is that you define functions to be called in response to events, and then the event manager (mainloop
) is a loop tht waits for events and then dispatches them to the handlers.
So, in your case Guess
should only handle a single guess and not try to loop over a range of guesses. It can keep a global counter for the number of guesses, and update it each time Guess
is called.
It might look something like this:
def Guess():
global guesses
global sam
a = int(player_2.get())
player_2.delete(0, "end")
guesses = 1
if a == correct:
print("you win")
elif guesses == 10:
print("you lose")
elif a > correct:
print(a,"is higher")
elif a < correct:
print(a,"is lower")
You need to initialize guesses
to zero when player 1 submits the value, since that designates the start of the game.
def get_1():
global correct
global guesses
correct = int(player1.get())
guesses = 0
player1.pack_forget()
sumbit.pack_forget()