如果按下鼠标按钮或键而不重复代码,有没有办法执行相同的代码?

问题描述

我想创建一个提示按钮,它可以通过单击按钮或单击“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

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

我真的很感激帮助。谢谢!

解决方法

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

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()