# Pyxel Studio
# Pyxel Studio

#Selbst gemacht: alle Ideen, alle drawings / Texts (sowohl im code wie auch in pyxres), Startbild, Schlussstatistik, Power-Ups, Musik (grösstenteils)



import pyxel
import random
import math

WIDTH = 512
HEIGHT = 512

FIELD_TOP = 60
FIELD_BOTTOM = 452

GOAL_SIZE = 120
GAME_TIME = 60 * 60
POWER_DURATION = 7 * 60

BALL_BASE_SPEED = 1.2
BALL_FAST_SPEED = 2


# ══════════════════════════════════════════════════════════════════════════════
#  Klasse 1: GameLogic  –  Spielzustand, Physik, KI, Power-Ups, Sounds
# ══════════════════════════════════════════════════════════════════════════════
class GameLogic:
    """Enthält die gesamte Spiellogik: Reset, Update, KI, Power-Ups, Sounds."""

    def _setup_sounds(self):
        pass  # wird in SoccerGame überschrieben / aufgerufen

    def distance(self, x1, y1, x2, y2):
        return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)

    def spawn_powerup(self):
        types = ["speed", "powershot", "freeze", "shrink"]
        self.powerup = {
            "type": random.choice(types),
            "x": random.randint(50, WIDTH - 50),
            "y": random.randint(FIELD_TOP + 10, FIELD_BOTTOM - 10)
        }

    def activate_power(self, player):
        if player == 1 and self.p1_power:
            if self.active_power1 == "freeze":
                self.p2_speed = 3.5
            self.active_power1 = self.p1_power
            self.power_timer1 = POWER_DURATION
            self.power_used1[self.p1_power] += 1
            if self.active_power1 == "speed":
                self.p1_speed = 5
            elif self.active_power1 == "freeze":
                self.p2_speed = 0
                self.power_timer1 = 3 * 60
            elif self.active_power1 == "powershot":
                self.ballvx = BALL_FAST_SPEED * 2
            elif self.active_power1 == "shrink":
                self.p1_goal_size = GOAL_SIZE // 2
                self.shrink_timer1 = POWER_DURATION
                self.shrinks1 += 1
            self.p1_power = None
        elif player == 2 and self.p2_power:
            if self.active_power2 == "freeze":
                self.p1_speed = 3.5
            self.active_power2 = self.p2_power
            self.power_timer2 = POWER_DURATION
            self.power_used2[self.p2_power] += 1
            if self.active_power2 == "speed":
                self.p2_speed = 5
            elif self.active_power2 == "freeze":
                self.p1_speed = 0
                self.power_timer2 = 3 * 60
            elif self.active_power2 == "powershot":
                self.ballvx = -BALL_FAST_SPEED * 2
            elif self.active_power2 == "shrink":
                self.p2_goal_size = GOAL_SIZE // 2
                self.shrink_timer2 = POWER_DURATION
                self.shrinks2 += 1
            self.p2_power = None


# ══════════════════════════════════════════════════════════════════════════════
#  Klasse 2: Renderer  –  alle Zeichenmethoden
# ══════════════════════════════════════════════════════════════════════════════
class Renderer:
    """Enthält alle draw-Methoden: Spielfeld, Spieler, Menüs, Effekte."""
    pass


