【问题标题】:button clicking on rectangle (pygame main menu)按钮单击矩形(pygame主菜单)
【发布时间】:2019-01-08 11:59:21
【问题描述】:

我目前是 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)

【问题讨论】:

  • buttons 是如何定义的?或者这就是你要问的?
  • 基本上我想做的是print ('start') 当鼠标点击我已经绘制的开始按钮时。开始按钮定义为rect1

标签: python button menu pygame main


【解决方案1】:

由于您已将矩形定义为单独的变量,您可以通过在事件循环中调用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')

如果列表中只有矩形(按钮)并且没有单独的按钮变量,则必须为每个按钮分配一个回调函数,使用for 循环遍历按钮,检查是否一个碰撞,然后调用回调函数(见this answer的附录1和2)。

【讨论】:

    【解决方案2】:

    你应该为按钮创建一个单独的函数:

    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: 按钮高度
    • 活动:鼠标悬停在按钮上时的按钮图片
    • inactive:按钮空闲时的图片

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多