hello everyone,

I am working on an assignment for my cs class. It is basically a board game with 20 levels.
i have a question about why this code in my program is not working...hopefully what I am posting makes any sense because what I am writing is already long...and psoting anymore might piss you all off...

i declared a 2d array:

public static int theBoardSize = 4;
Piece [][] tile = new Piece [theBoardSize][theBoardSize]

The Piece creates and displays a square of a particular size, color, and at an x & y position. I use 2 for loops to create the squares and each are stored in a single array element. the colors are randomly chosen by a random number generator.

theBoardSize is needed to increase the size of the board. So a 4X4 board is displayed for level 1 when the game begins, and when the user wins level 1, a 5x5 board is displayed an so on....until a 24x24 board is displayed.

If you are confused, here is an image if what the user would see when level 1 begins:

The game begins with tile[0][0] (in the image, it would be the blue square in the upper-left corner). The user types in a color and the computers job is to check if any surrounding squares (up, left, down and right. No diagonals...) are of that color. So if the user typed in the color black or green, no changes would be made to the board because there is no black square or green square surrounding tile[0][0]. If the user typed in red, the computer would notice that tile[0][1] square is red. tile[0][0] would also change to red. Here is an image showing the result.

The point of the game is to make the all the squares on the board the same color.

So far I have implemented this in my program.

In my Piece class, I have a portion of code:

The point of this method is for each square, determine the surrounding squares and store them.

private Piece theLeftSquare;         // Reference to the left neighbor on the board.
    private Piece theRightSquare;       // Reference to the right neighbor on the board.
    private Piece theTopSquare;         // Reference to the top neighbor on the board.
    private Piece theBottomSquare;    // Reference to the bottom neighbore of the board.

    /**
     * Sets the left, upper, bottom, and right neighbor Pieces.
     */
    
    void setTheNeighbors ( Piece left, Piece top, Piece right, Piece bottom )
    {
        theLeftSquare = left;   
        theTopSquare = top;         
        theRightSquare = right;      
        theBottomSquare = bottom;
    }

I also have a PlayGame class with the following code:

public void setNeighbors()
{
for ( int row = 0; row < boardSize; row++ )
{
     for ( int column = 0; column < boardSize; column++ )
     {
       tile[row][column].setTheNeighbors( tile[row][column - 1],  tile[row - 1][column],
                                                           tile[row][column+1],  tile[row + 1][column] ); 
                                                     
      }
 }
}

However, when I run my code, I get an array out of bound exception. I understand that when row = 0 and column = 0, that tile[0][-1] does not exist. This is also the case for any square on the edge of the board.

I want the computer to notice that if it is checking for a square that is outside of the board range, then the value of the neighbor should be null.
So for example, using the above method and tile[0][0]:

tile[0][0].setTheNeighbors( tile[0][-1],  tile[-1][0], tile[0][1], tile[1][0] );

would translate to:

tile[0][0].setTheNeighbors( null,  null, tile[0][1], tile[1][0] );

I don't know if that makes any sense at all...or if I should make a seperate method that checks to see if the neighbor is outside the board range?

I'm not sure how to get around this problem...

if (SecondIndex == -1)
//call method with null params here
else
//call method with normal params here

So you would just do some calculations to figure out if the index is not a valid index. You could do this anywhere you want - I'd recommend a separate method, it keeps your code clean & readable. Then, you'd call the method setTheNeighbors based on what your method returned.

Hello Vualta. I show You 3 points.
1.Some abstracts about a piece properties,
2.Possible first solution based on array[][] of pieces,
3.Possible second solution based on own class without use of array[][] - with own DATA structue.

1.
All of piece have specialy set of geometry properties.
Piece can be in corner, on rand or inside the square array of pieces.
I use symbols:
L - left
R - right
T - top
B -bottom
and their combinatins.

For [2][2] we have:
TL,TR
BL,BR
(there are 4 unique symbols)

For [3][3] we have:
TL,T,TR
L, I, R
BL,B,BR
(there are 9 unique symbols)

if we we grow the array to [8][8] we use also 9 unique symbols.

Other property: how many neighbours particulary piece has?
I listed this:
I 4,
T,B,L,R 3,
TL,TR,BL,BR 2.

Simple we can write this as...

public enum PieceType {

    TL, //TopLeft
    T,  //Top
    TR, //TopRight
    L,  //Left
    I,  //Inside
    R,  //Right
    BL, //BottomLeft
    B,  //Bottom
    BR  //BottomRight
}

Piece we can describe as...

import java.awt.Color;

public class Piece {

    private Color color;
    private PieceType pieceType;
    // indexes
    private int x;
    private int y;

