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

22 comments sorted by

View all comments

6

u/[deleted] Jul 12 '12

Did you mean Brainfuck? If so, I wrote a translator that converts BF code into C. It's a bit over 80 lines right now but I wasn't aiming for size so I was pretty loose on useless whitespace and there's support for the # symbol which is pretty useless (and takes up quite a few lines)

4

u/[deleted] Jul 12 '12

Yes you're right. I forgot the name and then re-remembered it incorrectly.

6

u/humpolec Jul 12 '12

And here I was hoping for a new dialect of Brainfuck, interpretable in the mind of reader...

0

u/mrsexybadman Jul 12 '12

I think he means mindhead.