Skip to content Skip to sidebar Skip to footer

Python/pygame Adding A Title Screen With A Button

I have this code import pygame, random, sys from pygame.locals import * BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0 , 0, 255) WIDTH

Solution 1:

The implementation of a button is answered several times. For example Pygame mouse clicking detection, How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover or How can I add an image or icon to a button rectangle in Pygame? and myn more.


Create 2 scenes with 2 application loops. The first loop shows the title screen and waits for button 2 to be pressed. The 2nd loop is the game loop:

button_rect = pygame.Rect(x, y, width, height) # start button rectangle

abort = False
start = False
whilenot abort andnot start:
    foreventin pygame.event.get():
        ifevent.type == pygame.QUIT:
            abort = True   

        ifevent.type == MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):
                start = True
 
    # draw title screen# [...]

done = abort
whilenot done:
 
    whilenot done:
    foreventin pygame.event.get():
        ifevent.type == pygame.QUIT:
            done = True

    # game# [...]

Alternatively, you can combine both scenes in one loop.Add a variable game_state, implement event handling and draw the scenes depending on the value of game_state. Change the game_state when the start button is pressed:

game_state = 'title'

done = Falsewhilenot done:
    
    # event handlingfor event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = Trueif game_state == 'title':
            if event.type == MOUSEBUTTONDOWN:
                if button_rect.collidepoint(event.pos):
                    game_state = 'game'elif game_state == 'game':
            # handle game events:# [...]# drawingif game_state == 'title':
        # draw title screen# [...]elif game_state == 'game':
        # game# [...]

Post a Comment for "Python/pygame Adding A Title Screen With A Button"