import pyxel

WIDTH, HEIGHT = 144, 96
PADDLE_H = 18
BALL_SPEED = 2

p1_y = p2_y = HEIGHT // 2 - PADDLE_H // 2
ball_x, ball_y = WIDTH // 2, HEIGHT // 2
ball_dx, ball_dy = BALL_SPEED, BALL_SPEED
score1 = score2 = 0
game_over = False
FRAME_RATE = 2

def update():
    global p1_y, p2_y, ball_x, ball_y, ball_dx, ball_dy, score1, score2, game_over

    if game_over:
        if pyxel.btnp(pyxel.KEY_R):
            reset_game()
        return

    # Contrôles
    if pyxel.btn(pyxel.KEY_S): p1_y -= 2
    if pyxel.btn(pyxel.KEY_W): p1_y += 2
    if pyxel.btn(pyxel.KEY_UP): p2_y -= 2
    if pyxel.btn(pyxel.KEY_DOWN): p2_y += 2

    p1_y = max(0, min(HEIGHT - PADDLE_H, p1_y))
    p2_y = max(0, min(HEIGHT - PADDLE_H, p2_y))

    if (pyxel.frame_count % FRAME_RATE == 1):
        # Balle
        ball_x += ball_dx
        ball_y += ball_dy
    
        if ball_y <= 0 or ball_y >= HEIGHT - 2:
            ball_dy *= -1
    
        if ball_x <= 6 and p1_y <= ball_y <= p1_y + PADDLE_H:
            ball_dx *= -1
        if ball_x >= WIDTH - 11 and p2_y <= ball_y <= p2_y + PADDLE_H:
            ball_dx *= -1
    
        if ball_x < 0:
            score2 += 1
            check_win()
            reset_ball()
        elif ball_x > WIDTH:
            score1 += 1
            check_win()
            reset_ball()

def check_win():
    global game_over
    if score1 >= 10 or score2 >= 10:
        game_over = True

def reset_ball():
    global ball_x, ball_y, ball_dx
    ball_x, ball_y = WIDTH // 2, HEIGHT // 2
    ball_dx *= 1

def reset_game():
    global score1, score2, game_over, ball_dx
    score1 = score2 = 0
    ball_dx = BALL_SPEED
    reset_ball()
    game_over = False

def draw():
    global LEVEL
    pyxel.cls(0)
    pyxel.bltm(0,0,0,0,0,144,96,0)
    #pyxel.rect(1, p1_y, 3, PADDLE_H, 4)
    pyxel.blt(1, p1_y, 1, 0, 0 ,3 ,18 ,0)
    #pyxel.rect(WIDTH - 4, p2_y, 3, PADDLE_H, 4)
    pyxel.blt(WIDTH - 4, p2_y, 1, 0, 0 ,3 ,18 ,0)
    #pyxel.circ(ball_x, ball_y, 2, 14)
    # dessiner un sprite
    pyxel.blt(ball_x, ball_y, 0, 0, 0 ,11 ,11 ,0)
    pyxel.text(10, 5, f"{score1}", 10)
   
    if game_over:
        winner = "1" if score1 >= 10 else "2"
        winner_text = f"Joueur {winner} gagne !"
        restart_text = "Appuie sur R pour recommencer"
        
        # Calcul de la position X pour centrer le texte
        winner_x = (WIDTH - len(winner_text) * 4) // 2
        restart_x = (WIDTH - len(restart_text) * 4) // 2

        pyxel.text(winner_x, HEIGHT // 2 - 10, winner_text, 8)  # Centré pour le gagnant
        pyxel.text(restart_x, HEIGHT // 2 + 10, restart_text, 14)  # Centré pour le message "Recommencer"

pyxel.init(WIDTH, HEIGHT, title="Pong 2 joueurs - Fin à 10 pts")
pyxel.load("res.pyxres")
pyxel.run(update, draw)