---
title: "Project: A Game on a Grid"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 37
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/37-project-a-game-on-a-grid
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 37 — Project: A Game on a Grid

The last project of this book is a game: a maze in the terminal, drawn with [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string), where the player hunts for a treasure. It uses everything the grade has built: [grids](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid), dictionaries, [text files](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-text-file), [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), tests. As in the earlier projects, it grows in versions, and each version runs and is tested before the next one starts. Here is what the finished game must do:

> The player starts at S and must reach the treasure T without walking through walls. The treasure is behind a gate, which opens only once every gem of the maze has been collected. The player has a limited number of moves, and sees the maze drawn again after each move that they type. Each level is read from a [text file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-text-file), so that new levels need no new code.

**You already know.**

A [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid) is a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and `grid[r][c]` is the cell in row `r`, column `c` ([Chapter 33](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#ch-g9-grids-and-images)). A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) keeps [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) under keys ([Chapter 26](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#ch-g8-dictionaries)); a [text file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-text-file) is read with `open` ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)). A project grows in versions, each one tested ([Chapter 24](https://one-course.com/books/computer-science/1/en/chapter/24-project-a-quiz-game#ch-g7-project-quiz-game), [Chapter 30](https://one-course.com/books/computer-science/1/en/chapter/30-project-a-data-explorer#ch-g8-project-data-explorer)).

## 37.1 What must it do?

The paragraph above, turned into checks small enough to test:

1. A level [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) gives the number of moves on its first line, then the maze, one row per line: `#` for a wall, `.` for the floor, `S` , `T` , `g` for a gem and `=` for the gate.
2. A level with no S, two S’s, no T or rows of different lengths is refused with a message.
3. The player cannot enter a wall, nor the gate while a gem is left.
4. Stepping on a gem collects it; the last gem opens the gate.
5. Each move costs one move; a blocked move costs nothing.
6. The game ends with a win on T, or a loss when no moves are left.

![Level 1: walls in dark, the start S, the treasure T, two gems (green) and the gate (yellow bar) that keeps T closed until both gems are collected.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-project-grid-game/fig-e071cbb8ca3d.svg)

*Level 1: walls in dark, the start S, the treasure T, two gems (green) and the gate (yellow bar) that keeps T closed until both gems are collected.*

![The five versions, with what each one adds; a sixth program checks levels by trying every sequence of moves.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-project-grid-game/fig-12b338ee03f3.svg)

*The five versions, with what each one adds; a sixth [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) checks levels by trying every sequence of moves.*

## 37.2 Representing the state

Everything the game must remember, at any moment, is its *state*: the maze, where the player is, the gems left and the moves left. The maze is a [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid) of [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string), one [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) per row, so that a cell can be changed when a gem is collected; the rest goes into a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary), with the [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid) itself:

```python
rows = ["#########",
        "#S..#.#T#",
        "#.#.#.#=#",
        "#g#...#.#",
        "#.###g#.#",
        "#.......#",
        "#########"]
grid = []
for row in rows:
    grid.append(list(row))           # a list of characters per row
grid[1][1] = "."                     # the player stands on the floor
state = {"grid": grid, "row": 1, "col": 1, "gems_left": 2, "moves_left": 20}

print("the maze has", len(grid), "rows and", len(grid[0]), "columns")
print("the player is at row", state["row"], "column", state["col"])
print("below the player:", repr(grid[state["row"] + 1][state["col"]]))
print("right of the start:", repr(grid[1][2]), " the treasure:", repr(grid[1][7]))
print("gems left:", state["gems_left"], " moves left:", state["moves_left"])
```

***Listing 37.1.** Version 1: the state of a game. code/grade-9/07-project-grid-game/listings/maze_v1.py*

```
$ python maze_v1.py
the maze has 7 rows and 9 columns
the player is at row 1 column 1
below the player: '.'
right of the start: '.'  the treasure: 'T'
gems left: 2  moves left: 20
```

***Output 37.1.** Rows and columns counted from 0, as for every [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid).*

`repr` prints a [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) with its quotes, so that a space or a dot is easy to see. The start cell is replaced by floor: S only marks where the player begins, and the player’s position lives in the [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary).

![The state at the start of level 1: one dictionary, whose "grid" is the list of rows; the S has become floor.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-project-grid-game/fig-31d5b657b705.svg)

*The state at the start of level 1: one [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary), whose `"grid"` is the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of rows; the S has become floor.*

## 37.3 Reading a maze file

Version 2 reads the level from a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) and checks it before using it. A level that breaks a rule gets a message saying what is wrong; a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) that returns an empty [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) when all is well is easy to test.

