import turtle
import time
import random
import math
import os


# Play a sound: .wav files on Windows, .mp3 files with afplay on a Mac
def play_sound(name):
    if os.name == 'nt':
        import winsound
        winsound.PlaySound(name + '.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
    else:
        os.system('afplay ' + name + '.mp3&')


# Setup the Adventure
def setup_adventure():
    turtle.setup(650, 650)
    wn = turtle.Screen()
    wn.bgcolor("purple")
    wn.bgpic('kbgame-bg.gif')
    wn.tracer(3)
    time.sleep(2)

# Setup the Game World
def create_game_world():
    mypen = turtle.Turtle()
    mypen.color("white")
    mypen.penup()
    mypen.setposition(-300, -300)
    mypen.pendown()
    mypen.pensize(3)
    for side in range(4):
        mypen.forward(600)
        mypen.left(90)
    mypen.hideturtle()
    time.sleep(2)

# Create the Players
def create_players_and_opponents():
    player = turtle.Turtle()
    player.color("green")
    player.shape("turtle")
    player.penup()
    player.speed(0)

    comp = turtle.Turtle()
    comp.color('hotpink')
    comp.shape('turtle')
    comp.penup()
    comp.setposition(random.randint(-290, 290), random.randint(-290, 290))
    time.sleep(2)
    return player, comp

# Setup the Scoring
def manage_scores_and_food():
    mypen2 = turtle.Turtle()
    mypen2.color("red")
    mypen2.hideturtle()

    score = 0
    comp_score = 0

    maxFoods = 6
    foods = []
    for count in range(maxFoods):
        foods.append(turtle.Turtle())
        foods[count].color("orange")
        foods[count].shape("circle")
        foods[count].shapesize(0.5)
        foods[count].penup()
        foods[count].speed(0)
        foods[count].setposition(random.randint(-290, 290), random.randint(-290, 290))
    time.sleep(2)
    return mypen2, score, comp_score, foods

# Adding the Controls
def define_controls_and_collisions(player):
    speed = 1

    def turnleft():
        player.left(30)

    def turnright():
        player.right(30)

    def increase_speed():
        nonlocal speed
        speed += 1

    def get_speed():
        return speed

    def is_collision(t1, t2):
        d = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
        return d < 20

    turtle.listen()
    turtle.onkey(turnleft, "Left")
    turtle.onkey(turnright, "Right")
    turtle.onkey(increase_speed, "Up")
    time.sleep(2)
    return get_speed, is_collision

#Creating the Game Loop
def main_game_loop(player, comp, get_speed, is_collision, score, comp_score, foods):
    gametime = 0
    timeout = time.time() + 10 * 6
    mypen = turtle.Turtle()
    mypen2 = turtle.Turtle()
   

    while True:
        gametime = 0
        if gametime == 6 or time.time() > timeout:
            break
        gametime = gametime - 1

        player.forward(get_speed())
        comp.forward(12)

        if player.xcor() > 290 or player.xcor() < -290:
            player.right(180)
            play_sound('bounce')

        if player.ycor() > 290 or player.ycor() < -290:
            player.right(180)
            play_sound('bounce')

        if comp.xcor() > 290 or comp.xcor() < -290:
            comp.right(180)
            play_sound('bounce')

        if comp.ycor() > 290 or comp.ycor() < -290:
            comp.right(180)
            play_sound('bounce')

        for count in range(len(foods)):
            foods[count].forward(3)

            if foods[count].xcor() > 290 or foods[count].xcor() < -290:
                foods[count].right(180)
                play_sound('bounce')

            if foods[count].ycor() > 290 or foods[count].ycor() < -290:
                foods[count].right(180)
                play_sound('bounce')

            if is_collision(player, foods[count]):
                foods[count].setposition(random.randint(-290, 290), random.randint(-290, 290))
                foods[count].right(random.randint(0, 360))
                play_sound('chomp')
                score += 1
                mypen.undo()
                mypen.penup()
                mypen.hideturtle()
                mypen.setposition(-290, 310)
                scorestring = "Score: %s" % score
                mypen.write(scorestring, False, align='left', font=('Arial', 14, 'normal'))

            if is_collision(comp, foods[count]):
                foods[count].setposition(random.randint(-290, 290), random.randint(-290, 290))
                foods[count].right(random.randint(0, 360))
                play_sound('chomp')
                comp_score += 1
                mypen2.undo()
                mypen2.penup()
                mypen2.hideturtle()
                mypen2.setposition(200, 305)
                scorestring = "Score: %s" % comp_score
                mypen2.write(scorestring, False, align='left', font=('Arial', 14, 'normal'))

    if int(score) > int(comp_score):
        mypen.setposition(0, 0)
        mypen.color("yellow")
        mypen.write("Game Over: You WIN", False, align="center", font=("Arial", 28, "normal"))
    elif int(score) == int(comp_score):
        mypen.setposition(0, 0)
        mypen.color("yellow")
        mypen.write("Game Over: It's a DRAW", False, align="center", font=("Arial", 28, "normal"))
    else:
        mypen.setposition(0, 0)
        mypen.color("yellow")
        mypen.write("Game Over: You LOSE", False, align="center", font=("Arial", 28, "normal"))

    delay = input("Press Enter to finish.")


# Start the Game
setup_adventure()
create_game_world()
player, comp = create_players_and_opponents()
mypen2, score, comp_score, foods = manage_scores_and_food()
get_speed, is_collision = define_controls_and_collisions(player)
main_game_loop(player, comp, get_speed, is_collision, score, comp_score, foods)
