Question Constellation Sign up for free

AQA · GCSE · Computer Science · Higher

Programming array-based movement validation

Q15.0 8 marks

A programmer is writing a game. The game uses a row of cells represented as an array. Figure 20 shows an example.

Figure 20
01234567
XX

Figure 21 describes how the game is to be played.

Figure 21
The player starts at position 0 in a row of cells.
The aim of the game is for the player to reach the end of the row.
At each turn the player must enter either 1 or 2: entering 1 increases the player's position by 1; entering 2 increases the player's position by 2.
If the player's position goes beyond the end of the row or contains an X, the message Bad move is displayed and the player goes back to position 0.
These steps are repeated until the player reaches the end of the row.
If the player reaches the end of the row the game is finished.

In the example in Figure 20, the player starts at position 0. Inputs 1 then 2 attempt to reach position 3, which contains X, so Bad move is displayed and the player returns to 0. Inputs 2, 2, 1 and 2 then reach positions 2, 4, 5 and 7, finishing the game.

Figure 22 shows part of a C# program that will be used for the game.

Figure 22
int pos = 0;
int lastPos = row.Length - 1;
while (pos < lastPos)
{

pos is a variable that contains the player's current position.

Extend the program from Figure 22 so that the game works as described in Figure 21.

  • there is an array called row
  • the number of X characters in row can vary
  • the position of the X characters in row can vary
  • the X characters have already been added to the array called row
  • the row array can be of any length

You should use meaningful variable name(s) and C# syntax in your answer.

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. 1 Uses selection to display Bad move on an invalid destination.
  2. 2 Uses suitable nested, multiple-condition or multiple selection logic.
  3. 3 Inputs the move inside the supplied while loop.
  4. 4 Checks that the move is either 1 or 2.
  5. 5 Adds the accepted move to pos exactly once.
  6. 6 Resets pos to 0 when the destination is beyond the end.
  7. 7 Checks the destination for X and resets pos to 0 when X is present.
  8. 8 Orders or structures the checks so row is never accessed with an out-of-range index.

Full-mark answer

int move = Convert.ToInt32(Console.ReadLine()); if (move == 1 || move == 2) { pos = pos + move; if (pos > lastPos) { pos = 0; Console.WriteLine("Bad move"); } else if (row[pos] == "X") { pos = 0; Console.WriteLine("Bad move"); } }

Why this answer loses marks

I updated the position and checked the destination before checking whether its index was still inside the array.

Accessing the destination first can use an out-of-range index, so the bounds test must happen before the array lookup.