martes, 27 de julio de 2010

Hablando en esotérico

Hoy traigo un script que programa en lenguajes esotéricos, concretamente en Brainfuck, Ook!, Whitespace y Zombie.

Lo único que hace es escribir un programa que muestre por pantalla lo que el usuario pida, su uso es:


./esoprint.py [-h]  [-l <lenguaje>] [-o <archivo de salida>] [<datos> [<datos> | -n [...] ] | -n]
-h (--help): muestra esta "ayuda"
-l (--language): Selecciona el lenguaje
-o (--output) : Selecciona el archivo de salida (a stdout por defecto)
El resto se toma como información, el -n (--newline) es considerado un salto de línea



El script se puede descargar [aquí] o al final coloreado

Dejando a parte de Brainfuck y Ook!, de los que se habló antes, Whitespace es un lenguaje compuesto únicamente por espacios, tabuladores y saltos de línea, con un conjunto de instrucciones bastante completo [Whitespace Tutorial] . Zombie está por estar, ni siquiera encontré un intérprete así que no puedo asegurar que funcione, simplemente parecía fácil de programar :).

Y eso es todo.

Tengo que dejar la manía de poner los comentarios en inglés :S ...

[Referencias]
http://compsoc.dur.ac.uk/whitespace/
http://esoteric.voxelperfect.net/wiki/Main_Page



#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
   esoprint.py, encodes in esoteric language code

   Supported languages:
   - Brainfuck
   - Ook!
   - Whitespace
   - Zombie # Blindly coded, not tested

   Maybe future supported languages:
   - Tink
   - Piet
   - Befunge
   - False
   - Q-BAL # When I find a interpreter
   - Malbolge # Maybe too big...
   - Beatnik # Really ¿?
   - Unlambda

   Not future supported languages:
   # It's not a logical thing to make a computer generate this!
   - Sheakspere
   - Haiku
   - Chef
   # Make's it boring
   - Whenever
   # Impossible
   - HQ9+
   - BIT

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   Copyright (C) 2010 kenkeiras <kenkeiras@gmail.com>

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Usage:

./esoprint.py [-h]  [-l <language>] [-o <output file>] [<data> [<data> | -n [...] ] | -n]
-h (--help): prints this help
-l (--language): Set's output language, currently supported: Ook!, Brainf*ck, Whitespace, Zombie
-o (--output) : Set's output file (to stdout by default)
Whatever else is considered as data, the -n (--newline) is considered a line jump

"""

# Language dictionary elements for BrainFuck-like langs
# init: program initalization
# inc
# dec
# push
# pop
# show
# # get [Actually unused]

def usage():
    import sys

    print sys.argv[0]+" [-h]  [-l <language>] [-o <output file>] [<data> [<data> | -n [...] ] | -n] "
    print "-h (--help): prints this help"
    print "-l (--language): Set's output language"
    print "-o (--output) : Set's output file (to stdout by default)"
    print "Whatever else is considered as data, the -n (--newline) is considered a line jump"
    print "If no data is entered, it will be received from STDIN"
    print "Supported languages:"
    print """   - Brainfuck
   - Ook!
   - Whitespace
   - Zombie
"""

brainfuck = {
    "init": "",
    "inc":"+",
    "dec":"-",
    "push":">",
    "pop":"<",
    "show":".",
    "get":",",    #Unused
    "loop":"[",  # Unused
    "endloop":"]" # Unused
}

ook = {
    "init": "",
    "inc":"Ook. Ook. ",
    "dec":"Ook! Ook! ",
    "push":"Ook. Ook? ",
    "pop":"Ook? Ook. ",
    "show":"Ook! Ook. ",
    "get":"Ook. Ook! ",    # Unused
    "loop":"Ook! Ook? ",  # Unused
    "endloop":"Ook? Ook! " # Unused
}

# Encodes in a Zombie program
def zombie_encode(data):

    z = "Dundun is a zombie\n"
    z += "    summon\n"
    z += "    task talk\n"
    for p in data.split("\n"):
        z += "        say \""+str( p.replace("\"","\\\"") )+"\"\n"
    z += "    animate\n"
    z += "animate"
    return z

# Encodes in a Whitespace program
def whitespace_encode(data):
    for c in data:
        w += "  " # Push into the stack: [Space] [Space]
        w += " " # Element, always positive [Space]
        # Character to binary (needed)
        b = bin( ord( c ) )
        w += b[ 2 : ].replace("0"," ").replace("1","\t") #   Space: 0 || Tab: 1
        w += "\n" # Element end: [LF]
        w += "\t\n  " # Output stack top: [Tab][LF][Space][Space]

    w += "\n\n\n" # Ending [LF][LF]
    return w

# Encodes in a Brainf*ck-like language
def stack_encode(lang, data):
    s = lang['init']
    n = 0
    for c in data:
        i = ord( c )
        while ( n > i ):
            s += lang['dec']
            n -= 1

        while ( n < i ):
            s += lang['inc']
            n += 1

        s += lang['show']

    return s

bf_like = {"brainfuck":brainfuck,"ook":ook}
langlist = {"whitespace":whitespace_encode,"zombie":zombie_encode}
if __name__ == "__main__":

    import sys
    argc=len(sys.argv)
    lang=""
    data=""
    out = ""
    i=1
    while (i < argc):
        if (sys.argv[i] == "-l") or (sys.argv[i] == "--language"):
            i += 1
            lang = sys.argv[i]

        elif (sys.argv[i] == "-o") or (sys.argv[i] == "--output"):
            i += 1
            out = sys.argv[i]

        elif (sys.argv[i] == "-h") or (sys.argv[i] == "--help"):
            usage()
            sys.exit(0)

        elif (sys.argv[i] == "-n") or (sys.argv[i] == "--newline"):
            data += "\n"

        else:
            data = (data+" "+sys.argv[i]).strip()

        i+=1
    if (lang == ""):
        lang = raw_input("Select language: ")

    lang = lang.lower()
    if (lang not in langlist) and (lang not in bf_like):

        print "Unknown language (lenguaje desconocido)"
        sys.exit(1)

    if (data == ""):
        for line in sys.stdin:
            data += line

    if (data == "\n"):
        print "Sin entrada, saliendo..."

        sys.exit(0)

    if (lang in langlist):
        result = langlist[lang](data)
    else:
        result = stack_encode(bf_like[lang],data)

    if (out == ""):
        print result

    else:
        f = open(out,"w")
        f.write(result)
        f.close()

No hay comentarios:

Publicar un comentario