```python
def check_level(text):
    """An empty string if the level is right, or what is wrong with it."""
    rows = text.splitlines()[1:]
    for row in rows:
        if len(row) != len(rows[0]):
            return "every row must have the same length"
    if text.count("S") != 1 or text.count("T") != 1:
        return "a level needs exactly one S and one T"
    return ""


def parse_level(text):
    """The state of a game, from the text of a checked level file."""
    lines = text.splitlines()
    grid = []
    for r in range(1, len(lines)):
        grid.append(list(lines[r]))
        if "S" in lines[r]:
            start = [r - 1, lines[r].index("S")]
    grid[start[0]][start[1]] = "."
    return {"grid": grid, "row": start[0], "col": start[1],
            "gems_left": text.count("g"), "moves_left": int(lines[0])}


def read_text(filename):
    with open(filename, encoding="utf-8") as f:
        return f.read()

```

***Listing 37.2.** Version 2: checking a level, then reading it. code/grade-9/07-project-grid-game/listings/maze_v2.py*

```python
if __name__ == "__main__":
    for filename in ["level1.txt", "bad_level.txt"]:
        text = read_text(filename)
        problem = check_level(text)
        if problem == "":
            state = parse_level(text)
            print(filename + ": ok, start at", state["row"], state["col"],
                  "with", state["gems_left"], "gems and", state["moves_left"], "moves")
        else:
            print(filename + ":", problem)
```

***Listing 37.3.** Version 2: two [files](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) checked. code/grade-9/07-project-grid-game/listings/maze_v2.py*

```
$ python maze_v2.py
level1.txt: ok, start at 1 1 with 2 gems and 20 moves
bad_level.txt: a level needs exactly one S and one T
```

***Output 37.2.** The second [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) has two S’s.*

`parse_level` looks for S row by row: `"S" in lines[r]` tells whether the row holds it, and `lines[r].index("S")` gives its column. Row 0 of the [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid) is line 1 of the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file), after the number of moves.

## 37.4 Drawing as text

```python
def draw(state):
    for r in range(len(state["grid"])):
        line = ""
        for c in range(len(state["grid"][r])):
            if r == state["row"] and c == state["col"]:
                line = line + "@"
            else:
                line = line + state["grid"][r][c]
        print(line)
    print("gems left:", state["gems_left"], "  moves left:", state["moves_left"])


if __name__ == "__main__":
    draw(parse_level(read_text("level1.txt")))
```

***Listing 37.4.** Version 3: drawing the maze with the player. code/grade-9/07-project-grid-game/listings/maze_v3.py*

```
$ python maze_v3.py
#########
#@..#.#T#
#.#.#.#=#
#g#...#.#
#.###g#.#
#.......#
#########
gems left: 2   moves left: 20
```

***Output 37.3.** The player, @, at the start.*

## 37.5 The rules as functions

Each rule becomes a small [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) on the state. `can_move` looks at the cell the player would enter; `move` moves, collects a gem and opens the gate after the last one; `won` tells whether the player stands on T.

```python
def can_move(state, key):
    """True if the player may move in the direction of key."""
    cell = state["grid"][state["row"] + MOVES[key][0]][state["col"] + MOVES[key][1]]
    if cell == "#":
        return False
    if cell == "=" and state["gems_left"] > 0:
        return False
    return True


def move(state, key):
    """Move the player one cell; collect a gem; open the gate after the last."""
    state["row"] = state["row"] + MOVES[key][0]
    state["col"] = state["col"] + MOVES[key][1]
    state["moves_left"] = state["moves_left"] - 1
    grid = state["grid"]
    if grid[state["row"]][state["col"]] == "g":
        grid[state["row"]][state["col"]] = "."
        state["gems_left"] = state["gems_left"] - 1
        if state["gems_left"] == 0:
            for row in grid:
                for c in range(len(row)):
                    if row[c] == "=":
                        row[c] = "."


def won(state):
    return state["grid"][state["row"]][state["col"]] == "T"

```

***Listing 37.5.** Version 4: the rules. code/grade-9/07-project-grid-game/listings/maze_v4.py*

The maze is surrounded by walls, so `can_move` never looks outside the [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid): a level must keep its border (Exercise [37.4](#exo-g9-project-grid-game-4) shows what happens otherwise). Before a game [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) exists, a fixed sequence of moves tries the rules:

```python
if __name__ == "__main__":
    state = parse_level(read_text("level1.txt"))
    for key in "wssss":
        if can_move(state, key):
            move(state, key)
            print(key, "-> row", state["row"], "column", state["col"],
                  " gems left:", state["gems_left"])
        else:
            print(key, "-> blocked")
    draw(state)
```

***Listing 37.6.** Version 4: five moves, typed in the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). code/grade-9/07-project-grid-game/listings/maze_v4.py*

```
$ python maze_v4.py
w -> blocked
s -> row 2 column 1  gems left: 2
s -> row 3 column 1  gems left: 1
s -> row 4 column 1  gems left: 1
s -> row 5 column 1  gems left: 1
#########
#...#.#T#
#.#.#.#=#
#.#...#.#
#.###g#.#
#@......#
#########
gems left: 1   moves left: 16
```

***Output 37.4.** The wall above blocks the first move; the gem is collected on the way down.*

The tests of the chapter check each rule on hand-made [grids](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid) of a few cells: a gate that opens when the only gem is taken, a gate that stays closed while one gem is left, a treasure reached with the right number of moves left.

## 37.6 A turn and the game loop

![One turn of the game, as a flowchart. A typing mistake or a wall costs no move; every real move ends with the maze drawn again.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-project-grid-game/fig-1b5ff5fde9b3.svg)

*One turn of the game, as a flowchart. A typing mistake or a wall costs no move; every real move ends with the maze drawn again.*

Version 5 adds `play`, the game [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop). The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) now waits for the player at each turn and reacts to the key typed.

```python
def play(filename):
    """One game: read moves until the treasure is reached or no moves are left."""
    text = read_text(filename)
    if check_level(text) != "":
        print(filename + ":", check_level(text))
        return False
    state = parse_level(text)
    draw(state)
    while state["moves_left"] > 0:
        key = input("move (w a s d): ")
        if key not in MOVES:
            print("type w, a, s or d")
        elif not can_move(state, key):
            print("blocked")
        else:
            move(state, key)
            draw(state)
            if won(state):
                print("You found the treasure!")
                return True
    print("No moves left.")
    return False


if __name__ == "__main__":
    play("level1.txt")
```

***Listing 37.7.** Version 5: the game [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop). code/grade-9/07-project-grid-game/listings/maze_v5.py*

To test a game without a player at the keyboard, the moves come from a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of keys, one per line: the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) shows each one after its prompt. A winning game:

```
$ python maze_v5.py
#########
#@..#.#T#
#.#.#.#=#
#g#...#.#
#.###g#.#
#.......#
#########
gems left: 2   moves left: 20
move (w a s d): w
blocked
move (w a s d): w
#########
#...#.#T#
#.#.#.#.#
#.#...#.#
#.###@#.#
#.......#
#########
gems left: 0   moves left: 11
move (w a s d): w
#########
#...#.#@#
#.#.#.#.#
#.#...#.#
#.###.#.#
#.......#
#########
gems left: 0   moves left: 4
You found the treasure!
```

***Output 37.5.** A won game of 16 moves: the start, the second gem (the gate opens), the treasure. Some lines are left out.*

And a lost one, by a player who walks right and left until the moves run out:

```
$ python lost_game.py
move (w a s d): a
#########
#@..#.#T#
#.#.#.#=#
#g#...#.#
#.###g#.#
#.......#
#########
gems left: 2   moves left: 0
No moves left.
```

***Output 37.6.** The end of a lost game. Some lines are left out.*

## 37.7 A second level and a check by every sequence

Is a level winnable at all? A level whose gem is walled in can never open its gate. A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can find out by trying *every* sequence of moves. With 4 possible moves, there are 4 sequences of one move, $4 \times 4 = 16$ of two moves, and $4^n$ of $n$ moves: the count is multiplied by 4 at each step, as the count of [binary numbers](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) is multiplied by 2 at each new [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) ([Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal)).

![Every sequence of one and of two moves: each branch splits into four, so n moves make 4n sequences.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-project-grid-game/fig-86d88b45c13f.svg)

*Every sequence of one and of two moves: each branch splits into four, so $n$ moves make $4^n$ sequences.*

To [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) them, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) counts from 0 to $4^n - 1$ and writes each number in base 4, with the digits 0, 1, 2, 3 replaced by `w`, `a`, `s`, `d`. Each sequence is then replayed on a fresh state from the level text:

```python
from maze_v5 import can_move, move, parse_level, read_text, won


def wins(text, sequence):
    """True if the moves of sequence reach the treasure (blocked moves are skipped)."""
    state = parse_level(text)
    for key in sequence:
        if state["moves_left"] > 0 and can_move(state, key):
            move(state, key)
            if won(state):
                return True
    return False


def all_sequences(n):
    """Every sequence of n moves: the numbers 0 to 4**n - 1 written in base 4."""
    sequences = []
    for number in range(4 ** n):
        sequence = ""
        for _ in range(n):
            sequence = "wasd"[number % 4] + sequence
            number = number // 4
        sequences.append(sequence)
    return sequences


if __name__ == "__main__":
    for filename in ["tiny.txt", "level2.txt"]:
        text = read_text(filename)
        for n in range(1, 8):
            count = 0
            for sequence in all_sequences(n):
                if wins(text, sequence):
                    count = count + 1
            print(f"{filename:<11} {n} moves: {4 ** n:>6} sequences, {count:>3} win")
```

***Listing 37.8.** Trying every sequence of up to 7 moves. code/grade-9/07-project-grid-game/listings/try_all_moves.py*

```
$ python try_all_moves.py
tiny.txt    1 moves:      4 sequences,   0 win
tiny.txt    2 moves:     16 sequences,   0 win
tiny.txt    3 moves:     64 sequences,   0 win
tiny.txt    4 moves:    256 sequences,   0 win
tiny.txt    5 moves:   1024 sequences,   0 win
tiny.txt    6 moves:   4096 sequences,   1 win
tiny.txt    7 moves:  16384 sequences,  17 win
level2.txt  1 moves:      4 sequences,   0 win
level2.txt  2 moves:     16 sequences,   0 win
level2.txt  3 moves:     64 sequences,   0 win
level2.txt  4 moves:    256 sequences,   0 win
level2.txt  5 moves:   1024 sequences,   0 win
level2.txt  6 moves:   4096 sequences,   0 win
level2.txt  7 moves:  16384 sequences,   0 win
```

***Output 37.7.** A small level and an impossible one.*

On `tiny.txt`, no sequence of fewer than 6 moves wins, and exactly one of the 4,096 sequences of 6 moves does. On `level2.txt`, none of the 21,844 sequences of up to 7 moves wins. Is that a proof that it never can? For this level, yes, because the gem is walled in on all four sides, which the eye sees at once; for a large maze, $4^n$ grows far too fast to try every sequence, and cleverer searches are the subject of the next book.

## 37.8 Exercises

**Exercise 37.1 ★.**

Starting from level 1, the player types `s`, `s`, `s`. Draw the maze as version 5 shows it, with the line of gems and moves left.

**Solution of Exercise 37.1.**

Three steps down from row 1 take the player to row 4, column 1; the gem of row 3 is collected on the way:

| ######### |
| --- |
| #...#.#T# |
| #.#.#.#=# |
| #.#...#.# |
| #@###g#.# |
| #.......# |
| ######### |
| gems left: 1 moves left: 17 |

**Exercise 37.2 ★.**

At the start of level 1, what does `can_move(state, "w")` return, and why? And `can_move(state, "d")`?

**Solution of Exercise 37.2.**

`False`: the cell above the start, row 0, column 1, is a wall. `True` for `d`: the cell to the right is floor.

**Exercise 37.3 ★.**

Add a “wait” move, `x`: the player stays in place, but it costs a move. Find the smallest change to version 5 that does it.

**Solution of Exercise 37.3.**

One line: a move of zero rows and zero columns. `can_move` looks at the player’s own cell, which is floor, and `move` spends a move without going anywhere.

```python
from maze_v5 import MOVES, play

MOVES["x"] = [0, 0]          # x: stay in place, and spend a move

if __name__ == "__main__":
    play("level1.txt")
```

