Complete the Droppy practice problem before reviewing the solution.
Review the Droppy solution with AP CS Tutor Brandon Horn.
Part (a) handleCaughtItem
method
private void handleCaughtItem(String item)
{
int space = item.indexOf(" ");
String description = item.substring(0, space);
System.out.println("Player caught " + description);
String type = item.substring(space + 1);
if(type.equals("food"))
turnsLeft += 10;
else if(type.equals("prize"))
playerPoints++;
else
playerPoints--;
}
This method requires String
manipulation similar to that presented in the AP CS Magpie Lab. The item’s description and type are separated by a single space. indexOf
can be used to find the position of the space. substring
can be used to extract the description and the type. The types must be compared using the equals
method rather than ==
.
Part (b) shiftAndCatch
method
public void shiftAndCatch()
{
int lastRow = board.length - 1;
if(board[lastRow][playerCol] != null)
handleCaughtItem(board[lastRow][playerCol]);
for(int row = lastRow; row > 0; row--)
{
for(int col = 0; col < board[row].length; col++)
{
board[row][col] = board[row - 1][col];
board[row - 1][col] = null;
}
}
}
Determining whether an item is caught by the player can be accomplished with a single conditional statement. If an item is caught the handleCaughtItem
method must be called to update the game state. Note that repeating the code from handleCaughtItem
, instead of calling the method, would not receive credit.
Shifting the items requires a moderately complex traversal of a 2D array similar to that presented in the AP CS Pictures Lab. The loop must start at the bottom of the array and progress toward the top. Each iteration of the loop must access 2 different array positions (from adjacent rows).
The solution above uses row
to represent the destination. (row
could alternatively be used to represent the source.) The outer loop bounds are critical. The loop must skip the first row to avoid an ArrayIndexOutOfBoundsException
. (If row
represented the source the loop would skip the last row.) The inner loop simply visits each column.
Part (b) shiftAndCatch
method (alternate solution)
public void shiftAndCatch()
{
int lastRow = board.length - 1;
if(board[lastRow][playerCol] != null)
handleCaughtItem(board[lastRow][playerCol]);
for(int row = lastRow; row > 0; row--)
board[row] = board[row - 1];
board[0] = new String[board[0].length];
}
A 2D array is an array of 1D arrays. Each row in board
can be treated as a 1D array. The last line ensures that the first row contains all null
values.
Additional 2D array resources
- Intro to 2D arrays
- 2D array exercises
- Mazer FR
- Flight FR
- MatrixManipulator exercise
- DeterminantFinder exercise