Skip to content

Instantly share code, notes, and snippets.

@th3terrorist
Last active September 23, 2021 07:57
Show Gist options
  • Save th3terrorist/edbd1066d43117810376084b6282ff2a to your computer and use it in GitHub Desktop.
Save th3terrorist/edbd1066d43117810376084b6282ff2a to your computer and use it in GitHub Desktop.
A memory game on your terminal.
const fs = require("fs");
const memoryGame = () => {
class util {
static readNum() {
let buffer = Buffer.alloc(4);
buffer.fill(0);
fs.readSync(0 /*stdin*/, buffer, 0, 4);
return buffer[0] % 48; //( ͡° ͜ʖ ͡°)
}
}
const data = {
seq: [],
points: 0
}
const game = () => {
const NO_NUMB = 15;
const timer = ms => new Promise(res => setTimeout(res, ms));
const step = async () => {
await timer(5 * 1000);
}
const roll = () => {
let no = Math.floor(Math.random() * 5) + 1;
data.seq = [...data.seq, no];
return no;
}
const reset = () => {
data.points = 0;
data.seq = [];
console.log("Game over, wanna try again? (Yes: 1, No: 0)");
let no = util.readNum();
if(no !== 1) process.exit();
}
const match = (num) => {
let pts = data.points;
if(data.seq[pts] === num) {
data.points = ++pts;
return true
};
reset();
return false;
}
async function loop() {
for(let i = 0; i < NO_NUMB; i++) roll();
console.log("You have 5 seconds to memorize this sequence:");
console.log(data.seq);
await step();
console.clear();
console.log("Type here the sequence:");
for(let i = 0; i < data.seq.length; i++) {
if(!match(util.readNum())){
console.clear();
return;
}
}
}
return loop;
}
(async () => {
while(true) {
let loop = game();
await loop();
}
})();
}
memoryGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment