Menu
CoddyTech

Reach the Goal

Lesson 8 of 41 in Coddy's Make Games with Pygame course.

A game needs a goal. Draw a green square in the bottom right corner, and when the player's square gets inside it, the player wins.

The goal is at (420, 300) and 60 by 60. The player's square is inside it when its left side is at 420 or more and its top at 300 or more. Both must be true, so join them with and.

Winning must last. Keep it in a variable that starts False and only ever becomes True:

won = False

while running:
    # move the square
    if x >= 420 and y >= 300:
        won = True
    if won:
        screen.fill((40, 110, 70))
    else:
        screen.fill((30, 30, 46))

Once won is True, nothing sets it back, so the background stays green even if the square leaves the goal.

challenge icon

Challenge

Easy

Turn the screen green when the square reaches the goal.

  1. Make won = False before the loop. Set it to True when x >= 420 and y >= 300.
  2. Fill with (40, 110, 70) when won, else (30, 30, 46).
  3. Before the square, draw the goal: (60, 200, 120) at (420, 300, 60, 60).

Press Play and steer into the goal: the background turns green. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")
clock = pygame.time.Clock()

x, y = 220, 160

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    speed = 4
    if keys[pygame.K_SPACE]:
        speed = 8
    if keys[pygame.K_LEFT]:
        x -= speed
    if keys[pygame.K_RIGHT]:
        x += speed
    if keys[pygame.K_UP]:
        y -= speed
    if keys[pygame.K_DOWN]:
        y += speed

    x = max(0, min(x, 480 - 40))
    y = max(0, min(y, 360 - 40))

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), (x, y, 40, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Make Games with Pygame

Practice on your own: Pygame playground