Skip to content

Instantly share code, notes, and snippets.

@rayansostenes
Last active March 19, 2023 06:39
Show Gist options
  • Save rayansostenes/8c5eda21919f975f8dcfe65798ba566a to your computer and use it in GitHub Desktop.
Save rayansostenes/8c5eda21919f975f8dcfe65798ba566a to your computer and use it in GitHub Desktop.
Brainfuck Interpreter in Python
from __future__ import annotations
import curses
CODE = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
INCREMENT_PTR = ">"
DECREMENT_PTR = "<"
INCREMENT_VAL = "+"
DECREMENT_VAL = "-"
OUTPUT_VAL = "."
INPUT_VAL = ","
LOOP_START = "["
LOOP_END = "]"
def main(stdscr: curses._CursesWindow) -> None:
"""Main function."""
stdscr.clear()
data: list[int] = [0] * 30000
jump_stack: list[int] = []
data_pointer = 0
instruction_pointer = 0
op_code = CODE[instruction_pointer]
while op_code:
next_instruction = instruction_pointer + 1
if data_pointer >= len(data) or data_pointer < 0:
raise IndexError("Pointer out of bounds")
if op_code == INCREMENT_PTR:
data_pointer += 1
elif op_code == DECREMENT_PTR:
data_pointer -= 1
elif op_code == INCREMENT_VAL:
data[data_pointer] += 1
elif op_code == DECREMENT_VAL:
data[data_pointer] -= 1
elif op_code == OUTPUT_VAL:
stdscr.addstr(chr(data[data_pointer]))
elif op_code == INPUT_VAL:
data[data_pointer] = ord(stdscr.getkey())
elif op_code == LOOP_START:
if data[data_pointer] == 0:
counter = 0
while instruction_pointer < len(CODE):
instruction_pointer += 1
counter += CODE[instruction_pointer] == LOOP_START
if CODE[instruction_pointer] == LOOP_END:
if counter:
counter -= 1
else:
break
else:
jump_stack.append(instruction_pointer)
elif op_code == LOOP_END:
jump_to = jump_stack.pop()
if data[data_pointer]:
next_instruction = jump_to
try:
instruction_pointer = next_instruction
op_code = CODE[instruction_pointer]
except IndexError:
break
stdscr.addstr("\n\nProgram finished. Press any key to exit.")
stdscr.getkey()
if __name__ == "__main__":
curses.wrapper(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment