Python. PyGame. Time and animation code the movement of graphic objects; analyse the result of the program execution; control the characters with module Time.

Python. PyGame.

Time and animation


The main idea of animation in programming is moving an object to a new place during the next iteration.

Consider the movement of the circle on the screen from right to left. 
Before the game loop starts, we need to set the initial coordinates of the circle. For example:

x = 20
y = 100
To display an object in a new place, it is necessary to fill the screen with the background color every time before drawing.

screen.fill((0, 0, 0)) # fill the screen with blackIn the loop to draw the circle, we must use the variables (x, y) as the variable coordinates and at least one coordinate must change its value. For example:, (255, 0, 0), (x, y), 20, 0)
x += 1 # movement to the right

The animation is performed, but not at all as we would like. Time setting required.


The easiest way is to set a method delay() from module time before the screen refreshes.

pygame.time.delay(n) # n - number of milliseconds

!!! The best way to use the Clock class of the time module to improve image quality.

clock = pygame.time.Clock() # create a new clock object
fps = 50                    # frames per second (max 60)
v = 20                      # speed: pixels per second
x += v / fps           # new x-position 
clock.tick(fps)             # delay by 1/fps seconds

Example:import pygame
size = width, height = 500, 200
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
fps = 50
v = 40
x = 20
y = 100
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill((0, 0, 0)), (255, 0, 0), (x, y), 20, 0)
    x += v / fps

To limit the movement, it is enough to add the condition. For example:

if x < 480:
    x += v/fps # movement to the right
# or
if x >= 20:
    x -= v/fps # movement to the left


1. Explain how to organize animation in programming.

2. Why do we use class Clock()?

3. How to implement movement to the right? left? upward? downward?



Ex. 1 Determine the direction of coordinate change using compass directions.



Task 1. Create infinity movement

Категория: Algorithms | Добавил: bzfar77 (13.11.2022)
Просмотров: 602 | Теги: Python, Time, PyGame, animation, FPS | Рейтинг: 5.0/2
Всего комментариев: 0