snake.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * Snake game extension - play snake with /snake command
  3. */
  4. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  5. import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
  6. const GAME_WIDTH = 40;
  7. const GAME_HEIGHT = 15;
  8. const TICK_MS = 100;
  9. type Direction = "up" | "down" | "left" | "right";
  10. type Point = { x: number; y: number };
  11. interface GameState {
  12. snake: Point[];
  13. food: Point;
  14. direction: Direction;
  15. nextDirection: Direction;
  16. score: number;
  17. gameOver: boolean;
  18. highScore: number;
  19. }
  20. function createInitialState(): GameState {
  21. const startX = Math.floor(GAME_WIDTH / 2);
  22. const startY = Math.floor(GAME_HEIGHT / 2);
  23. return {
  24. snake: [
  25. { x: startX, y: startY },
  26. { x: startX - 1, y: startY },
  27. { x: startX - 2, y: startY },
  28. ],
  29. food: spawnFood([{ x: startX, y: startY }]),
  30. direction: "right",
  31. nextDirection: "right",
  32. score: 0,
  33. gameOver: false,
  34. highScore: 0,
  35. };
  36. }
  37. function spawnFood(snake: Point[]): Point {
  38. let food: Point;
  39. do {
  40. food = {
  41. x: Math.floor(Math.random() * GAME_WIDTH),
  42. y: Math.floor(Math.random() * GAME_HEIGHT),
  43. };
  44. } while (snake.some((s) => s.x === food.x && s.y === food.y));
  45. return food;
  46. }
  47. class SnakeComponent {
  48. private state: GameState;
  49. private interval: ReturnType<typeof setInterval> | null = null;
  50. private onClose: () => void;
  51. private onSave: (state: GameState | null) => void;
  52. private tui: { requestRender: () => void };
  53. private cachedLines: string[] = [];
  54. private cachedWidth = 0;
  55. private version = 0;
  56. private cachedVersion = -1;
  57. private paused: boolean;
  58. constructor(
  59. tui: { requestRender: () => void },
  60. onClose: () => void,
  61. onSave: (state: GameState | null) => void,
  62. savedState?: GameState,
  63. ) {
  64. this.tui = tui;
  65. if (savedState && !savedState.gameOver) {
  66. // Resume from saved state, start paused
  67. this.state = savedState;
  68. this.paused = true;
  69. } else {
  70. // New game or saved game was over
  71. this.state = createInitialState();
  72. if (savedState) {
  73. this.state.highScore = savedState.highScore;
  74. }
  75. this.paused = false;
  76. this.startGame();
  77. }
  78. this.onClose = onClose;
  79. this.onSave = onSave;
  80. }
  81. private startGame(): void {
  82. this.interval = setInterval(() => {
  83. if (!this.state.gameOver) {
  84. this.tick();
  85. this.version++;
  86. this.tui.requestRender();
  87. }
  88. }, TICK_MS);
  89. }
  90. private tick(): void {
  91. // Apply queued direction change
  92. this.state.direction = this.state.nextDirection;
  93. // Calculate new head position
  94. const head = this.state.snake[0];
  95. let newHead: Point;
  96. switch (this.state.direction) {
  97. case "up":
  98. newHead = { x: head.x, y: head.y - 1 };
  99. break;
  100. case "down":
  101. newHead = { x: head.x, y: head.y + 1 };
  102. break;
  103. case "left":
  104. newHead = { x: head.x - 1, y: head.y };
  105. break;
  106. case "right":
  107. newHead = { x: head.x + 1, y: head.y };
  108. break;
  109. }
  110. // Check wall collision
  111. if (newHead.x < 0 || newHead.x >= GAME_WIDTH || newHead.y < 0 || newHead.y >= GAME_HEIGHT) {
  112. this.state.gameOver = true;
  113. return;
  114. }
  115. // Check self collision
  116. if (this.state.snake.some((s) => s.x === newHead.x && s.y === newHead.y)) {
  117. this.state.gameOver = true;
  118. return;
  119. }
  120. // Move snake
  121. this.state.snake.unshift(newHead);
  122. // Check food collision
  123. if (newHead.x === this.state.food.x && newHead.y === this.state.food.y) {
  124. this.state.score += 10;
  125. if (this.state.score > this.state.highScore) {
  126. this.state.highScore = this.state.score;
  127. }
  128. this.state.food = spawnFood(this.state.snake);
  129. } else {
  130. this.state.snake.pop();
  131. }
  132. }
  133. handleInput(data: string): void {
  134. // If paused (resuming), wait for any key
  135. if (this.paused) {
  136. if (matchesKey(data, "escape") || data === "q" || data === "Q") {
  137. // Quit without clearing save
  138. this.dispose();
  139. this.onClose();
  140. return;
  141. }
  142. // Any other key resumes
  143. this.paused = false;
  144. this.startGame();
  145. return;
  146. }
  147. // ESC to pause and save
  148. if (matchesKey(data, "escape")) {
  149. this.dispose();
  150. this.onSave(this.state);
  151. this.onClose();
  152. return;
  153. }
  154. // Q to quit without saving (clears saved state)
  155. if (data === "q" || data === "Q") {
  156. this.dispose();
  157. this.onSave(null); // Clear saved state
  158. this.onClose();
  159. return;
  160. }
  161. // Arrow keys or WASD
  162. if (matchesKey(data, "up") || data === "w" || data === "W") {
  163. if (this.state.direction !== "down") this.state.nextDirection = "up";
  164. } else if (matchesKey(data, "down") || data === "s" || data === "S") {
  165. if (this.state.direction !== "up") this.state.nextDirection = "down";
  166. } else if (matchesKey(data, "right") || data === "d" || data === "D") {
  167. if (this.state.direction !== "left") this.state.nextDirection = "right";
  168. } else if (matchesKey(data, "left") || data === "a" || data === "A") {
  169. if (this.state.direction !== "right") this.state.nextDirection = "left";
  170. }
  171. // Restart on game over
  172. if (this.state.gameOver && (data === "r" || data === "R" || data === " ")) {
  173. const highScore = this.state.highScore;
  174. this.state = createInitialState();
  175. this.state.highScore = highScore;
  176. this.onSave(null); // Clear saved state on restart
  177. this.version++;
  178. this.tui.requestRender();
  179. }
  180. }
  181. invalidate(): void {
  182. this.cachedWidth = 0;
  183. }
  184. render(width: number): string[] {
  185. if (width === this.cachedWidth && this.cachedVersion === this.version) {
  186. return this.cachedLines;
  187. }
  188. const lines: string[] = [];
  189. // Each game cell is 2 chars wide to appear square (terminal cells are ~2:1 aspect)
  190. const cellWidth = 2;
  191. const effectiveWidth = Math.min(GAME_WIDTH, Math.floor((width - 4) / cellWidth));
  192. const effectiveHeight = GAME_HEIGHT;
  193. // Colors
  194. const dim = (s: string) => `\x1b[2m${s}\x1b[22m`;
  195. const green = (s: string) => `\x1b[32m${s}\x1b[0m`;
  196. const red = (s: string) => `\x1b[31m${s}\x1b[0m`;
  197. const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`;
  198. const bold = (s: string) => `\x1b[1m${s}\x1b[22m`;
  199. const boxWidth = effectiveWidth * cellWidth;
  200. // Helper to pad content inside box
  201. const boxLine = (content: string) => {
  202. const contentLen = visibleWidth(content);
  203. const padding = Math.max(0, boxWidth - contentLen);
  204. return dim(" │") + content + " ".repeat(padding) + dim("│");
  205. };
  206. // Top border
  207. lines.push(this.padLine(dim(` ╭${"─".repeat(boxWidth)}╮`), width));
  208. // Header with score
  209. const scoreText = `Score: ${bold(yellow(String(this.state.score)))}`;
  210. const highText = `High: ${bold(yellow(String(this.state.highScore)))}`;
  211. const title = `${bold(green("SNAKE"))} │ ${scoreText} │ ${highText}`;
  212. lines.push(this.padLine(boxLine(title), width));
  213. // Separator
  214. lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width));
  215. // Game grid
  216. for (let y = 0; y < effectiveHeight; y++) {
  217. let row = "";
  218. for (let x = 0; x < effectiveWidth; x++) {
  219. const isHead = this.state.snake[0].x === x && this.state.snake[0].y === y;
  220. const isBody = this.state.snake.slice(1).some((s) => s.x === x && s.y === y);
  221. const isFood = this.state.food.x === x && this.state.food.y === y;
  222. if (isHead) {
  223. row += green("██"); // Snake head (2 chars)
  224. } else if (isBody) {
  225. row += green("▓▓"); // Snake body (2 chars)
  226. } else if (isFood) {
  227. row += red("◆ "); // Food (2 chars)
  228. } else {
  229. row += " "; // Empty cell (2 spaces)
  230. }
  231. }
  232. lines.push(this.padLine(dim(" │") + row + dim("│"), width));
  233. }
  234. // Separator
  235. lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width));
  236. // Footer
  237. let footer: string;
  238. if (this.paused) {
  239. footer = `${yellow(bold("PAUSED"))} Press any key to continue, ${bold("Q")} to quit`;
  240. } else if (this.state.gameOver) {
  241. footer = `${red(bold("GAME OVER!"))} Press ${bold("R")} to restart, ${bold("Q")} to quit`;
  242. } else {
  243. footer = `↑↓←→ or WASD to move, ${bold("ESC")} pause, ${bold("Q")} quit`;
  244. }
  245. lines.push(this.padLine(boxLine(footer), width));
  246. // Bottom border
  247. lines.push(this.padLine(dim(` ╰${"─".repeat(boxWidth)}╯`), width));
  248. this.cachedLines = lines;
  249. this.cachedWidth = width;
  250. this.cachedVersion = this.version;
  251. return lines;
  252. }
  253. private padLine(line: string, width: number): string {
  254. // Calculate visible length (strip ANSI codes)
  255. const visibleLen = line.replace(/\x1b\[[0-9;]*m/g, "").length;
  256. const padding = Math.max(0, width - visibleLen);
  257. return line + " ".repeat(padding);
  258. }
  259. dispose(): void {
  260. if (this.interval) {
  261. clearInterval(this.interval);
  262. this.interval = null;
  263. }
  264. }
  265. }
  266. const SNAKE_SAVE_TYPE = "snake-save";
  267. export default function (pi: ExtensionAPI) {
  268. pi.registerCommand("snake", {
  269. description: "Play Snake!",
  270. handler: async (_args, ctx) => {
  271. if (ctx.mode !== "tui") {
  272. ctx.ui.notify("Snake requires interactive mode", "error");
  273. return;
  274. }
  275. // Load saved state from session
  276. const entries = ctx.sessionManager.getEntries();
  277. let savedState: GameState | undefined;
  278. for (let i = entries.length - 1; i >= 0; i--) {
  279. const entry = entries[i];
  280. if (entry.type === "custom" && entry.customType === SNAKE_SAVE_TYPE) {
  281. savedState = entry.data as GameState;
  282. break;
  283. }
  284. }
  285. await ctx.ui.custom((tui, _theme, _kb, done) => {
  286. return new SnakeComponent(
  287. tui,
  288. () => done(undefined),
  289. (state) => {
  290. // Save or clear state
  291. pi.appendEntry(SNAKE_SAVE_TYPE, state);
  292. },
  293. savedState,
  294. );
  295. });
  296. },
  297. });
  298. }