Browse Source

Add ability to output to other computers

Added the ability to chain computers together by their `outputComputer`
class parameter. With this, any OUTPUT opcodes will then run that output
value to the output comptuer's RunWithInput function.
ApisNecros 1 year ago
parent
commit
6cab2b22da
1 changed files with 42 additions and 2 deletions
  1. 42 2
      IntComp/Computer.js

+ 42 - 2
IntComp/Computer.js

@@ -55,6 +55,15 @@ module.exports = class Computer {
             outputToConsole: options.outputToConsole ?? false,
         };
 
+        /**
+         * A function to pass the value from OUTPUT opcodes to
+         *
+         * If the outputToConsole option is false, and a function is provided here,
+         * any values from an OUTPUT opcode will be passed here.
+         * @type {?Computer}
+         */
+        this.outputComputer = null;
+
         /**
          * An input value provided at runtime
          *
@@ -65,6 +74,19 @@ module.exports = class Computer {
          * @type {number}
          */
         this.runtimeInput = null;
+
+        /**
+         * An array of outputs from the computer
+         *
+         * Outputs from the computer that weren't output to the console, or to a
+         * callback function.
+         *
+         * Ideally, when not in outputToConsole mode, the computer should only ever have
+         * one output, but I'm not certain that will be the case. In that case, this array
+         * will have the outputs in chronological order.
+         * @type {number[]}
+         */
+        this.outputValues = [];
     }
 
     /**
@@ -266,11 +288,20 @@ module.exports = class Computer {
      * @returns {void}
      */
     Operation_Output(rawOpcode) {
-        const currAddress = this.stack.pointer;
+        const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
+
         const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
         const output = this.stack.Next().Get(outputPositionMode);
 
-        console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
+        if (this.options.outputToConsole) {
+            console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
+        }
+        else if (this.outputComputer !== null) {
+            this.outputComputer.RunWithInput(output);
+        }
+        else {
+            this.outputValues.push(output);
+        }
     }
 
     /**
@@ -345,6 +376,15 @@ module.exports = class Computer {
         console.log(util.inspect(memory, { breakLength: Infinity, colors: true, compact: true }));
     }
 
+    /**
+     * Get a value from the unhandled OUTPUT values in FIFO order
+     *
+     * @returns {number} An unhandled value from an output call
+     */
+    FetchOutputValue() {
+        return this.outputValues.shift();
+    }
+
     /**
      * Resets the computer's memory to the value it was created with
      *