#include "iface.h"
#include <ctime>

namespace voxel
{
	ZPlayer::ZPlayer(int _px, int _py, uchar _r, uchar _g, uchar _b)
	{
		pos_x = _px;
		pos_y = _py;
		money = 100;
		hp = 100;
		r = _r; g = _g; b = _b;

		alpha = beta = 0;
		power = 50;
		X = Y = FIELD_N/2;

		weapon = 0;
	}

	void ZPlayer::do_ai( T your_pos, T enemy, T wind )
	{
		//weapon = 0;

		int cost[] = { 0, 50, 80, 120, 250, 500 };

		if (money < 50)
		{
			// пропускаем ход
			weapon = 0;
			return;
		}

		int best_a, best_b, best_p, best_x, best_y, best_w;
		float dist = 1000000.f;

		static float pi = acos(-1.f);

		for (int zz = 0; zz < 1000; zz++)
		{
			// 1000 раз рандомно че нить выбираем
			int w = rand()%5+1;
			while (money < cost[w]) w = rand()%5+1;
			int a = rand()%360;
			int b = rand()%161-80;
			int p = rand()%91+10;
			int x = rand()%FIELD_N;
			int y = rand()%FIELD_N;

			float min_dist = 1000000.f;
			// тупо моделируем
			if (w==1 || w==2 || w==3 || w==5)
			{
				T pos = your_pos;
				float aa = a*pi/180.f, bb = b*pi/180.f;
				T v = T( sin( aa )*cos( bb ), cos( aa )*cos( bb ), sin( bb ) );
				v.x *= p;
				v.y *= p;
				v.z *= p;

				if (w==5)
				{
					pos = T( x+a*5.f, y+b*5.f, FIELD_H*2.f );
					v = T( 0.f, 0.f, 0.f );
				}

				for (int ii = 0; ii < 100; ii++)
				{
					const float WIND_C = 5.f;
					const float G_C = 40.f;
					const float D_T = 0.1f;
					T F = T( wind.x*WIND_C, wind.y*WIND_C, - G_C );
					v.x += F.x*D_T;
					v.y += F.y*D_T;
					v.z += F.z*D_T;

					pos.x += v.x*D_T;
					pos.y += v.y*D_T;
					pos.z += v.z*D_T;

					float dx = pos.x-enemy.x, dy = pos.y-enemy.y, dz = pos.z-enemy.z;
					float dd = dx*dx + dy*dy + dz*dz;
					min_dist = std::min( min_dist, dd );

					if (pos.x < 0.f || pos.y < 0.f || pos.z < 0.f) break;
					if (pos.x > FIELD_N || pos.y > FIELD_N) break;
				}
			}
			else if (w==4)
			{
				T pos = your_pos;
				float aa = a*pi/180.f, bb = b*pi/180.f;
				T v = T( sin( aa )*cos( bb ), cos( aa )*cos( bb ), sin( bb ) );
				v.x *= 25.f;
				v.y *= 25.f;
				v.z *= 25.f;

				for (int ii=0; ii < 100; ii++)
				{
					const float D_T = 0.1f;
					pos.x += v.x*D_T;
					pos.y += v.y*D_T;
					pos.z += v.z*D_T;

					float dx = pos.x-enemy.x, dy = pos.y-enemy.y, dz = pos.z-enemy.z;
					float dd = dx*dx + dy*dy + dz*dz;
					min_dist = std::min( min_dist, dd );

					if (pos.x < 0.f || pos.y < 0.f || pos.z < 0.f) break;
					if (pos.x > FIELD_N || pos.y > FIELD_N) break;
				}
			}

			if (min_dist < dist)
			{
				dist = min_dist;
				best_a = a;
				best_b = b;
				best_p = p;
				best_x = x;
				best_y = y;
				best_w = w;
			}
		}

		weapon = best_w;
		alpha = best_a;
		beta = best_b;
		power = best_p;
		X = best_x;
		Y = best_y;
	}
};