Created
May 16, 2014 01:55
-
-
Save pzp1997/354c2a20ea56f9c944aa to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in Python.
This file contains hidden or 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
## Brainfuck.py by pzp1997 (May 11, 2014) | |
## Written in Python 3.4.0 | |
def interpreter(program, userInput): | |
array = [0]*30000 | |
pointer = 0 | |
pc = 0 | |
nest = 1 | |
while pc < len(program): | |
if program[pc] == ">": | |
if pointer + 1 == len(array): | |
array.append(0) | |
pointer += 1 | |
elif program[pc] == "<": | |
pointer -= 1 | |
elif program[pc] == "+": | |
array[pointer] += 1 | |
elif program[pc] == "-": | |
array[pointer] -= 1 | |
elif program[pc] == ".": | |
print(chr(array[pointer]), end="") | |
elif program[pc] == ",": | |
try: | |
array[pointer] = ord(userInput[0]) | |
userInput = userInput[1:] | |
except IndexError: | |
break | |
elif program[pc] == "[": | |
if array[pointer] == 0: | |
while pc < len(program): | |
pc += 1 | |
if program[pc] == "]": | |
nest -= 1 | |
elif program[pc] == "[": | |
nest += 1 | |
if nest == 0: | |
nest = 1 | |
break | |
elif program[pc] == "]": | |
if array[pointer] != 0: | |
while pc > 0: | |
pc -= 1 | |
if program[pc] == "]": | |
nest += 1 | |
elif program[pc] == "[": | |
nest -= 1 | |
if nest == 0: | |
nest = 1 | |
break | |
pc += 1 | |
def main(): | |
print("Brainfuck.py by pzp1997 (May 11, 2014)") | |
print("Written in Python 3.4.0") | |
print() | |
while True: | |
code = input() | |
if "," in code: | |
interpreter(code, input("Input: ")) | |
else: | |
interpreter(code, "") | |
print() | |
print("End of program.") | |
print() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment