int main(int argc, const char *argv[])
{
    const char *filename;
    ALLEGRO_DISPLAY *display;
    ALLEGRO_BITMAP *membitmap, *bitmap;
    ALLEGRO_TIMER *timer;
    ALLEGRO_EVENT_QUEUE *queue;
    bool redraw = true;
    double zoom = 1;
    double t0;
    double t1;

    if (argc > 1) {
       filename = argv[1];
    }
    else {
       filename = "data/mysha.pcx";
    }

    if (!al_init()) {
       abort_example("Could not init Allegro.\n");
    }
       
    if (argc > 2) {
       al_set_new_display_adapter(atoi(argv[2]));
    }

    al_install_mouse();
    al_install_keyboard();

    al_init_image_addon();

    display = al_create_display(640, 480);
    if (!display) {
       abort_example("Error creating display\n");
    }
    
    al_set_window_title(display, filename);
    
    /* We load the bitmap into a memory bitmap, because creating a
     * display bitmap could fail if the bitmap is too big to fit into a
     * single texture.
     * FIXME: Or should A5 automatically created multiple display bitmaps?
     */
    al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
    t0 = al_get_time();
    membitmap = al_load_bitmap(filename);
    t1 = al_get_time();
    if (!membitmap) {
       abort_example("%s not found or failed to load\n", filename);
    }
    al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);

    printf("Loading took %.4f seconds\n", t1 - t0);
    
    // FIXME: 
    // Now try to split the memory bitmap into display bitmaps?
    bitmap = al_clone_bitmap(membitmap);
    if (!bitmap)
        bitmap = membitmap;

    timer = al_create_timer(1.0 / 30);
    queue = al_create_event_queue();
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_timer_event_source(timer));
    al_start_timer(timer);

    while (1) {
        ALLEGRO_EVENT event;
        al_wait_for_event(queue, &event);
        if (event.type == ALLEGRO_EVENT_DISPLAY_ORIENTATION) {
            int o = event.display.orientation;
            if (o == ALLEGRO_DISPLAY_ORIENTATION_0_DEGREES) {
                printf("0 degrees\n");
            }
            else if (o == ALLEGRO_DISPLAY_ORIENTATION_90_DEGREES) {
                printf("90 degrees\n");
            }
            else if (o == ALLEGRO_DISPLAY_ORIENTATION_180_DEGREES) {
                printf("180 degrees\n");
            }
            else if (o == ALLEGRO_DISPLAY_ORIENTATION_270_DEGREES) {
                printf("270 degrees\n");
            }
            else if (o == ALLEGRO_DISPLAY_ORIENTATION_FACE_UP) {
                printf("Face up\n");
            }
            else if (o == ALLEGRO_DISPLAY_ORIENTATION_FACE_DOWN) {
                printf("Face down\n");
            }
        }
        if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            break;
        if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
                break;
            if (event.keyboard.unichar == '1')
                zoom = 1;
            if (event.keyboard.unichar == '+')
                zoom *= 1.1;
            if (event.keyboard.unichar == '-')
                zoom /= 1.1;
            if (event.keyboard.unichar == 'f')
                zoom = (double)al_get_display_width(display) /
                    al_get_bitmap_width(bitmap);
        }
        if (event.type == ALLEGRO_EVENT_TIMER)
            redraw = true;
            
        if (redraw && al_is_event_queue_empty(queue)) {
            redraw = false;
            al_clear_to_color(al_map_rgb_f(0, 0, 0));
            if (zoom == 1)
                al_draw_bitmap(bitmap, 0, 0, 0);
            else
                al_draw_scaled_rotated_bitmap(
                    bitmap, 0, 0, 0, 0, zoom, zoom, 0, 0);
            al_flip_display();
        }
    }

    al_destroy_bitmap(bitmap);

    return 0;
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
	ALLEGRO_DISPLAY *display;
	ALLEGRO_BITMAP *bmp, *tmp;
	ALLEGRO_SHADER *horz_shader;
	ALLEGRO_SHADER *vert_shader;

	al_init();
	al_install_keyboard();
	al_init_image_addon();

	display = al_create_display(480, 320);
	bmp = al_load_bitmap("glow.png");
	ALLEGRO_BITMAP *bg = al_load_bitmap("bg.png");
	tmp = al_create_bitmap(
		al_get_bitmap_width(bmp),
		al_get_bitmap_height(bmp)
	);

	horz_shader = al_create_shader(ALLEGRO_SHADER_GLSL);
	vert_shader = al_create_shader(ALLEGRO_SHADER_GLSL);

	al_attach_shader_source(
		horz_shader,
		ALLEGRO_VERTEX_SHADER,
		glsl_vertex_source
	);
	al_attach_shader_source(
		horz_shader,
		ALLEGRO_PIXEL_SHADER,
		glsl_pixel_source_horz
	);
	al_link_shader(horz_shader);

	al_attach_shader_source(
		vert_shader,
		ALLEGRO_VERTEX_SHADER,
		glsl_vertex_source
	);
	al_attach_shader_source(
		vert_shader,
		ALLEGRO_PIXEL_SHADER,
		glsl_pixel_source_vert
	);
	al_link_shader(vert_shader);

	ALLEGRO_COLOR white = al_map_rgb(255, 255, 255);
	al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, white);

	ALLEGRO_VERTEX *v;
	v = new ALLEGRO_VERTEX[6*4];

	v[0].x = 0;
	v[0].y = 320;
	v[0].z = 0;
	v[0].u = 0;
	v[0].v = 0;
	v[0].color = white;
	v[1].x = 0;
	v[1].y = 0;
	v[1].z = 0;
	v[1].u = 0;
	v[1].v = 1;
	v[1].color = white;
	v[2].x = 480;
	v[2].y = 0;
	v[2].z = 0;
	v[2].u = 1;
	v[2].v = 1;
	v[2].color = white;

	v[3].x = 0;
	v[3].y = 320;
	v[3].z = 0;
	v[3].u = 0;
	v[3].v = 0;
	v[3].color = white;
	v[4].x = 480;
	v[4].y = 0;
	v[4].z = 0;
	v[4].u = 1;
	v[4].v = 1;
	v[4].color = white;
	v[5].x = 480;
	v[5].y = 320;
	v[5].z = 0;
	v[5].u = 1;
	v[5].v = 0;
	v[5].color = white;

	al_set_shader_vertex_array(horz_shader, &v[0].x, sizeof(ALLEGRO_VERTEX));
	al_set_shader_color_array(horz_shader, (unsigned char *)&v[0].color, sizeof(ALLEGRO_VERTEX));
	al_set_shader_texcoord_array(horz_shader, &v[0].u, sizeof(ALLEGRO_VERTEX));

	al_set_shader_vertex_array(vert_shader, &v[0].x, sizeof(ALLEGRO_VERTEX));
	al_set_shader_color_array(vert_shader, (unsigned char *)&v[0].color, sizeof(ALLEGRO_VERTEX));
	al_set_shader_texcoord_array(vert_shader, &v[0].u, sizeof(ALLEGRO_VERTEX));

	float radius = 1;
	float rinc = 4;

	while (1) {
		al_set_target_bitmap(tmp);
		al_clear_to_color(al_map_rgba(0, 0, 0,0));
		ALLEGRO_KEYBOARD_STATE s;
		al_get_keyboard_state(&s);
		if (al_key_down(&s, ALLEGRO_KEY_ESCAPE))
			break;

		radius += rinc;
		if (rinc > 0 && radius >= 25) {
			rinc = -rinc;
		}
		else if (rinc < 0 && radius < 1) {
			rinc = -rinc;
		}

		al_set_shader_sampler(horz_shader, "t", bmp, 0);
		al_set_shader_float(horz_shader, "img_width", al_get_bitmap_width(bmp));
		al_set_shader_float(horz_shader, "radius", radius);
		al_use_shader(horz_shader, true);
		al_draw_bitmap(bmp, 0, 0, 0);
		al_use_shader(horz_shader, false);

		al_set_target_bitmap(al_get_backbuffer());
		al_draw_bitmap(bg, 0, 0, 0);
		al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ONE, white);
		al_set_shader_sampler(vert_shader, "t", tmp, 0);
		al_set_shader_float(vert_shader, "img_height", al_get_bitmap_height(bmp));
		al_set_shader_float(vert_shader, "radius", radius);
		al_use_shader(vert_shader, true);
		al_draw_bitmap(tmp, 0, 0, 0);
		al_use_shader(vert_shader, false);
		al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, white);

		al_draw_bitmap(bmp, 0, 0, 0);

		al_flip_display();
		al_rest(0.016);
	}

	al_save_bitmap("bgxx.png", bg);
	al_save_bitmap("tmpxx.png", tmp);

	return 0;
}
Ejemplo n.º 3
0
int game_loop() {

	bool exit_game = false;
	bool redraw = true;
	
	int nrooms = 2;
	int change_room = 0;
	int current_room = -1;
	int previous_room = -1;


	int current_p_missile = 0;
	int player_can_collide = true;

	int i;
	int j;
	int k;

	ALLEGRO_FONT *font10 = al_load_font("fonts/Roboto-Black.ttf", 10,0);


	struct Subject player;
	player.health = 100;
	player.x = 0;
	player.y = 0;
	player.width = 15;
	player.height = 15;
	player.dx = 0;
	player.dy = 0;
	player.direction = 0;
	player.rotation = .03;
	player.acceleration = .03;
	player.sprite = al_create_bitmap(15, 15);
	player.weapon = 1;
	player.reload_time = 10;
	player.reload_timer = 0;
	player.nanimatics = 3;
	
	player.spritesheet = al_load_bitmap("gfx/firefly_spritesheet.png");

	player.animatic = malloc(player.nanimatics * sizeof(struct Animatic));

	player.animatic[0].source_x = 0;
	player.animatic[0].source_y = 0;
	player.animatic[0].width = 15;
	player.animatic[0].height = 15;
	player.animatic[0].pivot_x = 8;
	player.animatic[0].pivot_y = 8;
	player.animatic[0].destination_x = 8;
	player.animatic[0].destination_y = 8;
	player.animatic[0].scale_x = 1;
	player.animatic[0].scale_y = 1;
	player.animatic[0].is_running = false;
	player.animatic[0].draw = true;
	player.animatic[0].key = -1;
	player.animatic[0].tint = al_map_rgba_f(1,1,1,1);


	player.animatic[1].source_x = 0;
	player.animatic[1].source_y = 15;
	player.animatic[1].width = 15;
	player.animatic[1].height = 15;
	player.animatic[1].pivot_x = 8;
	player.animatic[1].pivot_y = 8;
	player.animatic[1].destination_x = 8;
	player.animatic[1].destination_y = 8;
	player.animatic[1].scale_x = 1;
	player.animatic[1].scale_y = 1;
	player.animatic[1].is_running = false;
	player.animatic[1].draw = false;
	player.animatic[1].nframes = 4;
	player.animatic[1].frame_rate = 15;
	player.animatic[1].key = UP;
	player.animatic[1].tint = al_map_rgba_f(1,1,1,1);

	player.animatic[2].source_x = 0;
	player.animatic[2].source_y = 30;
	player.animatic[2].width = 15;
	player.animatic[2].height = 15;
	player.animatic[2].pivot_x = 8;
	player.animatic[2].pivot_y = 8;
	player.animatic[2].destination_x = 8;
	player.animatic[2].destination_y = 8;
	player.animatic[2].scale_x = 1;
	player.animatic[2].scale_y = 1;
	player.animatic[2].is_running = false;
	player.animatic[2].draw = false;
	player.animatic[2].nframes = 4;
	player.animatic[2].frame_rate = 15;
	player.animatic[2].key = DOWN;
	player.animatic[2].tint = al_map_rgba_f(1,1,1,1);



	struct Room room[nrooms];
	for (i = 0; i < nrooms; i++) {
		room[i].initialized = false;
	}
	
	struct Subject p_missile[100];
	for (i = 0; i < 100; i++) {
		p_missile[i].exist = false;
	}


	ALLEGRO_EVENT event;
	al_start_timer(timer);

	while(!exit_game) {

		al_wait_for_event(event_queue, &event);

		#include "get_input.c"

		if (change_room != -1) {
			previous_room = current_room;
			current_room = change_room;
			change_room = -1;
			#include "change_room.c"
		}

		#include "update_logic.c"
		#include "room_specific_logic.c"

		#include "update_graphics.c"

	}

	#include "destroy_bitmaps.c"

	return 0;

}
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_BITMAP *bmp;
   ALLEGRO_BITMAP *mem_bmp;
   ALLEGRO_BITMAP *disp_bmp;
   ALLEGRO_FONT *font;
   char *text;
   bool done = false;
   bool redraw = true;

   if (!al_init()) {
      abort_example("Failed to init Allegro.\n");
      return 1;
   }

   if (!al_init_image_addon()) {
      abort_example("Failed to init IIO addon.\n");
      return 1;
   }

   al_init_font_addon();

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Error creating display.\n");
      return 1;
   }

   if (!al_install_keyboard()) {
      abort_example("Error installing keyboard.\n");
      return 1;
   }

   font = al_load_font("data/fixed_font.tga", 0, 0);
   if (!font) {
      abort_example("Error loading data/fixed_font.tga\n");
      return 1;
   }

   bmp = disp_bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Error loading data/mysha.pcx\n");
      return 1;
   }
   text = "Display bitmap (space to change)";

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   mem_bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Error loading data/mysha.pcx\n");
      return 1;
   }


   timer = al_create_timer(INTERVAL);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_timer_event_source(timer));
   al_register_event_source(queue, al_get_display_event_source(display));

   al_start_timer(timer);

   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);

   while (!done) {
      ALLEGRO_EVENT event;

      if (redraw && al_is_event_queue_empty(queue)) {
         update(bmp);
         al_clear_to_color(al_map_rgb_f(0, 0, 0));
         al_draw_tinted_bitmap(bmp, al_map_rgba_f(1, 1, 1, 0.5),
            bmp_x, bmp_y, bmp_flag);
         al_draw_text(font, al_map_rgba_f(1, 1, 1, 0.5), 0, 0, 0, text);
         al_flip_display();
         redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_DOWN:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               if (bmp == mem_bmp) {
                  bmp = disp_bmp;
                  text = "Display bitmap (space to change)";
               }
               else {
                  bmp = mem_bmp;
                  text = "Memory bitmap (space to change)";
               }
            }
               
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_TIMER:
            redraw = true;
            break;
      }
   }

   al_destroy_bitmap(bmp);

   return 0;
}
Ejemplo n.º 5
0
void show_options()
{
    int licznik=0;
    int x,y;
    x=500;
    y=100;

    ALLEGRO_FONT * font_ttf    = al_load_ttf_font("cour.ttf",80, 0);
    ALLEGRO_FONT * font_ttfbolt   = al_load_ttf_font("courbd.ttf",80, 0);
    ALLEGRO_BITMAP  *bitmapa = al_load_bitmap( "media/menu.png" );

    bool done=false,draw=false;

    al_draw_bitmap (bitmapa, 0, 0, 0);
    al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"muzyka");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"dźwięki");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"powrót do menu");
    al_flip_display();

    ALLEGRO_EVENT_QUEUE *event_queue1 = al_create_event_queue();
    ALLEGRO_KEYBOARD_STATE keyState;

    //al_register_event_source(event_queue, al_get_mouse_event_source());
    al_register_event_source(event_queue1, al_get_display_event_source(display));
    al_register_event_source(event_queue1, al_get_keyboard_event_source());
    while(!done)
    {
        ALLEGRO_EVENT events;
        al_wait_for_event(event_queue1, &events);
        al_get_keyboard_state(&keyState);

        if(events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;

        }
        else if (al_key_down( &keyState, ALLEGRO_KEY_ESCAPE))
        {
            done=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_ENTER))
        {
            if(licznik==2)
            {
                done=true;
                draw=false;
            }
            else if(licznik==0)
            {
                show_sound();
                draw=true;


            }
            else if(licznik==1)
            {
                show_sound2();
                draw=true;


            }

        }
        else  if(al_key_down(&keyState, ALLEGRO_KEY_UP))
        {

            licznik--;
            if(licznik<0)licznik=2;
            draw=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_DOWN))
        {
            licznik++;
            if(licznik>2)licznik=0;

            draw=true;
        }
        if(draw)
        {
            draw=false;
            al_draw_bitmap (bitmapa, 0, 0, 0);
            if(licznik==0)
            {
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"muzyka");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"dźwięki");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"powrót do menu");
                al_rest(0.15);
            }
            else if(licznik==1)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"muzyka");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"dźwięki");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"powrót do menu");
                al_rest(0.15);
            }
            else if(licznik==2)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"muzyka");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"dźwięki");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"powrót do menu");
                al_rest(0.15);
            }

            al_flip_display();
        }
    }
    al_destroy_bitmap(bitmapa);
    al_destroy_event_queue(event_queue1);
    al_destroy_font(font_ttf);
    al_destroy_font(font_ttfbolt);

}
int main(int argc, char *argv[])
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_FONT *font;

   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro\n");
      return 1;
   }
   al_init_primitives_addon();
   al_install_keyboard();
   al_install_mouse();

   al_init_font_addon();
   al_init_image_addon();

   al_set_new_display_flags(ALLEGRO_GENERATE_EXPOSE_EVENTS);
   display = al_create_display(800, 600);
   if (!display) {
      abort_example("Unable to create display\n");
      return 1;
   }

   font = al_load_font("data/fixed_font.tga", 0, 0);
   if (!font) {
      abort_example("Failed to load data/fixed_font.tga\n");
      return 1;
   }
   allegro = al_load_bitmap("data/allegro.pcx");
   if (!allegro) {
      abort_example("Failed to load data/allegro.pcx\n");
      return 1;
   }
   mysha = al_load_bitmap("data/mysha.pcx");
   if (!mysha) {
      abort_example("Failed to load data/mysha.pcx\n");
      return 1;
   }
   
   target = al_create_bitmap(320, 200);

   al_add_new_bitmap_flag(ALLEGRO_MEMORY_BITMAP);
   allegro_bmp = al_clone_bitmap(allegro);
   mysha_bmp = al_clone_bitmap(mysha);
   target_bmp = al_clone_bitmap(target);

   /* Don't remove these braces. */
   {
      Theme theme(font);
      Prog prog(theme, display);
      prog.run();
   }

   al_destroy_bitmap(allegro);
   al_destroy_bitmap(allegro_bmp);
   al_destroy_bitmap(mysha);
   al_destroy_bitmap(mysha_bmp);
   al_destroy_bitmap(target);
   al_destroy_bitmap(target_bmp);

   al_destroy_font(font);

   return 0;
}
Ejemplo n.º 7
0
bool Map::loadMap(std::string mapDirectory)
{
    GUI *guiPtr = Base::instance()->getGuiPtr();

    std::ifstream fileStream;
    fileStream.open(mapDirectory);
    if(!fileStream.good())
        return false;

    int linei = 0;
    bool error = false;
    while(!fileStream.eof())
    {
        linei+=1;
        std::string line;
        std::vector<std::string> translatedLine;

        //line decryption
        std::getline(fileStream, line);

        if(line.size()==0)
            continue;

        std::string::iterator it;
        std::string temporaryCommandContainer;
        bool nameEnclosure = false;
        for(it=line.begin();it!=line.end();it++)
        {
            if(*it == '#')
                break;
            else if(*it == '\"')
            {
                nameEnclosure = !nameEnclosure;
            }
            else if(*it == ' ' && !nameEnclosure)
            {
                translatedLine.push_back(temporaryCommandContainer);
                temporaryCommandContainer = "";
            }
            else
            {
                temporaryCommandContainer += *it;
            }
        }

        if(temporaryCommandContainer.size()>0)
        {
            translatedLine.push_back(temporaryCommandContainer);
            temporaryCommandContainer = "";
        }

        if(translatedLine.size()==0)
            continue;

        //command decryption
        if(translatedLine[0]=="nazwa")
        {
            if(translatedLine.size()!=2)
                error=true;
            else
                setMapName(translatedLine[1]);
        }
        else if(translatedLine[0]=="mapa")
        {
            if(translatedLine.size()!=2)
                error=true;
            else
            {
                al_destroy_bitmap(mapaPtr);
                mapaPtr = al_load_bitmap(translatedLine[1].c_str());
                al_clear_to_color(al_map_rgb(0, 0, 255));
                mapaWidth = al_get_bitmap_width(mapaPtr);
                mapaHeight = al_get_bitmap_height(mapaPtr);
            }
        }
        else if(translatedLine[0]=="kraj")
        {
            if(translatedLine.size()!=6)
                error=true;
            else
                addRealm(translatedLine[1],al_map_rgb(std::stoi(translatedLine[2]),
                        std::stoi(translatedLine[3]),std::stoi(translatedLine[4])), translatedLine[5]);
        }
        else if(translatedLine[0]=="koniec")
        {
            if(translatedLine.size()!=2)
                error=true;
            else if(translatedLine[1]=="krajow")
                fillDiplomaticStates();
            else
                error=true;
        }
        else if(translatedLine[0]=="region")
        {
            if(translatedLine.size()!=7)
                error=true;
            else if(!addRegion(std::stoi(translatedLine[1]),std::stoi(translatedLine[2]),
                    translatedLine[3],translatedLine[4],std::stoi(translatedLine[5]), std::stoi(translatedLine[6])))
                error=true;
        }
        else if(translatedLine[0]=="droga")
        {
            if(translatedLine.size()!=3)
                error=true;
            else if(!addRegionsConnector(translatedLine[1], translatedLine[2]))
                error=true;
        }
        else if(translatedLine[0]=="wojna")
        {
            if(translatedLine.size()!=3)
                error=true;
            else if(!changeDiplomaticState(WAR, translatedLine[1], translatedLine[2]))
                error=true;
        }
        else if(translatedLine[0]=="handel")
        {
            if(translatedLine.size()!=3)
                error=true;
            else if(!changeDiplomaticState(TRADE_AGREEMENT, translatedLine[1], translatedLine[2]))
                error=true;
        }
        else if(translatedLine[0]=="sojusz")
        {
            if(translatedLine.size()!=3)
                error=true;
            else if(!changeDiplomaticState(ALLIANCE, translatedLine[1], translatedLine[2]))
                error=true;
        }

        if(error)
        {
            guiPtr->showNotification("Błąd w mapie w linii: " + std::to_string(linei));
            return false;
        }
    }

    fillRealmsRegions();
    return true;
}
Ejemplo n.º 8
0
int main(void)
{
	//Initialize allegro--------------------------------
	if (InitAllegro())
	{
		return -1;
	}

	srand(time(NULL));

	//variables-----------------------------------------
	const int FPS = 60;//how many frames the game should run at
	bool StartScreen = true; //start screen while loop bool
	bool QuitGame = false;
	int NumberOfAI = 30;

	//Allegro variables---------------------------------
	ALLEGRO_EVENT_QUEUE *Event_Queue = NULL;
	ALLEGRO_TIMER *Timer = NULL;
	
	Event_Queue = al_create_event_queue();				
	Timer = al_create_timer(1.0 / FPS);

	Display MainDisplay(Event_Queue);

	if (!MainDisplay.TestDisplay())
	{
		return -1;
	}

	ALLEGRO_BITMAP *AIImage = al_load_bitmap("AI_Sprite.png");
	ALLEGRO_BITMAP *StartImage = al_load_bitmap("Start_Screen.jpg");
	ALLEGRO_BITMAP *GameOverImage = al_load_bitmap("GameOver_Screen.jpg");

	Player MainPlayer(Event_Queue);
	Camera MainCamera(Event_Queue, MainDisplay.Get_ScreenWidth(), MainDisplay.Get_ScreenHeight());
	AI_Group TestAIGroup(Event_Queue);  // Instance of an AI_Group
	GUILayer MainGUILayer(MainDisplay.Get_ScreenWidth(), MainDisplay.Get_ScreenHeight());

	DungeonGenerator Dungeon(Event_Queue, &MainPlayer);
	Dungeon.GenerateDungeon(MainDisplay);

	MainPlayer.SetXPosition(Dungeon.GetStartPosition().x());
	MainPlayer.SetYPosition(Dungeon.GetStartPosition().y());

	TestAIGroup.RandomSetup(NumberOfAI, Dungeon);  // Generates AI with random attributes in the group. Their spawn points will also be set randomly.
	
	al_register_event_source(Event_Queue, al_get_timer_event_source(Timer));
	al_register_event_source(Event_Queue, al_get_keyboard_event_source());
	al_register_event_source(Event_Queue, al_get_mouse_event_source());
	

	al_start_timer(Timer);
	
	//Main game loop------------------------------------
	while (!QuitGame)
	{
		while (StartScreen)
		{
			//allegro event and queue
			ALLEGRO_EVENT ev;
			al_wait_for_event(Event_Queue, &ev);

			//if space pressed end start screen
			if (ev.keyboard.keycode == ALLEGRO_KEY_SPACE)
			{
				StartScreen = false;
				al_add_timer_count(Timer, al_get_timer_count(Timer) * -1);
			}

			if (al_is_event_queue_empty(Event_Queue))
			{
				//draw title image
				al_draw_bitmap(StartImage, 0, 0, NULL);

				//Draw display last
				MainDisplay.Draw();
			}
		}

		ALLEGRO_EVENT ev;
		al_wait_for_event(Event_Queue, &ev);
		
		Dungeon.Event_Handler(ev);
		TestAIGroup.EventHandler(ev);
		TestAIGroup.ProcessAll(ev, MainPlayer);  // Process each AI in the group
		MainPlayer.EventHandler(ev, MainCamera.GetMouseXWorldCoordinate(), MainCamera.GetMouseYWorldCoordinate());
		MainCamera.EventHandler(ev, MainPlayer.GetXPosition(), MainPlayer.GetYPosition());
		
		if (MainDisplay.Event_Handler(ev))
			QuitGame = true;

		//Current Dungeon complete move on to the next one
		if (ev.type == DUNGEON_COMPLETE_EVENT)
		{
			al_stop_timer(Timer); //Pause the timer while all the new level loads
			Dungeon.GenerateDungeon(MainDisplay);
			TestAIGroup.RandomSetup(30, Dungeon);
			MainPlayer.SetXPosition(Dungeon.GetStartPosition().x());
			MainPlayer.SetYPosition(Dungeon.GetStartPosition().y());
			MainPlayer.ScaleGameUp(Dungeon.Get_DungeonLevel());
			al_start_timer(Timer); //resume the timer after the new level loads
		}

		// Collide with AI
		if (TestAIGroup.CollideWithAI(MainPlayer.GetCollisionXBoundOne(), MainPlayer.GetCollisionYBoundOne()))
			MainPlayer.MovementCollidingBoundOne();
		if (TestAIGroup.CollideWithAI(MainPlayer.GetCollisionXBoundTwo(), MainPlayer.GetCollisionYBoundTwo()))
			MainPlayer.MovementCollidingBoundTwo();
		
		// Hit the AI
		TestAIGroup.HitAI(MainPlayer.GetWeaponHitBoxXBoundOne(), MainPlayer.GetWeaponHitBoxYBoundOne(), MainPlayer.GetWeaponDamage());
		TestAIGroup.HitAI(MainPlayer.GetWeaponHitBoxXBoundTwo(), MainPlayer.GetWeaponHitBoxYBoundTwo(), MainPlayer.GetWeaponDamage());

		if (Dungeon.Get_Map()->CheckMapCollision(Vec2f(MainPlayer.GetCollisionXBoundOne(), MainPlayer.GetCollisionYBoundOne())))
			MainPlayer.MovementCollidingBoundOne();
		if (Dungeon.Get_Map()->CheckMapCollision(Vec2f(MainPlayer.GetCollisionXBoundTwo(), MainPlayer.GetCollisionYBoundTwo())))
			MainPlayer.MovementCollidingBoundTwo();


		if (MainPlayer.IsDead())
		{
			MainCamera.ResetTranslate();

			bool GameOverScreen = true; //bool for game over screen sequence
			int PlayerFinalScore = MainPlayer.GetFinalTimedScore(Timer);
			
			while (GameOverScreen)
			{
				//allegro event and queue
				ALLEGRO_EVENT ev;
				al_wait_for_event(Event_Queue, &ev);

				//if space pressed end start screen
				if (ev.keyboard.keycode == ALLEGRO_KEY_ENTER)
				{
					StartScreen = true;
					GameOverScreen = false;
				}
				else if (ev.keyboard.keycode == ALLEGRO_KEY_SPACE)
				{
					GameOverScreen = false;
				}

				if (al_is_event_queue_empty(Event_Queue))
				{
					//draw title image
					al_draw_bitmap(GameOverImage, 0, 0, NULL);
					MainGUILayer.DrawFinalScoreScreen(PlayerFinalScore);
					//Draw display last
					MainDisplay.Draw();
				}
			}

			
			MainPlayer.ResetPlayer();
			Dungeon.Set_DungeonLevel(1);
			Dungeon.GenerateDungeon(MainDisplay);
			TestAIGroup.RandomSetup(NumberOfAI += Random(2,5), Dungeon);
			MainPlayer.SetXPosition(Dungeon.GetStartPosition().x());
			MainPlayer.SetYPosition(Dungeon.GetStartPosition().y());
			MainPlayer.ScaleGameUp(Dungeon.Get_DungeonLevel());
			al_add_timer_count(Timer, al_get_timer_count(Timer) * -1);
		}

		//Code Dealing with drawing to the screen goes within this if statement
		if (al_is_event_queue_empty(Event_Queue))
		{
			Dungeon.Draw(1); //Draw the bottom layers of the dungeon
			MainPlayer.DrawPlayer(); //Draw the player
			TestAIGroup.DrawAll();  // Draw all AI.
			Dungeon.Draw(0); //Draw the top layers of the dungeon

			MainGUILayer.DrawPlayerInformation(MainCamera, MainPlayer.GetCurrentLevel(), MainPlayer.GetCurrentHealth());
			MainGUILayer.DrawScoreInformation(MainCamera, MainPlayer.GetCurrentScore());
			MainGUILayer.DrawGameTimeInformation(MainCamera, Timer);

			//Draw display last
			MainDisplay.Draw();
		}
	}

	
	//Game Ending--------------------------------------

	return 0;
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "Variable Initialization"
	
	const float FPS = 60;
	int screenw = 900;
	int screenh = 650;
	float bounce = 25;
	float bouncer_x = 604;
	float bouncer_y = 300;
	float wall1_x = 140.0;
	float wall1_y = 30.0;
	float wall1_w = 30.0;
	float wall1_h = 30.0;
	float wall2_x = 140.0;
	float wall2_y = 30.0;
	float wall2_w = 70.0;
	float wall2_h = 70.0;
	float food_x = 146;
	float food_y = 37;
	float food_h = 10;
	float food_w = 10;
	bool key[4] = { false, false, false, false };
	bool redraw = true;
	bool exiting = false;
	bool menu = false;
	int maze[20][20];
	int dir = 0;
	int coly[20][20] = {0};

#pragma region "Maze Init"
	for (int row = 0; row < 20; row++)
	{
		for (int col = 0; col < 20; col++)
		{
			maze[row][col] = true;
		}
	}

	int row = 1;
	while (1)
	{
		for (int col = 0; col < 3; col++)
		{
			maze[1][col] = false;
		}
		for (int col = 4; col < 16; col++)
		{
			maze[1][col] = false;
		}
		for (int col = 17; col < 20; col++)
		{
			maze[1][col] = false;
		}
		row = row + 14;
		if (row > 15)
			break;
	}

	int col = 4;
	while (1)
	{
		for (int row = 2; row < 16; row++)
		{
			maze[row][col] = false;
		}

		col = col + 11;
		if (col > 15)
			break;
	}

	for (int col = 2; col < 8; col++)
	{
		maze[3][col] = false;
	}
	for (int col = 12; col < 18; col++)
	{
		maze[3][col] = false;
	}

	col = 1;
	while (1)
	{
		for (int row = 3; row < 7; row++)
		{
			maze[row][col] = false;
		}

		col = col + 17;
		if (col > 18)
			break;
	}

	for (col = 7; col < 13; col++)
	{
		maze[4][col] = false;
	}

	row = 6;
	while (1)
	{
		for (int col = 2; col < 18; col++)
		{
			maze[row][col] = false;
		}

		row = row + 5;
		if (row > 11)
			break;
	}

	col = 2;
	while (1)
	{
		for (int row = 7; row < 16; row++)
		{
			maze[row][col] = false;
		}

		col = col + 15;
		if (col > 17)
			break;
	}

	maze[7][9] = false;
	maze[7][10] = false;

	col = 0;
	while (1)
	{
		for (int row = 10; row < 14; row++)
		{
			maze[row][col] = false;
		}

		col = col + 19;
		if (col > 19)
			break;
	}

	for (int col = 6; col < 14; col++)
	{
		maze[13][col] = false;
	}

	col = 1;
	while (1)
	{
		for (row = 16; row < 18; row++)
		{
			maze[row][col] = false;
		}

		col = col + 17;
		if (col > 18)
			break;
	}

	for (int col = 5; col < 8; col++)
	{
		maze[17][col] = false;
	}
	for (int col = 12; col < 15; col++)
	{
		maze[17][col] = false;
	}

	for (col = 1; col < 6; col++)
	{
		maze[18][col] = false;
	}
	for (col = 7; col < 13; col++)
	{
		maze[18][col] = false;
	}
	for (col = 14; col < 19; col++)
	{
		maze[18][col] = false;
	}

	maze[2][2] = false;
	maze[2][17] = false;
	maze[7][9] = false;
	maze[7][10] = false;
	maze[12][6] = false;
	maze[12][13] = false;
	maze[16][5] = false;
	maze[16][14] = false;
	maze[16][2] = false;
	maze[16][4] = false;
	maze[16][17] = false;
	maze[16][15] = false;
	maze[1][0] = true;
	maze[1][19] = true;
	maze[1][1] = true;
	maze[1][18] = true;
	maze[1][2] = true;
	maze[1][17] = true;
	maze[2][2] = true;
	maze[2][17] = true;


	for (int row = 8; row < 10; row++)
	{
		for (int col = 6; col < 14; col++)
		{
			maze[row][col] = false;
		}
	}
#pragma endregion

	enum MYKEYS 
	{
		KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT
	};
	pac game;

	game.setpacmanx(bouncer_x);
	game.setpacmany(bouncer_y);
	game.initpacsize();

	ALLEGRO_DISPLAY *display = NULL;			
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *bouncer = NULL;
	ALLEGRO_BITMAP *wall1 = NULL;
	ALLEGRO_BITMAP *food = NULL;
	ALLEGRO_BITMAP *wall2[20][20] = {NULL};
	ALLEGRO_BITMAP *ghostb = NULL;
	ALLEGRO_BITMAP *ghostg = NULL;
	ALLEGRO_BITMAP *ghostr = NULL;
	ALLEGRO_BITMAP *ghostp = NULL;
	ALLEGRO_COLOR color;

#pragma endregion

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "System Protection" 
	
	// Begining Initialization
	// Checks if Allegro is initialized
	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	//Checks if keyboard is initialized
	if (!al_install_keyboard()) {
		fprintf(stderr, "failed to initialize the keyboard!\n");
		return -1;
	}

	//Checks if mouse is initialized
	if (!al_install_mouse()) {
		fprintf(stderr, "failed to initialize the mouse!\n");
		return -1;
	}

	//Intializes timer to fps and then checks if there is a timer
	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "failed to create timer!\n");
		return -1;
	}

	//checks if there is a display
	display = al_create_display(screenw , screenh);
	if (!display) {
		fprintf(stderr, "failed to create display!\n");
		return -1;
	}

	al_init_font_addon();
	al_init_ttf_addon();

	al_init_primitives_addon();
	
	ALLEGRO_FONT *font = al_load_ttf_font("DroidSans.ttf", 23, 0);
	ALLEGRO_FONT *font2 = al_load_ttf_font("DroidSans.ttf", 12, 0);

	if (!font){
		fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
		return -1;
	}

	bouncer = al_create_bitmap(bounce,bounce);
	if (!bouncer) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	ghostb = al_create_bitmap(bounce,bounce);
	if (!bouncer) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	ghostg = al_create_bitmap(bounce,bounce);
	if (!bouncer) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	ghostr = al_create_bitmap(bounce,bounce);
	if (!bouncer) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	ghostp = al_create_bitmap(bounce,bounce);
	if (!bouncer) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	wall1 = al_create_bitmap(wall1_w, wall1_h);
	if (!wall1) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	food = al_create_bitmap(food_w, food_h);
	if (!food) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					wall2[col][row] = al_create_bitmap(wall1_w,wall1_w);

					al_set_target_bitmap(wall2[col][row]);

					al_clear_to_color(al_map_rgb(0, 0, 255));

					al_set_target_bitmap(al_get_backbuffer(display));
				}
			}



	al_init_image_addon();


	ALLEGRO_DISPLAY_MODE   disp_data;
	al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);
	

	al_set_target_bitmap(food);

	al_clear_to_color(al_map_rgb(255, 255, 255));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(bouncer);

	al_clear_to_color(al_map_rgb(255, 255, 0));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(ghostb);

	al_clear_to_color(al_map_rgb(0, 150, 255));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(ghostr);

	al_clear_to_color(al_map_rgb(255, 0, 0));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(ghostg);

	al_clear_to_color(al_map_rgb(0, 255, 0));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(ghostp);

	al_clear_to_color(al_map_rgb(255, 0, 255));

	al_set_target_bitmap(al_get_backbuffer(display));

	al_set_target_bitmap(wall1);

	al_clear_to_color(al_map_rgb(0, 0, 255));

	al_set_target_bitmap(al_get_backbuffer(display));

	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event_queue!\n");
		al_destroy_bitmap(bouncer);
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

