Menu
CoddyTech

Move Every Frame

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 7 of 32.

The game loop runs 60 times a second, so a line in the "Change things here" part runs once per frame. Use it to change a variable a little each time:

comet_x = comet_x + 2

Read it from the right: take the value in comet_x, add 2, and store the result back in comet_x. If it held 40, it now holds 42. On the next frame it becomes 44, then 46.

The comet is drawn at comet_x on every frame, so each frame shows it 2 pixels further right: 120 pixels a second. That is how everything moves in a game: a number that changes a little on every frame.

comet_x = 40 sits in the setup part, where it runs once. Inside the loop it would set the comet back to 40 on every frame, and the comet would stand still.

Python has a short form: comet_x += 2 does the same.

challenge icon

Challenge

Easy

Make the comet fly: in the # Change things here, once a frame. part, add 2 to comet_x on every frame, so it moves 2 pixels right per frame.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.
moon_x = 160
moon_y = 120
comet_x = 40
comet_y = 200

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)
    pygame.draw.circle(screen, (120, 200, 255), (comet_x, comet_y), 8)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground