2017-04-19 13 views
0

나는 간단한 그리드와 "플레이어"로 작동하는 간단한 스프라이트를 만들었습니다.Pygame.key.get_pressed - 간격을 추가하는 방법은 무엇입니까?

enter image description here

내 질문은 : 내가 이동하는 화살표 키를 사용하면 아래의 그림과 같이하지만, 캐릭터가 너무 빨리 이동 내가 이것을 방지하기 위해 키를 누를 때마다 이벤트 후 지연 또는 간격을 설정하는 방법 문제?

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 

답변

1

새로운 시간이 적어도 일부 구간 때까지 다시 이벤트의 처리를 첫 번째 이벤트 처리 시간을 기록하고 억제되는 가장 간단한 것은 첫 번째 인스턴스보다 큼. 이와

# 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!" 

, 프로그램이 키의 사용을 추적하고 일정 시간이 경과 한 번만 다시 생각 :

일부 코드는이 명확하게 할 수있다.

위의 코드는 그대로 사용할 수 없습니다. 다른 시간 원본을 고려하고 가장 적합한 것을 선택해야합니다.

또한 많은 다른 마지막 사용 시간을 추적하는 방법을 고려해야합니다. 사전 (키의 많은 선행 추가를 피하기 위해 여기에 유용 할 수있는 기본) 사전과 마지막으로 클릭 한 시간이 가치가있을 수 있습니다 사용.