Simple Tic Tac Toe Game With Vanilla JavaScript

Syiainfoku make a Simple Tic Tac Toe Game With Vanilla JavaScript

Simple Tic Tac Toe Game With Vanilla JavaScript

Hello everyone, I am the founder of Syiainfoku. Today in Syiainfoku you will learn how to create a Tic Tac Toe Game With Vanilla JavaScript.

Tic Tac Toe Game is also a JavaScript Mini Project, and very useful to train you, if you are just starting to learn JS. And many people suggest you to practice creating some Mini Projects JS so that you understand JS better.

Preview Simple Tic Tac Toe Game

Preview Simple Tic Tac Toe Game

In my Tic Tac Toe Game design, there will be several elements in it which you can also customize to your liking.

  1. Tic Tac Toe Board Game
  2. The phrase "Tic Tac Toe Game"
  3. Replay Button
  4. "O" and "X" sign You can change the font as you wish
  5. Simple AI (Artificial Intelligence)
  6. If you win this game it will display the words "You Win!" and displays a blue background, according to the board you won.
  7. On the other hand, if you lose, "You Lose" will appear and the background will be red
  8. And if the result is a draw, the words "Draw" will appear and the background is green.
  9. This game (Tic Tac Toe) is also quite responsive, although there are still many shortcomings

Source Code and Brief Explanation

To make this program [Simple Tic Tac Toe Game with Vanilla JavaScript]. First you need to create three Files, one HTML File and one CSS File and lastly one JS File. After creating these files, just paste the following code into your file. You can also download the source code file of this Password Generate from the given download button.

First, create an HTML file with the name index.html and paste the given code in your HTML file. Remember, you must create a file with an .html extension.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Tic-Tac-Toe-Game | hitoricoding</title>
<link rel="stylesheet" href="./assets/style.css">
</head>

<body>
<h1>Tic Tac Toe Game</h1>
<table>
<tr>
<td class="cell" id="0"></td>
<td class="cell" id="1"></td>
<td class="cell" id="2"></td>
</tr>
<tr>
<td class="cell" id="3"></td>
<td class="cell" id="4"></td>
<td class="cell" id="5"></td>
</tr>
<tr>
<td class="cell" id="6"></td>
<td class="cell" id="7"></td>
<td class="cell" id="8"></td>
</tr>
</table>
<div class="endgame">
<div class="text"></div>
</div>
<button onClick="startGame()">Replay</button>

<script src="./assets/main.js" charset="utf-8"></script>
</body>

</html>

Second, create a CSS file with the name style.css and paste the given code in your CSS file. Remember, you must create a file with a .css extension.

@import url('https://fonts.googleapis.com/css2?family=Gloria+Hallelujah&display=swap');

body {
margin: 0;
padding: 0;
box-sizing: border-box;
background: #fff;
font-family: sans-serif;
}

td {
border: 2px solid #24252b;
height: 170px;
width: 170px;
text-align: center;
vertical-align: middle;
font-family: 'Gloria Hallelujah', cursive;
font-size: 70px;
cursor: pointer;
}

table {
border-collapse: collapse;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

table tr:first-child td {
border-top: 0;
}

table tr:last-child td {
border-bottom: 0;
}

table tr td:first-child {
border-left: 0;
}

table tr td:last-child {
border-right: 0;
}

button {
border: none;
border-radius: 10px;
margin: 10px;
padding: 10px 30px;
background: #366fa3;
cursor: pointer;
color: #fff;
}

h1 {
color: #223238;
text-align: center;
margin: 20px;
}

.endgame {
display: none;
position: absolute;
width: 250px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 60px 0;
font-size: 2em;
background-color: rgba(222, 124, 29, 0.8);
text-align: center;
border-radius: 5px;
color: white;
}

@media screen and (max-width: 450px) {
td {
width: 95px;
height: 95px;
font-size: 30px;
}

button {
padding: 5px 10px;
margin-left: 10px;
}

.endgame {
padding: 20px 0;
}
}

Finally, create a JS file with the name main.js and paste the given code in your JS file. Remember, you must create a file with a .js extension.

let oriBoard;
const huPlayer = '0';
const aiPlayer = 'X';
const winCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[6, 4, 2]
]
const cells = document.querySelectorAll('.cell');
startGame();

function startGame() {
document.querySelector(".endgame").style.display = "none";
oriBoard = Array.from(Array(9).keys());
for (var i = 0; i < cells.length; i++) {
cells[i].innerText = '';
cells[i].style.removeProperty('background-color');
cells[i].addEventListener('click', turnClick, false);
}
}

function turnClick(square) {
if (typeof oriBoard[square.target.id] == 'number') {
turn(square.target.id, huPlayer)
if (!checkWin(oriBoard, huPlayer) && !checkTie()) turn(bestSpot(), aiPlayer);
}
}

function turn(squareId, player) {
oriBoard[squareId] = player;
document.getElementById(squareId).innerText = player;
let gameWon = checkWin(oriBoard, player)
if (gameWon) gameOver(gameWon)
}

function checkWin(board, player) {
let plays = board.reduce((a, e, i) =>
(e === player) ? a.concat(i) : a, []);
let gameWon = null;
for (let [index, win] of winCombos.entries()) {
if (win.every(elem => plays.indexOf(elem) > -1)) {
gameWon = {
index: index,
player: player
};
break;
}
}
return gameWon;
}

function gameOver(gameWon) {
for (let index of winCombos[gameWon.index]) {
document.getElementById(index).style.backgroundColor =
gameWon.player == huPlayer ? "#28b5da" : "#db1a1a";
}
for (var i = 0; i < cells.length; i++) {
cells[i].removeEventListener('click', turnClick, false);
}
declareWinner(gameWon.player == huPlayer ? "You Win!" : "You Lose :(");
}

function declareWinner(who) {
document.querySelector(".endgame").style.display = "block";
document.querySelector(".endgame .text").innerText = who;
}

function emptySqueres() {
return oriBoard.filter(s => typeof s == 'number');
}

function bestSpot() {
return minimax(oriBoard, aiPlayer).index;
}

function checkTie() {
if (emptySqueres().length == 0) {
for (var i = 0; i < cells.length; i++) {
cells[i].style.backgroundColor = "#21bf31";
cells[i].removeEventListener('click', turnClick, false);
}
declareWinner("Draw :)")
return true;
}
return false;
}

function minimax(newBoard, player) {
var availSpots = emptySqueres();
if (checkWin(newBoard, huPlayer)) {
return {
score: -10
};
} else if (checkWin(newBoard, aiPlayer)) {
return {
score: 10
};
} else if (availSpots.length === 0) {
return {
score: 0
};
}
var moves = [];
for (var i = 0; i < availSpots.length; i++) {
var move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;

if (player == aiPlayer) {
var result = minimax(newBoard, huPlayer);
move.score = result.score;
} else {
var result = minimax(newBoard, aiPlayer);
move.score = result.score;
}

newBoard[availSpots[i]] = move.index;
moves.push(move);
}
var bestMove;
if (player === aiPlayer) {
var bestScore = -10000;
for (var i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 10000;
for (var i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}

That's it, now you have successfully created a Simple Tic Tac Toe Game with Vanilla JavaScript, If your code is not working or you are facing any error/problem, please download the source code file from the given download button. It's free and a .zip file will be downloaded then you have to extract it.

Closing

Thank you for those of you who have read and downloaded this source code, hopefully it can be useful and add to your insight.

If you found this article useful, you can share it. That's all from me, and THANK YOU