YouSof YouSof - 10 months ago 60
Java Question

Java board game

Basically I'm creating a board game in java and have managed to create cells, using arrays, to look like a 10x10 grid. Now I've numbered them they go from left to right top to bottom (as pic)

I'm creating a game similar to a snakes and ladders game but having its own twist.

Question is: How to create a zigzag board similar to a snakes & ladder board?

That's how it currently looks: enter image description here

Code below is of whats required to create arrays and print them and number them.

Object named Game:

private Cell[][] cell = new Cell[10][10];

public Game(String nameIt)
JPanel x = new JPanel();

x.setLayout(new GridLayout(10, 10, 2, 2));
for (int r = 0; ir< 10; r++)
for (int c= 0; c < 10; c++)

x.add(cell[r][c] = new Cell(r, c, this));


Object named cell:

private int row;
private int col;
private int cellNum;
static int count = 0;

public Cell(int row, int column, Game guy)
{ = row;
this.col = column;
this.parent = guy;

count = count+1;
cellNum = count;

setBorder(new LineBorder(Color.BLUE, 1)); // Set cell's border

protected void paintComponent(Graphics p)

p.drawString(String.valueOf(" " + cellNo), 24, 24);



Ok so I won't write the exact code for you, but I'll show you an example of how to do it with a regular 2D array. I only have a C++ compiler available right now, but it should be clear enough:

So basically you need to cycle through rows from end to start. That's why the first, outer loop you're going from 9 to 0. This will start at bottom row and finish at the top row, thus reversing.

for (int i = 9; i >= 0; i--) {

    // now the trick to making a "zig-zag" is to alternate between two ways
    // of printing out each row. if i is even, you print out from right to left

    if (i % 2)
        for (int j = 9; j >= 0; j--)
            cout << numbers[i][j] << "\t";

    // and if i is odd, you print it out from left to right
        for (int j = 0; j < 10; j++)
            cout << numbers[i][j] << "\t";

    cout << endl;


Result: enter image description here