UNPKG

namastejs

Version:

A spiritual greeting from your JavaScript code. Because every function deserves a 'Namaste 🙏'

111 lines (92 loc) 2.68 kB
const readline = require("readline"); const { SCREEN_WIDTH, SCREEN_HEIGHT, HEADER_HEIGHT } = require("./config"); const EXPLOSION_FRAMES = ["*", "x"]; function drawBorder() { const top = "╔" + "═".repeat(SCREEN_WIDTH) + "╗"; const bottom = "╚" + "═".repeat(SCREEN_WIDTH) + "╝"; const empty = "║" + " ".repeat(SCREEN_WIDTH) + "║"; readline.cursorTo(process.stdout, 0, 0); process.stdout.write(top); for (let i = 0; i < SCREEN_HEIGHT + HEADER_HEIGHT; i++) { readline.cursorTo(process.stdout, 0, i + 1); process.stdout.write(empty); } readline.cursorTo(process.stdout, 0, SCREEN_HEIGHT + HEADER_HEIGHT + 1); process.stdout.write(bottom); } function drawHeader(state) { const headerText = ` SCORE: ${state.score} LIVES: ${"♥".repeat( state.lives )} LEVEL: ${state.level} `; readline.cursorTo(process.stdout, 1, 1); process.stdout.write(headerText.padEnd(SCREEN_WIDTH, " ")); } function createGrid() { return Array.from({ length: SCREEN_HEIGHT }, () => Array(SCREEN_WIDTH).fill(" ") ); } function drawPlayer(grid, player) { if (!player) return; const row = grid.length - 1 - player.yOffset; if ( row >= 0 && row < grid.length && player.x >= 0 && player.x < SCREEN_WIDTH ) { grid[row][player.x] = player.sprite; } } function drawEnemies(grid, enemies) { enemies.forEach((e) => { if (!e.alive) return; if (e.y >= 0 && e.y < grid.length) { grid[e.y][e.x] = e.sprite; } }); } function drawBullets(grid, bullets) { bullets.forEach((b) => { if (b.y >= 0 && b.y < grid.length) { grid[b.y][b.x] = b.sprite; } }); } function drawExplosions(grid, explosions) { explosions.forEach((e) => { if (e.y >= 0 && e.y < grid.length && e.x >= 0 && e.x < grid[0].length) { grid[e.y][e.x] = EXPLOSION_FRAMES[e.frame] || "*"; } e.frame++; e.ttl--; }); } function drawEnemyBullets(grid, bullets) { bullets.forEach((b) => { if (b.y >= 0 && b.y < grid.length && b.x >= 0 && b.x < grid[0].length) { grid[b.y][b.x] = b.sprite; } }); } function renderGrid(grid) { for (let row = 0; row < SCREEN_HEIGHT; row++) { readline.cursorTo(process.stdout, 1, HEADER_HEIGHT + 1 + row); process.stdout.write(grid[row].join("")); } } function parkCursor() { readline.cursorTo(process.stdout, 0, SCREEN_HEIGHT + HEADER_HEIGHT + 3); } module.exports = { drawBorder, drawHeader, createGrid, renderGrid, parkCursor, drawPlayer, drawEnemies, drawBullets, drawExplosions, drawEnemyBullets, };