【问题标题】:Is there a way to do the same code if either a mouse button or key is pressed without repeating the code?如果按下鼠标按钮或键而不重复代码,是否有办法执行相同的代码?
【发布时间】:2023-03-08 12:00:02
【问题描述】:

我想创建一个提示按钮,可以通过单击按钮或单击“h”键来工作。有没有更简单的方法来做到这一点而不必重复提示按钮的代码?

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        quit()
    if event.type==pygame.KEYDOWN:
        if event.key==pygame.K_h:
            code for hint button
    if event.type == pygame.MOUSEBUTTONUP:
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if mouse_x and mouse_y are over hint button:
            code for hint button

但我在“提示按钮的代码”部分下有相当多的代码,所以我宁愿不必重复两次。有没有办法绕过这种重复?

非常感谢您的帮助。谢谢!

【问题讨论】:

  • 编写一个包含“提示按钮代码”的函数,并在任一情况下调用该函数。 clean code

标签: python pygame event-handling


【解决方案1】:

编写一个执行您想要的操作的函数:

def code_for_hint_button():
    # [...]

在任一情况下调用该函数:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        quit()
    if event.type==pygame.KEYDOWN:
        if event.key==pygame.K_h:
            code_for_hint_button()
    if event.type == pygame.MOUSEBUTTONUP:
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if mouse_x and mouse_y are over hint button:
            code_for_hint_button()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多