-
Notifications
You must be signed in to change notification settings - Fork 0
/
bf_interpreter.py
68 lines (47 loc) · 1.64 KB
/
bf_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
#!/usr/bin/python3
#
# Brainfuck interpreter with read from the file
# Copyright 2017 Kamil Szpakowski
#
# You can use it like this: ./bf_interpreter.py [FILENAME]
import sys
def execute(filename):
f = open(filename, 'r')
translate(f.read())
f.close()
def translate(commands):
cells, cell_pointer, code_pointer = [0], 0, 0
bf_code = list(commands)
stack = []
while code_pointer < len(bf_code):
if bf_code[code_pointer] == '>':
cell_pointer += 1
if cell_pointer == len(cells): cells.append(0)
if bf_code[code_pointer] == '<':
if cell_pointer <= 0:
cell_pointer = 0
else:
cell_pointer -= 1
if bf_code[code_pointer] == '+':
if cells[cell_pointer] < 255:
cells[cell_pointer] += 1
else:
cells[cell_pointer] = 0
if bf_code[code_pointer] == '-':
if cells[cell_pointer] > 0:
cells[cell_pointer] -= 1
else:
cells[cell_pointer] = 255
if bf_code[code_pointer] == '.': print(chr(cells[cell_pointer]))
if bf_code[code_pointer] == ',': cells[cell_pointer] = ord(input('Write a sign: '))
if bf_code[code_pointer] == '[':
stack.append(code_pointer)
if bf_code[code_pointer] == ']' and cells[cell_pointer] != 0:
code_pointer = stack[-1]
if bf_code[code_pointer] == ']' and cells[cell_pointer] == 0:
stack.pop()
code_pointer += 1
def main():
if len(sys.argv) == 2: execute(sys.argv[1])
else: print('Try:', sys.argv[0], 'filename.')
main()