Menu
CoddyTech

Colours That Change

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 12 of 35.

A colour is three numbers, so a variable can be one of them. Change the variable every frame and the colour changes on the screen.

glow = 0

while running:
    # events
    glow = (glow + 3) % 256
    pygame.draw.circle(screen, (255, glow, 0), (240, 180), 60)

Each frame adds 3 to the green part, so the circle turns from red through orange to yellow.

Every part of a colour must stay from 0 to 255. At 256 pygame stops with ValueError: invalid color. The % operator gives the remainder of a division: 256 % 256 is 0 and 258 % 256 is 2. So (glow + 3) % 256 starts again near 0 instead of passing 255, and the circle glows from red to yellow over and over.

challenge icon

Challenge

Easy

Make the circle glow from red to yellow.

  1. Before the loop, set glow = 0.
  2. In the loop, before drawing, add 3 to glow and keep it from 0 to 255 with % 256.
  3. Draw the circle in (255, glow, 0).

Press Play: the circle glows from red to yellow, over and over. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Glow")
clock = pygame.time.Clock()

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

    screen.fill((30, 30, 46))
    pygame.draw.circle(screen, (255, 120, 0), (240, 180), 60)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in The Game Loop

Practice on your own: Pygame playground