import os
import time
import random
import shutil

clear = lambda: print("\033[H\033[J", end="")
COLS, ROWS = shutil.get_terminal_size((100, 30))

RESET = "\033[0m"

def cor_ansi(n):
    return f"\033[38;5;{n}m"

# =========================
# 🎨 CORES (nomes)
# =========================

cores_dict = {
    "preto": 0,
    "vermelho": 1,
    "verde": 2,
    "amarelo": 3,
    "azul": 4,
    "magenta": 5,
    "ciano": 6,
    "branco": 7,
    "cinza": 8,
    "vermelho_claro": 9,
    "verde_claro": 10,
    "amarelo_claro": 11,
    "azul_claro": 12,
    "magenta_claro": 13,
    "ciano_claro": 14,
    "branco_brilhante": 15
}

# =========================
# 🎭 EMOJIS
# =========================

def emoji_normal(frame):
    olho = "o" if frame % 20 < 18 else "-"
    return [
    "    _________    ",
    "   /         \\   ",
    "  /           \\  ",
    f" |   {olho}     {olho}   | ",
    " |      ^      | ",
    " |    \\___/    | ",
    " |             | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

def emoji_chorando(frame):
    lag_y = frame % 6
    base = [
    "    _________    ",
    "   /         \\   ",
    "  /           \\  ",
    " |   o     o   | ",
    " |      ^      | ",
    " |    \\___/    | ",
    " |             | ",
    "  \\           /  ",
    "   \\_________/   "
    ]
    if lag_y < 6:
        linha = list(base[3])
        linha[14] = "|"
        base[3] = "".join(linha)
        if 4 + lag_y < len(base):
            l = list(base[4 + lag_y])
            l[14] = "|"
            base[4 + lag_y] = "".join(l)
    return base

def emoji_bravo(frame):
    return [
    "    _________    ",
    "   /  _____  \\   ",
    "  /  >     <  \\  ",
    " |      ^      | ",
    " |    \\___/    | ",
    " |             | ",
    " |             | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

def emoji_estrela(frame):
    estrela = "*" if frame % 10 < 5 else "+"
    return [
    "    _________    ",
    "   /         \\   ",
    "  /           \\  ",
    f" |   {estrela}     {estrela}   | ",
    " |      ^      | ",
    " |    \\___/    | ",
    " |             | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

def emoji_sono(frame):
    z = ["Z", "z", "Z"]
    return [
    f"      {z[frame%3]}        ",
    "    _________    ",
    "   /         \\   ",
    "  /           \\  ",
    " |   -     -   | ",
    " |      o      | ",
    " |    \\___/    | ",
    " |             | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

def emoji_caveira(frame):
    boca = "_" if frame % 10 < 5 else "-"
    return [
    "    _________    ",
    "   /         \\   ",
    "  /  x     x  \\  ",
    " |      ^      | ",
    f" |    {boca*5}    | ",
    " |   |     |   | ",
    " |   |_____|   | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

def emoji_robo(frame):
    olho = "o" if frame % 6 < 3 else "O"
    return [
    "    _________    ",
    "   /  _____  \\   ",
    f"  /  |{olho}   {olho}|  \\  ",
    " |   |  -  |   | ",
    " |   |_____|   | ",
    " |     | |     | ",
    " |    _| |_    | ",
    "  \\           /  ",
    "   \\_________/   "
    ]

tipos = [emoji_normal, emoji_chorando, emoji_bravo, emoji_estrela, emoji_sono, emoji_caveira, emoji_robo]

emojis_dict = {
    "normal": emoji_normal,
    "chorando": emoji_chorando,
    "bravo": emoji_bravo,
    "estrela": emoji_estrela,
    "sono": emoji_sono,
    "caveira": emoji_caveira,
    "robo": emoji_robo
}

# =========================
# 🎮 ENTRADA
# =========================

print("Emojis disponíveis:", ", ".join(emojis_dict.keys()))

print("\n=== CORES ===")
print("Você pode escolher de 2 formas:")
print("1) Nome: vermelho, azul, verde...")
print("2) Número: 0 até 255")
print("\nExemplos:")
print("vermelho | azul | 196 | 46 | 226\n")

print ("Mas é melhor usar o nome da cor do que o número!")

print("Cores básicas:", ", ".join(cores_dict.keys()))

tempo = int(input("T> "))
velocidade = int(input("V> "))
escolha = input("E> ").strip().lower()
cor_input = input("C> ").strip().lower()

# escolher cor
if cor_input.isdigit():
    cor_num = int(cor_input)
elif cor_input in cores_dict:
    cor_num = cores_dict[cor_input]
else:
    cor_num = 226  # padrão

COR_BASE = cor_ansi(cor_num)

delay = max(0.01, 0.1 * (100 / max(velocidade, 1)))

# =========================
# OBJETOS
# =========================

objs = []
for _ in range(6):
    objs.append({
        "x": random.randint(0, COLS-20),
        "y": random.randint(0, ROWS-12),
        "dx": random.choice([-1, 1]),
        "dy": random.choice([-1, 0, 1]),
        "tipo": emojis_dict.get(escolha, random.choice(tipos)),
        "frame": 0
    })

# =========================
# DESENHO
# =========================

def draw(forma, x, y, tela):
    for i, linha in enumerate(forma):
        for j, ch in enumerate(linha):
            tx = x + j
            ty = y + i
            if 0 <= tx < COLS and 0 <= ty < ROWS:
                tela[ty][tx] = COR_BASE + ch + RESET

# =========================
# LOOP
# =========================

inicio = time.time()

try:
    while time.time() - inicio < tempo:
        tela = [[" "]*COLS for _ in range(ROWS)]

        for o in objs:
            forma = o["tipo"](o["frame"])
            draw(forma, o["x"], o["y"], tela)

            o["x"] += o["dx"]
            o["y"] += o["dy"]
            o["frame"] += 1

            if o["x"] <= 0 or o["x"] >= COLS-20:
                o["dx"] *= -1
            if o["y"] <= 0 or o["y"] >= ROWS-12:
                o["dy"] *= -1

        clear()
        for linha in tela:
            print("".join(linha))

        time.sleep(delay)

except KeyboardInterrupt:
    clear()
    print("Encerrado")
