pygame.key.get_pressed-如何添加间隔? [英] Pygame.key.get_pressed - how to add interval?

查看:557
本文介绍了pygame.key.get_pressed-如何添加间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个简单的网格和一个简单的精灵,用作玩家".但是当我使用箭头键移动时,角色移动得太快,如下图所示:

I have made a simple grid and a simple sprite which works as "player". but when i use arrow keys to move, the character moves too fast as shown in the picture below:

我的问题是:如何在每次按键事件之后设置延迟或间隔以防止出现此问题?

player.py

#!/usr/bin/python
import os, sys, pygame, random
from os import path
from pt import WIDTH,HEIGHT
from pygame.locals import *

img_dir = path.join(path.dirname(__file__), 'img')

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.width = 64
        self.height = 64
        self.image = pygame.image.load(path.join(img_dir, "player.png")).convert_alpha()
        self.image = pygame.transform.scale(self.image,(self.width, self.height))
        self.rect = self.image.get_rect()
        self.speed = 64
    #    self.rect.x =
    #    self.rect.y =

    def update(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and self.rect.x > 0:
            self.rect.x -= self.speed
        elif keys[pygame.K_RIGHT] and self.rect.x < (WIDTH-self.width):
            self.rect.x += self.speed
        elif keys[pygame.K_UP] and self.rect.y > 0:
            self.rect.y -= self.speed
        elif keys[pygame.K_DOWN] and self.rect.y < (HEIGHT-self.height):
            self.rect.y += self.speed

推荐答案

最简单的方法是记录您处理第一个事件的时间,然后再次抑制该事件的处理,直到新的时间至少间隔一定时间为止比第一审更大.

The simplest thing to do is record the time that you processed the first event, and then suppress handling of the event again until the new time is at least some interval greater than the first instance.

一些代码可以使这一点更清楚:

Some code may make this clearer:

# In your setup set the initial time and interval
lastTime = 0
interval = 500    # 500 ms
# [...]
while True:       # Main event loop
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and (getCurrentMillis() > lastTime + interval):
        lastTime = getCurrentMillis()    # Save the new most-recent time
        print "Handled a keypress!"

以此,程序将跟踪密钥的使用,并且仅在经过一定时间后才重新考虑密钥.

With this, the program tracks the use of the key and only considers it again once some amount of time has passed.

上面的代码不能一字不差地工作:您需要考虑可用的不同时间来源,并选择最适合您的时间来源.

The above code wont work verbatim: you need to consider the different time sources available to you and pick the one that suits you best.

您还应该考虑如何跟踪许多不同的上次使用时间:密钥的字典(为避免大量预先添加密钥而在这里使用defaultdict可能很有用),并且它们的上次单击时间可能值得使用

You should also consider how it is you will track many different last used times: a dictionary (a defaultdict might be useful here to avoid lots of up-front adding of keys) of keys and their last clicked time might be worth using.

这篇关于pygame.key.get_pressed-如何添加间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