Menu
CoddyTech

Do the Maths

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

Python does arithmetic: + adds, - subtracts, * multiplies and / divides. Variables can go in a sum:

star_x = moon_x + 90
star_y = moon_y - 40

Python works out the right side first, then stores the result. With moon_x = 160, star_x becomes 250.

A sum can also go straight where a number goes: (moon_x + 90, moon_y - 40) is a centre 90 pixels right of the moon and 40 pixels above it. Move the moon and the star moves with it.

Python follows the order of maths: * and / before + and -. 2 + 3 * 4 is 14. Brackets change the order: (2 + 3) * 4 is 20.

challenge icon

Challenge

Easy

Place two white (255, 255, 255) stars of radius 4 from the moon's variables.

  1. Draw one at (moon_x + 90, moon_y - 40).
  2. Draw one at (moon_x * 3, moon_y + 60).

Press Play: one star sits just above and right of the moon at (250, 80), the other far to the right at (480, 180). Then Check.

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

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.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground