Name a Value
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 5 of 32.
A variable is a name for a value. A single = stores the value on its right under the name on its left:
moon_x = 500
moon_y = 110
pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)Wherever Python meets moon_x, it uses the value stored there, 500. Change the number in one place and every line that uses the name follows.
= does not mean "is equal" as in maths. It means "store": moon_x = 160 puts 160 in moon_x, replacing what was there.
A name is made of letters, digits and underscores, and starts with a letter. Capitals count: Moon_x is another name. Pick names that say what the value is.
Make variables in the setup part, before the game loop. The loop then reads them on every frame.
Challenge
EasyPut the moon's position in variables:
- In the setup part, make
moon_x = 160andmoon_y = 120. - Draw the moon at
(moon_x, moon_y), radius 50, in its usual colour.
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.
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), (500, 110), 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