Menu
CoddyTech

Reach the Goal

Lesson 8 of 40 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
  1. Before the loop, set won = False.
  2. After you limit x and y, set won = True when x >= 420 and y >= 300.
  3. Fill the screen with (40, 110, 70) when won is true, and with (30, 30, 46) otherwise.
  4. Before the player's square, draw the goal: green (60, 200, 120) at (420, 300, 60, 60).

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground