Search code examples
pythonpygamecrashgame-development

Pygame window crashing on run


I am trying to make a hangman game that has a window which shows the hangman being drawn every time you make a wrong guess.. i am using pygame library for it but when i run the program it opens the window and then crashes. How to fix?

Here's the code:

import pygame

def wait():
    result=None
    import msvcrt 
    result=msvcrt.getch()
    return result

window=pygame.display.set_mode((600, 600))
window.fill((0, 0, 0))

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

    print ("Press any key to start a game")
    wait()

    Wrong=0
    Word=list(input("Give the hidden word"))
    Hidden=[]
    Guess=input("Guess a letter or the word")

    for j in range(len(Word)):
        Hidden.append("_")

    if Guess in Word:
        for i in range(len(Word)):
            if Guess==Word[i]:
                Hidden.pop(i)
                Hidden.insert(i,Guess)
                print (Hidden)
    else:
        Wrong+=1

    if Wrong==1:
        White=pygame.draw.circle(window, (255, 255, 255),[300, 80], 50, 3)
        pygame.display.update()
    elif Wrong==2:
        Blue=pygame.draw.line(window, (0, 0, 255),[300, 130],[300, 350], 3)
        pygame.display.update()
    elif Wrong==3:
        Green=pygame.draw.line(window, (0, 255, 0),[300, 200],[400, 300], 3)
        pygame.display.update()
    elif Wrong==4:
        Red=pygame.draw.line(window, (255, 0, 0),[300, 200],[200, 300], 3)
        pygame.display.update()
    elif Wrong==5:
        Cyan=pygame.draw.line(window, (0, 255, 255),[300, 350],[200, 500], 3)
        pygame.display.update()
    elif Wrong==6:
        Yellow=pygame.draw.line(window, (0, 255, 255),[300, 350],[400, 500], 3)
        pygame.display.update()
    elif Wrong==7:
        print ("You Lost")

Solution

    1. Every pygame program needs pygame.init() at the beginning
    2. Use pygame.display.update() only once at the end of the program
    3. Your program freezes because input() breaks the main loop of your program

    Pygame start file:

    import pygame
    from sys import exit
    
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
    
        #Your code...
    
        pygame.display.update()
        clock.tick(FPS)
    

    You can solve this by adding an input box to the pygame window: https://stackoverflow.com/a/46390412/15500012

    I hope it will help you, Adam