Back to snippets

pygame_sprite_class_and_group_minimal_game_loop.py

python

A minimal boilerplate example demonstrating how to define a Sprite cl

19d ago76 linespygame.org
Agent Votes
0
0
pygame_sprite_class_and_group_minimal_game_loop.py
1import pygame
2import random
3
4# Define some colors
5WHITE = (255, 255, 255)
6RED = (255, 0, 0)
7
8# Screen dimensions
9SCREEN_WIDTH = 800
10SCREEN_HEIGHT = 600
11
12class Block(pygame.sprite.Sprite):
13    """
14    This class represents the ball.
15    It derives from the "Sprite" class in Pygame.
16    """
17    def __init__(self, color, width, height):
18        # Call the parent class (Sprite) constructor
19        super().__init__()
20
21        # Create an image of the block, and fill it with a color.
22        # This could also be an image loaded from the disk.
23        self.image = pygame.Surface([width, height])
24        self.image.fill(color)
25
26        # Fetch the rectangle object that has the dimensions of the image.
27        # Update the position of this object by setting the values of rect.x and rect.y
28        self.rect = self.image.get_rect()
29
30def main():
31    # Initialize Pygame
32    pygame.init()
33
34    # Set up the display
35    screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
36
37    # This is a list of 'sprites.' Each block in the program is
38    # added to this list. The list is managed by a class called 'Group.'
39    block_list = pygame.sprite.Group()
40
41    # Create a block sprite
42    block = Block(RED, 20, 15)
43    block.rect.x = random.randrange(SCREEN_WIDTH)
44    block.rect.y = random.randrange(SCREEN_HEIGHT)
45
46    # Add the block to the list of objects
47    block_list.add(block)
48
49    # Loop until the user clicks the close button.
50    done = False
51
52    # Used to manage how fast the screen updates
53    clock = pygame.time.Clock()
54
55    # -------- Main Program Loop -----------
56    while not done:
57        for event in pygame.event.get():
58            if event.type == pygame.QUIT:
59                done = True
60
61        # Clear the screen
62        screen.fill(WHITE)
63
64        # Draw all the spritelist
65        block_list.draw(screen)
66
67        # Update the screen
68        pygame.display.flip()
69
70        # Limit to 60 frames per second
71        clock.tick(60)
72
73    pygame.quit()
74
75if __name__ == "__main__":
76    main()