JSFiddle - React, Tailwind, and code Playground
by ronilan
HTML
<span href="#" id="button1" class="button handleButton" data-cell="1"> </span>
<span href="#" id="button2" class="button handleButton" data-cell="2"> </span>
<span href="#" id="button3" class="button handleButton" data-cell="3"> </span>
<hr>
<span href="#" id="button4" class="button handleButton" data-cell="4"> </span>
<span href="#" id="button5" class="button handleButton" data-cell="5"> </span>
<span href="#" id="button6" class="button handleButton" data-cell="6"> </span>
<hr>
<span href="#" id="button7" class="button handleButton" data-cell="7"> </span>
<span href="#" id="button8" class="button handleButton" data-cell="8"> </span>
<span href="#" id="button9" class="button handleButton" data-cell="9"> </span>
<hr>
<h2 id="status"></h2>
CSS
.button {
width: 50px;
height: 50px;
border: 1px solid #ccc;
display: inline-block;
text-align: center;
}
.red {
background: red;
}
.blue {
background: blue;
}
hr {
visibility: hidden;
}
JavaScript
// input is a number
// output is the board
var app = {
// array of 9
// 0 = empty
// 1 = user
// -1 = ai
board: [0, 0, 0, 0, 0, 0, 0, 0, 0],
vector: {
hTop: {
value: 0,
cells: [1, 2, 3]
},
hMid: {
value: 0,
cells: [4, 5, 6]
},
hBot: {
value: 0,
cells: [7, 8, 9]
},
vLeft: {
value: 0,
cells: [1, 4, 7]
},
vMid: {
value: 0,
cells: [2, 5, 8]
},
vRight: {
value: 0,
cells: [3, 6, 9]
},
dLeft: {
value: 0,
cells: [1, 5, 9]
},
dRight: {
value: 0,
cells: [3, 5, 7]
},
},
attack: {},
init: function () {
app.bindEvents();
},
// user interface input
userTurn: function (buttonNumber) {
var gameStatus;
$("#button" + buttonNumber).addClass("blue");
$("#button" + buttonNumber).off("click");
if (app.board[buttonNumber - 1] === 0) {
app.board[buttonNumber - 1] = 1;
app.computeVectors(buttonNumber, 1);
gameStatus = app.checkEndGame();
// ai play automatically
if (gameStatus === 0) {
app.aiTurn();
} else if (gameStatus === 1) {
$("#status").html("you win");
$(".handleButton").off("click");
} else {
$("#status").html("a tie");
$(".handleButton").off("click");
}
}
},
aiTurn: function () {
//
var gameStatus,
buttonNumber,
i = 3,
boardCount = app.board.length;
buttonNumber = 5;
// if not middle
if (app.board[4] !== 0) {
// need to defend?
for (var key in app.vector) {
//...