Looks like the brainfuck is working. It can do a hello world program.
This commit is contained in:
parent
5b18849ddc
commit
38104f60f3
3 changed files with 78 additions and 4 deletions
|
@ -1,5 +1,6 @@
|
|||
#include <map>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/color.h>
|
||||
#include "game_engine.hpp"
|
||||
|
@ -51,6 +52,53 @@ Brainfucker::Brainfucker() {
|
|||
|
||||
}
|
||||
|
||||
/*
|
||||
* Just a jank way to use a counter to find
|
||||
* the previous matching brace rather than
|
||||
* using a stack. Should work for now.
|
||||
*/
|
||||
void Brainfucker::jump_forward() {
|
||||
int counter = 1;
|
||||
|
||||
for(++ip; // when counter hits 0 we found it
|
||||
counter > 0 && ip < code.size();
|
||||
++ip)
|
||||
{
|
||||
char op = code.at(ip);
|
||||
if(op == '[') {
|
||||
// new branch so increment
|
||||
++counter;
|
||||
} else if(op == ']') {
|
||||
// close branch so decrement
|
||||
--counter;
|
||||
}
|
||||
}
|
||||
|
||||
++ip; // need to go 1 after
|
||||
}
|
||||
|
||||
/*
|
||||
* Same jank style of using a counter to
|
||||
* jump back.
|
||||
*/
|
||||
void Brainfucker::jump_backward() {
|
||||
int counter = 1;
|
||||
|
||||
for(--ip; // when counter hits 0 we found it
|
||||
counter > 0 && ip > 0;
|
||||
--ip)
|
||||
{
|
||||
char op = code.at(ip);
|
||||
if(op == '[') {
|
||||
// close branch so decrement
|
||||
--counter;
|
||||
} else if(op == ']') {
|
||||
// new branch so increment
|
||||
++counter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Totally fragile but it seems to be working
|
||||
* enough to test the idea.
|
||||
|
@ -67,17 +115,31 @@ void Brainfucker::run(int ticks) {
|
|||
--dp;
|
||||
break;
|
||||
case '+':
|
||||
data[dp] = 1;
|
||||
data[dp] = data[dp] + 1;
|
||||
break;
|
||||
case '-':
|
||||
data[dp] = 0;
|
||||
data[dp] = data[dp] - 1;
|
||||
break;
|
||||
case '.':
|
||||
print("{}", data.at(dp));
|
||||
cout << (char)data.at(dp);
|
||||
break;
|
||||
case ',':
|
||||
print(ERROR, "Not implemented.\n");
|
||||
break;
|
||||
case '[': {
|
||||
// [ - if 0 jump to after ]
|
||||
if(data.at(dp) == 0) {
|
||||
jump_forward();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ']': {
|
||||
// ] if not 0 jump to after [
|
||||
if(data.at(dp) != 0) {
|
||||
jump_backward();
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
print(ERROR, "Unknown operation {}\n", op);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue