এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
Primary & Middle School Computer Science · শ্রেণি 1–9
37Project: A Game on a Grid
The last project of this book is a game: a maze in the terminal, drawn with characters, where the player hunts for a treasure. It uses everything the grade has built: grids, dictionaries, text files, functions, 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, so that new levels need no new code.
You already know
A grid is a list of lists, and grid[r][c] is the cell in row r, column c (Chapter 33). A dictionary keeps values under keys (Chapter 26); a text file is read with open (Chapter 27). A project grows in versions, each one tested (Chapter 24, Chapter 30).
37.1 What must it do?
The paragraph above, turned into checks small enough to test:
- A level 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,gfor a gem and=for the gate. - A level with no S, two S’s, no T or rows of different lengths is refused with a message.
- The player cannot enter a wall, nor the gate while a gem is left.
- Stepping on a gem collects it; the last gem opens the gate.
- Each move costs one move; a blocked move costs nothing.
- The game ends with a win on T, or a loss when no moves are left.
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 of characters, one list per row, so that a cell can be changed when a gem is collected; the rest goes into a dictionary, with the grid itself:
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"])
$ 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
repr prints a 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.
"grid" is the list of rows; the S has become floor.37.3 Reading a maze file
Version 2 reads the level from a file and checks it before using it. A level that breaks a rule gets a message saying what is wrong; a function that returns an empty string when all is well is easy to test.
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()
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)
$ 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
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 is line 1 of the file, after the number of moves.
37.4 Drawing as text
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")))
$ python maze_v3.py
#########
#@..#.#T#
#.#.#.#=#
#g#...#.#
#.###g#.#
#.......#
#########
gems left: 2 moves left: 20
37.5 The rules as functions
Each rule becomes a small 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.
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"
The maze is surrounded by walls, so can_move never looks outside the grid: a level must keep its border (Exercise 37.4 shows what happens otherwise). Before a game loop exists, a fixed sequence of moves tries the rules:
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)
$ 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
The tests of the chapter check each rule on hand-made grids 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
Version 5 adds play, the game loop. The program now waits for the player at each turn and reacts to the key typed.
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")
To test a game without a player at the keyboard, the moves come from a file of keys, one per line: the output 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!
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.
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 can find out by trying every sequence of moves. With 4 possible moves, there are 4 sequences of one move, of two moves, and of moves: the count is multiplied by 4 at each step, as the count of binary numbers is multiplied by 2 at each new bit (Chapter 25).
To list them, the program counts from 0 to 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:
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")
$ 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
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, 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
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
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
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.
from maze_v5 import MOVES, play
MOVES["x"] = [0, 0] # x: stay in place, and spend a move
if __name__ == "__main__":
play("level1.txt")
Exercise 37.4 ★
A maze without a border of walls is checked by this function. What does it print? Explain each answer, then fix the function.
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"))
Solution
Solution of Exercise 37.4.
It prints True True False. From the top left corner, a reads column , 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 , 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:
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"))
It prints False False False.
Exercise 37.5 ★★
Write a function replay(text, sequence) that plays a string of moves on a level and returns the number of moves used to win, or if the sequence does not win. How many moves did the winning game of Output 37.5 use?
Solution
Solution of Exercise 37.5.
The same replay as in wins, counting the moves that are made:
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"))
The game of Output 37.5 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.
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] = "."
Solution
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.
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
Solution of Exercise 37.7.
After the usual move, look for the other o and put the player there:
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]
Exercise 37.8 ★★
How many sequences of 6 moves are there? Of 10 moves? If a computer replays a million sequences per second, how long do the sequences of 15 moves take?
Solution
Solution of Exercise 37.8.
and . Sequences of 15 moves: , 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 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
Solution of Exercise 37.9.
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))
It prints tiny.txt: True and level2.txt: False. The function stops at the first winning sequence; it reuses all_sequences and wins from Listing 37.8.
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
Solution of Exercise 37.10.
The test abs(r - state["row"]) <= sight keeps the rows near the player, and the same for the columns:
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)
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 ) moves.
Solution
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 floor cells, it visits at most cells, so it makes at most moves. (With gems and a gate, the cut may skip a gem, and the argument no longer works.)
Exercise 37.12 ★★★
Write a 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
Solution of Exercise 37.12.
Trying the lengths in order means the first winning sequence found is a shortest one:
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))
For tiny.txt it returns ddssaa: right twice (the gem), down twice (through the gate), left twice (the treasure).