#include <allegro.h>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <cstdio>
#include "classes.h"
using namespace std;

player p;
vector<bullet> bullets;
BITMAP* buffer;

int maxBul;

void addBullets()
{
    while (bullets.size()<maxBul)
    {
        bullets.push_back(bullet(rand()%40+600, rand()%480));
    }
}
void init();
bool checkwin()
{
    for (int c = 0; c<bullets.size(); c++)
    {
        if (bullets[c].x<0)
        {
            bullets.erase(bullets.begin()+c);
            continue;
        }
        int dis = (bullets[c].x-p.x)*(bullets[c].x-p.x) + (bullets[c].y-p.y)*(bullets[c].y-p.y);
        dis -= 225;
        if (dis<=0)
        {
            p.health--;
            bullets.erase(bullets.begin()+c);
            continue;
        }
    }
    if (p.health<=0)
    {
        rectfill(screen, 0, 0, 640, 480, makecol(0,0,0));
        textout_ex(screen, font, "You died! press A to play again, esc to quit", 200, 200, makecol(255,0,0), -1);
        while (true)
        {
            if (key[KEY_ESC])
            return false;
            if (key[KEY_A])
            {
                init();
                return true;
            }
        }
    }
    return true;
}
void pause()
{
    rectfill(screen, 0, 0, 640, 480, makecol(0,0,0));
    textout_ex(screen, font, "Paused. SPACE to continue...", 320, 240, makecol(255,0,0), -1);
    while (true)
    {
        if (key[KEY_SPACE])
        break;
    }
}
void init()
{
    p.x = p.y = 100;
    p.health = 5;
    bullets.clear();
}

int main()
{
    srand(time(0));

    allegro_init();
    install_keyboard();
    install_mouse();
    install_sound(MIDI_AUTODETECT, DIGI_AUTODETECT, 0);

    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);

    init();
    p.img = load_bitmap("player.bmp", NULL);
    if (!p.img)
    printf("PROBLEM\n");
    buffer = create_bitmap(640,480);
    maxBul = rand() % 5+1;

    while (!key[KEY_ESC])
    {
        if (!checkwin())
        break;
        if (key[KEY_C])
        pause();
        p.move();
        addBullets();
        rectfill(buffer, 0, 0, 640, 480, makecol(0,0,0));
        for (int c = 0; c<bullets.size(); c++)
        {
            bullets[c].move();
            bullets[c].draw();
        }
        p.draw();
        textprintf_ex(buffer, font, 320, 0, makecol(255,0,0), -1, "lives: %i", p.health);
        draw_sprite(screen, buffer, 0, 0);
    }

    return 0;
}END_OF_MAIN()