#pragma endregion

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "Event Initialization"
	al_register_event_source(event_queue, al_get_display_event_source(display));  //display event handler
	al_register_event_source(event_queue, al_get_timer_event_source(timer));   //time envent handler
	al_register_event_source(event_queue, al_get_keyboard_event_source());   //keyboard event handler
	al_register_event_source(event_queue, al_get_mouse_event_source());  //mouse event handler
	al_clear_to_color(al_map_rgb(0, 0, 0));
	al_flip_display();
	al_start_timer(timer);
#pragma endregion

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "Simple Menu"
	while (!menu)
	{
		ALLEGRO_EVENT ev;
		al_install_audio();
		al_reserve_samples(1);
		ALLEGRO_SAMPLE *sample = al_load_sample("song.wav");
		ALLEGRO_SAMPLE_INSTANCE *songinstance;
		//songinstance = al_create_sample_instance(sample);
		//al_set_sample_instance_playmode(songinstance, ALLEGRO_PLAYMODE_ONCE);
		//al_attach_sample_instance_to_mixer(songinstance, al_get_default_mixer());
		al_wait_for_event(event_queue, &ev);
		al_install_mouse();
		al_init_image_addon();
		ALLEGRO_BITMAP *image = al_load_bitmap("Pacman.jpg"); 
		//al_init_image_addon();
		al_init_font_addon();
		al_init_ttf_addon();
		ALLEGRO_FONT *font24 = al_load_font("PAC-FONT.ttf", 35, 0);
		//ALLEGRO_BITMAP *title = al_load_bitmap("title.jpg"); 
		al_register_event_source(event_queue, al_get_mouse_event_source());

		if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) 
		{
			if (ev.mouse.button == 1 && ev.mouse.x > 500 && ev.mouse.x < 700 && ev.mouse.y > 525) 
				{
					menu = true;
					break;
				}
			else if(ev.mouse.button == 1 && ev.mouse.x > 500 && ev.mouse.y < 475 && ev.mouse.y > 425 )
			{
				al_show_native_message_box(NULL, "Credits", "Created by:", "Anuraag Shankar, Ronit Sharma, and Sahana Premkumar", NULL, NULL);
					
			}
			else if(ev.mouse.button == 1 && ev.mouse.x > 500 && ev.mouse.y < 420 )
			{
				al_show_native_message_box(NULL, "Controls", "Movement- Arrow Keys", "Objective: Avoid ghosts and collect maximum pellets", NULL, NULL);
					
			}
			
		}
		
		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
				break;
			}
		


		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;

			al_clear_to_color(al_map_rgb(0, 0, 0));
			al_init_primitives_addon();
			
			al_init_acodec_addon();
			
			//al_play_sample(sample, 255, 0, 2000, ALLEGRO_PLAYMODE_ONCE, 0);
			al_draw_text(font24, al_map_rgb(255, 255, 255), 420, 150, 0, "Pacman: The Game");
			//al_draw_bitmap(title, 700, (50), NULL);
			al_draw_bitmap(image, 100, (100), NULL);
			al_draw_filled_rectangle(500,300,804,375, al_map_rgb(255, 0, 0));
			al_draw_filled_rectangle(500,500,804,575, al_map_rgb(255, 0, 0));
			al_draw_filled_rectangle(500,400,804,475, al_map_rgb(255, 0, 0));
			al_draw_text(font, al_map_rgb(255, 255, 255), 650, 315, ALLEGRO_ALIGN_CENTRE, "Controls");
			al_draw_text(font, al_map_rgb(255, 255, 255), 650, 525, ALLEGRO_ALIGN_CENTRE, "Click to play");
			al_draw_text(font, al_map_rgb(255, 255, 255), 650, 415, ALLEGRO_ALIGN_CENTRE, "Credits");

			

			al_flip_display();
		}

	}

