Skip to content

Instantly share code, notes, and snippets.

@ymrl
Created October 28, 2011 23:14
Show Gist options
  • Save ymrl/1323819 to your computer and use it in GitHub Desktop.
Save ymrl/1323819 to your computer and use it in GitHub Desktop.
眠れないのでbrainf*ck処理系を1時間くらいで作った
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>brainf*ck</title>
<script>
var ptr = 0;
var memory = [];
var code = "";
var ptrIncr = />/;
var ptrDecr = /</;
var varIncr = /\+/;
var varDecr = /-/;
var output = /\./;
var input = /,/;
var jmpIn = /\[/;
var jmpOut = /\]/;
var index = 0;
var clear = function(){
memory = [];
ptr = 0;
index = 0;
}
var step = function(){
if(!code || index >= code.length){return ;}
var op = code[index];
try{
if(op.match(ptrIncr)){
ptr++;
}else if(op.match(ptrDecr)){
ptr--;
if(ptr < 0) throw "ポインタが負の値を取りました";
}else if(op.match(varIncr)){
if(!memory[ptr]) memory[ptr] = 0 ;
memory[ptr]++;
memory[ptr] &= 0xff;
}else if(op.match(varDecr)){
if(!memory[ptr]) memory[ptr] = 0 ;
memory[ptr]--;
memory[ptr] &= 0xff;
}else if(op.match(output)){
if(!memory[ptr]) memory[ptr] = 0 ;
document.getElementById('outputArea').value += String.fromCharCode(memory[ptr]);
}else if(op.match(input)){
var value = window.prompt('input');
memory[ptr] = value ? value.charCodeAt(0):0;
}else if(op.match(jmpIn)){
if(!memory[ptr]) memory[ptr] = 0 ;
if(memory[ptr] == 0){
var count = 0;
while(index < code.length){
index++ ;
if(code[index].match(jmpIn)){
count++;
}else if(code[index].match(jmpOut)){
if( count > 0){
count--;
}else{
break;
}
}
}
}
}else if(op.match(jmpOut)){
if(!memory[ptr]) memory[ptr] = 0 ;
if(memory[ptr] != 0){
var count = 0;
while(index >= 0){
index--;
if(code[index].match(jmpOut)){
count++;
}else if(code[index].match(jmpIn)){
if( count > 0){
count--;
}else{
break;
}
}
}
}
}
index++;
step();
}catch(e){
window.alert(e)
}
};
window.addEventListener('load',function(){
document.getElementById('codeForm').addEventListener('submit',function(e){
e.preventDefault();
clear();
code = document.getElementById('codeArea').value;
step();
return false;
});
});
</script>
</head>
<body>
<h2>コード</h2>
<form id="codeForm">
<textarea id="codeArea" name="codeArea"></textarea>
<input type="submit" value="実行" />
</form>
<form id="interactionForm">
<h2>実行結果</h2>
<textarea id="outputArea" name="outputArea" id="outputArea"></textarea>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment