How to Program a Tic Tac Toe Game in Javascript (freecodecamp)

I’ve been doing freecodecamp Front End Developer certificate for last two months. And it has been a great learning experience. I’ve had the chance to practice on old Computer Science concept as well as learning new Web Development skills. In this article, I’m going to show you how to program a Tic Tac Toe web application using HTML, CSS, and Javascript. We’ll do the UI using html and css, and for the functionality we use javascript, and Jquery. For this project I used codepen.io which is great for creating web dev projects. Also, note that there’s no right or wrong way to implement the functionality of the game. In my approached, I chose to use a 2d array, as it resembles the board of the game. Here’s the code for the whole project. So let’s get started it!

Note: The AI of the game is done using a random number generator with no logic at all. If you want to implement a true AI (play against the computer) you might want to look into minimax algorithm.

If you prefer watching a video, Here’s a video I made of how to code the game. But if not then proceed reading!!!

1- Open a project in codepen or create a new project.

2- We start by creating the user interface skeleton (html)

<div class="container">
  <!-- header -->
  <div class="header">
    <img src="http://pctechtips.org/pics/header-logo-tictactoe.png">
  </div>
  <div class="select">
    <p>You're playing against computer. Choose X or O</p>
  <form action="#" >
    <input class="checkBox" type="checkbox" name="xPlayer" value="X">X Player    
</form>
  <form action="#">
    <input class="checkBox" type="checkbox" name="oPlayer" value="O">O Player 
  </form>
  </div>
  <div class="tictactoe">  
     <!-- selection for X or O -->       
    <!-- first row (3 square) -->
    <div class="row">
      <div id="0" class="square right bottom"></div><!-- 
      --><div id="1" class="square right bottom"></div><!--
      --><div id="2" class="square bottom"></div>      
    </div>
 
    <!-- second row (3 square) -->
    <div class="row">
      <div id="3" class="square right bottom"></div><!--
      --><div id="4" class="square right bottom"></div><!--
      --><div id="5" class="square bottom"></div>      
    </div> 
 
    <!-- third row (3 square) -->
    <div class="row">
      <div id="6" class="square right"></div><!--
      --><div id="7" class="square right"></div><!--
      --><div id="8" class="square"></div>      
    </div>     
  </div> 
</div>

3- In this section we style our app using css.

body {
  background-color: #174c6d;
  font-family: verdana, sans-serif;
  color: white;
}
 
.container {
  margin: 0 auto;
  text-align: center;
}
 
.header {
  margin-top: 10px;
}
 
p {
  font-size: 20px;
  margin-bottom: 0px;
}
 
.select > form {
  display: inline-block;
  margin-top: 20px;
  margin-right:20px;
  margin-left:20px;
  font-size: 20px;
}
 
h2 {
  margin-bottom: 30px;
}
 
.tictactoe {
  margin-top: 70px;
  margin-bottom: 70px;
}
 
/* setting font-size of row to 0px
   to prevent indentation/margin row*/
/* .row {
  font-size: 0px;
} */
.row > div {
  margin: 0px;
  display: inline-block;
  font-size: 90px;
  width: 100px;
  height: 100px;
  text-align: center; 
  padding: 0px;
  vertical-align: top;
  line-height: 100px;
}
 
.right {
  border-right: solid 7px white;
}
 
 
.bottom {
  border-bottom: solid 7px white;
}
 
.resetGame {
  font-size: 20px;
  background-color: gray;
}
 
#message {
  /* display: inline-block; */
  text-align: center; 
}

4- Finally, we use javascript and jquery for the functionality.

//variables
  var turn;
  var computer;
  var user;
  var sqrId;
  var board = [
    ["","",""], 
    ["","",""], 
    ["","",""]
  ];
  var row, col;
 
$(document).ready(function() { 
 
  //listener for checkboxes X and O
  $(".checkBox").click(function() {
    console.log("checked");
    if($(this).is(":checked")) {
      user = $(this).val();
      turn = user;
      computer = (user == 'X') ? 'O' : 'X';
      console.log(turn + " " + user + " " + computer);
    }
  });
 
  //listener for event clicks
  $(".square").click(function() {
    sqrId = $(this).attr("id");    
    playerMove(sqrId)
    computerPlayLevel1();    
    if(checkWinners()) {
      alert(turn+" Wins the Game!");
      resetGame();
    }
    //checking board: if empty sqr play, else its a draw
    if(!checkBoard()) {
      alert("is a draw!");
    } 
    turn = (turn == user) ? computer : user;
  });  
});
 
//reset game function
function resetGame() {
  $(".square").text("");
  turn = undefined;
  computer = undefined;
  user = undefined;
  //unchecking dialog boxes
  $(".checkBox").prop("checked", false);
  board = [["","",""], ["","",""], ["","",""]];
}
 
//getting user move and output to board
function playerMove(sqrId) {
  console.log("player move: "+$('#'+sqrId).attr("id")+" "+turn);
  //if sqr is empty then run logic, else error: wrong play!
  if($('#'+sqrId).text() == "") {
      $('#'+sqrId).text(user);
      row = getRow();
      col = getCol();
      console.log(sqrId+" "+row+","+col);
      board[row][col] = user;
      console.log(board);
    }
    else {
      alert("wrong move. Try again!");
      return;
    }    
}
 
/* AI logic level 1  generating random play */
function computerPlayLevel1() {
  var random;
  var min = 0, max = 8;
  do{
    random = Math.floor(Math.random() * (max + min));
  }while($("#"+random).text() != "")
  sqrId = random;
  row = getRow();
  col = getCol();
  board[row][col] = computer;
  $('#'+sqrId).text(computer);
}
 
//setting player to be X or O (check box)
function setPlayer() {
 
}
 
/* return row: divide sqrId by 3 as board[3][3] */
function getRow() {
  return Math.floor(sqrId / board.length);  
}
 
/* return column: module sqrId by 3 as board[3][3] */
function getCol() {
  return sqrId % board.length;
}
 
//checking for winning combinations
function checkWinners() {
  console.log(board[1]);  
  //checking rows
  for(var i = 0; i < board.length; i++) {
    if(board[i][0] != "" && board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
      console.log("rows: "+board[i][0]+""+board[i][1]+""+board[i][2]);
      return true;
    }      
  }
  //checking columns
  for(var j = 0; j < board.length; j++) {
    if(board[0][j] != "" && board[0][j] == board[1][j] && board[1][j] == board[2][j]) {
      console.log("column: "+board[0][j]+""+board[1][j]+""+board[2][j]);
      return true;
    }
  }
  //checking across
  if(board[0][0] != "" && board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
    console.log("across1");
      return true;
  }
  if(board[0][2] != "" && board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
    console.log("across2");
      return true;
  }
  //if reached here, no winners
  return false;
}
 
/* checking if there's more room to play, if not 
   then it's a draw'*/
function checkBoard() {
  for(var i = 0; i < board.length; i++) {
    for(var j = 0; j < board[i].length; j++)
    if(board[i][j] == "") { 
      return true;
    }
  }  
  return false;
}
Share This!

Leave a Reply

Your email address will not be published.