I am still a beginner in java and I am attempting to create a game. I just created a 20 x 20 board that I added to a 2D array of squares. But, I am confused on some syntax….I still have a hard time with writing proper conditionals and algorithms, especially.
So, what I want to do is fill in 8X8 inside squares with black, and then the outside bordering 2 columns and rows on either side a different color red.
How would I go about factoring this out?
So far, I have two for loops for the rows and columns.
I know I need some sort of if statement I am guessing….like if ([row] == 1, 2, 19, 20 (topmost and bottommost rows)…and likewise for columns
_gameSquares = new Square[GameConstants._numCol][GameConstants._numRow];
for (int col=0; col<GameConstants.numCol; col++) {
for (int row=0; row<GameConstants.numRow; row++) {
Square square;
// if (row == 1) {
// square = new Square(this, java.awt.Color.RED);
// }
// else
square = new Square(this, java.awt.Color.BLACK);
tile.setLocation(col*GameConstants.squareWidth,row*GameConstants.squareHeight);
_gameSquares[col][row] = square;
}
}
public void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
java.awt.Graphics2D brush = (java.awt.Graphics2D) g;
for (int col=0; col<GameConstants.numCol; col++) {
for (int row=0; row<GameConstants.numRow; row++) {
_gameSquares[col][row].paint(brush);
}
}
}
So you want to have the logic depending on which row or column? Lets try this in a structured way.
Remember that arrays are 0-indexed, so if you have an array with 20 slots, then they are numbered 0,1,2…18,19.
In this case you want a different color if you are on on of the first two rows or on one of the last two rows or on on of the first two columns or on one of the last two columns (long sentence).
But to maintain this you should probably break the logic into a separate method to get more readable code, this is an example:
Of course this could be further cleaned up, but it is a start and now it is easier to read the creation logic of your board.