Kevin Sanchez
Kevin Sanchez

Reputation: 53

Making a player move on 2D array game grid

I am creating a game using a 10x10 2D array. The player starts at the top left hand corner indicated as "P" and the objective is to get the player to avoid obstacles to get to the treasure indicated as "T" located in the lower right corner.

How would I go about making the player move about the grid using commands Up/Down/Left/Right?

Would I use a for loop to count through the elements in the array to designate the move?

Here is what I have so far:

import java.util.Scanner;
import java.util.Random;

public class Adventure {

public static void main(String[] args) {
    char grid[][]= new char[10][10];
    Scanner move = new Scanner(System.in);
    System.out.println("Here is the current game board:");
    System.out.println("-------------------------------");

    for(int i=0; i<grid.length; i++) {          
        for(int j=0; j<grid.length; j++) {
            double random = Math.random();
            if(random <=.05) {
                grid[i][j]='*';
            }
            else if(random > .06 && random <= .15) {
                grid[i][j]='X';
            }
            else {
                grid[i][j]='.';
            }
            grid[0][0]='P';
            grid[9][9]='T';
            System.out.print(grid[i][j]);
        }
        System.out.println("");         
    }           
        System.out.print("Enter your move (U/D/L/R)>");
}
}

Upvotes: 4

Views: 27934

Answers (3)

ggrigery
ggrigery

Reputation: 411

All of the above answers are great. Here are a few suggestions I would make:

Instead of a char two-dimensional array, I would make a custom object, such as Space, and define a two-dimensional array of Spaces (eg, Space[][]). There are a few reasons for this:

  1. You can define a space in a variety of ways (rather than just 1 character). For example, Space[i][j].hasTreasure() can return a boolean to let you know whether or not you found the treasure.
  2. If you want to add functionality later, its as easy as adding an attribute to your Space class. Again, you are not limited to one character here.

More to your question of movement, I would also recommend a few things. Similar to redneckjedi's suggestion of a CheckIfMoveIsValid() method, I would pass the grid and move direction as parameters and return a boolean. To ensure that you do not end up with ArrayIndexOutOfBounds issues, I would also suggest adding a row/column of walls on each side. I would widen the grid out to 12x12 and put a strip of obstacle-type blocks around the outside. This will ensure that you cannot step outside of the grid as hitting a wall will always return 'false' on a valid move.

Upvotes: 0

David Merriman
David Merriman

Reputation: 6086

Looks like you're using row-major ordering, judging from the way your board prints out. Based on that, here's what you'll need to do:

  1. First, you need to store the player's position somewhere. Right now it's hardcoded to 0,0.
  2. Second, you need to read in the player's move. That will have to happen in a loop, where you get a move, check if the move is allowed, perform the move, and display the results.
  3. Third, you need to be able to calculate the new position based on the move. Up means row -= 1. Right means column += 1. Etc.
  4. Given the new coordinates, you need to make sure the move is valid. At the very least, you have to stop them from walking off the board, but you may also prevent them from entering a square with an obstacle, etc.
  5. Once you know that the move is valid, you have to update the variables you're storing the current coordinates in.
  6. At the end of the loop, you'll need to redraw the board.

That's the basic gist of it. Right now you are doing everything in main(), and that's okay, but if it were me I would start to split things out into separate methods, like InitializeBoard(), GetNextMove(), CheckIfMoveIsValid(int r, int c), and so on. That way, main() becomes a high-level view of your game loop, and the guts of the different operations are compartmentalized and more easy to deal with. This will require storing off things like your game board into class variables rather than local variables, which should actually make things like obstacle detection easier than it would be currently.

Upvotes: 2

yurib
yurib

Reputation: 8147

you should keep track of the current position of the player and just update those variables. initial values would be (0,0) as you said.

int px = 0;
int py = 0;

when a move is made, update the variables accordingly:

grid[px][py] = <empty cell>;
switch (move) {
  case 'u': py += 1; break;
  case 'r': px += 1; break;
  ...
}
grid[px][py] = 'P';

of course you shouldn't just updated the values "blindly", you should insert some validation logic to follow the rules of the game:

if (grid[px][py] != <obstacle> )
   // update player coordinates...

Upvotes: 2

Related Questions