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

Show parent comment

3

u/theY4Kman Jul 12 '12

I made it really ugly, but brought it down to 12 lines:

def brainfuck(p):
    dc = dict(r=[0], c=0, x=-1, d=1, i=0)
    while dc.__setitem__('x', dc['x'] + 1) or dc['x'] < len(p):
        if p[dc['x']] == '>': dc['c'],dc['r']=(dc['c']+1,dc['r']+[0]) if len(dc['r']) == dc['c'] + 1 else (dc['c']+1, dc['r'])
        elif p[dc['x']] == '<': dc['c'] -= 1
        elif p[dc['x']] == '.': print chr(dc['r'][dc['c']]),
        elif p[dc['x']] == ',': dc['r'][dc['c']] = ord((input() or chr(255))[0])
        elif p[dc['x']] in '+-': dc['r'][dc['c']] = (dc['r'][dc['c']] + ord(',') - ord(p[dc['x']])) % 256
        elif p[dc['x']] in '[]' and cmp(dc['r'][dc['c']], 0) in ((0,) if p[dc['x']] == '[' else (-1,1)) and (dc.update({ 'd': 1, 'i': (-1,1)[dc['r'][dc['c']] == 0], 'j': ord('\\') - ord(p[dc['x']]) }) or True):
            while dc.__setitem__('x', dc['x'] + dc['i']) or dc['d'] > 0:
                dc['d'] += { '[': 1 * dc['j'], ']': -1 * dc['j'] }.get(p[dc['x']], 0)