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
420 views
in Technique[技术] by (71.8m points)

python - Pygame Window not Responding after few seconds

The below code makes the window not respond when started.. I wanted to make hangman game and I got the logic done and I was just trying to make the window pop up and its not responding. Also when I run the program, when I type in the letter and type another one then it erases the previous letter a writes the new letter with the underscores. How can I make it so that it keeps the previous letter and prints it with the new letter?

import pygame
pygame.init()

running  = True

window_width = 600
window_height = 600
window = pygame.display.set_mode((window_width, window_height))

clock = pygame.time.Clock()

word = "something"
while running:
    dt = clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        


    answer = ""
    guessed = []

    guessed.append(input("write your letter here -> "))

    for i in word:
        
        if i in guessed:
            answer += i + " "
        else:
            answer += "_ "

    print(answer)
    answer = ""
pygame.quit()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your issue is here:

while running:
    dt = clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        


    answer = ""
    guessed = [] # <-----ISSUE

Everytime the while loop starts over, you're assigning the guessed list to an empty list. What you need to do is place the guessed = [] before the while like this:

import pygame
pygame.init()

running  = True

window_width = 600
window_height = 600
window = pygame.display.set_mode((window_width, window_height))

clock = pygame.time.Clock()

word = "something"
guessed = []
while running:
    pygame.display.update() # <---- Needs to be called every loop passing to update the window
    dt = clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
    answer = ""

    guessed.append(input("write your letter here -> "))

    for i in word:
        
        if i in guessed:
            answer += i + " "
        else:
            answer += "_ "

    print(answer)
    answer = ""
pygame.quit()

You also need to update your window every time the while loop goes by. I added it in the code I provided above.


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

...