【问题标题】:Can you call functions using the arrow keys? [closed]您可以使用箭头键调用函数吗? [关闭]
【发布时间】:2022-01-03 05:22:15
【问题描述】:

我正在尝试制作一个高尔夫游戏,当用户按下左箭头或右箭头时,实际的箭头将指向您建议的位置。然后按下空格键将球释放并滚开,希望被捕获在高尔夫球洞中。不过,这并不是让我感到困扰,而是第一部分;箭的瞄准。 我已经制作了 10 个指向不同方向的不同功能,但问题在于用户交互。我需要使箭头(功能)按箭头键。我将这些函数命名为:

one_one
one_two
one_three

等等。我如何调用它们并删除最后一个,但更重要的是,使该过程重复进行? 提前致谢! P.S 我正在使用 Python-3 和 VS 代码。

【问题讨论】:

    标签: python python-3.x function arrow-functions


    【解决方案1】:

    你不需要循环; keyboard 模块使用事件触发激活而不是轮询。

    import keyboard
    
    def on_left_arrow(e):
        print('Hello World')
    
    keyboard.on_press_key("left", on_left_arrow)
    

    对于您问题的第二部分,您可以将方向放在“队列”中;

    directions = ['N', 'E', 'W', 'S']
    
    def on_left_arrow(e):
        # pop the first item out of the list 
        current = direction.pop(0)
    
        # move it to the end
        directions = directions.append(current)
    
        print(current) 
    
    def on_right_arrow(e):
        # pop the last item
        current = direction.pop()
    
        # move it to the beginning
        directions = directions.insert(0, current)
    
        print(current)
    

    请注意keyboard 库需要sudo

    【讨论】:

    • 是的,但我需要反复进行。如果我继续按我的情况下的左箭头,我会一次又一次地得到相同的箭头。我将如何将其更改为下一个?如果用户按下右箭头怎么办?然后我也需要让它倒退。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多