微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。