I am creating a game that contains a Board and Pieces. The Board is basically a 2D array of Pieces. [Think smaller chess board]
One of the things that I want to accomplish is to be able to retrieve the left piece of a given.. (Also want to be able to retrieve the right, up, and down).
The easiest way to achieve this is to simply do something like:
board[i-1][j] //which will give me the piece that's to the left of board[i][j]
The problem with just doing this is that this can get ugly and there is no error checking (array out of range).
I have a feeling that there may be a better data structure to use than a 2D array.
Also, I have two implementations that work, but neither really seem like a good idea
I have the following (untested) Java classes, which is a small scale of my application:
the class Board:
public class Board
{
protected Piece[][] board;
public Board()
{
board = new Piece[7][7];
int ctr = 0;
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new Piece(i, j, ctr++);
}
}
}
public Piece PieceAt(int i, int j)
{
return board[i][j];
}
public Piece LeftOf(Piece p)
{
return PieceAt(p.verticalIndex, p.horizontalIndex - 1);
}
}
And the Piece class
public class Piece
{
int verticalIndex;
int horizontalIndex;
int value;
public Piece(int i, int j, int value)
{
this.horizontalIndex = i;
this.verticalIndex = j;
this.value = value;
}
public Piece GetLeftPiece(Board b)
{
return (this.horizontalIndex == 0 ? null : b.PieceAt(this.horizontalIndex, this.verticalIndex - 1));
}
}
The first implementation sits in Board.java
. The problem with this is that If I want to call it, it's a big ugly: b.LeftOf(b.PieceAt(3,3))
where b is of type Board.
The second implementation seems like a better idea, however since the Pieces no nothing about each other, I have to include board in the method signature.