gpt4 book ai didi

python - Pygame 按钮功能问题

转载 作者:行者123 更新时间:2023-12-01 06:29:34 26 4
gpt4 key购买 nike

所以我正在为游戏创建一个菜单,并且我已经制作了一个按钮功能。这些按钮确实有效,但只是有时:

  • 第一个按钮(2 人游戏)几乎每次都能第一次点击
  • 第二个按钮(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

任何帮助将不胜感激,谢谢。

最佳答案

问题是按钮函数中的事件循环。注意,pygame.event.get()获取所有消息并从队列中删除它们。
因此,1 个按钮(主要是第一个按钮)将获取事件,其他按钮不会获​​取事件。

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

无论如何,您根本不需要按钮函数中的事件循环,因为您可以通过 pygame.mouse.get_pressed() 评估按钮的状态。 .
但是,我建议使用 MOUSEBUTTONDOWN 事件。请参阅pygame.event .

def button(events,msg,x,y,h):
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, textRect = text_objects(msg, smallText, WHITE)
textRect.center = button_rect.center

mouse = pygame.mouse.get_pos()
button_rect = pygame.Rect(x, y, BUTTON_WIDTH, h)
hit = button_rect.collidepoint(mouse)

pygame.draw.rect(screen, BRIGHT_RED if hit else RED, button_rect)
screen.blit(textSurf, textRect)

if hit:
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
return True
def intro_screen():
intro = True
while intro:

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

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

pygame.display.update()

请注意,每帧只能调用 1 次 pygame.event.get()

关于python - Pygame 按钮功能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com