space-invaders.js

class Enemy { constructor(x, y, width = 3, height = 2) { this.x = x; this.y = y; this.width = width; this.height = height; } } let intervalId; const gameState = { direction: 1, enemies: generateEnemies(), gridWidth: 70, playerX: 0, yPosition: 4, }; function generateEnemies(rows = 5, cols = 11, startX = 0, startY = 0, spacingX = 6, spacingY = 3) { const enemies = []; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { let x = startX + col * spacingX; let y = startY + row * spacingY; enemies.push(new Enemy(x, y)); } } return enemies; } function printEnemies(gridWidth = gameState.gridWidth, gridHeight = 20) { let grid = Array.from({ length: gridHeight }, () => Array(gridWidth).fill(" ")); gameState.enemies.forEach(enemy => { for (let dx = 0; dx < enemy.width; dx++) { for (let dy = 0; dy < enemy.height; dy++) { let x = enemy.x + dx; let y = enemy.y + dy; if (x < gridWidth && y < gridHeight) { grid[y][x] = "X"; } } } }); console.clear(); grid.forEach(row => console.log(row.join(""))); } function moveEnemies() { let moveDown = false; for (const enemy of gameState.enemies) { const tooFarRight = enemy.x + enemy.width >= gameState.gridWidth if ( (tooFarRight && gameState.direction === 1) || enemy.x <= 0 && gameState.direction === -1 ) { moveDown = true; break; } } if (moveDown) { gameState.enemies = gameState.enemies.map((enemy) => ({ ...enemy, y: enemy.y + 1 })); gameState.direction = gameState.direction === 1 ? -1 : 1; gameState.yPosition = gameState.yPosition - 1 if (gameState.yPosition === 0) { console.clear(); console.log("Game Over!") clearInterval(intervalId) process.exit(0) } } else { gameState.enemies = gameState.enemies.map((enemy) => ({ ...enemy, x: enemy.x += gameState.direction })) } } function gameLoop() { moveEnemies(); printEnemies(); } intervalId = setInterval(gameLoop, 500); process.stdin.setRawMode(true); process.stdin.resume(); process.stdin.setEncoding("utf-8"); process.stdin.on("data", (key) => { if (key === "\u0003") process.exit(); if (key === "\u001b[D" && gameState.playerX > 0) gameState.playerX--; if (key === "\u001b[C" && gameState.playerX < gameState.gridWidth - 1) gameState.playerX++; // if (key === " ") fireShot() });
Space Invaders

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.