import pyxel
import random
import math

WIDTH = 200
HEIGHT = 200
PISTE_HOEHE = 800

PISTE_LINKS  = 32
PISTE_RECHTS = 168

spieler_x = float(WIDTH // 2)
spieler_y = 60.0

kamera_y = 0
speed = 1
boost_timer = 0
invincible_timer = 0
slow_timer = 0

score = 0
level = 1
state = "start"
high_score = 0
sterne_gesammelt = 0
selected_char = 1

kurve_amplitude = 0.0
kurve_ziel      = 0.0
kurve_timer     = 0
kurve_offset    = 0.0

spieler_bewegt_sich = False
spieler_richtung    = 0
anim_timer          = 0

# ---- Figuren: (normal_x, normal_y, rechts_x, rechts_y, links_x, links_y, name) ----
CHAR_SPRITES = {
    1: (40, 40, 56, 40, 72, 40, "Skifahrer"),
    2: (8,  40, 24, 96, 40, 96, "Skifahrer"),
    3: (0,   0,  0, 96,  0,112, "Pinguin"),
    4: (24, 16,  0,128, 16,128, "Eisbaer"),
}

ZUSCHAUER_TYPEN = [
    (88,  104),
    (120, 136),
    (152, 168),
    (184, 200),
]

buesche          = []
hindernisse      = []
hindernisse_bewegend = []
bretter          = []
sterne           = []
schneeflocken    = []
spuren           = []
felsen           = []
wind_x           = 0
wind_timer       = 0
crash_timer      = 0
frame            = 0

zuschauer_links  = []
zuschauer_rechts = []

pyxel.init(WIDTH, HEIGHT, title="Crashing the Pist", fps=60)
pyxel.load("res.pyxres")

#  Sound

pyxel.sounds[0].set("f2rg2rc3rb-2rf2rg2re-3rc3r","pppppppppppppppp","6565656565656565","nnnnnnnnnnnnnnnn",12)
pyxel.sounds[1].set("e-3rb-2rg2re-2rc3rb-2ra-2rg2r","pppppppppppppppppp","656565656565656565","nnnnnnnnnnnnnnnnnn",12)
pyxel.sounds[2].set("f1rrrb-1rrre-1rrrc1rrr","ssssssssssssssss","6400640064006400","nnnnnnnnnnnnnnnn",14)
pyxel.sounds[3].set("c3e3g3c4","s","7654","n",8)
pyxel.sounds[4].set("c3d3e3g3a3","p","76543","n",6)
pyxel.sounds[5].set("g2f2e2d2c2","n","77654","n",6)
pyxel.sounds[6].set("c3e3g3c4g3e3c4","s","7777777","n",10)
pyxel.sounds[7].set("c4","p","5","n",4)
pyxel.sounds[8].set("c3e3g3","s","765","n",8)
pyxel.sounds[9].set("g2e2c2","n","543","n",8)

musik_phase  = 0
musik_timer  = 0
musik_laeuft = False
PHRASE_LAENGE = 128


def musik_starten():
    global musik_phase, musik_timer, musik_laeuft
    musik_phase = 0; musik_timer = 0; musik_laeuft = True
    pyxel.play(0, 0, loop=False)
    pyxel.play(1, 2, loop=False)


def musik_stoppen():
    global musik_laeuft
    musik_laeuft = False
    pyxel.stop(0); pyxel.stop(1)


def musik_update():
    global musik_phase, musik_timer
    if not musik_laeuft:
        return
    musik_timer += 1
    if musik_timer >= PHRASE_LAENGE:
        musik_timer = 0
        musik_phase = (musik_phase + 1) % 4
        pyxel.play(0, 0 if musik_phase % 2 == 0 else 1, loop=False)
        if musik_phase % 2 == 0:
            pyxel.play(1, 2, loop=False)


# Hilfsfunktionen


def draw_center_text(y, text, color):
    x = WIDTH // 2 - len(text) * 2
    pyxel.text(x, y, text, color)


def draw_outlined_text(y, text, color, outline_color):
    x = WIDTH // 2 - len(text) * 2
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if dx != 0 or dy != 0:
                pyxel.text(x + dx, y + dy, text, outline_color)
    pyxel.text(x, y, text, color)


def draw_outlined_text_xy(x, y, text, color, outline_color):
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if dx != 0 or dy != 0:
                pyxel.text(x + dx, y + dy, text, outline_color)
    pyxel.text(x, y, text, color)


def draw_big_text(y, text, color, outline_color, scale=2):
    x = WIDTH // 2 - len(text) * 2 * scale
    for dx in range(-scale, scale + 1):
        for dy in range(-scale, scale + 1):
            if dx != 0 or dy != 0:
                pyxel.text(x + dx, y + dy, text, outline_color)
    pyxel.text(x, y, text, color)


def get_speed():
    base = 0.8 + level * 0.18
    if slow_timer > 0:
        return base * 0.45
    return base


def get_hindernis_geschwindigkeit():
    return 0.5 + (level - 3) * 0.25


def hat_kurven():
    return level in (2, 4)


def get_kurven_offset(world_y):
    if not hat_kurven():
        return 0.0
    faktor = 0.018 if level == 2 else 0.022
    return kurve_amplitude * math.sin(world_y * faktor + kurve_offset)


def init_schneeflocken():
    global schneeflocken
    schneeflocken = []
    for _ in range(60):
        schneeflocken.append([
            random.uniform(0, WIDTH), random.uniform(0, HEIGHT),
            random.uniform(0.3, 1.2), random.uniform(-0.3, 0.3),
            random.randint(0, 2)
        ])


def init_spuren():
    global spuren
    spuren = []


def init_zuschauer():
    global zuschauer_links, zuschauer_rechts
    zuschauer_links = []; zuschauer_rechts = []
    y = 40
    while y < PISTE_HOEHE - 20:
        zuschauer_links.append((random.randint(-5, 5), y, random.randint(0, 29), random.randint(0, 3)))
        y += random.randint(22, 45)
    y = 40
    while y < PISTE_HOEHE - 20:
        zuschauer_rechts.append((random.randint(-5, 5), y, random.randint(0, 29), random.randint(0, 3)))
        y += random.randint(22, 45)


def init_buesche():
    global buesche
    buesche = []
    letzter = -1
    y = 20
    while y < PISTE_HOEHE - 20:
        typen = [t for t in range(3) if t != letzter]
        typ = random.choice(typen)
        letzter = typ
        buesche.append(("links", y, typ))
        y += random.randint(14, 28)
    letzter = -1
    y = 20
    while y < PISTE_HOEHE - 20:
        typen = [t for t in range(3) if t != letzter]
        typ = random.choice(typen)
        letzter = typ
        buesche.append(("rechts", y, typ))
        y += random.randint(14, 28)


def init_kurven():
    global kurve_amplitude, kurve_ziel, kurve_timer, kurve_offset
    kurve_amplitude = 0.0; kurve_ziel = 0.0; kurve_timer = 0
    kurve_offset = random.uniform(0, math.pi * 2)


#  Level - generierung


def pos_ok(x, y, liste, min_dx=24, min_dy=24):
    if x < PISTE_LINKS + 8 or x > PISTE_RECHTS - 8:
        return False
    for h in liste:
        if abs(x - h[0]) < min_dx and abs(y - h[1]) < min_dy:
            return False
    return True


def neues_level():
    global hindernisse, hindernisse_bewegend, sterne, felsen, spuren, bretter

    hindernisse = []; hindernisse_bewegend = []
    sterne = []; felsen = []; spuren = []; bretter = []

    finish_y  = PISTE_HOEHE - 60
    min_start = 120
    alle      = []

    if level == 1:
        init_kurven(); anzahl_statisch = 10; min_abstand = 30
    elif level == 2:
        init_kurven(); anzahl_statisch = 12; min_abstand = 28
    elif level == 3:
        init_kurven(); anzahl_statisch = 18; min_abstand = 24
    else:
        init_kurven(); anzahl_statisch = 24; min_abstand = 20

    for _ in range(anzahl_statisch * 5):
        if len(hindernisse) >= anzahl_statisch:
            break
        x = random.randint(PISTE_LINKS + 10, PISTE_RECHTS - 10)
        y = random.randint(min_start, finish_y - 20)
        if pos_ok(x, y, alle, min_abstand, min_abstand):
            typ = random.choices(["tree", "snowman"], weights=[3, 1])[0]
            hindernisse.append([x, y, typ])
            alle.append([x, y])

    if level >= 3:
        anzahl_b = 2 if level == 3 else 6
        geschw   = get_hindernis_geschwindigkeit()
        for _ in range(anzahl_b * 8):
            if len(hindernisse_bewegend) >= anzahl_b:
                break
            x = random.randint(PISTE_LINKS + 10, PISTE_RECHTS - 10)
            y = random.randint(min_start, finish_y - 20)
            if pos_ok(x, y, alle, min_abstand + 10, min_abstand):
                typ      = random.choices(["tree", "snowman"], weights=[3, 1])[0]
                richtung = random.choice([-1, 1])
                hindernisse_bewegend.append([x, y, typ, richtung, geschw])
                alle.append([x, y])

    anzahl_bretter = max(3, level)
    for _ in range(anzahl_bretter * 10):
        if len(bretter) >= anzahl_bretter:
            break
        x = random.randint(PISTE_LINKS + 15, PISTE_RECHTS - 15)
        y = random.randint(min_start, finish_y - 20)
        if pos_ok(x, y, alle, 25, 25):
            bretter.append([x, y])
            alle.append([x, y])

    for _ in range(5 * 30):
        if len(sterne) >= 5:
            break
        x = random.randint(PISTE_LINKS + 10, PISTE_RECHTS - 10)
        y = random.randint(min_start, finish_y - 20)
        if pos_ok(x, y, alle, 20, 20):
            sterne.append([x, y])
            alle.append([x, y])

    for _ in range(10 + level * 2):
        if random.random() < 0.5:
            x = random.randint(2, PISTE_LINKS - 4)
        else:
            x = random.randint(PISTE_RECHTS + 4, WIDTH - 2)
        y = random.randint(60, finish_y)
        felsen.append([x, y, random.randint(3, 6)])


def reset():
    global spieler_x, spieler_y, kamera_y, score, level, state
    global speed, boost_timer, invincible_timer, wind_x, wind_timer, frame
    global sterne_gesammelt, slow_timer, anim_timer

    spieler_x = float(WIDTH // 2); spieler_y = 60.0; kamera_y = 0
    score = 0; level = 1; speed = 1
    boost_timer = 0; invincible_timer = 0; slow_timer = 0; anim_timer = 0
    wind_x = 0; wind_timer = 0; frame = 0
    sterne_gesammelt = 0; state = "start"
    musik_stoppen(); init_spuren(); init_kurven()

# Update

def update():
    global spieler_x, spieler_y, kamera_y, speed, boost_timer, invincible_timer
    global score, level, state, crash_timer, high_score, slow_timer
    global wind_x, wind_timer, frame, sterne_gesammelt, selected_char
    global kurve_amplitude, kurve_ziel, kurve_timer, kurve_offset
    global spieler_bewegt_sich, spieler_richtung, anim_timer

    frame += 1
    spieler_bewegt_sich = False

    for s in schneeflocken:
        s[1] += s[2]; s[0] += s[3] + wind_x * 0.3
        if s[1] > HEIGHT: s[1] = -2; s[0] = random.uniform(0, WIDTH)
        s[0] = s[0] % WIDTH

    wind_timer -= 1
    if wind_timer <= 0:
        wind_x = random.uniform(-0.6, 0.6); wind_timer = random.randint(120, 300)

    musik_update()

    if hat_kurven() and state == "game":
        kurve_timer -= 1
        if kurve_timer <= 0:
            amp_max = 28 if level == 2 else 35
            kurve_ziel  = random.uniform(-amp_max, amp_max)
            kurve_timer = random.randint(100, 200)
        kurve_amplitude += (kurve_ziel - kurve_amplitude) * 0.028

    if slow_timer > 0:
        slow_timer -= 1

    if state == "start":
        if not musik_laeuft:
            musik_starten()
        if pyxel.btnp(pyxel.KEY_S):
            pyxel.play(2, 8); state = "char_select"

    elif state == "char_select":
        if pyxel.btnp(pyxel.KEY_Y):
            selected_char = (selected_char - 2) % 4 + 1; pyxel.play(2, 7)
        if pyxel.btnp(pyxel.KEY_X):
            selected_char = selected_char % 4 + 1; pyxel.play(2, 7)
        if pyxel.btnp(pyxel.KEY_S):
            pyxel.play(2, 8); state = "game"; neues_level()

    elif state == "game":

        for h in hindernisse_bewegend:
            h[0] += h[3] * h[4]
            if h[0] <= PISTE_LINKS + 8:   h[0] = PISTE_LINKS + 8;   h[3] = 1
            elif h[0] >= PISTE_RECHTS - 8: h[0] = PISTE_RECHTS - 8; h[3] = -1

        move = 2 if boost_timer == 0 else 3
        if slow_timer > 0:
            move = 1

        kurven_versatz = get_kurven_offset(spieler_y)
        piste_mitte    = WIDTH // 2 + kurven_versatz
        piste_l        = piste_mitte - (PISTE_RECHTS - PISTE_LINKS) // 2
        piste_r        = piste_mitte + (PISTE_RECHTS - PISTE_LINKS) // 2

        if pyxel.btn(pyxel.KEY_Y):
            spieler_x -= move
            spieler_bewegt_sich = True
            if spieler_richtung != -1:
                spieler_richtung = -1
                anim_timer = 1  
        if pyxel.btn(pyxel.KEY_X):
            spieler_x += move
            spieler_bewegt_sich = True
            if spieler_richtung != 1:
                spieler_richtung = 1
                anim_timer = 1

        if not spieler_bewegt_sich:
            if anim_timer > 0:
                anim_timer -= 1
            else:
                spieler_richtung = 0

        spieler_x = max(piste_l + 4, min(piste_r - 4, spieler_x))

        if spieler_bewegt_sich and frame % 3 == 0:
            spuren.append([spieler_x - 3, spieler_x + 3, spieler_y])
            if len(spuren) > 100:
                spuren.pop(0)

       
        if boost_timer > 0:
            boost_timer -= 1
            spieler_y += get_speed() + 0.6
        else:
            spieler_y += get_speed()

        kamera_y = max(0, spieler_y - HEIGHT // 3)

        if invincible_timer > 0:
            invincible_timer -= 1

        if frame % 30 == 0:
            score += 1

        for b in bretter:
            if abs(spieler_x - b[0]) < 14 and abs(spieler_y - b[1]) < 10:
                if slow_timer == 0:
                    slow_timer = 90
                    pyxel.play(2, 9)

      
        for s in sterne[:]:
            if abs(spieler_x - s[0]) < 12 and abs(spieler_y - s[1]) < 12:
                sterne.remove(s)
                sterne_gesammelt += 1
                score += 15
                boost_timer = 50
                pyxel.play(2, 3); pyxel.play(3, 4)

        if invincible_timer <= 0:
            for h in hindernisse + hindernisse_bewegend:
                if abs(spieler_x - h[0]) < 11 and abs(spieler_y - h[1]) < 11:
                    state = "crash"; crash_timer = 30
                    musik_stoppen(); pyxel.play(2, 5)
                    if score > high_score: high_score = score
                    break

        if spieler_y >= PISTE_HOEHE - 40:
            score += level * 50
            if score > high_score: high_score = score
            musik_stoppen(); pyxel.play(2, 6)
            state = "level_end"

    elif state == "crash":
        crash_timer -= 1
        if crash_timer <= 0: state = "gameover"

    elif state == "level_end":
        if pyxel.btnp(pyxel.KEY_S):
            pyxel.play(2, 8)
            if level < 4:
                level += 1
                spieler_y = 60.0; spieler_x = float(WIDTH // 2)
                kamera_y = 0; slow_timer = 0; anim_timer = 0
                boost_timer = 0; invincible_timer = 90
                init_spuren(); neues_level(); musik_starten()
                state = "game"
            else:
                state = "win"

    elif state == "win":
        if pyxel.btnp(pyxel.KEY_S):
            pyxel.play(2, 8); reset()

    elif state == "gameover":
        if pyxel.btnp(pyxel.KEY_S):
            pyxel.play(2, 8); reset()


#  Grafik

def draw_zuschauer():
    for (x_off, world_y, phase_off, typ) in zuschauer_links:
        sy = world_y - kamera_y
        if -16 <= sy <= HEIGHT:
            phase = (frame + phase_off) // 15 % 2
            sx, lx = ZUSCHAUER_TYPEN[typ]
            pyxel.blt(4 + x_off, int(sy), 0, sx if phase == 0 else lx, 40, 16, 16, 0)

    for (x_off, world_y, phase_off, typ) in zuschauer_rechts:
        sy = world_y - kamera_y
        if -16 <= sy <= HEIGHT:
            phase = (frame + phase_off) // 15 % 2
            sx, lx = ZUSCHAUER_TYPEN[typ]
            pyxel.blt(WIDTH - 20 + x_off, int(sy), 0, sx if phase == 0 else lx, 40, -16, 16, 0)


# Busch-Sprite-Koordinaten
BUSCH_SPRITES = [(88, 16), (104, 16), (120, 16)]

def draw_busch(screen_x, screen_y, typ):
    sx, sy = BUSCH_SPRITES[typ]
    pyxel.blt(screen_x - 8, screen_y - 8, 0, sx, sy, 16, 16, 0)


def draw_buesche():
    for (seite, world_y, typ) in buesche:
        sy = world_y - kamera_y
        if -10 <= sy <= HEIGHT + 10:
            offset = int(get_kurven_offset(world_y)) if hat_kurven() else 0
            if seite == "links":
                draw_busch(PISTE_LINKS + offset - 8, int(sy), typ)
            else:
                draw_busch(PISTE_RECHTS + offset + 8, int(sy), typ)


def draw_brett(x, y):
    sy = y - kamera_y
    pyxel.blt(int(x) - 8, int(sy) - 8, 0, 0, 240, 16, 16, 0)


def draw_piste():
    pyxel.cls(7)

    if hat_kurven():
        for y in range(0, HEIGHT, 2):
            world_y = y + kamera_y
            offset  = int(get_kurven_offset(world_y))
            l = PISTE_LINKS  + offset
            r = PISTE_RECHTS + offset
            if 0 <= l - 1 < WIDTH: pyxel.pset(l - 1, y, 6)
            if 0 <= r + 1 < WIDTH: pyxel.pset(r + 1, y, 6)

    for spur in spuren:
        sy = spur[2] - kamera_y
        if 0 <= sy <= HEIGHT:
            pyxel.pset(int(spur[0]) - 2, int(sy), 13)
            pyxel.pset(int(spur[1]) + 2, int(sy), 13)

    draw_buesche()
    draw_zuschauer()


def draw_finish_line():
    fwy = PISTE_HOEHE - 40
    fsy = int(fwy - kamera_y)
    if -20 <= fsy <= HEIGHT + 20:
        for row in range(6):
            for x in range(0, WIDTH, 8):
                color = 0 if (x // 8 + row) % 2 == 0 else 7
                pyxel.rect(x, fsy + row * 4, 8, 4, color)
        draw_center_text(fsy - 8, "FINISH", 8)


def draw_hud():
    pyxel.rect(0, 0, WIDTH, 22, 0)
    pyxel.text(4, 4,  f"Score:{score}", 7)
    pyxel.text(4, 13, f"Lvl:{level}/4  *{sterne_gesammelt}", 7)
    pyxel.text(WIDTH - 50, 4,  f"Hi:{high_score}", 7)
    bar_w = int(min(get_speed() / (0.8 + level * 0.18 + 0.6 + 1.5), 1.0) * 30)
    pyxel.text(WIDTH - 50, 13, "Spd", 7)
    pyxel.rect(WIDTH - 32, 13, 30, 5, 1)
    bar_col = 9 if slow_timer > 0 else (10 if boost_timer > 0 else 11)
    pyxel.rect(WIDTH - 32, 13, bar_w, 5, bar_col)
    if abs(wind_x) > 0.2:
        pyxel.text(WIDTH // 2 - 4, 14, "<" if wind_x < 0 else ">", 7)


def draw_player(x, y):
    sy = y - kamera_y
    if invincible_timer > 0 and frame % 4 < 2:
        return
    nx, ny, rx, ry, lx, ly, _ = CHAR_SPRITES[selected_char]
    if spieler_richtung == 1:
        sx, sprite_y = rx, ry
    elif spieler_richtung == -1:
        sx, sprite_y = lx, ly
    else:
        sx, sprite_y = nx, ny
    pyxel.blt(int(x) - 8, int(sy) - 8, 0, sx, sprite_y, 16, 16, 0)


def draw_hindernis(h):
    offset = int(get_kurven_offset(h[1])) if hat_kurven() else 0
    sy = h[1] - kamera_y
    if -20 <= sy <= HEIGHT + 20:
        dx = int(h[0] + offset)
        if h[2] == "tree":
            pyxel.blt(dx - 8, int(sy) - 8, 0, 32, 72, 16, 16, 0)
        else:
            pyxel.blt(dx - 8, int(sy) - 8, 0, 48, 72, 16, 16, 0)


def draw_bewegendes_hindernis(h):
    sy = h[1] - kamera_y
    if -20 <= sy <= HEIGHT + 20:
        if h[2] == "tree":
            pyxel.blt(int(h[0]) - 8, int(sy) - 8, 0, 32, 72, 16, 16, 0)
        else:
            pyxel.blt(int(h[0]) - 8, int(sy) - 8, 0, 48, 72, 16, 16, 0)
        pyxel.text(int(h[0]) - 2, int(sy) - 12, "<" if h[3] < 0 else ">", 8)


def draw_star(x, y):
    offset = int(get_kurven_offset(y)) if hat_kurven() else 0
    sy = y - kamera_y
    if frame % 20 < 10:
        pyxel.blt(int(x + offset) - 8, int(sy) - 8, 0, 16, 72, 16, 16, 0)
    else:
        pyxel.blt(int(x + offset) - 7, int(sy) - 7, 0, 16, 72, 14, 14, 0)


def draw_crash_sprite(x, y):
    sy = y - kamera_y
    pyxel.blt(int(x) - 8, int(sy) - 8, 0, 24, 40, 16, 16, 0)


def draw_schneeflocken():
    for s in schneeflocken:
        sx, sy = int(s[0]), int(s[1])
        size   = s[4]
        if size == 0:
            pyxel.pset(sx, sy, 13)
        elif size == 1:
            pyxel.pset(sx, sy, 13); pyxel.pset(sx + 1, sy, 13)
        else:
            pyxel.pset(sx, sy, 6); pyxel.pset(sx + 1, sy, 13); pyxel.pset(sx, sy + 1, 13)


#  Startscreen

def draw_startscreen():
    pyxel.cls(12)

    # Sonne
    pyxel.blt(152, 18, 0, 0, 224, 16, 16, 0)
    for angle in range(0, 360, 45):
        rad = math.radians(angle + frame * 0.4)
        x1  = int(160 + math.cos(rad) * 18)
        y1  = int(26  + math.sin(rad) * 18)
        x2  = int(160 + math.cos(rad) * 22)
        y2  = int(26  + math.sin(rad) * 22)
        pyxel.line(x1, y1, x2, y2, 10)

    # Berge
    for bx in range(0, WIDTH, 32):
        pyxel.blt(bx, 68, 0, 24, 216, 32, 16, 0)

    # Schneedecke
    pyxel.rect(0, 82, WIDTH, HEIGHT - 82, 7)

    # Pisten-Andeutung
    pyxel.line(65, 84, 45, HEIGHT, 13)
    pyxel.line(135, 84, 155, HEIGHT, 13)

    # Büsche am Rand
    for i, y in enumerate(range(98, HEIGHT, 20)):
        draw_busch(22, y, i % 3)
        draw_busch(178, y, (i + 1) % 3)

    # Zuschauer links neben der Piste 
    zuschauer_start_y = [96, 112, 128, 144, 160, 176]
    for i, sy in enumerate(zuschauer_start_y):
        phase = (frame + i * 7) // 15 % 2
        typ   = i % 4
        sx_sprite, lx_sprite = ZUSCHAUER_TYPEN[typ]
        sprite_x = sx_sprite if phase == 0 else lx_sprite
        # Links
        pyxel.blt(30, sy, 0, sprite_x, 40, 16, 16, 0)
        # Rechts
        pyxel.blt(154, sy, 0, sprite_x, 40, -16, 16, 0)

    # Spielfiguren
    pyxel.blt(60, 138, 0, CHAR_SPRITES[1][0], CHAR_SPRITES[1][1], 16, 16, 0)
    pyxel.blt(80, 152, 0, CHAR_SPRITES[2][0], CHAR_SPRITES[2][1], 16, 16, 0)
    pyxel.blt(110, 145, 0, CHAR_SPRITES[3][0], CHAR_SPRITES[3][1], 16, 16, 0)
    pyxel.blt(130, 155, 0, CHAR_SPRITES[4][0], CHAR_SPRITES[4][1], 16, 16, 0)

    # Pokal
    pyxel.blt(WIDTH // 2 - 8, 118, 0, 104, 72, 16, 16, 0)

    # Schneeflocken
    draw_schneeflocken()

    # Titel
    titel = "CRASHING THE PISTE"
    tx = WIDTH // 2 - len(titel) * 2
    for ddx in [-1, 0, 1]:
        for ddy in [-1, 0, 1]:
            if ddx != 0 or ddy != 0:
                pyxel.text(tx + ddx, 18 + ddy, titel, 0)
    pyxel.text(tx, 18, titel, 10)

    # Anweisungsbox
    box_x = 2
    box_y = 28
    box_w = 96   
    pyxel.rect(box_x, box_y, box_w, 36, 0)
    pyxel.rectb(box_x, box_y, box_w, 36, 10)
    pyxel.text(box_x + 4, box_y + 4,  "Y/X=Links/Rechts", 7)
    pyxel.text(box_x + 4, box_y + 14, "Stern = Boost", 10)
    pyxel.text(box_x + 4, box_y + 24, "Huetchen=Langsam!", 9)

    if high_score > 0:
        pyxel.text(4, HEIGHT - 10, f"Hi:{high_score}", 10)

    if frame % 30 < 20:
        pyxel.rect(4, HEIGHT - 20, 68, 10, 8)
        pyxel.rectb(4, HEIGHT - 20, 68, 10, 10)
        pyxel.text(8, HEIGHT - 17, "S = SPIELEN!", 10)


#  Draw Haupt

def draw():
    if state == "start":
        draw_startscreen()
        return

    if state == "char_select":
        pyxel.cls(12)
        draw_schneeflocken()
        draw_outlined_text(18, "CRASHING THE PIST", 10, 0)
        draw_center_text(38, "WAEHLE DEINEN FAHRER", 0)
        positionen = [(44, 55), (116, 55), (44, 120), (116, 120)]
        for i, char_nr in enumerate([1, 2, 3, 4]):
            bx, by = positionen[i]
            sel    = (selected_char == char_nr)
            nx, ny, rx, ry, lx, ly, name = CHAR_SPRITES[char_nr]
            pyxel.rectb(bx, by, 40, 52, 10 if sel else 7)
            if sel:
                pyxel.rect(bx + 1, by + 1, 38, 50, 6)
            pyxel.blt(bx + 12, by + 8, 0, nx, ny, 16, 16, 0)
            name_x = bx + 20 - len(name) * 2
            draw_outlined_text_xy(name_x, by + 30, name, 10, 0)
            pyxel.text(bx + 3, by + 3, str(char_nr), 0 if sel else 13)
        draw_center_text(178, "Y / X = Wechseln     S = Los!", 0)
        return

    draw_piste()

    if state == "game":
        draw_finish_line()
        for h in hindernisse:
            draw_hindernis(h)
        for h in hindernisse_bewegend:
            draw_bewegendes_hindernis(h)
        for b in bretter:
            sy = b[1] - kamera_y
            if -20 <= sy <= HEIGHT + 20:
                draw_brett(b[0], b[1])
        for s in sterne:
            sy = s[1] - kamera_y
            if -20 <= sy <= HEIGHT + 20:
                draw_star(s[0], s[1])
        draw_player(spieler_x, spieler_y)
        draw_schneeflocken()
        draw_hud()
        if boost_timer > 0:
            draw_center_text(HEIGHT - 12, "BOOST!", 10)
        if slow_timer > 0:
            draw_center_text(HEIGHT - 22, "LANGSAM!", 9)

    elif state == "crash":
        draw_crash_sprite(spieler_x, spieler_y)
        draw_schneeflocken()
        if crash_timer > 20:
            pyxel.rect(0, 0, WIDTH, HEIGHT, 8)
            pyxel.rect(2, 2, WIDTH - 4, HEIGHT - 4, 7)
            draw_crash_sprite(spieler_x, spieler_y)
        draw_center_text(90, "CRASH!", 8)
        draw_center_text(102, f"Score: {score}", 0)

    elif state == "level_end":
        draw_schneeflocken()
        draw_center_text(50,  "LEVEL COMPLETE!", 11)
        draw_center_text(65,  f"Score: {score}", 0)
        draw_center_text(77,  f"Highscore: {high_score}", 5)
        draw_center_text(89,  f"Bonus: +{level * 50}", 10)
        draw_center_text(101, f"Sterne: {sterne_gesammelt}", 10)
        if level < 4:
            draw_center_text(118, "Press S for next level", 0)
            draw_center_text(130, f"Naechstes: Level {level + 1}", 7)
        else:
            draw_center_text(118, "Press S for FINALE!", 8)

    elif state == "win":
        draw_schneeflocken()
        draw_center_text(50,  "DU HAST GEWONNEN!", 10)
        draw_center_text(65,  "Alle 4 Level geschafft!", 11)
        draw_center_text(80,  f"Finalscore: {score}", 7)
        draw_center_text(92,  f"Highscore:  {high_score}", 10)
        draw_center_text(110, "Press S to restart", 0)

    elif state == "gameover":
        draw_schneeflocken()
        draw_center_text(55,  "GAME OVER", 8)
        draw_center_text(70,  f"Score: {score}", 0)
        draw_center_text(82,  f"Highscore: {high_score}", 5)
        draw_center_text(96,  f"Sterne: {sterne_gesammelt}", 5)
        draw_center_text(110, "Press S to restart", 0)


init_schneeflocken()
init_zuschauer()
init_kurven()
init_buesche()
pyxel.run(update, draw)