xxxxxxxxxx
122
let board;
let currentPlayer;
let players;
let w; // ancho de cada celda
let h; // altura de cada celda
let colors;
function setup() {
createCanvas(400, 400);
w = width / 3;
h = height / 3;
colors = {
background: color(255, 204, 229),
x: color(66, 135, 245),
o: color(245, 66, 138),
grid: color(20, 20, 20)
};
players = ['X', 'O'];
currentPlayer = 0;
board = new Board();
}
function draw() {
background(colors.background);
board.display();
if (board.checkWinner()) {
noLoop();
currentPlayer = (currentPlayer + 1) % 2;
let resultP = createP(`${players[currentPlayer]} gana!`);
resultP.style('color', '#000');
resultP.style('font-size', '32pt');
} else if (board.isTie()) {
noLoop();
let resultP = createP('Empate!');
resultP.style('color', '#000');
resultP.style('font-size', '32pt');
}
}
function mousePressed() {
let i = floor(mouseX / w);
let j = floor(mouseY / h);
if (board.makeMove(i, j, players[currentPlayer])) {
currentPlayer = (currentPlayer + 1) % 2;
}
}
class Board {
constructor() {
this.grid = [
['', '', ''],
['', '', ''],
['', '', '']
];
}
display() {
stroke(colors.grid);
strokeWeight(4);
for (let i = 1; i < 3; i++) {
line(i * w, 0, i * w, height);
line(0, i * h, width, i * h);
}
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
let x = w * i + w / 2;
let y = h * j + h / 2;
let spot = this.grid[i][j];
textSize(32);
let r = w / 4;
if (spot == players[1]) {
noFill();
stroke(colors.o);
ellipse(x, y, r * 2);
} else if (spot == players[0]) {
stroke(colors.x);
line(x - r, y - r, x + r, y + r);
line(x + r, y - r, x - r, y + r);
}
}
}
}
makeMove(i, j, player) {
if (this.grid[i][j] == '') {
this.grid[i][j] = player;
return true;
}
return false;
}
checkWinner() {
let winner = null;
for (let i = 0; i < 3; i++) {
if (this.grid[i][0] == this.grid[i][1] && this.grid[i][1] == this.grid[i][2] && this.grid[i][0] != '') {
winner = this.grid[i][0];
}
if (this.grid[0][i] == this.grid[1][i] && this.grid[1][i] == this.grid[2][i] && this.grid[0][i] != '') {
winner = this.grid[0][i];
}
}
if (this.grid[0][0] == this.grid[1][1] && this.grid[1][1] == this.grid[2][2] && this.grid[0][0] != '') {
winner = this.grid[0][0];
}
if (this.grid[2][0] == this.grid[1][1] && this.grid[1][1] == this.grid[0][2] && this.grid[2][0] != '') {
winner = this.grid[2][0];
}
return winner;
}
isTie() {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (this.grid[i][j] == '') {
return false;
}
}
}
return !this.checkWinner();
}
}