Created
September 3, 2021 19:37
-
-
Save AMiller42/3639ea03b6e4b59f2d78b36d20efe30b to your computer and use it in GitHub Desktop.
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
""" | |
Make a brainfuck interpreter. | |
""" | |
import sys | |
bf = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." | |
def run(program): | |
inputptr = 0 | |
data = [0] | |
ptr = 0 | |
head = 0 | |
while head < len(program): | |
if program[head] == ">": | |
ptr += 1 | |
if ptr == len(data): | |
data.append(0) | |
elif program[head] == "<": | |
ptr -= 1 | |
elif program[head] == "+": | |
data[ptr] = (data[ptr] + 1) % 256 | |
elif program[head] == "-": | |
data[ptr] = (data[ptr] - 1) % 256 | |
elif program[head] == ".": | |
sys.stdout.write(chr(data[ptr])) | |
elif program[head] == ",": | |
data[ptr] = ord(sys.stdin.read(1)) | |
elif program[head] == "[": | |
if data[ptr] == 0: | |
count = 1 | |
while count != 0: | |
head += 1 | |
if program[head] == "[": | |
count += 1 | |
elif program[head] == "]": | |
count -= 1 | |
elif program[head] == "]": | |
if data[ptr] != 0: | |
count = 1 | |
while count != 0: | |
head -= 1 | |
if program[head] == "]": | |
count += 1 | |
elif program[head] == "[": | |
count -= 1 | |
head += 1 | |
if __name__ == "__main__": | |
if len(sys.argv) == 2: | |
run(sys.argv[1]) | |
else: | |
run(bf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment