Brainfuck Interpreter
HTML
<textarea id="code">++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.</textarea>
<br />
<button id="run">Run</button>
<button id="stop">Stop</button>
<label for="printletters">Print Letters: </label>
<input id="printletters" type="checkbox" checked/>
<div id="console"></div>
CSS
textarea {
width:500px;
height:200px;
}
JavaScript
(function() {
function Interpreter(console) {
this.Source = undefined;
this.OriginalSource = undefined;
this.Output = undefined;
this.Scope = undefined;
this.StopInterpret = false;
this.PrintLetters = true;
this.Console = console;
this.$Console = $(this.Console);
}
Interpreter.prototype.Run = function(source) {
this.StopInterpret = false;
this.OriginalSource = source;
this.ClearConsole();
this.Interpret();
}
Interpreter.prototype.Interpret = function() {
this.Source = this.OriginalSource.replace(/[\s]/g, "");
this.Scope = new Scope();
for(var i=0, iL = this.Source.length; i<iL; i++) {
if(this.StopInterpret) {
break;
}
var character = this.Source.charAt(i);
if(!this.Scope.IsLoopCompleted()) {
switch(character) {
case '>':
this.Scope.IncrementPointer();
break;
case '<':
this.Scope.DecrementPointer();
break;
case '+':
this.Scope.IncrementCell();
break;
case '-':
this.Scope.DecrementCell();
break;
case ',':
var input = parseInt(window.prompt("Input a single byte (0-255)"));
while(input > 255 || input < 0) {
input = parseInt(window.prompt("Input a single byte (0-255)"));
}
this.Scope.SetCell(input);
break;
case '.':
this.PrintToConsole(this.Scope.GetCellValue());
break;
case '[':
if(this.Scope.GetCellValue() == 0) {
this.Scope.IncrementDepth();
this.Scope.SetLoopCompleted();
}
else {
this.Scope.IncrementDepth();
this.Scope.SetLoopIndex(i);
}
break;
case ']':
if(this.Scope.GetCellValue() != 0) {
i = this.Scope.GetLoopIndex() - 1;
this.Scope.DestroyLoop();
}
else {
this.Scope.DestroyLoop();
}
break;
}
}
else...