package version9_2.environment;

public class Prey {

	
	private Environment env;

	private float px;								// position (x,y) in grid cell unit
	private float py;
	
	private float rz;								// orientation rz in radius

	public static float speed=0.7f;
	
	public Prey(Environment e){
		env=e;
	}
	
	// activate the robot
	public void move(){
		
		////////////////////////////////////////////////////////////////////
		// movements
		double orientation=rz;
		double movement=0.099*speed;
		
		px+=  movement*Math.cos(orientation);
		py+=  movement*Math.sin(orientation);
		

		
		////////////////////////////////////////////////////////////////////
		// collisions (reverse direction)
		
		int i=Math.round(px);
		int j=Math.round(py);
		
		
		for (int w=-1;w<=1;w++){
			for (int h=-1;h<=1;h++){
				if (i!=0 && j!=0){
					
					if (i+w>=0 && i+w<env.m_w && j+h>=0 && j+h<env.m_h){
						if (!env.isWalkthroughable(i+w,j+h)){
							// case lateral block
							if (w==0){
								if ((j+h - py)*h<1){
									py-= h*(1 - h*(j+h - py));
									rz+=Math.PI;
								}
							}
							else{ 
								if (h==0){
									if ((i+w - px)*w<1){
										px-= w*(1 - w*(i+w - px));
										rz+=Math.PI;
									}
								}
								else{
									// case corner block
									float x2= (i+w)-w*0.5f;
									float y2= (j+h)-h*0.5f;
									
									double dist=Math.sqrt((px-x2)*(px-x2)+(py-y2)*(py-y2));

									if (dist<0.5){
										rz+=Math.PI;
										px+= (px-x2) * (0.5-(dist-0.05)) /0.5;
										py+= (py-y2) * (0.5-(dist-0.05)) /0.5;
									}
								}
							}
						}
					}
					
				}
			}
		}
		
		if (rz<0) rz+=2*Math.PI;
		if (rz>=2*Math.PI) rz-=2*Math.PI;
	}
	
	
	///////////////////////////////////////////////////////////////////////////////
	
	public float getpx(){ return px;}
	public float getpy(){ return py;}
	public float getrz(){ return rz;}
	
	public void setPosition(float x, float y){
		px=x;
		py=y;
	}
	
	public void setPosition(float x, float y, float theta){
		px=x;
		py=y;
		rz=theta;
	}
	
}
