-- Fonctions
function commandes_p1()
	if pad:down() or pad:l() then
		yp1=yp1+3
		if t==1 and side=="right" then
			alea=math.random(2)
			acc=acc+1+alea/10
		end
	end
	if pad:up() then
		yp1=yp1-3
		if t==1 and side=="right" then
			alea=math.random(2)
			acc=acc-1-alea/10
		end
	end
end

function b_pos()
	if side=="left" then
		xb=xb-v_b
		yb=yb+acc
	end
	if side=="right" then
		xb=xb+v_b
		yb=yb+acc
	end
	if side=="stop" then
		screen:print(60,40,"APPUYER SUR 'start' POUR LANCER LA BILLE",blanc)
		screen:print(60,55,"Rebonds:"..rebonds,blanc)
		
		if go_to==1 then
			screen:print(227,142,"<--",blanc)
			if pad:start() then
				side="left"
				rebonds=0
			end
		end
		if go_to==2 then
			screen:print(232,142,"-->",blanc)			
			if pad:start() then
				side="right"
				rebonds=0
			end
		end
	end
end

function edge()
	if yb<3 or yb>265 then
		acc=-acc
	end
end

function bille()
	if xb<20 and yb>yp1 and yb<(yp1+71) and side=="left" and xb>10 then
		t=1
		side="right"
		rebonds=rebonds+1
		rebonds_t=rebonds_t+1
	end
	if xb>454 and yb>yp2 and yb<(yp2+71) and side=="right" and xb<464 then
		t=1
		side="left"
		rebonds=rebonds+1
		rebonds_t=rebonds_t+1
	end
	if xb<10 or xb>470 then
		if xb>470 then
			score_j1=score_j1+1
			go_to=2
		else
			score_j2=score_j2+1
			go_to=1
		end
			xb=238
			yb=134
			acc=0
			side="stop"
	end
end

screen.waitVblankStart(8) -- On attend un tout petit peu
-- Boucle principale
while true do
	screen:clear()
	pad=Controls.read()
	t=0	
	screen:fillRect(21,0,438,272,terrain) -- Dessin du terrain.
	screen:fillRect(20,136,440,1,grisf)
	screen:fillRect(239,0,1,480,gris)
	screen:fillRect(19,0,1,272,gris)
	screen:fillRect(460,0,1,272,gris)
	screen:fillRect(20,0,440,2,gris)
	screen:fillRect(20,270,440,2,gris)

	screen:fillRect(8,yp1,12,70,joueur1) --J1
	screen:fillRect(460,yp2,12,70,joueur2) --J2
	screen:fillRect(xb,yb,5,5,cbille) -- Bille
	
	screen:print(160,5,title_game,gris)
	screen:print(240,261,"Score : J1="..score_j1.."     J2="..score_j2,blanc)
	screen:print(30,260,"Rebonds:"..rebonds,blanc)
	screen:print(30,250,"Rebonds total:"..rebonds_t,grisf)
	screen:print(200,250,xb.."-"..yp1.."-"..yp2,grisf)
	screen:print(380,250,"vb:"..v_b,grisf)
	screen:print(150,260,"Acc="..acc,blanc)
	edge()
	b_pos()
	bille()
	commandes_p1()
	player2()
	
	if pad:start() and pad:select()  then
		side=nil
		terrain=nil
		joueur1=nil
		joueur2=nil
		dofile("script.lua")
	end
	if pad:select() and pad:triangle() then
		v_b=v_b+0.5
	end
	if pad:select() and pad:square() then
		v_b=v_b-0.5
	end
     if pad:select() then
	 System.message("Merci d'avoir jouer",0)
		dofile("./scripts/menu.lua")
	end

	screen.waitVblankStart()
	screen:flip()
end
-- By Fabien ;)