Tic Tac Toe Week 1
by RolloRallo
HTML
<h1 id="title">
Tic Tac Toe
</h1>
<div id="board">
<button>?</button>
<button>?</button>
<button>?</button>
<br>
<button>?</button>
<button>?</button>
<button>?</button>
<br>
<button>?</button>
<button>?</button>
<button>?</button>
</div>
<h1 id="score_x">0</h1>
<button id="restart">Restart Game</button>
<h1 id="score_o">0</h1>
<textarea id="log">[Log content goes here...]</textarea>
CSS
body
{
font-family: Courier New;
text-align: center;
}
#title
{
font-size: 24px;
margin-top: 30px;
margin-bottom: 30px;
}
#board
{
margin-bottom: 30px;
}
#board button
{
background-color: white;
font-size:24px;
margin: 10px;
padding: 20px 0px;
width: 70px;
color: lightgray;
}
#board button.activated
{
background-color: lightgray;
}
#board button.x
{
color: red;
}
#board button.o
{
color: blue;
}
#score_x
{
color: red;
}
#score_o
{
color: blue;
}
#restart
{
font-size: 16px;
padding: 10px;
background-color: black;
color: white;
margin: 5px;
}
#log
{
width: 400px;
height: 200px;
}
JavaScript
// EVENTS (THINGS TO WATCH OUT FOR)
$(window).on("load", init);
$(document).on("click", "#restart", init);
$(document).on("click", "#board button:not(.activated)", mark);
// VARIABLES AND PARAMETERS (THINGS THAT DEFINE THE GAME)
var turn = "X";
var win_x = 0;
var win_o = 0;
var win_sequence = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
// FUNCTIONS (OUTCOMES THAT CAN BE TRIGGERED)
function init() {
$("#board button").text("?").removeClass("activated X O");
turn = "X";
}
function mark() {
$(this).addClass("activated");
if (turn == "X") {
$(this).text("X").addClass("X");
turn = "O";
} else if (turn == "O") {
$(this).text("O").addClass("O");
turn = "X";
}
check();
if (turn == "O") {
robot();
}
}
function check() {
// SERIALIZE GAME DATA
var data_x = [];
var data_o = [];
$("#board button.x").each(function() {
var index = $(this).index("button");
data_x.push(index);
});
$("#log").prepend("\n");
$("#log").prepend("X: " + data_x);
$("#board button.o").each(function() {
var index = $(this).index("button");
data_o.push(index);
});
$("#log").prepend("\n");
$("#log").prepend("O: " + data_o);
// COMPARE TO WINNING SEQUENCES
var winner = null;
var count = $("#board button:not(.activated)").length;
$("#log").prepend("\n");
$("#log").prepend("REMAINING: " + count);
$.each(win_sequence, function(i, seq) {
// SEE IF X OR O DATA INTERSECTS WITH ANY WINNING SEQUENCES
var intersect_x = seq.filter(value => data_x.includes(value));
var intersect_o = seq.filter(value => data_o.includes(value));
$("#log").prepend("\n");
$("#log").prepend("IX: " + intersect_x);
$("#log").prepend("\n");
$("#log").prepend("IO: " + intersect_o);
if (intersect_x.length == 3) {
winner = "X";
win_x += 1;
} else if (intersect_o.length == 3) {
winner = "O";
win_o += 1;
...