
:-object wasp4 : [bcilib].

var url = './soccer/soccer2b.wrl'.

var timelimit = 500.


main :-
	text_area(Browser),
	set_output(Browser),

	format('Load the game ...~n'),
	loadURL(url),

	format('the game will start in 5 seconds,~n'),
	format('note that the total playing time period is ~w seconds,~n', [timelimit]),
	delay(5000),
	format('the game startup,~n'),
	play_ball(me, ball).


play_ball(Agent, Ball) :-
	-- timelimit,
	timelimit > 0, !,
	format('time left: ~w seconds~n', [timelimit]),
	delay(800),
	look_at_ball(goalKeeper1,Ball),
	near_ball_then_kick(Agent, Ball),
	play_ball(Agent, Ball).

play_ball(_, _).


near_ball_then_kick(Agent, Ball):-
	getViewpointPositionEx(Agent,X,_Y,Z),
	getPosition(Ball,X1,Y1,Z1),
	Xdif is X1-X,
	Zdif is Z1-Z,
	Dist is sqrt(Xdif*Xdif + Zdif*Zdif),
	Dist < 5, !,
	X2 is Xdif*3,
	Z2 is Zdif*3,
	X3 is X2 + X1,
	Z3 is Z2 + Z1,
	setPosition(Ball,X3,Y1,Z3),
	checkBallPosition(Ball,X3,Y1,Z3).

near_ball_then_kick(_, _).



checkBallPosition(Ball, X, Y, Z):-
	getPosition(goalKeeper1,X1,_Y1,Z1),
	Xdif is X-X1,
	Zdif is Z-Z1,
	Dist is sqrt(Xdif*Xdif + Zdif*Zdif),
	Dist < 4, !,
	X2 is X - 8,
	format('The goalkeeper kicks the ball back~n'),
	setPosition(Ball,X2,Y,Z).

checkBallPosition(_,_,_,_).
	
look_at_ball(Sportman,Ball):-
	getPosition(Sportman,X,_,Z),
	getPosition(Ball, X1,_,Z1),
	Xdif is X-X1,
	Zdif is Z1-Z,
	Xdif =\= 0.0,
	R is atan(Zdif/Xdif) - sign(Xdif)*1.571,
	setRotation(Sportman,0.0, 1.0, 0.0, R).
	
look_at_ball(Sportman,Ball):-
	getPosition(Sportman,_X,_,Z),
	getPosition(Ball, _X1,_,Z1),
	Z1 < Z,
	setRotation(Sportman,0.0, 1.0, 0.0, 3.14).

look_at_ball(Sportman,Ball):-
	getPosition(Sportman,_X,_,Z),
	getPosition(Ball, _X1,_,Z1),
	Z1 > Z,
	setRotation(Sportman,0.0, 1.0, 0.0, 0.0).		
	
look_at_ball(_,_).

getViewpointPositionEx(_,X,Y,Z) :- getSFVec3f(proxSensor,position,X,Y,Z).
getViewpointOrientationEx(_,X,Y,Z,R):- getSFRotation(proxSensor,orientation,X,Y,Z,R).


:-end_object wasp4.

