Search code examples
pythonpython-2.7pygamedelaykey-events

Pygame.key.get_pressed - how to add interval?


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:

enter image description here

and my question is: How do I set delay or Interval after each keypress event to prevent this problem?

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

Solution

  • 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.

    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.