1

it's my first time making a game in pygame and i'm starting with the main title screen, just now i realised that there's going to be a lot of buttons to press, and i wonder if there's a way around having to write the blit method for every image file that i want to put in screen.

this is a part of the code i want as the example i want to improve (there'll be a lot more buttons), i just want it to be less redundant and ugly looking

    screen.blit(start_button, [20, 30])
    screen.blit(settings_button, [20, 255])
    screen.blit(load_button, [20, 325])
    screen.blit(quit_button, [20, 490])
  • 1
    What is ugly? Use classes. The usual way in Pygame to do this is to use [`pygame.sprite`](https://www.pygame.org/docs/ref/sprite.html) module. – Rabbid76 Jul 28 '23 at 05:48

1 Answers1

1

There is no way around the fact that you have to use every image you want to display somewhere in the code. You can use a list of tuples and a loop:

buttons = [(start_button, [20, 30]), (settings_button, [20, 255]),
    (load_button, [20, 325]), (quit_button, [20, 490])]
for button in buttons:
    pygame.blit(*button)

However, the usual way to do this in pygame is to the pygame.sprite. See What is the difference between pygame sprite and surface?, How can I add objects to a "pygame.sprite.Group()"?, What does pygame.sprite.Group() do and many more.

Create a Button class, subclass pygame.sprite.Sprite:

class Button(pygame.sprite.Sprite):
    def __init__(self, image, pos):
        super().__init__() 
        self.image = image
        self.rect = self.image.get_rect(topleft = pos)

Create a pygame.sprite.Group and add the sprites:

button_group = pygame.sprite.Group()
button_group.add(Button(start_button, [20, 30]))
button_group.add(Button(settings_button, [20, 255]))
button_group.add(Button(load_button, [20, 325]))
button_group.add(Button(quit_button, [20, 490]))

Draw the buttons of the group in the application loop:

while run:
    # [...]

    button_group.draw(scren)

    # [...]

    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174