您可以创建一个字典,将操作名称作为字典键,将pygame键(
pygame.K_LEFT
等)作为值。例如:
input_map = {'move right': pygame.K_d, 'move left': pygame.K_a}
这允许你将其他pygame按键分配给这些操作(在分配菜单的事件循环中):
if event.type == pygame.KEYDOWN:
input_map[selected_action] = event.key
接下来,在主while
循环中,您可以使用动作名称来检查相应的键盘按键是否已按下:
pressed_keys = pygame.key.get_pressed()
if pressed_keys[input_map['move right']]:
在下面的例子中,你可以通过点击 ESCAPE
键来访问 assignment_menu
。这是一个独立的函数,有自己的 while 循环,在其中我创建了一个动作和 pygame 键的表格,您可以通过鼠标选择。如果选择了一个动作并且用户按下一个键,我会更新 input_map
字典,并在用户再次按下 Esc 时将其返回给主游戏函数。
import sys
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
FONT = pg.font.Font(None, 40)
BG_COLOR = pg.Color('gray12')
GREEN = pg.Color('lightseagreen')
def create_key_list(input_map):
"""A list of surfaces of the action names + assigned keys, rects and the actions."""
key_list = []
for y, (action, value) in enumerate(input_map.items()):
surf = FONT.render('{}: {}'.format(action, pg.key.name(value)), True, GREEN)
rect = surf.get_rect(topleft=(40, y*40+20))
key_list.append([surf, rect, action])
return key_list
def assignment_menu(input_map):
"""Allow the user to change the key assignments in this menu.
The user can click on an action-key pair to select it and has to press
a keyboard key to assign it to the action in the `input_map` dict.
"""
selected_action = None
key_list = create_key_list(input_map)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
elif event.type == pg.KEYDOWN:
if selected_action is not None:
input_map[selected_action] = event.key
selected_action = None
key_list = create_key_list(input_map)
if event.key == pg.K_ESCAPE:
return input_map
elif event.type == pg.MOUSEBUTTONDOWN:
selected_action = None
for surf, rect, action in key_list:
if rect.collidepoint(event.pos):
selected_action = action
screen.fill(BG_COLOR)
for surf, rect, action in key_list:
screen.blit(surf, rect)
if selected_action == action:
pg.draw.rect(screen, GREEN, rect, 2)
pg.display.flip()
clock.tick(30)
def main():
player = pg.Rect(300, 220, 40, 40)
input_map = {'move right': pg.K_d, 'move left': pg.K_a}
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
input_map = assignment_menu(input_map)
pressed_keys = pg.key.get_pressed()
if pressed_keys[input_map['move right']]:
player.x += 3
elif pressed_keys[input_map['move left']]:
player.x -= 3
screen.fill(BG_COLOR)
pg.draw.rect(screen, GREEN, player)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pg.quit()
key_selected = True
并使用它来停止再次选择键。 - furaskey.pressed()
总是返回一个包含所有按键的True/False
值的列表。使用event.key
来获取被按下的按键。 - furasMoveUp = event.key
BTW: you forgot:
afterpygame.KEYDOWN
- furas