3 # Brainfuck Interpreter
4 # Copyright 2011 Sebastian Kaspari
5 # Trivial mods 2014 Rob Myers
7 # Usage: ./brainfuck.py [FILE]
10 from dogecode.getch import getch
12 def execute(filename):
13 f = open(filename, "r")
19 code = cleanup(list(code))
20 bracemap = buildbracemap(code)
22 cells, codeptr, cellptr = [0], 0, 0
24 while codeptr < len(code):
25 command = code[codeptr]
29 if cellptr == len(cells): cells.append(0)
32 cellptr = 0 if cellptr <= 0 else cellptr - 1
35 cells[cellptr] = cells[cellptr] + 1 if cells[cellptr] < 255 else 0
38 cells[cellptr] = cells[cellptr] - 1 if cells[cellptr] > 0 else 255
40 if command == "[" and cells[cellptr] == 0: codeptr = bracemap[codeptr]
41 if command == "]" and cells[cellptr] != 0: codeptr = bracemap[codeptr]
42 if command == ".": sys.stdout.write(chr(cells[cellptr]))
43 if command == ",": cells[cellptr] = ord(getch.getch())
49 return list(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))
52 def buildbracemap(code):
53 temp_bracestack, bracemap = [], {}
55 for position, command in enumerate(code):
56 if command == "[": temp_bracestack.append(position)
58 start = temp_bracestack.pop()
59 bracemap[start] = position
60 bracemap[position] = start
65 if len(sys.argv) == 2: execute(sys.argv[1])
66 else: print("Usage:", sys.argv[0], "filename")
68 if __name__ == "__main__": main()