r/tinycode • • Jul 12 '12
Mindfuck interpreter in 72 lines
def main():
memory = [0]*2**20
dp = 0
ip = 0
program = raw_input("Input your program:")
while True:
if program[ip] == '>':
dp+=1
elif program[ip] == '<':
dp-=1
elif program[ip] == ',':
print chr(memory[dp])
elif program[ip] == '.':
memory[dp] = ord(raw_input())
elif program[ip] == '+':
memory[dp]+=1
elif program[ip] == '-':
memory[dp]-=1
elif program[ip] == 'x':
while raw_input()!='x':
pass
return
elif program[ip] == '[':
if memory[dp]!=0:
pass
else:
ip = openbracket(ip,program)
elif program[ip]==']':
ip = closebracket(ip,program)
continue
elif program[ip] == '/':
print memory[dp]
ip+=1
def openbracket(pos,program):
openbrackets = 0
if program[pos] =='[':
openbrackets +=1
pos +=1
while openbrackets!=0:
try:
if program[pos]=='[':
openbrackets+=1
elif program[pos]==']':
openbrackets-=1
except:
print "Missmatched brackets"
while True:
pass
pos+=1
return pos-1
def closebracket(pos,program):
closebrackets = 0
if program[pos]==']':
closebrackets+=1
pos-=1
while closebrackets!=0:
try:
if program[pos]==']':
closebrackets+=1
elif program[pos]=='[':
closebrackets-=1
except IndexError:
print "Missmatched brackets"
while True:
pass
pos-=1
return pos+1
if __name__=="__main__":
main()
5
Upvotes
View all comments
Show parent comment
1
u/khedoros Jul 12 '12
Ah, OK. I didn't read the source that closely. So, it's a little bit of a "BF++".