#include "main.h"

#define ALIENS_BLUE_FRAME 19
#define ALIENS_PURPLE_FRAME_START 16

#define EXPLODE_ANIMATE_SPEED 3

void aliens_create_wave(alien* aliens, int num)
{
	int i;
	for(i=0; i < num; i++)
	{
		alien* a = &aliens[i];
		a->x = 240 + (i * 20);
		//a->y = rand() / (RAND_MAX / (160-16));
		a->y = i * 30;
		a->active = 1;
		a->speed = 1;
		a->explode = 0;

		a->sprite.sprite = sprite_alloc();
		a->sprite.bx = 2;		a->sprite.by = 2;
		a->sprite.bw = 12;	a->sprite.bh = 12;
		a->sprite.tile = (4*2) * ALIENS_BLUE_FRAME;
		a->sprite.a0 = COLOR_256 | SQUARE;
		a->sprite.a1 = SIZE_16;
	}
}

void aliens_draw(game* g)
{
	int i;
	for(i=0; i < g->num_aliens; i++)
	{
		alien* a = &g->aliens[i];
		if(a->active)
		{
			a->x -= a->speed;
			if(a->x <= -16) a->active = 0;
			a->sprite.x = a->x; a->sprite.y = a->y;
			DRAW_SPRITE(a->sprite);
		}
		if(a->explode)
		{
			a->sprite.x = a->x; a->sprite.y = a->y;
			a->sprite.tile = ((a->explode / EXPLODE_ANIMATE_SPEED) + EXPLOSION_FRAMES_START - 1) * (4*2);
			DRAW_SPRITE(a->sprite);
			
			a->explode++;
			if(a->explode > (EXPLOSION_FRAMES_NUM * EXPLODE_ANIMATE_SPEED))
			{
				a->explode = 0;
				sprite_free(a->sprite.sprite);
			}
		}
	}
}

/* macro for checking collision of bounding boxes */

#define BOUNDS_COLLIDE(minx1, miny1, w1, h1, minx2, miny2, w2, h2) \
 (((minx1 + w1) >= minx2) && (minx1 <= (minx2 + w2)) && \
	((miny1 + h1) >= miny2) && (miny1 <= (miny2 + h2)))

#define SPRITE_BOUNDS_COLLIDE(s1, s2) \
 (((s1.x + s1.bx + s1.bw) >= (s2.x + s2.bx)) && \
	((s1.x + s1.bx) <= (s2.x + s2.bx + s2.bw)) && \
  ((s1.y + s1.by + s1.bh) >= (s2.y + s2.by)) && \
	((s1.y + s1.by) <= (s2.y + s2.by + s2.bh)))
 
int collide_aliens_bullets_ship(game* g)
{
	int i;
	playership* ship = g->ship;

	/* iterate through the aliens */
	for(i=0; i < g->num_aliens; i++)
	{
		alien* a = &g->aliens[i];

		if(a->active)
		{
			/* check this alien against the ship */

			if(SPRITE_BOUNDS_COLLIDE(ship->sprite, a->sprite))
			{
				/* we're dead - return true */
				return(1);
			}
			
			/* check this alien against each bullet in turn */
			int bul;
			for(bul=0; bul < ship->num_bullets; bul++)
			{
				bullet* b = &ship->bullets[bul];
				if(b->active)
				{
					/* we have an active bullet and an active alien - see if they
					 * collide */
					
					/* check x and y bounds */
					if(SPRITE_BOUNDS_COLLIDE(b->sprite, a->sprite))
					{
						/* woo - the alien and bullet bounding boxes collide */

						/* we should do a per-pixel comparison of the sprite data to make
						 * sure the objects (as opposed to their bounding boxes) have
						 * collided - do this later :) */

						b->active = 0;
						a->active = 0;
						a->explode = 1;
						sprite_free(b->sprite.sprite);
						ship->score++;
					}
				}
			}
		}
	}
	return(0);
}