#pragma endregion

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "Driver Program"

	while (!exiting)
	{

#pragma region "Timer Events"

		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);
		if (ev.type == ALLEGRO_EVENT_TIMER) {

			if(key[KEY_UP]  && game.getpacmany() >= 4.0 ) {
				for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					if(coly[row][col] !=2)
					{
						game.uppacman();
						dir = 1;
						
					}
				}
			}
			}

			if (key[KEY_DOWN] && game.getpacmany() <= screenh - bounce - 4.0 ) {

				for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					if(coly[row][col] != 4)
					{
						game.downpacman();
						dir = 2;
						
					}
				}
			}
			}

			if (key[KEY_LEFT] && game.getpacmanx() >= 4.0) {
				for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					if(coly[row][col] != 1)
					{
						game.leftpacman();
						dir = 3;
						
					}
				}
			}
			}

			if (key[KEY_RIGHT] && game.getpacmanx() <= screenw - bounce - 4.0) {
				for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					if(coly[row][col] != 3)
					{
						game.rightpacman();
						dir = 4;
						
					}
				}
			}
			}

			redraw = true;
		}

// "Closes the Window When Pressing X button"
		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
#pragma endregion

#pragma region "Checks for when key was pressed down"
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = true;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = true;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = true;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = true;
				break;
			}
		}
#pragma endregion 

#pragma region "Checks for when key was released"
		else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = false;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = false;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = false;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = false;
				break;

			case ALLEGRO_KEY_ESCAPE:
				exiting = true;
				break;

			case ALLEGRO_KEY_Q:
				exiting = true;
				break;

			//Full screen when f is pressed
			case ALLEGRO_KEY_F:
				if (screenw != disp_data.width)
				{
					al_set_new_display_flags(ALLEGRO_FULLSCREEN);
					display = al_create_display(disp_data.width, disp_data.height);
					screenw = disp_data.width;
					screenh = disp_data.height;
					wall1_x = 2 * (screenw / 10);
					wall1_y = (screenh / screenh) + 50 * (screenh / screenh);
				}
				
				break;

			//Normal screen when n is pressed
			case ALLEGRO_KEY_N:
				
					al_show_native_message_box(al_get_current_display(), 
                                 "THIS IS THE END", 
                                 "YOU LOST", 
                                 "Game Over",
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
				break;
			
			case ALLEGRO_KEY_P:
					cout << "bx:" << (wall1_x + wall1_w + 13) - game.getpacmanx() << endl;
					cout << "by:" << (wall1_y + wall1_w + 13) - game.getpacmany() << endl;
					cout << "dx:" << (game.getpacmanx() + bounce) - wall1_x << endl;
					cout << "dy:" << (game.getpacmany() + bounce) - wall1_y << endl;
					cout << "dir:" << coly << endl;
					cout << "x:" << game.getpacmanx() << endl;
					cout << "y:" << game.getpacmany() << endl;
			}
		}

#pragma endregion

#pragma region "Redraw Objects"
		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;

			al_clear_to_color(al_map_rgb(0, 0, 0));

			for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{

					if (maze[row][col] == 1)
					{
						al_draw_bitmap(wall1, wall1_x + col*30, wall1_y + row*30, 0);
					//	al_draw_bitmap(wall2[row][col], wall1_x + col*30, wall1_y + row*30, 0);
						coly[row][col] = game.collision(wall1_x + col*30,wall1_y + row*30,wall1_w + 13);
					}
					else
						al_draw_bitmap(food, food_x + col*30, food_y + row*30, 0);
				}
			}


			int x = game.getpacmanx();
			int y = game.getpacmany();

			color = al_map_rgb(255,200,0);

			//al_draw_bitmap(bouncer, game.getpacmanx(), game.getpacmany(), 0);
			al_draw_filled_circle(game.getpacmanx(),game.getpacmany(),13.0,color);
			al_draw_bitmap(ghostb,screenw/2, 63, 0);
			al_draw_bitmap(ghostr,screenw/2 - 20, 213, 0);
			al_draw_bitmap(ghostg,screenw/2 - 20, 363, 0);
			al_draw_bitmap(ghostp, screenw/2 - 246,500, 0);

#pragma region "TEST CODE"
			if(game.getpacmanx() - screenw/2 > 30 && game.getpacmanx() - screenw/2< 33)
			{
				al_show_native_message_box(al_get_current_display(), 
                                 "THIS IS THE END", 
                                 "YOU LOST", 
                                 "Game Over",
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
			}

#pragma endregion

			al_draw_text(font2, al_map_rgb(255, 0, 0), screenw / 2, (screenh / screenh), ALLEGRO_ALIGN_CENTRE, "PAC-MAN VERSION 1.0");

			al_flip_display();
		}
