An Introduction to Javascript Games: The Best Guide

Introduction

JavaScript is an open-source programming language. It is designed for creating web-centric applications. It is lightweight and interpreted, which makes it much faster than other languages. JavaScript is integrated with HTML, which makes it easier to implement JavaScript in web applications.

In this ‘Introduction to JavaScript Games’ article, we are entirely focussing on the practical application of JavaScript in real-world web applications. We will be building two games based entirely on JavaScript throughout this article, so brace yourself and start your JavaScript journey!

The two games that we are going to build are:

  • JavaScript Game: Snake
  • JavaScript Game: Tic-Tac-Toe

Become a Certified UI UX Expert in Just 5 Months!

With The Best-in-class UI UX ProgramExplore Program
Become a Certified UI UX Expert in Just 5 Months!

JavaScript Game: Snake

Let’s go ahead and build our very first JavaScript game that looks and feels exactly like one of those old-school Nokia snake games. The logic is not very complex and we think you’ll have fun developing this game, so let’s get started!

JavaScript_Game_Snake

Fig: JavaScript Game: Snake

You can use any text editor of your choice for developing this game. Using Visual Studio Code is a great IDE for various programming languages like JavaScript and Python.

Our area of focus will be on three aspects of this project that we will work on:

  • HTML - This file is the base file for this project and houses the contents of this JavaScript game.
  • CSS - This is a stylesheet that we use to stylize various elements of our game.
  • JS - This JavaScript file contains all the magic that happens behind the scenes for this game to work.

Project Directory

The Project Directory should look like the image attached below, in the end. This project is inspired by a GitHub repository, and therefore a license file is included in the project directory to comply with the software distribution and modification conditions.

/JavaScript_Game_Snake_PD

Fig: Project Directory

Index.html For Java Programs

This file, as previously stated, consists of all the codes that we need, to display the contents of this JavaScript game on the screen. We will go through the code and explore what each snippet of code is for.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <title>JavaScript Snake Game</title>

    <link rel="stylesheet" href="app.css" />

  </head>

  <body>

    Speed:

    <input type="number" id="gameSpeed" value="5" min="1" max="9" step="1" />

    <input type="button" value="Start" id="gameStart" />

    <br />

    <br />

    <div>

      <canvas id="gameArea"></canvas>

    </div>

    <div class="relative">

      <img src="./images/simplilearn.png" style="width: 200px; height: 80px;" />

    </div>

    <script src="app.js"></script>

  </body>

</html>

  • This file contains the basic HTML boilerplate code.
  • Import CSS stylesheet inside the head tag.
  • The title of the game, as usual, is defined within the head tag.
  • The layout of the web page is within the body tag.
  • We are using the canvas tag to design the game.
  • Include the javascript file in the end, within the body tag.

app.js

This file includes the code that makes the game work. Let’s go through the code and understand what each snippet of the code is for.

"use strict";

var gameStart = null,

  gameSpeed = null,

  gameArea = null,

  gameAreaContext = null,

  gameAreaWidth = 0,

  gameAreaHeight = 0,

  cellWidth = 0,

  playerScore = 0,

  snake = null,

  snakeFood = null,

  snakeDirection = null,

  speedSize = 0,

  timer = null;

function initialize() {

  gameStart = document.querySelector("#gameStart");

  gameSpeed = document.querySelector("#gameSpeed");

  gameArea = document.querySelector("#gameArea");

  gameAreaContext = gameArea.getContext("2d");

  gameAreaWidth = 400;

  gameAreaHeight = 600;

  cellWidth = 20;

  gameArea.width = gameAreaWidth;

  gameArea.height = gameAreaHeight;

  gameStart.onclick = function () {

    this.disabled = true;

    startGame();

  };

}

function startGame() {

  playerScore = 0;

  snakeDirection = "right";

  speedSize = parseInt(gameSpeed.value);

  if (speedSize > 9) {

    speedSize = 9;

  } else if (speedSize < 0) {

    speedSize = 1;

  }

  snake = [];

  snake.push({ x: 0, y: cellWidth });

  createFood();

  clearInterval(timer);

  timer = setInterval(createGameArea, 500 / speedSize);

}

function createFood() {

  snakeFood = {

    x: Math.round((Math.random() * (gameAreaWidth - cellWidth)) / cellWidth),

    y: Math.round((Math.random() * (gameAreaHeight - cellWidth)) / cellWidth),

  };

}

function createGameArea() {

  var snakeX = snake[0].x;

  var snakeY = snake[0].y;

  gameAreaContext.fillStyle = "#FFFFFF";

  gameAreaContext.fillRect(0, 0, gameAreaWidth, gameAreaHeight);

  gameAreaContext.strokeStyle = "#CCCCCC";

  gameAreaContext.strokeRect(0, 0, gameAreaWidth, gameAreaHeight);

  if (snakeDirection == "right") {

    snakeX++;

  } else if (snakeDirection == "left") {

    snakeX--;

  } else if (snakeDirection == "down") {

    snakeY++;

  } else if (snakeDirection == "up") {

    snakeY--;

  }

  if (

    snakeX == -1 ||

    snakeX == gameAreaWidth / cellWidth ||

    snakeY == -1 ||

    snakeY == gameAreaHeight / cellWidth ||

    Control(snakeX, snakeY, snake)

  ) {

    writeScore();

    clearInterval(timer);

    gameStart.disabled = false;

    return;

  }

  if (snakeX == snakeFood.x && snakeY == snakeFood.y) {

    var newHead = { x: snakeX, y: snakeY };

    playerScore += speedSize;

    createFood();

  } else {

    var newHead = snake.pop();

    newHead.x = snakeX;

    newHead.y = snakeY;

  }

  snake.unshift(newHead);

  for (var i = 0; i < snake.length; i++) {

    createSquare(snake[i].x, snake[i].y);

  }

  createSquare(snakeFood.x, snakeFood.y);

}

function Control(x, y, array) {

  for (var i = 0; i < array.length; i++) {

    if (array[i].x == x && array[i].y == y) return true;

  }

  return false;

}

function writeScore() {

  gameAreaContext.font = "50px sans-serif";

  gameAreaContext.fillStyle = "#FFF333";

  gameAreaContext.fillText(

    "Score: " + playerScore,

    gameAreaWidth / 2 - 100,

    gameAreaHeight / 2

  );

}

function createSquare(x, y) {

  gameAreaContext.fillStyle = "#000000";

  gameAreaContext.fillRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth);

}

function changeDirection(e) {

  var keys = e.which;

  if (keys == "40" && snakeDirection != "up") snakeDirection = "down";

  else if (keys == "39" && snakeDirection != "left") snakeDirection = "right";

  else if (keys == "38" && snakeDirection != "down") snakeDirection = "up";

  else if (keys == "37" && snakeDirection != "right") snakeDirection = "left";

}

window.onkeydown = changeDirection;

