Created
May 22, 2017 12:01
Simple Brainfuck interpreter created by andreaskällberg - https://repl.it/IKt3/1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def get_dir(c): | |
# return 1 if c == '[' else -1 if c == ']' else 0 | |
dirs = {'[':1, ']': -1} | |
return dirs[c] if c in dirs else 0 | |
class Code: | |
code = "" | |
pc = 0 | |
def __init__(self, code): | |
self.code = code | |
@property | |
def here(self): | |
return self.code[self.pc] | |
def next(self): | |
self.pc += 1 | |
return self.pc < len(self.code) | |
def go_to_match(self): | |
count = get_dir(self.here) | |
while count != 0: | |
self.pc += 1 if count>0 else -1 | |
count += get_dir(self.here) | |
class BF: | |
world = [0]*10 | |
p=0 | |
def __init__(self, code): | |
self.code = Code(code) | |
@property | |
def here(self): | |
return self.world[self.p] | |
@here.setter | |
def here(self, value): | |
self.world[self.p] = value | |
def __call__(self): | |
self.go_step() | |
return self | |
def go_step(self): | |
op = self.code.here | |
if op == '+': | |
self.here += 1 | |
elif op == '-': | |
self.here -= 1 | |
elif op == '>': | |
self.p += 1 | |
elif op == '<': | |
self.p -= 1 | |
elif op == '.': | |
self.op_print() | |
elif op == '[': | |
if self.here == 0: | |
self.code.go_to_match() | |
elif op == ']': | |
if self.here != 0: | |
self.code.go_to_match() | |
return self.code.next() | |
def run(self): | |
while self.go_step(): | |
pass | |
self.code.pc = 0 | |
def op_print(self): | |
print("{:c}".format(self.here)) | |
def int_print(self): | |
print("{:d}".format(self.here)) | |
b = BF("++++[>++++<-]>[<++++>-]>+++++[<+++++>-]<+[<+.>-]") | |
b.run() | |
#print(b.here) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment