pacman/exercises/small/131-functions-and-parameters.md

45 lines
1.8 KiB
Markdown
Raw Normal View History

2021-10-04 11:27:29 +00:00
# 131. Functions and Parameter Passing
In this exercise we will write some helper functions for the game board.
2021-10-04 11:27:29 +00:00
The file [`Board.cpp`](../../lib/Board.cpp) defines functions to manipulate the game Board, for example finding where
the walls and the portals are.
2021-10-04 11:27:29 +00:00
## Board.cpp
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-10-04 11:27:29 +00:00
`Cell` is an enum representing the different types of cells.
2021-10-04 11:27:29 +00:00
`isWalkableForGhost` and `isWalkableForPacMan` are two functions which need to check whether a cell is a wall.
```cpp
bool isWalkableForPacMan(GridPosition point) {
2021-10-04 11:27:29 +00:00
return cellAtPosition(point) != Cell::wall && cellAtPosition(point) != Cell::pen;
}
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);
}
```
## Exercise
2021-10-04 11:27:29 +00:00
Let's add a simple helper function.
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-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 12:16:12 +00:00
2. Replace the checks within `isWalkableForPacMan` and `isWalkableForGhost` with your new function.
2021-10-04 11:27:29 +00:00
3. Check to see that the game still works as expected.