Pygame按钮功能出现问题

问题描述 投票:1回答:1

因此,我正在为游戏创建菜单,并且已经完成了按钮功能。这些按钮可以工作,但仅在某些情况下可以:

  • [第一个按钮(2-Player)几乎每次都可以单击第一次
  • 第二个按钮(1-播放器)的工作方式可能不像每10次单击
  • 第三个按钮(得分)比上一个按钮更难上班其他

这对我来说没有意义,因为所有按钮都使用相同的功能:

def button(msg,x,y,h):
  mouse = pygame.mouse.get_pos()
  click = pygame.mouse.get_pressed()

  pygame.draw.rect(screen, RED, (x,y, BUTTON_WIDTH, h))
  smallText = pygame.font.Font("freesansbold.ttf", 20)
  textSurf, textRect = text_objects(msg, smallText, WHITE)
  textRect.center = ((x+(BUTTON_WIDTH/2)),(y+(h/2)))
  screen.blit(textSurf, textRect)

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
        sys.exit()

    if x+BUTTON_WIDTH > mouse[0] > x and y+h > mouse[1] > y:
      pygame.draw.rect(screen, BRIGHT_RED, (x,y, BUTTON_WIDTH, h))
      screen.blit(textSurf, textRect)
      if click[0] == 1:
        return True

def intro_screen():
  intro = True
  while intro:
    screen.fill(GREEN)
    if button("2-Player",245,145,BUTTON_HEIGHT):
      multiplayer_loop()
    if button("1-Player",245,270,BUTTON_HEIGHT):
      login_screen(True)
    if button("Scores",245,395,40):
      login_screen(False)
    screen.blit(TITLE, (120, 5))

    pygame.display.update()

pygame.init()
intro_screen()

Here is how the menu looks

非常感谢您的帮助,谢谢。

python function button pygame click
1个回答
0
投票

问题是按钮功能中的事件循环。注意,pygame.event.get()获取所有消息,然后从队列中删除。因此,一个按钮(通常是第一个按钮)将获得事件,而其他按钮则没有事件。

从按钮中删除pygame.event.get()。在主应用程序循环中获取事件,并将事件列表传递给按钮函数。

无论如何,您根本不需要按钮功能中的事件循环,因为您可以通过pygame.event.get()评估按钮的状态。我建议使用pygame.mouse.get_pressed()事件。参见pygame.mouse.get_pressed()

MOUSEBUTTONDOWN
pygame.event

注意,每帧pygame.event只能有1个调用。

© www.soinside.com 2019 - 2024. All rights reserved.