Creating Tic Tac Toe with HTML, CSS, and JavaScript II Buffoon Sachin

Introduction:
Tic Tac Toe is a timeless game loved by people of all ages. In this blog, I'll walk you through the steps to create your own Tic Tac Toe game using HTML, CSS, and JavaScript. At last code is given.

Step 1: Setting Up the HTML Structure:
Start by creating a new HTML file and defining the basic structure. Add a heading to indicate the title of your game, and create a container for the game board. You can use a simple grid layout using div elements to represent the Tic Tac Toe grid.

Step 2: Styling the Game Board with CSS:
Once the HTML structure is in place, apply some CSS styles to make the game board visually appealing. You can use CSS to define the size of the grid cells, add borders, and customize the appearance of X and O symbols.

Step 3: Implementing the Game Logic with JavaScript:
Now comes the exciting part – adding the game logic using JavaScript. You'll need to handle player moves, check for a winner after each move, and implement the AI for the computer player (if desired). Break down the game logic into smaller functions, such as handling player input, checking for win conditions, and resetting the game state.

Step 4: Testing and Debugging:
Once you've implemented the game logic, it's time to test your Tic Tac Toe game. Play the game yourself to ensure that it behaves as expected and handles different scenarios correctly. Use browser developer tools to debug any issues and refine your code as needed.

Step 5: Enhancements and Customizations: 

With the basic game functionality in place, you can add enhancements and customizations to make your Tic Tac Toe game stand out. Consider adding features like sound effects, animations for player moves, or implementing a responsive design for mobile devices. Get creative and make the game your own! 

You can use the below code just copy and paste it !!

<!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>

<style>

  /* Styles for the heading */

  .heading {

    text-align: center;

    font-family: Cambria, serif;

    font-size: 36px;

    margin-bottom: 20px;

  }

  /* Styles for the game board and centering */

  body, html {

    height: 100%;

    margin: 0;

    display: flex;

    flex-direction: column;

    align-items: center;

    justify-content: center;

    background-color: #f5f5f5;

  }

  .board {

    display: grid;

    grid-template-columns: repeat(3, 100px);

    grid-template-rows: repeat(3, 100px);

    gap: 10px; /* Add gap between cells */

    text-align: center;

  }

  .board div {

    width: 100px;

    height: 100px;

    border: 3px solid #333; /* Make border thicker */

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 3em; /* Increase font size */

    cursor: pointer;

    transition: background-color 0.3s, color 0.3s; /* Add transition effect */

  }

  .board div:hover {

    background-color: #ddd; /* Change background color on hover */

    box-shadow: 0 0 10px #7ed957; /* Add glow effect on hover */

  }

</style>

</head>

<body>

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

<div class="board" id="board">

  <!-- Game board cells will be dynamically generated by JavaScript -->

</div>


<script>

// Game state variables

var humanPlayer = "X";

var computerPlayer = "O";

var currentPlayer = humanPlayer;

var boardState = [

  ["", "", ""],

  ["", "", ""],

  ["", "", ""]

];


// Function to generate the game board

function generateBoard() {

  var board = document.getElementById("board");

  var cells = "";

  for (var row = 0; row < 3; row++) {

    for (var col = 0; col < 3; col++) {

      cells += `<div onclick="makeMove(${row}, ${col})" id="cell_${row}_${col}"></div>`;

    }

  }

  board.innerHTML = cells;

}


// Function to make a move

function makeMove(row, col) {

  var cell = document.getElementById(`cell_${row}_${col}`);

  if (boardState[row][col] === "" && currentPlayer === humanPlayer) {

    boardState[row][col] = humanPlayer;

    cell.textContent = humanPlayer;

    if (checkWinner(humanPlayer)) {

      alert(`Player ${humanPlayer} wins!`);

      resetGame();

    } else if (checkDraw()) {

      alert("It's a draw!");

      resetGame();

    } else {

      currentPlayer = computerPlayer;

      setTimeout(makeComputerMove, 500); // Add delay before computer move

    }

  }

}