window.onload = initialize;

  • “use strict” gives an error when a variable is declared without specifying its type. This leads to cleaner code.
  • We declare all the variables that we will be needing in the game and set a default value.
  • We define a function ‘initialize()’ that initializes the game canvas onto the screen:
  • We select the corresponding HTML elements by ID and store them in a variable.
  • Next, create a game area and then define its width and height, along with single-cell size.
  • Then, we set the game by clicking on the ‘start game’ button.
  • We define a function ‘startGame()’ that performs the following operations:
  • Sets the initial score to 0.
  • Sets the starting snake direction to the right.
  • We store the game speed inputted by the user and validate the input.
  • Snake is declared as an array and is initialized with a single cell value by pushing the cell width.
  • We call the createFood() function that creates a food cell randomly on the canvas.
  • Lastly, we reset the timer and then set the timer according to the game speed.
  • We define a function ‘createFood()’ that creates the food at random locations on the canvas by doing the following:
  • ‘snakeFood’ is a javascript object that has ‘x’ and ‘y’ names having values for width and height respectively.
  • Width and height are kept random at every function call to create food randomly on the canvas.
  • We define a function ‘createGameArea()’ that performs the following operations:
  • We set the snake x and y-axis to initial values.
  • Then we fill the ‘gameArea’ with white color and border as dark gray.
  • We then adjust the snake’s x and y positions according to its direction.
  • Then we check for abnormal values of the snake’s x and y-axis:
  • If true:
  • We call the ‘writeScore()’ function that shows up the score on canvas.
  • Reset the timer.
  • Enable the game start button.
  • And stop the game.
  • We also check if  the snake encounters food:
  • If true:
  • We add that food to snake size.
  • We create a new food on the canvas.
  • Else:
  • We pop a cell from the snake’s size when it moves forward and assign it to ‘newHead’.
  • newHead is added to the beginning of the snake array.
  • Then we loop through the snake array and create squares by calling the createSquare() function according to its length
  • We also create a square for the snake food by calling the function.
  • We define a function Control(x, y, array) that checks if the snake hits itself, and returns true if it does, false if it doesn’t.
  • We define a function writeScore() that prints the user score on the screen and when the game ends:
  • We set the font size and family.
  • Then, we set the font color.
  • After that, we set the game area to show the text on the canvas.
  • We then define a function createSquare(x, y) that creates a square for the given x and y-axis:
  • We define the color of the shape.
  • Then, we define the cell dimensions.
  • Lastly, we define the function changeDirection(e) that changes the direction of the snake, by the following ways:
  • We first take the keypress event and store the key value in a variable.
  • Every key on the keyboard is assigned a number.
  • We identify which key is pressed by checking its number and then move the snake in that direction.
  • Then we set the events to the screen by doing so:
  • Whenever a key is pressed, changeDirection() function is called.
  • The initialize() function runs whenever the windows loads.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

app.css

This file contains the code that we use to stylize the elements of the snake game. Let’s go through the stylesheet and understand all the styles applied to this project.

body {

  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,

    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;

  margin: 20px auto;

  text-align: center;

  font-size: 150%;

  background-image: url("./images//wp2409705.jpg");

  background-color: #cccccc; /* Used if the image is unavailable */

  height: 800px; /* You must set a specified height */

  background-position: center;/* Center the image */

  background-repeat: no-repeat; /* Do not repeat the image */

  background-size: cover; /* Resize the background image to cover the entire container */

}

input {

  font-size: 100%;

  text-align: center;

  padding: 5px 7px;

}

 canvas {

  background-color: white;

  border-radius: 20px;

  -webkit-box-shadow: 3px 3px 5px 6px black; /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */

  -moz-box-shadow: 3px 3px 5px 6px black; /* Firefox 3.5 - 3.6 */

  box-shadow: 3px 5px 6px black; /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */

}

 div.relative {

  position: absolute;

  top: 760px;

  left: 120px;

}

          • Define CSS styles for the body, which includes background, font styles, and basic layout.
          • Define the style for the input element.
          • Define the look and feel of canvas.
          • Define the position of the Simplilearn logo.

End Result

The game should look and feel like this in the end, though you are free to tweak the logic and style of this game and make it your own!

JavaScript_Game_Snake_%28End_Result%29

Fig: JavaScript Game: Snake (End Result)

JavaScript Game: Tic-Tac-Toe

Now that we have created the first game based on JavaScript, let’s move onto building our next JavaScript game which will be tic-tac-toe. The very same game that we are used to playing since school. So without further ado, let’s get started!

JavaScript_Game_Tic-Tac-Toe

Fig: JavaScript Game: Tic-Tac-Toe

Like in the previous game, we are going to concentrate on the three aspects, namely:

          • HTML
          • JS
          • CSS

Project Directory

The project directory should look like the following image in the end.

JavaScript_Game_Tic-Tac-Toe_PD

Fig: Project Directory

index.html

This file consists of the contents of our JavaScript game. Let’s move ahead and understand the code.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Tic-Tac-Toe</title>

    <link

      href="https://fonts.googleapis.com/css?family=Permanent+Marker"

      rel="stylesheet"

    />

    <link rel="stylesheet" href="css/app.css" type="text/css" />

    <script type="text/javascript" src="js/app.js"></script>

  </head>

  <body>

    <div>

      <h1 class="header">Tic Tac Toe</h1>

    </div>

    <div class="enter-players">

      <form id="player-form">

        <div class="player-container">

          <label for="player1">Player 1</label>

          <input

            type="text"

            placeholder="enter name"

            name="player1"

            id="player1"

            class="input-field"

          />

        </div>

        <div class="player-container">

          <label for="player2">Player 2</label>

          <input

            type="text"

            placeholder="enter name"

            name="player2"

            id="player2"

            class="input-field"

          />

        </div>

        <input type="submit" class="submit-btn" value="Start Game" />

      </form>

    </div>

    <div class="board__main hide-container">

      <div class="board___player-turn"></div>

      <div class="board__container">

        <div class="board__cell">

          <div class="letter" data-id="0"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="1"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="2"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="3"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="4"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="5"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="6"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="7"></div>

        </div>

        <div class="board__cell">

          <div class="letter" data-id="8"></div>

        </div>

      </div>

    </div>

    <div class="relative">

      <img src="./assets/simplilearn.png" style="width: 200px; height: 80px;" />

    </div>

    <div class="reset reset--hidden">

      <div class="reset__text"></div>

      <button class="replay-btn" value="replay">

        <span class="clear-board">Clear Board</span>

      </button>

    </div>

  </body>

</html>

      • Basic HTML boilerplate.
      • Import CSS stylesheet and JavaScript file inside the head tag.
      • Title, as usual, is added within the head tag.
      • The layout of the web page is within the body tag.
      • Create a player entry form.
      • Create the main game container which will be hidden at first and is only visible once the player entry has been submitted.
      • Add the Simplilearn logo.
      • Add a reset button that will be visible when the game starts.

app.js

This file contains all the javascript codes that we need to build the logic of our game. Relevant comments are also added in the code, in case you are wondering what each line in this code is used for. Let’s go ahead and understand the code.

"use strict";

window.addEventListener("load", app);

let gameBoard = ["", "", "", "", "", "", "", "", ""];

let turn = 0; // Keeps track if X or O player's turn

let winner = false;

// CREATE PLAYER

const player = (name) => {

  name = name;

  return { name };

};

let playerX = player("");

let playerY = player("");

// INITIALIZE APP

function app() {

  let inputField = document.querySelector(".input-field").focus();

  const addPlayerForm = document.getElementById("player-form");

  addPlayerForm.addEventListener("submit", addPlayers); 

  let replayButton = document.querySelector(".replay-btn");

  replayButton.addEventListener("click", resetBoard);

}

// Add PLAYERS

function addPlayers(event) {

  event.preventDefault();

  if (this.player1.value === "" || this.player2.value === "") {

    alert("You Must Enter a Name for Each Field");

    return;

  }

  const playerFormContainer = document.querySelector(".enter-players");

  const boardMain = document.querySelector(".board__main");

  playerFormContainer.classList.add("hide-container");

  boardMain.classList.remove("hide-container"); 

  playerX.name = this.player1.value;

  playerY.name = this.player2.value;

  buildBoard();

}

// RETURN CURRENT PLAYER

function currentPlayer() {

  return turn % 2 === 0 ? "X" : "O";

}

// Resize squares in event browser is resized

window.addEventListener("resize", onResize);

function onResize() {

  let allCells = document.querySelectorAll(".board__cell");

  let cellHeight = allCells[0].offsetWidth;

  allCells.forEach((cell) => {

    cell.style.height = `${cellHeight}px`;

  });

}

// Build Board

