HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Basic BrainFuck interpreter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
brainfuckinterpreterbasic

Problem

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.

Solution

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.

Context

StackExchange Code Review Q#58071, answer score: 8

Revisions (0)

No revisions yet.