Script que recebe pela linha de comando um arquivo contendo código fonte na linguagem BrainFuck e o interpreta. Pode ser facilmente extendido, sinta-se a vontade para criar sua própria implementação de BrainFuck
1 import sys
2 import re
3
4 # Variables
5 arq = None
6 top = 30000
7 ptr = 0
8 cou = 0
9 src = ''
10
11 segment = [0 for i in range(top)]
12 loops = []
13
14 # Opening the file
15 if len(sys.argv) < 2:
16 print "Usage: mybf.py myscript.bf"
17 sys.exit(1)
18 else:
19 try:
20 arq = open(sys.argv[1], 'r')
21 src = ''.join(arq.readlines())
22 arq.close()
23 del arq
24 except Exception, e:
25 print "Can't read the specifyed script."
26 sys.exit(1)
27
28 # Eliminating non-bf characters
29 src = re.sub('[^\+\-\.\[\],<>]', '', src);
30
31 # Verifyig the brackets equivalency
32 (lbrackets, rbrackets) = (src.count('['), src.count(']'))
33 if lbrackets != rbrackets:
34 print "Missing brackets -> ([: %d | ]: %d)" % (lbrackets, rbrackets)
35 sys.exit(1)
36
37 # Execution loop
38 while cou < len(src):
39 ch = src[cou]
40 cou += 1
41
42 if ch == '+':
43 segment[ptr] += 1
44 if segment[ptr] > 256: segment[ptr] = 0
45
46 if ch == '-':
47 segment[ptr] -= 1
48 if segment[ptr] < 0: segment[ptr] = 256
49
50 if ch == '>':
51 ptr += 1
52 if ptr == top: ptr = 0
53
54 if ch == '<':
55 ptr -= 1
56 if ptr < 0: ptr = top-1
57
58 if ch == ',':
59 tmp = raw_input()
60 if tmp: segment[ptr] = ord(tmp[0])
61
62 if ch == '.':
63 print chr(segment[ptr]),
64
65 if ch == '[':
66 loops.append(cou)
67
68 if ch == ']':
69 if segment[ptr] != 0:
70 cou = loops[len(loops) - 1]
71 else:
72 loops.pop()
Danillo Souza <danillo012@gmail.com>