tic tac toe in javascript

Here's an example implementation of Tic Tac Toe game in JavaScript:

index.tsx
// Set up the game board
const board = [
  ['_', '_', '_'],
  ['_', '_', '_'],
  ['_', '_', '_']
];

// Prints the game board
function printBoard() {
  console.log(board[0].join(' | '));
  console.log(board[1].join(' | '));
  console.log(board[2].join(' | '));
}

// Check if a player has won
function checkWin(player) {
  // Check all rows
  for (let i = 0; i < 3; i++) {
    if (board[i][0] === player && board[i][1] === player && board[i][2] === player) {
      return true;
    }
  }

  // Check all columns
  for (let j = 0; j < 3; j++) {
    if (board[0][j] === player && board[1][j] === player && board[2][j] === player) {
      return true;
    }
  }

  // Check diagonal from top left to bottom right
  if (board[0][0] === player && board[1][1] === player && board[2][2] === player) {
    return true;
  }

  // Check diagonal from bottom left to top right
  if (board[0][2] === player && board[1][1] === player && board[2][0] === player) {
    return true;
  }

  return false;
}

// Play the game
let currentPlayer = 'X';

while (true) {
  console.log(`Player ${currentPlayer}'s turn:`);
  printBoard();

  // Ask player for input
  let row;
  let col;

  do {
    row = parseInt(prompt('Enter row (0-2): '));
    col = parseInt(prompt('Enter column (0-2): '));
  } while (isNaN(row) || isNaN(col) || row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] !== '_');

  // Update the board
  board[row][col] = currentPlayer;

  // Check if the game is won
  if (checkWin(currentPlayer)) {
    console.log(`Player ${currentPlayer} wins!`);
    break;
  }

  // Switch to other player
  currentPlayer = currentPlayer === 'X' ? 'O' : 'X';

  // Check if the game is tied
  if (board.every(row => row.every(col => col !== '_'))) {
    console.log('Tie!');
    break;
  }
}
1784 chars
78 lines

This implementation uses a 2-dimensional array to represent the Tic Tac Toe board, and prompts the players for input using prompt() method. It also checks if a player has won or if there is a tie after every turn.

Note that this implementation doesn't include any styling or graphics, it's just a simple console-based game. To make it more visually appealing, you would need to add HTML, CSS and possibly a JavaScript library like jQuery or React to handle the UI.

related categories

gistlibby LogSnag