简体   繁体   中英

Getting an error whenever I try to rerun the gameloop

while gameStart == True:
    startScreen()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            youLose = True
            gameStart = False 
        
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            moveY = -snek.fast
            moveX = 0
            gameStart = False
        if event.key == pygame.K_ESCAPE:
            youLose = True
            gameStart = False

I have no trouble when I run the game the first time around. I'm trying to get the game to reset after I've lost but I keep getting the error:

if event.type == pygame.KEYDOWN:
UnboundLocalError: local variable 'event' referenced before assignment

I don't understand why this is giving me an error, and even less why it gives an error only on the second time around. I've tried indenting the block so as to include it inside the for loop, but it makes my game crash.

The keydown if-else statement should be inside the for-loop

while gameStart == True:
    startScreen()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            youLose = True
            gameStart = False 
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                moveY = -snek.fast
                moveX = 0
                gameStart = False
            if event.key == pygame.K_ESCAPE:
                youLose = True
                gameStart = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM