Python 不遵循缩进规则

问题描述 投票:0回答:1

我有一个 while 函数,只要“game_over”设置为 False,它就会运行游戏。代码本身可以工作,但似乎它认为第一段之后的所有代码都不是 while 循环的一部分,即使它缩进正确。

while game_over == False:    # Checks that the game is not over
    
     while game_close == True:
        dis.fill(white)
        message("You Lost! Press Q-Quit or C-Play Again", red)
        pygame.display.update()
 
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    game_over = True
                    game_close = False
                if event.key == pygame.K_c:
                    gameLoop()
        
    for event in pygame.event.get():
        print(event)    # Prints out all the actions that take place on the screen
    
        if event.type == pygame.QUIT:   # Closes game by setting "game_over" to True
            game_over = True
        
        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1Change = -10
                    y1Change = 0
                elif event.key == pygame.K_RIGHT:
                    x1Change = 10
                    y1Change = 0
                elif event.key == pygame.K_UP:
                    y1Change = -10
                    x1Change = 0
                elif event.key == pygame.K_DOWN:
                    y1Change = 10
                    x1Change = 0



    if x1 >= dis_width or x1 <= 0 or y1 >= dis_height or y1 <= 0:
        game_close = True
                
    x1 += x1Change
    y1 += y1Change
    dis.fill(white)
    pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])
    pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
    pygame.display.update()
    
    if x1 == foodx and y1 == foody:
        print("Yummy!!")
    clock.tick(snake_speed)

    dis.fill(black)     # Sets colour for background

    pygame.draw.rect(dis, white, [x1, y1, 15, 15])      # Draws the snake

          
    pygame.display.update()

    clock.tick(30)

我尝试检查缩进是否正确,以及删除 while 循环中的所有代码并将其粘贴回去,删除 while 语句并再次将其写回。

python while-loop indentation
1个回答
-1
投票

这里好像有一个空间 对于 pygame.event.get() 中的事件: 这会使缩进无效,并且可能有一个函数调用它,因为此代码看起来像一个片段,或者构建不依赖于源代码的更改。我建议您重新启动服务器并尝试再次运行更改后。

© www.soinside.com 2019 - 2024. All rights reserved.