Snake

An arrow-key game: the snake eats food and avoids walls, itself and poison. It beeps when it eats and plays falling tones at the end. Teaches key controls, game pace, checking what is on the screen, lists, functions and sound.

Open in Tokbit Level: Expert. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Snake example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""The snake eats and grows; it must not hit a wall or itself. Teaches lists of coordinates."""
from random import randint
# Tokbit screen functions, not in plain Python:
from tokbit import (
    cls, at, color, background, border, char_at, key, sleep, beep, note, BLACK,
    WHITE, RED, GREEN, BLUE, YELLOW, LIGHT_GREEN,
)

def place(ch: str):
    """Puts a character on a random free spot of the screen."""
    x: int = 0
    y: int = 0
    while True:
        x = randint(1, 38)
        y = randint(2, 23)
        if not (char_at(x, y) != " "):
            break
    if ch == "*":
        color(YELLOW)
    else:
        color(RED)
    at(x, y)
    print(ch, end="")

def draw_wall():
    """Black screen and a green wall of # round the field."""
    background(BLACK)
    border(BLUE)
    cls()
    color(GREEN)
    for x in range(40):
        at(x, 1)
        print("#", end="")
        at(x, 24)
        print("#", end="")
    for y in range(1, 25):
        at(0, y)
        print("#", end="")
        at(39, y)
        print("#", end="")

def draw_snake(body_x: list[int], body_y: list[int]):
    """Draws the body of O and the head @ from the coordinate lists."""
    color(LIGHT_GREEN)
    for i in range(len(body_x) - 1):
        at(body_x[i], body_y[i])
        print("O", end="")
    at(body_x[-1], body_y[-1])
    print("@", end="")

def show_score(score: int):
    """Prints the score at the top left."""
    color(WHITE)
    at(0, 0)
    print("Score:", score, end="")

def new_direction(k: str, direction: str) -> str:
    """The new direction from the arrow key; turning back into yourself is not allowed, then the old one stays."""
    if (k == "left" and direction != "right") or (k == "right" and direction != "left") or (k == "up" and direction != "down") or (k == "down" and direction != "up"):
        return k
    return direction

def next_x(direction: str, x: int) -> int:
    """The head column after a step in the given direction."""
    if direction == "left":
        return x - 1
    if direction == "right":
        return x + 1
    return x

def next_y(direction: str, y: int) -> int:
    """The head row after a step in the given direction."""
    if direction == "up":
        return y - 1
    if direction == "down":
        return y + 1
    return y

def move_head(body_x: list[int], body_y: list[int], hx: int, hy: int):
    """The old head becomes body, the new head @ is added at the end of the lists."""
    color(LIGHT_GREEN)
    at(body_x[-1], body_y[-1])
    print("O", end="")
    body_x.append(hx)
    body_y.append(hy)
    at(hx, hy)
    print("@", end="")

def erase_tail(body_x: list[int], body_y: list[int]):
    """Removes the last piece of the tail, so the snake moves on."""
    tx: int = body_x.pop(0)
    ty: int = body_y.pop(0)
    at(tx, ty)
    print(" ", end="")

def game_over(score: int):
    """A melody, GAME OVER and the score."""
    note("G4", 150)
    note("E4", 150)
    note("C4", 300)
    color(WHITE)
    at(15, 11)
    print("GAME OVER", end="")
    at(15, 12)
    print("Score:", score, end="")
    at(10, 14)

playing: str = "a"
while True:
    draw_wall()
    body_x: list[int] = [18, 19, 20]
    body_y: list[int] = [12, 12, 12]
    draw_snake(body_x, body_y)
    place("*")
    place("X")
    place("X")
    place("X")
    direction: str = "right"
    score: int = 0
    eaten: int = 0
    over: bool = False
    paused: int = 120
    show_score(score)
    # Game loop: direction from the arrows, moving the body, food and collisions.
    while not over:
        paused = 120
        k: str = key()
        direction = new_direction(k, direction)
        hx: int = next_x(direction, body_x[-1])
        hy: int = next_y(direction, body_y[-1])
        c: str = char_at(hx, hy)
        if c == "#" or c == "O" or c == "X":
            over = True
        else:
            move_head(body_x, body_y, hx, hy)
            if c == "*":
                score = score + 10
                eaten = eaten + 1
                place("*")
                beep(880, 40)
                paused = 80
                if eaten % 3 == 0:
                    place("X")
            else:
                erase_tail(body_x, body_y)
            show_score(score)
            sleep(paused)
    game_over(score)
    playing = input("Play again (y/n)?")
    if not (playing == "a" or playing == "y"):
        break

All examples