import pyxel
import random

pyxel.init(256, 256, title="space")

pyxel.load("3.pyxres")

# --- Variables du jeu ---
x_fusee = 125
y_fusee = 93
x_feu = x_fusee + 4
y_feu = y_fusee + 16
sc = 0
muni = 10
timers = 0
tf = 0
vies = 3
munition_timer = 0

bullet = []
monstres = []
spawn_timer = 0
spawn_delay = pyxel.rndi(10, 60)  # délai spawn initial

# Ajout d'étoiles en fond
stars = [[random.randint(0, 255), random.randint(0, 255)] for _ in range(200)]

# --- Variables menu ---
menu_active = True
menu_options = ["Jouer", "Skin"]
menu_selection = 0

game_over = False

def Bullet():
    global bullet, muni
    if muni >= 2:  # vérifier qu'il y a au moins 2 munitions
        bullet.append([x_fusee + 4, y_fusee])
        bullet.append([x_fusee - 5, y_fusee])  # deuxième balle décalée à gauche
        muni -= 2  # retirer 2 munitions à chaque tir double

def spawn_monstre():
    x = pyxel.rndi(0, 240)
    y = -16
    sprites = {
        0: (1, 50),
        16: (2, 100),
        32: (3, 150),
        48: (4, 200),
        64: (5, 250)
    }
    sprite_index = random.choice(list(sprites.keys()))
    vitesse, valeur = sprites[sprite_index]
    monstres.append([x, y, sprite_index, vitesse, valeur])
    # Spawn supplémentaire pour doubler la quantité
    x2 = pyxel.rndi(0, 240)
    sprite_index2 = random.choice(list(sprites.keys()))
    vitesse2, valeur2 = sprites[sprite_index2]
    monstres.append([x2, y, sprite_index2, vitesse2, valeur2])

def update():
    global x_fusee, y_fusee, timers, x_feu, y_feu, tf
    global spawn_timer, spawn_delay, bullet, monstres, sc, muni, vies, game_over
    global menu_active, menu_selection
    global munition_timer

    if not game_over:
        munition_timer += 1
        if munition_timer >= 180:  # 3 secondes * 60 FPS
            muni += 1
            munition_timer = 0

    # Mise à jour étoiles (vitesse x2)
    for star in stars:
        star[1] += 2
        if star[1] > 255:
            star[0] = random.randint(0, 255)
            star[1] = 0

    if menu_active:
        # Navigation menu
        if pyxel.btnp(pyxel.KEY_LEFT) or pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_LEFT):
            menu_selection = (menu_selection - 1) % len(menu_options)
        if pyxel.btnp(pyxel.KEY_RIGHT) or pyxel.btnp(pyxel.GAMEPAD1_BUTTON_DPAD_RIGHT):
            menu_selection = (menu_selection + 1) % len(menu_options)

        # Validation choix
        if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.GAMEPAD1_BUTTON_A):
            if menu_options[menu_selection] == "Jouer":
                menu_active = False
                reset_game()
            elif menu_options[menu_selection] == "Skin":
                # Pour l'instant, on peut juste afficher un message ou implémenter plus tard
                # Ici on pourrait lancer un écran de sélection skin, mais on fait rien pour l'instant
                pass
        return

    if game_over:
        # Dans game over, Q revient au menu (ne quitte plus)
        if pyxel.btnp(pyxel.KEY_Q):
            menu_active = True
            game_over = False
        return

    # Touche secrète 'S' ajoute 1000 points
    if pyxel.btnp(pyxel.KEY_S):
        sc += 1000

    # Contrôles du jeu
    if (pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_LEFT)) and x_fusee > -2:
        x_fusee -= 3
        timers = max(timers - 2, -8)
        tf = max(tf - 2, -8)
    if (pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_RIGHT)) and x_fusee < 241:
        x_fusee += 3
        timers = min(timers + 2, 8)
        tf = max(tf - 2, -8)
    if (pyxel.btn(pyxel.KEY_UP) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_UP)) and y_fusee > 0:
        y_fusee -= 3
        tf = max(tf - 2, -8)
    if (pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_DOWN)) and y_fusee < 211:
        y_fusee += 3
        tf = max(tf - 2, -8)
    if (pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.GAMEPAD1_BUTTON_A)) and y_fusee > 0:
        Bullet()

    timers = timers - 1 if timers > 0 else (timers + 1 if timers < 0 else 0)
    tf = tf - 1 if tf > 0 else (tf + 1 if tf < 0 else 0)

    x_feu = x_fusee + 4
    y_feu = y_fusee + 16

    for b in bullet:
        b[1] -= 4
    bullet[:] = [b for b in bullet if b[1] > -16]

    spawn_timer += 1
    if spawn_timer >= spawn_delay:
        spawn_monstre()
        spawn_timer = 0
        if sc <= 10000:
            spawn_delay = pyxel.rndi(10, 60)
        elif sc <= 50000:
            spawn_delay = pyxel.rndi(10, 30)
        else:
            spawn_delay = pyxel.rndi(5, 20)

    for m in monstres:
        m[1] += m[3]

    for b in bullet:
        for m in monstres:
            if abs(b[0] - m[0]) < 12 and abs(b[1] - m[1]) < 12:
                if m in monstres:
                    sc += m[4]
                    monstres.remove(m)
                if b in bullet:
                    bullet.remove(b)
                muni += 3
                break

    for m in monstres[:]:
        if abs(m[0] - x_fusee) < 12 and abs(m[1] - y_fusee) < 12:
            vies -= 1
            monstres.remove(m)
            if vies <= 0:
                game_over = True

    for m in monstres[:]:
        if m[1] >= 256:
            sc = max(sc - 10, 0)
            monstres.remove(m)

