Last active
December 22, 2023 13:59
-
-
Save Stilic/a24707457547ea55319fbea0149eeefe to your computer and use it in GitHub Desktop.
Minimal interpreter for Brainfuck, written in Python. Doesn't make use of any AST, parses and interprets the code at the same time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." | |
position = 0 | |
memory = {} | |
pointer = 0 | |
def getPointerValue(): | |
try: | |
return memory[pointer] | |
except: | |
return 0 | |
while position < len(code): | |
char = code[position] | |
if char == ">": | |
pointer += 1 | |
elif char == "<": | |
pointer -= 1 | |
elif char == "+": | |
memory[pointer] = getPointerValue() + 1 | |
elif char == "-": | |
memory[pointer] = getPointerValue() - 1 | |
elif char == ".": | |
print(chr(getPointerValue()), end="") | |
elif char == ",": | |
memory[pointer] = ord(input("The program asks for input: ")[0]) | |
elif char == "[": | |
if getPointerValue() == 0: | |
position += 1 | |
endsToIgnore = 0 | |
while position < len(code): | |
char = code[position] | |
if char == "[": | |
endsToIgnore += 1 | |
elif char == "]": | |
if endsToIgnore > 0: | |
endsToIgnore -= 1 | |
else: | |
break | |
position += 1 | |
elif char == "]": | |
if getPointerValue() != 0: | |
position -= 1 | |
startsToIgnore = 0 | |
while position > 0: | |
char = code[position] | |
if char == "]": | |
startsToIgnore += 1 | |
elif char == "[": | |
if startsToIgnore > 0: | |
startsToIgnore -= 1 | |
else: | |
position -= 1 | |
break | |
position -= 1 | |
position += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment