from Tkinter import *
import random
from math import sqrt

def move():
	global ball
	global gameCanvas
	global x, y, dx, dy
	global BALL_SIZE
	global WAIT_TIME
	global mittx, mitty
	global MITT_SIZE
	
	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:
		print "Good Catch"
		x = 0
		y=random.randint(0,gameCanvas.winfo_height()-BALL_SIZE)
		dy=random.randint(-5,5)
		gameCanvas.after(WAIT_TIME*10, move)
	# or have we totally missed it
	elif x>gameCanvas.winfo_width():
		print "You missed"
		x = 0
		y=random.randint(0,gameCanvas.winfo_height()-BALL_SIZE)
		dy=random.randint(-5,5)
		gameCanvas.after(WAIT_TIME*10, move)
	# 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)
gameCanvas.wait_visibility()

x=0
y=random.randint(0,gameCanvas.winfo_height()-BALL_SIZE)
dx=8
dy=random.randint(-5,5)
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()