// a 3x3 array of characters represents the board
char[][] board = new char[3][3];
// how big is each box, and where did you click
int boxSize, clickX, clickY;
// is it X's turn (true) or O's turn (false)
boolean turnX = true;
int backgroundColor = 155;
int strokeColor = 0;
void setup() {
size(300,300);
boxSize = width/3;
strokeWeight(2.0);
stroke(strokeColor);
background(backgroundColor);
resetBoard();
}
// set all the squares to '?' (no player has used them)
void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '?';
}
}
}
// draw an X
void drawX(int x, int y) {
line(x - boxSize/4, y - boxSize/4, x + boxSize/4, y + boxSize/4);
line(x - boxSize/4, y + boxSize/4, x + boxSize/4, y - boxSize/4);
}
// draw an O
void drawO(int x, int y) {
fill(155);
ellipse(x, y, boxSize/2, boxSize/2);
}
void drawBoard() {
// draw the grid lines
line(boxSize, 0, boxSize, height);
line(2*boxSize, 0, 2*boxSize, height);
line(0, boxSize, width, boxSize);
line(0, 2*boxSize, width, 2*boxSize);
// populate the board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 'X') {
drawX(boxSize*i + boxSize/2, boxSize*j + boxSize/2);
}
else if (board[i][j] == 'O') {
drawO(boxSize*i + boxSize/2, boxSize*j + boxSize/2);
}
}
}
}
// when a square is clicked, save the mouse coords and update
void mousePressed() {
clickX = mouseX;
clickY = mouseY;
updateBoard();
}
// update the board[][] array with the clicked square
void updateBoard() {
int i, j;
// which 3rd of the board did the X coord land on
if (clickX < boxSize) i = 0;
else if (clickX < 2*boxSize) i = 1;
else if (clickX < width) i = 2;
else i = -1;
// which 3rd of the board did the Y coord land on
if (clickY < boxSize) j = 0;
else if (clickY < 2*boxSize) j = 1;
else if (clickY < width) j = 2;
else j = -1;
// if the click was inside the grid and the space hasn't been used
if (i >= 0 && j >= 0 & board[i][j] == '?') {
// set the square based on whose turn it is
if (turnX) {
board[i][j] = 'X';
}
else {
board[i][j] = 'O';
}
}
}
void draw() {
drawBoard();
}
Comments