from gasp import *

COMPUTER_WINS = 1
PLAYER_WINS = 0
QUIT = -1
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BALL_SIZE = 10
MITT_SIZE = 20
BALL_SPEED = 4
MITT_SPEED = 5

def distance(x1, y1, x2, y2):
    return ((x2 - x1)**2 + (y2 - y1)**2)**0.5


def play_round():
    ball_x = 10
    ball_y = random_between(20, SCREEN_HEIGHT/2)
    ball = Circle((ball_x, ball_y), BALL_SIZE, filled=True)
    dx = BALL_SPEED
    dy = random_between(-BALL_SPEED, BALL_SPEED) 

    mitt_x = SCREEN_WIDTH - MITT_SIZE
    mitt_y = random_between(20, SCREEN_HEIGHT/2)
    mitt = Circle((mitt_x, mitt_y), MITT_SIZE)

    while True:
        if (ball_y >= SCREEN_HEIGHT-BALL_SIZE) or (ball_y <= BALL_SIZE):
            dy *= -1
        ball_x += dx
        ball_y += dy
        move_to(ball, (ball_x, ball_y))

        if key_pressed('k') and mitt_y <= SCREEN_HEIGHT-MITT_SIZE:
            mitt_y += MITT_SPEED
        elif key_pressed('j') and mitt_y >= MITT_SIZE:
            mitt_y -= MITT_SPEED

        move_to(mitt, (mitt_x, mitt_y))

        if key_pressed('escape'):
            return QUIT
        elif ball_x >= SCREEN_WIDTH-BALL_SIZE:
            remove_from_screen(ball)
            remove_from_screen(mitt)
            return COMPUTER_WINS 
        elif distance(ball_x, ball_y, mitt_x, mitt_y) <= BALL_SIZE+MITT_SIZE:
            remove_from_screen(ball)
            remove_from_screen(mitt)
            return PLAYER_WINS

        update_when('next_tick')


def play_game():
    player_score = 0
    comp_score = 0

    while True:
        pmsg = Text("Player: %d Points" % player_score, (10, SCREEN_HEIGHT-30),
                    size=24)
        cmsg = Text("Computer: %d Points" % comp_score,
                    (SCREEN_WIDTH-200, SCREEN_HEIGHT-30), size=24)
        sleep(3)
        remove_from_screen(pmsg)
        remove_from_screen(cmsg)

        result = play_round()

        if result == PLAYER_WINS:
            player_score += 1
        elif result == COMPUTER_WINS:
            comp_score += 1
        else:
            return QUIT 

        if player_score == 5:
            return PLAYER_WINS
        elif comp_score == 5:
            return COMPUTER_WINS 


begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT, title="Catch",
               background=color.YELLOW)
set_speed(320)

result = play_game()

if result == PLAYER_WINS:
    Text("Player Wins!", (SCREEN_WIDTH/2-60, SCREEN_HEIGHT/2), size=32)
elif result == COMPUTER_WINS:
    Text("Computer Wins!", (SCREEN_WIDTH/2-60, SCREEN_HEIGHT/2), size=32)

sleep(4)

end_graphics()
