微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在PyGame中将事件限制为每帧迭代一个事件

如何解决如何在PyGame中将事件限制为每帧迭代一个事件

我是初学者。请放心吧。

所以我试图在过去的几周里学习编程,我尝试自己为Pygame制作一款游戏。我试图制作一个Snake游戏,但我认为它快完成了。我有一个不断出现的错误

因此,如果我太快地单击2个按钮,它们将在一帧内被察觉(重复)。这导致玩家要么死于现场(因为他向后撞向自己),要么就一直往前走。 在后一种情况下,这会导致错误,导致玩家只是在穿越边界或在到达边界之前死亡而死

这是控件的代码

#Control
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            #arrows
            if event.key == pygame.K_UP and player_moveY <= 0:
                player_moveY = -playerWith
                player_moveX = 0
            if event.key == pygame.K_DOWN and player_moveY >= 0:
                player_moveY = playerWith
                player_moveX = 0
            if event.key == pygame.K_LEFT and player_moveX <= 0:
                player_moveX = -playerWith
                player_moveY = 0
            if event.key == pygame.K_RIGHT and player_moveX >= 0:
                player_moveX = playerWith
                player_moveY = 0

这是边框的代码

# boundries
    if playerY < 0 or playerY > screen_width:
        runningGame = False
        
    if playerX < 0 or playerX > screen_width:
        runningGame = False
        

这是整个代码(270处的Gameloop): Codeshare.io

有什么办法可以消除此错误

解决方法

使用pygame.event.poll从队列中获取单个事件:

从队列中返回一个事件。如果事件队列为空,则将立即返回pygame.NOEVENT类型的事件。返回的事件将从队列中删除。

例如:

event = pygame.event.poll()
if event.type == pygame.QUIT:
    pygame.quit()
    quit()

# [...]

另一种可能的解决方案是通过pygame.key.get_pressed来获得键的状态,而不是键盘事件(在应用程序循环而不是事件循环中)。
确保仅按下方向键之一并更改方向:

keys = pygame.key.get_pressed()
sum_keys = keys[pygame.K_UP] + keys[pygame.K_DOWN] + keys[pygame.K_LEFT] + keys[pygame.K_RIGHT]

if sum_keys == 1:
    if  keys[pygame.K_UP] and player_moveY <= 0:
        player_moveY = -playerWith
        player_moveX = 0
    if keys[pygame.K_DOWN] and player_moveY >= 0:
        player_moveY = playerWith
        player_moveX = 0
    if keys[pygame.K_LEFT] and player_moveX <= 0:
        player_moveX = -playerWith
        player_moveY = 0
    if keys[pygame.K_RIGHT] and player_moveX >= 0:
        player_moveX = playerWith
        player_moveY = 0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。