from Tkinter import *
import random
from math import sqrt

def restart():
    global gameCanvas
    global BALL_SIZE
    global WAIT_TIME
    
    x = 0
    dx = 4
    y=random.randint(0,gameCanvas.winfo_height()-BALL_SIZE)
    dy=random.randint(-5,5)
    gameCanvas.after(WAIT_TIME*10, move);
    return x, dx, y, dy
	
def move():
    global ball
    global gameCanvas
    global x, y, dx, dy
    global BALL_SIZE
    global WAIT_TIME
    global mittx, mitty
    global MITT_SIZE
    global player_score
    global computer_score
    global scores
	
    x = x+dx
    y = y+dy
    
    # check if we've gone off the screen
    if y<0:
        y = 0
        dy = -dy
    elif y>gameCanvas.winfo_height()-BALL_SIZE:
        y = gameCanvas.winfo_height()-BALL_SIZE
        dy = -dy
    # draw the ball
    gameCanvas.coords(ball, x, y, x+BALL_SIZE, y+BALL_SIZE)
    
    # check if we've caught the ball
    ball_centre_x = x + BALL_SIZE/2.0
    ball_centre_y = y + BALL_SIZE/2.0
    mitt_centre_x = mittx + MITT_SIZE/2.0
    mitt_centre_y = mitty + MITT_SIZE/2.0
    distance = sqrt((ball_centre_x-mitt_centre_x)**2+
                    (ball_centre_y-mitt_centre_y)**2)
    # did we catch the ball?
    if distance<=(BALL_SIZE+MITT_SIZE)/2.0:
        player_score += 1
        scores.configure(text="Computer " + str(computer_score) + 
                         ": Player " + str(player_score))
        x, dx, y, dy = restart()
    # or have we totally missed it
    elif x>gameCanvas.winfo_width():
        computer_score += 1
        scores.configure(text="Computer " + str(computer_score) + 
                         ": Player " + str(player_score))
        x, dx, y, dy = restart()
    # or hasn't it got to us yet
    else:
        # make sure we're called again
        gameCanvas.after(WAIT_TIME, move)

def move_mitt(event):
    global mitt
    global gameCanvas
    global mittx, mitty

    if event.char=="j":
        mitty = mitty+10
    elif event.char=="k":
        mitty = mitty-10
    gameCanvas.coords(mitt, mittx, mitty, mittx+MITT_SIZE, mitty+MITT_SIZE)


MITT_SIZE = 20
BALL_SIZE = 10
WAIT_TIME = 100

root = Tk()
gameCanvas = Canvas(root, width=400, height=400)
gameCanvas.grid(column=0,row=0)
scores = Label(root, text="Computer 0: Player 0")
scores.grid(column=0,row=1)
gameCanvas.wait_visibility()

player_score=0
computer_score=0
x, dx, y, dy = restart()
ball = gameCanvas.create_oval(x, y, x+BALL_SIZE, y+BALL_SIZE, fill="blue")

# gameCanvas.after(WAIT_TIME, move)
mittx = gameCanvas.winfo_width()-30
mitty = gameCanvas.winfo_height()/2
mitt = gameCanvas.create_oval(mittx, mitty,
                              mittx+MITT_SIZE, mitty+MITT_SIZE, 
                              fill="red")

root.bind("k", move_mitt)
root.bind("j", move_mitt)

root.mainloop()
