问题描述
我是计算机科学专业的一年级学生,我有一个学期项目需要制作迷宫游戏。
我的游戏菜单代码同时显示一个大按钮和三个小按钮。
我不知道如何隐藏 3 个较小的按钮,只有当我将鼠标移到较大的按钮上时才显示它们。
这是我的代码:
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()
background_color = (50,70,90)
# Define font
FONT = pygame.font.SysFont ("Times New norman",60)
smallfont = pygame.font.SysFont('Corbel',35)
# Making buttons
text0 = FONT.render("LABYRINTHE",True,(255,255,255))
text1 = smallfont.render("niveau 1",255))
text2 = smallfont.render("niveau 2",255))
text3 = smallfont.render("niveau 3",255))
rect0 = pygame.Rect(250,100,300,100)
rect1 = pygame.Rect(300,205,80)
rect2 = pygame.Rect(300,400,80)
rect3 = pygame.Rect(300,500,80)
# The buttons are text,rectangle and color
buttons = [
[text0,rect0,(30,236,85)],[text1,rect1,[text2,rect2,[text3,rect3,85)]]
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] = background_color
else:
button[2] = (30,85)
screen.fill((20,50,70))
for text,rect,color in buttons:
pygame.draw.rect(screen,color,rect)
screen.blit(text,rect)
pygame.display.flip()
clock.tick(15)
game_intro()
pygame.quit()
解决方法
我建议给按钮添加一个标志,告诉它当前是否可见。然后你可以只绘制可见的按钮。
...
buttons = [
[text0,rect0,(30,236,85),True],# text,rect,color,visible
[text1,rect1,False],[text2,rect2,[text3,rect3,False]
]
def game_intro():
while True:
...
elif event.type == pygame.MOUSEMOTION:
for button in buttons:
if button[1].collidepoint(event.pos):
button[2] = fond_couleur
button[4] = True # set visible
else:
button[2] = (30,85)
button[4] = False # set invisible
...
for text,visible in buttons:
if visible: # draw only visible buttons
pygame.draw.rect(screen,rect)
screen.blit(text,rect)
...
改进:
不要使用列表来表示按钮。最好使用类或 namedtuple
。通过这种方式,您可以使用命名属性而不是 button[n]
,后者更具可读性。
from collections import namedtuple
Button = namedtuple('Button','text rect color visible')
btn1 = Button(text=text1,rect=rect1,color=(30,visible=False)
if btn1.visible:
pygame.draw.rect(screen,btn1.color,btn1.rect)
screen.blit(btn1.text,btn1.rect)