# ══════════════════════════════════════════════════════════════════════════════
#  Klasse 3: SoccerGame  –  Hauptklasse, erbt von GameLogic + Renderer
# ══════════════════════════════════════════════════════════════════════════════
class SoccerGame(GameLogic, Renderer):

    def __init__(self):

        pyxel.init(WIDTH, HEIGHT, title="Mini Soccer Duel")
        pyxel.load("res_title_256.pyxres")

        self._setup_sounds()

        self.state = "title"   # "title" | "menu" | "daytime" | "playing" | "game_over"
        self.title_blink = 0
        self.game_mode = "pvp"      # "pvp" | "pvc_easy" | "pvc_hard"
        self.menu_cursor = 0        # 0=1v1, 1=KI easy, 2=KI hard
        self.ai_difficulty = "easy" # "easy" | "hard"
        self.time_of_day = "day"    # "day" | "night"
        self.daytime_cursor = 0     # 0=Tag, 1=Nacht

        self.reset()

        pyxel.run(self.update, self.draw)


    def _setup_sounds(self):
        """Definiert alle Sounds direkt im Code."""

        # --- Sound 0: Ball-Kick (kurzer, harter Aufprall) ---
        s = pyxel.sound(0)
        s.set(
            notes="C3C3C3",
            tones="NNN",
            volumes="764",
            effects="FFF",
            speed=6
        )

        # --- Sound 1: Tor-Jubel – langer aufsteigender Fanfare-Sweep ---
        s = pyxel.sound(1)
        s.set(
            notes="C3D3E3F3G3A3B3C4D4E4F4G4A4B4C4",
            tones="SSSSSSSSSSSSSSS",
            volumes="345566777777654",
            effects="NNNNNNNNNNNNNNN",
            speed=5
        )

        # --- Sound 2: Tor-Jubel – langes Stadion-Crowd-Rauschen ---
        s = pyxel.sound(2)
        s.set(
            notes="C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3",
            tones="NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
            volumes="23456677777777776666665554443322",
            effects="NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
            speed=5
        )

        # --- Sound 3: Tor-Jubel – triumphaler Schluss-Akkord ---
        s = pyxel.sound(3)
        s.set(
            notes="E4G4C4E4G4C4E4C4",
            tones="SSSSSSSS",
            volumes="77777654",
            effects="NNNNNNFF",
            speed=8
        )

        # --- Hintergrundmusik: Sound 4 – Epische Triumph-Melodie ---
        s = pyxel.sound(4)
        s.set(
            notes="G3G3G3E3F3F3F3D3E3E3E3C3D3D3G3G3A3A3B3A3G3B3A3A3G3G3G3G3G3G3",
            tones="SSSSSSSSSSSSSSSSSSSSSSSSSSSSSS",
            volumes="456677776677776655667777667766",
            effects="NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN",
            speed=36
        )

        # --- Hintergrundmusik: Sound 5 – Tiefer Power-Bass ---
        s = pyxel.sound(5)
        s.set(
            notes="C3C3C3C3F2F2F2F2C3C3C3C3G2G2G2G2",
            tones="TTTTTTTTTTTTTTTT",
            volumes="6666666666666666",
            effects="NNNNNNNNNNNNNNNN",
            speed=25
        )

     


    def reset(self):

        self.p1x = 80
        self.p1y = HEIGHT // 2

        self.p2x = WIDTH - 80
        self.p2y = HEIGHT // 2

        self.p1_speed = 3.5
        self.p2_speed = 3.5

        self.ballx = WIDTH // 2
        self.bally = HEIGHT // 2

        self.ballvx = random.choice([-1, 1])
        self.ballvy = random.uniform(-0.5, 0.5)
        
        self.ball_speed_timer = 0

        self.score1 = 0
        self.score2 = 0

        self.timer = GAME_TIME
        self.game_over = False

        self.powerup = None

        self.p1_power = None
        self.p2_power = None
        self.ai_power_delay = 0   # Frames bis KI Power-Up einsetzt

        self.active_power1 = None
        self.active_power2 = None

        self.power_timer1 = 0
        self.power_timer2 = 0

        self.last_w = 0
        self.last_up = 0
        
        self.overtime = False
        self.show_overtime = 0

        self.celebration_timer = 0

        self._init_audience()

        self.confetti = []
        self.pyro = []
        self.smoke_overlay_timer = 0
        self.smoke_particles = []

        # --- Pitch Invader (Flitzer) ---
        self.invader_timer = 25 * 60   # alle 25 Sekunden
        self.invader = None            # None oder dict mit Status

        # --- Kamera-Shake ---
        self.shake_timer = 0
        self.shake_x = 0
        self.shake_y = 0

        # --- GOAL-Text Animation ---
        self.goal_anim_timer = 0
        self.goal_anim_scale = 0.0
        self.goal_scorer = 0

        # --- Shrink-Goal Power-Up ---
        self.p1_goal_size = GOAL_SIZE
        self.p2_goal_size = GOAL_SIZE
        self.shrink_timer1 = 0
        self.shrink_timer2 = 0

        # --- Statistiken ---
        self.shots1 = 0
        self.shots2 = 0
        self.powerups1 = 0
        self.powerups2 = 0
        self.shrinks1 = 0
        self.shrinks2 = 0

        # Detaillierte Power-Up-Nutzung pro Typ
        self.power_used1 = {"speed": 0, "powershot": 0, "freeze": 0, "shrink": 0}
        self.power_used2 = {"speed": 0, "powershot": 0, "freeze": 0, "shrink": 0}

        # --- NEU: Pfiff-nach-Tor-Timer ---
        # Nach dem Jubel ertönt der Anpfiff. Timer zählt runter nach celebration.
        self.whistle_pending = False

        # --- Ballspur ---
        # Liste von Dicts: {"x", "y", "speed"} – speed = ball-Geschwindigkeit zum Zeitpunkt
        self.ball_trail = []

        # Blickrichtung: 1 = rechts, -1 = links
        self.p1_facing = 1   # P1 schaut standardmässig nach rechts
        self.p2_facing = -1  # P2 schaut standardmässig nach links

        self._start_background_music()


    def _init_audience(self):
        """Erstellt Zuschauer mit Teamfarben: linke Hälfte Blau (P1), rechte Hälfte Rot (P2)."""
        self.audience = []
        # Teamfarben: Blau = 12 (Pyxel-Blau), Rot = 8 (Pyxel-Rot)
        skin_colors  = [15, 4, 14, 9]
        hat_colors   = [1, 2, 6, 8, 10, 12, 13]
        for row in range(9):
            y = 2 + row * 4
            for i in range(0, WIDTH, 7):
                offset = 0 if row % 2 == 0 else 3
                x = i + offset
                # Linke Hälfte = P1 Blau, rechte Hälfte = P2 Rot
                # Kleine Variation damit es lebendig aussieht
                if x < WIDTH // 2:
                    # P1-Seite: Blautöne (12 = hellblau, 1 = dunkelblau)
                    shirt_options = [12, 12, 12, 1, 7]
                    shirt = shirt_options[(x * 3 + row * 7) % len(shirt_options)]
                else:
                    # P2-Seite: Rottöne (8 = rot, 2 = dunkelrot/pink)
                    shirt_options = [8, 8, 8, 2, 7]
                    shirt = shirt_options[(x * 3 + row * 7) % len(shirt_options)]

                person = {
                    "x": x,
                    "y": y,
                    "skin":  skin_colors[ (x * 3 + row * 7) % len(skin_colors) ],
                    "shirt": shirt,
                    "has_hat": (x // 7 + row) % 3 == 0,
                    "hat_col": hat_colors[(x * 2 + row) % len(hat_colors)],
                    "scarf":   (x // 7 + row * 2) % 4 == 0,
                    "team":    1 if x < WIDTH // 2 else 2,
                    "side":    "top",
                }
                self.audience.append(person)

        # --- Untere Tribüne (gespiegelt für Stadion-Effekt) ---
        bottom_base = HEIGHT - 2  # unterster Pixel der unteren Tribüne
        for row in range(8):
            y = bottom_base - row * 6
            for i in range(0, WIDTH, 7):
                offset = 0 if row % 2 == 0 else 3
                x = i + offset
                if x < WIDTH // 2:
                    shirt_options = [12, 12, 12, 1, 7]
                    shirt = shirt_options[(x * 3 + row * 7) % len(shirt_options)]
                else:
                    shirt_options = [8, 8, 8, 2, 7]
                    shirt = shirt_options[(x * 3 + row * 7) % len(shirt_options)]

                person = {
                    "x": x,
                    "y": y,
                    "skin":  skin_colors[ (x * 3 + row * 7) % len(skin_colors) ],
                    "shirt": shirt,
                    "has_hat": (x // 7 + row) % 3 == 0,
                    "hat_col": hat_colors[(x * 2 + row) % len(hat_colors)],
                    "scarf":   (x // 7 + row * 2) % 4 == 0,
                    "team":    1 if x < WIDTH // 2 else 2,
                    "side":    "bottom",
                }
                self.audience.append(person)


    def _play_whistle(self):
        """Spielt den Schiedsrichter-Pfiff auf Channel 3."""
        pyxel.play(3, 6, loop=False)


    def _play_goal_celebration(self):
        """Stoppt Hintergrundmusik und spielt langen Tor-Jubel."""
        pyxel.stop(0)
        pyxel.stop(1)
        pyxel.stop(2)
        pyxel.play(0, [1, 3], loop=False)
        pyxel.play(1, [2],    loop=False)
        self.celebration_timer = 180

        # Kamera-Shake starten
        self.shake_timer = 25

        # GOAL-Text Animation starten
        self.goal_anim_timer = 90
        self.goal_anim_scale = 0.0

        # Pfiff nach dem Jubel vormerken
        self.whistle_pending = True

        for _ in range(40):
            self.confetti.append({
                "x":  random.uniform(0, WIDTH),
                "y":  random.uniform(0, FIELD_TOP),
                "vx": random.uniform(-1.5, 1.5),
                "vy": random.uniform(0.5, 2.5),
                "col": random.choice([7, 8, 9, 10, 11, 12, 13, 14]),
                "life": random.randint(60, 150),
            })

        # --- PYRO: Fackel bei den Fans des Torschützen, Rauch zieht über das Feld ---
        self.pyro = []
        self.smoke_overlay_timer = 230   # ~3.8s starke Sichteinschraenkung

        if self.goal_scorer == 1:
            # P1 = Blau, Fans auf der linken Hälfte der Tribüne
            flare_x = random.uniform(20, WIDTH * 0.45)
            pyro_col_main = 12   # blau
            pyro_col_core = 6    # helles blaugrau
            smoke_col_outer = 12
            smoke_col_inner = 1
        else:
            # P2 = Rot, Fans auf der rechten Hälfte der Tribüne
            flare_x = random.uniform(WIDTH * 0.55, WIDTH - 20)
            pyro_col_main = 8    # rot
            pyro_col_core = 10   # gelb-orange Glut
            smoke_col_outer = 8
            smoke_col_inner = 2

        flare_top = random.random() < 0.5
        flare_y = random.uniform(4, FIELD_TOP - 6) if flare_top else random.uniform(FIELD_BOTTOM + 6, HEIGHT - 4)
        self.pyro.append({
            "x": flare_x, "y": flare_y, "timer": 0, "top": flare_top,
            "col_main": pyro_col_main, "col_core": pyro_col_core,
        })

        # Funken, die von der Fackel sprühen (Teamfarbe)
        for _ in range(30):
            angle = random.uniform(0, math.pi * 2)
            speed = random.uniform(0.3, 1.5)
            self.confetti.append({
                "x":  flare_x,
                "y":  flare_y,
                "vx": math.cos(angle) * speed,
                "vy": math.sin(angle) * speed - 0.5,
                "col": pyro_col_main,
                "life": random.randint(40, 90),
            })

        # Dichter Rauch, der von der Fackel komplett über das Spielfeld zieht
        target_y = HEIGHT // 2  # Rauch driftet bis zur Feldmitte
        for _ in range(70):
            start_x = flare_x + random.uniform(-15, 15)
            start_y = flare_y + random.uniform(-10, 10)
            # Driftrichtung: vom Tribünenrand Richtung Feldmitte
            dx = (WIDTH / 2 - start_x) / 60.0
            dy = (target_y - start_y) / 60.0
            self.smoke_particles.append({
                "x": start_x,
                "y": start_y,
                "r": random.randint(18, 34),
                "vx": dx + random.uniform(-0.4, 0.4),
                "vy": dy + random.uniform(-0.4, 0.4),
                "life": random.randint(90, 130),
                "col_outer": smoke_col_outer,
                "col_inner": smoke_col_inner,
            })


    def _start_background_music(self):
        """Startet die Hintergrundmusik (loop)."""
        pyxel.play(0, 4, loop=True)
        pyxel.play(1, 5, loop=True)
        pyxel.play(2, 6, loop=True)

    def _play_kick(self):
        """Spielt den Ball-Kick-Sound auf Channel 3 (unabhängig)."""
        pyxel.play(3, 0, loop=False)


    # ------------------------------------------------------------------ #
    #  UPDATE                                                              #
    # ------------------------------------------------------------------ #
    def update(self):

        # --- TITELSCREEN ---
        if self.state == "title":
            self.title_blink = (self.title_blink + 1) % 60
            if pyxel.btnp(pyxel.KEY_SPACE):
                self.state = "menu"
                self.menu_cursor = 0
            return

        # --- MODUS-MENUE ---
        if self.state == "menu":
            self.title_blink = (self.title_blink + 1) % 60
            if pyxel.btnp(pyxel.KEY_UP) or pyxel.btnp(pyxel.KEY_W):
                self.menu_cursor = (self.menu_cursor - 1) % 3
            if pyxel.btnp(pyxel.KEY_DOWN) or pyxel.btnp(pyxel.KEY_S):
                self.menu_cursor = (self.menu_cursor + 1) % 3
            if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.KEY_RETURN):
                if self.menu_cursor == 0:
                    self.game_mode = "pvp"
                    self.ai_difficulty = "easy"
                elif self.menu_cursor == 1:
                    self.game_mode = "pvc_easy"
                    self.ai_difficulty = "easy"
                else:
                    self.game_mode = "pvc_hard"
                    self.ai_difficulty = "hard"
                self.state = "daytime"
                self.daytime_cursor = 0
            if pyxel.btnp(pyxel.KEY_R) or pyxel.btnp(pyxel.KEY_ESCAPE):
                self.state = "title"
                self.title_blink = 0
            return

        # --- TAGESZEIT-MENUE ---
        if self.state == "daytime":
            self.title_blink = (self.title_blink + 1) % 60
            if pyxel.btnp(pyxel.KEY_LEFT) or pyxel.btnp(pyxel.KEY_A) or \
               pyxel.btnp(pyxel.KEY_RIGHT) or pyxel.btnp(pyxel.KEY_D) or \
               pyxel.btnp(pyxel.KEY_UP) or pyxel.btnp(pyxel.KEY_W) or \
               pyxel.btnp(pyxel.KEY_DOWN) or pyxel.btnp(pyxel.KEY_S):
                self.daytime_cursor = 1 - self.daytime_cursor
            if pyxel.btnp(pyxel.KEY_SPACE) or pyxel.btnp(pyxel.KEY_RETURN):
                self.time_of_day = "day" if self.daytime_cursor == 0 else "night"
                self.state = "playing"
                self.reset()
                self._play_whistle()
            if pyxel.btnp(pyxel.KEY_R) or pyxel.btnp(pyxel.KEY_ESCAPE):
                self.state = "menu"
            return

        # --- NEUSTART (aus beliebigem Zustand) ---
        if pyxel.btnp(pyxel.KEY_R):
            self.state = "title"
            self.title_blink = 0
            return

        if self.game_over:
            return

        if not self.overtime:
            self.timer -= 1

        if self.timer <= 0:

            if self.score1 == self.score2 and not self.overtime:
                self.overtime = True
                self.show_overtime = 60
    
            elif not self.overtime:
                self.game_over = True
                # NEU: Abpfiff am Spielende
                pyxel.stop(0)
                pyxel.stop(1)
                pyxel.stop(2)
                self._play_whistle()
            
        if self.show_overtime > 0:
            self.show_overtime -= 1

        if self.celebration_timer > 0:
            self.celebration_timer -= 1
            if self.celebration_timer == 0:
                self._start_background_music()
                # NEU: Anpfiff nach Tor (wenn Jubel vorbei)
                if self.whistle_pending:
                    self.whistle_pending = False
                    self._play_whistle()

        # --- Kamera-Shake Update ---
        if self.shake_timer > 0:
            self.shake_timer -= 1
            intensity = self.shake_timer // 5 + 1
            self.shake_x = random.randint(-intensity, intensity)
            self.shake_y = random.randint(-intensity, intensity)
        else:
            self.shake_x = 0
            self.shake_y = 0

        # --- GOAL-Text Animation Update ---
        if self.goal_anim_timer > 0:
            self.goal_anim_timer -= 1
            progress = 1.0 - self.goal_anim_timer / 90.0
            if progress < 0.4:
                self.goal_anim_scale = progress / 0.4
            elif progress < 0.75:
                self.goal_anim_scale = 1.0
            else:
                self.goal_anim_scale = 1.0 - (progress - 0.75) / 0.25

        # --- Shrink-Timers ---
        if self.shrink_timer1 > 0:
            self.shrink_timer1 -= 1
            if self.shrink_timer1 == 0:
                self.p1_goal_size = GOAL_SIZE
        if self.shrink_timer2 > 0:
            self.shrink_timer2 -= 1
            if self.shrink_timer2 == 0:
                self.p2_goal_size = GOAL_SIZE

        for p in self.confetti:
            p["x"]   += p["vx"]
            p["y"]   += p["vy"]
            p["vy"]  += 0.08
            p["life"] -= 1
        self.confetti = [p for p in self.confetti if p["life"] > 0 and p["y"] < HEIGHT]

        for p in self.pyro:
            p["timer"] += 1
        self.pyro = [p for p in self.pyro if p["timer"] < 60]

        for p in self.smoke_particles:
            p["x"] += p["vx"]
            p["y"] += p["vy"]
            p["life"] -= 1
            if p["r"] < 40:
                p["r"] += 0.3
        self.smoke_particles = [p for p in self.smoke_particles if p["life"] > 0]

        if self.smoke_overlay_timer > 0:
            self.smoke_overlay_timer -= 1

        if pyxel.btn(pyxel.KEY_W):
            self.p1y -= self.p1_speed
        if pyxel.btn(pyxel.KEY_S):
            self.p1y += self.p1_speed
        if pyxel.btn(pyxel.KEY_A):
            self.p1x -= self.p1_speed
            self.p1_facing = -1
        if pyxel.btn(pyxel.KEY_D):
            self.p1x += self.p1_speed
            self.p1_facing = 1

        if self.game_mode == "pvp":
            if pyxel.btn(pyxel.KEY_UP):
                self.p2y -= self.p2_speed
            if pyxel.btn(pyxel.KEY_DOWN):
                self.p2y += self.p2_speed
            if pyxel.btn(pyxel.KEY_LEFT):
                self.p2x -= self.p2_speed
                self.p2_facing = -1
            if pyxel.btn(pyxel.KEY_RIGHT):
                self.p2x += self.p2_speed
                self.p2_facing = 1
        elif self.game_mode in ("pvc_easy", "pvc_hard"):
            self._update_ai()

        self.p1x = max(1, min(WIDTH - 9, self.p1x))
        self.p1y = max(FIELD_TOP + 1, min(FIELD_BOTTOM - 16, self.p1y))

        self.p2x = max(1, min(WIDTH - 9, self.p2x))
        self.p2y = max(FIELD_TOP + 1, min(FIELD_BOTTOM - 16, self.p2y))

        # Spieler darf nicht durch die Tor-Seitenwände gehen
        goal_top1 = HEIGHT//2 - self.p1_goal_size//2
        goal_bot1 = HEIGHT//2 + self.p1_goal_size//2
        goal_top2 = HEIGHT//2 - self.p2_goal_size//2
        goal_bot2 = HEIGHT//2 + self.p2_goal_size//2

        # P1: darf linke Wand nur im Tor betreten
        if self.p1x < 14 and not (goal_top1 < self.p1y + 8 < goal_bot1):
            self.p1x = 14

        # P2: darf rechte Wand nur im Tor betreten
        if self.p2x > WIDTH - 14 and not (goal_top2 < self.p2y + 8 < goal_bot2):
            self.p2x = WIDTH - 14

        if pyxel.btnp(pyxel.KEY_W):
            if pyxel.frame_count - self.last_w < 15:
                self.activate_power(1)
            self.last_w = pyxel.frame_count

        if self.game_mode == "pvp":
            if pyxel.btnp(pyxel.KEY_UP):
                if pyxel.frame_count - self.last_up < 15:
                    self.activate_power(2)
                self.last_up = pyxel.frame_count

        if self.power_timer1 > 0:
            self.power_timer1 -= 1
        elif self.active_power1:
            if self.active_power1 == "speed":
                self.p1_speed = 3.5
            elif self.active_power1 == "freeze":
                self.p2_speed = 3.5
            self.active_power1 = None
        
        if self.power_timer2 > 0:
            self.power_timer2 -= 1
        elif self.active_power2:
            if self.active_power2 == "speed":
                self.p2_speed = 3.5
            elif self.active_power2 == "freeze":
                self.p1_speed = 3.5
            self.active_power2 = None

        self.ballx += self.ballvx
        self.bally += self.ballvy

        # --- Ballspur aktualisieren ---
        ball_speed = math.sqrt(self.ballvx**2 + self.ballvy**2)
        self.ball_trail.append({"x": self.ballx, "y": self.bally, "speed": ball_speed})
        if len(self.ball_trail) > 18:
            self.ball_trail.pop(0)

        if self.bally <= FIELD_TOP:
            self.bally = FIELD_TOP
            self.ballvy *= -1

        if self.bally >= FIELD_BOTTOM:
            self.bally = FIELD_BOTTOM
            self.ballvy *= -1
            
        if self.ball_speed_timer > 0:
            self.ball_speed_timer -= 1
        else:
            if self.ballvx > 0:
                self.ballvx = BALL_BASE_SPEED
            else:
                self.ballvx = -BALL_BASE_SPEED

        # Ball-Kollision: AABB-Check gegen die gesamte Spielerfigur (16x28px)
        PLAYER_W, PLAYER_H, BALL_R = 16, 28, 8
        def player_hits_ball(px, py, bx, by):
            return (px - BALL_R < bx < px + PLAYER_W + BALL_R and
                    py - BALL_R < by < py + PLAYER_H + BALL_R)

        if player_hits_ball(self.p1x, self.p1y, self.ballx, self.bally):
            self.ballvx = BALL_FAST_SPEED
            self.ballvy = (self.bally - (self.p1y + PLAYER_H//2)) * 0.3
            self.ball_speed_timer = 180
            self._play_kick()
            self.shots1 += 1

        if player_hits_ball(self.p2x, self.p2y, self.ballx, self.bally):
            self.ballvx = -BALL_FAST_SPEED
            self.ballvy = (self.bally - (self.p2y + PLAYER_H//2)) * 0.3
            self.ball_speed_timer = 180
            self._play_kick()
            self.shots2 += 1

        # Tor-Erkennung mit dynamischer Torgröße
        goal_top1 = HEIGHT//2 - self.p1_goal_size//2
        goal_bottom1 = HEIGHT//2 + self.p1_goal_size//2
        goal_top2 = HEIGHT//2 - self.p2_goal_size//2
        goal_bottom2 = HEIGHT//2 + self.p2_goal_size//2

        if self.ballx <= 0:
            if goal_top1 < self.bally < goal_bottom1:
                self.score2 += 1
                self.goal_scorer = 2
                self._play_goal_celebration()
                if self.overtime:
                    self.game_over = True
                self.ballx = WIDTH//2
                self.bally = HEIGHT//2
                self.p1x = 80
                self.p1y = HEIGHT//2
                self.p2x = WIDTH-50
                self.p2y = HEIGHT//2
                self.ballvx = random.choice([-1,1])
                self.ballvy = random.uniform(-0.5,0.5)
                self.p1_speed = 3.5
                self.p2_speed = 3.5
                self.active_power1 = None
                self.active_power2 = None
                self.power_timer1 = 0
                self.power_timer2 = 0
            else:
                self.ballvx *= -1

        if self.ballx >= WIDTH:
            if goal_top2 < self.bally < goal_bottom2:
                self.score1 += 1
                self.goal_scorer = 1
                self._play_goal_celebration()
                if self.overtime:
                    self.game_over = True
                self.ballx = WIDTH//2
                self.bally = HEIGHT//2
                self.p1x = 80
                self.p1y = HEIGHT//2
                self.p2x = WIDTH-50
                self.p2y = HEIGHT//2
                self.ballvx = random.choice([-1,1])
                self.ballvy = random.uniform(-0.5,0.5)
                self.p1_speed = 3.5
                self.p2_speed = 3.5
                self.active_power1 = None
                self.active_power2 = None
                self.power_timer1 = 0
                self.power_timer2 = 0
            else:
                self.ballvx *= -1

        if self.powerup is None and random.random() < 0.008:
            self.spawn_powerup()

        # --- Flitzer (Pitch Invader) ---
        if self.invader is None:
            self.invader_timer -= 1
            if self.invader_timer <= 0:
                self.invader_timer = 25 * 60
                # Startet von unten oder oben zufällig
                side = random.choice(["top", "bottom"])
                start_x = random.randint(80, WIDTH - 80)
                if side == "top":
                    start_y = FIELD_TOP - 5
                    target_y = self.bally
                else:
                    start_y = FIELD_BOTTOM + 5
                    target_y = self.bally
                self.invader = {
                    "x": float(start_x),
                    "y": float(start_y),
                    "side": side,
                    "phase": "running_in",   # running_in -> touched -> running_out
                    "skin": random.choice([15, 4, 14, 9]),
                    "shirt": random.choice([6, 9, 10, 14, 11]),
                    "speed": 2.5,
                }
        else:
            inv = self.invader
            if inv["phase"] == "running_in":
                # Laufe zum Ball
                dx = self.ballx - inv["x"]
                dy = self.bally - inv["y"]
                dist = math.sqrt(dx*dx + dy*dy) or 1
                inv["x"] += inv["speed"] * dx / dist
                inv["y"] += inv["speed"] * dy / dist
                # Ball berührt?
                if dist < 10:
                    inv["phase"] = "touched"
                    # Ball-Richtung: komplett zufälliger Winkel (voller Kreis)
                    angle = random.uniform(0, math.pi * 2)
                    speed = BALL_FAST_SPEED * 1.5
                    self.ballvx = math.cos(angle) * speed
                    self.ballvy = math.sin(angle) * speed
                    self.ball_speed_timer = 180
                    self._play_kick()
            elif inv["phase"] == "touched":
                # Sofort zur Gegenüberliegenden Seite laufen
                if inv["side"] == "top":
                    target_y = FIELD_BOTTOM + 20
                else:
                    target_y = FIELD_TOP - 20
                dx = 0
                dy = target_y - inv["y"]
                dist = abs(dy) or 1
                inv["x"] += inv["speed"] * dx / dist if dist > 0 else 0
                inv["y"] += inv["speed"] * (dy / dist)
                inv["phase"] = "running_out"
            elif inv["phase"] == "running_out":
                if inv["side"] == "top":
                    target_y = FIELD_BOTTOM + 20
                else:
                    target_y = FIELD_TOP - 20
                dy = target_y - inv["y"]
                dist = abs(dy) or 1
                inv["y"] += inv["speed"] * (dy / dist)
                # Verschwunden?
                if inv["side"] == "top" and inv["y"] > FIELD_BOTTOM + 15:
                    self.invader = None
                elif inv["side"] == "bottom" and inv["y"] < FIELD_TOP - 15:
                    self.invader = None

        if self.powerup:
            PU_R = 8
            def player_hits_powerup(px, py):
                return (px - PU_R < self.powerup["x"] < px + PLAYER_W + PU_R and
                        py - PU_R < self.powerup["y"] < py + PLAYER_H + PU_R)
            if player_hits_powerup(self.p1x, self.p1y):
                self.p1_power = self.powerup["type"]
                self.powerup = None
                self.powerups1 += 1
            elif player_hits_powerup(self.p2x, self.p2y):
                self.p2_power = self.powerup["type"]
                self.powerup = None
                self.powerups2 += 1
                self.ai_power_delay = 0  # Neue Verzoegerung wird in _update_ai gewuerfelt


    def _draw_player1(self, x, y, facing=1):
        """P1 (blau-gelb) – Seitenansicht. facing=1 rechts, facing=-1 links."""
        f = (pyxel.frame_count // 8) % 2

        # Spiegelung: bei facing=-1 alles horizontal spiegeln (innerhalb 16px)
        def px(ox): return x + ox if facing == 1 else x + (15 - ox)

        # Haare
        if facing == 1:
            pyxel.rect(px(6), y+0, 6, 3, 2)
        else:
            pyxel.rect(px(9), y+0, 6, 3, 2)   # gespiegelt = x+4..9
        # Kopf
        pyxel.rect(px(4) if facing==1 else px(11), y+2, 8, 7, 14)
        # Nase
        pyxel.pset(px(12), y+5, 14)
        # Auge
        pyxel.pset(px(10), y+4, 0)
        # Mund
        pyxel.pset(px(11), y+7, 0)
        # Ohr
        pyxel.pset(px(4), y+5, 14)
        # Hals
        pyxel.rect(px(6) if facing==1 else px(9), y+9, 4, 2, 14)
        # Körper blau
        pyxel.rect(px(4) if facing==1 else px(11), y+11, 8, 8, 12)
        # Gelbe Flecken
        pyxel.rect(px(5) if facing==1 else px(10), y+12, 2, 2, 10)
        pyxel.rect(px(8) if facing==1 else px(7),  y+14, 2, 2, 10)
        # Arm vorne
        ax_f = px(10) if facing==1 else px(5)
        ax_b = px(4)  if facing==1 else px(11)
        if f == 0:
            pyxel.rect(ax_f, y+12, 2, 5, 14)
            pyxel.pset(px(11) if facing==1 else px(4), y+17, 14)
        else:
            pyxel.rect(ax_f, y+13, 2, 5, 14)
            pyxel.pset(px(12) if facing==1 else px(3), y+17, 14)
        # Arm hinten
        if f == 0:
            pyxel.rect(ax_b, y+13, 2, 4, 9)
        else:
            pyxel.rect(ax_b, y+12, 2, 4, 9)
        # Shorts
        pyxel.rect(px(4) if facing==1 else px(11), y+19, 8, 3, 7)
        # Beine
        lf = px(8) if facing==1 else px(7)   # Vorderbein x
        lb = px(4) if facing==1 else px(11)  # Hinterbein x
        sf_x = px(9) if facing==1 else px(6)  # Schuh vorne
        sb_x = px(3) if facing==1 else px(12) # Schuh hinten
        if f == 0:
            pyxel.rect(lf, y+22, 3, 5, 12)
            pyxel.rect(sf_x, y+27, 4, 1, 1)
            pyxel.rect(lb, y+22, 3, 3, 9)
            pyxel.rect(sb_x, y+25, 3, 1, 1)
        else:
            pyxel.rect(lf, y+22, 3, 3, 12)
            pyxel.rect(sf_x, y+25, 3, 1, 1)
            pyxel.rect(lb, y+22, 3, 5, 9)
            pyxel.rect(sb_x, y+27, 4, 1, 1)

    def _draw_player2(self, x, y, facing=-1):
        """P2 (pink) – Seitenansicht. facing=-1 links (Standard), facing=1 rechts."""
        f = (pyxel.frame_count // 8) % 2

        # Basis-Design schaut nach links (facing=-1). Bei facing=1 spiegeln.
        def px(ox): return x + ox if facing == -1 else x + (15 - ox)

        # Haare (links-basis bei x+4..10)
        pyxel.rect(px(4) if facing==-1 else px(9), y+0, 6, 3, 2)
        # Kopf
        pyxel.rect(px(4) if facing==-1 else px(11), y+2, 8, 7, 14)
        # Nase (links-basis bei x+3)
        pyxel.pset(px(3), y+5, 14)
        # Auge
        pyxel.pset(px(5), y+4, 0)
        # Mund
        pyxel.pset(px(4), y+7, 0)
        # Ohr (rechts-basis bei x+12)
        pyxel.pset(px(12), y+5, 14)
        # Hals
        pyxel.rect(px(6) if facing==-1 else px(9), y+9, 4, 2, 14)
        # Körper pink
        pyxel.rect(px(4) if facing==-1 else px(11), y+11, 8, 8, 8)
        # Hellorange Flecken
        pyxel.rect(px(9) if facing==-1 else px(6),  y+12, 2, 2, 14)
        pyxel.rect(px(5) if facing==-1 else px(10), y+14, 2, 2, 14)
        # Arm vorne (links-basis bei x+4)
        ax_f = px(4)  if facing==-1 else px(11)
        ax_b = px(10) if facing==-1 else px(5)
        if f == 0:
            pyxel.rect(ax_f, y+12, 2, 5, 14)
            pyxel.pset(px(3) if facing==-1 else px(12), y+17, 14)
        else:
            pyxel.rect(ax_f, y+13, 2, 5, 14)
            pyxel.pset(px(2) if facing==-1 else px(13), y+17, 14)
        # Arm hinten
        if f == 0:
            pyxel.rect(ax_b, y+13, 2, 4, 2)
        else:
            pyxel.rect(ax_b, y+12, 2, 4, 2)
        # Shorts
        pyxel.rect(px(4) if facing==-1 else px(11), y+19, 8, 3, 7)
        # Beine
        lf = px(5) if facing==-1 else px(10)   # Vorderbein (links-basis)
        lb = px(9) if facing==-1 else px(6)    # Hinterbein
        sf_x = px(3) if facing==-1 else px(12) # Schuh vorne
        sb_x = px(10) if facing==-1 else px(5) # Schuh hinten
        if f == 0:
            pyxel.rect(lf, y+22, 3, 5, 8)
            pyxel.rect(sf_x, y+27, 4, 1, 1)
            pyxel.rect(lb, y+22, 3, 3, 2)
            pyxel.rect(sb_x, y+25, 3, 1, 1)
        else:
            pyxel.rect(lf, y+22, 3, 3, 8)
            pyxel.rect(sf_x, y+25, 3, 1, 1)
            pyxel.rect(lb, y+22, 3, 5, 2)
            pyxel.rect(sb_x, y+27, 4, 1, 1)

    def _draw_audience(self):
        """Zeichnet den Publikumsbereich mit Teamfarben und Jubel-Animation bei Tor."""
        celebrating = self.celebration_timer > 0

        # --- Obere Tribüne: voller Hintergrund von 0 bis FIELD_TOP ---
        pyxel.rect(0, 0,  WIDTH, FIELD_TOP, 1)   # dunkelblau als Basis
        pyxel.rect(0, 10, WIDTH, 10, 5)           # zweite Reihe etwas heller
        pyxel.line(0,  7, WIDTH,  7, 13)
        pyxel.line(0, 13, WIDTH, 13, 13)
        pyxel.line(0, 19, WIDTH, 19, 13)

        # --- Untere Tribüne: voller Hintergrund von FIELD_BOTTOM bis HEIGHT ---
        pyxel.rect(0, FIELD_BOTTOM, WIDTH, HEIGHT - FIELD_BOTTOM, 1)
        pyxel.rect(0, HEIGHT - 20, WIDTH, 10, 5)
        pyxel.line(0, HEIGHT - 8,  WIDTH, HEIGHT - 8,  13)
        pyxel.line(0, HEIGHT - 14, WIDTH, HEIGHT - 14, 13)
        pyxel.line(0, HEIGHT - 20, WIDTH, HEIGHT - 20, 13)

        wave_offset = (pyxel.frame_count // 4) % WIDTH if celebrating else -999

        for p in self.audience:
            x   = p["x"]
            y   = p["y"]
            sk  = p["skin"]
            side = p.get("side", "top")

            # NEU: Bei Jubel leuchten die Teamfarben noch stärker auf
            if celebrating and self.goal_scorer > 0:
                if p["team"] == self.goal_scorer:
                    sh = 12 if p["team"] == 1 else 8
                else:
                    sh = p["shirt"]
            else:
                sh = p["shirt"]

            jubel = celebrating and (abs(x - wave_offset) < 12 or
                                     abs(x - wave_offset + WIDTH) < 12)

            if side == "top":
                dy2 if jubel else 0
                pyxel.circ(x, y + dy, 2, sk)
                pyxel.pset(x - 1, y - 1 + dy, 0)
                pyxel.pset(x + 1, y - 1 + dy, 0)
                if p["has_hat"]:
                    pyxel.rect(x - 2, y - 3 + dy, 5, 2, p["hat_col"])
                    pyxel.rect(x - 1, y - 4 + dy, 3, 1, p["hat_col"])
                pyxel.rect(x - 1, y + 2 + dy, 3, 3, sh)
                if p["scarf"]:
                    scarf_col = 12 if p["team"] == 1 else 8
                    pyxel.line(x - 1, y + 3 + dy, x + 1, y + 3 + dy, scarf_col)
                if jubel:
                    pyxel.pset(x - 2, y + 1, sh)
                    pyxel.pset(x + 2, y + 1, sh)
                    pyxel.pset(x - 3, y,     sh)
                    pyxel.pset(x + 3, y,     sh)
                else:
                    pyxel.pset(x - 2, y + 3, sh)
                    pyxel.pset(x + 2, y + 3, sh)
            else:
                # Untere Tribüne: Fans schauen zum Spielfeld (nach oben)
                # Körper oben (näher Feld), Hinterkopf unten (kein Gesicht sichtbar)
                dy = -2 if jubel else 0
                body_top = y - 5 + dy
                body_h = 4
                # Körper nicht ins Spielfeld ragen lassen (kein "Beine auf Feld"-Effekt)
                if body_top < FIELD_BOTTOM:
                    cut = FIELD_BOTTOM - body_top
                    body_top = FIELD_BOTTOM
                    body_h -= cut
                if body_h > 0:
                    pyxel.rect(x - 1, body_top, 3, body_h, sh)
                if p["scarf"] and (y - 4 + dy) >= FIELD_BOTTOM:
                    scarf_col = 12 if p["team"] == 1 else 8
                    pyxel.line(x - 1, y - 4 + dy, x + 1, y - 4 + dy, scarf_col)
                # Hinterkopf (unten = Feld-fern, kein Gesicht)
                pyxel.circ(x, y + 1 + dy, 2, sk)
                # Kein Gesicht! Nur Haaransatz oben am Kopf
                pyxel.rect(x - 1, y - 1 + dy, 3, 1, 2)
                if p["has_hat"]:
                    pyxel.rect(x - 2, y + 3 + dy, 5, 2, p["hat_col"])
                    pyxel.rect(x - 1, y + 5 + dy, 3, 1, p["hat_col"])
                if jubel:
                    pyxel.pset(x - 2, y - 6 + dy, sh)
                    pyxel.pset(x + 2, y - 6 + dy, sh)
                    pyxel.pset(x - 3, y - 7 + dy, sh)
                    pyxel.pset(x + 3, y - 7 + dy, sh)
                else:
                    pyxel.pset(x - 2, y - 6, sh)
                    pyxel.pset(x + 2, y - 6, sh)


    # ------------------------------------------------------------------ #
    #  KI (Spieler 2 - Computer)                                          #
    # ------------------------------------------------------------------ #
    def _update_ai(self):
        """KI fuer Spieler 2: easy (langsam, verzoegert) oder hard (schnell, sofort)."""
        hard = (self.ai_difficulty == "hard")

        # Power-Up: hard=sofort, easy=1-3 Sek Verzoegerung
        if self.p2_power:
            if hard:
                self.activate_power(2)
            else:
                if self.ai_power_delay == 0:
                    self.ai_power_delay = random.randint(60, 180)
                else:
                    self.ai_power_delay -= 1
                    if self.ai_power_delay <= 0:
                        self.ai_power_delay = 0
                        self.activate_power(2)

        AI_SPEED = self.p2_speed if hard else self.p2_speed * 0.72
        goal_center = HEIGHT // 2

        # --- Ziel bestimmen: Power-Up holen ---
        chase_powerup = False
        if self.powerup:
            pu = self.powerup
            dist_pu = math.sqrt((pu["x"] - self.p2x)**2 + (pu["y"] - self.p2y)**2)
            dist_ball = math.sqrt((self.ballx - self.p2x)**2 + (self.bally - self.p2y)**2)
            if hard:
                if dist_pu < dist_ball * 1.6 or pu["x"] > WIDTH * 0.4:
                    chase_powerup = True
            else:
                if dist_pu < dist_ball * 1.4 or pu["x"] > WIDTH * 0.45:
                    chase_powerup = True

        if chase_powerup:
            target_x = self.powerup["x"]
            target_y = self.powerup["y"]
        else:
            # Entscheidung: angreifen oder verteidigen?
            defending = (self.ballvx > 0 and self.ballx > WIDTH * 0.5) or self.ballx > WIDTH * 0.65

            if defending:
                target_x = self.ballx + 35
                target_y = self.bally
                if abs(self.ballx - self.p2x) > 200:
                    target_y = goal_center + (self.bally - goal_center) * 0.5
            else:
                target_x = self.ballx + 10
                target_y = self.bally

        # Kleiner Zufallsfehler (menschlicher)
        jitter_x = (pyxel.frame_count * 7 % 5) - 2
        jitter_y = (pyxel.frame_count * 13 % 5) - 2
        target_x += jitter_x
        target_y += jitter_y

        dx = target_x - self.p2x
        dy = target_y - self.p2y

        # --- Ecken-Anti-Stuck: Wand-Abstossung ---
        MARGIN = 30
        wall_push_x = 0
        wall_push_y = 0
        if self.p2x < MARGIN:
            wall_push_x = AI_SPEED * 1.5
        elif self.p2x > WIDTH - MARGIN:
            wall_push_x = -AI_SPEED * 1.5
        if self.p2y < FIELD_TOP + MARGIN:
            wall_push_y = AI_SPEED * 1.5
        elif self.p2y > FIELD_BOTTOM - MARGIN:
            wall_push_y = -AI_SPEED * 1.5

        dx += wall_push_x
        dy += wall_push_y

        # Horizontal
        if abs(dx) > 1:
            move = min(AI_SPEED, abs(dx))
            if dx > 0:
                self.p2x += move
                self.p2_facing = 1
            else:
                self.p2x -= move
                self.p2_facing = -1

        # Vertikal
        if abs(dy) > 1:
            move = min(AI_SPEED, abs(dy))
            if dy > 0:
                self.p2y += move
            else:
                self.p2y -= move


    # ------------------------------------------------------------------ #
    #  DRAW MENU SCREEN                                                    #
    # ------------------------------------------------------------------ #
    def _draw_menu(self):
        pyxel.cls(0)

        # Hintergrund-Spielfeld
        for i in range(0, WIDTH, 20):
            color = 3 if (i // 20) % 2 == 0 else 11
            pyxel.rect(i, FIELD_TOP + 20, 20, FIELD_BOTTOM - FIELD_TOP - 40, color)
        pyxel.rect(0, 0, WIDTH, 50, 1)
        pyxel.rect(0, HEIGHT - 50, WIDTH, 50, 1)

        title = "MINI SOCCER DUEL"
        tx = WIDTH // 2 - len(title) * 3
        pyxel.text(tx + 1, 56, title, 0)
        pyxel.text(tx, 55, title, 7)

        sub = "SPIELMODUS WAEHLEN"
        sx2 = WIDTH // 2 - len(sub) * 2
        pyxel.text(sx2 + 1, 68, sub, 0)
        pyxel.text(sx2, 67, sub, 13)

        pyxel.line(60, 80, WIDTH - 60, 80, 5)

        # 3 Optionen: label, desc, detail, col_main, col_accent, icon_mode
        options = [
            ("1 vs 1  (2 Spieler)", "Beide am selben PC",       "P1:WASD   P2:Pfeiltasten",  12, 8,  "pvp"),
            ("1 vs KI  (Einfach)",  "Computer-KI, fair",         "Langsamer, Powerup-Verz.",   11, 3,  "easy"),
            ("1 vs KI  (Schwer)",   "Computer-KI, aggressiv",    "Schnell, Powerups sofort",   9,  2,  "hard"),
        ]

        box_x = 60
        box_w = WIDTH - 120
        box_h = 54

        for i, (label, desc, detail, col_main, col_accent, mode) in enumerate(options):
            box_y = 88 + i * 64
            selected = (self.menu_cursor == i)

            border_col = 7 if selected else 5
            bg_col = 1 if selected else 0
            pyxel.rect(box_x, box_y, box_w, box_h, bg_col)
            pyxel.rectb(box_x, box_y, box_w, box_h, border_col)
            if selected:
                pyxel.rectb(box_x + 2, box_y + 2, box_w - 4, box_h - 4, border_col)

            if selected and (pyxel.frame_count // 15) % 2 == 0:
                pyxel.text(box_x + 5, box_y + 10, ">", col_main)

            # Mini-Figuren
            ix = box_x + 14
            iy = box_y + 5
            # P1 blau
            pyxel.rect(ix, iy + 4, 5, 9, 12)
            pyxel.circ(ix + 2, iy + 2, 3, 14)
            # "vs"
            pyxel.text(ix + 7, iy + 7, "vs", 7)
            # P2 je nach Modus
            p2x = ix + 17
            if mode == "pvp":
                pyxel.rect(p2x, iy + 4, 5, 9, 8)
                pyxel.circ(p2x + 2, iy + 2, 3, 14)
            elif mode == "easy":
                pyxel.rect(p2x, iy + 4, 5, 9, 11)
                pyxel.rect(p2x - 1, iy + 2, 7, 5, 11)
                pyxel.pset(p2x + 1, iy + 4, 0)
                pyxel.pset(p2x + 3, iy + 4, 0)
            else:  # hard
                pyxel.rect(p2x, iy + 4, 5, 9, 9)
                pyxel.rect(p2x - 1, iy + 2, 7, 5, 9)
                pyxel.pset(p2x + 1, iy + 4, 7)
                pyxel.pset(p2x + 3, iy + 4, 7)

            # Text
            lx = box_x + 48
            pyxel.text(lx + 1, box_y + 9,  label,  0)
            pyxel.text(lx,     box_y + 8,  label,  col_main if selected else 6)
            pyxel.text(lx,     box_y + 20, desc,   col_accent if selected else 5)
            pyxel.text(lx,     box_y + 31, detail, 5 if not selected else 6)
            if mode != "pvp":
                tag = "[EINFACH]" if mode == "easy" else "[SCHWER]"
                tag_col = 11 if mode == "easy" else 8
                pyxel.text(box_x + box_w - len(tag)*4 - 6, box_y + 9, tag, tag_col if selected else 5)

        hint = "W/S: Navigieren   SPACE: Bestaetigen   R: Zurueck"
        hx = WIDTH // 2 - len(hint) * 2
        pyxel.text(hx, HEIGHT - 38, hint, 6)


    # ------------------------------------------------------------------ #
    #  DRAW DAYTIME MENU                                                   #
    # ------------------------------------------------------------------ #
    def _draw_daytime_menu(self):
        pyxel.cls(0)

        # Hintergrund: Spielfeld wie im Spiel
        for i in range(0, WIDTH, 20):
            color = 3 if (i // 20) % 2 == 0 else 11
            pyxel.rect(i, FIELD_TOP + 20, 20, FIELD_BOTTOM - FIELD_TOP - 40, color)
        pyxel.rect(0, 0, WIDTH, 50, 1)
        pyxel.rect(0, HEIGHT - 50, WIDTH, 50, 1)

        title = "TAGESZEIT WAEHLEN"
        tx = WIDTH // 2 - len(title) * 3
        pyxel.text(tx + 1, 56, title, 0)
        pyxel.text(tx,     55, title, 7)

        pyxel.line(60, 80, WIDTH - 60, 80, 5)

        # Zwei Optionen nebeneinander: TAG | NACHT
        box_w = 170
        box_h = 220
        gap   = 20
        total = box_w * 2 + gap
        bx1   = (WIDTH - total) // 2
        bx2   = bx1 + box_w + gap
        by    = 96

        for idx, (bx, label, is_night) in enumerate([(bx1, "TAG", False), (bx2, "FLUTLICHTSPIEL", True)]):
            selected = (self.daytime_cursor == idx)
            border   = 7 if selected else 5
            bg       = 1 if selected else 0
            pyxel.rect(bx, by, box_w, box_h, bg)
            pyxel.rectb(bx, by, box_w, box_h, border)
            if selected:
                pyxel.rectb(bx + 2, by + 2, box_w - 4, box_h - 4, border)

            # Vorschau-Minifeld
            px  = bx + 10
            py2 = by + 20
            pw  = box_w - 20
            ph  = 130

            if not is_night:
                # --- TAG: heller Rasen ---
                for si in range(pw // 10):
                    gc = 3 if si % 2 == 0 else 11
                    pyxel.rect(px + si * 10, py2, 10, ph, gc)
                # Linien
                pyxel.line(px + pw // 2, py2, px + pw // 2, py2 + ph, 7)
                pyxel.circb(px + pw // 2, py2 + ph // 2, 18, 7)
                pyxel.rectb(px,            py2 + ph // 2 - 26, 28, 52, 7)
                pyxel.rectb(px + pw - 28,  py2 + ph // 2 - 26, 28, 52, 7)
                pyxel.rect(px,             py2 + ph // 2 - 14, 3, 28, 7)
                pyxel.rect(px + pw - 3,    py2 + ph // 2 - 14, 3, 28, 7)
                pyxel.line(px, py2, px + pw, py2,       7)
                pyxel.line(px, py2 + ph, px + pw, py2 + ph, 7)
                # Zuschauer-Pixel (hell)
                for zx in range(px, px + pw, 5):
                    pyxel.pset(zx, py2 - 3, [12, 8, 7][(zx // 5) % 3])
                    pyxel.pset(zx, py2 + ph + 3, [12, 8, 7][(zx // 5) % 3])
                sun_x = px + pw - 14
                sun_y = py2 + 8
                pyxel.circ(sun_x, sun_y, 5, 10)
                for a in range(8):
                    ang = a * math.pi / 4
                    pyxel.pset(int(sun_x + math.cos(ang) * 8),
                               int(sun_y + math.sin(ang) * 8), 10)
            else:
                # --- NACHT: dunkles Feld ---
                for si in range(pw // 10):
                    gc = 1 if si % 2 == 0 else 0
                    pyxel.rect(px + si * 10, py2, 10, ph, gc)
                # Linien (gedimmt)
                pyxel.line(px + pw // 2, py2, px + pw // 2, py2 + ph, 5)
                pyxel.circb(px + pw // 2, py2 + ph // 2, 18, 5)
                pyxel.rectb(px,           py2 + ph // 2 - 26, 28, 52, 5)
                pyxel.rectb(px + pw - 28, py2 + ph // 2 - 26, 28, 52, 5)
                pyxel.line(px, py2, px + pw, py2,       5)
                pyxel.line(px, py2 + ph, px + pw, py2 + ph, 5)
                # Flutlichter (4 Ecken): heller Kegel
                lights = [
                    (px + 4,      py2 + 4),
                    (px + pw - 4, py2 + 4),
                    (px + 4,      py2 + ph - 4),
                    (px + pw - 4, py2 + ph - 4),
                ]
                cx_f = px + pw // 2
                cy_f = py2 + ph // 2
                flicker = (pyxel.frame_count // 8) % 2
                for lx, ly in lights:
                    # Lichtkegel (Dreieck zum Feldmittelpunkt)
                    steps = 10
                    for s in range(1, steps):
                        t = s / steps
                        ix = int(lx + (cx_f - lx) * t)
                        iy = int(ly + (cy_f - ly) * t)
                        spread = int(s * 2.2)
                        cone_col = 6 if (s < 5 and flicker == 0) else (7 if s < 3 else 5)
                        pyxel.line(ix - spread, iy, ix + spread, iy, cone_col)
                    # Lampe selbst
                    pyxel.circ(lx, ly, 2, 10)
                    pyxel.pset(lx, ly, 7)
                # Sterne
                for si in range(12):
                    sx3 = px + (si * 17 + 3) % pw
                    sy3 = py2 - 8 + (si * 11) % 6
                    if si % 3 == 0:
                        pyxel.pset(sx3, sy3, 7)
                    else:
                        pyxel.pset(sx3, sy3, 6)

            # Label
            lbl_col = 10 if not is_night else 6
            if selected:
                lbl_col = 7
            lx2 = bx + (box_w - len(label) * 4) // 2
            pyxel.text(lx2 + 1, by + box_h - 28, label, 0)
            pyxel.text(lx2,     by + box_h - 29, label, lbl_col)

            if selected:
                ar = ">>  AUSGEWAEHLT  <<"
                ax = bx + (box_w - len(ar) * 4) // 2
                if (pyxel.frame_count // 15) % 2 == 0:
                    pyxel.text(ax, by + box_h - 16, ar, 9)

        hint = "A/D oder Pfeile: Wechseln   SPACE: Bestaetigen   R: Zurueck"
        hx = WIDTH // 2 - len(hint) * 2
        pyxel.text(hx, HEIGHT - 28, hint, 6)

    # ------------------------------------------------------------------ #
    #  DRAW TITLE SCREEN                                                   #
    # ------------------------------------------------------------------ #
    def _draw_title(self):
        pyxel.cls(0)

        # ── STADION-HINTERGRUND ──────────────────────────────────────────────
        for i in range(0, WIDTH, 20):
            color = 3 if (i // 20) % 2 == 0 else 11
            pyxel.rect(i, 0, 20, HEIGHT, color)

        TRIB_H = 44
        pyxel.rect(0, 0, WIDTH, TRIB_H, 1)
        skin_colors = [15, 4, 14, 9]
        for row in range(8):
            ty = 2 + row * 5
            for xi in range(0, WIDTH, 7):
                ox = 0 if row % 2 == 0 else 3
                tx = xi + ox
                shirt_opts = [12, 12, 1, 7] if tx < WIDTH // 2 else [8, 8, 2, 7]
                shirt = shirt_opts[(tx * 3 + row * 7) % len(shirt_opts)]
                skin  = skin_colors[(tx * 3 + row * 7) % len(skin_colors)]
                if ty < TRIB_H - 4:
                    pyxel.pset(tx, ty, skin)
                    pyxel.pset(tx, ty + 2, shirt)

        pyxel.rect(0, HEIGHT - TRIB_H, WIDTH, TRIB_H, 1)
        for row in range(8):
            ty = HEIGHT - 4 - row * 5
            for xi in range(0, WIDTH, 7):
                ox = 0 if row % 2 == 0 else 3
                tx = xi + ox
                shirt_opts = [12, 12, 1, 7] if tx < WIDTH // 2 else [8, 8, 2, 7]
                shirt = shirt_opts[(tx * 3 + row * 7) % len(shirt_opts)]
                skin  = skin_colors[(tx * 3 + row * 7) % len(skin_colors)]
                if ty > HEIGHT - TRIB_H + 4:
                    pyxel.pset(tx, ty, skin)
                    pyxel.pset(tx, ty - 2, shirt)

        pyxel.line(WIDTH // 2, TRIB_H, WIDTH // 2, HEIGHT - TRIB_H, 7)
        pyxel.circb(WIDTH // 2, HEIGHT // 2, 55, 7)

        # ── Layout: Bild + Controls-Box vertikal zentriert ───────────────────
        crop_u  = 0
        crop_v  = 22      # schwarzen Rand oben überspringen
        crop_w  = 256
        crop_h  = 210     # schwarzen Rand unten abschneiden

        ctrl_w  = crop_w
        ctrl_h  = 36
        space_h = 14      # Höhe Press-SPACE-Balken

        gap1    = 6       # Abstand Bild → Controls
        gap2    = 6       # Abstand Controls → Space

        total_h = crop_h + gap1 + ctrl_h + gap2 + space_h
        img_x   = (WIDTH  - crop_w) // 2          # horizontal zentriert = 128
        img_y   = (HEIGHT - total_h) // 2          # vertikal zentriert

        # Titelbild
        pyxel.blt(img_x, img_y, 2, crop_u, crop_v, crop_w, crop_h)

        # Controls-Box
        ctrl_x = img_x
        ctrl_y = img_y + crop_h + gap1
        pyxel.rect(ctrl_x, ctrl_y, ctrl_w, ctrl_h, 0)
        pyxel.rectb(ctrl_x, ctrl_y, ctrl_w, ctrl_h, 5)

        if self.game_mode == "pvp":
            lines = [
                ("P1: WASD",                  12),
                ("P2: Pfeiltasten",             8),
                ("Doppelklick W/UP: Power-Up",  6),
                ("R = Menu",                   13),
            ]
        else:
            lines = [
                ("P1: WASD",                  12),
                ("P2: Computer-KI",            11),
                ("Doppelklick W: Power-Up",     6),
                ("R = Menu",                   13),
            ]
        for li, (txt, col) in enumerate(lines):
            tx = ctrl_x + (ctrl_w - len(txt) * 4) // 2
            pyxel.text(tx, ctrl_y + 4 + li * 8, txt, col)

        # Press SPACE (blinkend)
        space_y = ctrl_y + ctrl_h + gap2
        if self.title_blink < 40:
            lbl = "PRESS SPACE TO PLAY"
            sw  = len(lbl) * 4 + 8
            sx2 = img_x + (ctrl_w - sw) // 2
            pyxel.rect(sx2, space_y, sw, space_h, 0)
            pyxel.rectb(sx2, space_y, sw, space_h, 7)
            pyxel.text(sx2 + 4, space_y + 3, lbl, 9)

    # ------------------------------------------------------------------ #
    #  GOAL-Text Animations-Zeichnung                                      #
    # ------------------------------------------------------------------ #
    def _draw_goal_anim(self, sx, sy):
        """Zeichnet den animierten GOAL!-Text (einzoomen & ausblenden)."""
        if self.goal_anim_timer <= 0:
            return

        scale = self.goal_anim_scale
        if scale <= 0:
            return

        # Farbe je nach Torschütze: P1=Blau, P2=Rot
        col = 12 if self.goal_scorer == 1 else 8

        cx = WIDTH // 2 + sx
        cy = HEIGHT // 2 + sy

        if scale > 0.85:
            bw, bh = 50, 14
            pyxel.rect(cx - bw//2 - 1, cy - bh//2 - 1, bw + 2, bh + 2, 0)
            pyxel.rectb(cx - bw//2 - 1, cy - bh//2 - 1, bw + 2, bh + 2, col)
            pyxel.text(cx - 10, cy - 2, "GOAL!", col)
        elif scale > 0.5:
            bw, bh = 38, 12
            pyxel.rect(cx - bw//2, cy - bh//2, bw, bh, 0)
            pyxel.rectb(cx - bw//2, cy - bh//2, bw, bh, col)
            pyxel.text(cx - 10, cy - 2, "GOAL!", col)
        else:
            bw, bh = 26, 10
            pyxel.rect(cx - bw//2, cy - bh//2, bw, bh, 0)
            pyxel.rectb(cx - bw//2, cy - bh//2, bw, bh, col)
            pyxel.text(cx - 8, cy - 2, "GOL", col)

    # ------------------------------------------------------------------ #
    #  DRAW (Haupt-Dispatcher)                                             #
    # ------------------------------------------------------------------ #
    def draw(self):

        if self.state == "title":
            self._draw_title()
            return

        if self.state == "menu":
            self._draw_menu()
            return

        if self.state == "daytime":
            self._draw_daytime_menu()
            return

        pyxel.cls(0)

        # Kamera-Offset für alle Elemente
        sx = self.shake_x
        sy = self.shake_y

        night = (self.time_of_day == "night")

        # ── RASEN ────────────────────────────────────────────────────────────
        # Tag: normale Grüntöne. Nacht: gedimmte Variante (dunkelgrün statt hell)
        if night:
            for i in range(0, WIDTH, 20):
                color = 3 if (i//20)%2==0 else 1   # dunkelgrün / dunkelblau
                pyxel.rect(i + sx, FIELD_TOP + sy, 20, FIELD_BOTTOM-FIELD_TOP, color)
        else:
            for i in range(0, WIDTH, 20):
                color = 3 if (i//20)%2==0 else 11
                pyxel.rect(i + sx, FIELD_TOP + sy, 20, FIELD_BOTTOM-FIELD_TOP, color)

        # ── TRIBÜNE & PUBLIKUM ───────────────────────────────────────────────
        # Nacht: Zuschauer zeichnen, dann jeden 2. Pixel dunkel übermalen
        self._draw_audience()
        if night:
            for p in self.audience:
                x, y = p["x"], p["y"]
                if (x + y) % 2 == 0:
                    pyxel.pset(x,     y,     1)
                    pyxel.pset(x,     y + 2, 1)
                    pyxel.pset(x - 1, y + 3, 1)

        # ── LATERNEN IN DEN 4 SPIELFELD-ECKEN ───────────────────────────────
        if night:
            flicker = (pyxel.frame_count // 6) % 2

            mast_specs = [
                (sx + 8,         FIELD_TOP    + sy, -1),
                (sx + WIDTH - 9, FIELD_TOP    + sy, -1),
                (sx + 8,         FIELD_BOTTOM + sy,  1),
                (sx + WIDTH - 9, FIELD_BOTTOM + sy,  1),
            ]

            for cx, cy, d in mast_specs:
                mast_h = 32
                top_y = cy - mast_h if d == -1 else cy
                is_left = (cx < WIDTH // 2 + sx)
                is_top  = (d == -1)

                if   is_left  and is_top:     a0, a1 = 0,   90
                elif not is_left and is_top:  a0, a1 = 90,  180
                elif is_left  and not is_top: a0, a1 = 270, 360
                else:                          a0, a1 = 180, 270

                light_src_x = cx
                light_src_y = top_y if d == -1 else top_y + mast_h

                # Untere Laternen: Licht JETZT zeichnen (vor HUD ist ok, unten kein HUD)
                if not is_top:
                    R = 52
                    for r in range(R, 0, -1):
                        if r > R - 10:   col = 9
                        elif r > R - 25: col = 10
                        elif r > R - 38: col = 10
                        else:            col = 7  # weiss
                        for deg in range(a0, a1, 2):
                            ang = deg * math.pi / 180
                            px_ = int(light_src_x + math.cos(ang) * r)
                            py_ = int(light_src_y + math.sin(ang) * r)
                            if 0 <= px_ < WIDTH and FIELD_TOP + sy <= py_ <= FIELD_BOTTOM + sy + 40:
                                pyxel.pset(px_, py_, col)

                # Mast + Lampenkasten (immer jetzt)
                pyxel.rect(cx - 2, top_y, 5, mast_h, 5)
                pyxel.line(cx + 1, top_y + 2, cx + 1, top_y + mast_h - 2, 6)
                mid_y = top_y + mast_h // 2
                pyxel.rect(cx - 7, mid_y - 1, 14, 3, 5)
                pyxel.line(cx - 6, mid_y, cx + 6, mid_y, 6)
                head_y = top_y if d == -1 else top_y + mast_h
                hx = cx - 11
                hy = head_y - 12 if d == -1 else head_y
                pyxel.rect(hx,     hy,     22, 12, 5)
                pyxel.rect(hx + 1, hy + 1, 20, 10, 6)
                pyxel.rect(hx + 2, hy + 2, 18,  8, 6)
                dot_col = 10 if flicker == 0 else 9
                for li in range(4):
                    lsx = hx + 2 + li * 5
                    lsy = hy + 3
                    pyxel.rect(lsx, lsy, 4, 5, dot_col)
                    pyxel.pset(lsx + 1, lsy + 1, 7)
                    pyxel.pset(lsx + 2, lsy + 2, 7)

        # ── FELDLINIEN ───────────────────────────────────────────────────────
        line_col = 7 if not night else 6
        pyxel.line(WIDTH//2 + sx, FIELD_TOP + sy, WIDTH//2 + sx, FIELD_BOTTOM + sy, line_col)
        pyxel.circb(WIDTH//2 + sx, HEIGHT//2 + sy, 55, line_col)
        pyxel.rectb(0 + sx,           HEIGHT//2-110 + sy, 100, 220, line_col)
        pyxel.rectb(WIDTH-100 + sx,   HEIGHT//2-110 + sy, 100, 220, line_col)
        pyxel.rectb(0 + sx,           HEIGHT//2-40 + sy,  30,  80,  line_col)
        pyxel.rectb(WIDTH-30 + sx,    HEIGHT//2-40 + sy,  30,  80,  line_col)

        # --- Tore mit dynamischer Größe zeichnen ---
        goal_top1 = HEIGHT//2 - self.p1_goal_size//2
        goal_top2 = HEIGHT//2 - self.p2_goal_size//2
        draw_left  = True
        draw_right = True
        if self.shrink_timer1 > 0 and (pyxel.frame_count // 8) % 2 == 0:
            draw_left = False
        if self.shrink_timer2 > 0 and (pyxel.frame_count // 8) % 2 == 0:
            draw_right = False
        if draw_left:
            pyxel.rect(0 + sx, goal_top1 + sy, 4, self.p1_goal_size, 7)
        if draw_right:
            pyxel.rect(WIDTH-4 + sx, goal_top2 + sy, 4, self.p2_goal_size, 7)

        for p in self.confetti:
            pyxel.pset(int(p["x"]) + sx, int(p["y"]) + sy, p["col"])

        # --- Pyro: Fackel in Teamfarbe ---
        for p in self.pyro:
            t = p["timer"]
            fx = int(p["x"]) + sx
            fy = int(p["y"]) + sy
            flicker = (pyxel.frame_count % 4)
            # Fackel-Stab
            pyxel.rect(fx-1, fy, 2, 4, 0)
            # Flamme (flackernd, in Teamfarbe)
            flame_h = 5 + flicker
            pyxel.rect(fx-2, fy-flame_h, 4, flame_h, p["col_main"])
            pyxel.rect(fx-1, fy-flame_h+1, 2, flame_h-1, p["col_core"])
            pyxel.pset(fx, fy-flame_h, 7)

        self._draw_player1(self.p1x + sx, self.p1y + sy, self.p1_facing)
        self._draw_player2(self.p2x + sx, self.p2y + sy, self.p2_facing)

        # --- Ballspur zeichnen ---
        trail_len = len(self.ball_trail)
        for ti, tp in enumerate(self.ball_trail):
            # Älteste Punkte = Index 0, neueste = Index -1 (kurz vor Ball)
            age_frac = ti / max(trail_len - 1, 1)  # 0.0 = älteste, 1.0 = neueste
            spd = tp["speed"]
            # Basis-Sichtbarkeit: sehr schwach bei langsamer Geschwindigkeit
            # Spur startet schon bei sehr geringer Stärke (0.05 Minimum bei max speed)
            speed_fac = min(spd / 2.5, 1.0)  # 2.5 ≈ max Ballgeschwindigkeit
            # Gesamt-Alpha: erst neuere Spurpunkte sind sichtbarer
            combined = age_frac * speed_fac
            if combined < 0.04:
                continue
            # Farbe wählen: weiss (7) bei hoher Geschwindigkeit, grau (5/6) sonst
            if combined > 0.55:
                col = 7
            elif combined > 0.3:
                col = 6
            elif combined > 0.15:
                col = 5
            else:
                col = 1
            # Radius: neuere Punkte etwas grösser
            r = 1 if age_frac > 0.5 else 0
            tx = int(tp["x"]) + sx
            ty = int(tp["y"]) + sy
            if r == 0:
                pyxel.pset(tx, ty, col)
            else:
                pyxel.circb(tx, ty, r, col)

        pyxel.blt(int(self.ballx) - 8 + sx, int(self.bally) - 8 + sy, 1, 0, 0, 16, 16, 0)

        # --- Flitzer zeichnen (grösser, ~12x18px, etwas kleiner als Spieler) ---
        if self.invader:
            inv = self.invader
            ix = int(inv["x"]) + sx
            iy = int(inv["y"]) + sy
            leg = (pyxel.frame_count // 4) % 2
            # Kopf
            pyxel.circ(ix, iy - 7, 3, inv["skin"])
            pyxel.pset(ix-1, iy-8, 0)
            pyxel.pset(ix+1, iy-8, 0)
            # Körper / Shirt
            pyxel.rect(ix - 3, iy - 4, 6, 7, inv["shirt"])
            # Arme
            pyxel.rect(ix - 5, iy - 3, 2, 5, inv["skin"])
            pyxel.rect(ix + 3, iy - 3, 2, 5, inv["skin"])
            # Hose
            pyxel.rect(ix - 3, iy + 3, 6, 3, 5)
            # Beine (Laufanimation)
            if leg == 0:
                pyxel.rect(ix - 3, iy + 6, 2, 4, inv["skin"])
                pyxel.rect(ix + 1, iy + 6, 2, 3, inv["skin"])
            else:
                pyxel.rect(ix - 3, iy + 6, 2, 3, inv["skin"])
                pyxel.rect(ix + 1, iy + 6, 2, 4, inv["skin"])

        if self.powerup:
            pyxel.blt(self.powerup["x"] - 8 + sx, self.powerup["y"] - 8 + sy, 1, 0, 16, 16, 16, 0)

        # --- Driftender Pyro-Rauch in Teamfarbe: schränkt die Sicht aufs Feld stark ein ---
        if self.smoke_overlay_timer > 0:
            for p in self.smoke_particles:
                px_ = int(p["x"]) + sx
                py_ = int(p["y"]) + sy
                pyxel.circ(px_, py_, p["r"], p["col_outer"])
                pyxel.circb(px_, py_, p["r"], p["col_inner"])
                pyxel.circ(px_, py_, max(1, p["r"]-4), p["col_inner"])

        # ── HUD OBEN: schwarzer Balken zwischen Tribüne und Spielfeld ──
        HUD_Y = 40
        HUD_H = FIELD_TOP - HUD_Y   # = 20px
        pyxel.rect(0, HUD_Y, WIDTH, HUD_H, 0)
        pyxel.line(0, HUD_Y,       WIDTH, HUD_Y,       5)
        pyxel.line(0, FIELD_TOP-1, WIDTH, FIELD_TOP-1, 5)

        def shadowed(tx, ty, txt, col):
            pyxel.text(tx+1, ty+1, txt, 1)
            pyxel.text(tx, ty, txt, col)

        # P1 links – näher zur Mitte
        p1_offset = 80 if night else 60
        shadowed(p1_offset, HUD_Y + 6, f"P1: {self.score1}", 12)

        # P2 rechts – näher zur Mitte
        p2_label  = "KI" if self.game_mode in ("pvc_easy", "pvc_hard") else "P2"
        p2_txt    = f"{p2_label}: {self.score2}"
        p2_offset = 80 if night else 60
        shadowed(WIDTH - p2_offset - len(p2_txt) * 4, HUD_Y + 6, p2_txt, 8)

        # Timer mittig
        seconds = self.timer // 60
        t_txt = str(seconds) if not self.overtime else f"{seconds}OT"
        t_x = WIDTH // 2 - len(t_txt) * 2
        shadowed(t_x, HUD_Y + 6, t_txt, 10)

        # Trennlinien
        pyxel.line(WIDTH//2 - 40, HUD_Y+2, WIDTH//2 - 40, HUD_Y+HUD_H-2, 5)
        pyxel.line(WIDTH//2 + 40, HUD_Y+2, WIDTH//2 + 40, HUD_Y+HUD_H-2, 5)

        # ── POWER-ANZEIGEN UNTEN (direkt über unterer Tribüne) ──
        BOT_Y = FIELD_BOTTOM + 4

        has_p1_info = self.p1_power or self.active_power1 or self.shrink_timer1 > 0
        has_p2_info = self.p2_power or self.active_power2 or self.shrink_timer2 > 0

        if has_p1_info:
            pyxel.rect(2, BOT_Y, 120, 14, 0)
            pyxel.rectb(2, BOT_Y, 120, 14, 12)
            if self.p1_power:
                pyxel.text(5, BOT_Y+4, f"P1 GOT: {self.p1_power.upper()}  (2xW)", 12)
            elif self.active_power1:
                secs = self.power_timer1 // 60
                pyxel.text(5, BOT_Y+4, f"P1 ACTIVE: {self.active_power1.upper()} {secs}s", 10)
            elif self.shrink_timer1 > 0:
                secs = self.shrink_timer1 // 60
                pyxel.text(5, BOT_Y+4, f"P1 SHRINK: {secs}s", 11)

        if has_p2_info:
            pyxel.rect(WIDTH-122, BOT_Y, 120, 14, 0)
            pyxel.rectb(WIDTH-122, BOT_Y, 120, 14, 8)
            if self.p2_power:
                pyxel.text(WIDTH-119, BOT_Y+4, f"P2 GOT: {self.p2_power.upper()}  (2x^)", 8)
            elif self.active_power2:
                secs = self.power_timer2 // 60
                pyxel.text(WIDTH-119, BOT_Y+4, f"P2 ACTIVE: {self.active_power2.upper()} {secs}s", 10)
            elif self.shrink_timer2 > 0:
                secs = self.shrink_timer2 // 60
                pyxel.text(WIDTH-119, BOT_Y+4, f"P2 SHRINK: {secs}s", 11)
        
        if self.show_overtime > 0:
            pyxel.rect(156, 40, 200, 22, 0)
            pyxel.rectb(156, 40, 200, 22, 7)
            pyxel.text(196, 44, "OVERTIME!", 7)
            pyxel.text(178, 52, "GOLDEN GOAL RULE", 7)

        # ── Obere Laternen: Lichtkreis NACH HUD zeichnen (liegt drüber) ──────
        if night:
            for cx, cy, d in [
                (sx + 8,         FIELD_TOP + sy, -1),
                (sx + WIDTH - 9, FIELD_TOP + sy, -1),
            ]:
                is_left = (cx < WIDTH // 2 + sx)
                a0, a1 = (0, 90) if is_left else (90, 180)
                light_src_x = cx
                light_src_y = cy - 32
                R = 52
                for r in range(R, 0, -1):
                    if r > R - 10:   col = 9
                    elif r > R - 25: col = 10
                    elif r > R - 38: col = 10
                    else:            col = 7
                    for deg in range(a0, a1, 2):
                        ang = deg * math.pi / 180
                        px_ = int(light_src_x + math.cos(ang) * r)
                        py_ = int(light_src_y + math.sin(ang) * r)
                        if 0 <= px_ < WIDTH and 0 <= py_ < HEIGHT:
                            pyxel.pset(px_, py_, col)

        # --- GOAL-Text Animation ---
        self._draw_goal_anim(sx, sy)
        
        if self.game_over:
            if self.score1 > self.score2:
                winner = "PLAYER 1 WINS!"
                w_col = 12
            elif self.score2 > self.score1:
                winner = "PLAYER 2 WINS!"
                w_col = 8
            else:
                winner = "DRAW!"
                w_col = 7

            PX, PY, PW, PH = 80, 110, 352, 290
            pyxel.rect(PX, PY, PW, PH, 0)
            pyxel.rectb(PX, PY, PW, PH, 7)
            pyxel.rectb(PX+2, PY+2, PW-4, PH-4, 5)

            def shadowed(tx, ty, txt, col):
                pyxel.text(tx+1, ty+1, txt, 1)
                pyxel.text(tx, ty, txt, col)

            # Winner
            wx = PX + PW//2 - len(winner) * 2
            shadowed(wx, PY + 14, winner, w_col)

            # Score
            result = f"{self.score1}  :  {self.score2}"
            rx = PX + PW//2 - len(result) * 2
            shadowed(rx, PY + 28, result, 7)

            pyxel.line(PX+10, PY+40, PX+PW-10, PY+40, 5)

            # Stats header
            shadowed(PX + PW//2 - 22, PY + 48, "STATISTICS", 13)

            col_p1 = PX + PW - 100
            col_p2 = PX + PW - 50

            # Spalten-Header
            pyxel.text(col_p1 + 4, PY + 62, "P1", 12)
            pyxel.text(col_p2 + 4, PY + 62, "P2", 8)

            # Allgemeine Stats
            pyxel.text(PX+16, PY+74,  "Shots on goal:", 6)
            shadowed(col_p1, PY+74, str(self.shots1), 12)
            shadowed(col_p2, PY+74, str(self.shots2), 8)

            pyxel.text(PX+16, PY+86,  "Power-Ups gesammelt:", 6)
            shadowed(col_p1, PY+86, str(self.powerups1), 12)
            shadowed(col_p2, PY+86, str(self.powerups2), 8)

            pyxel.line(PX+10, PY+98, PX+PW-10, PY+98, 5)

            # Power-Up-Typ Header
            shadowed(PX + PW//2 - 34, PY + 104, "POWER-UPS USED", 13)

            type_labels = {
                "speed": "Speed Boost:",
                "powershot": "Power Shot:",
                "freeze": "Freeze:",
                "shrink": "Goal Shrink:",
            }
            row_y = PY + 118
            for ptype, label in type_labels.items():
                pyxel.text(PX+16, row_y, label, 6)
                shadowed(col_p1, row_y, str(self.power_used1[ptype]), 12)
                shadowed(col_p2, row_y, str(self.power_used2[ptype]), 8)
                row_y += 12

            pyxel.line(PX+10, row_y+2, PX+PW-10, row_y+2, 5)

            # Restart
            if (pyxel.frame_count // 20) % 2 == 0:
                rr = "PRESS R FOR MENU"
                shadowed(PX + PW//2 - len(rr)*2, row_y+16, rr, 9)

        
SoccerGame()