space-invaders.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /**
  2. * Space Invaders game extension - play with /invaders command
  3. * Uses Kitty keyboard protocol for smooth movement (press/release detection)
  4. */
  5. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  6. import { isKeyRelease, Key, matchesKey, visibleWidth } from "@earendil-works/pi-tui";
  7. const GAME_WIDTH = 60;
  8. const GAME_HEIGHT = 24;
  9. const TICK_MS = 50;
  10. const PLAYER_Y = GAME_HEIGHT - 2;
  11. const ALIEN_ROWS = 5;
  12. const ALIEN_COLS = 11;
  13. const ALIEN_START_Y = 2;
  14. type Point = { x: number; y: number };
  15. interface Bullet extends Point {
  16. direction: -1 | 1; // -1 = up (player), 1 = down (alien)
  17. }
  18. interface Alien extends Point {
  19. type: number; // 0, 1, 2 for different alien types
  20. alive: boolean;
  21. }
  22. interface Shield {
  23. x: number;
  24. segments: boolean[][]; // 4x3 grid of destructible segments
  25. }
  26. interface GameState {
  27. player: { x: number; lives: number };
  28. aliens: Alien[];
  29. alienDirection: 1 | -1;
  30. alienMoveCounter: number;
  31. alienMoveDelay: number;
  32. alienDropping: boolean;
  33. bullets: Bullet[];
  34. shields: Shield[];
  35. score: number;
  36. highScore: number;
  37. level: number;
  38. gameOver: boolean;
  39. victory: boolean;
  40. alienShootCounter: number;
  41. }
  42. interface KeyState {
  43. left: boolean;
  44. right: boolean;
  45. fire: boolean;
  46. }
  47. function createShields(): Shield[] {
  48. const shields: Shield[] = [];
  49. const shieldPositions = [8, 22, 36, 50];
  50. for (const x of shieldPositions) {
  51. shields.push({
  52. x,
  53. segments: [
  54. [true, true, true, true],
  55. [true, true, true, true],
  56. [true, false, false, true],
  57. ],
  58. });
  59. }
  60. return shields;
  61. }
  62. function createAliens(): Alien[] {
  63. const aliens: Alien[] = [];
  64. for (let row = 0; row < ALIEN_ROWS; row++) {
  65. const type = row === 0 ? 2 : row < 3 ? 1 : 0;
  66. for (let col = 0; col < ALIEN_COLS; col++) {
  67. aliens.push({
  68. x: 4 + col * 5,
  69. y: ALIEN_START_Y + row * 2,
  70. type,
  71. alive: true,
  72. });
  73. }
  74. }
  75. return aliens;
  76. }
  77. function createInitialState(highScore = 0, level = 1): GameState {
  78. return {
  79. player: { x: Math.floor(GAME_WIDTH / 2), lives: 3 },
  80. aliens: createAliens(),
  81. alienDirection: 1,
  82. alienMoveCounter: 0,
  83. alienMoveDelay: Math.max(5, 20 - level * 2),
  84. alienDropping: false,
  85. bullets: [],
  86. shields: createShields(),
  87. score: 0,
  88. highScore,
  89. level,
  90. gameOver: false,
  91. victory: false,
  92. alienShootCounter: 0,
  93. };
  94. }
  95. class SpaceInvadersComponent {
  96. private state: GameState;
  97. private keys: KeyState = { left: false, right: false, fire: false };
  98. private interval: ReturnType<typeof setInterval> | null = null;
  99. private onClose: () => void;
  100. private onSave: (state: GameState | null) => void;
  101. private tui: { requestRender: () => void };
  102. private cachedLines: string[] = [];
  103. private cachedWidth = 0;
  104. private version = 0;
  105. private cachedVersion = -1;
  106. private paused: boolean;
  107. private fireCooldown = 0;
  108. private playerMoveCounter = 0;
  109. // Opt-in to key release events for smooth movement
  110. wantsKeyRelease = true;
  111. constructor(
  112. tui: { requestRender: () => void },
  113. onClose: () => void,
  114. onSave: (state: GameState | null) => void,
  115. savedState?: GameState,
  116. ) {
  117. this.tui = tui;
  118. if (savedState && !savedState.gameOver && !savedState.victory) {
  119. this.state = savedState;
  120. this.paused = true;
  121. } else {
  122. this.state = createInitialState(savedState?.highScore);
  123. this.paused = false;
  124. this.startGame();
  125. }
  126. this.onClose = onClose;
  127. this.onSave = onSave;
  128. }
  129. private startGame(): void {
  130. this.interval = setInterval(() => {
  131. if (!this.state.gameOver && !this.state.victory) {
  132. this.tick();
  133. this.version++;
  134. this.tui.requestRender();
  135. }
  136. }, TICK_MS);
  137. }
  138. private tick(): void {
  139. // Player movement (smooth, every other tick)
  140. this.playerMoveCounter++;
  141. if (this.playerMoveCounter >= 2) {
  142. this.playerMoveCounter = 0;
  143. if (this.keys.left && this.state.player.x > 2) {
  144. this.state.player.x--;
  145. }
  146. if (this.keys.right && this.state.player.x < GAME_WIDTH - 3) {
  147. this.state.player.x++;
  148. }
  149. }
  150. // Fire cooldown
  151. if (this.fireCooldown > 0) this.fireCooldown--;
  152. // Player shooting
  153. if (this.keys.fire && this.fireCooldown === 0) {
  154. const playerBullets = this.state.bullets.filter((b) => b.direction === -1);
  155. if (playerBullets.length < 2) {
  156. this.state.bullets.push({ x: this.state.player.x, y: PLAYER_Y - 1, direction: -1 });
  157. this.fireCooldown = 8;
  158. }
  159. }
  160. // Move bullets
  161. this.state.bullets = this.state.bullets.filter((bullet) => {
  162. bullet.y += bullet.direction;
  163. return bullet.y >= 0 && bullet.y < GAME_HEIGHT;
  164. });
  165. // Alien movement
  166. this.state.alienMoveCounter++;
  167. if (this.state.alienMoveCounter >= this.state.alienMoveDelay) {
  168. this.state.alienMoveCounter = 0;
  169. this.moveAliens();
  170. }
  171. // Alien shooting
  172. this.state.alienShootCounter++;
  173. if (this.state.alienShootCounter >= 30) {
  174. this.state.alienShootCounter = 0;
  175. this.alienShoot();
  176. }
  177. // Collision detection
  178. this.checkCollisions();
  179. // Check victory
  180. if (this.state.aliens.every((a) => !a.alive)) {
  181. this.state.victory = true;
  182. }
  183. }
  184. private moveAliens(): void {
  185. const aliveAliens = this.state.aliens.filter((a) => a.alive);
  186. if (aliveAliens.length === 0) return;
  187. if (this.state.alienDropping) {
  188. // Drop down
  189. for (const alien of aliveAliens) {
  190. alien.y++;
  191. if (alien.y >= PLAYER_Y - 1) {
  192. this.state.gameOver = true;
  193. return;
  194. }
  195. }
  196. this.state.alienDropping = false;
  197. } else {
  198. // Check if we need to change direction
  199. const minX = Math.min(...aliveAliens.map((a) => a.x));
  200. const maxX = Math.max(...aliveAliens.map((a) => a.x));
  201. if (
  202. (this.state.alienDirection === 1 && maxX >= GAME_WIDTH - 3) ||
  203. (this.state.alienDirection === -1 && minX <= 2)
  204. ) {
  205. this.state.alienDirection *= -1;
  206. this.state.alienDropping = true;
  207. } else {
  208. // Move horizontally
  209. for (const alien of aliveAliens) {
  210. alien.x += this.state.alienDirection;
  211. }
  212. }
  213. }
  214. // Speed up as fewer aliens remain
  215. const aliveCount = aliveAliens.length;
  216. if (aliveCount <= 5) {
  217. this.state.alienMoveDelay = 1;
  218. } else if (aliveCount <= 10) {
  219. this.state.alienMoveDelay = 2;
  220. } else if (aliveCount <= 20) {
  221. this.state.alienMoveDelay = 3;
  222. }
  223. }
  224. private alienShoot(): void {
  225. const aliveAliens = this.state.aliens.filter((a) => a.alive);
  226. if (aliveAliens.length === 0) return;
  227. // Find bottom-most alien in each column
  228. const columns = new Map<number, Alien>();
  229. for (const alien of aliveAliens) {
  230. const existing = columns.get(alien.x);
  231. if (!existing || alien.y > existing.y) {
  232. columns.set(alien.x, alien);
  233. }
  234. }
  235. // Random column shoots
  236. const shooters = Array.from(columns.values());
  237. if (shooters.length > 0 && this.state.bullets.filter((b) => b.direction === 1).length < 3) {
  238. const shooter = shooters[Math.floor(Math.random() * shooters.length)];
  239. this.state.bullets.push({ x: shooter.x, y: shooter.y + 1, direction: 1 });
  240. }
  241. }
  242. private checkCollisions(): void {
  243. const bulletsToRemove = new Set<Bullet>();
  244. for (const bullet of this.state.bullets) {
  245. // Player bullets hitting aliens
  246. if (bullet.direction === -1) {
  247. for (const alien of this.state.aliens) {
  248. if (alien.alive && Math.abs(bullet.x - alien.x) <= 1 && bullet.y === alien.y) {
  249. alien.alive = false;
  250. bulletsToRemove.add(bullet);
  251. const points = [10, 20, 30][alien.type];
  252. this.state.score += points;
  253. if (this.state.score > this.state.highScore) {
  254. this.state.highScore = this.state.score;
  255. }
  256. break;
  257. }
  258. }
  259. }
  260. // Alien bullets hitting player
  261. if (bullet.direction === 1) {
  262. if (Math.abs(bullet.x - this.state.player.x) <= 1 && bullet.y === PLAYER_Y) {
  263. bulletsToRemove.add(bullet);
  264. this.state.player.lives--;
  265. if (this.state.player.lives <= 0) {
  266. this.state.gameOver = true;
  267. }
  268. }
  269. }
  270. // Bullets hitting shields
  271. for (const shield of this.state.shields) {
  272. const relX = bullet.x - shield.x;
  273. const relY = bullet.y - (PLAYER_Y - 5);
  274. if (relX >= 0 && relX < 4 && relY >= 0 && relY < 3) {
  275. if (shield.segments[relY][relX]) {
  276. shield.segments[relY][relX] = false;
  277. bulletsToRemove.add(bullet);
  278. }
  279. }
  280. }
  281. }
  282. this.state.bullets = this.state.bullets.filter((b) => !bulletsToRemove.has(b));
  283. }
  284. handleInput(data: string): void {
  285. const released = isKeyRelease(data);
  286. // Pause handling
  287. if (this.paused && !released) {
  288. if (matchesKey(data, Key.escape) || data === "q" || data === "Q") {
  289. this.dispose();
  290. this.onClose();
  291. return;
  292. }
  293. this.paused = false;
  294. this.startGame();
  295. return;
  296. }
  297. // ESC to pause and save
  298. if (!released && matchesKey(data, Key.escape)) {
  299. this.dispose();
  300. this.onSave(this.state);
  301. this.onClose();
  302. return;
  303. }
  304. // Q to quit without saving
  305. if (!released && (data === "q" || data === "Q")) {
  306. this.dispose();
  307. this.onSave(null);
  308. this.onClose();
  309. return;
  310. }
  311. // Movement keys (track press/release state)
  312. if (matchesKey(data, Key.left) || data === "a" || data === "A" || matchesKey(data, "a")) {
  313. this.keys.left = !released;
  314. }
  315. if (matchesKey(data, Key.right) || data === "d" || data === "D" || matchesKey(data, "d")) {
  316. this.keys.right = !released;
  317. }
  318. // Fire key
  319. if (matchesKey(data, Key.space) || data === " " || data === "f" || data === "F" || matchesKey(data, "f")) {
  320. this.keys.fire = !released;
  321. }
  322. // Restart on game over or victory
  323. if (!released && (this.state.gameOver || this.state.victory)) {
  324. if (data === "r" || data === "R" || data === " ") {
  325. const highScore = this.state.highScore;
  326. const nextLevel = this.state.victory ? this.state.level + 1 : 1;
  327. this.state = createInitialState(highScore, nextLevel);
  328. this.keys = { left: false, right: false, fire: false };
  329. this.onSave(null);
  330. this.version++;
  331. this.tui.requestRender();
  332. }
  333. }
  334. }
  335. invalidate(): void {
  336. this.cachedWidth = 0;
  337. }
  338. render(width: number): string[] {
  339. if (width === this.cachedWidth && this.cachedVersion === this.version) {
  340. return this.cachedLines;
  341. }
  342. const lines: string[] = [];
  343. // Colors
  344. const dim = (s: string) => `\x1b[2m${s}\x1b[22m`;
  345. const green = (s: string) => `\x1b[32m${s}\x1b[0m`;
  346. const red = (s: string) => `\x1b[31m${s}\x1b[0m`;
  347. const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`;
  348. const cyan = (s: string) => `\x1b[36m${s}\x1b[0m`;
  349. const magenta = (s: string) => `\x1b[35m${s}\x1b[0m`;
  350. const white = (s: string) => `\x1b[97m${s}\x1b[0m`;
  351. const bold = (s: string) => `\x1b[1m${s}\x1b[22m`;
  352. const boxWidth = GAME_WIDTH;
  353. const boxLine = (content: string) => {
  354. const contentLen = visibleWidth(content);
  355. const padding = Math.max(0, boxWidth - contentLen);
  356. return dim(" │") + content + " ".repeat(padding) + dim("│");
  357. };
  358. // Top border
  359. lines.push(this.padLine(dim(` ╭${"─".repeat(boxWidth)}╮`), width));
  360. // Header
  361. const title = `${bold(green("SPACE INVADERS"))}`;
  362. const scoreText = `Score: ${bold(yellow(String(this.state.score)))}`;
  363. const highText = `Hi: ${bold(yellow(String(this.state.highScore)))}`;
  364. const levelText = `Lv: ${bold(cyan(String(this.state.level)))}`;
  365. const livesText = `${red("♥".repeat(this.state.player.lives))}`;
  366. const header = `${title} │ ${scoreText} │ ${highText} │ ${levelText} │ ${livesText}`;
  367. lines.push(this.padLine(boxLine(header), width));
  368. // Separator
  369. lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width));
  370. // Game grid
  371. for (let y = 0; y < GAME_HEIGHT; y++) {
  372. let row = "";
  373. for (let x = 0; x < GAME_WIDTH; x++) {
  374. let char = " ";
  375. let colored = false;
  376. // Check aliens
  377. for (const alien of this.state.aliens) {
  378. if (alien.alive && alien.y === y && Math.abs(alien.x - x) <= 1) {
  379. const sprites = [
  380. x === alien.x ? "▼" : "╲╱"[x < alien.x ? 0 : 1],
  381. x === alien.x ? "◆" : "╱╲"[x < alien.x ? 0 : 1],
  382. x === alien.x ? "☆" : "◄►"[x < alien.x ? 0 : 1],
  383. ];
  384. const colors = [green, cyan, magenta];
  385. char = colors[alien.type](sprites[alien.type]);
  386. colored = true;
  387. break;
  388. }
  389. }
  390. // Check shields
  391. if (!colored) {
  392. for (const shield of this.state.shields) {
  393. const relX = x - shield.x;
  394. const relY = y - (PLAYER_Y - 5);
  395. if (relX >= 0 && relX < 4 && relY >= 0 && relY < 3) {
  396. if (shield.segments[relY][relX]) {
  397. char = dim("█");
  398. colored = true;
  399. }
  400. break;
  401. }
  402. }
  403. }
  404. // Check player
  405. if (!colored && y === PLAYER_Y && Math.abs(x - this.state.player.x) <= 1) {
  406. if (x === this.state.player.x) {
  407. char = white("▲");
  408. } else {
  409. char = white("═");
  410. }
  411. colored = true;
  412. }
  413. // Check bullets
  414. if (!colored) {
  415. for (const bullet of this.state.bullets) {
  416. if (bullet.x === x && bullet.y === y) {
  417. char = bullet.direction === -1 ? yellow("│") : red("│");
  418. colored = true;
  419. break;
  420. }
  421. }
  422. }
  423. row += colored ? char : " ";
  424. }
  425. lines.push(this.padLine(dim(" │") + row + dim("│"), width));
  426. }
  427. // Separator
  428. lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width));
  429. // Footer
  430. let footer: string;
  431. if (this.paused) {
  432. footer = `${yellow(bold("PAUSED"))} Press any key to continue, ${bold("Q")} to quit`;
  433. } else if (this.state.gameOver) {
  434. footer = `${red(bold("GAME OVER!"))} Press ${bold("R")} to restart, ${bold("Q")} to quit`;
  435. } else if (this.state.victory) {
  436. footer = `${green(bold("VICTORY!"))} Press ${bold("R")} for level ${this.state.level + 1}, ${bold("Q")} to quit`;
  437. } else {
  438. footer = `←→ or AD to move, ${bold("SPACE")}/F to fire, ${bold("ESC")} pause, ${bold("Q")} quit`;
  439. }
  440. lines.push(this.padLine(boxLine(footer), width));
  441. // Bottom border
  442. lines.push(this.padLine(dim(` ╰${"─".repeat(boxWidth)}╯`), width));
  443. this.cachedLines = lines;
  444. this.cachedWidth = width;
  445. this.cachedVersion = this.version;
  446. return lines;
  447. }
  448. private padLine(line: string, width: number): string {
  449. const visibleLen = line.replace(/\x1b\[[0-9;]*m/g, "").length;
  450. const padding = Math.max(0, width - visibleLen);
  451. return line + " ".repeat(padding);
  452. }
  453. dispose(): void {
  454. if (this.interval) {
  455. clearInterval(this.interval);
  456. this.interval = null;
  457. }
  458. }
  459. }
  460. const INVADERS_SAVE_TYPE = "space-invaders-save";
  461. export default function (pi: ExtensionAPI) {
  462. pi.registerCommand("invaders", {
  463. description: "Play Space Invaders!",
  464. handler: async (_args, ctx) => {
  465. if (ctx.mode !== "tui") {
  466. ctx.ui.notify("Space Invaders requires interactive mode", "error");
  467. return;
  468. }
  469. // Load saved state from session
  470. const entries = ctx.sessionManager.getEntries();
  471. let savedState: GameState | undefined;
  472. for (let i = entries.length - 1; i >= 0; i--) {
  473. const entry = entries[i];
  474. if (entry.type === "custom" && entry.customType === INVADERS_SAVE_TYPE) {
  475. savedState = entry.data as GameState;
  476. break;
  477. }
  478. }
  479. await ctx.ui.custom((tui, _theme, _kb, done) => {
  480. return new SpaceInvadersComponent(
  481. tui,
  482. () => done(undefined),
  483. (state) => {
  484. pi.appendEntry(INVADERS_SAVE_TYPE, state);
  485. },
  486. savedState,
  487. );
  488. });
  489. },
  490. });
  491. }