// Function to make a move for the computer

function makeComputerMove() {

  var bestScore = -Infinity;

  var move;

  for (var row = 0; row < 3; row++) {

    for (var col = 0; col < 3; col++) {

      if (boardState[row][col] === "") {

        boardState[row][col] = computerPlayer;

        var score = minimax(boardState, 0, false);

        boardState[row][col] = "";

        if (score > bestScore) {

          bestScore = score;

          move = { row, col };

        }

      }

    }

  }

  var row = move.row;

  var col = move.col;

  boardState[row][col] = computerPlayer;

  document.getElementById(`cell_${row}_${col}`).textContent = computerPlayer;

  if (checkWinner(computerPlayer)) {

    alert(`Player ${computerPlayer} wins!`);

    resetGame();

  } else if (checkDraw()) {

    alert("It's a draw!");

    resetGame();

  } else {

    currentPlayer = humanPlayer;

  }

}


// Minimax algorithm for AI

function minimax(board, depth, isMaximizing) {

  var result = checkResult();

  if (result !== null) {

    return result;

  }

  if (isMaximizing) {

    var bestScore = -Infinity;

    for (var row = 0; row < 3; row++) {

      for (var col = 0; col < 3; col++) {

        if (board[row][col] === "") {

          board[row][col] = computerPlayer;

          var score = minimax(board, depth + 1, false);

          board[row][col] = "";

          bestScore = Math.max(score, bestScore);

        }

      }

    }

    return bestScore;

  } else {

    var bestScore = Infinity;

    for (var row = 0; row < 3; row++) {

      for (var col = 0; col < 3; col++) {

        if (board[row][col] === "") {

          board[row][col] = humanPlayer;

          var score = minimax(board, depth + 1, true);

          board[row][col] = "";

          bestScore = Math.min(score, bestScore);

        }

      }

    }

    return bestScore;

  }

}


// Function to check for a winner or draw

function checkResult() {

  for (var i = 0; i < 3; i++) {

    if (boardState[i][0] !== "" && boardState[i][0] === boardState[i][1] && boardState[i][1] === boardState[i][2]) {

      return (boardState[i][0] === humanPlayer) ? -10 : 10;

    }

    if (boardState[0][i] !== "" && boardState[0][i] === boardState[1][i] && boardState[1][i] === boardState[2][i]) {

      return (boardState[0][i] === humanPlayer) ? -10 : 10;

    }

  }

  if (boardState[0][0] !== "" && boardState[0][0] === boardState[1][1] && boardState[1][1] === boardState[2][2]) {

    return (boardState[0][0] === humanPlayer) ? -10 : 10;

  }

  if (boardState[0][2] !== "" && boardState[0][2] === boardState[1][1] && boardState[1][1] === boardState[2][0]) {

    return (boardState[0][2] === humanPlayer) ? -10 : 10;

  }

  // Check for draw

  for (var row = 0; row < 3; row++) {

    for (var col = 0; col < 3; col++) {

      if (boardState[row][col] === "") {

        return null;

      }

    }

  }

  return 0; // Draw

}


// Function to check for a winner

function checkWinner(player) {

  var result = checkResult();

  return (result === 10 && player === computerPlayer) || (result === -10 && player === humanPlayer);

}


// Function to check for a draw

function checkDraw() {

  return checkResult() === 0;

}


// Function to reset the game

function resetGame() {

  currentPlayer = humanPlayer;

  boardState = [

    ["", "", ""],

    ["", "", ""],

    ["", "", ""]

  ];

  generateBoard();

}


// Generate the initial game board

generateBoard();

</script>

</body>

</html>

Hope you enjoy the blog. Feel free to share your doubt . 

Thanks.

Comments

Popular posts from this blog

How to Hide Drive Letters on Your PC ll Buffoon Sachin

Set passoword on Folder without using software II Buffoon Sachin

What is Hacker in Details