FreeCodeCamp Tic Tac Toe
The best you can do is draw.
by Brock Callahan
HTML
<h2>FreeCodeCamp: Unbeatable Tic-TacToe</h2>
<h4 id="io"></h4>
<table id="board" border="1">
<caption>Tic Tac Toe</caption>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<button id="play">New Game</button>
CSS
body {
font-family: sans-serif;
}
td {
height: 30px;
width: 30px;
text-align: center;
cursor: pointer;
}
button {
margin-top: 30px;
}
table {
border: none;
}
tr {
border: none;
}
td {
border: 3px solid #009999;
}
tr:first-child > td:first-child,
tr:first-child > td:last-child,
tr:first-child > td:nth-child(2) {
border-top: none;
}
tr:last-child > td:first-child,
tr:last-child > td:last-child,
tr:last-child > td:nth-child(2) {
border-bottom: none;
}
td:first-of-type {
border-left: none;
}
td:last-of-type {
border-right: none;
}
JavaScript
var ticTacToe = {
playing: false,
player: {
letter: '',
move: function (square) {
if (ticTacToe.board[square] !== '-') {
return console.log('Space not empty');
} else {
ticTacToe.board[square] = this.letter;
ticTacToe.computer.move();
}
}
},
computer: {
letter: '',
move: function () {
var gameOver = checkWin(ticTacToe.board, ticTacToe.player.letter);
var drawGame = draw(ticTacToe.board);
if (drawGame) {
ticTacToe.playing = false;
io.innerText = "Draw";
setTimeout(ticTacToe.restart, 1000);
} else if (!gameOver) {
winBlock(ticTacToe.board, ticTacToe.computer.letter, ticTacToe.player.letter);
gameOver = checkWin(ticTacToe.board, ticTacToe.computer.letter);
if (!gameOver) {
return "Your turn";
} else {
ticTacToe.playing = false;
// clearBoard(ticTacToe.board);
return console.log(gameOver);
}
} else {
console.log(gameOver);
}
}
},
start: function () {
var letter = prompt('x or o?').toUpperCase();
if (letter === 'X' || letter === 'O') {
this.playing = true;
clearBoard(ticTacToe.board);
this.player.letter = letter;
this.computer.letter = (letter === 'X') ? 'O' : 'X';
}
},
board: ['-','-','-','-','-','-','-','-','-'],
restart: function () {
clearBoard(ticTacToe.board);
displayBoard(ticTacToe.board, squares);
ticTacToe.playing = true;
}
};
// A function to produce a diagonal array from the board array
function diag(arr, reverse) {
var a = [];
if (reverse === true) {
for (var j = 2; j < 7; j+=2) {
a.push(arr[j]);
}
} else {
for (var i = 0; i < arr.length; i+=4) {
a.push(arr[i]);
}
}
return a;
}
// A function to produce a single row from the board array
function row(arr, which) {
if (which === 1) {
return arr.slice(0,3);
} else if (which === 2) {
return arr.slice(3,6);
} else {
return arr.slice(6,9);
}
}
// A function to produce a single column
function...