在矩形上单击按钮(pygame主菜单)

时间:2018-08-01 01:59:18

标签: python button menu pygame main

我目前是pygame的新手,想知道如何编写矩形的位置以打印“开始”

到目前为止,我的循环是

def game_intro():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.MOUSEMOTION:
                for button in buttons:
                    if button[1].collidepoint(event.pos):
                        button[2] = HOVER_COLOR
                    else:
                        button[2] = BLACK

                        screen.blit(bg, (0, 0))
        for text, rect, color in buttons:
            pygame.draw.rect(screen, color, rect)
            screen.blit(text, rect)
            if event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = pygame.mouse.get_pos()

我的矩形位置和大小是

rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
rect3 = pygame.Rect(300,500,205,80)

2 个答案:

答案 0 :(得分:0)

由于已将rects定义为单独的变量,因此可以通过在事件循环中调用pygame.Rect.collidepoint方法来检查特定对象是否与鼠标位置发生冲突:

def game_intro():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 1 = left button, 2 = middle, 3 = right.
                    # `event.pos` is the mouse position.
                    if rect1.collidepoint(event.pos):
                        print('Start')

如果列表中仅包含rect(按钮),而按钮没有单独的变量,则必须为每个按钮分配一个回调函数,请使用for循环遍历按钮,检查是否发生冲突,然后调用回调函数(请参见this answer的附录1和2)。

答案 1 :(得分:0)

您应该为按钮创建一个单独的功能:

def button(x, y, w, h, inactive, active, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        gameDisplay.blit(active, (x, y))      #Images are a bit easier to use
        if click[0] == 1 and action is not None:
              print("start")
    else:
        gameDisplay.blit(inactive, (x, y))

完成此操作后,您可以这样称呼它:

#For Example
button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop)

这是每个参数的含义:

  • x:按钮的x坐标
  • y:按钮的y坐标
  • w:按钮的宽度
  • h:按钮的高度
  • 活动:鼠标悬停在按钮上时按钮的图片
  • 无效:按钮处于空闲状态时的图片