starfish.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. /**
  2. * The code box class
  3. */
  4. class CodeBox {
  5. constructor(codeBoxID, initialStackID, outputID) {
  6. /**
  7. * Possible vectors the pointer can move in
  8. * @type {Object}
  9. */
  10. this.directions = {
  11. NORTH: [ 0, -1],
  12. EAST: [ 1, 0],
  13. SOUTH: [ 0, 1],
  14. WEST: [-1, 0],
  15. };
  16. /**
  17. * The current vector of the pointer
  18. * @type {int[]}
  19. */
  20. this.curr_direction = this.directions.EAST;
  21. /**
  22. * The Set of instructions to execute
  23. *
  24. * Either a 1 or 2-dimensional array
  25. * @type {Array|Array[]}
  26. */
  27. this.box = [];
  28. /**
  29. * The farthest right the box goes
  30. * @type {int}
  31. */
  32. this.maxBoxWidth = 0;
  33. /**
  34. * The bottom of the box
  35. *
  36. * @type {int}
  37. */
  38. this.maxBoxHeight = 0;
  39. /**
  40. * The coordinates of the currently executing instruction inside the code box
  41. * @type {Object}
  42. */
  43. this.pointer = {
  44. X: 0,
  45. Y: 0,
  46. };
  47. /**
  48. * Was the instruction last moving in the left direction
  49. *
  50. * Used by the {@link Fisherman}
  51. * @type {boolean}
  52. */
  53. this.dirWasLeft = false;
  54. /**
  55. * Are we currently under the influence of the {@link Fisherman}
  56. * @type {boolean}
  57. */
  58. this.onTheHook = false;
  59. /**
  60. * Are we currently processing code box instructions as a string
  61. *
  62. * 0 when false, otherwise it holds the char code for string delimiter, either
  63. * 34 or 39
  64. *
  65. * @type {int}
  66. */
  67. this.stringMode = 0;
  68. /**
  69. * A list of stacks for the script to work with
  70. *
  71. * @type {Stack[]}
  72. */
  73. this.stacks = [new Stack()];
  74. /**
  75. * The index of the currently used stack
  76. *
  77. * @type {int}
  78. */
  79. this.curr_stack = 0;
  80. this.codeBoxDOM = document.getElementById(codeBoxID);
  81. if(!this.codeBoxDOM) {
  82. throw new Error(`Failed to find textarea with ID: ${codeBoxID}`);
  83. }
  84. this.outputDOM = document.getElementById(outputID);
  85. if(!this.outputDOM) {
  86. throw new Error(`Failed to find textarea with ID: ${outputID}`);
  87. }
  88. this.initialStackDOM = document.getElementById(initialStackID);
  89. if(!this.initialStackDOM) {
  90. throw new Error(`Failed to find input with ID: ${initialStackID}`);
  91. }
  92. }
  93. /**
  94. * Parse the initial code box
  95. *
  96. * Transforms the textual code box into usable matrix
  97. */
  98. ParseCodeBox() {
  99. // Reset some fields for a clean run
  100. this.box = [];
  101. this.stacks = [new Stack()];
  102. this.curr_stack = 0;
  103. this.pointer = {X: 0, Y: 0};
  104. this.curr_direction = this.directions.EAST;
  105. this.outputDOM.value = "";
  106. const cbRaw = this.codeBoxDOM.value;
  107. const rows = cbRaw.split("\n");
  108. let maxRowLength = 0;
  109. for(const row of rows) {
  110. const rowSplit = row.split("");
  111. // Store this for later processing
  112. while(rowSplit.length > maxRowLength) {
  113. maxRowLength = rowSplit.length
  114. }
  115. this.box.push(rowSplit);
  116. }
  117. this.EqualizeBoxWidth(maxRowLength);
  118. this.maxBoxWidth = maxRowLength - 1;
  119. this.maxBoxHeight = this.box.length - 1;
  120. let fin = null;
  121. try {
  122. while(!fin) {
  123. fin = this.Swim();
  124. }
  125. }
  126. catch(e) {
  127. console.error(e);
  128. }
  129. }
  130. /**
  131. * Make all the rows in the code box the same length
  132. *
  133. * All rows not long enough will have NOPs added until they're uniform in size.
  134. *
  135. * @param {int} [rowLength] The longest row in the code box
  136. */
  137. EqualizeBoxWidth(rowLength = null) {
  138. if(!rowLength) {
  139. for(const row of this.box) {
  140. if(row.length > rowLength) {
  141. rowLength = row.length;
  142. }
  143. }
  144. }
  145. for(const row of this.box) {
  146. while(row.length < rowLength) {
  147. row.push(" ");
  148. }
  149. }
  150. }
  151. /**
  152. * Print the value to the display
  153. *
  154. * @TODO Set up an actual display
  155. * @param {*} value
  156. */
  157. Output(value) {
  158. this.outputDOM.value += value;
  159. }
  160. Execute(instruction) {
  161. let output = null;
  162. try{
  163. switch(instruction) {
  164. // NOP
  165. case " ":
  166. break;
  167. // Numbers
  168. case "1":
  169. case "2":
  170. case "3":
  171. case "4":
  172. case "5":
  173. case "6":
  174. case "7":
  175. case "8":
  176. case "9":
  177. case "0":
  178. case "a":
  179. case "b":
  180. case "c":
  181. case "d":
  182. case "e":
  183. case "f":
  184. this.stacks[this.curr_stack].Push(parseInt(instruction, 16));
  185. break;
  186. // Operators
  187. case "+": {
  188. const x = this.stacks[this.curr_stack].Pop();
  189. const y = this.stacks[this.curr_stack].Pop();
  190. this.stacks[this.curr_stack].Push(y + x);
  191. break;
  192. }
  193. case "-": {
  194. const x = this.stacks[this.curr_stack].Pop();
  195. const y = this.stacks[this.curr_stack].Pop();
  196. this.stacks[this.curr_stack].Push(y - x);
  197. break;
  198. }
  199. case "*": {
  200. const x = this.stacks[this.curr_stack].Pop();
  201. const y = this.stacks[this.curr_stack].Pop();
  202. this.stacks[this.curr_stack].Push(y * x);
  203. break;
  204. }
  205. case ",": {
  206. const x = this.stacks[this.curr_stack].Pop();
  207. const y = this.stacks[this.curr_stack].Pop();
  208. this.stacks[this.curr_stack].Push(y / x);
  209. break;
  210. }
  211. case "%": {
  212. const x = this.stacks[this.curr_stack].Pop();
  213. const y = this.stacks[this.curr_stack].Pop();
  214. this.stacks[this.curr_stack].Push(y % x);
  215. break;
  216. }
  217. case "(": {
  218. const x = this.stacks[this.curr_stack].Pop();
  219. const y = this.stacks[this.curr_stack].Pop();
  220. this.stacks[this.curr_stack].Push(y < x ? 1 : 0);
  221. break;
  222. }
  223. case ")": {
  224. const x = this.stacks[this.curr_stack].Pop();
  225. const y = this.stacks[this.curr_stack].Pop();
  226. this.stacks[this.curr_stack].Push(y > x ? 1 : 0);
  227. break;
  228. }
  229. case "=": {
  230. const x = this.stacks[this.curr_stack].Pop();
  231. const y = this.stacks[this.curr_stack].Pop();
  232. this.stacks[this.curr_stack].push(y == x ? 1 : 0);
  233. break;
  234. }
  235. //String mode
  236. case "\"":
  237. case "'":
  238. this.stringMode = !!this.stringMode ? 0 : dec(instruction);
  239. break;
  240. // Movement
  241. case "^":
  242. this.MoveUp();
  243. break;
  244. case ">":
  245. this.MoveRight();
  246. break;
  247. case "v":
  248. this.MoveDown();
  249. break;
  250. case "<":
  251. this.MoveLeft();
  252. break;
  253. // Mirrors
  254. case "/":
  255. this.ReflectForward();
  256. break;
  257. case "\\":
  258. this.ReflectBack();
  259. break;
  260. case "_":
  261. this.VerticalMirror();
  262. break;
  263. case "|":
  264. this.HorizontalMirror();
  265. break;
  266. case "#":
  267. this.OmniMirror();
  268. break;
  269. // Trampolines
  270. case "!":
  271. this.Move();
  272. break;
  273. case "?":
  274. if(this.stacks[this.curr_stack].Pop() === 0){ this.Move(); }
  275. break;
  276. // Stack manipulation
  277. case "&": {
  278. if (this.stacks[this.curr_stack].register == null) {
  279. this.stacks[this.curr_stack].register = this.stacks[this.curr_stack].Pop();
  280. }
  281. else {
  282. this.stacks[this.curr_stack].Push(this.stacks[this.curr_stack].register);
  283. this.stacks[this.curr_stack].register = null;
  284. }
  285. }
  286. case ":":
  287. this.stacks[this.curr_stack].Duplicate();
  288. break;
  289. case "~":
  290. this.stacks[this.curr_stack].Remove();
  291. break;
  292. case "$":
  293. this.stacks[this.curr_stack].SwapTwo();
  294. break;
  295. case "@":
  296. this.stacks[this.curr_stack].SwapThree();
  297. break;
  298. case "{":
  299. this.stacks[this.curr_stack].ShiftLeft();
  300. break;
  301. case "}":
  302. this.stacks[this.curr_stack].ShiftRight();
  303. break;
  304. case "r":
  305. this.stacks[this.curr_stack].Reverse();
  306. break;
  307. case "l":
  308. this.stacks[this.curr_stack].PushLength();
  309. break;
  310. case "[": {
  311. this.SpliceStack(this.stacks[this.curr_stack].Pop());
  312. break;
  313. }
  314. case "]":
  315. this.CollapseStack();
  316. break;
  317. case "I": {
  318. this.curr_stack++;
  319. if (this.curr_stack >= this.stacks.length) {
  320. throw new RangeError("curr_stack value out of bounds");
  321. }
  322. break;
  323. }
  324. case "D": {
  325. this.curr_stack--;
  326. if (this.curr_stack < 0) {
  327. throw new RangeError("curr_stack value out of bounds");
  328. }
  329. break;
  330. }
  331. // Output
  332. case "n":
  333. output = this.stacks[this.curr_stack].Pop();
  334. break;
  335. case "o":
  336. output = String.fromCharCode(this.stacks[this.curr_stack].Pop());
  337. break;
  338. // Time
  339. case "S":
  340. // TODO
  341. break;
  342. case "h":
  343. // TODO
  344. break;
  345. case "m":
  346. // TODO
  347. break;
  348. case "s":
  349. // TODO
  350. break;
  351. // Code box manipulation
  352. case "g":
  353. this.PushFromCodeBox();
  354. break;
  355. case "p":
  356. this.PlaceIntoCodeBox();
  357. break;
  358. // End execution
  359. case ";":
  360. output = true;
  361. break;
  362. default:
  363. throw new Error(`Unknown instruction: ${instruction}`);
  364. }
  365. }
  366. catch(e) {
  367. console.error(`Something smells fishy!\n${e != "" ? `${e}\n` : ""}Instruction: ${instruction}\nStack: ${JSON.stringify(this.stacks[this.curr_stack].stack)}`);
  368. return true;
  369. }
  370. return output;
  371. }
  372. Swim() {
  373. const instruction = this.box[this.pointer.Y][this.pointer.X];
  374. if(this.stringMode != 0 && dec(instruction) != this.stringMode) {
  375. this.stacks[this.curr_stack].Push(dec(instruction));
  376. }
  377. else {
  378. const exeResult = this.Execute(instruction);
  379. if(exeResult === true) {
  380. return true;
  381. }
  382. else if(exeResult != null) {
  383. this.Output(exeResult);
  384. }
  385. }
  386. this.Move();
  387. }
  388. Move() {
  389. let newX = this.pointer.X + this.curr_direction[0];
  390. let newY = this.pointer.Y + this.curr_direction[1];
  391. // Keep the X coord in the boxes bounds
  392. if(newX < 0) {
  393. newX = this.maxBoxWidth;
  394. }
  395. else if(newX > this.maxBoxWidth) {
  396. newX = 0;
  397. }
  398. // Keep the Y coord in the boxes bounds
  399. if(newY < 0) {
  400. newY = this.maxBoxHeight;
  401. }
  402. else if(newY > this.maxBoxHeight) {
  403. newY = 0;
  404. }
  405. this.SetPointer(newX, newY);
  406. }
  407. /**
  408. * Implement C and .
  409. */
  410. SetPointer(x, y) {
  411. this.pointer = {X: x, Y: y};
  412. }
  413. /**
  414. * Implement ^
  415. *
  416. * Changes the swim direction upward
  417. */
  418. MoveUp() {
  419. this.curr_direction = this.directions.NORTH;
  420. }
  421. /**
  422. * Implement >
  423. *
  424. * Changes the swim direction rightward
  425. */
  426. MoveRight() {
  427. this.curr_direction = this.directions.EAST;
  428. this.dirWasLeft = false;
  429. }
  430. /**
  431. * Implement v
  432. *
  433. * Changes the swim direction downward
  434. */
  435. MoveDown() {
  436. this.curr_direction = this.directions.SOUTH;
  437. }
  438. /**
  439. * Implement <
  440. *
  441. * Changes the swim direction leftward
  442. */
  443. MoveLeft() {
  444. this.curr_direction = this.directions.WEST;
  445. this.dirWasLeft = true;
  446. }
  447. /**
  448. * Implement /
  449. *
  450. * Reflects the swim direction depending on its starting value
  451. */
  452. ReflectForward() {
  453. if (this.curr_direction == this.directions.NORTH) {
  454. this.MoveRight();
  455. }
  456. else if (this.curr_direction == this.directions.EAST) {
  457. this.MoveUp();
  458. }
  459. else if (this.curr_direction == this.directions.SOUTH) {
  460. this.MoveLeft();
  461. }
  462. else {
  463. this.MoveDown();
  464. }
  465. }
  466. /**
  467. * Implement \
  468. *
  469. * Reflects the swim direction depending on its starting value
  470. */
  471. ReflectBack() {
  472. if (this.curr_direction == this.directions.NORTH) {
  473. this.MoveLeft();
  474. }
  475. else if (this.curr_direction == this.directions.EAST) {
  476. this.MoveDown();
  477. }
  478. else if (this.curr_direction == this.directions.SOUTH) {
  479. this.MoveRight();
  480. }
  481. else {
  482. this.MoveUp();
  483. }
  484. }
  485. /**
  486. * Implement |
  487. *
  488. * Swaps the horizontal swim direction to its opposite
  489. */
  490. HorizontalMirror() {
  491. if (this.curr_direction == this.directions.EAST) {
  492. this.MoveLeft();
  493. }
  494. else {
  495. this.MoveRight();
  496. }
  497. }
  498. /**
  499. * Implement _
  500. *
  501. * Swaps the horizontal swim direction to its opposite
  502. */
  503. VerticalMirror() {
  504. if (this.curr_direction == this.directions.NORTH) {
  505. this.MoveDown();
  506. }
  507. else {
  508. this.MoveUp();
  509. }
  510. }
  511. /**
  512. * Implement #
  513. *
  514. * A combination of the vertical and the horizontal mirror
  515. */
  516. OmniMirror() {
  517. if (this.curr_direction[0]) {
  518. this.VerticalMirror();
  519. }
  520. else {
  521. this.HorizontalMirror();
  522. }
  523. }
  524. /**
  525. * Implement x
  526. *
  527. * Pseudo-randomly switches the swim direction
  528. */
  529. ShuffleDirection() {
  530. this.curr_direction = Object.values(this.directions)[Math.floor(Math.random() * 4)];
  531. }
  532. /**
  533. * Implement [
  534. *
  535. * Takes X number of elements out of a stack and into a new stack
  536. *
  537. * This action creates a new stack, and places it on top of the one it was created from.
  538. * So, if you have three stacks, A, B, and C, and you splice a stack off of stack B,
  539. * the new order will be: A, B, D, and C.
  540. *
  541. * @see {@link https://esolangs.org/wiki/Fish#Stacks ><> Documentation}
  542. *
  543. * @param {int} spliceCount The number of elements to pop into a new stack
  544. */
  545. SpliceStack(spliceCount) {
  546. const stackCount = this.stacks[this.curr_stack].stack.length;
  547. if (spliceCount > stackCount) {
  548. throw new RangeError(`Cannot remove ${spliceCount} elements from a stack of only ${stackCount} elements`);
  549. }
  550. const newStack = new Stack(this.stacks[this.curr_stack].stack.splice(stackCount - spliceCount, spliceCount));
  551. // We're at the top of the stacks stack, so we can use .push
  552. if (this.curr_stack == this.stacks.length - 1) {
  553. this.stacks.push(newStack);
  554. }
  555. else {
  556. this.stacks.splice(this.curr_stack + 1, 0, newStack);
  557. }
  558. this.curr_stack++;
  559. }
  560. /**
  561. * Implement ]
  562. *
  563. * Collapses the current stack onto the one below it
  564. * If the current stack is the only one, it is replaced with a blank stack
  565. */
  566. CollapseStack() {
  567. // Undefined behavior collapsing the first stack down when there are other stacks available
  568. if (this.curr_stack == 0 && this.stacks.length != 1) {
  569. throw new Error();
  570. }
  571. if (this.curr_stack == 0) {
  572. this.stacks = [new Stack()];
  573. }
  574. else {
  575. const collapsed = this.stacks.splice(this.curr_stack, 1).pop();
  576. this.curr_stack--;
  577. const currStackCount = this.stacks[this.curr_stack].stack.length;
  578. this.stacks[this.curr_stack].stack.splice(currStackCount, 0, ...collapsed.stack);
  579. }
  580. }
  581. /**
  582. * Implement g
  583. *
  584. * Pops `y` and `x` from the stack, and then pushes the value of the character
  585. * at `[x, y]` in the code box.
  586. *
  587. * NOP's and coords that are out of bounds are converted to 0.
  588. *
  589. * Implements the behavior as defined by the original {@link https://gist.github.com/anonymous/6392418#file-fish-py-L306 ><>}, and not {@link https://github.com/redstarcoder/go-starfish/blob/master/starfish/starfish.go#L378 go-starfish}
  590. */
  591. PushFromCodeBox() {
  592. const y = this.stacks[this.curr_stack].Pop();
  593. const x = this.stacks[this.curr_stack].Pop();
  594. let val = undefined;
  595. try {
  596. val = this.box[y][x] || " ";
  597. }
  598. catch (e) {
  599. val = " ";
  600. }
  601. const valParsed = val == " " ? 0 : dec(val);
  602. this.stacks[this.curr_stack].Push(valParsed);
  603. }
  604. /**
  605. * Implement p
  606. *
  607. * Pops `y`, `x`, and `v` off of the stack, and then places the string
  608. * representation of that value at `[x, y]` in the code box.
  609. */
  610. PlaceIntoCodeBox() {
  611. const y = this.stacks[this.curr_stack].Pop();
  612. const x = this.stacks[this.curr_stack].Pop();
  613. const v = this.stacks[this.curr_stack].Pop();
  614. while(y >= this.box.length) {
  615. this.box.push([]);
  616. }
  617. while(x >= this.box[y].length) {
  618. this.box[y].push(" ");
  619. }
  620. this.EqualizeBoxWidth();
  621. this.box[y][x] = String.fromCharCode(v);
  622. }
  623. /**
  624. * Implement `
  625. *
  626. * Changes the swim direction based on the previous direction
  627. * @see https://esolangs.org/wiki/Starfish#Fisherman
  628. */
  629. Fisherman() {
  630. if (this.curr_direction[0]) {
  631. if (this.dirWasLeft) {
  632. this.MoveLeft();
  633. }
  634. else {
  635. this.MoveRight();
  636. }
  637. }
  638. else {
  639. if (this.onTheHook) {
  640. this.onTheHook = false;
  641. this.MoveUp();
  642. }
  643. else {
  644. this.onTheHook = true;
  645. this.MoveDown();
  646. }
  647. }
  648. }
  649. }
  650. /**
  651. * The stack class
  652. */
  653. class Stack {
  654. /**
  655. * @param {int[]} stackValues An array of values to initialize the stack with
  656. */
  657. constructor(stackValues = []) {
  658. /**
  659. * The stack
  660. * @type {int[]}
  661. */
  662. this.stack = stackValues;
  663. /**
  664. * A single value saved off the stack
  665. * @type {int}
  666. */
  667. this.register = null;
  668. }
  669. /**
  670. * Wrapper function for Array.prototype.push
  671. * @param {*} newValue
  672. */
  673. Push(newValue) {
  674. this.stack.push(newValue);
  675. }
  676. /**
  677. * Wrapper function for Array.prototype.pop
  678. * @returns {*}
  679. */
  680. Pop() {
  681. const value = this.stack.pop();
  682. if(value == undefined){ throw new Error(); }
  683. return value;
  684. }
  685. /**
  686. * Implement }
  687. *
  688. * Shifts the entire stack leftward by one value
  689. */
  690. ShiftLeft() {
  691. const temp = this.stack.shift();
  692. this.stack.push(temp);
  693. }
  694. /**
  695. * Implement {
  696. *
  697. * Shifts the entire stack rightward by one value
  698. */
  699. ShiftRight() {
  700. const temp = this.stack.pop();
  701. this.stack.unshift(temp);
  702. }
  703. /**
  704. * Implement $
  705. *
  706. * Swaps the top two values of the stack
  707. */
  708. SwapTwo() {
  709. if(this.stack.length < 2) { throw new Error(); }
  710. const popped = this.stack.splice(this.stack.length - 2, 2);
  711. this.stack.push(...popped.reverse());
  712. }
  713. /**
  714. * Implement @
  715. *
  716. * Swaps the top three values of the stack
  717. */
  718. SwapThree() {
  719. if(this.stack.length < 3) { throw new Error(); }
  720. // Get the top three values
  721. const popped = this.stack.splice(this.stack.length - 3, 3);
  722. // Shift the elements to the right
  723. popped.unshift(popped.pop());
  724. this.stack.push(...popped);
  725. }
  726. /**
  727. * Implement :
  728. *
  729. * Duplicates the element on the top of the stack
  730. */
  731. Duplicate() {
  732. this.stack.push(this.stack[this.stack.length-1]);
  733. }
  734. /**
  735. * Implements ~
  736. *
  737. * Removes the element on the top of the stack
  738. */
  739. Remove() {
  740. this.stack.pop();
  741. }
  742. /**
  743. * Implement r
  744. *
  745. * Reverses the entire stack
  746. */
  747. Reverse() {
  748. this.stack.reverse();
  749. }
  750. /**
  751. * Implement l
  752. *
  753. * Pushes the length of the stack onto the top of the stack
  754. */
  755. PushLength() {
  756. this.stack.push(this.stack.length);
  757. }
  758. }
  759. /**
  760. * Get the char code of any character
  761. *
  762. * Can actually take any length of a value, but only returns the
  763. * char code of the first character.
  764. *
  765. * @param {*} value Any character
  766. * @returns {int} The value's char code
  767. */
  768. function dec(value) {
  769. return value.toString().charCodeAt(0);
  770. }