#pragma endregion

	}

#pragma endregion

//--------------------------------------------------------------------------------------------------------------------------------
#pragma region "Destroyers"

	al_destroy_bitmap(bouncer);
	al_destroy_bitmap(wall1);
		for (int row = 0; row < 20; row++) //display
			{
				for (int col = 0; col < 20; col++)
				{
					al_destroy_bitmap(wall2[row][col]);
				}
			}	
	al_destroy_bitmap(food);
	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
#pragma endregion

	return 0;
}
Ejemplo n.º 10
0
int main()

{

	// Inicializando 

	const float FPS = 60.0;
	const float gravedad = 5.0;

	if(!al_init())
	{
		al_show_native_message_box(NULL, "Fatal Error", NULL, "No se pudo inicializar Allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}
	
	al_set_new_display_flags(ALLEGRO_WINDOWED); // Pone la ventana en modo Windowed
	ALLEGRO_DISPLAY *display = al_create_display(AnchoPantalla, AltoPantalla);

	// Pone la posición en la que debe salir la ventana
	al_set_window_position(display, 0, 0);

	// Pone el título de la ventana
	al_set_window_title(display, "Muévete!");

	if(!display)	// Si no se pudo crear la ventana, entonces pone un mensaje de error
	{
		al_show_native_message_box(NULL, "Error", NULL, "No se pudo crear la pantalla", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}
	// Fin de la inicialización

	al_install_keyboard();
	al_init_image_addon();

	ALLEGRO_BITMAP *image = al_load_bitmap("sprites/mario.png");
	ALLEGRO_BITMAP *mario = al_create_sub_bitmap(image, 3, 603, 16, 21);
	ALLEGRO_BITMAP *fondo = al_load_bitmap("sprites/jordy.jpg");
	ALLEGRO_BITMAP *malo  = al_load_bitmap ("sprites/enemigo.jpg");
	ALLEGRO_KEYBOARD_STATE estadoTeclado;
	ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS);
	ALLEGRO_EVENT_QUEUE *listaEventos = al_create_event_queue();

	al_register_event_source(listaEventos, al_get_keyboard_event_source());
	al_register_event_source(listaEventos, al_get_display_event_source(display));
	al_register_event_source(listaEventos, al_get_timer_event_source(timer));


	// Ahora si comenzamos con lo del juego

	bool finJuego = false;
	float velocidad = 8.0, rotacion = 360.0;
	float x = AnchoPantalla/2, y = AltoPantalla/2;
	int right = 0, distancia_arma = 10;


	ALLEGRO_BITMAP *arma = al_load_bitmap("sprites/submachine.png");
	ALLEGRO_BITMAP *submachine = al_create_sub_bitmap(arma, 4, 4, 49, 21);
	al_convert_mask_to_alpha(mario, al_map_rgb(0,0,0));


	al_start_timer(timer);

	while(!finJuego)
	{
		ALLEGRO_EVENT eventos;

		al_wait_for_event(listaEventos, &eventos);


		if(eventos.type == ALLEGRO_EVENT_TIMER)
		{
			al_get_keyboard_state(&estadoTeclado);

			if(al_key_down(&estadoTeclado, ALLEGRO_KEY_Q) || al_key_down(&estadoTeclado, ALLEGRO_KEY_ESCAPE))
				finJuego = true;

			if(al_key_down(&estadoTeclado, ALLEGRO_KEY_LEFT))
			{
				right = 0;
				distancia_arma = 10;
				rotacion = 0.0;
				x -= velocidad;
			}		
			if(al_key_down(&estadoTeclado, ALLEGRO_KEY_RIGHT))
			{
				right = 1;
				distancia_arma = 0;
				rotacion = 0.0;
				x += velocidad;
			}
			if(al_key_down(&estadoTeclado, ALLEGRO_KEY_UP))
				{
					rotacion = -90.0;
					y -= velocidad;
				}
			if(al_key_down(&estadoTeclado, ALLEGRO_KEY_DOWN))
				{
					rotacion = 90.0;
					y += velocidad;
				}

		if(x <= 0) x = 0;
		if(x+32 >= AnchoPantalla) x = AnchoPantalla-32;
		if(y <= 0) y = 0;
		y += gravedad;
		if(y+42 >= AltoPantalla) y = AltoPantalla-42;

		}

		al_clear_to_color(al_map_rgb(0, 0, 0));
		al_draw_scaled_bitmap(fondo, 0, 0, 300, 290, 0, 0, AnchoPantalla, AltoPantalla, 0);
		al_draw_scaled_bitmap(mario, 0, 0, 16, 21, x, y, 32, 42, right);
		al_draw_bitmap(submachine, x - distancia_arma, y+15, right);
		al_draw_bitmap(malo, 10, 30, 0);

		al_flip_display();
	}

	al_destroy_bitmap(image);
	al_destroy_bitmap(mario);
	al_destroy_bitmap(arma);
	al_destroy_bitmap(submachine);
	al_destroy_event_queue(listaEventos);
	al_destroy_display(display);
	al_destroy_timer(timer);

	return 0;
}
Ejemplo n.º 11
0
Weapon::Weapon(WeaponType Type, int minAttack, int maxAttack) {
	type = Type;
	switch (type) {
	case _NoWeapon:
		name = "None";
		break;
	case _Knife:
		name = "Knife";
		break;
	case _Wand:
		name = "Wand";
		break;
	case _Sword:
		name = "Sword";
	}

	min_attack = minAttack;
	max_attack = maxAttack;

	xCorrection = 0;
	yCorrection = 0;

	switch (type) {
	case _NoWeapon:
		thumbnail = al_load_bitmap(NoWeaponThumb);
		break;
	case _Knife:
		thumbnail = al_load_bitmap(KnifeThumb);
		break;
	case _Wand:
		thumbnail = al_load_bitmap(WandThumb);
		break;
	case _Sword:
		thumbnail = al_load_bitmap(SwordThumb);
		break;
	}
	if (!thumbnail) {
		al_show_native_message_box(RPG::GetInstance()->GetDisplay(), "Error", "Could not load weapon bitmap.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		exit(-1);
	}

	if (type != _NoWeapon) {
		switch (type) {
		case _Knife:
		case _Sword:
			sprite = al_load_bitmap(SwordsPng);
			break;
		case _Wand:
			sprite = al_load_bitmap(WandsPng);
			break;
		}

		if (!sprite) {
			al_show_native_message_box(RPG::GetInstance()->GetDisplay(), "Error", "Could not load weapon sprite.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
			exit(-1);
		}
	}
	startPlayingAnimation = false;
	playingAnimation = false;
	frame = 0;
}
Ejemplo n.º 12
0
void init(void)
{
    if (!al_init())
        abort_game("Failed to initialize allegro");

    if (!al_install_keyboard())
        abort_game("Failed to install keyboard");

    if (!al_install_mouse())
    {
        abort_game("Mouse init Failed\n");
    }

    if (!al_init_image_addon())
    {
        abort_game("image init Failed\n");
    }

    al_init_font_addon(); // initialize the font addon

    al_init_ttf_addon();// initialize the ttf (True Type Font) addon 
    if (!al_init_ttf_addon())
    {
        abort_game("ttf addon init Failed\n");
    }

    timer = al_create_timer(1.0 / FPS);
    if (!timer)
        abort_game("Failed to create timer");

    al_set_new_display_flags(ALLEGRO_WINDOWED);
    display = al_create_display(screenW, screenH);
    if (!display)
        abort_game("Failed to create display");

    event_queue = al_create_event_queue();
    if (!event_queue)
        abort_game("Failed to create event queue");

    //Registering Allegro Events
    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_mouse_event_source());

    done = false;

    //creating bitmaps
   playerBitmap = al_create_bitmap(squareSize, squareSize);
   if(!playerBitmap) {
      fprintf(stderr, "failed to create playerBitmap bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      done = true;
   }

   crosshair = al_load_bitmap("data/crosshair.png");
   if(!crosshair) 
   {
      fprintf(stderr, "failed to create crosshair bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      done = true;
   }

   transporter = al_load_bitmap("data/transporter.png");
   if(!transporter) 
   {
      fprintf(stderr, "failed to create transporter bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      done = true;
   }

   tilesDungeon = al_load_bitmap("data/bigDungeonTiles.png");
   if(!crosshair) 
   {
      fprintf(stderr, "failed to load bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      done = true;
   }

   al_set_target_bitmap(playerBitmap);
   al_clear_to_color(al_map_rgb(255, 0, 255));
   al_set_target_bitmap(al_get_backbuffer(display));
   al_flip_display();

}
Ejemplo n.º 13
0
/* FUNCION INICIAR ALLEGRO */
void iniciar_allegro (){
  event_queue = NULL;
  display = NULL;
  timer = NULL;
  sample = NULL;
  redraw = true;

  
  /* Allegro */
  if (!al_init ()){
      al_show_native_message_box (display, "Error", "Error", "Error al cargar Allegro.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }
  
  /* Imágenes */
  if (!al_init_image_addon ()){
      al_show_native_message_box (display, "Error", "Error", "Error al cargar el addon de imágenes.", NULL, ALLEGRO_MESSAGEBOX_ERROR); 
      exit (EXIT_FAILURE);
  }
  
  /* Teclado */
  if (!al_install_keyboard()){
      al_show_native_message_box (display, "Error", "Error", "Error al inicializar el teclado.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  /* Timer */
  timer = al_create_timer (1.0 / FPS);
  if (!timer){
      al_show_native_message_box (display, "Error", "Error", "Error al crear un temporizador.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  /* Display */
  display = al_create_display (	ANCHO_VENTANA, ALTO_VENTANA);
  if (!display){
      al_destroy_timer (timer);
      al_show_native_message_box (display, "Error", "Error", "Error al crear el display.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }
  
  /* Cola de eventos */
  event_queue = al_create_event_queue ();
  if (!event_queue){
      al_destroy_timer (timer);
      al_destroy_display (display);
      al_show_native_message_box (display, "Error", "Error", "Error al crear la cola de eventos.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  /* Nombre ventana */
  al_set_window_title(display, "Skillful Driver");
  if (!al_set_window_title){
      al_show_native_message_box (display, "Error", "Error", "Error al poner título de ventana.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  /* Portada */
  portada = al_load_bitmap(PORTADA);

  /* Fuentes */
  al_init_font_addon();
  al_init_ttf_addon();
 /* if (!al_init_ttf_addon()){
      al_show_native_message_box (display, "Error", "Error", "Error al cargar las fuentes.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }*/
  font = al_load_ttf_font("UpheavalPro.ttf"/*"David Sans.ttf"*/, 30, 0);

  /* Icono del ejecutable - PROBANDO
  icon = al_load_bitmap("sprites/icono.png");
  al_set_display_icon(display, icon);
  */

  /* Música */
  if (!al_install_audio()){
      al_show_native_message_box (display, "Error", "Error", "Error de audio.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  if (!al_init_acodec_addon()){
      al_show_native_message_box (display, "Error", "Error", "Error de audio.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  if (!al_reserve_samples(1)){
      al_show_native_message_box (display, "Error", "Error", "Error al reservar el sample.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  sample = al_load_sample ("outrun.ogg");
  if (!sample){
      al_show_native_message_box (display, "Error", "Error", "Error al cargar el sample.", NULL, ALLEGRO_MESSAGEBOX_ERROR);
      exit (EXIT_FAILURE);
  }

  al_register_event_source (event_queue, al_get_timer_event_source (timer));
  al_register_event_source (event_queue, al_get_keyboard_event_source());
  al_register_event_source (event_queue, al_get_display_event_source (display));
  
  al_clear_to_color (al_map_rgb(255, 255, 255));
  al_draw_bitmap_region(portada, 0, 0, 400, 595, 0, 0, 0);
  al_draw_text (font, al_map_rgb(224, 224, 224), ANCHO_VENTANA/2, 495, ALLEGRO_ALIGN_CENTRE, "Cargando...");

  al_flip_display ();

  al_rest(5.0);
  
  al_start_timer (timer);
  
  al_play_sample (sample, 1.0, 0.0, 1.1, ALLEGRO_PLAYMODE_LOOP, NULL);
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
    ALLEGRO_DISPLAY *display;
    ALLEGRO_TIMER *timer;
    ALLEGRO_EVENT_QUEUE *queue;
    int redraw = 0;
    double t = 0;

    if (!al_init()) {
        abort_example("Could not init Allegro.\n");
    }

    open_log_monospace();

    al_init_primitives_addon();
    al_install_mouse();
    al_init_font_addon();
    al_init_ttf_addon();
    al_init_image_addon();
    init_platform_specific();

#ifdef ALLEGRO_IPHONE
    al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
#endif
    display = al_create_display(640, 480);
    if (!display) {
        abort_example("Could not create display.\n");
    }
    al_install_keyboard();

    if (argc >= 2) {
        font_file = argv[1];
    }

    ex.f1 = al_load_font(font_file, 48, 0);
    ex.f2 = al_load_font(font_file, 48, ALLEGRO_TTF_NO_KERNING);
    ex.f3 = al_load_font(font_file, 12, 0);
    /* Specifying negative values means we specify the glyph height
     * in pixels, not the usual font size.
     */
    ex.f4 = al_load_font(font_file, -140, 0);
    ex.f5 = al_load_font(font_file, 12, ALLEGRO_TTF_MONOCHROME);

    {
        int ranges[] = {0x1F40A, 0x1F40A};
        ALLEGRO_BITMAP *icon = al_load_bitmap("data/icon.png");
        ALLEGRO_BITMAP *glyph = al_create_bitmap(50, 50);
        al_set_target_bitmap(glyph);
        al_clear_to_color(al_map_rgba_f(0, 0, 0, 0));
        al_draw_rectangle(0.5, 0.5, 49.5, 49.5, al_map_rgb_f(1, 1, 0),
         1);
        al_draw_bitmap(icon, 1, 1, 0);
        al_set_target_backbuffer(display);
        ex.f_alex = al_grab_font_from_bitmap(glyph, 1, ranges);
    }

    if (!ex.f1 || !ex.f2 || !ex.f3 || !ex.f4 || !ex.f_alex) {
        abort_example("Could not load font: %s\n", font_file);
    }

    al_set_fallback_font(ex.f3, ex.f_alex);

    ex.ranges_count = al_get_font_ranges(ex.f1, 0, NULL);
    print_ranges(ex.f1);

    ex.config = al_load_config_file("data/ex_ttf.ini");
    if (!ex.config) {
        abort_example("Could not data/ex_ttf.ini\n");
    }

    timer = al_create_timer(1.0 / 60);

    queue = al_create_event_queue();
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_timer_event_source(timer));

    al_start_timer(timer);
    while (true) {
        ALLEGRO_EVENT event;
        al_wait_for_event(queue, &event);
        if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            break;
        if (event.type == ALLEGRO_EVENT_KEY_DOWN &&
                event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
            break;
        }
        if (event.type == ALLEGRO_EVENT_TIMER)
            redraw++;

        while (redraw > 0 && al_is_event_queue_empty(queue)) {
            double dt;
            redraw--;

            dt = al_get_time();
            render();
            dt = al_get_time() - dt;

            t = 0.99 * t + 0.01 * dt;

            ex.fps = 1.0 / t;
            al_flip_display();
        }
    }

    al_destroy_font(ex.f1);
    al_destroy_font(ex.f2);
    al_destroy_font(ex.f3);
    al_destroy_font(ex.f4);
    al_destroy_font(ex.f5);
    al_destroy_config(ex.config);

    close_log(false);

    return 0;
}
Ejemplo n.º 15
0
Archivo: main.c Proyecto: dos1/bttbw
int main(int argc, char **argv){
	signal(SIGSEGV, derp);

	srand(time(NULL));

	al_set_org_name("Super Derpy");
    al_set_app_name("Back to the Browser Wars");

       #ifdef ALLEGRO_MACOSX
       char exe_path[MAXPATHLEN];
       char link_path[MAXPATHLEN];

       uint32_t size = sizeof(exe_path);
       _NSGetExecutablePath(exe_path, &size);
       realpath(exe_path, link_path);
       chdir(link_path);
       #endif

	if(!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	struct Game game;

	InitConfig(&game);

	game._priv.fps_count.frames_done = 0;
	game._priv.fps_count.fps = 0;
	game._priv.fps_count.old_time = 0;

	game._priv.font_bsod = NULL;
	game._priv.console = NULL;

	game.config.fullscreen = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "fullscreen", "0"));
	game.config.music = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "music", "10"));
	game.config.voice = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "voice", "10"));
	game.config.fx = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "fx", "10"));
	game.config.debug = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "debug", "0"));
	game.config.width = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "width", "1280"));
	if (game.config.width<320) game.config.width=320;
	game.config.height = atoi(GetConfigOptionDefault(&game, "SuperDerpy", "height", "720"));
	if (game.config.height<180) game.config.height=180;

	if(!al_init_image_addon()) {
		fprintf(stderr, "failed to initialize image addon!\n");
		/*al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!",
															 NULL, ALLEGRO_MESSAGEBOX_ERROR);*/
		return -1;
	}

	if(!al_init_acodec_addon()){
		fprintf(stderr, "failed to initialize audio codecs!\n");
		return -1;
	}

	if(!al_install_audio()){
		fprintf(stderr, "failed to initialize audio!\n");
		return -1;
	}

	if(!al_install_keyboard()){
		fprintf(stderr, "failed to initialize keyboard!\n");
		return -1;
	}

	if(!al_init_primitives_addon()){
		fprintf(stderr, "failed to initialize primitives!\n");
		return -1;
	}

    if(!al_install_mouse()) {
        fprintf(stderr, "failed to initialize the mouse!\n");
        return -1;
    }
	
	al_init_font_addon();

	if(!al_init_ttf_addon()){
		fprintf(stderr, "failed to initialize fonts!\n");
		return -1;
	}

	if (game.config.fullscreen) al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
	else al_set_new_display_flags(ALLEGRO_WINDOWED);
	al_set_new_display_option(ALLEGRO_VSYNC, 2-atoi(GetConfigOptionDefault(&game, "SuperDerpy", "vsync", "1")), ALLEGRO_SUGGEST);
	al_set_new_display_option(ALLEGRO_OPENGL, atoi(GetConfigOptionDefault(&game, "SuperDerpy", "opengl", "1")), ALLEGRO_SUGGEST);
#ifdef ALLEGRO_WINDOWS
	al_set_new_window_position(20, 40); // workaround nasty Windows bug with window being created off-screen
#endif

	game.display = al_create_display(game.config.width, game.config.height);
	if(!game.display) {
		fprintf(stderr, "failed to create display!\n");
		return -1;
	}

	SetupViewport(&game);

	PrintConsole(&game, "Viewport %dx%d", game.viewport.width, game.viewport.height);

    ALLEGRO_BITMAP *icon = al_load_bitmap(GetDataFilePath(&game, "icons/bttbw.png"));
	al_set_window_title(game.display, "Back to the Browser Wars");
	al_set_display_icon(game.display, icon);
	al_destroy_bitmap(icon);

    if (game.config.fullscreen) al_hide_mouse_cursor(game.display);
    al_inhibit_screensaver(true);

	al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR);

	game._priv.gamestates = NULL;

	game._priv.event_queue = al_create_event_queue();
	if(!game._priv.event_queue) {
		FatalError(&game, true, "Failed to create event queue.");
		al_destroy_display(game.display);
		return -1;
	}

	game.audio.v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
	game.audio.mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.fx = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.music = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	game.audio.voice = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	al_attach_mixer_to_voice(game.audio.mixer, game.audio.v);
	al_attach_mixer_to_mixer(game.audio.fx, game.audio.mixer);
	al_attach_mixer_to_mixer(game.audio.music, game.audio.mixer);
	al_attach_mixer_to_mixer(game.audio.voice, game.audio.mixer);
	al_set_mixer_gain(game.audio.fx, game.config.fx/10.0);
	al_set_mixer_gain(game.audio.music, game.config.music/10.0);
	al_set_mixer_gain(game.audio.voice, game.config.voice/10.0);

	al_register_event_source(game._priv.event_queue, al_get_display_event_source(game.display));
    al_register_event_source(game._priv.event_queue, al_get_mouse_event_source());
    al_register_event_source(game._priv.event_queue, al_get_keyboard_event_source());

	game._priv.showconsole = game.config.debug;

	al_clear_to_color(al_map_rgb(0,0,0));
	game._priv.timer = al_create_timer(ALLEGRO_BPS_TO_SECS(60)); // logic timer
	if(!game._priv.timer) {
		FatalError(&game, true, "Failed to create logic timer.");
		return -1;
	}
	al_register_event_source(game._priv.event_queue, al_get_timer_event_source(game._priv.timer));

	al_flip_display();
	al_start_timer(game._priv.timer);

	setlocale(LC_NUMERIC, "C");

	game.shuttingdown = false;
	game.restart = false;

    game.mediator.lives = 3;
    game.mediator.score = 0;
    game.mediator.modificator = 1;

    game.mediator.heart = CreateCharacter(&game, "heart");
    RegisterSpritesheet(&game, game.mediator.heart, "heart");
    RegisterSpritesheet(&game, game.mediator.heart, "blank");
    LoadSpritesheets(&game, game.mediator.heart);
    SelectSpritesheet(&game, game.mediator.heart, "heart");

	char* gamestate = strdup("dosowisko"); // FIXME: don't hardcore gamestate

	int c;
	while ((c = getopt (argc, argv, "l:s:")) != -1)
		switch (c) {
			case 'l':
				free(gamestate);
				gamestate = strdup("levelX");
				gamestate[5] = optarg[0];
				break;
			case 's':
				free(gamestate);
				gamestate = strdup(optarg);
				break;
		}

	LoadGamestate(&game, gamestate);
    game._priv.gamestates->showLoading = false; // we have only one gamestate right now
    StartGamestate(&game, gamestate);
	free(gamestate);

	char libname[1024] = {};
    snprintf(libname, 1024, "libsuperderpy-%s-loading" LIBRARY_EXTENTION, "bttbw");
	void *handle = dlopen(libname, RTLD_NOW);
	if (!handle) {
		FatalError(&game, true, "Error while initializing loading screen %s", dlerror());
		exit(1);
	} else {

		#define GS_LOADINGERROR FatalError(&game, true, "Error on resolving loading symbol: %s", dlerror()); exit(1);

		if (!(game._priv.loading.Draw = dlsym(handle, "Draw"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Load = dlsym(handle, "Load"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Start = dlsym(handle, "Start"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Stop = dlsym(handle, "Stop"))) { GS_LOADINGERROR; }
		if (!(game._priv.loading.Unload = dlsym(handle, "Unload"))) { GS_LOADINGERROR; }
	}

	game._priv.loading.data = (*game._priv.loading.Load)(&game);

	bool redraw = false;

	while(1) {
		ALLEGRO_EVENT ev;
		if (redraw && al_is_event_queue_empty(game._priv.event_queue)) {

			struct Gamestate *tmp = game._priv.gamestates;
			int toLoad = 0, loaded = 0;

			// FIXME: move to function
			// TODO: support dependences
			while (tmp) {
				if ((tmp->pending_start) && (tmp->started)) {
					PrintConsole(&game, "Stopping gamestate \"%s\"...", tmp->name);
					(*tmp->api.Gamestate_Stop)(&game, tmp->data);
					tmp->started = false;
					tmp->pending_start = false;
				}

				if ((tmp->pending_load) && (!tmp->loaded)) toLoad++;
				tmp=tmp->next;
			}

			tmp = game._priv.gamestates;
			// FIXME: move to function
			// TODO: support dependences

			double t = -1;

			while (tmp) {
				if ((tmp->pending_load) && (tmp->loaded)) {
					PrintConsole(&game, "Unloading gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					tmp->loaded = false;
					tmp->pending_load = false;
					(*tmp->api.Gamestate_Unload)(&game, tmp->data);
					dlclose(tmp->handle);
					tmp->handle = NULL;
					al_start_timer(game._priv.timer);
				} else if ((tmp->pending_load) && (!tmp->loaded)) {
					PrintConsole(&game, "Loading gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					// TODO: take proper game name
					char libname[1024];
                    snprintf(libname, 1024, "libsuperderpy-%s-%s" LIBRARY_EXTENTION, "bttbw", tmp->name);
					tmp->handle = dlopen(libname,RTLD_NOW);
					if (!tmp->handle) {
						//PrintConsole(&game, "Error while loading gamestate \"%s\": %s", tmp->name, dlerror());
						FatalError(&game, false, "Error while loading gamestate \"%s\": %s", tmp->name, dlerror());

						tmp->pending_load = false;
						tmp->pending_start = false;
					} else {

#define GS_ERROR FatalError(&game, false, "Error on resolving gamestate symbol: %s", dlerror()); tmp->pending_load = false; tmp->pending_start = false; tmp=tmp->next; continue;

						if (!(tmp->api.Gamestate_Draw = dlsym(tmp->handle, "Gamestate_Draw"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Logic = dlsym(tmp->handle, "Gamestate_Logic"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_Load = dlsym(tmp->handle, "Gamestate_Load"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Start = dlsym(tmp->handle, "Gamestate_Start"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Pause = dlsym(tmp->handle, "Gamestate_Pause"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Resume = dlsym(tmp->handle, "Gamestate_Resume"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Stop = dlsym(tmp->handle, "Gamestate_Stop"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Unload = dlsym(tmp->handle, "Gamestate_Unload"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_ProcessEvent = dlsym(tmp->handle, "Gamestate_ProcessEvent"))) { GS_ERROR; }
						if (!(tmp->api.Gamestate_Reload = dlsym(tmp->handle, "Gamestate_Reload"))) { GS_ERROR; }

						if (!(tmp->api.Gamestate_ProgressCount = dlsym(tmp->handle, "Gamestate_ProgressCount"))) { GS_ERROR; }

						int p = 0;

						void progress(struct Game *game) {
							p++;
							DrawGamestates(game);
							float progress = ((p / (*(tmp->api.Gamestate_ProgressCount) ? (float)*(tmp->api.Gamestate_ProgressCount) : 1))/(float)toLoad)+(loaded/(float)toLoad);
							if (game->config.debug) PrintConsole(game, "[%s] Progress: %d% (%d/%d)", tmp->name, (int)(progress*100), p, *(tmp->api.Gamestate_ProgressCount));
							if (tmp->showLoading) (*game->_priv.loading.Draw)(game, game->_priv.loading.data, progress);
							DrawConsole(game);
							if (al_get_time() - t >= 1/60.0) {
								al_flip_display();
							}
							t = al_get_time();
						}

						t = al_get_time();

						// initially draw loading screen with empty bar
						DrawGamestates(&game);
						if (tmp->showLoading) {
                            (*game._priv.loading.Draw)(&game, game._priv.loading.data, loaded/(float)toLoad);
						}
						DrawConsole(&game);
						if (al_get_time() - t >= 1/60.0) {
							al_flip_display();
						}
						t = al_get_time();
						tmp->data = (*tmp->api.Gamestate_Load)(&game, &progress); // feel free to replace "progress" with empty function if you want to compile with clang
						loaded++;

						tmp->loaded = true;
						tmp->pending_load = false;
					}
					al_start_timer(game._priv.timer);
				}

				tmp=tmp->next;
			}

			bool gameActive = false;
			tmp=game._priv.gamestates;

			while (tmp) {

				if ((tmp->pending_start) && (!tmp->started) && (tmp->loaded)) {
					PrintConsole(&game, "Starting gamestate \"%s\"...", tmp->name);
					al_stop_timer(game._priv.timer);
					(*tmp->api.Gamestate_Start)(&game, tmp->data);
					al_start_timer(game._priv.timer);
					tmp->started = true;
					tmp->pending_start = false;
				}

				if ((tmp->started) || (tmp->pending_start) || (tmp->pending_load)) gameActive = true;
				tmp=tmp->next;
			}

			if (!gameActive) {
				PrintConsole(&game, "No gamestates left, exiting...");
				break;
			}

			DrawGamestates(&game);
			DrawConsole(&game);
			al_flip_display();
			redraw = false;

		} else {
Ejemplo n.º 16
0
int main(int argc, char **argv) {
	ALLEGRO_DISPLAY *display=NULL;
	ALLEGRO_EVENT_QUEUE *event=NULL;
	ALLEGRO_TIMER *timer=NULL;
	ALLEGRO_BITMAP *foreground=NULL;
	bool redraw = false;
	
	if(!al_init()) {
      al_show_native_message_box(display, "Error", "Error", "Failed to initialize allegro!", 
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
      return 0;
   }
 
   if(!al_init_image_addon()) {
      al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!", 
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
      return 0;
   }
 
   display = al_create_display(800,600);
 
   if(!display) {
      al_show_native_message_box(display, "Error", "Error", "Failed to initialize display!", 
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
      return 0;
   }
 
   foreground = al_load_bitmap("Foreground.png");
 
   if(!foreground) {
      al_show_native_message_box(display, "Error", "Error", "Failed to load image!", 
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
      al_destroy_display(display);
      return 0;
   }
   al_register_event_source(event, al_get_display_event_source(display));
 
   al_register_event_source(event, al_get_timer_event_source(timer));
 
   al_clear_to_color(al_map_rgb(0,0,0));
   
   al_draw_bitmap(foreground,200,200,0);
 
   al_flip_display();
 
   //al_start_timer(timer);
   
 	//while(1) {
 		//ALLEGRO_EVENT ev;
 		//al_wait_for_event(event, &ev);
 		
 		//if(ev.type == ALLEGRO_EVENT_TIMER) {
         	//redraw = true;
      	//}
      	//else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         //	break;
      	//}
 
      	//if(redraw && al_is_event_queue_empty(event)) {
         //	redraw = false;
    
         	//al_flip_display();
      	//}
   //}
 
   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_bitmap(foreground);
   al_destroy_event_queue(event);
	
	return 0;
}
Ejemplo n.º 17
0
int main() {
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("nao foi possivel inicializar camera");

  int largura = cam->largura;
  int altura = cam->altura;

  if(!al_init())
    erro("nao foi possivel inicializar allegro");

  if(!al_init_primitives_addon())
    erro("nao foi possivel inicializar adicional de primitivas");

  if(!al_init_image_addon())
    erro("nao foi possivel inicializar a adicional de imagem ");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("nao foi possivel criar fila de eventos");

  ALLEGRO_DISPLAY *display = al_create_display(2 * largura, altura * 2);
  if(!display)
    erro("nao foi possivel criar janela");

  al_register_event_source(queue, al_get_display_event_source(display));

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("nao foi possivel criar relogio");

  al_register_event_source(queue, al_get_timer_event_source(timer));

  /**********/

  unsigned char ***matriz = camera_aloca_matriz(cam);
  unsigned char ***anterior;

  ALLEGRO_COLOR cor = al_map_rgb_f(0, 0, 1);

  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);

  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);

  ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura, 0, largura, altura);

  ALLEGRO_BITMAP * baixo = al_create_sub_bitmap(buffer, largura/2, altura, largura, altura);

  sniper = al_load_bitmap("semi.png");

  /**********/

  int continuar = 1;
  int atualizar = 0;

  al_start_timer(timer);

  while(continuar) {
    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      continuar = 0;
      break;
    case ALLEGRO_EVENT_TIMER:
      atualizar = 1;
      break;
    }

    if(atualizar && al_is_event_queue_empty(queue)) {
      camera_atualiza(cam);

      /**********/

      int cy = 0;
      int cx = 0;
      int cn = 0;

      for(int y = 0; y < altura; y++)
        for(int x = 0; x < largura; x++) {
          float r = (cam->quadro[y][x][0]) / 255;
          float g = (cam->quadro[y][x][1]) / 255;
          float b = (cam->quadro[y][x][2]) / 255;

          /*if(compara_imagem(cam, matriz, anterior)) {
            cy += y;
            cx += x;
            cn += 1;

            matriz[y][x][0] = 255;
            matriz[y][x][1] = 255;
            matriz[y][x][2] = 255;
          }
          else {
            matriz[y][x][0] = 0;
            matriz[y][x][1] = 0;
            matriz[y][x][2] = 0;
          }
        }
        */

      anterior = compara_imagem(cam, matriz, anterior);
        //int x1 = cx / cn;
        //int y1 = cy / cn;
        
      /**********/
      }
      camera_copia(cam, cam->quadro, esquerda);
      camera_copia(cam, matriz, direita);
      camera_copia(cam, anterior, baixo);   
      if(cn > 0){
        //al_draw_circle(cx / cn, cy / cn, 120, cor, 1);
        //al_draw_bitmap(sniper, cx / cn, cy / cn, 120);
        // SNIPER al_draw_bitmap(sniper, cx / cn - 400, cy / cn - 300, 120);
        

      camera_copia(cam, cam->quadro, direita);

      /**********/

      al_flip_display();

      atualizar = 0;
    }
  }
}
  al_stop_timer(timer);

  /**********/

  al_destroy_bitmap(direita);

  al_destroy_bitmap(esquerda);

  camera_libera_matriz(cam, matriz);

  /**********/

  al_unregister_event_source(queue, al_get_timer_event_source(timer));
  al_destroy_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_destroy_display(display);

  al_destroy_event_queue(queue);
  al_shutdown_primitives_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;


}
Ejemplo n.º 18
0
billiard_ball *create_billiard_balls()
{
	int i;
	const int key_size = 256;
	char key[key_size];
	billiard_ball *balls = malloc(sizeof(billiard_ball) * BALL_COUNT);
	ALLEGRO_CONFIG *config = al_load_config_file(BCONFIG_FPATH);

	if(!balls)
	{
		perror("fail to malloc for billiard balls");
		return NULL;
	}

	if(!config)
	{
		perror("fail to load billiard_ball.config");
		free(balls);
		return NULL;
	}

	for(i = 0 ; i < BALL_COUNT ; i ++)
	{
		balls[i].number = i;
		balls[i].is_on_table = 1;
		balls[i].dx = 0;
		balls[i].dy = 0;

		// prepare the key for reading config file
		memset(key, '\0', key_size);
		sprintf(key, "ball%d", i);

		// read the score for each ball
		balls[i].score = atoi(al_get_config_value(config, key, "score"));

		// read the bitmap
		balls[i].bitmap = al_load_bitmap(
				al_get_config_value(config, "pictures", key));
		if(!balls[i].bitmap)
		{
			perror("fail to load billiard ball bitmap");
			free(balls);
			return NULL;
		}
		// load in bitmap width and height
		balls[i].bitmap_sw = al_get_bitmap_width(balls[i].bitmap);
		balls[i].bitmap_sh = al_get_bitmap_height(balls[i].bitmap);

		// read the initial position
		balls[i].cx = atof(al_get_config_value(config, key, "start_x"));
		balls[i].cy = atof(al_get_config_value(config, key, "start_y"));

		// read the collision sound file
		balls[i].collision_sound = al_load_sample(
				al_get_config_value(config, key, "collision_sound"));
		if(!balls[i].collision_sound)
		{
			perror("fail to load billiard ball collision sound");
			al_destroy_bitmap(balls[i].bitmap);
			free(balls);
			return NULL;
		}
	}

	/* DEBUG
	// ball colors
	balls[0].color = al_map_rgb(255, 255, 255);
	balls[1].color = al_map_rgb(255, 191, 0);
	balls[2].color = al_map_rgb(0, 0, 255);
	balls[3].color = al_map_rgb(255, 0, 0);
	balls[4].color = al_map_rgb(191, 0, 255);
	balls[5].color = al_map_rgb(255, 128, 0);
	balls[6].color = al_map_rgb(1, 225, 1);
	balls[7].color = al_map_rgb(138, 8, 8);
	balls[8].color = al_map_rgb(0, 0, 0);
	*/

	/* DEBUG
	balls[0].cx = 600;
	balls[0].cy = TABLE_Y_POSITION + TABLE_HEIGHT / 2;

	balls[1].cx = 260;
	balls[1].cy = TABLE_Y_POSITION + TABLE_HEIGHT / 2;

	balls[2].cx = balls[1].cx - 2 * BILLIARD_BALL_RADIUS * cos(PI / 6);
	balls[2].cy = balls[1].cy - 2 * BILLIARD_BALL_RADIUS * sin(PI / 6);

	balls[3].cx = balls[1].cx - 2 * BILLIARD_BALL_RADIUS * cos(PI / 6);
	balls[3].cy = balls[1].cy + 2 * BILLIARD_BALL_RADIUS * sin(PI / 6);

	for(i = 4 ; i <= 6 ; i ++)
		balls[i].cx = balls[1].cx - 4 * BILLIARD_BALL_RADIUS * cos(PI / 6);
	balls[4].cy = balls[1].cy - 2 * BILLIARD_BALL_RADIUS;
	balls[5].cy = balls[1].cy;
	balls[6].cy = balls[1].cy + 2 * BILLIARD_BALL_RADIUS;

	for(i = 7 ; i <= 8 ; i ++)
	{
		balls[i].cx = balls[i - 5].cx - 4 * BILLIARD_BALL_RADIUS * cos(PI / 6);
		balls[i].cy = balls[i - 5].cy;
	}
	*/
	// destroy the config file handler
	al_destroy_config(config);
	return balls;
}
Ejemplo n.º 19
0
int main(void)
{
	//primitive variable
	const int FPS = 60;
	bool done = false;
	bool redraw = true;
	bool isGameOver = false;

	//object variables
	struct SpaceShip ship;
	struct Bullet bullets[NUM_BULLETS];
	struct Comet comets[NUM_COMETS];

	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *shipImage;
	ALLEGRO_BITMAP *cometImage;
	ALLEGRO_BITMAP *bulletImage;

	ALLEGRO_FONT *font = NULL;
	ALLEGRO_PATH *font_path;

	//Initialization Functions
	if (!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(WIDTH, HEIGHT);		//create our display object

	if (!display)										//test display object
		return -1;

	// inicio inicializacao fontes
	al_init_image_addon();

	font_path = get_resources_path();
	al_set_path_filename(font_path, "a4_font.tga");

	al_init_font_addon();
	al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
	font = al_load_bitmap_font(al_path_cstr(font_path, '/'));
	if (!font)
	{
		return 1;
	}

	al_destroy_path(font_path);
	// termino inicializacao fontes

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_image_addon();

	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);

	shipImage = al_load_bitmap("spaceship_by_arboris.png");
	al_convert_mask_to_alpha(shipImage, al_map_rgb(255, 0, 255));

	bulletImage = al_load_bitmap("bullets_by_arboris.png");
	al_convert_mask_to_alpha(bulletImage, al_map_rgb(255, 0, 255));

	cometImage = al_load_bitmap("asteroid-1-96.png");

	srand(time(NULL ));

	//Game Init
	ship = InitShip(shipImage);

	// init bullets
	int i = 0;
	while (i < NUM_BULLETS)
	{
		bullets[i].ID = BULLET;
		bullets[i].speed = 10;
		bullets[i].live = false;

		bullets[i].maxFrame = 143;
		bullets[i].curFrame = 0;
		bullets[i].frameCount = 0;
		bullets[i].frameDelay = 2;
		bullets[i].frameWidth = 20;
		bullets[i].frameHeight = 10;
		bullets[i].animationColumns = 1;

		bullets[i].animationRow = 1;

		bullets[i].image = bulletImage;

		i++;
	}

	// init comets
	i = 0;
	while (i < NUM_COMETS)
	{
		comets[i].ID = ENEMY;
		comets[i].live = false;
		comets[i].speed = 5;
		comets[i].boundx = 35;
		comets[i].boundy = 35;

		comets[i].maxFrame = 143;
		comets[i].curFrame = 0;
		comets[i].frameCount = 0;
		comets[i].frameDelay = 2;
		comets[i].frameWidth = 96;
		comets[i].frameHeight = 96;
		comets[i].animationColumns = 21;

		if (rand() % 2)
			comets[i].animationDirection = 1;
		else
			comets[i].animationDirection = -1;

		comets[i].image = cometImage;

		i++;
	}

	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_start_timer(timer);

	while (!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			redraw = true;
			if (keys[UP])
				ship = MoveShipUp(ship);
			else if (keys[DOWN])
				ship = MoveShipDown(ship);
			else
				ship = ResetShipAnimation(ship, 1);

			if (keys[LEFT])
				ship = MoveShipLeft(ship);
			else if (keys[RIGHT])
				ship = MoveShipRight(ship);
			else
				ship = ResetShipAnimation(ship, 2);

			if (!isGameOver)
			{
				//UpdateBullet
				int i = 0;
				while (i < NUM_BULLETS)
				{
					if (bullets[i].live)
					{
						bullets[i].x += bullets[i].speed;
						if (bullets[i].x > WIDTH)
							bullets[i].live = false;
					}

					i++;
				}

				// start comet
				i = 0;
				while (i < NUM_COMETS)
				{
					if (!comets[i].live)
					{
						if (rand() % 500 == 0)
						{
							comets[i].live = true;
							comets[i].x = WIDTH;
							comets[i].y = 30 + rand() % (HEIGHT - 60);

							break;
						}
					}

					i++;
				}

				// UpdateComet(Comet comets[], int size)
				i = 0;
				while (i < NUM_COMETS)
				{
					if (comets[i].live)
					{
						if (++comets[i].frameCount >= comets[i].frameDelay)
						{
							comets[i].curFrame += comets[i].animationDirection;
							if (comets[i].curFrame >= comets[i].maxFrame)
								comets[i].curFrame = 0;
							else if (comets[i].curFrame <= 0)
								comets[i].curFrame = comets[i].maxFrame - 1;

							comets[i].frameCount = 0;
						}

						comets[i].x -= comets[i].speed;
					}

					i++;
				}

				// collide bullet
				i = 0;
				while (i < NUM_BULLETS)
				{
					if (bullets[i].live)
					{
						int j = 0;
						while (j < NUM_COMETS)
						{
							if (comets[j].live)
							{
								if (bullets[i].x
										> (comets[j].x - comets[j].boundx)
										&& bullets[i].x
												< (comets[j].x
														+ comets[j].boundx)
										&& bullets[i].y
												> (comets[j].y
														- comets[j].boundy)
										&& bullets[i].y
												< (comets[j].y
														+ comets[j].boundy))
								{
									bullets[i].live = false;
									comets[j].live = false;

									ship.score++;
								}
							}

							j++;
						}
					}

					i++;
				}

				// collide comet
				i = 0;
				while (i < NUM_COMETS)
				{
					if (comets[i].live)
					{
						if (comets[i].x - comets[i].boundx
								< ship.x + ship.boundx
								&& comets[i].x + comets[i].boundx
										> ship.x - ship.boundx
								&& comets[i].y - comets[i].boundy
										< ship.y + ship.boundy
								&& comets[i].y + comets[i].boundy
										> ship.y - ship.boundy)
						{
							ship.lives--;
							comets[i].live = false;
						}
						else if (comets[i].x < 0)
						{
							comets[i].live = false;
							ship.lives--;
						}
					}

					i++;
				}

				if (ship.lives <= 0)
					isGameOver = true;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;

				//FireBullet
				int i = 0;
				while (i < NUM_BULLETS)
				{
					if (!bullets[i].live)
					{
						bullets[i].x = ship.x + 17;
						bullets[i].y = ship.y;
						bullets[i].live = true;
						break;
					}

					i++;
				}

				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}

		if (redraw && al_is_event_queue_empty(event_queue))
		{
			redraw = false;

			if (!isGameOver)
			{
				DrawShip(ship);
				DrawBullet(bullets, NUM_BULLETS);
				DrawComet(comets, NUM_COMETS);
				al_draw_textf(font, al_map_rgb(255, 0, 255), 5, 5, 0,
						"Player has %i lives left. Player has destroyed %i objects",
						ship.lives, ship.score);
			}
			else
			{
				al_draw_textf(font, al_map_rgb(0, 255, 255), WIDTH / 2,
						HEIGHT / 2, ALLEGRO_ALIGN_CENTRE,
						"Game Over. Final Score: %i", ship.score);
			}

			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
		}
	}

	al_destroy_bitmap(bulletImage);
	al_destroy_bitmap(cometImage);
	al_destroy_bitmap(shipImage);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font);
	al_destroy_display(display);					//destroy our display object

	return 0;
}
Ejemplo n.º 20
0
void Prog::draw_sample()
{
   const int i = source_list.get_cur_value();
   const int j = dest_list.get_cur_value();
   ALLEGRO_BITMAP *bitmap1;
   ALLEGRO_BITMAP *bitmap2;
   bool use_memory = use_memory_button.get_pushed();
   bool enable_timing = enable_timing_button.get_pushed();
   
   if (use_memory)
      al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   else
      al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);

   al_set_new_bitmap_format(formats[i].format);

   bitmap1 = al_load_bitmap("data/allegro.pcx");
   if (!bitmap1) {
      printf("Could not load image, bitmap format = %d\n", formats[i].format);
   }

   al_set_new_bitmap_format(formats[j].format);

   bitmap2 = al_create_bitmap(320, 200);
   if (!bitmap2) {
      printf("Could not create bitmap, format = %d\n", formats[j].format);
   }

   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);

   if (bitmap1 && bitmap2) {
      ALLEGRO_BITMAP *target = al_get_target_bitmap();

      al_set_target_bitmap(bitmap2);
      if (enable_timing) {
         double t0, t1;
         char str[256];
         int frames = 0;

         t0 = al_get_time();
         printf("Timing...\n");
         do {
           al_draw_bitmap(bitmap1, 0, 0, 0);
           frames++;
           t1 = al_get_time();
         } while (t1 - t0 < 0.25);
         printf("    ...done.\n");
         sprintf(str, "%.0f FPS", (double)frames / (t1 - t0));
         time_label.set_text(str);
      }
      else {
         al_draw_bitmap(bitmap1, 0, 0, 0);
         time_label.set_text("");
      }

      al_set_target_bitmap(target);
      al_draw_bitmap(bitmap2, 0, 0, 0);
   }
   else {
      al_draw_line(0, 0, 320, 200, al_map_rgb_f(1, 0, 0), 0);
      al_draw_line(0, 200, 320, 0, al_map_rgb_f(1, 0, 0), 0);
   }

   std::string s = get_format_name(bitmap1);
   s += " -> ";
   s += get_format_name(bitmap2);
   true_formats.set_text(s);

   al_destroy_bitmap(bitmap1);
   al_destroy_bitmap(bitmap2);
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   bool redraw = true;
   ALLEGRO_FONT *font;
   ALLEGRO_BITMAP *spin, *spin2;
   int current_bitmap = 0;
   int loaded_bitmap = 0;
   ALLEGRO_THREAD *thread;

   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   al_init_image_addon();
   al_init_font_addon();
   al_init_primitives_addon();
   init_platform_specific();

   open_log();

   al_install_mouse();
   al_install_keyboard();

   spin = al_load_bitmap("data/cursor.tga");
   log_printf("default bitmap without display: %p\n", spin);

   al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
   spin2 = al_load_bitmap("data/cursor.tga");
   log_printf("video bitmap without display: %p\n", spin2);
   
   log_printf("%p before create_display: ", spin);
   print_bitmap_flags(spin);
   log_printf("\n");

   display = al_create_display(64, 64);
   if (!display) {
      abort_example("Error creating display\n");
   }
   
   spin2 = al_load_bitmap("data/cursor.tga");
   log_printf("video bitmap with display: %p\n", spin2);
   
   log_printf("%p after create_display: ", spin);
   print_bitmap_flags(spin);
   log_printf("\n");
   
   log_printf("%p after create_display: ", spin2);
   print_bitmap_flags(spin2);
   log_printf("\n");

   al_destroy_display(display);
   
   log_printf("%p after destroy_display: ", spin);
   print_bitmap_flags(spin);
   log_printf("\n");
   
   log_printf("%p after destroy_display: ", spin2);
   print_bitmap_flags(spin2);
   log_printf("\n");

   display = al_create_display(640, 480);
   
   log_printf("%p after create_display: ", spin);
   print_bitmap_flags(spin);
   log_printf("\n");
   
   log_printf("%p after create_display: ", spin2);
   print_bitmap_flags(spin2);
   log_printf("\n");

   font = al_load_font("data/fixed_font.tga", 0, 0);

   mutex = al_create_mutex();
   thread = al_create_thread(loading_thread, NULL);
   al_start_thread(thread);

   timer = al_create_timer(1.0 / 30);
   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));
   al_register_event_source(queue, al_get_timer_event_source(timer));
   al_start_timer(timer);

   while (1) {
      ALLEGRO_EVENT event;
      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
         break;
      if (event.type == ALLEGRO_EVENT_KEY_DOWN) {
         if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
             break;
         }
      if (event.type == ALLEGRO_EVENT_TIMER)
         redraw = true;

      if (redraw && al_is_event_queue_empty(queue)) {
         float x = 20, y = 320;
         int i;
         ALLEGRO_COLOR color = al_map_rgb_f(0, 0, 0);
         float t = al_current_time();

         redraw = false;
         al_clear_to_color(al_map_rgb_f(0.5, 0.6, 1));
         
         al_draw_textf(font, color, x + 40, y, 0, "Loading %d%%",
            100 * load_count / load_total);

         al_lock_mutex(mutex);
         if (loaded_bitmap < load_count) {
            /* This will convert any video bitmaps without a display
             * (all the bitmaps being loaded in the loading_thread) to
             * video bitmaps we can use in the main thread.
             */
            al_convert_bitmap(bitmaps[loaded_bitmap]);
            loaded_bitmap++;
         }
         al_unlock_mutex(mutex);

         if (current_bitmap < loaded_bitmap) {
            int bw;
            al_draw_bitmap(bitmaps[current_bitmap], 0, 0, 0);
            if (current_bitmap + 1 < loaded_bitmap)
               current_bitmap++;

            for (i = 0; i <= current_bitmap; i++) {
               bw = al_get_bitmap_width(bitmaps[i]);
               al_draw_scaled_rotated_bitmap(bitmaps[i],
                  0, 0, (i % 20) * 640 / 20, 360 + (i / 20) * 24,
                  32.0 / bw, 32.0 / bw, 0, 0);
            }
         }
         
         if (loaded_bitmap < load_total) {
            al_draw_scaled_rotated_bitmap(spin,
               16, 16, x, y, 1.0, 1.0, t * ALLEGRO_PI * 2, 0);
         }
         
         al_flip_display();
      }
   }

   al_join_thread(thread, NULL);
   al_destroy_mutex(mutex);
   al_destroy_font(font); 
   al_destroy_display(display);

   close_log(true);

   return 0;
}
Ejemplo n.º 22
0
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *cursor;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   ALLEGRO_FONT *font;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT touch_events[MAX_TOUCHES];
   int touch = 0;
   bool in = true;
   bool down = false;
   int i;
   
   memset(touch_events, 0, sizeof(touch_events));
   
   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   al_init_primitives_addon();
   al_install_mouse();
   al_init_image_addon();
   al_init_font_addon();

   display = al_create_display(480, 320);
   if (!display) {
      abort_example("Error creating display\n");
   }

   al_hide_mouse_cursor();

   cursor = al_load_bitmap("data/cursor.tga");
   if (!cursor) {
      abort_example("Error loading cursor.tga\n");
   }

   font = al_load_font("data/fixed_font.tga", 1, 0);
   if (!font) {
      abort_example("data/fixed_font.tga not found\n");
   }

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));
   
   timer = al_create_timer(1/10.0);
   al_register_event_source(queue, al_get_timer_event_source(timer));
   al_start_timer(timer);

   while (1) {
      al_wait_for_event(queue, &event);
         switch (event.type) {
         case ALLEGRO_EVENT_MOUSE_AXES:
            touch_events[touch] = event;
            touch++;
            touch %= MAX_TOUCHES;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            down = true;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            down = false;
            break;

         case ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY:
            in = true;
            break;

         case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
            in = false;
            break;

         case ALLEGRO_EVENT_TIMER:
            al_clear_to_color(al_map_rgb(0xff, 0xff, 0xc0));
            if (down) {
               for (i = 0; i < MAX_TOUCHES; i++) {
                  al_draw_bitmap(cursor, touch_events[i].mouse.x, touch_events[i].mouse.y, 0);
               }
            }
            al_flip_display();
            break;
               
         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            goto done;
         }
   }

done:

   al_destroy_event_queue(queue);

   return 0;
}
Ejemplo n.º 23
0
void show_sound()
{
    int licznik=0;
    int x,y;
    x=500;
    y=100;


    ALLEGRO_FONT * font_ttf    = al_load_ttf_font("cour.ttf",80, 0);
    ALLEGRO_FONT * font_ttfbolt   = al_load_ttf_font("courbd.ttf",80, 0);
    ALLEGRO_BITMAP  *bitmapa = al_load_bitmap( "media/menu.png" );

    bool done=false,draw=false;

    al_draw_bitmap (bitmapa, 0, 0, 0);
    al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"on");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"off");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"cofnij");
    al_flip_display();

    ALLEGRO_EVENT_QUEUE *event_queue1 = al_create_event_queue();
    ALLEGRO_KEYBOARD_STATE keyState;

    //al_register_event_source(event_queue, al_get_mouse_event_source());
    al_register_event_source(event_queue1, al_get_display_event_source(display));
    al_register_event_source(event_queue1, al_get_keyboard_event_source());
    while(!done)
    {
        ALLEGRO_EVENT events;
        al_wait_for_event(event_queue1, &events);
        al_get_keyboard_state(&keyState);

        if(events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;

        }
        else if (al_key_down( &keyState, ALLEGRO_KEY_ESCAPE))
        {
            done=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_ENTER))
        {
            if(licznik==2)
            {
                done=true;
                draw=false;
            }
            else if(licznik==0)
            {

                if(!sample)
                    al_reserve_samples(2);
                sample= al_load_sample("media/The Wild Hunt.wav");

                al_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);
                FILE *fp;
                fp=fopen("ustawienia1.txt","w");
                fprintf(fp,"%d", 1);
                fclose(fp);
                done=true;


            }
            else if(licznik==1)
            {
                // if(!sample)
                al_destroy_sample(sample);
                FILE *fp;
                fp=fopen("ustawienia1.txt","w");
                fprintf(fp,"%d", 0);
                fclose(fp);

                done=true;
            }

        }
        else  if(al_key_down(&keyState, ALLEGRO_KEY_UP))
        {

            licznik--;
            if(licznik<0)licznik=2;
            draw=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_DOWN))
        {
            licznik++;
            if(licznik>2)licznik=0;

            draw=true;
        }
        if(draw)
        {
            draw=false;
            al_draw_bitmap (bitmapa, 0, 0, 0);
            if(licznik==0)
            {
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"on");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"off");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"cofnij");
                al_rest(0.15);
            }
            else if(licznik==1)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"on");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"off");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"cofnij");
                al_rest(0.15);
            }
            else if(licznik==2)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"on");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"off");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"cofnij");
                al_rest(0.15);
            }

            al_flip_display();
        }
    }
    al_destroy_bitmap(bitmapa);
    al_destroy_event_queue(event_queue1);
    al_destroy_font(font_ttf);
    al_destroy_font(font_ttfbolt);

}
Ejemplo n.º 24
0
 /**
     loads a bitmap from a file.
     @param filename filename.
  */
 bool load(const char *filename) {
     reset(al_load_bitmap(filename), al_destroy_bitmap);
     return (bool)(*this);
 }
