Tic Tac Toe Solution

Using only Tests, Lists, and Loops (Week 4 material)

by jazahn

HTML

<h2>Tic Tac Toe <a href="https://en.wikipedia.org/wiki/Tic-tac-toe" target="_blank">wiki</a></h2>
<div id="result"></div>
<div id="board">
  <div>0</div><div>1</div><div>2</div>
  <div>3</div><div>4</div><div>5</div>
  <div>6</div><div>7</div><div>8</div>
</div>
<div id="controls">
  <button id="start">Start Game</button>
</div>

CSS

h2 > a { font-size: 12px; }
#board {
  border: 1px solid #ccc;
  background-color: lightyellow;
  color: #999;
  font-weight: bold;
  font-size: 18px;
  float: left;
}
#board > div {
  float: left; 
  padding: 10px 20px; 
  border: 1px solid #ccc;
}
#board > div:hover {
  background-color: yellow;
  color: black;
}
#board > div:nth-child(3n+1) { clear: left; }
#controls {clear:both;}
.player-x {color: red;}
.player-o {color: blue;}

JavaScript

/*
TIC TAC TOE:
Two players, X and O, take turns marking a 3x3 grid until one or the other wins by getting 3 in a row, either vertically, horizontally, or diagonally. Otherwise the game ends in a tie.

LEARNING GOALS:
Use loops, conditionals, and arrays. For example:
- Use loops to repeat the same process for each turn.
- Use arrays to keep track of the game state (you need to know what moves have been made).
- Use conditionals to test whether the game is over, either because a player has won or no more turns or left.

YOUR TASK:
Fill in the function below to play the game of tic tac toe.

HOW TO APPROACH:
  Initialize the game state: reset the board, the turn counter to zero, and start with player 1.
  Prompt player for move.
  Update the board.
  Check if it's a winning move.
  Repeat with next player as long as neithier player has won and there are turns left.
*/
document.getElementById("start").onclick = function() {
    var players = ["x", "o"];
    var human = null;
    var board = Array(9);
    var turn = 0;
    var winner = null;
    var moves = [];
    var boardElement = document.getElementById("board");
    var resultElement = document.getElementById("result");
    var player, move, i, isValidChoice;

    // Initialize board.
    for (i = 0; i < board.length; i++) {
        board[i] = i;
        boardElement.children[i].innerHTML = i;
        boardElement.children[i].className = "";
    }

    resultElement.innerHTML = "Game in progress...";

    // Prompt for player choice 
    do {
        human = prompt("Would you like to be 'x' or 'o'? Enter 'x' or 'o' or cancel to play both: ");
        isValidChoice = (human === null) || (players.indexOf(human) >= 0)
    } while (!isValidChoice);

    // Begin game.
    GAME_LOOP:
        while (turn < 9) {

            // Whose turn is it?
            player = players[turn % 2];

            // Prompt player for move.
            do {
                if (player == human || human === null) {
                   ...