Skip to content

Instantly share code, notes, and snippets.

@mcgingras
Created April 19, 2023 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcgingras/d1c85a85add7d6afa3d38fffabfd7107 to your computer and use it in GitHub Desktop.
Save mcgingras/d1c85a85add7d6afa3d38fffabfd7107 to your computer and use it in GitHub Desktop.
Terminal Tic Tac Toe (tttt)
const prompt = require("prompt");
prompt.start();
const state = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "],
];
const printBoard = (state) => {
console.log("\n");
state.forEach((row, i) => {
console.log(row.join("|"));
if (i < 2) {
console.log("-----");
}
});
console.log("\n");
};
const gameLoop = (isX) => {
printBoard(state);
prompt.get(["move"], function (err, result) {
const move = result.move;
const [row, col] = move.split(",");
if (row < 0 || row > 2 || col < 0 || col > 2) {
console.log(
"Invalid move. Please format move as 0-2,0-2. For example, 1,1"
);
gameLoop(isX);
return;
}
if (state[row][col] !== " ") {
console.log("Invalid move. That cell is already taken.");
gameLoop(isX);
return;
}
state[row][col] = isX ? "X" : "O";
if (checkWinner(state)) {
console.log(isX ? "X" : "O", "wins!");
printBoard(state);
return;
}
if (checkDraw(state)) {
console.log("Draw!");
printBoard(state);
return;
}
gameLoop(!isX);
});
};
const checkDraw = (state) => {
// check if every cell is filled
// if so, return true
// this means all moves have been taken, and we have no winner, so draw
return state.every((row) => row.every((cell) => cell !== " "));
};
checkWinner = (state) => {
for (let i = 0; i < 3; i++) {
if (
state[i][0] === state[i][1] &&
state[i][1] === state[i][2] &&
state[i][0] !== " "
) {
return true;
}
if (
state[0][i] === state[1][i] &&
state[1][i] === state[2][i] &&
state[0][i] !== " "
) {
return true;
}
if (
state[0][0] === state[1][1] &&
state[1][1] === state[2][2] &&
state[0][0] !== " "
) {
return true;
}
if (
state[0][2] === state[1][1] &&
state[1][1] === state[2][0] &&
state[0][2] !== " "
) {
return true;
}
}
return false;
};
gameLoop(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment