#include <allegro.h>
#include "classes.h"

bool checkwin(player& plr, bot& bt)
{
    if (plr.health<=0)
    {
        textout_ex(screen, font, "You lost!!! Play again(y/n)?", 300, 230, makecol(255,0,0), -1);
        while (true)
        {
            if (key[KEY_Y])
            goto con;
            if (key[KEY_N])
            return false;
        }
    }
    if (bt.health<=0)
    {
        textout_ex(screen, font, "You won!!! Play again(y/n)?", 300, 230, makecol(0, 180, 0), -1);
        while (true)
        {
            if (key[KEY_Y])
            goto con;
            if (key[KEY_N])
            return false;
        }
    }
    return true;

    con:
    plr.x = plr.y = 10;
    plr.dir = 1;
    plr.health = 51;
    plr.ammo = 1000;
    bt.health = 50;
    bt.x = 600;
    bt.y = 400;
    bt.dir = 3;
    return true;
}

int main()
{
    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);

    BITMAP* buffer = create_bitmap(640, 480);
    SAMPLE* bgnd = load_sample("bgnd.wav");
    BITMAP* ppl[4] = {load_bitmap("dir0.bmp", NULL), load_bitmap("dir1.bmp", NULL),
                      load_bitmap("dir2.bmp", NULL), load_bitmap("dir3.bmp", NULL)};

    player Player(20, 20, 1, 51, 1000, 35, ppl);
    bot Bot(600, 400, 3, 50, 500, 15, ppl);
    play_sample(bgnd, 255, 128, 1000, 1);

    bool bcm = true;

    while (!key[KEY_ESC])
    {
        Player.move();
        if (bcm)
        {
            Bot.move(Player);
            bcm = false;
        }
        else
        bcm = true;
        for (int c = 0; c<bullets.size(); c++)
        {
            bullets[c].move();
        }

        if (!checkwin(Player, Bot))
        break;

        rectfill(buffer, 0, 0, 640, 480, makecol(255,255,255));
        for (int c = 0; c<bullets.size(); c++)
        {
            bullets[c].draw(buffer);
        }
        Bot.draw(buffer);
        Player.draw(buffer);
        textprintf_ex(buffer, font, 20, 0, makecol(255,0,0), -1, "Health: %i", Player.health);
        textprintf_ex(buffer, font, 200, 0, makecol(255,0,0), -1, "%i/", Player.mag);
        textprintf_ex(buffer, font, 230, 0, makecol(255,0,0), -1, "%i", Player.ammo);
        textprintf_ex(buffer, font, 500, 460, makecol(255,0,0), -1, "Enemy health: %i", Bot.health);
        draw_sprite(screen, buffer, 0, 0);

        rest(5);
    }

    stop_sample(bgnd);

    return 0;
}END_OF_MAIN()
