Natchanon
Natchanon

Reputation: 21

How to check if an index is already occupied?

I'm developing a board game program using 2D array. Because in board games you can place your stone into a cell that already has a stone in it. Is there a way in Java to check if an index is already occupied? For example,

int[][] board = new int[5][5];

I want to check if the user or the program already chose cell [1][3], and use a while loop to tell the user to choose another cell that hasn't been chosen?

Upvotes: 2

Views: 1128

Answers (4)

Dawid Pura
Dawid Pura

Reputation: 1029

You should define a cell that is not used, for example:

boolean[][] initMap(int x, int y) {
   boolean[][] result = new boolean[x][y];
}

boolean isOccupied(int[][] map, int x, int y) {
  return map[x][y]; 
}

boolean putARock(boolean[][] map, int x, int y) {
   if(isOccupied(map)) {
      map[x][y] = true;
      return true;
   } else {
      return false;
   } 
}

/* somewhere in main or GUI code */

boolean[][] map = initMap(x,y);

boolean isPuttingDone = false;

do {
  isPuttingDone = putARock(map, getXFromKeyboard(), getYFromKeyboard());
} while (!isPuttingDone);

You have to write a right methods to get X and Y from user input (or you can do it differently). This is not really OO code though.

Upvotes: 0

Egg Vans
Egg Vans

Reputation: 944

Java initialises arrays of objects to null, ints to 0, floats to 0.0 and booleans to false, so you could just check if the index equals 0. i.e

if(board[x][y]==0){
//set piece
}else{
//handle already occupied case
}

Upvotes: 1

Trinimon
Trinimon

Reputation: 13957

Have a look at this little Java Sample Chess Applet. It uses value 0 for empty squares and 1 for border fields. This simplifies the out of border check as well. The board has a size of 10x12 fields.

Other values represent roughly the material value - positive values for white, negative for black. So the balance is 0 if both opponents have the same pieces.

Upvotes: 1

Zanidd
Zanidd

Reputation: 133

I would create an object with a boolean attribute and create an Array with it. example:

public class myField{
    private bool chosen = false;
    private ... 
    ....
}

Usage:

public class main{
    private myField[][] board = new myField[5][5];
    ....
}

Checking if occupied:

if(board[1][3].chosen == true)
{
    //doSomething
}

Upvotes: 1

Related Questions