*A wait move. code/grade-9/07-project-grid-game/exercises/wait_move.py*

**Exercise 37.4 ★.**

A maze without a border of walls is checked by this [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function). What does it print? Explain each answer, then fix the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function).

```python
MOVES = {"w": [-1, 0], "s": [1, 0], "a": [0, -1], "d": [0, 1]}
grid = [list("S.g"), list(".#."), list("..T")]


def can_move(row, col, key):
    cell = grid[row + MOVES[key][0]][col + MOVES[key][1]]
    return cell != "#"


print(can_move(0, 0, "a"), can_move(0, 0, "w"), can_move(1, 0, "d"))
```

***Listing 37.9.** Moves on a maze without a border. code/grade-9/07-project-grid-game/exercises/wrap_bug.py*

**Solution of Exercise 37.4.**

It prints `True True False`. From the top left corner, `a` reads column $-1$, which Python takes as the last column of the row, a gem: the player could walk off the left edge and come back on the right. `w` reads row $-1$, the last row, in the same way. Only the third answer is right: the cell right of row 1, column 0 is a wall. The fix checks the edges first:

```python
def can_move(row, col, key):
    r = row + MOVES[key][0]
    c = col + MOVES[key][1]
    if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]):
        return False                     # off the edge of the maze
    return grid[r][c] != "#"


print(can_move(0, 0, "a"), can_move(0, 0, "w"), can_move(1, 0, "d"))
```

*Moves that stay inside the maze. code/grade-9/07-project-grid-game/exercises/wrap_fixed.py*

It prints `False False False`.

