from Tkinter import *
import random
from math import sqrt

def restart():
	global cx, cy
	global dx, dy
	cx = 10
	cy = random.randint(0, 600)
	dx = random.randint(5, 10)
	dy = random.randint(0, 10)
	w.coords(ball, cx, cy, cx+10, cy+10)
	w.after(30, move_ball)

def move_mitt(event):
	global mittx
	global mitty
	global w
	global mitt
	
	if event.char=="j":
		mitty += 10
	elif event.char=="k":
		mitty -= 10
	w.coords(mitt, mittx, mitty, mittx+30, mitty+30)
	

def move_ball():
	global ball
	global w
	global cx
	global cy
	global dx
	global dy
	global mittx, mitty
	global scores
	global computer_score
	global player_score
	
	cx = cx+dx
	cy = cy+dy
	w.coords(ball, cx, cy, cx+10, cy+10)
	if ((cy<10) or (cy>590)):
		dy = -dy
	
	# computer wins
	if (cx > 790):
		computer_score += 1
		scores.configure(text="Computer " + str(computer_score) + ": Player " + str(player_score))
		w.after(1000, restart)
	# player wins
	elif (sqrt((mittx-cx+10)*(mittx-cx+10)+(mitty-cy+10)*(mitty-cy+10))<=15):
		w.coords(ball, mittx, mitty, mittx+10, mitty+10)
		player_score += 1
		scores.configure(text = "Computer " + str(computer_score) + ": Player " + str(player_score))
		w.after(1000, restart)
	else:
		w.after(30, move_ball)
			


#start the script here
root = Tk()
w = Canvas(root, width=800, height=600)
w.grid(column=0,row=0)

scores = Label(root, text="Computer 0: Player 0")
scores.grid(column=0,row=1)
computer_score = 0
player_score = 0

mittx = 760
mitty = 300
mitt = w.create_oval(mittx, mitty, mittx+30, mitty+30, fill="red")
root.bind("j", move_mitt)
root.bind("k", move_mitt)

ball = w.create_oval(0,0,1,1, fill="blue")
restart()

# w.after(100, move_ball)
w.mainloop()