Introducing pygame module to make games with pygame.
The following code draws a rectangle on the screen.
- import the module pygame
- initialize pygame
- create screen object
- the clock object to control the frame rate
- the endless loop to control the window (whith the event handler to quit the window)
- in the loop we draw a rectangle every frame (60 for sec)
- the update of the screen
- the frame rate fixed at 60 frame per seconds
- 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 templatesTwitter: @pythonprogrammi - python_pygame
Claude's Games
1. Memory gameVideos
Speech recognition gamePygame's Platform Game