Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <h1>Tic-Tac-Toe</h1>
- <div id="board">
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- <div class="cell"></div>
- </div>
- <button id="reset">Reset Game</button>
- <script src="script.js"></script>
- <style>
- #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;
- }
- </style>
- <script>
- let board = [
- ['', '', ''],
- ['', '', ''],
- ['', '', '']
- ];
- let currentPlayer = 'X';
- document.addEventListener('DOMContentLoaded', () => {
- const cells = document.querySelectorAll('.cell');
- cells.forEach((cell, index) => {
- cell.addEventListener('click', function() {
- const row = Math.floor(index / 3);
- const col = index % 3;
- makeMove(row, col, cell);
- });
- });
- document.getElementById('reset').addEventListener('click', resetGame);
- });
- function makeMove(row, col, cell) {
- if (board[row][col] === '') {
- board[row][col] = currentPlayer;
- cell.textContent = currentPlayer;
- if (checkWinner(row, col)) {
- alert(`${currentPlayer} wins!`);
- resetGame();
- } else {
- currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
- }
- }
- }
- function checkWinner(row, col) {
- return (
- checkRow(row) ||
- checkCol(col) ||
- checkDiagonalFromTopLeft() ||
- checkDiagonalFromTopRight()
- );
- }
- function checkRow(row) {
- return board[row].every(cell => cell === currentPlayer);
- }
- function checkCol(col) {
- return board.every(row => row[col] === currentPlayer);
- }
- function checkDiagonalFromTopLeft() {
- return board.every((row, index) => row[index] === currentPlayer);
- }
- function checkDiagonalFromTopRight() {
- return board.every((row, index) => row[2 - index] === currentPlayer);
- }
- function resetGame() {
- board = [
- ['', '', ''],
- ['', '', ''],
- ['', '', '']
- ];
- currentPlayer = 'X';
- document.querySelectorAll('.cell').forEach(cell => (cell.textContent = ''));
- }
- </script>
Advertisement
Add Comment
Please, Sign In to add comment