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

rDisk = 100
rBall = 8
#tol = 0.5

def bouncyBallMovie(directory):
	#os.mkdir(directory)
	movie = makeMovie()
	print "The radius of the ball is %d" % rBall
	h = 650 #input("Enter height of the box (300..1000): ")
	centreY = h / 2
	w = 650 #input("Enter width of the box (300..1000): ")
	centreX = w / 2
	canvas = makeEmptyPicture(w, h)
	x = 100 #input("Enter initial x-position of the ball (inside the box): ")
	y = 100 #input("Enter initial y-position of the ball (inside the box): ")
	vx = input("Enter horizontal velocity (0..5): ")
	vy = input("Enter vertical velocity (0..5): ")
	vabs = sqrt(vx**2 + vy**2)
	#assert(vabs <= rBall), "The ball speed is too high, sprurious jerks are possible"
	frame = 1
	while frame <= 250:
		setAllPixelsToAColor(canvas,white)
		addOvalFilled(canvas,centreX - rDisk,centreY - rDisk,2*rDisk,2*rDisk,blue)
		if (x <= 1 or x >= w - 2*rBall): #horizontal rebound
			vx = -vx
		if (y <= 1 or y >= h - 2*rBall ): #vertical rebound
			vy = -vy
		# rebound at the central disk border
		if (sqrt((x+rBall-centreX)**2 + (y+rBall-centreY)**2) < rDisk):
			nx = (x+rBall-centreX) / rDisk
			ny = (y+rBall-centreY) / rDisk
			vn = nx * vx + ny * vy
			vx = int(vx - 2*vn*nx)
			vy = int(vy - 2*vn*ny)
		# advance ball position
		x += vx
		y += vy
		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
		addOvalFilled(canvas,x,y,2*rBall,2*rBall,red)
		#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)
	
	

