Pygame 的 key.set_repeat() 无法工作
我正在尝试写一个简单的地图编辑器,但在使用pygame.set_repeat()时遇到了问题。我把它放在了循环之前设置,也试过在循环里面设置,但似乎都没有效果。
我查了其他的讨论,但没有找到能帮上忙的内容。有没有人能给点建议?
import pygame
import math
import sys
import os
import os.path
from pygame.locals import *
from classes.tile_sprites import sprites
from classes.tile_sprites import buttons
class MainCode:
def main(self):
size = width, height = 800, 600
display = pygame.display.set_mode(size)
fps_clock = pygame.time.Clock()
button_location = "../resources/images/buttons"
icon_location = "../resources/images/icons"
surface_type = {"track":os.path.join(icon_location, "track.png"),
"dirt":os.path.join(icon_location, "dirt.png"),
"grass":os.path.join(icon_location, "grass")}
incline_type = {"steep_incline":os.path.join(icon_location, "steep_incline.png"),
"moderate_incline":os.path.join(icon_location,"moderate_incline.png"),
"flat":os.path.join(icon_location, "flat.png"),
"moderate_decline":os.path.join(icon_location, "moderate_decline.png"),
"steep_decline":os.path.join(icon_location, "steep_decline.png")}
surface_selections = ["track", "dirt", "grass"]
incline_selections = ["steep_incline", "moderate_incline", "flat", "moderate_decline", "steed_decline"]
tile_group = pygame.sprite.Group()
button_group = pygame.sprite.Group()
selected_group = pygame.sprite.GroupSingle()
sbl = buttons((25, 25), (0, 255, 0), "left")
sbl.rect.x, sbl.rect.y = 0, 0
sbr = buttons((25, 25), (0, 255, 0), "right")
sbr.rect.x, sbl.rect.y = 100, 0
ibl = buttons((25, 25), (0, 255, 0), "left")
ibl.rect.x, ibl.rect.y = 0, 100
ibr = buttons((25, 25), (0, 255, 0), "right")
ibr.rect.x, ibr.rect.y = 100, 100
to_add = [sbl, sbr, ibl, ibr]
button_group = self.pygame_group_add_many(to_add, button_group)
pygame.key.set_repeat(1, 1000000000)
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
mouse = pygame.mouse.get_pos()
key = pygame.key.get_pressed()
if key[K_DOWN]:
print "down"
display.fill((0, 0, 0))
tile_group.draw(display)
button_group.draw(display)
pygame.display.flip()
fps_clock.tick(30)
def pygame_group_add_many(self, items_to_add, group):
for each in items_to_add:
group.add(each)
return group
if __name__ == "__main__":
MainCode().main()
1 个回答
3
get_pressed()
和 if key[K_DOWN]:
的意思是你一直按着 K_DOWN
键,没有松开它。get_pressed()
和 set_repeat()
没有关系。
set_repeat()
是用来处理事件的。
这段代码在你按住 K_DOWN
键的时候,只会打印一次 "event down"。
if event.type == KEYDOWN:
if event.key == K_DOWN:
print "event down"
如果你加上 set_repeat(1,1000)
,那么在你按住 K_DOWN
键的时候,每隔 1000 毫秒就会打印一次 "event down"。
完整示例:
import pygame
from pygame.locals import *
pygame.init()
display = pygame.display.set_mode( (800,600) )
pygame.key.set_repeat(1,1000) # add/remove this line
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.key == K_DOWN:
print "EVENT DOWN"
pygame.quit()