I want to create a peg solitaire game based on a 2d array in Processing.
I've succeeded to create the board and pawns.
Now i want to get the index from a pawn by clicking on it and be able to move it around the board.
Here is what i have now to create the image above.
/**
* Gameboard array
* 0 = non playable squares
* 1 = empty square
* 2 = pawn
**/
int[][] gameboard = {
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 2, 2, 2, 0, 0, 0},
{0, 0, 0, 2, 2, 2, 0, 0, 0},
{0, 2, 2, 2, 2, 2, 2, 2, 0},
{0, 2, 2, 2, 1, 2, 2, 2, 0},
{0, 2, 2, 2, 2, 2, 2, 2, 0},
{0, 0, 0, 2, 2, 2, 0, 0, 0},
{0, 0, 0, 2, 2, 2, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
};
boolean checkIfGameboardFits() {
return AMOUNT * SIDE < SCREENWIDTH && AMOUNT * SIDE < SCREENHEIGHT;
}
void giveErrorMessage() {
println("/ Gameboard doesnt fit the screen");
}
void drawGameboard(int xPos, int yPos, int[][] gameboard) {
for (int row = 0; row < AMOUNT; row++) {
for (int column = 0; column < AMOUNT; column++) {
int xPosSquare = xPos + (column * SIDE);
int yPosSquare = yPos + (row * SIDE);
switch (gameboard[row][column]) {
case 0:
fill(#760000);
break;
case 1:
fill(#FFFFFF);
break;
case 2:
fill(#9B9999);
break;
}
rect(xPosSquare, yPosSquare, SIDE, SIDE);
}
}
}
void drawBoardPieces(int xPos, int yPos, int[][] gameboard) {
for (int row = 0; row < AMOUNT; row++) {
for (int column = 0; column < AMOUNT; column++) {
if (gameboard[row][column] == 2) {
fill(#FFFFFF);
circle(xPos + (column * SIDE) + PAWNMARGE, yPos + (row * SIDE) + PAWNMARGE, PAWNSIZE);
}
}
}
}
void startGame() {
background(255);
gameState = 1;
if (checkIfGameboardFits()) {
int startXposGameboard = (width - (AMOUNT * SIDE)) /2;
int startYposGameboard = (height - (AMOUNT * SIDE)) /2;
drawGameboard(startXposGameboard, startYposGameboard, gameboard);
drawBoardPieces(startXposGameboard, startYposGameboard, gameboard);
} else {
giveErrorMessage();
}
}
And the rest of the code.
final int SIDE = 60;
final int AMOUNT = 9;
final int SCREENWIDTH = 800;
final int SCREENHEIGHT = 800;
final int PAWNSIZE = 40;
final int PAWNMARGE = 30;
int gameState;
void settings() {
size(SCREENWIDTH, SCREENHEIGHT);
}
void setup() {
startGame();
}
void draw() {
}
void mousePressed() {
// get index and value from clicked square
}
Any and all tips, examples or thinking processes would be welcome.
You can determine the index by dividing the relative mouse position by the size of a tile:
void mousePressed() {
int column = (mouseX - xPos) / SIDE;
int row = (mouseY - yPos) / SIDE;
if (column >= 0 && column < AMOUNT && row >= 0 && row < AMOUNT) {
// mouse is on the board at column and row
// ...
}
}