【问题标题】:PYGAME: Continous K_DOWN doesn't really workPYGAME:连续的 K_DOWN 并没有真正起作用
【发布时间】:2023-03-17 11:55:01
【问题描述】:

此代码应该使黑色矩形在 K_LEFT 或 K_RIGHT 被按下时连续移动,但发生的情况是它只是在按下时移动,然后一旦发生,当鼠标移动时窗口,它移动(当它不应该移动时,它应该只在按下一个键时移动)。 代码如下,希望对你有所帮助:

import pygame

pygame.init()

red = (255,0,0)
white = (255,255,255)
black = (0,0,0)

gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Slither')

gameExit = False

lead_x = 300
lead_y = 300
lead_x_change = 0

clock = pygame.time.Clock()

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
                gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x_change = -10
            if event.key == pygame.K_RIGHT:
                lead_x_change = 10

        lead_x += lead_x_change

        gameDisplay.fill(white)
        pygame.draw.rect(gameDisplay, black, [lead_x, lead_y,10,10])
        pygame.display.update()

        clock.tick(30)


pygame.quit()
quit()

【问题讨论】:

    标签: python-3.x pygame


    【解决方案1】:

    原因是因为您在事件循环中缩进了所有代码,这意味着您仅在事件循环中有事件(例如移动鼠标、按下按钮)时才更新 rect 的屏幕和位置等)。

    确保缩进正确,如下所示:

    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                    gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    lead_x_change = -10
                if event.key == pygame.K_RIGHT:
                    lead_x_change = 10
    
        # All code below was indented to much.
        lead_x += lead_x_change
    
        gameDisplay.fill(white)
        pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, 10, 10])
        pygame.display.update()
    
        clock.tick(30)
    

    此外,在命名变量时保持一致通常是一种很好的做法。最好将gameDisplaygameExit命名为game_displaygame_exit以获得更多连续性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-13
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多