Reputation: 11
I'm a first year computer science major and I have a semester project I need to make a maze game.
My code for the menu of the game shows one big button and 3 smaller ones at the same time.
I don't know how to hide the 3 smaller buttons ans show them only when I pass the mouse on the bigger button.
Here is my code:
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", True, (255, 255, 255))
text2 = smallfont.render("niveau 2", True, (255, 255, 255))
text3 = smallfont.render("niveau 3", True, (255, 255, 255))
rect0 = pygame.Rect(250,100,300,100)
rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
rect3 = pygame.Rect(300,500,205,80)
# The buttons are text, rectangle and color
buttons = [
[text0, rect0, (30,236,85)],
[text1, rect1, (30,236,85)],
[text2, rect2, (30,236,85)],
[text3, rect3, (30,236,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,236,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()
Upvotes: 1
Views: 41
Reputation: 1320
I would suggest to add a flag to the button which tells if it is currently visible. Then you can draw only the buttons which are visible.
...
buttons = [
[text0, rect0, (30,236,85), True], # text, rect, color, visible
[text1, rect1, (30,236,85), False],
[text2, rect2, (30,236,85), False],
[text3, rect3, (30,236,85), 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,236,85)
button[4] = False # set invisible
...
for text, rect, color, visible in buttons:
if visible: # draw only visible buttons
pygame.draw.rect(screen, color, rect)
screen.blit(text, rect)
...
Improvement:
Do not use lists to represent buttons. Better use a class or namedtuple
. By this you can use named attributes instead of button[n]
which is way more readable.
from collections import namedtuple
Button = namedtuple('Button', 'text rect color visible')
btn1 = Button(text=text1, rect=rect1, color=(30,236,85), visible=False)
if btn1.visible:
pygame.draw.rect(screen, btn1.color, btn1.rect)
screen.blit(btn1.text, btn1.rect)
Upvotes: 2