Wrap Around the Edge
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 11 of 33.
An if runs its lines only when a condition is true:
if comet_x > 640:
comet_x = 0The condition ends with a colon. The lines under it are indented 4 spaces: they belong to the if. Python tests the condition on every frame. While the comet is in the window it is false and nothing happens. Once the comet passes the right edge it is true, and the comet goes back to the left.
A comparison is either True or False. > means greater than, < less than, and == asks whether two values are equal. One = stores; two compare.
Test a range such as > 640, not one exact value. The comet starts at 50 and moves 3 pixels a frame: 635, 638, 641. It never lands on 640, so comet_x == 640 would never be true.
Challenge
EasySend the comet back to the left edge when it leaves the window.
- After the line that moves the comet, add an
if. - When
comet_xis greater than640, setcomet_xto0.
Press Play: the comet crosses the window again and again. 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
comet_x = 50
comet_y = 200
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Change things here, once a frame.
comet_x = comet_x + 3
screen.fill((20, 24, 48))
# Draw here, after the fill.
pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)
pygame.draw.circle(screen, (120, 200, 255), (comet_x, comet_y), 8)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
Practice on your own: Pygame playground