2021-10-05 11:48:15 +00:00
|
|
|
[< Back](../README.md)
|
2021-10-05 11:44:51 +00:00
|
|
|
|
2021-10-05 11:00:57 +00:00
|
|
|
# Exercise: Create an isWall function
|
2021-09-29 09:25:43 +00:00
|
|
|
|
|
|
|
In this exercise we will write some helper functions for the game board.
|
|
|
|
|
2021-10-05 08:37:48 +00:00
|
|
|
The file [`Board.cpp`](../../../lib/Board.cpp) defines functions to manipulate the game Board, for example finding where
|
2021-10-04 11:27:29 +00:00
|
|
|
the walls and the portals are.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-05 12:29:27 +00:00
|
|
|
## Background: Board.cpp
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
The Board itself is represented in memory as a 2 dimensional array. A cell in this grid can be for example walkable, a
|
|
|
|
wall, a pellet, a super pellet or a portal.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
`Cell` is an enum representing the different types of cells.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
`isWalkableForGhost` and `isWalkableForPacMan` are two functions which need to check whether a cell is a wall.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
|
|
|
```cpp
|
2021-09-29 12:18:06 +00:00
|
|
|
bool isWalkableForPacMan(GridPosition point) {
|
2021-10-04 11:27:29 +00:00
|
|
|
return cellAtPosition(point) != Cell::wall && cellAtPosition(point) != Cell::pen;
|
2021-09-29 09:25:43 +00:00
|
|
|
}
|
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
bool isWalkableForGhost(GridPosition point, GridPosition origin, bool isEyes) {
|
|
|
|
const Cell cell = cellAtPosition(point);
|
|
|
|
if (cell == Cell::wall)
|
|
|
|
return false;
|
|
|
|
return isEyes || isInPen(origin) || !isInPen(point);
|
|
|
|
}
|
|
|
|
```
|
2021-09-29 09:25:43 +00:00
|
|
|
|
|
|
|
## Exercise
|
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
Let's add a simple helper function.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:01:29 +00:00
|
|
|
You might notice that `isWalkableForPacMan` and `isWalkableForGhost` both call `cellAtPosition` with a `GridPosition`
|
2021-10-04 11:27:29 +00:00
|
|
|
variable and check if it is a wall. Maybe we can lift that check into a separate function (call it `isWall`) to avoid
|
|
|
|
repeating ourselves?
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
1. Create a function called `isWall` between `cellAtPosition` and `isWalkableForPacMan` that returns true if
|
|
|
|
the `GridPosition` parameter is a wall. A function needs to be defined before it is called, so the order of functions
|
|
|
|
is important. Try to define `isWall` after ``isWalkableForPacMan` or before `cellAtPosition`. It does not compile
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-09-29 12:16:12 +00:00
|
|
|
2. Replace the checks within `isWalkableForPacMan` and `isWalkableForGhost` with your new function.
|
2021-09-29 09:25:43 +00:00
|
|
|
|
2021-10-04 11:27:29 +00:00
|
|
|
3. Check to see that the game still works as expected.
|