Section 13.3 Stretch Level
Multidimensional Arrays
Objectives
Subsection 13.3.1 Overview
This is a basic grid-based game in Java where a player will move through a grid collecting coins, with the goal of reaching the exit. The player starts at the top left corner of the grid and the exit is at the bottom right corner. The player will move through the grid using the ’W’, ’A’, ’S’, and ’D’ keys.
Here is an example of what the grid can look like:
P O . . .
. . . . O
. . . . .
. . . . .
. O . . E
The player is denoted by ’P’
The coins are denoted by ’O’
The exit is denoted by ’E’
The player will move on the grid through user input, which will be handled by a Scanner
. Each time the game is run, a new grid must be created. That is, the coins must be placed at a random spot each time.
Subsection 13.3.2 Instructions
-
Building the grid with char[][] buildGrid(int width, int height)
-
Printing the grid with printGrid(char[][] grid)
-
Placing coins on the grid with placeCoins(char[][] grid, int coinCount)
-
Implementing game logic in playGame(int width, int height, int coinCount)
Call the buildGrid()
method and place the player (P) and the exit (E) in their designated spots on the grid. Ensure that you initialize variables to keep track of the player’s position
Populate the grid with coins using the placeCoins()
method
-
Use a while
loop to keep the game running until the player reaches the exit. Inside the loop, you will:
Print the grid after each move
Prompt the player to enter their next move and read the input in using a Scanner
Update the player’s position on the grid to the new coordinates and if they have moved to a coin, update their points
End the game once the player has reached the exit
Make sure to handle the case where the player tries to move out of bounds by checking if the new coordinates are within the valid range before updating the player’s position
Here is an example of what the gameplay output may look like:
P . .
O . .
. . E
Enter move (Only WASD, case sensitive):
S
Got a coin!
. . .
P . .
. . E
Enter move (Only WASD, case sensitive):
D
. . .
. P .
. . E
Enter move (Only WASD, case sensitive):
D
. . .
. . P
. . E
Enter move (Only WASD, case sensitive):
S
You won! Points: 1
You have attempted
of
activities on this page.