    public Piece(PieceType pieceType0, Color color0, int x0, int y0) {
        pieceType = pieceType0;
        color = color0;
        x = x0;
        y = y0;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getXPosition(int pieceSize) {
        return pieceSize * x;
    }
    // same for y ... 
    /**
     * 
     * @param color0 set new color
     */
    public void setColor(Color color0) {
        color = color0;
    }

    public Color getColor() {
        return color;
    }

    public PieceType getPieceType() {
        return pieceType;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Piece:");
        sb.append("pieceType=" + pieceType);
        sb.append(",x=" + x);
        sb.append(",y=" + y);
        sb.append(",color=" + color);
        return sb.toString();
    }
}

2.

import java.awt.Color;

public class GameExample1 {

    public static int theBoardSize;
    public static Piece[][] pieces;

    public GameExample1(int theBoardSize0) {
        theBoardSize = theBoardSize0;
        pieces = new Piece[theBoardSize][theBoardSize];
        fillArray2D();
        // check Neighbors for test
        Piece anyPiece = pieces[0][0];
        System.out.println("checked piece--> " + anyPiece);
        Piece[] someNeighbors = getNeighbors(anyPiece);
        System.out.println("checked neighbors--> ");
        for (int i = 0; i < someNeighbors.length; i++) {
            System.out.println(someNeighbors[i]);
        }
    }

    /**
     * 
     */
    public void fillArray2D() {
        //to make code a bit clear
        int last = theBoardSize - 1;

        //piece[x][y]
        //piece[column][row]
        //1.corners Tl,TR,BL,BR
        // choose own colors to proper assign (control)
        pieces[0][0] = new Piece(PieceType.TL, Color.RED, 0, 0);
        pieces[last][0] = new Piece(PieceType.TR, Color.GREEN, last, 0);
        pieces[0][last] = new Piece(PieceType.BL, Color.BLUE, 0, last);
        pieces[last][last] = new Piece(PieceType.BR, Color.BLACK, last, last);
        //2. rands T,B,L,R
        for (int i = 1; i < last; i++) {
            pieces[i][0] = new Piece(PieceType.T, Color.CYAN, i, 0);
        }
        for (int i = 1; i < last; i++) {
            pieces[i][last] = new Piece(PieceType.B, new Color(128, 128, 128), i, last);
        }
        for (int i = 1; i < last; i++) {
            pieces[0][i] = new Piece(PieceType.L, new Color(28, 28, 28), 0, i);
        }
        for (int i = 1; i < last; i++) {
            pieces[last][i] = new Piece(PieceType.R, Color.MAGENTA, last, i);
        }
    //3.inside I
    //... your role write this
    }

    /**
     * 
     * @param piece 
     * @return
     */
    public Piece[] getNeighbors(Piece piece) {
        Piece[] pie = null;
        switch (piece.getPieceType()) {
            case TL:
                pie = new Piece[2];
                pie[0] = pieces[piece.getX() + 1][piece.getY()];
                pie[1] = pieces[piece.getX()][piece.getY() + 1];
                return pie; //TopLeft
            case T:
                pie = new Piece[3];
//...
                return pie;  //Top
            case TR:
//...
                return pie; //TopRight
            case L:
//...
                return pie;  //Left
            case I:
                pie = new Piece[4];
//...
                return pie;  //Inside
            case R:
//...
                return pie; //Right
            case BL:
//...
                return pie; //BottomLeft
            case B:
//...
                return pie; //Bottom
            case BR:
//...
                return pie;  //BottomRight
            default:
                System.out.println("err...");
                return pie;
        }

    }

    public static void main(String[] args) {
        new GameExample1(4);
    }
}

3.
Brief

import java.awt.Color;

public class Piece2 extends Piece {

    Piece theLeftSquare;        // Reference to the left neighbor on the board.
    Piece theRightSquare;       // Reference to the right neighbor on the board.
    Piece theTopSquare;         // Reference to the top neighbor on the board.
    Piece theBottomSquare;      // Reference to the bottom neighbore of the board.

    public Piece2(PieceType pieceType0, Color color0, int x0, int y0) {
        super(pieceType0, color0, x0, y0);
    }

    public Piece2(PieceType pieceType0, Color color0, int x0, int y0, Piece theLeftSquare0, Piece theRightSquare0, Piece theTopSquare0, Piece theBottomSquare0) {
        super(pieceType0, color0, x0, y0);
        setNeighbors(theLeftSquare0, theRightSquare0, theTopSquare0, theBottomSquare0);
    }

    public void setNeighbors(Piece theLeftSquare0, Piece theRightSquare0, Piece theTopSquare0, Piece theBottomSquare0) {
        theLeftSquare = theLeftSquare0;
        theRightSquare = theRightSquare0;
        theTopSquare = theTopSquare0;
        theBottomSquare = theBottomSquare0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());
        sb.append("theLeftSquare--> ");
        sb.append(theLeftSquare.toString());
        sb.append("theRightSquare--> ");
        sb.append(theRightSquare.toString());
        sb.append("theTopSquare--> ");
        sb.append(theTopSquare.toString());
        sb.append("theBottomSquare--> ");
        sb.append(theBottomSquare.toString());
        return sb.toString();
    }
}

How own DATA structue of Piece collection should be looks like (roof?), how initialize this?
May be rest the array[][]?
quuba....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.