bfpy
This commit is contained in:
commit
e5199c8f13
2 changed files with 82 additions and 0 deletions
11
README.md
Normal file
11
README.md
Normal file
|
@ -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:
|
||||
```
|
||||
+++++++++++++++++++++++++[>++>+++>++++>+++++<<<<-]+++++++++++++++++++++++++>>>++++.---.+++++++..+++.<<<+++++++.>>>>------.<.+++.------.--------.>+++++++.```
|
71
bf.py
Normal file
71
bf.py
Normal file
|
@ -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
|
||||
|
||||
|
||||
|
Loading…
Reference in a new issue