7
\$\begingroup\$

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.
\$\endgroup\$
1
  • 10
    \$\begingroup\$ Please note, if you're asking how your code should be modified to support nested loops or reading from a file, ...that's changing what the code does, not how it's doing it. \$\endgroup\$ Jul 25, 2014 at 18:16

1 Answer 1

8
\$\begingroup\$

This being Python, it should be relatively easy to present the illusion of an infinite tape, at least in the positive direction. I don't see reason that cell_amount has to be specified, and the user shouldn't have to worry about such details.

Your input and output routines are wrong:

  • The . instruction should print one character, interpreting the cell value as an ASCII code. Instead, you print the cell value as a base-10 number, followed by Newline.
  • The , instruction should read one character, storing its ASCII code as the cell value. Instead, you read a string, and try to parse it as an integer.

while True: … is a lie. What you really mean is while step < steps: …. Then you can get rid of the if step == steps: exit(0) at the end of the loop.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.