Tic Tac Toe Game

To create a Tic Tac Toe game in HTML, you will need to use HTML, CSS and JavaScript. In this tutorial, we will create a responsive Tic Tac Toe game that can be played on desktop and mobile devices.

HTML

First, let's set up the HTML for our game board. We will create a 3x3 grid using the HTML 'table' element.

<table id='board'>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

CSS

Next, let's add some basic styles to make our game board look more appealing.

#board {
  border-collapse: collapse;
  margin: 0 auto;
}

#board td {
  border: 1px solid #333;
  font-size: 48px;
  height: 100px;
  text-align: center;
  vertical-align: middle;
  width: 100px;
}

#board td:hover {
  background: #eee;
  cursor: pointer;
}

JavaScript

Now, let's write the JavaScript code to make the game work. We will use the 'onclick' event to detect when a player clicks on a cell, and then we will update the cell with the player's symbol (X or O).

var currentPlayer = 'X';

function play(cell) {
  if (cell.innerHTML === '') {
    cell.innerHTML = currentPlayer;
    checkWin();
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
  }
}

function checkWin() {
  var board = document.getElementById('board');
  var cells = board.getElementsByTagName('td');
  var winningCombos = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (var i = 0; i < winningCombos.length; i++) {
    var combo = winningCombos[i];
    if (cells[combo[0]].innerHTML === currentPlayer &&
        cells[combo[1]].innerHTML === currentPlayer &&
        cells[combo[2]].innerHTML === currentPlayer) {
      alert(currentPlayer + ' wins!');
      reset();
      return;
    }
  }
}

function reset() {
  var board = document.getElementById('board');
  var cells = board.getElementsByTagName('td');
  for (var i = 0; i < cells.length; i++) {
    cells[i].innerHTML = '';
  }
  currentPlayer = 'X';
}

Conclusion

That's it! You now have a working Tic Tac Toe game that can be played on desktop and mobile devices. Feel free to customize the styles and add more features to the game.

How to Create a Tic Tac Toe Game with HTML, CSS, and JavaScript

原文地址: https://www.cveoy.top/t/topic/lnlg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录