Python / Pygame:尝试使用变量(可能包含字符串)来表示PyGame条件

时间:2018-06-26 20:55:38

标签: python keyboard pygame customization keyword

这是我的第一个帖子,对于任何礼节上的失误,我们深表歉意。

我目前正在Python中使用pygame,以允许用户自定义哪些键可以做什么。下面的代码是我目前的状况,但不能解决我遇到的问题。

 if keys[pygame.K_UP]:

我真正想要的是这样的东西:

if keys["pygame.customisable_key"]:

据我所知,由于我设计导入该类的类的方式,因此必须包含pygame前言。

谢谢

1 个答案:

答案 0 :(得分:0)

pygame.K_常数实际上只是数字(整数),您可以将其作为值放入keys字典中。

我要定义一个字典,将动作(字符串)作为dict键,将pygame键常量作为值,例如:keys = {'move_left': pg.K_a, 'move_right': pg.K_d}

然后,您可以签入事件循环if event.key == keys['move_left']:并根据需要处理该事件。

要更改键,首先需要弄清楚应将新键分配给哪个操作,并在按下下一个键盘键时,插入event.key属性作为新值:keys[selected_action] = event.key

这只是一个简单的示例,仍然可以改进,但是据我所知,它是完整的并且可以正常工作(按 Esc 切换分配场景,按前面的键之一选择一个动作,然后选择另一个键为该动作分配新的键):

import sys
import pygame as pg


def key_assignment_scene(keys, screen, clock):
    selected_action = None

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    return keys  # Return the keys to the main scene.
                elif selected_action:
                    # Assign a new key to the action.
                    keys[selected_action] = event.key
                    print(keys, 'new key:', event.unicode)
                    selected_action = None
                else:  # Select an action (a key from the `keys` dict).
                    for action, pygame_key in keys.items():
                        if event.key == pygame_key:
                            selected_action = action
                            print('Selected action:', selected_action)

        screen.fill((20, 40, 60))
        pg.display.flip()
        clock.tick(30)


def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    BG_COLOR = pg.Color('gray12')
    BLUE = pg.Color('dodgerblue1')
    rect = pg.Rect(300, 220, 20, 20)
    speed_x = 0
    keys = {'move_left': pg.K_a, 'move_right': pg.K_d}

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    print(keys)
                    # Switch to the key assigment scene.
                    keys = key_assignment_scene(keys, screen, clock)
                elif event.key == keys['move_left']:
                    speed_x = -3
                elif event.key == keys['move_right']:
                    speed_x = 3
            elif event.type == pg.KEYUP:
                if event.key == keys['move_left'] and speed_x < 0:
                    speed_x = 0
                elif event.key == keys['move_right'] and speed_x > 0:
                    speed_x = 0

        rect.x += speed_x

        screen.fill(BG_COLOR)
        pg.draw.rect(screen, BLUE, rect)
        pg.display.flip()
        clock.tick(30)

main()
pg.quit()