Tic Tac Toe

2022-JUN-09 Tic Tac dippin' my toe into AI

by val_p

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</button>
<h1 id="score_o">0</h1>

<textarea id="log">[Log content]</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;
}

#log
{
  width: 300px;
  height: 200px;
}

JavaScript

// EVENTS TO MONITOR
$(document).on("click", "#restart", init);
$(document).on("click", "#board button:not(.activated)", mark);
$(window).on("load", init);

// GAME DEFINITION 
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 TO PERFORM

function init() {

  $("#board button").text("?").removeClass("activated o x");
  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() {

    // CONVERT BOARD INTO SERIALS

    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(" / ");
    $("#log").prepend("O: " + data_o);

    // COMPARE TO WINNING SEQUENCES

    var winner = null;
    var count = $("#board button:not(.activated)").length;

    $("#log").prepend(" / ");
    $("#log").prepend("REMAINING: " + count);

    $.each(win_sequence, function(i, seq) {

      var inter_x = seq.filter(value => data_x.includes(value));
      var inter_o = seq.filter(value => data_o.includes(value));

      $("#log").prepend("\n");
      $("#log").prepend("INTER_X: " + inter_x);
      $("#log").prepend(" / ");
      $("#log").prepend("INTER_O: " + inter_o);

      if (inter_x.length == 3) {

        winner = "X";
        win_x += 1;

      } else if (inter_o.length == 3) {
        winner = "O";
        win_o += 1;

      }

    });

    // ANNOUNCE RESULTS

    if (winner != null) {

     ...