// Declare the game board as a 2D array
var board = [ ["", "", ""],
["", "", ""],
["", "", ""]
];
// Declare the players and the current player
var players = ["X", "O"];
var currentPlayer = players[0];
// A function to place a move on the board
function placeMove(row, col) {
if (board[row][col] === "") {
board[row][col] = currentPlayer;
switchPlayer();
} else {
console.log("This space is already taken.");
}
}
// A function to switch to the next player
function switchPlayer() {
currentPlayer = (currentPlayer === players[0]) ? players[1] : players[0];
}
// A function to check if someone has won the game
function checkWin() {
// Check rows
for (var i = 0; i < 3; i++) {
if (board[i][0] === board[i][1] && board[i][1] === board[i][2] && board[i][0] !== "") {
return board[i][0];
}
}
// Check columns
for (var j = 0; j < 3; j++) {
if (board[0][j] === board[1][j] && board[1][j] === board[2][j] && board[0][j] !== "") {
return board[0][j];
}
}
// Check diagonals
if (board[0][0] === board[1][1] && board[1][1] === board[2][2] && board[0][0] !== "") {
return board[0][0];
}
if (board[0][2] === board[1][1] && board[1][1] === board[2][0] && board[0][2] !== "") {
return board[0][2];
}
// No one has won yet
return "";
}
// The main game loop
while (true) {
// Print the game board
for (var i = 0; i < 3; i++) {
console.log(board[i].join(" | "));
}
// Get the next move from the player
var row = parseInt(prompt("Enter row for player " + currentPlayer + " (0-2):"));
var col = parseInt(prompt("Enter column for player " + currentPlayer + " (0-2):"));
// Place the move on the board
placeMove(row, col);
// Check if someone has won the game
var winner = checkWin();
if (winner !== "") {
console.log("Player " + winner + " wins!");
break;
}
}