Do the Maths
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 6 of 32.
Python does arithmetic: + adds, - subtracts, * multiplies and / divides. Variables can go in a sum:
star_x = moon_x + 90
star_y = moon_y - 40Python 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
EasyDraw two white (255, 255, 255) stars of radius 4, placed from the moon's variables:
- One at
(moon_x + 90, moon_y - 40). - One at
(moon_x * 3, moon_y + 60). - With the moon at (160, 120) they land at (250, 80) and (480, 180).
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
2Numbers and Variables
Name a ValueDo the MathsMove Every FrameWords on the ScreenWhole and Half NumbersPractice on your own: Pygame playground