javascriptCopy code
function* alienGenerator(maxX) {
while (true) {
yield Math.floor(Math.random() * maxX);
}
}
function drawGame(playerPosition, bulletPosition, alienPosition, maxX) {
for (let i = 0; i < maxX; i++) {
if (bulletPosition !== null && bulletPosition === i) {
process.stdout.write('|');
} else if (alienPosition === i) {
process.stdout.write('v');
} else {
process.stdout.write(' ');
}
}
console.log();
for (let i = 0; i < maxX; i++) {
if (i === playerPosition) {
process.stdout.write('^');
} else {
process.stdout.write(' ');
}
}
console.log("\n----------------");
}
const maxX = 10;
let playerPosition = Math.floor(maxX / 2);
let bulletPosition = null;
const aliens = alienGenerator(maxX);
let alienPosition = aliens.next().value;
let alienDistance = 0;
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (str, key) => {
if (key.ctrl && key.name === 'c') {
process.exit();
} else if (key.name === 'left' && playerPosition > 0) {
playerPosition--;
} else if (key.name === 'right' && playerPosition < maxX - 1) {
playerPosition++;
} else if (key.name === 'space' && bulletPosition === null) {
bulletPosition = playerPosition;
}
});
setInterval(() => {
if (bulletPosition !== null) {
if (bulletPosition === alienPosition) {
console.log("Hit!");
alienPosition = aliens.next().value;
alienDistance = 0;
bulletPosition = null;
} else if (bulletPosition === 0) {
bulletPosition = null;
} else {
bulletPosition--;
}
}
alienDistance++;
if (alienDistance === maxX - 1) {
console.log("Game Over! Alien invaded.");
process.exit();
}
drawGame(playerPosition, bulletPosition, alienPosition, maxX);
}, 500);