如何设置两个键盘事件之间的间隔?

2024-09-27 04:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让玩家在迷宫中一次移动一个街区。你知道吗

我试着用一个时钟和time.time(),但都没用。你知道吗

这是我的游戏循环:

while self.running:
    self.counter += 1
    self.clock.tick(self.fps)

    if self.counter == self.fps:
        self.counter = 0
        self.canUpdate = True

这是移动代码:

if self.game.canUpdate:
    if pressed_keys[K_DOWN]:
        self.moveDown()
        self.game.canUpdate = False

def moveDown(self):
    if self.canMoveTo(self.gridx, self.gridy+1):
        for sprite in self.game.sprites:
            if sprite != self:
                sprite.y -= self.game.gridSize
                self.gridy += 1
                print(self.gridy, self.game.canUpdate)

按一次向下箭头gridy增加到500以上,self.game.canUpdate保持为真


Tags: selfgame游戏iftimecounter时钟running
2条回答

您可以使用time.sleep()

import time    
time.sleep(500)

用按键事件调用此块,以便下一次按键时,代码执行停止500秒,然后等待下一次按键事件。而且Counter()需要算上500,如果你打算做更大的事情,这需要比sleep()更多的CPU。你知道吗

如果要在每次按键时移动一次,应该使用event loop^{}。当按下向下键时,带有key属性pygame.K_DOWN的单个pygame.KEYDOWN事件将被添加到事件队列中。只需检查这个键是否在事件循环中按下,然后移动精灵。你知道吗

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

pos = pg.Vector2(120, 80)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_DOWN:
                # This will be executed once per event.
                pos.y += 20
            elif event.key == pg.K_UP:
                pos.y -= 20

    screen.fill(BG_COLOR)
    pg.draw.rect(screen, (0, 128, 255), (pos, (20, 20)))
    pg.display.flip()
    clock.tick(60)

pg.quit()

相关问题 更多 >

    热门问题