Brainfuck Python interpreter (ChatGPT)

From Esolang
Jump to navigation Jump to search

Here is a Brainfuck interpreter in Python. Edited from the Numberfuck interpreter which was coded by ChatGPT. Still is optimized for everything, including printing the full lyrics of the song Never Gonna Give You Up.

def interpret():
    code = input("Enter Brainfuck code: ")
    memory = [0] * 30000
    pointer = 0
    output_string = ""
    code_length = len(code)
    code_pointer = 0

    loop_stack = []

    commands = {
        '>': lambda: nonlocal_pointer('+'),
        '<': lambda: nonlocal_pointer('-'),
        '+': lambda: increment_memory(),
        '-': lambda: decrement_memory(),
        '.': lambda: output_to_string(),
        ',': lambda: take_input(),
        '[': lambda: start_loop(),
        ']': lambda: end_loop()
    }

    def nonlocal_pointer(op):
        nonlocal pointer
        if op == '+':
            pointer += 1
        else:
            pointer -= 1

    def increment_memory():
        nonlocal memory, pointer
        memory[pointer] = (memory[pointer] + 1) % 256

    def decrement_memory():
        nonlocal memory, pointer
        memory[pointer] = (memory[pointer] - 1) % 256

    def output_to_string():
        nonlocal memory, pointer, output_string
        output_string += chr(memory[pointer])

    def take_input():
        nonlocal memory, pointer
        user_input = input("Enter input (1 character): ")
        memory[pointer] = ord(user_input[0])

    def start_loop():
        nonlocal memory, pointer, code_pointer, loop_stack
        if memory[pointer] == 0:
            count = 1
            while count != 0 and code_pointer < code_length - 1:
                code_pointer += 1
                if code[code_pointer] == '[':
                    count += 1
                elif code[code_pointer] == ']':
                    count -= 1
        else:
            loop_stack.append(code_pointer)

    def end_loop():
        nonlocal code_pointer, loop_stack
        if memory[pointer] != 0:
            code_pointer = loop_stack[-1]
        else:
            loop_stack.pop()

    while code_pointer < code_length:
        command = code[code_pointer]
        if command in commands:
            commands[command]()
        code_pointer += 1

    print("Output:", output_string)

interpret()