Ejemplo n.º 25
0
void show_menu()
{

    int licznik=0;
    int x,y;
    x=500;
    y=100;

    ALLEGRO_FONT * font_ttf    = al_load_ttf_font("cour.ttf",80, 0);
    ALLEGRO_FONT * font_ttfbolt   = al_load_ttf_font("courbd.ttf",80, 0);
    ALLEGRO_BITMAP  *bitmapa = al_load_bitmap( "media/menu.png" );

    bool done=false,draw=false;

    al_draw_bitmap (bitmapa, 0, 0, 0);
    al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
    al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");


    al_flip_display();

    ALLEGRO_EVENT_QUEUE *event_queue1 = al_create_event_queue();
    ALLEGRO_KEYBOARD_STATE keyState;

    //al_register_event_source(event_queue, al_get_mouse_event_source());
    al_register_event_source(event_queue1, al_get_display_event_source(display));
    al_register_event_source(event_queue1, al_get_keyboard_event_source());
    while(!done)
    {
        ALLEGRO_EVENT events;
        al_wait_for_event(event_queue1, &events);
        al_get_keyboard_state(&keyState);

        if(events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;

        }
        else if (al_key_down( &keyState, ALLEGRO_KEY_ESCAPE))
        {
            done=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_ENTER))
        {
            if(licznik==3)
            {
                done=true;
                draw=false;
            }
            else if(licznik==0)
            {

                roszada_w_long=true;
                roszada_w_short=true;
                roszada_b_long=true;
                roszada_b_short=true;
                czyjruch=0;
                create_game();
                show_game();
                break;
                done=true;
            }
            else if(licznik==1)
            {
                // create_game();
                load_game();
                show_game();
                done=true;
            }
            else
            {
                show_options();
                draw=true;
            }
        }
        else  if(al_key_down(&keyState, ALLEGRO_KEY_UP))
        {

            licznik--;
            if(licznik<0)licznik=3;
            draw=true;

        }
        else if(al_key_down(&keyState, ALLEGRO_KEY_DOWN))
        {
            licznik++;
            if(licznik>3)licznik=0;

            draw=true;
        }
        if(draw)
        {
            draw=false;
            al_draw_bitmap (bitmapa, 0, 0, 0);
            if(licznik==0)
            {
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else if(licznik==1)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else if(licznik==2)
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            else
            {
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y,ALLEGRO_ALIGN_CENTRE,"nowa gra");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+100,ALLEGRO_ALIGN_CENTRE,"kontynuuj");
                al_draw_textf(font_ttf,al_map_rgb(255,255,255), x, y+200,ALLEGRO_ALIGN_CENTRE,"opcje");
                al_draw_textf(font_ttfbolt,al_map_rgb(255,255,255), x, y+300,ALLEGRO_ALIGN_CENTRE,"wyjdź");
                al_rest(0.15);
            }
            al_flip_display();
        }
    }
    al_destroy_bitmap(bitmapa);
    al_destroy_event_queue(event_queue1);
    al_destroy_font(font_ttf);
    al_destroy_font(font_ttfbolt);

}
Ejemplo n.º 26
0
 /**
     Loads a bitmap from file.
     @param filename filename.
  */
 Bitmap(const char *filename) : Shared(al_load_bitmap(filename), al_destroy_bitmap) {
 }
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *cursor;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   ALLEGRO_FONT *font;
   int mx = 0;
   int my = 0;
   int mz = 0;
   int mw = 0;
   int mmx = 0;
   int mmy = 0;
   int mmz = 0;
   int mmw = 0;
   bool in = true;
   bool buttons[NUM_BUTTONS] = {false};
   int i;
   float p = 0.0;
   ALLEGRO_COLOR black;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
      return 1;
   }

   al_init_primitives_addon();
   al_install_mouse();
   al_install_keyboard();
   al_init_image_addon();
   al_init_font_addon();
   
   actual_buttons = al_get_mouse_num_buttons();
   if (actual_buttons > NUM_BUTTONS)
      actual_buttons = NUM_BUTTONS;

   al_set_new_display_flags(ALLEGRO_RESIZABLE);
   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Error creating display\n");
      return 1;
   }

   al_hide_mouse_cursor(display);

   cursor = al_load_bitmap("data/cursor.tga");
   if (!cursor) {
      abort_example("Error loading cursor.tga\n");
      return 1;
   }

   font = al_load_font("data/fixed_font.tga", 1, 0);
   if (!font) {
      abort_example("data/fixed_font.tga not found\n");
      return 1;
   }
   
   black = al_map_rgb_f(0, 0, 0);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));

   while (1) {
      if (al_is_event_queue_empty(queue)) {
         al_clear_to_color(al_map_rgb(0xff, 0xff, 0xc0));
         for (i = 0; i < actual_buttons; i++) {
            draw_mouse_button(i, buttons[i]);
         }
         al_draw_bitmap(cursor, mx, my, 0);
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
         al_draw_textf(font, black, 5, 5, 0, "dx %i, dy %i, dz %i, dw %i", mmx, mmy, mmz, mmw);
         al_draw_textf(font, black, 5, 25, 0, "x %i, y %i, z %i, w %i", mx, my, mz, mw);
         al_draw_textf(font, black, 5, 45, 0, "p = %g", p);
         al_draw_textf(font, black, 5, 65, 0, "%s", in ? "in" : "out");
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
         mmx = mmy = mmz = 0;
         al_flip_display();
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_MOUSE_AXES:
            mx = event.mouse.x;
            my = event.mouse.y;
            mz = event.mouse.z;
            mw = event.mouse.w;
            mmx = event.mouse.dx;
            mmy = event.mouse.dy;
            mmz = event.mouse.dz;
            mmw = event.mouse.dw;
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            if (event.mouse.button-1 < NUM_BUTTONS) {
               buttons[event.mouse.button-1] = true;
            }
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            if (event.mouse.button-1 < NUM_BUTTONS) {
               buttons[event.mouse.button-1] = false;
            }
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY:
            in = true;
            break;

         case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
            in = false;
            break;

         case ALLEGRO_EVENT_KEY_DOWN:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
               goto done;
            }
            break;

         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            goto done;
      }
   }

