import os
from string import zfill
#from math import sqrt, cos, sin

H = 650 #box height
W = 650 #box width
rBall = 12
#tol = 0.5

def advanceBall(vars):
	"""Advances ball position at one iteration
	returns new coordinates (4-tuple of coordinates and velocities)"""
	# unpacking the tuple into components
	x,y,vx,vy = vars
	#horizontal rebound
	if (x <= 1 or x >= W - 2*rBall): 
		vx = -vx
	#vertical rebound
	if (y <= 1 or y >= H - 2*rBall ): 
		vy = -vy
	# advance ball position
	x += vx
	y += vy
	#correction on going off the box
	if x < 1:
		x = 1
	elif x > W - 2*rBall:
		x = W - 2*rBall
	if y < 1:
		y = 1
	elif y > H - 2*rBall:
		y = H - 2*rBall
			
	return (x,y,vx,vy)

def twoBallMovie(directory,numFrames):
	#os.mkdir(directory)
	movie = makeMovie()
	print "The radius of the ball is %d" % rBall
	centreY = H / 2
	centreX = W / 2
	canvas = makeEmptyPicture(W, H)
	x = centreX
	y = centreY
	vx = input("Enter horizontal velocity (0..5): ")
	vy = input("Enter vertical velocity (0..5): ")
	v1 = input("Enter another velocity (as 2-tuple): ")
	# 4-tuple of coordinates and velocities
	var = (x,y,vx,vy)
	var1 = (x,y) + v1
	
	frame = 1
	while frame <= numFrames:
		setAllPixelsToAColor(canvas,black)
		#addOvalFilled(canvas,centreX - rDisk,centreY - rDisk,2*rDisk,2*rDisk,blue)
		var = advanceBall(var)
		var1 = advanceBall(var1)
		addOvalFilled(canvas,var[0],var[1],2*rBall,2*rBall,red)
		addOvalFilled(canvas,var1[0],var1[1],2*rBall,2*rBall,blue)
		#writing the frame to a file
		frnum = str(frame).zfill(3) #padding zeros on the left 
		#print frnum
		fname = directory + os.sep + frnum + ".jpg"
		writePictureTo(canvas,fname)
		
		# jes 3.0.6 does not have this function
		#addFrameToMovie(fname,movie)
		frame += 1
	
	return movie
	#openFrameSequencerTool(movie)
	#writeQuicktime(movie,16)
	
	