**Exercise 37.5 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `replay(text, sequence)` that plays a [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) of moves on a level and returns the number of moves used to win, or $-1$ if the sequence does not win. How many moves did the winning game of [Output 37.5](#out-g9-project-grid-game-v5) use?

**Solution of Exercise 37.5.**

The same replay as in `wins`, counting the moves that are made:

```python
from maze_v5 import can_move, move, parse_level, read_text, won


def replay(text, sequence):
    """The number of moves used to win with sequence, or -1 if it does not win."""
    state = parse_level(text)
    used = 0
    for key in sequence:
        if state["moves_left"] > 0 and can_move(state, key):
            move(state, key)
            used = used + 1
            if won(state):
                return used
    return -1


if __name__ == "__main__":
    print(replay(read_text("level1.txt"), "wssssddddwsddwwww"))
    print(replay(read_text("level1.txt"), "ssss"))
```

*Replaying a sequence. code/grade-9/07-project-grid-game/exercises/replay.py*

The game of [Output 37.5](#out-g9-project-grid-game-v5) used 16 moves: the first `w` was blocked and cost nothing, and 4 of the 20 moves were left. A test of the chapter checks it.

**Exercise 37.6 ★★.**

In this version of `move`, the gate of level 1 opens too soon. When does it open? Fix it.

```python
def move(state, key):
    state["row"] = state["row"] + MOVES[key][0]
    state["col"] = state["col"] + MOVES[key][1]
    state["moves_left"] = state["moves_left"] - 1
    grid = state["grid"]
    if grid[state["row"]][state["col"]] == "g":
        grid[state["row"]][state["col"]] = "."
        state["gems_left"] = state["gems_left"] - 1
    if state["gems_left"] <= 1:
        for row in grid:
            for c in range(len(row)):
                if row[c] == "=":
                    row[c] = "."
```

***Listing 37.10.** A gate that opens early. code/grade-9/07-project-grid-game/exercises/gate_bug.py*

**Solution of Exercise 37.6.**

The test `gems_left <= 1` is true as soon as one of the two gems is collected, so the gate of level 1 opens after the first gem. In a level with a single gem it is worse: the test is true at the very first move, before the gem is touched. The test must be `== 0`, and it belongs inside the `if` that collects a gem, as in [Listing 37.5](#lst-g9-project-grid-game-v4).

**Exercise 37.7 ★★.**

A level may hold two teleport squares, marked `o`: a player who steps on one jumps to the other. Write `move_teleport(state, key)`, using `move`.

**Solution of Exercise 37.7.**

After the usual move, look for the other `o` and put the player there:

```python
from maze_v5 import move


def move_teleport(state, key):
    """Move as usual; a player who lands on an o jumps to the other o."""
    move(state, key)
    grid = state["grid"]
    if grid[state["row"]][state["col"]] == "o":
        for r in range(len(grid)):
            for c in range(len(grid[r])):
                if grid[r][c] == "o" and [r, c] != [state["row"], state["col"]]:
                    target = [r, c]
        state["row"] = target[0]
        state["col"] = target[1]
```

*Teleport squares. code/grade-9/07-project-grid-game/exercises/teleport.py*

**Exercise 37.8 ★★.**

How many sequences of 6 moves are there? Of 10 moves? If a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) replays a million sequences per second, how long do the sequences of 15 moves take?

**Solution of Exercise 37.8.**

$4^6 = 4{,}096$ and $4^{10} = 1{,}048{,}576$. Sequences of 15 moves: $4^{15} = 1{,}073{,}741{,}824$, about 1,074 seconds at a million per second, nearly 18 minutes. Each extra move multiplies the time by 4.

**Exercise 37.9 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `winnable(text, most)` that tells whether some sequence of at most `most` moves wins the level. Check it on `tiny.txt` and `level2.txt`.

**Solution of Exercise 37.9.**

```python
from maze_v5 import read_text
from try_all_moves import all_sequences, wins


def winnable(text, most):
    """True if some sequence of at most most moves wins the level."""
    for n in range(1, most + 1):
        for sequence in all_sequences(n):
            if wins(text, sequence):
                return True
    return False


if __name__ == "__main__":
    print("tiny.txt:", winnable(read_text("tiny.txt"), 6))
    print("level2.txt:", winnable(read_text("level2.txt"), 6))
```

*Is a level winnable? code/grade-9/07-project-grid-game/exercises/checker.py*

It prints `tiny.txt: True` and `level2.txt: False`. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) stops at the first winning sequence; it reuses `all_sequences` and `wins` from [Listing 37.8](#lst-g9-project-grid-game-all).

**Exercise 37.10 ★★★.**

Add a “fog” mode: `draw_fog(state, sight)` draws only the cells at most `sight` rows and `sight` columns from the player, and a `?` everywhere else.

**Solution of Exercise 37.10.**

The test `abs(r - state["row"]) <= sight` keeps the rows near the player, and the same for the columns:

```python
def draw_fog(state, sight):
    """Draw only the cells at most sight rows and columns from the player."""
    for r in range(len(state["grid"])):
        line = ""
        for c in range(len(state["grid"][r])):
            if r == state["row"] and c == state["col"]:
                line = line + "@"
            elif abs(r - state["row"]) <= sight and abs(c - state["col"]) <= sight:
                line = line + state["grid"][r][c]
            else:
                line = line + "?"
        print(line)
```

*A fog mode. code/grade-9/07-project-grid-game/exercises/fog.py*

At the start of level 1 with `sight` 1, the first row drawn is `###??????`.

**Exercise 37.11 ★★★.**

A maze has no gems and no gate. Show that if the treasure can be reached at all, it can be reached in at most (number of floor cells $- 1$) moves.

**Solution of Exercise 37.11.**

Take a winning path. If it visits some cell twice, cut out everything between the two visits: the player is in the same place afterwards, so the rest of the path still works, and it is shorter. Repeat until no cell is visited twice. The path then visits each floor cell at most once; with $f$ floor cells, it visits at most $f$ cells, so it makes at most $f - 1$ moves. (With gems and a gate, the cut may skip a gem, and the argument no longer works.)

**Exercise 37.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `shortest(text, most)` that returns a shortest winning sequence, by trying the lengths 1, 2, 3, … in order. What does it return for `tiny.txt`?

**Solution of Exercise 37.12.**

Trying the lengths in order means the first winning sequence found is a shortest one:

```python
from maze_v5 import read_text
from try_all_moves import all_sequences, wins


def shortest(text, most):
    """The first winning sequence, trying the lengths 1, 2, 3, ... in order."""
    for n in range(1, most + 1):
        for sequence in all_sequences(n):
            if wins(text, sequence):
                return sequence
    return ""


if __name__ == "__main__":
    print(shortest(read_text("tiny.txt"), 7))
```

*The shortest winning sequence. code/grade-9/07-project-grid-game/exercises/shortest.py*

For `tiny.txt` it returns `ddssaa`: right twice (the gem), down twice (through the gate), left twice (the treasure).