function buildBoard() {

  let resetContainer = document.querySelector(".reset");

  resetContainer.classList.remove("reset--hidden");

  onResize();

  addCellClickListener();

  changeBoardHeaderNames();

}

// CELL CLICK EVENT FOR PLAYER TO ATTEMPT TO MAKE MOVE

function makeMove(event) {

  console.log(turn);

  let currentCell = parseInt(event.currentTarget.firstElementChild.dataset.id);

  let cellToAddToken = document.querySelector(`[data-id='${currentCell}']`);

  if (cellToAddToken.innerHTML !== "") {

    console.log("This cell is already taken.");

    return;

  } else {

    if (currentPlayer() === "X") {

      cellToAddToken.textContent = currentPlayer();

      gameBoard[currentCell] = "X";

    } else {

      cellToAddToken.textContent = currentPlayer();

      gameBoard[currentCell] = "O";

    }

  }

  // CHECK IF WE HAVE A WINNER

  isWinner();

  // Update turn count so next player can choose

  turn++;

  // CHANGE BOARD HEADER INFO

  changeBoardHeaderNames();

}

function checkIfTie() {

  if (turn > 7) {

    alert("game over a tie");

  }

}

function isWinner() {

  const winningSequences = [

    [0, 1, 2],

    [3, 4, 5],

    [6, 7, 8],

    [0, 3, 6],

    [1, 4, 7],

    [2, 5, 8],

    [0, 4, 8],

    [2, 4, 6],

  ];

  winningSequences.forEach((winningCombos) => {

    let cell1 = winningCombos[0];

    let cell2 = winningCombos[1];

    let cell3 = winningCombos[2];

    if (

      gameBoard[cell1] === currentPlayer() &&

      gameBoard[cell2] === currentPlayer() &&

      gameBoard[cell3] === currentPlayer()

    ) {

      const cells = document.querySelectorAll(".board__cell");

      cells.forEach((cell) => {

        let cellId = cell.firstElementChild.dataset.id;

        if (cellId == cell1 || cellId == cell2 || cellId == cell3) {

          cell.classList.add("board__cell--winner");

        }

      });

      let currentPlayerText = document.querySelector(".board___player-turn");

      if (currentPlayer() === "X") {

        currentPlayerText.innerHTML = `

          <div class="congratulations">Congratulations ${playerX.name}</div>

          <div class="u-r-winner">You are our winner!</div>

        `;

        winner = true;

        removeCellClickListener();

        return true;

      } else {

        currentPlayerText.innerHTML = `

          <div class="congratulations">Congratulations ${playerY.name}</div>

          <div class="u-r-winner">You are our winner!</div>

        `;

        winner = true;

        removeCellClickListener();

        return true;

      }

    }

  });

  if (!winner) {

    checkIfTie();

  }

  return false;

}

function changeBoardHeaderNames() {

  if (!winner) {

    let currentPlayerText = document.querySelector(".board___player-turn");

    if (currentPlayer() === "X") {

      currentPlayerText.innerHTML = `

        <span class="name--style">${playerX.name}</span>, you are up!

        <div class="u-r-winner"></div>

      `;

    } else {

      currentPlayerText.innerHTML = `

        <span class="name--style">${playerY.name}</span>, you are up.

        <div class="u-r-winner"></div>

      `;

    }

  }

}

function resetBoard() {

  console.log("resetting");

  gameBoard = ["", "", "", "", "", "", "", "", ""];

  let cellToAddToken = document.querySelectorAll(".letter");

  cellToAddToken.forEach((square) => {

    square.textContent = "";

    square.parentElement.classList.remove("board__cell--winner");

  });

  turn = 0;

  winner = false;

  let currentPlayerText = document.querySelector(".board___player-turn");

  currentPlayerText.innerHTML = `

    <span class="name--style">${playerX.name}</span>, you are up!

    <div class="u-r-winner"></div>

  `;

  addCellClickListener();

}

