Skip to content

Instantly share code, notes, and snippets.

@anka-213
Created May 22, 2017 12:31
Show Gist options
  • Save anka-213/9b551db0d30bc72aab331adfeda41def to your computer and use it in GitHub Desktop.
Save anka-213/9b551db0d30bc72aab331adfeda41def to your computer and use it in GitHub Desktop.
Simple Brainfuck interpreter created by andreaskällberg - https://repl.it/IKt3/2
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.has_code_left()
def has_code_left(self):
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:
def __init__(self, code):
self.code = Code(code)
self.world = [0]*10
self.p = 0
@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 == ',':
c = input()
self.here = ord(c) if len(c)==1 else 0
elif op == ':':
self.int_print()
elif op == ';':
self.here = int(input())
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))
def run_bf(code):
BF(code).run()
b = BF("++++[>++++<-]>[<++++>-]>+++++[<+++++>-]<+[<+.>-]")
b.run()
run_bf(">,[>,]<[.<]")
#BF(",----").run()
#print(b.here)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment