Pygame from scratch 1: rectangles

Introducing pygame module to make games with pygame.

The following code draws a rectangle on the screen.

  1. import the module pygame
  2. initialize pygame
  3. create screen object
  4. the clock object to control the frame rate
  5. the endless loop to control the window (whith the event handler to quit the window)
  6. in the loop we draw a rectangle every frame (60 for sec)
  7. the update of the screen
  8. the frame rate fixed at 60 frame per seconds
  9. if you quit the window goes to pygame.quit

Here you can see the result.

The comment are the lines with the # at the beginning, they are ignored in excection.

import pygame

pygame.init()


screen = pygame.display.set_mode((800, 600)) # The main Surface (where everything is shown)
clock = pygame.time.Clock() # this is for the frame rate (see below clock.tick)

loop = 1 # we use this to make the window be active until it becomes 0
while loop: # the infinite loop
    # these lines makes the user able to close the window with the red x button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = 0 # when you press the x loop is = to 0 and the loop stops and goes to pygame.quit()
    
    pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 200)) # the rectangle is drawn in every frame. 60 times per second

    pygame.display.update() # this update the screen 60 times per second
    clock.tick(60) # this fix to 60 time per seconds the frame rate, i.e. the number of screen refresh, causing animations

pygame.quit()


Subscribe to the newsletter for updates
Tkinter templates

Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Claude's Games

Arkanoid
Platform 2d

1. Memory game

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Advertisement