Menu
CoddyTech

Levels

Lesson 28 of 40 in Coddy's Make Games with Pygame course.

Every 5 food, the snake reaches a new level and moves faster. The level follows from the score: whole division score // 5 is 0 for scores 0 to 4, 1 for 5 to 9, and so on.

level = score // 5 + 1
clock.tick(8 + 2 * level)

The snake moves one cell a frame, so more frames a second is a faster snake: 10 steps a second at level 1, 12 at level 2, 14 at level 3.

Reaching 15 food wins. The game stops while alive and score < 15 is false, and shows You win!.

challenge icon

Challenge

Hard
  1. Each frame, set level = score // 5 + 1 and show f"Level: {level}" at (370, 6).
  2. Tick at 8 + 2 * level frames a second.
  3. Move only while alive and score < 15, and show You win! centred at (240, 180) when the score is 15.

Try it yourself

import random
import pygame

CELL = 20
COLS, ROWS = 24, 18
TURNS = {
    pygame.K_LEFT: (-1, 0),
    pygame.K_RIGHT: (1, 0),
    pygame.K_UP: (0, -1),
    pygame.K_DOWN: (0, 1),
}

pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)


def draw_cell(cell, color):
    col, row = cell
    pygame.draw.rect(screen, color, (col * CELL + 1, row * CELL + 1, CELL - 2, CELL - 2))


def new_food(body):
    while True:
        cell = (random.randrange(COLS), random.randrange(ROWS))
        if cell not in body:
            return cell


body = [(5, 9), (4, 9), (3, 9)]
direction = (1, 0)
food = new_food(body)
score = 0
alive = True

running = True
while running:
    moving = direction
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key in TURNS:
            turn = TURNS[event.key]
            if turn != (-moving[0], -moving[1]):
                direction = turn

    if alive:
        x = body[0][0] + direction[0]
        y = body[0][1] + direction[1]
        if x < 0 or x >= COLS or y < 0 or y >= ROWS or (x, y) in body[:-1]:
            alive = False
        else:
            body.insert(0, (x, y))
            if (x, y) == food:
                score += 1
                food = new_food(body)
            else:
                body.pop()

    screen.fill((30, 30, 46))
    draw_cell(food, (235, 80, 80))
    for cell in body[1:]:
        draw_cell(cell, (120, 220, 120))
    draw_cell(body[0], (180, 255, 160))
    score_text = font.render(f"Score: {score}", True, (240, 240, 240))
    screen.blit(score_text, (8, 6))
    if not alive:
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 180)))
    pygame.display.flip()
    clock.tick(10)

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