True or False
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 14 of 32.
True and False are values of their own, called booleans. A variable can hold one, like a switch:
lamp_on = FalseAn if can test it directly: if lamp_on: runs when it holds True. not flips it, so lamp_on = not lamp_on switches the lamp.
A switch needs a key press, not a held key. get_pressed() is True on every frame the key is down, so it would flip the lamp 60 times a second. A press arrives once, as a KEYDOWN event, in the event loop at the top of the game loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
lamp_on = not lamp_onSection 2 explains events in full. For now: event.type says what happened and event.key which key.
Challenge
MediumMake Space switch the lamp:
- In the setup part, make
lamp_on = False. - In the event loop, when a
KEYDOWNevent forK_SPACEarrives, setlamp_on = not lamp_on. - Draw the light at
(320, 290), radius 30:(255, 220, 100)whenlamp_onis True, otherwise(70, 70, 90).
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.rect(screen, (90, 90, 110), (310, 300, 20, 180))
pygame.draw.circle(screen, (70, 70, 90), (320, 290), 30)
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python in a Game Window
Practice on your own: Pygame playground