def draw():
    if menu_active:
        pyxel.cls(0)
        # Étoiles tombantes sur fond noir
        for star in stars:
            pyxel.pset(star[0], star[1], 7)

        # Affichage titre menu
        pyxel.text(100, 60, "MENU", pyxel.frame_count % 16)

        # Affichage options
        for i, option in enumerate(menu_options):
            color = 11 if i == menu_selection else 7
            x_pos = 80 + i * 100
            pyxel.text(x_pos, 120, option, color)

            # Petit curseur flèche sous option sélectionnée
            if i == menu_selection:
                pyxel.text(x_pos + 2, 132, "▼", color)

        return

    pyxel.cls(0)

    # Fond étoilé
    for star in stars:
        pyxel.pset(star[0], star[1], 7)

    if game_over:
        pyxel.text(45+64, 100, "GAME OVER", 8)
        pyxel.text(26+64, 120, "Appuyer Q pour revenir au menu", 7)
        pyxel.text(42+64, 140, "Scores :", 7)
        pyxel.text(80+64, 140, str(sc), 7)
        return

    # Dessin du joueur
    if timers <= -4:
        pyxel.blt(x_fusee, y_fusee, 0, 48, 16, 16, 16, 1)
    elif timers >= 4:
        pyxel.blt(x_fusee, y_fusee, 0, 64, 16, 16, 16, 1)
    elif -4 < timers < 0 or 0 < timers < 4:
        pyxel.blt(x_fusee, y_fusee, 0, 32, 16, 16, 16, 1)
    else:
        pyxel.blt(x_fusee, y_fusee, 0, 16, 16, 16, 16, 1)

    if abs(tf) >= 4:
        pyxel.blt(x_feu, y_feu, 0, 40, 64, 8, 8, 1)
    elif 0 < abs(tf) < 4:
        pyxel.blt(x_feu, y_feu, 0, 32, 64, 8, 8, 1)
    else:
        pyxel.blt(x_feu, y_feu, 0, 48, 64, 8, 8, 1)

    for b in bullet:
        pyxel.blt(b[0], b[1], 0, 0, 80, 16, 16, 1)

    for m in monstres:
        pyxel.blt(m[0], m[1], 0, m[2], 48, 16, 16, 1)

    # Interface
    pyxel.blt(0, 225, 1, 0, 0, 16, 16, 0)
    pyxel.blt(0, 241, 1, 0, 16, 16, 16, 0)
    pyxel.blt(240, 225, 1, 32, 0, 16, 16, 0)
    pyxel.blt(240, 241, 1, 32, 16, 16, 16, 0)
    for i in range(16, 240, 16):
        pyxel.blt(i, 225, 1, 16, 0, 16, 16, 0)
    for i in range(16, 240, 16):
        pyxel.blt(i, 241, 1, 16, 16, 16, 16, 0)

    if vies == 3:
        pyxel.blt(96+32, 238, 0, 0, 96, 16, 16, 1)
    elif vies == 2:
        pyxel.blt(96+32, 238, 0, 16, 96, 16, 16, 1)
    elif vies == 1:
        pyxel.blt(96+32, 238, 0, 32, 96, 16, 16, 1)
    else:
        pyxel.blt(96+32, 238, 0, 48, 96, 16, 16, 1)

    pyxel.text(14+64, 238, "Munitions:", 0)
    pyxel.text(55+64, 238, str(muni), 0)
    pyxel.text(14+64, 246, "Scores:", 0)
    pyxel.text(55+64, 246, str(sc), 0)

def reset_game():
    global x_fusee, y_fusee, timers, tf, x_feu, y_feu
    global sc, muni, vies, game_over
    global bullet, monstres, spawn_timer, spawn_delay

    x_fusee = 125
    y_fusee = 93
    timers = 0
    tf = 0
    x_feu = x_fusee + 4
    y_feu = y_fusee + 16
    sc = 0
    muni = 10
    vies = 3
    game_over = False

    bullet = []
    monstres = []
    spawn_timer = 0
    spawn_delay = pyxel.rndi(10, 60)

pyxel.run(update, draw)