a tik-tok-toe game in javascript

Here's a basic example of how to create a tic-tac-toe game in JavaScript:

HTML:

<div id="game">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
257 chars
12 lines

CSS:

#game {
  width: 150px;
  height: 150px;
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 50px;
  height: 50px;
  border: 1px solid black;
}
147 chars
13 lines

JS:

const boxes = document.querySelectorAll('.box');
let currentPlayer = 'X';

boxes.forEach(box => {
  box.addEventListener('click', () => {
    if (!box.textContent) {
      box.textContent = currentPlayer;
      checkResult();
      currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
    }
  });
});

function checkResult() {
  const topLeft = boxes[0].textContent;
  const topMiddle = boxes[1].textContent;
  const topRight = boxes[2].textContent;
  const middleLeft = boxes[3].textContent;
  const middleMiddle = boxes[4].textContent;
  const middleRight = boxes[5].textContent;
  const bottomLeft = boxes[6].textContent;
  const bottomMiddle = boxes[7].textContent;
  const bottomRight = boxes[8].textContent;

  if (topLeft && topLeft === topMiddle && topLeft === topRight) {
    alert(`${topLeft} wins!`);
  } else if (middleLeft && middleLeft === middleMiddle && middleLeft === middleRight) {
    alert(`${middleLeft} wins!`);
  } else if (bottomLeft && bottomLeft === bottomMiddle && bottomLeft === bottomRight) {
    alert(`${bottomLeft} wins!`);
  } else if (topLeft && topLeft === middleLeft && topLeft === bottomLeft) {
    alert(`${topLeft} wins!`);
  } else if (topMiddle && topMiddle === middleMiddle && topMiddle === bottomMiddle) {
    alert(`${topMiddle} wins!`);
  } else if (topRight && topRight === middleRight && topRight === bottomRight) {
    alert(`${topRight} wins!`);
  } else if (topLeft && topLeft === middleMiddle && topLeft === bottomRight) {
    alert(`${topLeft} wins!`);
  } else if (topRight && topRight === middleMiddle && topRight === bottomLeft) {
    alert(`${topRight} wins!`);
  }
}
1622 chars
43 lines

This is just a basic implementation of a tic-tac-toe game using a simple HTML and CSS layout and vanilla JavaScript for the game logic. There are many ways to improve this implementation, such as adding a reset button, better styling, and more robust logic for checking the win condition.

related categories

gistlibby LogSnag