Name a Value
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 6 of 33.
A variable is a name for a value. A single = stores the value on its right under the name on its left:
star_x = 300
star_y = 60
pygame.draw.circle(screen, (255, 255, 255), (star_x, star_y), 3)Wherever Python meets star_x, it uses the value stored there, 300. 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": star_x = 320 puts 320 in star_x, replacing what was there.
A name is made of letters, digits and underscores, and starts with a letter. Capitals count: Star_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
EasyMove the moon by giving its position names.
- Under
# Set things up here, addmoon_x = 160andmoon_y = 120, with no spaces in front. - In the moon's draw line, replace
(500, 110)with(moon_x, moon_y).
Press Play: the moon moves to the top left. 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.
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