xxxxxxxxxx
148
// Referencing The Coding Train/ Daniel Shiffman's Product on Tic Tac Toe
// Removing the Minimax Algorithm
// https://thecodingtrain.com/CodingChallenges/154-tic-tac-toe-minimax.html
// https://youtu.be/I64-UTORVfU
// https://editor.p5js.org/codingtrain/sketches/0zyUhZdJD
let board = [
['', '', ''],
['', '', ''],
['', '', '']
];
let ai = 'AI';
let human = 'Justin';
let w, h;
let currentPlayer = human;
let using = [];
let players = ['0', '1'];
let p;
function setup() {
createCanvas(400, 400);
firstTurn();
w = width / 3;
h = height / 3;
p = random(players);
}
function equals3(a, b, c) {
return (a == b && b == c && a != '');
}
function checkWinner() {
let winner = null
for (let i = 0; i < 3; i++) {
if (equals3(board[i][0], board[i][1], board[i][2])) {
winner = board[i][0];
}
}
for (let i = 0; i < 3; i++) {
if (equals3(board[0][i], board[1][i], board[2][i])) {
winner = board[0][i];
}
}
if (equals3(board[0][0], board[1][1], board[2][2])) {
winner = board[0][0];
}
if (equals3(board[2][0], board[1][1], board[0][2])) {
winner = board[2][0];
}
let openSpots = 0;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == '') {
openSpots++;
}
}
}
if (winner == null && openSpots == 0) {
return 'tie';
} else {
return winner;
}
}
function firstTurn() {
let available = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == '') {
available.push({
i,
j
});
}
}
}
let move = random(available);
board[move.i][move.j] = ai;
currentPlayer = human;
}
function mousePressed() {
if (currentPlayer == human) {
let i = floor(mouseX / w);
let j = floor(mouseY / h);
if (board[i][j] == '') {
board[i][j] = human;
firstTurn();
}
}
}
function draw() {
background(255);
strokeWeight(4);
line(w, 0, w, height);
line(w * 2, 0, w * 2, height);
line(0, h, width, h);
line(0, h * 2, width, h * 2);
for (let j = 0; j < 3; j++) {
for (let i = 0; i < 3; i++) {
let x = w * i + w / 2;
let y = h * j + h / 2;
let spot = board[i][j];
let r = w / 4;
textSize(32);
if (p == '0') {
if (spot == ai) {
noFill();
ellipse(x, y, r * 2);
} else if (spot == human) {
line(x - r, y - r, x + r, y + r);
line(x + r, y - r, x - r, y + r);
}
} else if (p == '1') {
if (spot == ai) {
line(x - r, y - r, x + r, y + r);
line(x + r, y - r, x - r, y + r);
} else if (spot == human) {
noFill();
ellipse(x, y, r * 2);
}
}
}
}
let result = checkWinner();
if (result != null) {
noLoop();
let resultP = createP('');
resultP.style('font-size', '32pt');
resultP.position(50, 50)
if (result == 'tie') {
resultP.html('Tie!');
} else {
resultP.html(`${result} wins!`);
}
}
}