How to make a simple animation with Pygame

A little script to show how to create a simple animation in python. Here is the result.

Circle changing size

https://pythonprogramming.altervista.org/wp-content/uploads/2021/03/pygame-window-2021-03-30-08-09-54.mp4

Step 1: the window

To make a window in pygame I use this function

import pygame as pg
import random

def listen():
        """ quit the window when user presses the red x button of the window """
	[pg.quit() for event in pg.event.get() if event.type == pg.QUIT]

def mainloop():
        """ This function runs until users quit the window """
	global grow
	grow = 1
	while True:
		listen() # this calls the function to quit the window
		screen.fill(0)
		# circle() # This will call the animation
		clock.tick(60)
		pg.display.update()


pg.init()
radius = 100
screen = pg.display.set_mode((200, 300))
clock = pg.time.Clock()
mainloop()

The animation of the circle

This function, called by the main function, draws a circle that changes size continuosly.

def circle():
    global grow, radius
    radius = radius + 1 if grow else radius - 1
    if radius > 100:
        grow = 0
    if radius < 10:
        grow = 1
    pg.draw.circle(screen,
        (0, 255, 0),
        (100, 150),
        radius)

The whole code to animate in pygame

This will make the code work putting everything together.

import pygame as pg
import random

def circle():
    global grow, radius
    radius = radius + 1 if grow else radius - 1
    if radius > 100:
        grow = 0
    if radius < 10:
        grow = 1
    pg.draw.circle(screen,
        (0, 255, 0),
        (100, 150),
        radius)


def listen():
    """ quit the window when user presses the red x button of the window """
    [pg.quit() for event in pg.event.get() if event.type == pg.QUIT]

def mainloop():
    """ This function runs until users quit the window """
    global grow
    grow = 1
    while True:
        listen() # this calls the function to quit the window
        screen.fill(0)
        circle() # This will call the animation
        clock.tick(60)
        pg.display.update()


pg.init()
radius = 100
screen = pg.display.set_mode((200, 300))
clock = pg.time.Clock()
mainloop()

Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts