Poetic/Interpreter

From Esolang
Jump to navigation Jump to search
Back to Poetic
Back to PoeticFuck

This is a:

by User:None1 in Python.

import sys
from random import randint
def p2pf(code): # Translates Poetic to PoeticFuck
    res=''
    while code:
        p=0
        q=0
        while p<len(code) and code[p] in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'":
            q+=code[p].isalpha()
            p+=1
        if q:   
            if q==10:
                res+='0'
            else:
                res+=str(q)
        while p<len(code) and code[p] not in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'":
            p+=1
        code=code[p:]
    r=''
    while res:
        if res[0] in '3456':
            try:
                r+=';[]+-><.,?'[int(res[0])]*(int(res[1]) if int(res[1]) else 10)
                res=res[2:]
            except:
                break
        else:
            r+=';[]+-><.,?'[int(res[0])]
            res=res[1:]
    return r
def pf(code): # Interprets PoeticFuck
    s=[]
    matches={}
    tape=[0]*1000000
    for i,j in enumerate(code):
        if j=='[':
            s.append(i)
        if j==']':
            m=s.pop()
            matches[m]=i
            matches[i]=m
    cp=0
    p=0
    while cp<len(code):
        if code[cp]=='+':
            tape[p]=(tape[p]+1)%256
        if code[cp]=='-':
            tape[p]=(tape[p]-1)%256
        if code[cp]==',':
            c=sys.stdin.read(1)
            tape[p]=(ord(c) if c else tape[p])%256
        if code[cp]=='.':
            print(chr(tape[p]),end='')
        if code[cp]=='<':
            p-=1
        if code[cp]=='>':
            p+=1
        if code[cp]=='[':
            if not tape[p]:
                cp=matches[cp]
        if code[cp]==']':
            if tape[p]:
                cp=matches[cp]
        if code[cp]=='?':
            tape[p]=randint(0,255)
        if code[cp]==';':
            return
        cp+=1
if __name__=='__main__': # Direct execution: Interprets Poetic
    pf(p2pf(sys.stdin.read()))