如何降低游戏中机器人的移动速度?
def game_loop():
player_cell_x = PLAYER_CELL_X
player_cell_y = PLAYER_CELL_Y
crystals = []
score = 0
collected_crystals = {color: 0 for color in CRYSTAL_COLORS_SMALL + CRYSTAL_COLORS_BIG}
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and player_cell_x > 0:
player_cell_x -= 1
if keys[pygame.K_d] and player_cell_x < NUM_CELLS_X - 1:
player_cell_x += 1
if keys[pygame.K_w] and player_cell_y > 0:
player_cell_y -= 1
if keys[pygame.K_s] and player_cell_y < NUM_CELLS_Y - 1:
player_cell_y += 1
player = pygame.Rect(player_cell_x * CELL_SIZE, player_cell_y * CELL_SIZE, PLAYER_SIZE, PLAYER_SIZE)
当您按下某个键时,机器人会移动 4-5 个单元格。如果您极快地按下按键并释放它,则 2-3 个单元格
默认情况下,每次调用 get_pressed() 方法都会返回按键的状态。在您的代码中,由于您在 while 循环中调用该方法,因此该函数会告诉您每次循环重复时都会按下按键。由于它重复得非常快,因此你的角色会移动很多次。
要控制调用 get_pressed() 的速率,可以使用 set_repeat() 方法。不带任何参数调用此方法或将延迟设置为 0 将禁用按键重复调用,如 pygame 文档中的here所示。