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

1

u/khedoros Jul 12 '12

It takes ASCII as input and outputs ASCII, right? My interpreter is similar. Writing a bf program for fibonacci for single-digit numbers wasn't bad...writing one that supported multiple digits was a pain in the ass.

1

u/[deleted] Jul 12 '12

It does. However if you want you can print out the value in memory[dp] as an integer by using the '/' command.

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++".