And, Or
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 13 of 32.
or joins two conditions and is true when at least one of them is true. and is true only when both are.
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
moon_x = moon_x - 4
if keys[pygame.K_RIGHT] and moon_x < 580:
moon_x = moon_x + 4The first if moves the moon left while Left or A is held: either key works. The second moves it right only while Right is held and the moon is left of x 580, so it stops before the edge of the window.
not turns True into False: not keys[pygame.K_LEFT] is true while Left is up.
Challenge
MediumChange the two key tests:
- Holding A moves the moon left too, like Left. Use
or. - Right moves the moon only while
moon_x < 580, so it stops at x 580. Useand.
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 = 320
moon_y = 240
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Change things here, once a frame.
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
moon_x = moon_x - 4
if keys[pygame.K_RIGHT]:
moon_x = moon_x + 4
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