Site icon DataFlair

JavaScript Project – Tic Tac Toe Game Console Version

Full Stack Web Development Courses with Real-time projects Start Now!!

Program 1

// Project for Tic Tac Toe Game

const ps=require("prompt-sync")
const prompt=ps({sigint:true})

// 2 D Array (Matrix)
const board =
 [
    [' ', ' ', ' '],
    [' ', ' ', ' '],
    [' ', ' ', ' ']
  ];
  
  
  function printBoard() {
    
    console.clear();
    console.log("*******Welcome to Tic Tac Toe!*********\n");
    console.log("-------------");
    for (let i = 0; i < 3; i++) 
        {
         console.log(`| ${board[i][0]} | ${board[i][1]} | ${board[i][2]} |`);
         console.log("-------------");
    }
  }
  
  function isBoardFull() {
    for (let row of board) {
      if (row.includes(' ')) return false;
    }
    return true;
  }
              
  function checkWin(player) {           
    // Rows and columns
    for (let i = 0; i < 3; i++) {
      if (
        (board[i][0] === player && board[i][1] === player && board[i][2] === player) ||
        (board[0][i] === player && board[1][i] === player && board[2][i] === player)
      ) return true;
    }
  
    // Diagonals
    if (
      (board[0][0] === player && board[1][1] === player && board[2][2] === player) ||
      (board[0][2] === player && board[1][1] === player && board[2][0] === player)
    ) return true;
  
    return false;
  }
  
  

  // Start the game
  currentPlayer = 'X'

  printBoard();

  while(1)
  {
     console.log(`Player ${currentPlayer}: enter your move (row and column: 1-3):`);
     row=parseInt(prompt())
     col=parseInt(prompt())
     row--    // Array 0 index
     col--
     if (row < 0 || row > 2 || col < 0 || col > 2) 
        {
            console.log("Invalid input. Try again.\n");
            continue;
        }
        if (board[row][col] != ' ') 
            {
                console.log("Cell already taken. Try again.\n");
                continue;
            }
    
            board[row][col] = currentPlayer;
            printBoard();
    
            if (checkWin(currentPlayer))   
            {
                console.log(`Congrats Player ${currentPlayer} wins!\n`);
                break;
            } 
            else if (isBoardFull()) 
             {
                console.log("It's a draw!\n");
                break;
            }
             else 
             {
                currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
            }
        }

 

Exit mobile version