Brainfu * k par QPython

brainfuck.py

from __future__ import print_function
from sys import stdin,stdout
class Brainfuck:
    def __init__(s,OPs="><+-.,[]",size=30000):
        s.clear(size)
        s.const(OPs)
        #return super().__new__(self)
    def compile(s,code):
        s.prgs = []
        tmps = []
        for op in code:
            if not op in s.opDic:
                continue
            prg = s.opDic[op]()
            prg.idx = len(s.prgs)
            if prg.block1:
                tmps += [prg]
            elif prg.block2:
                prg1 = tmps.pop()
                prg.op1 = prg1
                prg1.op2 = prg
            #end if
            s.prgs += [prg]
    def run(s,defmem=None,limit=1000,out=stdout):
        s.pc = 0
        s.out = out
        if not defmem is None:
            s.write(defmem)
        step = 0
        while s.pc<len(s.prgs):
            s.prgs[s.pc].do(s)
            step+=1
            if step > limit:
                raise RuntimeWarning("step limit(%s) over!"%(limit))
                break
    def clear(s,size=None):
        if size is None:
            size = len(s.mem)
            print("size:%d"%size)
        s.mem = bytearray(size)
        s.pt = 0
    def write(s,datam):
        for idx,data in zip(range(len(datam)),datam):
            s.mem[s.pt+idx] = data
    def const(s,OPs):
        s.opDic = {}
        s.opDic[OPs[0]]=opNxt # op >
        s.opDic[OPs[1]]=opPrv # op <
        s.opDic[OPs[2]]=opInc # op +
        s.opDic[OPs[3]]=opDec # op -
        s.opDic[OPs[4]]=opOut # op .
        s.opDic[OPs[5]]=opInp # op ,
        s.opDic[OPs[6]]=opJp1 # op [
        s.opDic[OPs[7]]=opJp2 # op ]
#end class
class op:
    block1 = False
    block2 = False
#end class
class opNxt(op):
    def do(s,bf):
        bf.pt+=1
        bf.pc+=1
#end class
class opPrv(op):
    def do(s,bf):
        bf.pt-=1
        bf.pc+=1
#end class
class opInc(op):
    def do(s,bf):
        bf.mem[bf.pt]+=1
        bf.pc+=1
#end class
class opDec(op):
    def do(s,bf):
        bf.mem[bf.pt]-=1
        bf.pc+=1
#end class
class opInp(op):
    def do(s,bf):
        bf.mem[bf.pt] = stdin.readline()
        bf.pc+=1
#end class
class opOut(op):
    def do(s,bf):
        #print(chr(bf.mem[bf.pt]),end="")
        bf.out.write(chr(bf.mem[bf.pt]))
        bf.pc+=1
#end class
class opJp1(op):
    block1=True
    def do(s,bf):
        if bf.mem[bf.pt]==0:
            bf.pc = s.op2.idx
        bf.pc+=1
#end class
class opJp2(op):
    block2=True
    def do(s,bf):
        if bf.mem[bf.pt]!=0:
            bf.pc = s.op1.idx
        bf.pc+=1
#end class      

Recommended Posts

Brainfu * k par QPython
Hello World! Par QPython avec Brainfu * k
Braincrash par QPython
Hello World! Par QPython avec Braincrash