"""
LESSON 2 - Two-Player Maze Race!
=================================
Goal: learn keyboard input (turtle.onkeypress) and collision detection.

Player 1 (BLUE)  : arrow keys  (Up / Down / Left / Right)
Player 2 (RED)   : W A S D keys

Both players start in the maze (bottom corners) and race to the gold
checkered square at the top. If you steer into a black wall... you crash
and you're out! First to reach the gold square wins.

HOW COLLISION DETECTION WORKS HERE (the key idea for this lesson):
We open the SAME background image with PIL (a Python image library) and,
every time a player tries to move, we check the color of the pixel at
their new position. If that pixel is the dark "wall" color -> crash!
This is a simple, very visual way to teach "collision detection" because
kids can literally see the walls they must avoid touching.
"""

import turtle
from PIL import Image

# ---------- CONFIG (matches gen_maze_bg.py) ----------
WIDTH, HEIGHT = 800, 600
STEP = 8                     # how many pixels each key press moves a player
WALL_BRIGHTNESS_THRESHOLD = 90   # pixel is a "wall" if it's this dark or darker
FINISH_ZONE = (20, 280, 40)      # (x, y, half-size) in turtle coordinates

bg_image = Image.open("maze_background.png").convert("RGB")
pixels = bg_image.load()

def is_wall(x, y):
    """Convert turtle coords -> image pixel coords, then check brightness."""
    px = int(x + WIDTH / 2)
    py = int(HEIGHT / 2 - y)
    if px < 0 or px >= WIDTH or py < 0 or py >= HEIGHT:
        return True  # off-screen counts as a wall
    r, g, b = pixels[px, py]
    return (r + g + b) / 3 <= WALL_BRIGHTNESS_THRESHOLD

def reached_finish(x, y):
    fx, fy, half = FINISH_ZONE
    return abs(x - fx) <= half and abs(y - fy) <= half

# ---------- SCREEN SETUP ----------
screen = turtle.Screen()
screen.setup(width=WIDTH, height=HEIGHT)
screen.bgpic("maze_background.png")
screen.title("Lesson 2: Two-Player Maze Race!")
screen.tracer(0)  # we'll update the screen manually for smooth control

game_over = False

# ---------- PLAYER 1 (blue, arrow keys) ----------
p1 = turtle.Turtle()
p1.shape("circle")
p1.shapesize(0.7)
p1.color("#2870e6")
p1.penup()
p1.goto(-380, -280)

# ---------- PLAYER 2 (red, WASD) ----------
p2 = turtle.Turtle()
p2.shape("circle")
p2.shapesize(0.7)
p2.color("#dc3c3c")
p2.penup()
p2.goto(380, -280)

status = turtle.Turtle()
status.hideturtle()
status.penup()
status.goto(0, -290)
status.color("black")

def show_status(msg):
    status.clear()
    status.write(msg, align="center", font=("Arial", 14, "bold"))

def try_move(player, dx, dy, name):
    global game_over
    if game_over:
        return
    new_x = player.xcor() + dx
    new_y = player.ycor() + dy

    if is_wall(new_x, new_y):
        show_status(f"{name} crashed into a wall! Game over.")
        player.color("black")
        game_over = True
        screen.update()
        return

    player.goto(new_x, new_y)

    if reached_finish(new_x, new_y):
        show_status(f"{name} reached the finish first! {name} wins!")
        game_over = True

    screen.update()

# ---------- KEYBOARD INPUT ----------
# Each function moves ONE player by STEP pixels in ONE direction.
# turtle.onkeypress + screen.listen() is how we "read keyboard input".
def p1_up():    try_move(p1, 0, STEP, "Player 1")
def p1_down():  try_move(p1, 0, -STEP, "Player 1")
def p1_left():  try_move(p1, -STEP, 0, "Player 1")
def p1_right(): try_move(p1, STEP, 0, "Player 1")

def p2_up():    try_move(p2, 0, STEP, "Player 2")
def p2_down():  try_move(p2, 0, -STEP, "Player 2")
def p2_left():  try_move(p2, -STEP, 0, "Player 2")
def p2_right(): try_move(p2, STEP, 0, "Player 2")

screen.listen()
screen.onkeypress(p1_up, "Up")
screen.onkeypress(p1_down, "Down")
screen.onkeypress(p1_left, "Left")
screen.onkeypress(p1_right, "Right")

screen.onkeypress(p2_up, "w")
screen.onkeypress(p2_down, "s")
screen.onkeypress(p2_left, "a")
screen.onkeypress(p2_right, "d")

show_status("Player 1: Arrow Keys   |   Player 2: W A S D   |   Reach the gold square!")
screen.update()

screen.mainloop()
