-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrainfuck_interpreter.py
91 lines (75 loc) · 2.46 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
#!/usr/bin/env python2
'''
One of my maths lecturers at Bristol University set us a task to answer what
is the sequence:
>+++++[<++>-]<+++ >++++[>+++<-]>[<++++>-]
<.+< . >. < . >-> >
+++++>+< [ >[> >+>+< < <-] > > >[< < <+> > >-]< < < >[<+>-]
< < < <[>+> > > > >+< < < < < <-] >[<+>-] > >
[< <+> > > > >+< < <-] < <[> >+< <-]> > > > >.[-]
< < < < < < < . > > > > > > [<+>-]< < <-]
begining of.
Being a computer scientist i didn't bother to do it by hand and wrote the
interpreter instead.
It is however missing the input ',' command.
'''
__author__ = "Adomas Venčkauskas"
__date__ = "2014-02"
import sys
import re
class BrainfuckInterpreter(object):
commands = {
'>': 'next',
'<': 'prev',
'+': 'inc',
'-': 'dec',
'[': 'jnz',
']': 'ctz',
'.': 'prt',
}
def __init__(self, code, memsize=20):
self.code = code
self.memory = [0] * memsize
self.mem_ptr = 0
self.ptr = 0
def next(self):
self.mem_ptr += 1
def prev(self):
self.mem_ptr -= 1
def inc(self):
self.memory[self.mem_ptr] += 1
def dec(self):
self.memory[self.mem_ptr] -= 1
def jnz(self):
brackCount = 0
if self.memory[self.mem_ptr] == 0:
self.ptr += 1
while(self.code[self.ptr] != ']' or brackCount != 0):
if(self.code[self.ptr] == '['): brackCount -= 1
elif(self.code[self.ptr] == ']'): brackCount += 1
self.ptr += 1
def ctz(self):
brackCount = 0
if self.memory[self.mem_ptr] != 0:
self.ptr -= 1
while(self.code[self.ptr] != '[' or brackCount != 0):
if(self.code[self.ptr] == '['): brackCount += 1
elif(self.code[self.ptr] == ']'): brackCount -= 1
self.ptr -= 1
def prt(self):
print chr(self.memory[self.mem_ptr])
def interpret(self):
while self.ptr < len(self.code):
c = self.code[self.ptr]
if(not re.match('[ \t\n]', c)):
method = getattr(self, BrainfuckInterpreter.commands[c])
method()
self.ptr += 1
if __name__ == '__main__':
if len(sys.argv) == 0:
print "Usage: ./brainfuck_interpreter <brainfuck code> [memory size]"
if len(sys.argv) > 2:
interpreter = BrainfuckInterpreter(sys.argv[1], sys.argv[2])
else:
interpreter = BrainfuckInterpreter(sys.argv[1])
interpreter.interpret()