蛇游戏按钮功能

时间:2017-12-31 12:53:22

标签: python python-3.x button pygame

我正在制作一个蛇游戏,我已经完成了但是我试图在其中制作一些关卡,就像简单的中等和难以达到目的我已经创建了这样的按钮

def button(msg, xposition, yposition, width, height, color, action = None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if click[0] == 1 and action!= None:
        if action == "play":
            another_screen()
        elif action == "easy":
            gameLoop_easy()
        elif action == "medium":
            gameLoop_medium()
        elif action == "hard":
            gameLoop_hard()
        elif action == "quit":
            pygame.quit()
            quit()
    pygame.draw.rect(screen, color, (xposition, yposition, width, height))
    message(msg, black, xposition + 10, yposition +10, 50)

我通过复制粘贴它创建了一个简单的游戏循环和游戏循环中等和硬功能,并编辑了用于提高蛇速的线条。但是当我玩这个游戏时,似乎就是行动=="轻松"只有当我点击中等或很难它才能轻松玩游戏环。这是更多代码

def another_screen():
    another_screen = True
    while another_screen:
        for event in pygame.event.get():
            screen.fill(white)
            border_design()
            message('Select Level', red, 20, 100, 100)
            button("Easy", 330, 290, 200, 65, green, "easy")
            button("Medium", 330, 390, 200, 65, pink, "medium")
            button("hard", 330, 490, 200, 65, blue, "hard")
            clock.tick(15)
            pygame.display.update()

我无法解决此问题。为什么按钮不起作用为什么没有执行受尊重的功能

1 个答案:

答案 0 :(得分:1)

你最大的错误是你没有检查它是否在区域"xposition, yposition, width, height"中点击了。您可以在屏幕上的任何位置单击,然后单击按钮。

您可以使用pygame.Rect()来保持按钮的位置和大小,然后您可以使用

rect.collidepoint(mouse)

检查碰撞。您也可以使用rect绘制矩形。

我还会将功能分配给action=而不是文字,然后您可以使用action()代替那些if/elif

BTW:你也不必在fill()内运行for event,按钮和其他功能。您可以在for event之后使用它们。因为您不使用event,所以您甚至不需要for event。但是您必须使用pygame.event.pump()(而不是 pygame.event.get()),因为如果没有此get_pos()/get_pressed()可能无效。

def button(msg, x, y, width, height, color, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    rect = pygame.Rect(x, y, width, height)

    if click[0] and action and rect.collidepoint(mouse):
        action()

    pygame.draw.rect(screen, color, rect)
    message(msg, black, x+10, y+10, 50)

def another_screen():
    another_screen = True
    while another_screen:
        pygame.event.pump()            

        screen.fill(white)
        border_design()
        message('Select Level', red, 20, 100, 100)

        button("Easy", 330, 290, 200, 65, green, gameLoop_easy)
        button("Medium", 330, 390, 200, 65, pink, gameLoop_medium)
        button("hard", 330, 490, 200, 65, blue, gameLoop_hard)

        clock.tick(15)
        pygame.display.update()

BTW:当鼠标悬停在按钮(rect.collidepoint(mouse))上时,您可以使用"hover"/"unhover"更改按钮颜色。

顺便说一句:使用get_pressed()你会在新屏幕上遇到问题,你会在同一个地方有其他按钮。在释放鼠标按钮之前,它将更改新屏幕上的屏幕和检查按钮 - 因此它将在新按钮中自动点击。

相关问题