-
Notifications
You must be signed in to change notification settings - Fork 17
/
intcode-computer.js
517 lines (444 loc) · 11.8 KB
/
intcode-computer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
const readline = require('readline');
const { green, cyan } = require('colors');
const ADD = '01'; // Add
const MUL = '02'; // Multiply
const INP = '03'; // Input
const OUT = '04'; // Output
const JIT = '05'; // Jump-if-true
const JIF = '06'; // Jump-if-false
const LTH = '07'; // Less Than
const EQU = '08'; // Equals
const ARB = '09'; // Adjust relative base
const STP = '99'; // Stop
const POSITION_MODE = '0';
const IMMEDIATE_MODE = '1';
const RELATIVE_MODE = '2';
class Computer {
constructor({
memory,
inputs = [],
replenish_input = undefined,
pause_on_output = true,
id = 0,
clone_memory = false,
}) {
// For debugging
this.id = String.fromCharCode('A'.charCodeAt(0) + id);
this.original_memory = clone_memory && memory.slice(0);
this.memory = memory.slice(0);
this.pointer = 0;
this.relative_base = 0;
this.pause_on_output = pause_on_output;
this.inputs = Array.isArray(inputs) ? inputs.slice(0) : [inputs];
this.replenish_input = replenish_input;
this.outputs = [];
this.OPS = {
[ADD]: {
name: ADD,
realName: 'ADD',
params: 3,
fn: (a, b, c) => {
this.memory[c] = a + b;
},
write: true,
},
[MUL]: {
name: MUL,
realName: 'MUL',
params: 3,
fn: (a, b, c) => {
this.memory[c] = a * b;
},
write: true,
},
[INP]: {
name: INP,
realName: 'INP',
params: 1,
fn: a => {
this.memory[a] = this.inputs.shift();
if (this.replenish_input !== undefined) {
this.inputs.push(this.replenish_input);
}
},
write: true,
},
[OUT]: {
name: OUT,
realName: 'OUT',
params: 1,
fn: a => this.output(a),
},
[ARB]: {
name: ARB,
realName: 'ARB',
params: 1,
fn: a => (this.relative_base += a),
},
[STP]: {
name: STP,
realName: 'STP',
params: 0,
fn: () => (this.halted = true),
},
[JIT]: {
name: JIT,
realName: 'JIT',
params: 2,
fn: (a, b) => {
if (a) {
this.pointer = b;
return true;
}
return false;
},
jumps: true,
},
[JIF]: {
name: JIF,
realName: 'JIF',
params: 2,
fn: (a, b) => {
if (!a) {
this.pointer = b;
return true;
}
return false;
},
jumps: true,
},
[LTH]: {
name: LTH,
realName: 'LTH',
params: 3,
fn: (a, b, c) => {
this.memory[c] = a < b ? 1 : 0;
},
write: true,
},
[EQU]: {
name: EQU,
realName: 'EQU',
params: 3,
fn: (a, b, c) => {
this.memory[c] = a === b ? 1 : 0;
},
write: true,
},
};
this.halted = false;
}
run() {
let op = this.parseOp();
while (!this.halted) {
this.runOp(op);
/**
* In circuits, computer execution should be paused on outout so that value can be passed to the next computer.
* Additionally, execution should immediately stopped if we have halted.
*/
if ((this.pause_on_output && op.name === OUT) || this.halted) {
break;
}
op = this.parseOp();
}
return this.outputs;
}
parseOp() {
let temp_op = String(this.memory[this.pointer]).padStart(2, '0');
// "The opcode is a two-digit number based only on the ones and tens digit of the value, that is, the opcode is the rightmost two digits of the first value in an instruction"
let op = this.OPS[temp_op.substr(-2, 2)];
let full_op = temp_op.padStart(op.params + 2, '0');
let modes = [];
// "Parameter modes are single digits, one per parameter, read **right-to-left** from the opcode"
for (let i = op.params - 1; i >= 0; i--) {
modes.push(full_op[i]);
}
return {
...op,
modes,
};
}
runOp({ modes, fn, jumps, write }) {
this.pointer++;
let values = [];
for (let i = 0; i < modes.length; i++) {
let mode = modes[i];
let value = this.memory[this.pointer + i];
// Values can overflow existing memory. If so, value should be 0
if (value === undefined) {
value = 0;
}
// Immediate Mode uses the value as is, no need to make adjustments
if (mode !== IMMEDIATE_MODE) {
/**
* While working in Position or Relative Mode, it is (at first)
* unituitive why I need to _skip_ the value re-mapping if we
* are at the _last_ value to calculate.
*
* Consider the ADD operation `1001,9,8,7`.
*
* Parsing this out gives us:
*
* ABCDE
* 1001
*
* DE - two-digit opcode, 01 == opcode 1
* C - mode of 1st parameter, 0 == position mode
* B - mode of 2nd parameter, 1 == immediate mode
* A - mode of 3rd parameter, 0 == position mode,
* omitted due to being a leading zero
*
* If I were to write this addition operation as a standard made equation,
* where number literals (immediate mode) are written as the number, and
* position numbers are written with a prefixed `@` symbol, the equation
* might look like
*
* @3 = @1 + 2
*
* Now, if I were to re-map the pointer'd `@` symbols, I'd get
*
* 7 = 9 + 2
*
* But _that isn't what we want!_ Namely, it doesn't make sense
* to set the _literal_ number 7 equal to some addition operation.
*
* So, the assignment part _always_ retains its pointer aspect.
*
* @3 = 9 + 2
*
* Because of this, when I do the re-mapping, I skip the last arugment
* whenever I am performing an operation that writes to memory. On operations
* that _don't_ write to memory, I can re-map regardless of which parameter I am
* inspecting.
*
* For example, on a JIT operation `5,3,4` (implicitly `0005,3,4`) on the computer
* `5,3,4,1001,0` would be executed as:
*
* if @3 != 0; then Jump to @4
*
* Re-mapping these pointers to the values from memory, the code becomes
*
* if 1001 != 0; then Jump to 0
*
* That is, even though the `@4` position parameter was the last parameter,
* I still performed the look up because the JIT op does _not_ write to memory.
*
* To, to recap, I want to re-map my value to the value stored in memory at
* a certain _position_ if:
*
* - I am running an op that does _not_ write to memory
* - Or if I am not at the last parameter in the op
*/
const can_switch_to_position = !write || i < modes.length - 1;
if (can_switch_to_position && mode === POSITION_MODE) {
value = this.memory[value];
} else if (mode === RELATIVE_MODE) {
/**
* In relative mode, value is always updated. However, again for the reasons
* above, the last parameter on operations that write to memory should only
* have the value adjusted by the relative base. For all other instances,
* the value should be looked up from memory (in a relative fashion, of course).
*/
if (can_switch_to_position) {
value = this.memory[value + this.relative_base];
} else {
value = value + this.relative_base;
}
}
}
// After remapping (if any) again adjust to 0 if we overflowed our memory read
if (value === undefined) {
value = 0;
}
values.push(value);
}
// If result is `true`, we moved the pointer
let result = fn(...values);
if (!jumps || (jumps && !result)) {
this.pointer += modes.length;
}
}
output(v) {
this.outputs.push(v);
}
// For debugging
get _() {
return this.memory.slice(Math.max(0, this.pointer - 1), this.pointer + 8);
}
}
const EMPTY = 0;
const WALL = 1;
const BLOCK = 2;
const PADDLE = 3;
const BALL = 4;
const DRAW_MAP = {
[EMPTY]: ' ',
[WALL]: '+',
[BLOCK]: '#',
[PADDLE]: '=',
[BALL]: 'o',
};
class Tile {
constructor(x, y, tile_id) {
this.x = x;
this.y = y;
this.tile_id = tile_id;
}
toString() {
return DRAW_MAP[this.tile_id] || ' ';
}
}
class Grid {
constructor(tiles) {
this.grid = {};
this.tiles = tiles;
tiles.forEach(tile => {
const { x, y } = tile;
this.grid[`${x},${y}`] = tile;
});
// { x: [min_x, max_x], y: [min_y, max_y] }
this.boundaries = this.setBoundariesFromTiles();
}
getNumberOfTilesOfType(type) {
return this.tiles.filter(tile => tile.tile_id === type).length;
}
printGrid() {
let screen = '';
let [min_x, max_x] = this.boundaries.x;
let [min_y, max_y] = this.boundaries.y;
for (let y = min_y; y <= max_y; y++) {
for (let x = min_x; x <= max_x; x++) {
let coord = `${x},${y}`;
screen += this.grid[coord].toString();
}
screen += '\n';
}
console.log(screen);
}
setBoundariesFromTiles() {
// Technically we sort our `this.tiles` array but that probably doesn't matter.
let tiles_x_sorted = this.tiles.sort((a, b) => a.x - b.x);
// [min_x, max_x]
let x = [tiles_x_sorted[0].x, tiles_x_sorted[tiles_x_sorted.length - 1].x];
let tiles_y_sorted = this.tiles.sort((a, b) => a.y - b.y);
// [min_y, max_y]
let y = [tiles_y_sorted[0].y, tiles_y_sorted[tiles_y_sorted.length - 1].y];
return { x, y };
}
}
class Screen {
constructor(boundaries = { x: [0, 37], y: [0, 20] }) {
this.grid = {};
this.score = 0;
this.paddle;
// { x: [min_x, max_x], y: [min_y, max_y] }
this.boundaries = boundaries;
}
paint(x, y, tile_id) {
if (x === -1 && y === 0) {
return (this.score = tile_id);
}
const coord = x + ',' + y;
if (!this.grid[coord]) {
this.grid[coord] = new Tile(x, y);
}
this.grid[coord].tile_id = tile_id;
if (tile_id === PADDLE) {
this.paddle = this.grid[coord];
}
}
toString() {
let screen = '';
let [min_x, max_x] = this.boundaries.x;
let [min_y, max_y] = this.boundaries.y;
for (let y = min_y; y <= max_y; y++) {
for (let x = min_x; x <= max_x; x++) {
let coord = `${x},${y}`;
let tile = this.grid[coord] || ' ';
screen += tile.toString();
}
if (y === min_y) {
screen += ' Score: ' + this.score;
}
screen += '\n';
}
return screen;
}
}
const wait = (ms = 500) => new Promise(r => setTimeout(r, ms));
class Arcade {
constructor(memory, options = {}) {
this.computer = new Computer({ memory, pause_on_output: false, ...options });
this.grid;
this.screen = new Screen();
this.print_game = options.print_game;
if (this.print_game) {
readline.cursorTo(process.stdout, 0, 0);
readline.clearLine(process.stdout);
}
}
runAndGetGrid() {
let computer = this.computer;
let output = this.computer.outputs;
while (!computer.halted) {
output = computer.run();
if (computer.halted) {
break;
}
}
let tiles = [];
for (let i = 0; i < output.length - 2; i += 3) {
let x = output[i];
let y = output[i + 1];
let tile_id = output[i + 2];
tiles.push(new Tile(x, y, tile_id));
}
this.grid = new Grid(tiles);
return this.grid;
}
// Run after changing position `0` in the memory to the value `2`
async freePlay() {
let computer = this.computer;
let output = this.computer.outputs;
while (!computer.halted) {
output = computer.run();
if (computer.halted) {
break;
}
if (output.length >= 3) {
const x = output.shift();
const y = output.shift();
const tile_id = output.shift();
let ms = 0;
if (tile_id === BALL && this.screen.paddle) {
ms = 3;
// See if ball is to the left or right of paddle
if (x < this.screen.paddle.x) {
computer.inputs[0] = -1;
} else if (x > this.screen.paddle.x) {
computer.inputs[0] = 1;
}
}
this.screen.paint(x, y, tile_id);
if (this.print_game) {
readline.cursorTo(process.stdout, 0, 0);
console.log(this.screen.toString());
await wait(ms);
}
}
}
let score_length = String(this.screen.score).length;
let border = Array(2 + 2 + score_length).fill('-');
border[0] = '+';
border[border.length - 1] = '+';
border = border.join('');
console.log(cyan(border));
console.log(green(`| ${this.screen.score} |`));
console.log(cyan(border));
}
}
module.exports = {
Computer,
Arcade,
TYPES: { EMPTY, WALL, BLOCK, PADDLE, BALL },
};