I was bored, so I wrote a BrainFuck interpreter in Python. It essentially takes input for the amount of cells, then parses the inputted code through a series of if
statements.
# Simple BrainFuck interpreter
from sys import exit
# Main interpreter function
def interpreter(cell_amount):
step = 0
cell = [0] * cell_amount
cell_pos = 0
loop = False
loop_ret = 0
code_input = raw_input('Code: ')
steps = len(code_input)
while True:
if code_input[step] == '+':
cell[cell_pos] += 1
elif code_input[step] == '-':
cell[cell_pos] -= 1
elif code_input[step] == '>':
cell_pos += 1
elif code_input[step] == '<':
cell_pos -= 1
elif code_input[step] == '[':
if loop == False:
loop_ret = step
loop = True
elif code_input[step] == ']':
if cell[cell_pos] != 0:
step = loop_ret
elif cell[cell_pos] == 0:
loop = False
elif code_input[step] == '.':
print str(cell[cell_pos])
elif code_input[step] == ',':
cell[cell_pos] = int(raw_input())
step += 1
if step == steps:
exit(0)
interpreter(int(raw_input('Cell amount: ')))
Now, it works, with one small issue: loops can't be nested. I'd like a few things to be improved about it.
- Read code from a text file instead of
stdin
. - Better system than a chain of
if/elif/else
statements. - Be able to nest loops.