function addCellClickListener() {

  const cells = document.querySelectorAll(".board__cell");

  cells.forEach((cell) => {

    cell.addEventListener("click", makeMove);

  });

}

function removeCellClickListener() {

  let allCells = document.querySelectorAll(".board__cell");

  allCells.forEach((cell) => {

    cell.removeEventListener("click", makeMove);

  });

}

  • The“use strict” gives an error when a variable is declared without specifying its type. This leads to cleaner code.
  • We add a listener that loads our game.
  • Initialize the gameboard as an array of empty strings.
  • Initialize the turn to the value of 0. It keeps track of a user’s turn.
  • Set winner to false initially.
  • Then, we define a function player that takes a parameter, name. And then returns it. 
  • We also define the variables for storing player names.
  • Initialize app by creating an app() function:
  • This function creates an input field variable that selects the input-field HTML element
  • We also attach events to start the game and reset the game button.
  • Define a function that handles adding players, by doing the following:
  • We first check if both the input fields are entered, if not we show an alert instead of proceeding forward.
  • If both user names are entered then we hide the input form and show the game board.
  • We store the usernames and then call the ‘buildBoard()’ function.
  • Define a function ‘currentPlayer()’ that returns the current player by checking if the turn is even or odd.
  • Also, add an event listener that resizes the game board if the browser resizes.
  • Next, we define a function ‘onResize()’ that resizes the game board whenever the browser resizes.
  • We then define a function ‘buildBoard()’ that builds the game board, the following way:
  • We first reset the container.
  • Then call the following functions:
  1. onResize()
  2. addCellClickListener()
  3. changeBoardHeaderNames()
  • We define a function makeMove() that add a value to a selected HTML cell element:
  • If the cell already has some value, we don’t allow the user to enter a new value.
  • Else, we check if the player is X or O, if X, the cell gets the value X, otherwise O.
  • We then check if there is a winner.
  • Update the turn so the next player can play.
  • Change the board header according to the player.
  • We define another function ‘isWinner()’ that checks and declares the winner:
  • We first store the winning sequences in an array.
  • Then, we take 3 cells at a time and check if all the cells within the winning sequence belong to the same player.
  • If they do, we declare that user as the winner.
  • To display the player name, we check if it is player X or player O, then according to that we display the player name in the header along with the congratulations message, and return true. 
  • If there is no winner, we call the function checkIfTie() and return false.
  • We then define a function changeBoardHeaderNames() that changes the player names in the header:
  • If there is no winner, this function changes the header content to the player name whose turn is next.
  • We also define a function resetBoard() that resets a board:
  • Gameboard cells are set to array of blank strings.
  • We set all the values to default, set turn to 0. And winner to false, to restart the game.
  • In the end, call addCellClickListener() so it listens when the user clicks on a cell.
  • In the end, we define functions for adding and removing cell click listeners, that respond whenever a user clicks on a cell.

app.css

This file contains the code that we use to stylize the elements of our Tic-Tac-Toe game. Let’s go through the stylesheet and understand all the styles applied to this project.

* {

  margin: 0;

  padding: 0;

  font-family: "Helvetica", sans-serif;

  box-sizing: border-box;

}

body {

  background-image: url("../assets/img1.jpg");

  background-color: #cccccc; /* Used if the image is unavailable */

  height: 800px; /* You must set a specified height */

  background-position: center;/* Center the image */

  background-repeat: no-repeat; /* Do not repeat the image */

  background-size: cover; /* Resize the background image to cover the entire container */

}

div.relative {

  position: absolute;

  top: 760px;

  right: 120px;

}

.hide-container {

  display: none;

}

.header {

  color: #eee;

  text-align: center;

  margin: 15px 0;

  font-family: "Permanent Marker";

}

.enter-players {

  color: #eee;

  margin: 0 auto;

  width: 80%;

  text-align: center;

  position: relative;

}

.input-field {

  border: 2px solid #000;

  outline: none;

  padding: 4px 8px;

  margin: 0 0 10px 4px;

  font-size: 18px;   

}