done:

   al_destroy_event_queue(queue);

   return 0;
}
Ejemplo n.º 28
0
static bool do_test(enum Mode mode)
{
   ALLEGRO_STATE state;
   ALLEGRO_BITMAP *b1;
   ALLEGRO_BITMAP *b2;
   int REPEAT;
   double t0, t1;
   int i;

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);

   b1 = al_load_bitmap("data/mysha.pcx");
   if (!b1) {
      abort_example("Error loading data/mysha.pcx\n");
      return false;
   }

   b2 = al_load_bitmap("data/allegro.pcx");
   if (!b2) {
      abort_example("Error loading data/mysha.pcx\n");
      return false;
   }

   al_set_target_bitmap(b1);
   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
   step(mode, b2);

   /* Display the blended bitmap to the screen so we can see something. */
   al_store_state(&state, ALLEGRO_STATE_ALL);
   al_set_target_backbuffer(display);
   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);
   al_draw_bitmap(b1, 0, 0, 0);
   al_flip_display();
   al_restore_state(&state);

   log_printf("Benchmark: %s\n", names[mode]);
   log_printf("Please wait...\n");

   /* Do warmup run and estimate required runs for real test. */
   t0 = current_clock();
   for (i = 0; i < WARMUP; i++) {
      step(mode, b2);
   }
   t1 = current_clock();
   REPEAT = TEST_TIME * 100 / (t1 - t0);

   /* Do the real test. */
   t0 = current_clock();
   for (i = 0; i < REPEAT; i++) {
      step(mode, b2);
   }
   t1 = current_clock();

   log_printf("Time = %g s, %d steps\n",
      t1 - t0, REPEAT);
   log_printf("%s: %g FPS\n", names[mode], REPEAT / (t1 - t0));
   log_printf("Done\n");
   
   al_destroy_bitmap(b1);
   al_destroy_bitmap(b2);
      
   return true;
}
int main(void)
{
	//primitive variable
	bool done = false;
	bool redraw = true;
	const int FPS = 60;
	bool isGameOver = false;

	//object variables
	spaceShip ship;
	Bullet bullets[NUM_BULLETS];
	Comet comets[NUM_COMETS];

	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_FONT *font18 = NULL;
	ALLEGRO_BITMAP *shipImage;
	ALLEGRO_BITMAP *cometImage;


	//Initialization Functions
	if(!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(WIDTH, HEIGHT);			//create our display object

	if(!display)										//test display object
		return -1;

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_image_addon();

	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);

	cometImage = al_load_bitmap("asteroid-1-96.png");
	//above does not need convert_mask_to_alpha because it is tranparent background in sprite sheet
	shipImage = al_load_bitmap("Spaceship_by_arboris.png");
	al_convert_mask_to_alpha(shipImage,al_map_rgb(255,0,255));

	srand(time(NULL));
	InitShip(ship, shipImage);
	InitBullet(bullets, NUM_BULLETS);
	InitComet(comets, NUM_COMETS, cometImage);
	
	font18 = al_load_font("arial.ttf", 18, 0);

	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_start_timer(timer);
	while(!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			redraw = true;
			if(keys[UP])
				MoveShipUp(ship);
			else if(keys[DOWN])
				MoveShipDown(ship);
			else
				ResetShipAnimation(ship,1);
			if(keys[LEFT])
				MoveShipLeft(ship);
			else if(keys[RIGHT])
				MoveShipRight(ship);
			else
				ResetShipAnimation(ship, 2);
			if(!isGameOver)
			{
				UpdateBullet(bullets, NUM_BULLETS);
				StartComet(comets, NUM_COMETS);
				UpdateComet(comets, NUM_COMETS);
				CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship);
				CollideComet(comets, NUM_COMETS, ship);

				if(ship.lives <= 0)
					isGameOver = true;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				FireBullet(bullets, NUM_BULLETS, ship);
				break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}

		if(redraw && al_is_event_queue_empty(event_queue))
		{
			redraw = false; 

			if(!isGameOver)
			{
				DrawShip(ship);
				DrawBullet(bullets, NUM_BULLETS);
				DrawComet(comets, NUM_COMETS);

				al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score);
			}
			else
			{
				al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score);
			}
		
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));
		}
	}

	al_destroy_bitmap(shipImage);
	al_destroy_bitmap(cometImage);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font18);
	al_destroy_display(display);						//destroy our display object

	return 0;
}
Ejemplo n.º 30
0
int main(int argc, char const *argv[])
{
    int n_hordas = 0;             //Numero de hordas chamadas
    bool nova_horda = true;       //Chama nova horda

    bool torre_mouse = false;     //Se a torre está no mouse
    bool info_torre = false;      //Chama a funçao de informaçoes da torre
    bool compra_torre = false;    //Exibe as informaçoes da torre a ser comprada
    bool upgrade_torre;           //Guarda os upgrades da torre]

    int tower_posx = 0;           //Posiçao x de determinada torre
    int tower_posy = 0;           //Posiçao y de determinada torre
    int torre_ID;                 //Identifica as torres
    int t = 0;                    //Contagem das torres
    int t_1, t_2;                 //Contagem para disparo

    int r;                        //Variável para colunas
    int l;                        //Variável para linhas
    bool render = false;          //Renderizaçao

    int resposta = 0;             //Resposta se os monstros estão todos mortos

    int gamestate = 0;            //Gamestates

    //Setup inicial
    Sistema sistema;

    Monstro monstro[tipos_monstros][n_monstros];

    Tipo tipo_torre;
    Tipo tipo1;
    Tipo tipo2;
    Tipo upgrade1_torre1;
    Torre torre[100];

    //Declaracao vairaveis allegro
    ALLEGRO_DISPLAY *janela = NULL;	            //Vari�vel para a janela
    ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;   //  ''     para eventos
    ALLEGRO_BITMAP *imagem = NULL;              //  ''     para imagem
    ALLEGRO_TIMER *timer = NULL;                //  ''     para o tempo (fps)
    ALLEGRO_FONT *fonte = NULL;                 //  ''     para fonte
    ALLEGRO_BITMAP *trilha = NULL;
    ALLEGRO_BITMAP *fundao = NULL;
    ALLEGRO_BITMAP *spawn = NULL;
    ALLEGRO_BITMAP *the_end = NULL;
    ALLEGRO_BITMAP *monstro2 = NULL;
    ALLEGRO_BITMAP *torre1 = NULL;
    ALLEGRO_FONT *fonte40 = NULL;

    //Inicializa o allegro, mouse e add-ons
    al_init();
    al_install_mouse();
    al_init_primitives_addon();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    //Setup inicial do sistema, monstros e torres
    init_horda(monstro, n_monstros, n_hordas, tipos_monstros);
    init_system(sistema);

    setup_torre1(tipo1);
    setup_torre2(tipo2);

    upgrade1_tower1(upgrade1_torre1);

    //Atribui atributos às variáveis allegro
    janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
    fila_eventos = al_create_event_queue();
    imagem = al_load_bitmap("virus.jpg");
    trilha = al_load_bitmap("fundoc.jpg");
    fundao = al_load_bitmap("fundod.jpg");
    spawn = al_load_bitmap("spawn.jpg");
    the_end = al_load_bitmap("the end.jpg");
    monstro2 = al_load_bitmap("virus2.jpg");
    torre1 = al_load_bitmap("halter.png");
    timer = al_create_timer(1.0 / fps);
    fonte = al_load_font("arial.ttf", 12, 0);
    fonte40 = al_load_font("arial.ttf", 40, 0);

    //Inicializa o mouse e tempo
    al_set_system_mouse_cursor(janela, ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);
    al_start_timer(timer);
    al_install_keyboard();

    init_fail(janela, fonte, fila_eventos, imagem, timer, trilha); //Fun�ao de teste de inicializaçao do allegro

    //Regista os eventos da janela, mouse e timer na vari�vel de eventos (fila_eventos)
    al_register_event_source(fila_eventos, al_get_display_event_source(janela));
    al_register_event_source(fila_eventos, al_get_mouse_event_source());
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

    al_clear_to_color(al_map_rgb(235, 235, 235));       //Limpa a tela
    al_flip_display();                                  //Atualiza a tela

    //Loop principal
    while (!GameOver)
    {
        ALLEGRO_EVENT evento;                           //Variavel para eventos
        al_wait_for_event(fila_eventos, &evento);       //Espera por eventos

        if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            GameOver = true;
        }

        switch(gamestate)
        {
        case 0:  //Menu inicial
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                render = true;
            }
            if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_ENTER:
                    gamestate = 1;
                    break;
                case ALLEGRO_KEY_BACKSPACE:
                    gamestate = 2;
                    break;
                }
            }
            break;
        }

        case 1:  //Jogo
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                if(info_torre)
                {
                    if (torre[torre_ID].upgrade == 0 && sistema.money >= 60)
                    {
                        mapa[25][30] = 12;
                    }
                }
                if(!info_torre)
                {
                    mapa[25][30] = 0;
                }

                for(int j = 0; j < t; j++)  //Loop para o disparo das torres
                {
                    if(torre[j].n == 1)
                    {
                        if(t_1 >= fps*(torre[j].fire_rate))
                        {
                            fire_tiro(torre, monstro, t, n_monstros, tipos_monstros); //Dispara tiros
                            t_1 = 0;
                        }
                    }

                    if(torre[j].n == 2)
                    {
                        if(t_2 >= fps*(torre[j].fire_rate))
                        {
                            fire_tiro(torre, monstro, t, n_monstros, tipos_monstros); //Dispara tiros
                            t_2 = 0;
                        }
                    }
                }

                update_horda(monstro, sistema, mapa, n_monstros, tipos_monstros);
                update_tiro(torre, monstro, t, n_monstros, tipos_monstros);
                colisao_horda(torre, monstro, t, n_monstros, sistema, &resposta, tipos_monstros);

                t_1++;
                t_2++;
                render = true;
                if(sistema.lives <= 0)
                    gamestate = 2;
            }



            else if(evento.type == ALLEGRO_EVENT_MOUSE_AXES)
            {
                pos_x = evento.mouse.x; //Armazena a posiçao x do mouse
                pos_y = evento.mouse.y; //Armazena a posiçao y do mouse

                r = pos_x/l_celula; // Atribui uma celula de coluna
                l = pos_y/a_celula; // Atribui uma celula de linha
            }

            else if(evento.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
            {
                switch (mapa[l][r])
                {
                case 10:
                    info_torre = false;
                    compra_torre = true;
                    tipo_torre = tipo1;
                    if(sistema.money >= tipo_torre.price && evento.mouse.button & 1)
                        torre_mouse = true;
                    break;
                case 20:
                    info_torre = false;
                    compra_torre = true;
                    tipo_torre = tipo2;
                    if(sistema.money >= tipo_torre.price && evento.mouse.button & 1)
                        torre_mouse = true;
                    break;
                case 11:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                case 12:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                case 21:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                default:
                    info_torre = false;
                }

                if(torre_mouse && (mapa[l][r] == 0 || mapa[l][r] == 5) && evento.mouse.button & 1) //Posicionamento da torre enquanto ela estiver no mouse
                {
                    setup_tower(torre, tipo_torre, t, r, l);
                    sistema.money -= tipo_torre.price;      //Pagamento da torre
                    torre_mouse = false;
                    compra_torre = false;
                    t++;
                }

                if(torre_mouse && evento.mouse.button & 2)  //Cancela compra
                {
                    torre_mouse = false;
                    compra_torre = false;
                }

                if(compra_torre && mapa[l][r] != 10 && mapa[l][r] != 20)  //Termina a exibiçao da torre a ser comprada
                {
                    compra_torre = false;
                }

                if(info_torre && mapa[l][r] == 12 )
                {
                    sistema.money -= 60;
                    torre_ID = find_tower_ID(torre, t, r, l);
                    upgrade_tower(torre, upgrade1_torre1, torre_ID);
                    //upgrade_torre = true;
                }
            }

            else if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                printf("resposta = %d\n", resposta);
                if(resposta == 1 || n_hordas == 0)
                {
                    switch(evento.keyboard.keycode)
                    {
                    case ALLEGRO_KEY_SPACE: //Inicializa uma nova horda
                        start_horda(monstro, n_monstros, n_hordas, tipos_monstros);
                        n_hordas++;
                        break;
                    }
                }
            }
        }
        break;

    case 2: //Fim de jogo
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                render = true;
            }
            if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_R:
                    init_system(sistema);
                    init_horda(monstro, n_monstros, n_hordas, tipos_monstros);
                    restart_tower(torre, t);
                    n_hordas = 0;
                    setup_array(mapa);
                    gamestate = 1;
                    break;
                case ALLEGRO_KEY_ESCAPE:
                    GameOver = true;
                    break;
                }
            }
            break;
        }
    }

    if(render && al_is_event_queue_empty(fila_eventos))
    {
        render = false;

        if(gamestate == 0)
        {
            al_clear_to_color(al_map_rgb(255,255,255));
            al_draw_textf(fonte, al_map_rgb(0, 0, 255), LARGURA_TELA/2, (ALTURA_TELA/2) - 20, 0, "Pressione ENTER para Jogar");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) + 20, 0, "Pressione BACKSPACE para Sair");
        }
        if(gamestate == 1)
        {
            al_clear_to_color(al_map_rgb(61, 10, 10));

            draw_background(mapa, fonte, trilha, fundao, spawn, the_end); //Desenha o plano de fundo
            draw_towers(mapa, sistema, fonte, the_end, torre1); //Desenha as torres

            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 900, 15, ALLEGRO_ALIGN_LEFT, "Vidas do sistema %i", sistema.lives);
            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 900, 35, ALLEGRO_ALIGN_LEFT, "Bitcoins %.2f", sistema.money);
            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 100, 15, ALLEGRO_ALIGN_LEFT, "Monstros mortos: %i  Wave: %i", sistema.score, n_hordas);
            /*
            Mouse debug     al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y, ALLEGRO_ALIGN_LEFT, "l:%i r:%i", l, r);
                            al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y + 15, ALLEGRO_ALIGN_CENTRE, "mapa[l][r]: %i", mapa[l][r]);
            */
            draw_horda(monstro, n_monstros, imagem, tipos_monstros, monstro2); //Desenha os montros

            if(torre_mouse)
            {
                draw_mouse_tower(r, l, tipo_torre); //Desenha a torre somente enquanto ela estiver no mouse
            }
            if(info_torre)
            {
                show_tower_information(torre, torre_ID, fonte); //info torres
                if (mapa[25][30] == 12)
                {
                    al_draw_filled_circle(25 * l_celula + (l_celula/2), 30 * a_celula + (a_celula/2), l_celula/2, al_map_rgb(40, 150, 10));
                }
            }
            if(compra_torre)
            {
                buy_tower(tipo_torre, fonte); //Exibe as informaçoes da torre a ser comprada
            }

            draw_tiro(torre, t); //Desenha os tiros
        }
        if(gamestate == 2)
        {
            al_clear_to_color(al_map_rgb(255,255,255));
            al_draw_textf(fonte40, al_map_rgb(255, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) - 100, 0, "Game Over");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) - 20, 0, "Pressione R para Jogar Novamente");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) + 20, 0, "Pressione ESC para Sair");
        }

        al_flip_display();
    }
}

destroy_al(janela, fonte, fila_eventos, imagem, timer); //Destroi as vari�veis allegro

return 0;
}