• Register
Post tutorial Report RSS Make A Simple Tic Tac Toe Game

Crafting a Simple Tic-Tac-Toe Game with HTML, CSS, and JavaScript.

Posted by on - Basic Other

Hey there, Urbanimp here. Today I want to take you through the steps on how to create a basic Tic Tac Toe game in HTML, CSS & JavaScript. This is a very basic version but it gets the job done. Let's get into it.

create tic tac toe

I'm going to break down the code into digestible parts, explaining each step along the way so you can understand the logic and maybe even modify it to your liking later on. The first step is to boot up your code editor. My code editor of choice is Visual Studio Code by Microsoft.

HTML: Structuring the Game Board

Create a new HTML file and let’s set up a basic HTML5 structure.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tic-Tac-Toe</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="game-board">
    <!-- Tic-tac-toe grid will be here -->
  </div>
  <script src="script.js"></script>
</body>
</html>

Notice how we've got a div with an ID of game-board. This is where our 3x3 grid for Tic-Tac-Toe will go. We’ve also linked a CSS file for styling and a JavaScript file for the game logic.

CSS: Styling the Board and Cells

Now, let’s add some basic styling. Create a styles.css file and add the following:

#game-board {
  width: 300px;
  height: 300px;
  display: grid;
  grid-template-columns: 100px 100px 100px;
}

.cell {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  text-align: center;
  vertical-align: middle;
  font-size: 32px;
}

We use the CSS Grid layout to create our 3x3 grid and style each cell. The .cell class will be used for each of the 9 cells in our Tic-Tac-Toe board.

[removed] Preparing the Battlefield

Create a script.js file for the JavaScript part. First, let's set some initial variables.

let board = [
  ['', '', ''],
  ['', '', ''],
  ['', '', '']
];

let currentPlayer = 'X'; // X will always start first

The board array will keep track of the game state, and currentPlayer keeps track of who is supposed to play next.

Initialize the Board

function init() {
  let gameBoard = document.getElementById('game-board');

  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      let cell = document.createElement('div');
      cell.className = 'cell';
      cell.addEventListener('click', cellClicked);
      cell.dataset.row = i;
      cell.dataset.col = j;
      gameBoard.appendChild(cell);
    }
  }
}

Here we create each cell as a div element, attach a click event listener (cellClicked, which we'll define soon), and use data-* attributes to store the row and column indices.

Handling Cell Clicks

When a cell is clicked, we need to update the board state and check for a winner.

function cellClicked(event) {
  let row = event.target.dataset.row;
  let col = event.target.dataset.col;

  if (board[row][col] === '') {
    board[row][col] = currentPlayer;
    event.target.textContent = currentPlayer;
    if (checkWinner(row, col)) {
      alert(`${currentPlayer} wins!`);
      return;
    }
    currentPlayer = (currentPlayer === 'X') ? 'O' : 'X';
  }
}

We check if the cell is empty (board[row][col] === ''). If it is, we update the cell with the currentPlayer and then check for a winner.

Checking for a Winner

function checkWinner(row, col) {
  // Check row
  if (board[row][0] === currentPlayer && board[row][1] === currentPlayer && board[row][2] === currentPlayer) {
    return true;
  }
  // Check column
  if (board[0][col] === currentPlayer && board[1][col] === currentPlayer && board[2][col] === currentPlayer) {
    return true;
  }
  // Check diagonals
  if (row === col && board[0][0] === currentPlayer && board[1][1] === currentPlayer && board[2][2] === currentPlayer) {
    return true;
  }
  if (Number(row) + Number(col) === 2 && board[0][2] === currentPlayer && board[1][1] === currentPlayer && board[2][0] === currentPlayer) {
    return true;
  }
  return false;
}

This function checks if there is a winning state in the row, column, or diagonals based on the most recently clicked cell.

Boot it up!

Last but not least, let's initialize our game board when the page loads:

window.onload = init;

This ensures that the init() function is called, setting up our game board. And voila! You have just built a Tic-Tac-Toe game with HTML, CSS, and JavaScript. Feel free to improve or extend this basic implementation.

Happy coding! Until next time.

urbanimp

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: