A State Variable
Part of the Game Rules section of Coddy's Pygame journey. Lesson 1 of 29.
Right now a hit closes the window. A game should stop and show what happened instead. The program needs to remember which part of the game it is in: playing, or over.
Keep that in one variable, a state, holding a short string:
state = "play"
...
if state == "play":
# move the player and the rock
if rock.colliderect(player):
state = "over"Only the code under if state == "play": moves things, so when the state becomes "over" everything freezes. The loop keeps running: it still reads events, draws and ticks the clock, so the window stays open and can show a message.
A string reads well in the code. A test like state == "over" says what it means, and the next lessons add more states the same way.
Challenge
Easy- Before the loop, add
state = "play". - Put the keys, the player and the rock code under
if state == "play":. - When the rock hits the player, set
state = "over"instead ofrunning = False. - After drawing the score, when
state == "over", showGame overcentred at (240, 160).
Try it yourself
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 6
if keys[pygame.K_RIGHT]:
player.x += 6
player.clamp_ip(screen.get_rect())
rock.y += 4
if rock.top > 360:
rock.y = -24
rock.x = random.randint(0, 456)
score += 1
if rock.colliderect(player):
running = False
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 196, 0), player)
pygame.draw.rect(screen, (235, 80, 80), rock)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Game Rules
1Game States
A State VariableA Menu ScreenPress R to Play AgainA Reset FunctionOne Function per StatePractice on your own: Pygame playground