Skip to content

Instantly share code, notes, and snippets.

@anka-213
Created May 22, 2017 12:01
Show Gist options
  • Save anka-213/c00a1c515e4ad1bb22021e083b69d112 to your computer and use it in GitHub Desktop.
Save anka-213/c00a1c515e4ad1bb22021e083b69d112 to your computer and use it in GitHub Desktop.
Simple Brainfuck interpreter created by andreaskällberg - https://repl.it/IKt3/1
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