-2
我目前正在製作一個brainf * ck並遇到了循環問題。Brainf * ck解釋器循環問題
我遵循this的一些建議,但我似乎無法得到它的工作。
這是到目前爲止我的代碼:
<html>
<body>
<font face="consolas">
<script>
var brPos = 0;
var k = 0;
var loop = [];
var printtape = "";
var out = "";
var i = 0;
var pointer = 0;
var tape = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var source = prompt("Code").split("");
while (i<source.length+1){
if (source[i] == "<"){
pointer--;
} else if (source[i] == ">"){
pointer++;
} else if (source[i] == "+"){
tape[pointer]++;
} else if (source[i] == "-"){
tape[pointer]--;
} else if (source[i] == ","){
tape[pointer] = prompt("Input").charCodeAt(0);
} else if (source[i] == "."){
out += String.fromCharCode(tape[pointer]);
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
i++;
for (j=0;j<tape.length;j++) {
if (tape[j] > 255) {
tape[j] = 0;
} else if (tape[j] < 0) {
tape[j] = 255;
}
}
console.log(tape);
console.log(loop);
}
printtape = "";
printtape += "|";
for (i=0;i<tape.length;i++) {
if (tape[i]<10) {
printtape += "00"+tape[i]+"|";
}
if (tape[i]>=10&&tape[i]<100) {
printtape += "0"+tape[i]+"|";
}
if (tape[i]>=100) {
printtape += tape[i]+"|";
}
}
printtape += "<br>";
printtape += " ";
for (i=0;i<pointer;i++) {
printtape += " ";
}
printtape += "^";
document.write(printtape);
alert(out);
</script>
</font>
</body>
</html>
這是有問題的代碼(我認爲):
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
當我與一個brainf * CK循環運行的代碼(IE)在它,它不結束while循環,並最終崩潰,我不知道爲什麼。
P.S.我知道在評論中有人會說<font>
標記是無效的HTML,我應該使用CSS,但它的工作原理,它比CSS快,我真的不在乎。
問題是什麼(除了不工作)? –
它永遠運行,似乎並沒有結束while循環。 – FinW