commit e5199c8f13ed7775f39d51a5deca6e7bbcb940e1 Author: davidovski Date: Mon Aug 2 02:29:01 2021 +0100 bfpy diff --git a/README.md b/README.md new file mode 100644 index 0000000..73dda26 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# Brainfuck in python + +Experimenting with writing a brainfuck intepreter in python + +The bf program is passed in as a string argument to the python (¬‿¬) + +Excuse the code, I will add comments in the future + +Hello World: +``` ++++++++++++++++++++++++++[>++>+++>++++>+++++<<<<-]+++++++++++++++++++++++++>>>++++.---.+++++++..+++.<<<+++++++.>>>>------.<.+++.------.--------.>+++++++.``` diff --git a/bf.py b/bf.py new file mode 100644 index 0000000..55888f4 --- /dev/null +++ b/bf.py @@ -0,0 +1,71 @@ +import sys +import getch + +memory, stack, ptr, i, program = [0 for v in range(300000)], [], 0, 0, sys.argv[1] + + +while i < len(program): + cmd = program[i] + + memory[ptr], ptr = ( + (memory[ptr] - 1) % 256 + ) if cmd == "-" else ( + (memory[ptr] + 1) % 256 + ) if cmd == "+" else [ + lambda x: + memory[ptr], + lambda x: + ord(getch.getch()), + print( + chr(memory[ptr]), + end="") + if cmd == "." + else None + + ][ + 1 + if cmd == "," + else + 0 + ](None), ( + (ptr - 1) % len( + memory + ) + ) if cmd == "<" else ( + (ptr + 1) % len( + memory + ) + ) if cmd == ">" else ( + ptr + ) + + if cmd == "]": + depth = 0 + + while not (program[i] == "[" and depth == 0): + depth, i = ( + depth + 1 + ) if program[i-1] == "]" else ( + depth - 1 + ) if program[i-1] == "[" and depth != 0 else ( + depth + ), i-1 + i -= 1 + + if cmd == "[": + if memory[ptr] == 0: + depth = 0 + + while not (program[i] == "]" and depth == 0) and i < len(program): + depth, i = ( + depth + 1 + ) if program[i+1] == "[" else ( + depth - 1 + ) if program[1+i] == "]" and depth != 0 else ( + depth + ), i+1 + + i += 1 + + +