code-snake 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +184 -0
  2. package/README.md +46 -0
  3. package/package.json +46 -0
  4. package/snake.js +389 -0
package/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work
75
+ to which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a
87
+ copy of this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating
90
+ that You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from
94
+ the Source form of the Work, excluding those notices that do not pertain to
95
+ any part of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
98
+ then any Derivative Works that You distribute must include a readable copy
99
+ of the attribution notices contained within such NOTICE file, excluding
100
+ those notices that do not pertain to any part of the Derivative Works, in
101
+ at least one of the following places: within a NOTICE text file distributed
102
+ as part of the Derivative Works; within the Source form or documentation,
103
+ if provided along with the Derivative Works; or, within a display generated
104
+ by the Derivative Works, if and wherever such third-party notices normally
105
+ appear. The contents of the NOTICE file are for informational purposes only
106
+ and do not modify the License. You may add Your own attribution notices
107
+ within Derivative Works that You distribute, alongside or as an addendum to
108
+ the NOTICE text from the Work, provided that such additional attribution
109
+ notices cannot be construed as modifying the License.
110
+
111
+ You may add Your own copyright statement to Your modifications and may
112
+ provide additional or different license terms and conditions for use,
113
+ reproduction, or distribution of Your modifications, or for any such
114
+ Derivative Works as a whole, provided Your use, reproduction, and
115
+ distribution of the Work otherwise complies with the conditions stated in
116
+ this License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
119
+ Contribution intentionally submitted for inclusion in the Work by You to the
120
+ Licensor shall be under the terms and conditions of this License, without any
121
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
122
+ supersede or modify the terms of any separate license agreement you may have
123
+ executed with Licensor regarding such Contributions.
124
+
125
+ 6. Trademarks. This License does not grant permission to use the trade names,
126
+ trademarks, service marks, or product names of the Licensor, except as required
127
+ for reasonable and customary use in describing the origin of the Work and
128
+ reproducing the content of the NOTICE file.
129
+
130
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
131
+ writing, Licensor provides the Work (and each Contributor provides its
132
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
133
+ KIND, either express or implied, including, without limitation, any warranties
134
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
135
+ PARTICULAR PURPOSE. You are solely responsible for determining the
136
+ appropriateness of using or redistributing the Work and assume any risks
137
+ associated with Your exercise of permissions under this License.
138
+
139
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
140
+ tort (including negligence), contract, or otherwise, unless required by
141
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
142
+ writing, shall any Contributor be liable to You for damages, including any
143
+ direct, indirect, special, incidental, or consequential damages of any character
144
+ arising as a result of this License or out of the use or inability to use the
145
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
146
+ computer failure or malfunction, or any and all other commercial damages or
147
+ losses), even if such Contributor has been advised of the possibility of such
148
+ damages.
149
+
150
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
151
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
152
+ acceptance of support, warranty, indemnity, or other liability obligations
153
+ and/or rights consistent with this License. However, in accepting such
154
+ obligations, You may act only on Your own behalf and on Your sole
155
+ responsibility, not on behalf of any other Contributor, and only if You agree to
156
+ indemnify, defend, and hold each Contributor harmless for any liability incurred
157
+ by, or claims asserted against, such Contributor by reason of your accepting any
158
+ such warranty or additional liability.
159
+
160
+ END OF TERMS AND CONDITIONS
161
+
162
+ APPENDIX: How to apply the Apache License to your work.
163
+
164
+ To apply the Apache License to your work, attach the following boilerplate
165
+ notice, with the fields enclosed by brackets "[]" replaced with your own
166
+ identifying information. (Don't include the brackets!) The text should be
167
+ enclosed in the appropriate comment syntax for the file format. We also
168
+ recommend that a file or class name and description of purpose be included on
169
+ the same "printed page" as the copyright notice for easier identification within
170
+ third-party archives.
171
+
172
+ Copyright 2026 Erdem Bircan
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # code-snake
2
+
3
+ Snake, played inside the program's own source code. **The code is the board.**
4
+
5
+ <p align="center">
6
+ <img src="assets/demo.gif" alt="code-snake gameplay">
7
+ </p>
8
+
9
+ No sprites, no box-drawing characters, no pixels. When code-snake starts, it reads
10
+ its own source file, minifies it, and lays it out as fully justified text filling
11
+ an exact rectangle. The snake exists only as *absence*: words are pushed together
12
+ and apart every frame so that a channel of whitespace moves through the live code.
13
+ Eat, and the program's text makes room for you.
14
+
15
+ ## Code as medium
16
+
17
+ Most programs treat their source as an implementation detail, the thing you look
18
+ at only when something breaks. Here the source is the material itself: the canvas,
19
+ the playfield, and the collision geometry are all the same bytes that implement
20
+ them. Edit the code and the board changes, because the board *is* the code.
21
+
22
+ This is not a quine. The program never reproduces itself; it consumes itself,
23
+ reflowing its own text around the game state as you play.
24
+
25
+ ## Run
26
+
27
+ ```sh
28
+ node snake.js
29
+ ```
30
+
31
+ Requires an interactive terminal and Node.js. No dependencies.
32
+
33
+ | Keys | |
34
+ |---|---|
35
+ | arrows / `wasd` / `hjkl` | move |
36
+ | `p` | pause |
37
+ | `r` | restart |
38
+ | `q` / `Ctrl-C` | quit |
39
+
40
+ ### Flags
41
+
42
+ | Flag | Effect |
43
+ |---|---|
44
+ | `--green` | paint the snake body green instead of pure whitespace |
45
+ | `--smoke [cols rows]` | render a single frame headless and exit (testing) |
46
+
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "code-snake",
3
+ "version": "1.0.0",
4
+ "description": "Snake, played inside its own source code. This program does not draw a board, it becomes one; the snake is the space its words leave behind. Code as medium.",
5
+ "keywords": [
6
+ "snake",
7
+ "game",
8
+ "terminal",
9
+ "cli",
10
+ "tui",
11
+ "ansi",
12
+ "text",
13
+ "justification",
14
+ "self-referential",
15
+ "code-as-medium",
16
+ "whitespace",
17
+ "art"
18
+ ],
19
+ "bin": {
20
+ "code-snake": "snake.js"
21
+ },
22
+ "main": "snake.js",
23
+ "files": [
24
+ "snake.js"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/erdembircan/code-snake.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/erdembircan/code-snake/issues"
32
+ },
33
+ "homepage": "https://github.com/erdembircan/code-snake#readme",
34
+ "author": "Erdem Bircan",
35
+ "license": "Apache-2.0",
36
+ "engines": {
37
+ "node": ">=14"
38
+ },
39
+ "license-wizard": {
40
+ "licenseId": "Apache-2.0",
41
+ "tokens": {
42
+ "[yyyy]": "2026",
43
+ "[name of copyright owner]": "Erdem Bircan"
44
+ }
45
+ }
46
+ }
package/snake.js ADDED
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ code-snake
5
+ by Erdem Bircan, 2026. Apache-2.0.
6
+
7
+ Code as medium: this program does not draw a board, it becomes one.
8
+ Source code spends its life hidden behind the screen; here it steps
9
+ out in front, and the game is played in the space it leaves behind.
10
+ Every word carries the rules that move it, and every move rearranges
11
+ the words. The player and the program wander the same page. If art
12
+ is material made self-aware, this file qualifies on a technicality.
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+
19
+ const SOURCE = fs.readFileSync(__filename, 'utf8');
20
+ const PUNCT = new Set('{}()[];,=+-*/<>!&|?:.'.split(''));
21
+
22
+ function minify(src) {
23
+ let out = '';
24
+ let q = null;
25
+ for (let i = 0; i < src.length; i++) {
26
+ const c = src[i];
27
+ if (q) { out += c; if (c === q && src[i - 1] !== '\\') q = null; continue; }
28
+ if (c === "'" || c === '"' || c === '`') { q = c; out += c; continue; }
29
+ if (/\s/.test(c)) {
30
+ while (i + 1 < src.length && /\s/.test(src[i + 1])) i++;
31
+ const prev = out[out.length - 1];
32
+ const next = src[i + 1];
33
+ if (prev && next && !PUNCT.has(prev) && !PUNCT.has(next)) out += ' ';
34
+ continue;
35
+ }
36
+ out += c;
37
+ }
38
+ return out;
39
+ }
40
+
41
+ function chunk(token) {
42
+ const MAX = 14;
43
+ const parts = [];
44
+ let rest = token;
45
+ while (rest.length > MAX) {
46
+ let cut = -1;
47
+ for (let i = MAX; i >= 4; i--) if (PUNCT.has(rest[i - 1])) { cut = i; break; }
48
+ if (cut === -1) cut = MAX;
49
+ parts.push(rest.slice(0, cut));
50
+ rest = rest.slice(cut);
51
+ }
52
+ if (rest) parts.push(rest);
53
+ return parts;
54
+ }
55
+
56
+ const TOKENS = minify(SOURCE).split(/\s+/).filter(Boolean).flatMap(chunk);
57
+ const CHAR_TOTAL = TOKENS.reduce((a, w) => a + w.length, 0);
58
+
59
+ const CELL_W = 5;
60
+ const CELL_H = 2;
61
+
62
+ function wrapRows(width) {
63
+ let rows = 1;
64
+ let used = 0;
65
+ for (const word of TOKENS) {
66
+ let len = word.length;
67
+ while (len > width) { rows++; len -= width; }
68
+ const need = (used ? 1 : 0) + len;
69
+ if (used + need <= width) used += need;
70
+ else { rows++; used = len; }
71
+ }
72
+ return rows;
73
+ }
74
+
75
+ let cols = 0;
76
+ let gw = 0;
77
+ let gh = 0;
78
+ let marginX = 0;
79
+ let marginY = 0;
80
+
81
+ function measure(fallbackCols, fallbackRows) {
82
+ const rawCols = process.stdout.columns || fallbackCols || 80;
83
+ const rawRows = process.stdout.rows || fallbackRows || 24;
84
+ const idealW = Math.round(Math.sqrt(CHAR_TOTAL * 5));
85
+ gw = Math.max(8, Math.floor(Math.min(idealW, rawCols) / CELL_W));
86
+ cols = gw * CELL_W;
87
+ gh = Math.max(6, Math.ceil(wrapRows(cols) / CELL_H) + 1);
88
+ const maxGh = Math.floor((rawRows - 1) / CELL_H);
89
+ if (gh > maxGh) gh = Math.max(6, maxGh);
90
+ marginX = Math.max(0, Math.floor((rawCols - cols) / 2));
91
+ marginY = Math.max(0, Math.floor((rawRows - 1 - gh * CELL_H) / 2));
92
+ }
93
+
94
+ const DIRS = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
95
+ const OPPOSITE = { up: 'down', down: 'up', left: 'right', right: 'left' };
96
+
97
+ let snake = [];
98
+ let dir = 'right';
99
+ let pending = [];
100
+ let food = null;
101
+ let grow = 0;
102
+ let score = 0;
103
+ let dead = false;
104
+ let paused = false;
105
+ let tickMs = 160;
106
+ let timer = null;
107
+
108
+ function reset() {
109
+ const cy = Math.floor(gh / 2);
110
+ const cx = Math.floor(gw / 2);
111
+ snake = [];
112
+ for (let i = 0; i < 4; i++) snake.push([cx - i, cy]);
113
+ dir = 'right';
114
+ pending = [];
115
+ grow = 0;
116
+ score = 0;
117
+ dead = false;
118
+ paused = false;
119
+ tickMs = 160;
120
+ placeFood();
121
+ }
122
+
123
+ function onSnake(x, y) {
124
+ return snake.some(([sx, sy]) => sx === x && sy === y);
125
+ }
126
+
127
+ function placeFood() {
128
+ let x, y;
129
+ do {
130
+ x = Math.floor(Math.random() * gw);
131
+ y = Math.floor(Math.random() * gh);
132
+ } while (onSnake(x, y));
133
+ food = [x, y];
134
+ }
135
+
136
+ function tick() {
137
+ if (dead || paused) return;
138
+ while (pending.length) {
139
+ const next = pending.shift();
140
+ if (next !== dir && next !== OPPOSITE[dir]) { dir = next; break; }
141
+ }
142
+ const [dx, dy] = DIRS[dir];
143
+ const head = [snake[0][0] + dx, snake[0][1] + dy];
144
+ const [hx, hy] = head;
145
+ if (hx < 0 || hy < 0 || hx >= gw || hy >= gh || onSnake(hx, hy)) {
146
+ dead = true;
147
+ draw();
148
+ return;
149
+ }
150
+ snake.unshift(head);
151
+ if (hx === food[0] && hy === food[1]) {
152
+ score++;
153
+ grow += 2;
154
+ tickMs = Math.max(70, tickMs - 5);
155
+ placeFood();
156
+ }
157
+ if (grow > 0) grow--; else snake.pop();
158
+ draw();
159
+ }
160
+
161
+ function loop() {
162
+ clearTimeout(timer);
163
+ tick();
164
+ timer = setTimeout(loop, tickMs);
165
+ }
166
+
167
+ let ti = 0;
168
+ let carry = [];
169
+
170
+ function nextWord() {
171
+ if (carry.length) return carry.shift();
172
+ if (ti >= TOKENS.length) return null;
173
+ return TOKENS[ti++];
174
+ }
175
+
176
+ const DIM = '\x1b[2m';
177
+ const RESET = '\x1b[0m';
178
+ const FOOD_MARK = '\x1b[0;48;5;157m' + ' '.repeat(CELL_W) + RESET + DIM;
179
+
180
+ const GREEN_BODY = process.argv.includes('--green');
181
+
182
+ function bodyMark(width) {
183
+ if (!GREEN_BODY) return ' '.repeat(width);
184
+ return '\x1b[0;48;5;34m' + ' '.repeat(width) + RESET + DIM;
185
+ }
186
+
187
+ function rowMarks(y) {
188
+ const gy = Math.floor(y / CELL_H);
189
+ const marks = [];
190
+ for (const [sx, sy] of snake) {
191
+ if (sy !== gy) continue;
192
+ marks.push({ s: sx * CELL_W, e: sx * CELL_W + CELL_W, t: 'body' });
193
+ }
194
+ if (food && food[1] === gy) {
195
+ marks.push({ s: food[0] * CELL_W, e: food[0] * CELL_W + CELL_W, t: 'food' });
196
+ }
197
+ marks.sort((a, b) => a.s - b.s);
198
+ const merged = [];
199
+ for (const m of marks) {
200
+ const last = merged[merged.length - 1];
201
+ if (last && last.t === 'body' && m.t === 'body' && m.s <= last.e) last.e = m.e;
202
+ else merged.push({ ...m });
203
+ }
204
+ return merged;
205
+ }
206
+
207
+ function justifySeg(seg) {
208
+ if (seg.w <= 0) return '';
209
+ if (seg.words.length === 0) return ' '.repeat(seg.w);
210
+ const extra = seg.w - seg.used;
211
+ const gaps = seg.words.length - 1;
212
+ if (gaps === 0) return seg.words[0] + ' '.repeat(extra);
213
+ let out = seg.words[0];
214
+ let prev = 0;
215
+ for (let i = 1; i <= gaps; i++) {
216
+ const acc = Math.floor((extra * i) / gaps);
217
+ out += ' '.repeat(1 + acc - prev) + seg.words[i];
218
+ prev = acc;
219
+ }
220
+ return out;
221
+ }
222
+
223
+ function layoutRow(marks, quota) {
224
+ const pieces = [];
225
+ let pos = 0;
226
+ for (const m of marks) {
227
+ pieces.push({ seg: true, w: m.s - pos, words: [], used: 0 });
228
+ pieces.push({ seg: false, m });
229
+ pos = m.e;
230
+ }
231
+ pieces.push({ seg: true, w: cols - pos, words: [], used: 0 });
232
+ const segs = pieces.filter(p => p.seg && p.w > 0);
233
+ const rowWords = [];
234
+ let want = 0;
235
+ while (want < quota) {
236
+ const word = nextWord();
237
+ if (word === null) break;
238
+ rowWords.push(word);
239
+ want += word.length;
240
+ }
241
+ const totalW = segs.reduce((a, s) => a + s.w, 0);
242
+ let cumW = 0;
243
+ let consumed = 0;
244
+ let wi = 0;
245
+ for (const seg of segs) {
246
+ cumW += seg.w;
247
+ const target = Math.floor((want * cumW) / totalW) - consumed;
248
+ let got = 0;
249
+ while (wi < rowWords.length && got < target) {
250
+ const word = rowWords[wi];
251
+ const sep = seg.words.length ? 1 : 0;
252
+ if (seg.used + sep + word.length <= seg.w) {
253
+ seg.words.push(word);
254
+ seg.used += sep + word.length;
255
+ got += word.length;
256
+ wi++;
257
+ } else {
258
+ const room = seg.w - seg.used - sep;
259
+ if (room >= 3) {
260
+ seg.words.push(word.slice(0, room));
261
+ seg.used += sep + room;
262
+ got += room;
263
+ rowWords[wi] = word.slice(room);
264
+ }
265
+ break;
266
+ }
267
+ }
268
+ consumed += got;
269
+ }
270
+ if (wi < rowWords.length) carry = rowWords.slice(wi).concat(carry);
271
+ let line = '';
272
+ for (const p of pieces) {
273
+ if (p.seg) line += justifySeg(p);
274
+ else line += p.m.t === 'food' ? FOOD_MARK : bodyMark(p.m.e - p.m.s);
275
+ }
276
+ return { line, consumed };
277
+ }
278
+
279
+ function renderFrame() {
280
+ ti = 0;
281
+ carry = [];
282
+ const H = gh * CELL_H;
283
+ const marksByRow = [];
284
+ const freeW = [];
285
+ let totalFree = 0;
286
+ for (let y = 0; y < H; y++) {
287
+ const m = rowMarks(y);
288
+ const carved = m.reduce((a, k) => a + (k.e - k.s), 0);
289
+ marksByRow.push(m);
290
+ freeW.push(cols - carved);
291
+ totalFree += cols - carved;
292
+ }
293
+ const lines = [];
294
+ let cumFree = 0;
295
+ let assigned = 0;
296
+ for (let y = 0; y < H; y++) {
297
+ cumFree += freeW[y];
298
+ const quota = Math.floor((CHAR_TOTAL * cumFree) / totalFree) - assigned;
299
+ const r = layoutRow(marksByRow[y], quota);
300
+ assigned += r.consumed;
301
+ lines.push(r.line);
302
+ }
303
+ return lines;
304
+ }
305
+
306
+ function statusLine() {
307
+ const left = dead
308
+ ? ` DEAD — score ${score} — press r to restart, q to quit`
309
+ : paused
310
+ ? ` PAUSED — score ${score} — press p to resume`
311
+ : ` score ${score} length ${snake.length}`;
312
+ const right = 'arrows/wasd move · p pause · r restart · q quit ';
313
+ const pad = Math.max(1, cols - left.length - right.length);
314
+ return (left + ' '.repeat(pad) + right).slice(0, cols);
315
+ }
316
+
317
+ function draw() {
318
+ const pad = ' '.repeat(marginX);
319
+ const lines = renderFrame().map(l => pad + l);
320
+ const frame =
321
+ '\x1b[H' + '\n'.repeat(marginY) + DIM + lines.join('\n') + RESET +
322
+ '\n' + pad + '\x1b[7m' + statusLine() + RESET;
323
+ process.stdout.write(frame);
324
+ }
325
+
326
+ function enterScreen() {
327
+ process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H');
328
+ }
329
+
330
+ function leaveScreen() {
331
+ process.stdout.write('\x1b[?25h\x1b[?1049l');
332
+ }
333
+
334
+ function quit(code) {
335
+ clearTimeout(timer);
336
+ leaveScreen();
337
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
338
+ process.exit(code || 0);
339
+ }
340
+
341
+ const KEYMAP = {
342
+ '\x1b[A': 'up', '\x1b[B': 'down', '\x1b[C': 'right', '\x1b[D': 'left',
343
+ w: 'up', s: 'down', d: 'right', a: 'left',
344
+ k: 'up', j: 'down', l: 'right', h: 'left',
345
+ };
346
+
347
+ function onInput(buf) {
348
+ let data = buf.toString('utf8');
349
+ while (data.length) {
350
+ let key;
351
+ if (data.startsWith('\x1b[')) { key = data.slice(0, 3); data = data.slice(3); }
352
+ else { key = data[0]; data = data.slice(1); }
353
+ if (key === '\x03' || key === 'q') quit(0);
354
+ else if (key === 'p' && !dead) { paused = !paused; draw(); }
355
+ else if (key === 'r') { reset(); draw(); }
356
+ else if (KEYMAP[key] && !dead && !paused) {
357
+ if (pending.length < 3) pending.push(KEYMAP[key]);
358
+ }
359
+ }
360
+ }
361
+
362
+ function main() {
363
+ const smokeAt = process.argv.indexOf('--smoke');
364
+ if (smokeAt !== -1) {
365
+ const w = parseInt(process.argv[smokeAt + 1], 10);
366
+ const h = parseInt(process.argv[smokeAt + 2], 10);
367
+ measure(w > 0 ? w : 100, h > 0 ? h : 30);
368
+ reset();
369
+ process.stdout.write(renderFrame().join('\n') + '\n' + statusLine() + '\n');
370
+ return;
371
+ }
372
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
373
+ process.stderr.write('code-snake needs an interactive terminal (or run with --smoke)\n');
374
+ process.exit(1);
375
+ }
376
+ measure();
377
+ reset();
378
+ enterScreen();
379
+ process.stdin.setRawMode(true);
380
+ process.stdin.resume();
381
+ process.stdin.on('data', onInput);
382
+ process.stdout.on('resize', () => { measure(); reset(); process.stdout.write('\x1b[2J'); draw(); });
383
+ process.on('SIGTERM', () => quit(0));
384
+ process.on('SIGINT', () => quit(0));
385
+ draw();
386
+ timer = setTimeout(loop, tickMs);
387
+ }
388
+
389
+ main();