AQA · GCSE · Computer Science · Higher
Programming a sliding-puzzle move loop
The sliding puzzle uses a 3 x 3 board with eight numbered tiles and one blank space. A tile can move into the blank space only when it is next to that space.
| Subroutine | Purpose |
|---|---|
| solved() | Returns true if the puzzle has been solved. Otherwise returns false. |
| checkSpace(row, column) | Returns true if there is a blank space next to the tile on the board in position (row, column). Otherwise returns false. |
| Subroutine | Purpose |
|---|---|
| move(row, column) | Moves the tile in position (row, column) to the blank space if the blank space is next to that tile. If the position is not next to the blank space, no move is made. |
Write a C# program to help the user solve the puzzle. Input the row and column of a tile; use checkSpace to determine whether it is next to the blank; call move if valid or output Invalid move otherwise; repeat until solved() is true. You must use the subroutines in Table 5 and Table 6. Use meaningful variable name(s) and C# syntax.
Write your answer first. You can study the marking guidance whenever you need it.
Study the marking See what earns credit and compare it with a full-mark answer.
Marking points
- 1 Uses an indefinite loop controlled by the puzzle's solved state.
- 2 Uses selection to branch on whether the tile is next to the blank space.
- 3 Reads and stores both row and column.
- 4 Calls solved() and checkSpace(row, column) in the correct logical roles.
- 5 Calls move with the entered row and column only on a valid-move path.
- 6 Outputs Invalid move for an invalid choice and repeats input only while unsolved.
Full-mark answer
while (!solved()) { int row = Convert.ToInt32(Console.ReadLine()); int column = Convert.ToInt32(Console.ReadLine()); if (checkSpace(row, column)) { move(row, column); } else { Console.WriteLine("Invalid move"); } }
Why this answer loses marks
I read the coordinates and moved the tile before checking whether a blank space was adjacent.
The adjacency check must control the move so an invalid choice follows the retry pathway instead.