-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrainfuck-interpreter.py
96 lines (76 loc) · 3.09 KB
/
brainfuck-interpreter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import numpy as np
import time
def execute_brainfuck(program: str):
programpointer = 0 # The index of the current instruction
data = np.full(100000000, 0)
datapointer = 0 # The number of the cell that is currently pointed to
print("Now executing...\n\n")
while(programpointer < len(program)): # until the program ends, run its code
currentInstruction = program[programpointer]
if (currentInstruction == ">"): # Move right
datapointer = datapointer + 1
programpointer += 1
elif (currentInstruction == "<"): # Move left
datapointer -= 1
programpointer += 1
elif (currentInstruction == "+"): # Increment
data[datapointer] += 1
programpointer += 1
elif (currentInstruction == "-"): # Decrement
data[datapointer] -= 1
programpointer += 1
elif (currentInstruction == "."): # Write
print(chr(data[datapointer]), end="")
programpointer += 1
elif (currentInstruction == ","): # Read
userinput = input()
if (userinput == ""): # If no input is read, enter was inputted
userinput = "\n"
data[datapointer] = ord(userinput[0])
programpointer += 1
data[datapointer] %= 256 # Correct value to between 0 and 255
if (currentInstruction == "["): # Loops
if(data[datapointer] == 0):
# Now, find the corresponding ] and jump to the command after it
opens = 0
while (True): # The loop will be broken out of with break.
if(program[programpointer] == "["):
opens += 1
if(program[programpointer] == "]"):
opens -= 1
if(opens == 0):
break
programpointer += 1
programpointer += 1
else:
# Just continue execution without jumping
programpointer += 1
elif (currentInstruction == "]"):
if(data[datapointer] != 0):
# Now find the corresponding [ and jump to the command after it
opens = 0
while(True):
if(program[programpointer] == "]"):
opens += 1
if(program[programpointer] == "["):
opens -= 1
if(opens == 0):
break
programpointer -= 1
programpointer += 1
else:
# Just continue execution without jumping
programpointer += 1
if(currentInstruction not in "+-<>[].,"):
print("Unknown Instruction:")
print((currentInstruction+"Unicode"+ord(currentInstruction)))
print("Stopping execution.")
break
print("Please input your Brainfuck program:")
line = input()
program = ""
while(line != ""):
program += line
line = input()
execute_brainfuck(program)
time.sleep(5)