Sokoban
The warehouse classic: push the boxes onto the goals; a box can only be pushed and two in a row will not move. Three levels as lists of texts, R restarts. Teaches a grid in a list, movement rules and levels as data.
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
Python program
The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.
"""The classic Sokoban: push the boxes onto the goals in three levels. Teaches a grid in a list, movement rules and levels as data."""
# Tokbit screen functions, not in plain Python:
from tokbit import (
cls, at, color, background, border, key, sleep, beep, note, sprite_at,
sprite_color, sprite_hide, sprite_shape, BLACK, WHITE, CYAN, YELLOW,
ORANGE, BROWN, GREY, LIGHT_GREEN,
)
def load_level(lines: list[str]) -> list[list[str]]:
"""Turns a level from a list of texts into a grid of characters that can change: # wall, . goal, $ box, * box on a goal. Takes the keeper (@) out of the grid."""
grid: list[list[str]] = []
for y in range(len(lines)):
row: list[str] = []
for x in range(len(lines[y])):
c: str = lines[y][x]
if c == "@":
c = " "
if c == "+":
c = "."
row.append(c)
grid.append(row)
return grid
def find_player(lines: list[str]) -> list[int]:
"""Where the keeper stands in the level: [column, row]."""
for y in range(len(lines)):
for x in range(len(lines[y])):
if lines[y][x] == "@" or lines[y][x] == "+":
return [x, y]
return [1, 1]
def draw_tile(grid: list[list[str]], x: int, y: int, ox: int, oy: int):
"""One grid square as 2 × 2 characters (16 points, the size of a sprite); a box on a goal is green."""
c: str = grid[y][x]
pattern: str = " "
color(GREY)
if c == "#":
pattern = "##"
if c == ".":
color(YELLOW)
pattern = "<>"
if c == "$":
color(ORANGE)
pattern = "[]"
if c == "*":
color(LIGHT_GREEN)
pattern = "[]"
at((ox + x) * 2, (oy + y) * 2)
print(pattern, end="")
at((ox + x) * 2, (oy + y) * 2 + 1)
print(pattern, end="")
def draw_level(grid: list[list[str]], ox: int, oy: int):
"""Draws the whole level and a hint."""
cls()
for y in range(len(grid)):
for x in range(len(grid[y])):
draw_tile(grid, x, y, ox, oy)
color(GREY)
at(0, 23)
print("Arrows: walk, R: restart level", end="")
def step(grid: list[list[str]], player: list[int], dx: int, dy: int) -> int:
"""The movement rules: the keeper steps (1), pushes a box (2), pushes it onto a goal (3), or cannot move (0). Changes the grid and the keeper's position."""
nx: int = player[0] + dx
ny: int = player[1] + dy
c: str = grid[ny][nx]
if c == "#":
return 0
# A box can only be pushed, not pulled.
if c == "$" or c == "*":
d: str = grid[ny + dy][nx + dx]
# A wall or another box behind the box: it cannot be pushed.
if d != " " and d != ".":
return 0
if d == ".":
grid[ny + dy][nx + dx] = "*"
else:
grid[ny + dy][nx + dx] = "$"
if c == "*":
grid[ny][nx] = "."
else:
grid[ny][nx] = " "
player[0] = nx
player[1] = ny
if d == ".":
return 3
return 2
player[0] = nx
player[1] = ny
return 1
def solved(grid: list[list[str]]) -> bool:
"""The level is solved when no box stands off a goal."""
for y in range(len(grid)):
for x in range(len(grid[y])):
if grid[y][x] == "$":
return False
return True
def show_status(level: int, count: int, moves: int):
"""At the top: the level and the number of moves."""
color(WHITE)
at(0, 0)
print("Level " + str(level + 1) + "/" + str(count) + " Moves: " + str(moves) + " ", end="")
def fanfare():
"""A solved level."""
notes: list[str] = ["C4", "E4", "G4", "C5"]
for i in range(len(notes)):
note(notes[i], 120)
background(BLACK)
border(BROWN)
# Levels as lists of texts: # wall, $ box, . goal, * box on a goal, @ keeper. Add your own.
levels: list[list[str]] = [["#######", "# #", "#@ $. #", "# #", "#######"], ["########", "# #", "#.$ $.#", "# @ #", "########"], [" ##### ", "### # ", "#.@$ # ", "### $.# ", "#.##$ # ", "# # . ##", "#$ *$$.#", "# . #", "########"]]
# Two shapes of the keeper: they alternate while walking.
keeper1: list[str] = ["......####......", ".....######.....", ".....#.##.#.....", ".....######.....", "......####......", "....########....", "...##.####.##...", "...#..####..#...", "......####......", "......####......", ".....##..##.....", ".....##..##.....", ".....##...##....", "....##....##....", "....##.....##...", "................"]
keeper2: list[str] = ["......####......", ".....######.....", ".....#.##.#.....", ".....######.....", "......####......", "....########....", "...##.####.##...", "...#..####..#...", "......####......", "......####......", ".....##..##.....", ".....##..##.....", "....##...##.....", "....##....##....", "...##.....##....", "................"]
sprite_shape(0, keeper1)
sprite_color(0, CYAN)
level: int = 0
steps: int = 0
# The loop over levels: after one is solved, the next comes.
while level < len(levels):
grid: list[list[str]] = load_level(levels[level])
player: list[int] = find_player(levels[level])
ox: int = (20 - len(grid[0])) // 2
oy: int = 2
draw_level(grid, ox, oy)
moves: int = 0
show_status(level, len(levels), moves)
sprite_at(0, (ox + player[0]) * 16, (oy + player[1]) * 16)
done: bool = False
# The game loop: a key, a move by the rules, redrawing two squares and a sound, until all boxes are on goals.
while not done:
k: str = key()
dx: int = 0
dy: int = 0
if k == "left":
dx = -1
if k == "right":
dx = 1
if k == "up":
dy = -1
if k == "down":
dy = 1
# R restarts the level.
if k == "r":
grid = load_level(levels[level])
player = find_player(levels[level])
draw_level(grid, ox, oy)
moves = 0
show_status(level, len(levels), moves)
sprite_at(0, (ox + player[0]) * 16, (oy + player[1]) * 16)
if dx != 0 or dy != 0:
result: int = step(grid, player, dx, dy)
if result > 0:
moves = moves + 1
steps = steps + 1
draw_tile(grid, player[0], player[1], ox, oy)
draw_tile(grid, player[0] + dx, player[1] + dy, ox, oy)
# The walking animation: a different shape every step.
if steps % 2 == 0:
sprite_shape(0, keeper1)
else:
sprite_shape(0, keeper2)
sprite_at(0, (ox + player[0]) * 16, (oy + player[1]) * 16)
show_status(level, len(levels), moves)
if result == 1:
beep(180, 15)
if result == 2:
beep(120, 40)
if result == 3:
beep(660, 60)
else:
beep(60, 30)
done = solved(grid)
sleep(20)
fanfare()
sleep(500)
level = level + 1
sprite_hide(0)
cls()
color(LIGHT_GREEN)
at(6, 11)
print("All levels solved!", end="")