// Set up the game board as an array let board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]; // Define a function to print the game board function printBoard() { console.log(`${board[0]} | ${board[1]} | ${board[2]}`); console.log(`${board[3]} | ${board[4]} | ${board[5]}`); console.log(`${board[6]} | ${board[7]} | ${board[8]}`); } // Define a function to handle a player's turn function takeTurn(player) { console.log(`${player}'s turn.`); let position = prompt("Choose a position from 1-9:"); position -= 1; while (position < 0 || position > 8 || board[position] !== "-") { position = prompt("Invalid input or position already taken. Choose a different position:"); position -= 1; } board[position] = player; printBoard(); } // Define a function to check if the game is over function checkGameOver() { // Check for a win if ((board[0] === board[1] && board[1] === board[2] && board[0] !== "-") || (board[3] === board[4] && board[4] === board[5] && board[3] !== "-") || (board[6] === board[7] && board[7] === board[8] && board[6] !== "-") || (board[0] === board[3] && board[3] === board[6] && board[0] !== "-") || (board[1] === board[4] && board[4] === board[7] && board[1] !== "-") || (board[2] === board[5] && board[5] === board[8] && board[2] !== "-") || (board[0] === board[4] && board[4] === board[8] && board[0] !== "-") || (board[2] === board[4] && board[4] === board[6] && board[2] !== "-")) { return "win"; } // Check for a tie else if (!board.includes("-")) { return "tie"; } // Game is not over else { return "play"; } } // Define the main game loop function main() { printBoard(); let currentPlayer = "X"; let gameOver = false; while (!gameOver) { takeTurn(currentPlayer); let gameResult = checkGameOver(); if (gameResult === "win") { console.log(`${currentPlayer} wins!`); gameOver = true; } else if (gameResult === "tie") { console.log("It's a tie!"); gameOver = true; } else { // Switch to the other player currentPlayer = currentPlayer === "X" ? "O" : "X"; } } } // Start the game main();