.input-field:focus {

  border: 2px solid #E15E32;

}

.submit-btn {

  border: 2px solid #000;

  padding: 8px 8px;

  font-size: 18px;

  width: 250px;

  border-radius: 5px;

  margin-top: 10px;

  background-color: #fff;

}

.submit-btn:active,

.submit-btn:focus {

  outline: none;

  border: 2px solid #E15E32;

}

.submit-btn:hover {

  background-color: #ece9e9;

}

.board___player-turn {

  color: #eee;

  text-align: center;

  margin: 10px 0 10px;

  height: 54px;

}

.name--style {

  color: #eee;

  font-size: 22px;

}

.board__container {

  width: 40%;

  background-color: cadetblue;

  margin: 0 auto;

  font-size: 0;

  border: 2px solid #000;

  -webkit-box-shadow: 3px 3px 3px 0px rgba(0,0,0,0.75);

  -moz-box-shadow: 3px 3px 3px 0px rgba(0,0,0,0.75);

  box-shadow: 3px 3px 3px 0px rgba(0,0,0,0.75);

}

.board__cell {

  width: calc(100% / 3);

  display: inline-block;

  font-size: 40px;

  text-align: center;

  border: 2px solid #000;

  padding: 20px;

  vertical-align: top;

  font-family: "Permanent Marker";

}

.board__cell--winner {

  background-color: #f9738a;

}

.letter {

  color: #eee;

  position: relative;

  top: 50%;

  transform: translateY(-50%);

  font-family: "Permanent Marker";

}

/* WINNER CONTAINER */

.reset {

  text-align: center;

  margin: 20px auto 0;

}

.reset--hidden {

  display: none;

}

.replay-btn {

  width: 25%;

    padding: 10px 20px;

    border: 2px solid #000;

    border-radius: 5px;

    outline: none;

    letter-spacing: 0;

    text-transform: uppercase;

    font-size: 16px;

    margin-top: 12px;

    word-spacing: 3px;

    background-color: #fff;

}

.replay-btn:hover,

.replay-btn:active {

  outline: none;

  color: #fff;

  background-color: #000;

}

.congratulations {

  font-size: 24px;

}

.u-r-winner {

  font-size: 18px;

  height: 18px;

  line-height: 18px;

  margin: 2px 0;

}

@media only screen and (max-width: 767px) {

  .board__cell {

    font-size: 16px;

    padding: 5px;

  }

  .replay-btn {

    width: 50%;

  }

}

This CSS stylesheet takes care of the styling aspect of the following elements in our JavaScript game:

      • Global style
      • Body
      • Simplilearn logo position
      • Container styles
      • Header styles
      • Input field styles
      • Submit button styles
      • Tic-tac-toe board styles
      • Board X, O styles
      • Reset button styles
      • Other text styles
      • Lastly, a couple of adaptive CSS styles for board and replay buttons

End Result

The game should look and feel like this in the end, though you are free to tweak the logic and style of this game and make it your own!

JavaScript_Game_Tic-Tac-Toe%28End_Result%29

Fig: JavaScript Game: Tic-Tac-Toe (End Result)

Hope you learned the basics of JavaScript games and enjoyed going through this ‘Introduction to JavaScript Games’ article.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Get Ahead of the Curve and Master JavaScript Today

Are you wondering how you can gain the skills necessary to take advantage of JavaScript’s immense popularity now that you are familiar with JavaScript Games? We have your back! We offer a comprehensive JavaScript Training Course, which will help you become career-ready upon completion. 

To learn more, check out our Youtube video that provides a quick introduction to JavaScript Games and explains how to implement develop games using JavaScript. If you’re an aspiring web and mobile developer, JavaScript training will broaden your skills and career horizons.

Do you have any questions for us? Please mention it in the comments section of this ‘Introduction to JavaScript Games’ article and we'll have our experts answer it for you.

About the Author

Taha SufiyanTaha Sufiyan

Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.