Loading

Paste #pm17hmkd8

  1. import sys
  2. import pygame
  3. #the action you want to perform when the key is pressed. Here simply print the event key
  4. #in a real game situation, this action would differ according to the key value
  5. def onkeypress(event):
  6.   print(event.key) #dict of key constants for which you want a longer delay and their tracking time
  7. #in ms, initialized to 0. Here only the spacebar
  8. repeat1000 = {pygame.K_SPACE : 0}
  9. pygame.init()
  10. screen = pygame.display.set_mode((500, 500)) #sets repeat interval to 10 milliseconds for all keys
  11. pygame.key.set_repeat(10)
  12. while True:
  13.   for event in pygame.event.get():
  14.     if event.type == pygame.QUIT:
  15.       sys.exit()
  16.     if event.type == pygame.KEYDOWN:
  17.       current_time = pygame.time.get_ticks()
  18.     if event.key in repeat1000.keys():
  19.       if current_time - repeat1000[event.key] > 1000: # 如果当前运行时间与上次作用时间差距超过1秒
  20.         repeat1000[event.key] = current_time
  21.         onkeypress(event) # 产生作用
  22.     elif event.key in [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]: # 这是间隔10ms的,由于set_repeat本身就是10ms,所以就不要上面那么麻烦了
  23.       onkeypress(event)