/*
 *    SPEED - by Shawn Hargreaves, 1999
 *
 *    Enemy control routines (attack waves).
 */

#include <allegro.h>

#include "speed.h"



/* info about someone nasty */
typedef struct BADGUY
{
   float x;
   float y;
   struct BADGUY *next;
} BADGUY;


static BADGUY *evildudes;

static int finished_counter;



/* creates a new swarm of badguys */
static void lay_attack_wave()
{
   BADGUY *b;
   int i;

   for (i=0; i<10; i++) {
      b = malloc(sizeof(BADGUY));
      b->x = (float)(rand() & 255) / 256.0;
      b->y = -(float)(rand() & 255) / 256.0;

      b->next = evildudes;
      evildudes = b;
   }

   finished_counter = 0;
}



/* initialises the badguy functions */
void init_badguys()
{
   evildudes = NULL;

   lay_attack_wave();
}



/* closes down the badguys module */
void shutdown_badguys()
{
   BADGUY *b;

   while (evildudes) {
      b = evildudes;
      evildudes = evildudes->next;
      free(b);
   }
}



/* updates the badguy position */
int update_badguys()
{
   BADGUY **p = &evildudes;
   BADGUY *b = evildudes;
   BADGUY *tmp;
   void *bullet;
   float x, y, d;
   int dead;

   while (b) {
      dead = FALSE;

      b->y += 0.0025;

      if (b->y >= 0.97) {
	 dead = TRUE;
      }
      else if (b->y > 0) {
	 bullet = get_first_bullet(&x, &y);

	 while (bullet) {
	    x = ABS(x - b->x);
	    y = ABS(y - b->y);

	    if (x < y)
	       d = y/2 + x;
	    else
	       d = x/2 + y;

	    if (d < 0.025) {
	       kill_bullet(bullet);
	       explode(b->x, b->y, 0);
	       dead = TRUE;
	       break;
	    }

	    bullet = get_next_bullet(bullet, &x, &y);
	 }
      }

      if (dead) {
	 *p = b->next;
	 tmp = b;
	 b = b->next;
	 free(tmp);
      }
      else {
	 p = &b->next;
	 b = b->next;
      }
   }

   if (!evildudes) {
      if (!finished_counter)
	 message("Wave Complete");

      finished_counter++;

      if (finished_counter > 64) {
	 lay_attack_wave();
	 return TRUE;
      }
   }

   return FALSE;
}



/* draws the badguys */
void draw_badguys(BITMAP *bmp, int r, int g, int b, int (*project)(float *f, int *i, int c))
{
   BADGUY *bad = evildudes;
   int c = makecol(r, g, b);
   float shape[12];
   int ishape[12];

   while (bad) {
      if (bad->y > 0) {
	 shape[0] = bad->x - 0.02;
	 shape[1] = bad->y + 0.01;

	 shape[2] = bad->x;
	 shape[3] = bad->y + 0.02;

	 shape[4] = bad->x + 0.02;
	 shape[5] = bad->y + 0.01;

	 shape[6] = bad->x + 0.01;
	 shape[7] = bad->y + 0.005;

	 shape[8] = bad->x;
	 shape[9] = bad->y - 0.015;

	 shape[10] = bad->x - 0.01;
	 shape[11] = bad->y + 0.005;

	 if (project(shape, ishape, 12))
	    polygon(bmp, 6, ishape, c);
      }

      bad = bad->next;
   }
}

