Creating Tic Tac Toe using Javascript

Hello, learner today In this blog post, We will be creating a Tic tac toe using Javascript. In the past post, we have created many projects one of them is Enjoy Code Animation Using HTML5 & CSS3. With Out wasting time Now it is time to create a Tic Tac Toe. This Code is written by Codingthai

Creating Tic Tac Toe using Javascript

In this Project, we have created a Tic tac toe game using Pure javascript. This code is designed on dribbble. In the HTML doc, we have created a <div> tag inside the tag we have created a 9 Column from Col-0 to Col8 after the column we have a button that reset the game.

Now in the CSS file, we have a color background of Blue. In the HTML we have created 9 Columns in Css we designed the box border with the gray color in the box we have added Blue color. We have to Create the Tic tac toc box inside a circle to look awsome We have put the game in the center using the CSS we have used press stat, 2p font family. for more detail look to the CSS code below

Code ByNarendra Chand
Language UsedHTML, CSS and Pure Javascript
External Link / DependenciesNo
ResponsiveYes

There are 3 types of styles to connect CSS with HTML files. Inline CSS, Internal CSS, External CSS. For Inline CSS in this, we have to write the CSS code inside the HTML code using style Attribute elements. For internal CSS we have to use the Style tag in the Head section on HTML File. we Have used this Internal CSS in The below section. Last is External CSS for this we have to create another CSS File in the same folder this

Preview of Code Animation

In this preview, we have used internal CSS in the code. In the internal CSS, we have to write the code in the head section using the Style tag. We have to write the code in <Style> CSS code </style> in the Head section in the HTML file. You can Copy and Run the preview in the Top left of the code

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - Tic Tac Toe Board (Pure JavaScript)</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.0.2/tailwind.min.css'><link rel="stylesheet" href="./style.css">
<style>
  @import url("https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap");
* {
  font-family: "Press Start 2P", cursive;
  user-select: none;
}

.ctr {
  display: flex;
  justify-content: center;
  align-items: center;
}

body {
  background: #285CA1;
}

.tabel {
  width: 480px;
  height: 480px;
  background: #76AFD6;
  border-radius: 100%;
  border: 1px solid #0D152B;
  box-shadow: -2px 20px 0 -3px #4283C4, -20px 20px #0D152B;
  flex-direction: column;
}

.board {
  width: 369.2307692308px;
  height: 369.2307692308px;
  background: #D3E2EA;
  border-radius: 20px;
  border: 1px solid #0D152B;
  box-shadow: -10px 5px 0px -2px #192852;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 8px;
  padding: 12px;
}

.board > span {
  background: #76AFD6;
  color: #fff;
  font-size: 4em;
  padding-left: 9px;
  padding-top: 6px;
  text-align: center;
  border: 2px solid #0D152B;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: -1.2px 2px 0px 0px #141D4C;
}
.board > span:hover {
  background: #6aa8d2;
}
.board > span:active {
  box-shadow: -1.2px 7.4px 0px -2.5px #141D4C;
}

#reset {
  margin-top: 14px;
  color: #fff;
}

.win {
  background: #55efc4 !important;
}
  </style>
</head>
<body>
<!-- partial:index.partial.html -->
<body class="w-screen h-screen ctr">
  <div class="tabel ctr">
    <div class="board"><span id="col-0"></span><span id="col-1"></span><span id="col-2"></span><span id="col-3"></span><span id="col-4"></span><span id="col-5"></span><span id="col-6"></span><span id="col-7"></span><span id="col-8"></span></div>
    <button id="reset">Reset</button>
  </div>
  <!--design on dribbble: https://dribbble.com/shots/6546099-Empty-Spaces-10-->
</body>
<!-- partial -->
  <script  src="./script.js">'use strict'

const _ = document,
          cols = Array.from(_.querySelectorAll('.board > span')),
					reset = _.querySelector('#reset')
let cur = true
let arr = new Array(9).fill(null)
const wins = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]
function event(can) {
	reset.addEventListener('click', fnreset)
  for(let col of cols)
    if(can)
      col.addEventListener('click', play)
    else
      col.removeEventListener('click', play)
}
event(true)
function play(e) {
  const __ = e.target
  if(!__.innerHTML){
    cur = !cur
    __.innerHTML = cur ? '<h1 name="O">O</h1>' :  '<h1 name="X">X</h1>'
    move(parseInt(__.id.split(/\D+/g)[1]), __.childNodes[0].getAttribute('name'))
  }
}

function move(ind, sign) {
  arr[ind] = sign
  console.log(arr)

  for (let i = 0; i < wins.length; i++) {
     let [a, b, c] = wins[i] 
      if(cmp(arr[a], arr[b], arr[c])){
        console.log(sign, ' wins')
        event(false)
        cols[a].classList.add('win')
        cols[b].classList.add('win')
        cols[c].classList.add('win')
      }
  }
}
function cmp(a, b, c) {
  if(a && b && c)
    return (a === b) && (a === c) && (b === c)
}

function fnreset() {
    for(let col of cols){
      col.classList.remove('win')
      col.innerHTML = ''
    }
    arr = new Array(9).fill(null)
    event(true)
}</script>

</body>
</html>

You might like this

Creating Tic Tac Toe using Javascript [Source code]

For Creating a Creating Tic Tac Toe using Javascript. First, you have to create three files (HTML, CSS & Javascript) files with the named index.html, style.css, and script.js in the same folder and you have to link the CSS and javascript files to HTML. after that paste, the HTML code in index.html, paste the CSS code in style.css and lastly paste the Javascript Code in Script.js that’s all after pasting the code.

First, you have to create an HTML file with the named index.html and paste the below HTML code on it and save it. Remember to give a .html extension to the HTML file.

<!DOCTYPE html>
<!--Codingthai.com--> 
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - Tic Tac Toe Board (Pure JavaScript)</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.0.2/tailwind.min.css'><link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<body class="w-screen h-screen ctr">
  <div class="tabel ctr">
    <div class="board"><span id="col-0"></span><span id="col-1"></span><span id="col-2"></span><span id="col-3"></span><span id="col-4"></span><span id="col-5"></span><span id="col-6"></span><span id="col-7"></span><span id="col-8"></span></div>
    <button id="reset">Reset</button>
  </div>
  <!--design on dribbble: https://dribbble.com/shots/6546099-Empty-Spaces-10-->
</body>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>

After pasting the HTML code, Now have to create a second CSS file with the named style.css. Paste the below code on it and save it. Again remember to give a .css extension to the CSS file.

@import url("https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap");
* {
  font-family: "Press Start 2P", cursive;
  user-select: none;
}

.ctr {
  display: flex;
  justify-content: center;
  align-items: center;
}

body {
  background: #285CA1;
}

.tabel {
  width: 480px;
  height: 480px;
  background: #76AFD6;
  border-radius: 100%;
  border: 1px solid #0D152B;
  box-shadow: -2px 20px 0 -3px #4283C4, -20px 20px #0D152B;
  flex-direction: column;
}

.board {
  width: 369.2307692308px;
  height: 369.2307692308px;
  background: #D3E2EA;
  border-radius: 20px;
  border: 1px solid #0D152B;
  box-shadow: -10px 5px 0px -2px #192852;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 8px;
  padding: 12px;
}

.board > span {
  background: #76AFD6;
  color: #fff;
  font-size: 4em;
  padding-left: 9px;
  padding-top: 6px;
  text-align: center;
  border: 2px solid #0D152B;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: -1.2px 2px 0px 0px #141D4C;
}
.board > span:hover {
  background: #6aa8d2;
}
.board > span:active {
  box-shadow: -1.2px 7.4px 0px -2.5px #141D4C;
}

#reset {
  margin-top: 14px;
  color: #fff;
}

.win {
  background: #55efc4 !important;
}

After pasting both HTML and CSS now it time to create a Javascript file in same folder after createing the file page the Javascript code in it and save the file don’t forget to save the file with .js extension.

'use strict'

const _ = document,
          cols = Array.from(_.querySelectorAll('.board > span')),
					reset = _.querySelector('#reset')
let cur = true
let arr = new Array(9).fill(null)
const wins = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]
function event(can) {
	reset.addEventListener('click', fnreset)
  for(let col of cols)
    if(can)
      col.addEventListener('click', play)
    else
      col.removeEventListener('click', play)
}
event(true)
function play(e) {
  const __ = e.target
  if(!__.innerHTML){
    cur = !cur
    __.innerHTML = cur ? '<h1 name="O">O</h1>' :  '<h1 name="X">X</h1>'
    move(parseInt(__.id.split(/\D+/g)[1]), __.childNodes[0].getAttribute('name'))
  }
}

function move(ind, sign) {
  arr[ind] = sign
  console.log(arr)

  for (let i = 0; i < wins.length; i++) {
     let [a, b, c] = wins[i] 
      if(cmp(arr[a], arr[b], arr[c])){
        console.log(sign, ' wins')
        event(false)
        cols[a].classList.add('win')
        cols[b].classList.add('win')
        cols[c].classList.add('win')
      }
  }
}
function cmp(a, b, c) {
  if(a && b && c)
    return (a === b) && (a === c) && (b === c)
}

function fnreset() {
    for(let col of cols){
      col.classList.remove('win')
      col.innerHTML = ''
    }
    arr = new Array(9).fill(null)
    event(true)
}

That’s all after pasting the code now your code will be successfully run. If you get any kind of error/problem in the code just comment or contact me on social media

Output Result

Creating Tic Tac Toe using Javascript
Written By@codingthai
Code By @Narendra Chand

Leave a Comment