Browse Source

Add waiting for input

When a INPUT opcode is called, and there are no values in the
runtimeInput array, execution is paused until input is present.
ApisNecros 1 year ago
parent
commit
337bf3d8ee
1 changed files with 31 additions and 1 deletions
  1. 31 1
      IntComp/Computer.js

+ 31 - 1
IntComp/Computer.js

@@ -98,6 +98,20 @@ module.exports = class Computer {
          * @type {number[]}
          */
         this.outputValues = [];
+
+        /**
+         * Is the computer currently running
+         * @type {boolean}
+         */
+        this.running = false;
+
+        /**
+         * Is the computer waiting for input
+         *
+         * Triggered by the INPUT opcode when the runtimeInputs array is empty
+         * @type {boolean}
+         */
+        this.awaitingInput = false;
     }
 
     /**
@@ -145,6 +159,7 @@ module.exports = class Computer {
      */
     Execute(rawOpcode) {
         let status = true;
+        this.running = true;
         this.skipNext = false;
 
         this.FollowExecution();
@@ -162,6 +177,11 @@ module.exports = class Computer {
                 break;
             }
             case this.OPCODES.INPUT: {
+                // If we're awaiting input, and still haven't received any, keep waiting
+                if (this.awaitingInput == true && this.runtimeInput.length == 0) {
+                    this.skipNext = true;
+                    break;
+                }
                 this.Operation_Input();
                 break;
             }
@@ -186,6 +206,7 @@ module.exports = class Computer {
                 break;
             }
             case this.OPCODES.HALT:
+                this.running = false;
                 status = false;
                 break;
             default:
@@ -287,9 +308,18 @@ module.exports = class Computer {
         switch (inputMode) {
             case InputModes.INPUT_FROM_RUNTIME_STACK: {
                 userInput = this.runtimeInput.shift();
+                // If no input was found, await input
                 if (userInput === undefined) {
-                    this.ThrowError("runtime Input array empty");
+                    // Set the stack back to the INPUT opcode
+                    this.stack.Prev();
+                    this.stack.Prev();
+                    // Set the awaitingInput flag
+                    this.awaitingInput = true;
+                    // Exit the function
+                    return;
                 }
+
+                this.awaitingInput = false;
                 break;
             }
             case InputModes.INPUT_FROM_CONSOLE: {