コード例 #1
0
ファイル: ex_windows.c プロジェクト: BorisCarvajal/allegro5
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *displays[2];
   ALLEGRO_MONITOR_INFO *info;
   int adapter_count;
   int x, y;
   ALLEGRO_FONT *myfont;
   ALLEGRO_EVENT_QUEUE *events;
   ALLEGRO_EVENT event;
   int i;

   (void)argc;
   (void)argv;

   srand(time(NULL));

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

   al_install_mouse();
   al_init_font_addon();
   al_init_image_addon();

   adapter_count = al_get_num_video_adapters();

   info = malloc(adapter_count * sizeof(ALLEGRO_MONITOR_INFO));

   for (i = 0; i < adapter_count; i++) {
      al_get_monitor_info(i, &info[i]);
   }

   x = ((info[0].x2 - info[0].x1) / 3) - (W / 2);
   y = ((info[0].y2 - info[0].y1) / 2) - (H / 2);

   al_set_new_window_position(x, y);

   displays[0] = al_create_display(W, H);

   x *= 2;
   al_set_new_window_position(x, y);

   displays[1] = al_create_display(W, H);

   if (!displays[0] || !displays[1]) {
      abort_example("Could not create displays.\n");
   }

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   myfont = al_load_font("data/fixed_font.tga", 0, 0);
   if (!myfont) {
      abort_example("Could not load font.\n");
   }

   events = al_create_event_queue();
   al_register_event_source(events, al_get_mouse_event_source());
   al_register_event_source(events, al_get_display_event_source(displays[0]));
   al_register_event_source(events, al_get_display_event_source(displays[1]));

   for (;;) {
      for (i = 0; i < 2; i++) {
        al_set_target_backbuffer(displays[i]);
        al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
        if (i == 0)
           al_clear_to_color(al_map_rgb(255, 0, 255));
        else
           al_clear_to_color(al_map_rgb(155, 255, 0));
        al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
        al_draw_textf(myfont, al_map_rgb(0, 0, 0), 50, 50, ALLEGRO_ALIGN_CENTRE, "Click me..");
        al_flip_display();
      }

      if (al_wait_for_event_timed(events, &event, 1)) {
         if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
            break;
         }
         else if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
            int a = rand() % adapter_count;
            int w = info[a].x2 - info[a].x1;
            int h = info[a].y2 - info[a].y1;
            int margin = 20;
            x = margin + info[a].x1 + (rand() % (w - W - margin));
            y = margin + info[a].y1 + (rand() % (h - H - margin));
            al_set_window_position(event.mouse.display, x, y);
         }
      }
   }

   al_destroy_event_queue(events);

   al_destroy_display(displays[0]);
   al_destroy_display(displays[1]);

   free(info);

   return 0;
}
コード例 #2
0
ファイル: GameMenu.c プロジェクト: lucasteles/Heredian
void gdp_selchar(){
    // Carregando o arquivo de fonte
    ALLEGRO_FONT *fonte = al_load_font(".//Fonts//font_menu.ttf", 100, 0);
    ALLEGRO_BITMAP *image = al_load_bitmap(".//Images//select.png");

    ALLEGRO_SAMPLE *musicsel= al_load_sample(".//Songs//Menu//musicsel.ogg");
    ALLEGRO_SAMPLE *musicconfirm= al_load_sample(".//Songs//Menu//musicconfirm.ogg");

    int options = 4,i;
    char **texto = calloc(options,sizeof(char*));
    texto[0] = "James";
    texto[1] = "Julios";
    texto[2] = "Japa";
    texto[3] = "Gauss";
    char *confirm = ">";

    int nopcao = 0,nposicao = 120,nitensmenu = 3,nespaco = 80;

    while(true){
        al_wait_for_event(event_queue, &evento);

        if(gdp_readclose()){
            break;
        }

        if(evento.type == ALLEGRO_EVENT_KEY_DOWN){

            if(evento.keyboard.keycode == ALLEGRO_KEY_DOWN){
                al_play_sample(musicsel, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                nopcao++;

            }
            if(evento.keyboard.keycode == ALLEGRO_KEY_UP){
                al_play_sample(musicsel, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                nopcao--;
            }

            if(evento.keyboard.keycode == ALLEGRO_KEY_ENTER){
                al_play_sample(musicconfirm, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                al_rest(1.0);
                opchar = nopcao;
                break;
            }
        }
        if(nopcao>nitensmenu)
                nopcao = nitensmenu;
        if(nopcao<=0)
                nopcao = 0;

        if(gdp_readtime() && al_is_event_queue_empty(event_queue)){
            gdp_clear();

            // imagem de fundo
            al_draw_scaled_bitmap(image,
                0, 0,
                al_get_bitmap_width(image),
                al_get_bitmap_height(image),
                0,
                0,
                wigth,
                height,
                0
            );

            // menu
            for(i=0;i<options;i++)
                al_draw_textf(fonte, al_map_rgb(0, 0, 0), wigth / 2, nposicao+nespaco*i, ALLEGRO_ALIGN_CENTRE, "%s", texto[i]);

            // selecao
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), (wigth / 2)-230, nposicao+nopcao*nespaco, ALLEGRO_ALIGN_LEFT, "%s", confirm);

            al_flip_display();
        }

    }
    free(texto);
    al_destroy_sample(musicsel);
    al_destroy_sample(musicconfirm);
    al_destroy_bitmap(image);
    al_destroy_font(fonte);
    opchar++;
}
コード例 #3
0
ファイル: timers.c プロジェクト: pasoev/praxis
int main(int argc, char *argv[])
{
  if(!al_init())
    {
      fprintf(stderr, "Failed to initialize allegro!\n");
      return -1;
    }

  ALLEGRO_DISPLAY *display = NULL;
  ALLEGRO_EVENT_QUEUE *event_queue = NULL;
  ALLEGRO_TIMER *timer = NULL;

  bool redraw = true;

  timer = al_create_timer(1.0 / FPS);
  if(!timer)
    {
      fprintf(stderr, "failed to create the timer.\n");
      return -1;
    }

  display = al_create_display(1024, 768);

  if(!display)
    {
      fprintf(stderr, "Failed to create the display.\n");
      al_destroy_timer(timer);
      return -1;
    }

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


  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_clear_to_color(al_map_rgb(0,0,0));
  al_flip_display();

  al_start_timer(timer);

  while(true)
    {
      ALLEGRO_EVENT ev;
      al_wait_for_event(event_queue, &ev);

      if(ev.type == ALLEGRO_EVENT_TIMER)
	redraw = true;
      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
	{
	  fprintf(stderr, "display closed\n");
	  break;
	}

      if(redraw && al_is_event_queue_empty(event_queue))
	{
	  redraw = false;
	  al_clear_to_color(al_map_rgb(99, 99, 99));
	  al_flip_display();
	}
    }
  al_destroy_timer(timer);
  al_destroy_display(display);
  al_destroy_event_queue(event_queue);

  return 0;
}
コード例 #4
0
void outputArray (pixel **array, int altura, int largura, int indice, int player_x, int player_x2, int player_y, int player_y2, int tamPixel) {
    ALLEGRO_COLOR terra = al_map_rgb(110, 60, 40);      /* Cores */
    ALLEGRO_COLOR agua = al_map_rgb(51, 153, 255);
    ALLEGRO_COLOR ilha = al_map_rgb(6, 96, 0);
    ALLEGRO_COLOR canoa = al_map_rgb(51, 51, 51);
    
    int i, j;
    int ilha0 = 999999, ilhaf = 0;      /* Variáveis que guardam o começo de uma ilha e o final dela */
    
    
    int playerSize = tamPixel + largura*0.1;
    if(playerSize > 30) playerSize = 30;
    
    al_clear_to_color(agua);
    
    for (i = 0; i < altura; i ++) { /* Imprime uma linha de cada vez */
        
        int TMargemEsquerda = margemEsquerda(array[(i+indice)%altura]);         /* Os tamanhos das margens */
        int TMargemDireita = margemDireita(array[(i+indice)%altura], largura);
        
        /* Desenha a margem esquerda */
        al_draw_filled_rectangle(0, tamPixel*i, tamPixel*(TMargemEsquerda - 2), tamPixel*(i+1), terra);
        
        j = TMargemEsquerda - 2;
        
        
        /* Desenha o encontro da terra com a água, criando triângulos ou retângulos conforme necessário */
        if (tipo(&array[(i+indice+1)%altura][j+2]) == TERRA) {          /* Se a linha de baixo era maior */
            al_draw_filled_rectangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*(i+1), terra);
            j++;
            al_draw_filled_triangle(tamPixel*j, tamPixel*i, tamPixel*j, tamPixel*(i+1), tamPixel*(j+1), tamPixel*(i+1), terra);
        }
        else if (tipo(&array[(i+indice+1)%altura][j+1]) == TERRA) {     /* Se era igual */
            al_draw_filled_rectangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*(i+1), terra);
            j++;
        }
        else {      /* Se era menor */
            al_draw_filled_triangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*i, tamPixel*j, tamPixel*(i+1), terra);
            j++;
        }
        
        
        
        /* Descobre onde começa e termina a ilha */
        for (j = TMargemEsquerda; j < largura - TMargemDireita - 2; j++)
            if (tipo(&array[(i+indice)%altura][j]) == TERRA) {
                if (j < ilha0)
                    ilha0 = j;
                if (j > ilhaf)
                    ilhaf = j;
            }
        
        
        if (ilhaf != 0)         /* Se existe uma ilha, desenha primeiro as duas partes de água, depois ela em cima */
            al_draw_filled_rounded_rectangle(tamPixel*ilha0,tamPixel*i,tamPixel*(ilhaf+1),tamPixel*(i+1),3,3, ilha);
        ilha0 = 999999;         /* Reseta os valores */
        ilhaf = 0;
        
        /* Desenha o segundo encontro da água com a terra */
        if (tipo(&array[(i+indice+1)%altura][j+2]) == AGUA) {
            j++;
            al_draw_filled_triangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*i, tamPixel*(j+1), tamPixel*(i+1), terra);
        }
        else if (tipo(&array[(i+indice+1)%altura][j+1]) == AGUA) {
            j++;
            al_draw_filled_rectangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*(i+1), terra);
        }
        else {
            al_draw_filled_triangle(tamPixel*(j+1), tamPixel*(i+1), tamPixel*(j+1), tamPixel*i, tamPixel*j, tamPixel*(i+1), terra);
            j++;
            al_draw_filled_rectangle(tamPixel*j, tamPixel*i, tamPixel*(j+1), tamPixel*(i+1), terra);
        }
        
        
        /* Desenha a margem direita */
        al_draw_filled_rectangle(tamPixel*(largura - TMargemDireita), tamPixel*i, tamPixel*(largura), tamPixel*(i+1), terra);

    }
    
    /* Desenha o jogador na posição correta */
    /*al_draw_filled_ellipse(player_x, player_y, playerSize/3, playerSize, canoa);*/
    al_draw_line(player_x, player_y, player_x2, player_y2, canoa, 5.0);
    /* Coloca tudo o que foi desenhado na tela */
    al_flip_display();
}
コード例 #5
0
ファイル: asteroids.c プロジェクト: benlemasurier/asteroids
int
main(void)
{
  asteroids.lives         = START_LIVES;
  asteroids.display       = NULL;
  asteroids.timer         = NULL;
  asteroids.event_queue   = NULL;
  SHIP *ship;

  bool redraw = true;
  bool quit   = false;
  bool key[7] = { false };

  seed_rand();
  atexit(shutdown);

  if(!init())
    exit(EXIT_FAILURE);

  if((asteroids.high_score = get_config_value("high_score")) == NULL)
    asteroids.high_score = "0";

  asteroids.level = level_create(0, 0);

  if(!(ship = ship_create()))
    exit(EXIT_FAILURE);

  al_flip_display();
  al_start_timer(asteroids.timer);

  while(!quit) {
    ALLEGRO_EVENT ev;
    al_wait_for_event(asteroids.event_queue, &ev);

    if(ev.type == ALLEGRO_EVENT_TIMER) {
      /* start game */
      if(asteroids.level->number == 0 && key[KEY_S]) {
        start();
        continue;
      }

      /* are we out of asteroids to destroy? */
      if(list_length(asteroids.level->asteroids) == 0)
        asteroids.level = level_next(asteroids.level);

      /* update objects */
      ship = ship_update(ship, key, asteroids.timer);
      explosions_update();
      asteroids.level = level_update(asteroids.level, ship, key, asteroids.timer);

      /* ship->asteroid collisions. */
      check_ship_asteroid_collisions(ship, asteroids.level->asteroids);

      /* ship[missile] -> asteroid collisions. */
      check_ship_missile_asteroid_collisions(asteroids.level, ship);

      /* ship[missile] -> saucer collisions. */
      check_ship_missile_saucer_collisions(asteroids.level, ship);

      /* saucer[missile] -> ship collisions. */
      check_saucer_missile_ship_collisions(asteroids.level, ship);

      /* saucer[missile] -> asteroid collisions. */
      check_saucer_missile_asteroids_collisions(asteroids.level);

      /* saucer->asteroid collisions. */
      check_saucer_asteroid_collisions(asteroids.level);

      redraw = true;
    } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
      keydown(ev, key);
      quit = key[KEY_ESCAPE];
    } else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
      keyup(ev, key);
      ship->fire_debounce  = key[KEY_SPACE];
      ship->hyper_debounce = key[KEY_LCONTROL];
    }

    if(redraw && al_is_event_queue_empty(asteroids.event_queue)) {
      redraw = false;
      al_clear_to_color(al_map_rgb(BLACK));

      level_draw(asteroids.level);
      draw_lives();
      draw_high_score();
      animation_draw_list(asteroids.explosions);

      if(asteroids.level->number == 0) {
        draw_home();
        al_flip_display();
        continue;
      }

      if(asteroids.lives > 0) {
        ship_draw(ship, key[KEY_UP]);
        missile_draw_list(ship->missiles);
      } else {
        if(ship->explosion)
          ship_draw(ship, false);
        draw_gameover();
      }

      al_flip_display();
    }
  };

  /* FIXME: cleanup */
  if(asteroids.timer != NULL)
    al_destroy_timer(asteroids.timer);
  if(asteroids.event_queue != NULL)
    al_destroy_event_queue(asteroids.event_queue);
  if(asteroids.display != NULL)
    al_destroy_display(asteroids.display);

  LIST *head = list_first(asteroids.level->asteroids);
  while(head != NULL) {
    ASTEROID *rock = (ASTEROID *) head->data;
    asteroid_free(rock);
    head = head->next;
  }
  ship_free(ship);

  al_destroy_bitmap(asteroids.lives_sprite);
  ship_shutdown();
  missile_shutdown();
  asteroid_shutdown();
  explosion_shutdown();

  al_uninstall_keyboard();

  exit(EXIT_SUCCESS);
}
コード例 #6
0
ファイル: ex_logo.c プロジェクト: dradtke/battlechess
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   int redraw = 0, i;
   bool quit = false;

   if (!al_init()) {
      abort_example("Could not initialise Allegro\n");
      return 1;
   }
   al_init_primitives_addon();
   al_install_mouse();
   al_init_image_addon();
   al_init_font_addon();
   al_init_ttf_addon();
   srand(time(NULL));

   white = al_map_rgba_f(1, 1, 1, 1);

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Could not create display\n");
      return 1;
   }
   al_set_window_title(display, "Allegro Logo Generator");
   al_install_keyboard();

   /* Read logo parameters from logo.ini (if it exists). */
   config = al_load_config_file("logo.ini");
   if (!config)
      config = al_create_config();
   for (i = 0; param_names[i]; i++) {
      char const *value = al_get_config_value(config, "logo", param_names[i]);
      if (value)
         strncpy(param_values[i], value, sizeof(param_values[i]));
   }

   font = al_load_font("data/DejaVuSans.ttf", 12, 0);
   if (!font) {
      abort_example("Could not load font\n");
      return 1;
   }

   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_mouse_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 (!quit) {
      ALLEGRO_EVENT event;
      al_wait_for_event(queue, &event);
      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
         break;
      if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
            quit = true;
         }
         else if (event.keyboard.keycode == ALLEGRO_KEY_ENTER) {
            if (editing) {
               regenerate = true;
               editing = false;
            }
            else {
               cursor = 0;
               editing = true;
            }
         }
         else if (event.keyboard.keycode == ALLEGRO_KEY_UP) {
            if (selection > 0) {
               selection--;
               cursor = 0;
               editing = false;
            }
         }
         else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) {
            if (param_names[selection + 1]) {
               selection++;
               cursor = 0;
               editing = false;
            }
         }
         else {
            int c = event.keyboard.unichar;
            if (editing) {
               if (c >= 32) {
                  ALLEGRO_USTR *u = al_ustr_new(param_values[selection]);
                  al_ustr_set_chr(u, cursor, c);
                  cursor++;
                  al_ustr_set_chr(u, cursor, 0);
                  strncpy(param_values[selection], al_cstr(u),
                     sizeof param_values[selection]);
                  al_ustr_free(u);
               }
            }
            else {
               if (c == 'r')
                  randomize();
               if (c == 's')
                  save();
            }
         }
      }
      if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
         if (event.mouse.button == 1) {
            mouse_click(event.mouse.x, event.mouse.y);
         }
      }
      if (event.type == ALLEGRO_EVENT_TIMER)
         redraw++;

      if (redraw && al_is_event_queue_empty(queue)) {
         redraw = 0;

         render();

         al_flip_display();
      }
   }

   /* Write modified parameters back to logo.ini. */
   for (i = 0; param_names[i]; i++) {
      al_set_config_value(config, "logo", param_names[i],
         param_values[i]);
   }
   al_save_config_file("logo.ini", config);
   al_destroy_config(config);

   return 0;
}
コード例 #7
0
ファイル: main.cpp プロジェクト: Frogulis/sunsyndrome
int main(int argc, char** argv)
{
    time_t t;

    srand((unsigned) time(&t));

    if (!al_init())
    {
        std::cout << "Failed to start Allegro.";
        return -1;
    }

    if (!al_init_image_addon())
    {
        std::cout << "Failed to start Allegro Imagea person who gives information to the police or to some other authority about the bad behavior or criminal activity of someone else Addon.\n";
        return -1;
    }

    if (!al_init_primitives_addon())
    {
        std::cout << "Failed to start Allegro Primitives Addon.\n";
        return -1;
    }

    if (!al_init_font_addon())
    {
        std::cout << "Failed to start Allegro Font Addon.\n";
        return -1;
    }

    if (!al_init_ttf_addon())
    {
        std::cout << "Failed to start Allegro TTF Addon.\n";
        return -1;
    }

    ALLEGRO_DISPLAY* main_window = al_create_display(800, 600);
    if (!main_window)
    {
        std::cout << "Failed to create display.";
        return -1;
    }

    ALLEGRO_EVENT_QUEUE* eq = al_create_event_queue();
    if (!eq)
    {
        std::cout << "Failed to create event queue.";
        return -1;
    }

    ALLEGRO_TIMER* fps_timer = al_create_timer(1.0 / 60);
    if (!fps_timer)
    {
        std::cout << "Failed to create timer.";
        return -1;
    }

    ALLEGRO_TIMER* count_timer = al_create_timer(1.0);
    if (!count_timer)
    {
        std::cout << "Failed to create count timer.";
        return -1;
    }

    if (!al_install_keyboard())
    {
        std::cout << "Failed to install keyboard.";
        return -1;
    }


    if (!al_install_mouse() || !al_set_mouse_cursor(main_window, al_create_mouse_cursor(al_load_bitmap("resources/sprites/UI/cursor/clicker.png"), 16, 31)))
    {
        std::cout << "Failed to install mouse.";
        return -1;
    }


    al_register_event_source(eq, al_get_timer_event_source(fps_timer));
    al_register_event_source(eq, al_get_timer_event_source(count_timer));
    al_register_event_source(eq, al_get_keyboard_event_source());
    al_register_event_source(eq, al_get_mouse_event_source());
    al_register_event_source(eq, al_get_display_event_source(main_window));

    Game base;
    if (!base.init())
    {
        std::cout << "Failed to initialise game! Quitting...\n";
        return -1;
    }

    bool ready_to_draw = false;
    bool ready_to_draw_fps = false;
    al_start_timer(fps_timer);
    al_start_timer(count_timer);
    int fps_count = 0;

    ALLEGRO_FONT* fps_font = al_load_ttf_font("resources/fonts/MontereyFLF.ttf", 11, 0);
    if (!fps_font)
    {
        std::cout << "Failed to load font for fps counter!";
        return -1;
    }

    while (true)
    {
        while (!al_event_queue_is_empty(eq))
        {
            ALLEGRO_EVENT ev;
            al_get_next_event(eq, &ev);
            if (ev.type == ALLEGRO_EVENT_TIMER)
            {
                if (ev.timer.source == fps_timer)
                {
                    ready_to_draw = true;
                }
                else if (ev.timer.source == count_timer)
                {
                    ready_to_draw_fps = true;
                }
            }
            else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            {
                std::cout << "Safely quitting.";
                al_destroy_display(main_window);
                al_destroy_event_queue(eq);
                al_destroy_timer(fps_timer);
                return 0;
            }
            else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) //current keyboard input section
                {
                    std::cout << "Safely quitting.";
                    al_destroy_display(main_window);
                    al_destroy_event_queue(eq);
                    al_destroy_timer(fps_timer);
                    return 0;
                }
            }
            base.runEvents(ev);
        }

        if (ready_to_draw)
        {
            fps_count++;
            base.runLogic();
            base.runDisplay();
            char buffer[25];
            if (ready_to_draw_fps)
            {
                sprintf(buffer, "%d", fps_count);
                fps_count = 0;
                ready_to_draw_fps = false;
            }
            al_draw_text(fps_font, al_map_rgb(0,255,0), 5, 5, 0, buffer);
            al_flip_display();
            ready_to_draw = false;
        }

    }
}
コード例 #8
0
int main(int argc, char const *argv[])
{
	const int FPS = 60;
	const int MAX_BULLETS = 10;
	const int MAX_ASTEROIDS = 10;
	const int MAX_EXPLOSIONS = 10;
	srand(time(NULL));
	int done = 0;
	int redraw = 1;

	if(!al_init())
	{
		al_show_native_message_box(NULL, "Error", "Error", 
			"Could not initialize Allegro 5.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_DISPLAY *display = al_create_display(screen_width, screen_height);
	if(!display)
	{
		al_show_native_message_box(NULL, "Error", "Error", 
			"Could not create display.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	if(!event_queue)
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not create event queue.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS);
	if(!timer)
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not create timer.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_install_keyboard())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not install keyboard.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_install_mouse())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not install mouse.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_init_image_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize image addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_init_primitives_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize primitives addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
	}

	al_init_font_addon(); // for whatever reason this function is void returning

	if(!al_init_ttf_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize ttf addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
	}
	
	al_hide_mouse_cursor(display);

	al_register_event_source(event_queue, al_get_mouse_event_source());
	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));

	ALLEGRO_FONT *font18 = al_load_font("Arial.ttf", 18, 0);

	int prev_x = screen_width, prev_y = screen_height;
	int fps_counter = 0;
	int fps_counter2 = 0;
	int i, j, k;

	struct spaceship ship;
	init_ship(&ship);

	struct bullet bullets[MAX_BULLETS];
	for(i = 0; i < MAX_BULLETS; i++)
	{
		init_bullet(&bullets[i]);
	}

	struct asteroid asteroids[MAX_ASTEROIDS];
	for(i = 0; i < MAX_ASTEROIDS; i++)
	{
		init_asteroid(&asteroids[i]);
	}

	struct explosion explosions[MAX_EXPLOSIONS];
	for(i = 0; i < MAX_EXPLOSIONS; i++)
	{
		init_explosion(&explosions[i]);
	}

	al_start_timer(timer);

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

		if(event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = 1;
		}
		if(event.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch(event.keyboard.keycode)
			{
				case ALLEGRO_KEY_Q: 
					done = 1;
					break;
				case ALLEGRO_KEY_ESCAPE:
					done = 1;
					break;
			}
		}
		if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
		{
			if(event.mouse.button & 1)
			{
				for(i = 0; i < MAX_BULLETS; i++)
				{
					if(!bullets[i].live)
					{
						fire_bullet(&bullets[i], ship);
						break;
					}
				}
			}
		}
		if(event.type == ALLEGRO_EVENT_MOUSE_AXES ||
              event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY)
		{
			set_ship_coordinates(&ship, event.mouse.x, event.mouse.y);
		}
		if(event.type == ALLEGRO_EVENT_TIMER)
		{	
			if(ship.x > prev_x)
			{	
				ship.sprite.dir_horizontal = RIGHT;
			}
			else if(ship.x == prev_x)
			{
				ship.sprite.dir_horizontal = CENTER;
			}
			else if(ship.x < prev_x) 
			{
				ship.sprite.dir_horizontal = LEFT;
			}

			if(ship.y > prev_y)
			{
				ship.sprite.dir_vertical = BACK;
			}
			else if(ship.y == prev_y)
			{
				ship.sprite.dir_vertical = NEUTRAL;
			}
			else if(ship.y < prev_y)
			{
				ship.sprite.dir_vertical = FORWARD;
			}

			if(++fps_counter >= FPS / 5)
			{
				fps_counter = 0;
				prev_x = ship.x;
				prev_y = ship.y;	
			}

			if(++fps_counter2 >= 2 * FPS)
			{
				for(i = 0; i < MAX_ASTEROIDS; i++)
				{
					if(!asteroids[i].live)
					{
						start_asteroid(&asteroids[i]);
						break;
					}
				}
				fps_counter2 = 0;
			}

			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					update_bullet(&bullets[i]);
				}
			}

			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					update_asteroid(&asteroids[i], &ship);
				}
			}

			for(i = 0; i < MAX_EXPLOSIONS; i++)
			{
				if(explosions[i].live)
				{
					update_explosion(&explosions[i]);
				}
			}

			update_ship_boundaries(&ship);

			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					for(j = 0; j < MAX_ASTEROIDS; j++)
					{
						if(asteroids[j].live)
						{
							if(bullet_and_asteroid_collision(bullets[i], asteroids[j]))
							{
								bullets[i].live = 0;
								asteroids[j].live = 0;
								ship.score += 20;
								for(k = 0; k < MAX_EXPLOSIONS; k++)
								{
									if(!explosions[k].live)
									{
										start_explosion(&explosions[k], bullets[i].x, bullets[i].y);
										break;
									}
								}
							}
						}
					}
				}
			}

			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					if(ship_and_asteroid_collision(ship, asteroids[i]))
					{
						asteroids[i].live = 0;
						for(k = 0; k < MAX_EXPLOSIONS; k++)
						{
							if(!explosions[k].live)
							{
								start_explosion(&explosions[k], ship.x, ship.y);
								break;
							}
						}
						
						ship.lives--;
					}
				}
			}

			if(!ship.lives)
			{
				done = true;
			}

			redraw = 1;
		}

		if(redraw)
		{
			redraw = 0;
			draw_ship_sprite(ship.sprite, ship.x, ship.y);
			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					draw_bullet(bullets[i]);
				}
			}
			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					draw_asteroid(asteroids[i]);
				}
			}
			for(i = 0; i < MAX_EXPLOSIONS; i++)
			{
				if(explosions[i].live)
				{
					draw_explosion(explosions[i]);
				}
			}
			al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 5, 0, 
				"Score: %d ", ship.score); // I have no idea why it doesn't print the S...
			al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 25, 0, 
				"Lives: %d", ship.lives);
			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
		}
	}

	for(i = 0; i < MAX_ASTEROIDS; i++)
	{
		destroy_asteroid(&asteroids[i]);
	}
	for(i = 0; i < MAX_EXPLOSIONS; i++)
	{
		destroy_explosion(&explosions[i]);
	}
	destroy_sprite(&ship.sprite);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font18);

	return 0;
}
コード例 #9
0
ファイル: ex_draw.c プロジェクト: BorisCarvajal/allegro5
static void tick(void)
{
   draw();
   al_flip_display();
}
コード例 #10
0
ファイル: main.cpp プロジェクト: tsteinholz/SpaceShooterIII
int main(void) {
    initialize();

    int nva = al_get_num_video_adapters();
    assert(nva);

    ALLEGRO_MONITOR_INFO aminfo;
    al_get_monitor_info(0, &aminfo);
    screen_w = aminfo.x2 - aminfo.x1 + 1;
    screen_h = aminfo.y2 - aminfo.y1 + 1;

    ALLEGRO_DISPLAY *display = al_create_display(screen_w, screen_h);
    ALLEGRO_EVENT_QUEUE *evqueue = al_create_event_queue();
    ALLEGRO_TIMER *fps_timer = al_create_timer(1.0 / 120.0);

    al_set_display_flag(display, ALLEGRO_FULLSCREEN_WINDOW, true);

    if (!display) {
        printf("Failed to create display!\n");
        exit(EXIT_FAILURE);
    }

    al_register_event_source(evqueue, al_get_keyboard_event_source());
    al_register_event_source(evqueue, al_get_mouse_event_source());
    al_register_event_source(evqueue, al_get_display_event_source(display));
    al_register_event_source(evqueue, al_get_timer_event_source(fps_timer));

    al_start_timer(fps_timer);

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Local Variables
    ////////////////////////////////////////////////////////////////////////////////////////////////

//#ifdef DEBUG
    float fps = 0, delta_time = 0, current_time = 0, last_time = al_get_time();
//#endif //DEBUG
    bool render = true, executing = true;

    unsigned int spawn_counter = 0;

    Assets* assets = new Assets();
    Stage stage = Menu;
    Stats stats;

    Button *play = new Button("Play", assets->fnt_menu, screen_w / 2, 300, [&stage, &stats]() -> void {
                stage = Game;
                stats.start_time = al_get_time();
                              }),
        *leaderboard = new Button("Leaderboard", assets->fnt_menu, screen_w / 2, 400, [&stage]() -> void {
                stage = Leaderboard;
                              }),
        *options = new Button("Options", assets->fnt_menu, screen_w / 2, 500, [&stage]() -> void {
                stage = Options;
                              }),
        *quit = new Button("Quit", assets->fnt_menu, screen_w / 2, 600, [&executing]() -> void {
                executing = false;
                              });

    b2Vec2 gravity(0.0f, 0.0f);
    b2World world(gravity);

    Projectile *player = new Projectile(assets->png_player, &world, screen_w / 2, screen_h - 200);
    std::vector<Projectile*> Meteors;

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Game Loop
    ////////////////////////////////////////////////////////////////////////////////////////////////

    while (executing) {
        ALLEGRO_EVENT event;
        al_wait_for_event(evqueue, &event);

//#ifdef DEBUG
        current_time = al_get_time();
        delta_time = current_time - last_time;
        fps = 1/(delta_time);
        last_time = current_time;
//#endif //DEBUG

        world.Step(delta_time, 8, 3);

        switch (event.type) { // HANDLE ALLEGRO EVENTS
            case ALLEGRO_EVENT_TIMER:
                render = true;
                if (stage == Game) spawn_counter++;
                break;
            case ALLEGRO_EVENT_DISPLAY_CLOSE:
                executing = false;
                break;
            case ALLEGRO_EVENT_KEY_DOWN:
                executing = event.keyboard.keycode != ALLEGRO_KEY_ESCAPE;
                switch(event.keyboard.keycode) {
                    case ALLEGRO_KEY_A:
                    case ALLEGRO_KEY_LEFT:
                        if (stage == Game) player->Velocity.x = -5;
                        break;
                    case ALLEGRO_KEY_D:
                    case ALLEGRO_KEY_RIGHT:
                        if (stage == Game) player->Velocity.x = 5;
                        break;
                }
                break;
            case ALLEGRO_EVENT_KEY_UP:
                if (stage == Game) {
                    player->Velocity.x = 0;
                    player->Velocity.y = 0;
                }
                break;
            default: break;
        }

        switch (stage) { // UPDATE
            case Menu:
                play->Update(&event);
                leaderboard->Update(&event);
                options->Update(&event);
                quit->Update(&event);
                break;
            case Game:
                if (player->m_body->GetPosition().x < 1) player->m_body->SetTransform(b2Vec2(screen_w - 2, player->m_body->GetPosition().y), 0);
                if (player->m_body->GetPosition().x > screen_w - 1) player->m_body->SetTransform(b2Vec2(2, player->m_body->GetPosition().y), 0);
                if (spawn_counter > 75) {
                    spawn_counter = 0;
                    ALLEGRO_BITMAP *meteor_png;
                    switch (rand() % 4) { // Size
                    case 0:
                        switch (rand() % 4) { // Selection
                        case 0:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_big1 : assets->png_meteor_grey_big1;
                            break;
                        case 1:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_big2 : assets->png_meteor_grey_big2;
                            break;
                        case 2:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_big3 : assets->png_meteor_grey_big3;
                            break;
                        case 3:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_big4 : assets->png_meteor_grey_big4;
                            break;
                        default: break;
                        }
                        break;
                    case 1:
                        switch (rand() % 2) { // Selection
                        case 0:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_med1 : assets->png_meteor_grey_med1;
                            break;
                        case 1:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_med2 : assets->png_meteor_grey_med2;
                            break;
                        default: break;
                        }
                        break;
                    case 2:
                        switch (rand() % 2) { // Selection
                        case 0:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_small1 : assets->png_meteor_grey_small1;
                            break;
                        case 1:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_small2 : assets->png_meteor_grey_small2;
                            break;
                        default: break;
                        }
                        break;
                    case 3:
                        switch (rand() % 2) { // Selection
                        case 0:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_tiny1 : assets->png_meteor_grey_tiny1;
                            break;
                        case 1:
                            meteor_png = rand() % 2 ? assets->png_meteor_brown_tiny2 : assets->png_meteor_grey_tiny2;
                            break;
                        default: break;
                        }
                        break;
                        default: break;
                    }
                    auto it = Meteors.end();
                    Projectile *meteor = new Projectile(meteor_png, &world, rand() % screen_w, -75);
                    meteor->Velocity = b2Vec2(-5 + (rand() % 10), rand() % 15);
                    Meteors.insert(it, meteor);
                }
                for (std::vector<Projectile*>::iterator it = Meteors.begin(); it != Meteors.end(); ++it) {
                    if (((*it)->m_body->GetPosition().x >= screen_w + 500 || (*it)->m_body->GetPosition().x <= -500) ||
                        ((*it)->m_body->GetPosition().y >= screen_h + 500 || (*it)->m_body->GetPosition().y <= -500) ||
                        (((*it)->m_body->GetTransform().p.x == 0.0) && (*it)->m_body->GetTransform().p.y == 0.0)) {
                            delete *it;
                            Meteors.erase(it);
                        }
                }
                player->Update(&event);
                for (auto& x : Meteors) {
                    x->Update(&event);
                }
                break;
            case Leaderboard:
                break;
            case Options:

                break;
            case End:

                break;
            default: break;
        }
        if (render && al_is_event_queue_empty(evqueue)) {
            render = false;
            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_set_target_bitmap(al_get_backbuffer(display));
            for (float x = 0; x < screen_w; x += al_get_bitmap_width(assets->png_background)) {
                for (float y = 0; y < screen_h; y += al_get_bitmap_height(assets->png_background)) {
                    al_draw_bitmap(assets->png_background, x, y, 0);
                }
            }
#ifdef DEBUG
            //al_draw_textf(assets->fnt_menu, al_map_rgb(255, 0, 255), 10, 5, ALLEGRO_ALIGN_LEFT, "Debug");
            //al_draw_textf(assets->fnt_menu, al_map_rgb(255, 0, 255), 10, 35, ALLEGRO_ALIGN_LEFT, "FPS: %i", (int)fps);
            //al_draw_textf(assets->fnt_menu, al_map_rgb(255, 0, 255), 10, 65, ALLEGRO_ALIGN_LEFT, "Meteor Count: %i", Meteors.size());
#endif // DEBUG
            switch (stage) { // RENDER
            default: break;
            case Menu:
                al_draw_text(assets->fnt_title, al_map_rgb(255, 255, 255), screen_w/2, 100, ALLEGRO_ALIGN_CENTRE, "SPACE SHOOTER III");
                play->Render();
                leaderboard->Render();
                options->Render();
                quit->Render();
                break;
            case Game:
                player->Render();
                for (auto& x : Meteors) {
                    x->Render();
                }
                break;
            case Leaderboard:

                break;
            case Options:

                break;
            case End:

                break;
            }
            al_flip_display();
        }
        render = false;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Deinitialization
    ////////////////////////////////////////////////////////////////////////////////////////////////

    delete player;

    al_unregister_event_source(evqueue, al_get_keyboard_event_source());
    al_unregister_event_source(evqueue, al_get_mouse_event_source());
    al_unregister_event_source(evqueue, al_get_display_event_source(display));
    al_unregister_event_source(evqueue, al_get_timer_event_source(fps_timer));

    al_destroy_display(display);
    al_destroy_event_queue(evqueue);
    al_destroy_timer(fps_timer);

    delete assets;
    shutdown();
    return EXIT_SUCCESS;
}
コード例 #11
0
void AllegroDisp::FlipBuffers()
{
	al_flip_display();
}
コード例 #12
0
/* Function: al_create_display
 */
ALLEGRO_DISPLAY *al_create_display(int w, int h)
{
   ALLEGRO_SYSTEM *system;
   ALLEGRO_DISPLAY_INTERFACE *driver;
   ALLEGRO_DISPLAY *display;
   ALLEGRO_EXTRA_DISPLAY_SETTINGS *settings;
   int flags;

   system = al_get_system_driver();
   driver = system->vt->get_display_driver();
   if (!driver) {
      ALLEGRO_ERROR("Failed to create display (no display driver)\n");
      return NULL;
   }

   display = driver->create_display(w, h);
   if (!display) {
      ALLEGRO_ERROR("Failed to create display (NULL)\n");
      return NULL;
   }

   ASSERT(display->vt);

   settings = &display->extra_settings;
   flags = settings->required | settings->suggested;
   if (!(flags & (1 << ALLEGRO_AUTO_CONVERT_BITMAPS))) {
      settings->settings[ALLEGRO_AUTO_CONVERT_BITMAPS] = 1;
   }

   display->min_w = 0;
   display->min_h = 0;
   display->max_w = 0;
   display->max_h = 0;
   display->use_constraints = false;

   display->vertex_cache = 0;
   display->num_cache_vertices = 0;
   display->cache_enabled = false;
   display->vertex_cache_size = 0;
   display->cache_texture = 0;
   al_identity_transform(&display->projview_transform);

   display->default_shader = NULL;

   _al_vector_init(&display->display_invalidated_callbacks, sizeof(void *));
   _al_vector_init(&display->display_validated_callbacks, sizeof(void *));

   display->render_state.write_mask = ALLEGRO_MASK_RGBA | ALLEGRO_MASK_DEPTH;
   display->render_state.depth_test = false;
   display->render_state.depth_function = ALLEGRO_RENDER_LESS;
   display->render_state.alpha_test = false;
   display->render_state.alpha_function = ALLEGRO_RENDER_ALWAYS;
   display->render_state.alpha_test_value = 0;

   _al_vector_init(&display->bitmaps, sizeof(ALLEGRO_BITMAP*));

   if (settings->settings[ALLEGRO_COMPATIBLE_DISPLAY]) {
      al_set_target_bitmap(al_get_backbuffer(display));
   }
   else {
      ALLEGRO_DEBUG("ALLEGRO_COMPATIBLE_DISPLAY not set\n");
      _al_set_current_display_only(display);
   }

   if (display->flags & ALLEGRO_PROGRAMMABLE_PIPELINE) {
      display->default_shader = _al_create_default_shader(display->flags);
      if (!display->default_shader) {
         al_destroy_display(display);
         return NULL;
      }
      al_use_shader(display->default_shader);
   }

   /* Clear the screen */
   if (settings->settings[ALLEGRO_COMPATIBLE_DISPLAY]) {
      al_clear_to_color(al_map_rgb(0, 0, 0));

      /* TODO:
       * on iphone, don't kill the initial splashscreen - in fact, it's also
       * annoying in linux to have an extra black frame as first frame and I
       * suppose we never really want it
       */
#if 0
      al_flip_display();
#endif
   }

   if (settings->settings[ALLEGRO_AUTO_CONVERT_BITMAPS]) {
      /* We convert video bitmaps to memory bitmaps when the display is
       * destroyed, so seems only fair to re-convertt hem when the
       * display is re-created again.
       */
      al_convert_memory_bitmaps();
   }

   return display;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: rlam1/AL_Tank_game
int main(int argc, char* argv [])
{
    al_init();
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_image_addon();

	ALLEGRO_CONFIG *configFile = al_load_config_file("data/config/config.ini");
	if (configFile == NULL)
	{
		al_show_native_message_box(NULL, "A fatal error has ocurred!",
			"The configuration file has not been found!", 
			"Be sure to always have a valid conf.ini in /data/config/ for the program to work...", "Understood", ALLEGRO_MESSAGEBOX_ERROR);
		return 0;
	}

	std::string dispW = al_get_config_value(configFile, "DISPLAY", "RESX");
	std::string dispH = al_get_config_value(configFile, "DISPLAY", "RESY");
	std::string fullscreenMode = al_get_config_value(configFile, "DISPLAY", "FULLSCREEN");

	int iDispW = stoi(dispW);
	int iDispH = stoi(dispH);
	bool bfullscreenMode = stoi(fullscreenMode);

	assert(iDispW < 5000 && iDispW > 0);
	assert(iDispH < 5000 && iDispH > 0);

	if (bfullscreenMode == true)
		al_set_new_display_flags(ALLEGRO_FULLSCREEN);

	ALLEGRO_DISPLAY *display = al_create_display(iDispW, iDispH);
	if (display == NULL)
	{
		al_show_native_message_box(NULL, "A fatal error has ocurred!",
			"Display creation failed!",
			"The resolution selected is not supported by your screen/video card...", "Understood", ALLEGRO_MESSAGEBOX_ERROR);
		return 0;
	}

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

    bool done = false;
    bool redraw = false;

    ALLEGRO_TIMER *timer = al_create_timer(1.0 / 60.0);

    ALLEGRO_EVENT_QUEUE *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));

    //**********************
    ALLEGRO_BITMAP *test = al_load_bitmap("data/background.png");

    int x = 320, y = 240;

	Vec2D size(40.0f, 40.0f);

	TestObject gameObject(Vec2D(10.0f, 10.0f));
	gameObject.AddComponent(new RenderComponent());
    gameObject.AddComponent(new PhysicsComponent(size, size, size, true));
    //*********************

    al_start_timer(timer);

	//newManager.AddComponent(new PhysicsComponent(Vec2D(), Vec2D(), Vec2D(5.0f, 10.0f), false));

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

        switch (ev.type)
        {
            case ALLEGRO_EVENT_TIMER:
                redraw = true;
                gameObject.Update();
                break;
            case ALLEGRO_EVENT_DISPLAY_CLOSE:
                done = true;
                break;
            case ALLEGRO_EVENT_KEY_DOWN:
                if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
                {
                    done = true;
                }
                //************
                else
                {
					// NOTHING
                }
                //************
                break;
            default:
                break;
        }

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

            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_draw_bitmap(test, 0, 0, NULL);

			//PhysicsComponent *test = (PhysicsComponent*) newManager.GetComponentByType(COMP_PHYSICS);
			//Vec2D pos = test->GetPosition();

            al_draw_filled_circle(x, y, 89, al_map_rgb(255, 0, 255));

            al_flip_display();
        }
    }

	al_destroy_config(configFile);
    al_destroy_display(display);
    al_destroy_event_queue(queue);
    al_destroy_timer(timer);
}
コード例 #14
0
//Render for States
void
state_render ()
{
  if (state_switched)
    return;
  if (state_terminated)
    return;

  state_to_render = 1;
  state_to_force_render = 0;

//To Set up for Transition Render
  if (state_trans_curf >= 0)
    {
      if (rbufferorig == NULL)
	rbufferorig = al_clone_bitmap (rbuffer);
      if (transrbuffer == NULL)
	transrbuffer = al_clone_bitmap (rbuffer);
    }

//Common for All Games
  al_set_target_bitmap (rbuffer);
  handlers[state].proc_render ();

//Transition Render
  if (state_trans_curf >= 0 && state_trans_curf < state_trans_totf && strans
      && rbufferorig && transrbuffer)
    {
      strans (rbufferorig, rbuffer, transrbuffer, state_trans_curf++,
	      state_trans_totf);
      state_to_force_render = 1;
    }

//To Destroy Transition
  if (strans && (state_trans_curf >= state_trans_totf))
    {
      trans_stop ();
      state_to_force_render = 1;
    }

//Switch Modes
  if (state_to_switch_render)
    init_screen ();

//This is Because of GUI.    
  state_to_force_render = 1;

  if (state_to_force_render || state_to_switch_render || state_to_render)
    {
//Render to Screen
      al_set_target_backbuffer (screen);
      if (transrbuffer)
	blit (transrbuffer, 0, 0, 0, 0, xres, yres, 0);
      else
	blit (rbuffer, 0, 0, 0, 0, xres, yres, 0);
      gui_render ();
#ifdef LINUX
//VSync helped remove bad artifacts in Linux
      al_wait_for_vsync ();
#endif //LINUX
      al_flip_display ();
    }

  state_to_switch_render = 0;
}
コード例 #15
0
ファイル: engine.c プロジェクト: eliasYFGM/Luna2
void engine_run(struct State *s)
{
  int redraw = FALSE;

  if (engine_active)
    {
      return;
    }

  change_state(s, NULL);

  // Generate display events
  al_register_event_source(engine.event_queue,
                           al_get_display_event_source(engine.display));

  // Timer events
  al_register_event_source(engine.event_queue,
                           al_get_timer_event_source(engine.timer));

  // Keyboard events
  al_register_event_source(engine.event_queue,
                           al_get_keyboard_event_source());

  // Mouse events
  al_register_event_source(engine.event_queue,
                           al_get_mouse_event_source());

  al_start_timer(engine.timer);
  engine_active = TRUE;

  // Main game loop
  while (engine_active)
    {
      ALLEGRO_EVENT event;
      al_wait_for_event(engine.event_queue, &event);

      // Event processing
      engine.states[current_state]->_events(&event, &engine.sm);

      // If the close button was pressed...
      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
          engine_active = FALSE;
          break;
        }
      else if (event.type == ALLEGRO_EVENT_KEY_DOWN)
        {
          keys[event.keyboard.keycode] = TRUE;

          // F4 key will toggle full-screen
          if (event.keyboard.keycode == ALLEGRO_KEY_F4)
            {
              al_stop_timer(engine.timer);

              if (al_get_display_flags(engine.display)
                  & ALLEGRO_FULLSCREEN_WINDOW)
                {
                  al_toggle_display_flag(engine.display,
                                         ALLEGRO_FULLSCREEN_WINDOW, 0);
                }
              else
                {
                  al_toggle_display_flag(engine.display,
                                         ALLEGRO_FULLSCREEN_WINDOW, 1);
                }

              aspect_ratio_transform();

              al_start_timer(engine.timer);
            }
        }
      else if (event.type == ALLEGRO_EVENT_KEY_UP)
        {
          keys[event.keyboard.keycode] = FALSE;
        }
      else if (event.type == ALLEGRO_EVENT_TIMER)
        {
          engine.states[current_state]->_update(&engine.sm);
          redraw = TRUE;
        }

      if (redraw && engine_active
          && al_is_event_queue_empty(engine.event_queue))
        {
          redraw = FALSE;

          if (MAINCONF->buffer)
            {
              al_set_target_bitmap(engine.buffer);
            }
          else
            {
              al_set_target_backbuffer(engine.display);
            }

          al_clear_to_color(engine.bg_color);

          engine.states[current_state]->_draw(&engine.sm);

          if (MAINCONF->buffer)
            {
              al_set_target_backbuffer(engine.display);
              al_clear_to_color(C_BLACK);
              al_draw_bitmap(engine.buffer, 0, 0, 0);
            }

          al_flip_display();
        }
    }

  while (loaded_count > 0)
    {
      engine.loaded_states[--loaded_count]->_free();
    }

  al_destroy_display(engine.display);
  al_destroy_timer(engine.timer);
  al_destroy_event_queue(engine.event_queue);
  al_destroy_font(font);

  if (MAINCONF->buffer)
    {
      al_destroy_bitmap(engine.buffer);
    }
}
コード例 #16
0
/*
Main Loop running the project engine. Cycles through an infinite loop while States are still running.
Pushes in the first state of main menu of the editor application and it will cycle through the States registered events
Then it will perform that States keypress method and mouse activity method.
If a states resulting processing will decide that the state is no longer needed. EG: closing current map or option menu it will push or pop the State stack and destroy/dispose/clean those objects from memory.
If those State directions have not been triggered. The game will run the current states Update(game logic) method and then run the Draw method
*/
void EditorEngine::Run()
{

	ALLEGRO_EVENT ev;
	while(currentState_->GetRunning()){
		al_wait_for_event(currentState_->GetEventQueue(),&ev);



		currentState_->SetEvent(&ev);
		currentState_->KeyPress();
		currentState_->MouseActivity();

		if(currentState_->GetStateDirection() == STATEDIRECTION::PUSH){
			PushState();
			continue;
		}
		else if(currentState_->GetStateDirection() == STATEDIRECTION::POP){
			PopState();
			continue;
		}
		else if(currentState_->GetStateDirection() == STATEDIRECTION::POPPUSH){
			PopPushState();
			continue;
		}
		else if(currentState_->GetStateDirection() == STATEDIRECTION::POPTOFIRST){
			PopStateToFirst();
			continue;
		}
		if(currentState_->GetEvent()->type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			//close window if display is closed via X in top right corner
			currentState_->SetRunning(false);
		}
		currentState_->Update();
		if(currentState_->GetRedraw() && al_is_event_queue_empty(currentState_->GetEventQueue()))
		{
			currentState_->SetRedraw(false);
			currentState_->Draw();
			//bread and butter

			char text[20];
			sprintf(text, "%f", ev.timer.timestamp);
			al_draw_text(currentState_->GetFont(), chosenColorText_, 
				settings_->GetScreenWidth()-al_get_text_width(currentState_->GetFont(), text),
				settings_->GetScreenHeight() - Constants::TileSize(), ALLEGRO_ALIGN_LEFT, text);

			al_flip_display();
			al_clear_to_color(chosenColor_);//clears color to dark green to remove all back image
		}


		/*
		Get state done or not
		if done == true delete current state and Set new state
		if not done and state change push new state to stack
		if neither do normal again (-2 default)
		*/
		//Get keypress state
		//mmm change state
	}
}
コード例 #17
0
ファイル: main.c プロジェクト: 0ctobyte/speedrun
// The main Allegro loop, all input handling, animation and drawing is done here
_Bool main_loop(void)
{
    // Flag for drawing
    _Bool needredraw = true;
    // Declare primitive data types
    float old_time = 0.0, current_time = 0, dt = 0;

    while(!data->exit)
    {
        if(needredraw && al_event_queue_is_empty(data->queue) && al_event_queue_is_empty(data->queue2))
        {
            // Clear, draw, flip
            al_clear_to_color(data->background_color);
            render();
            if(get_fps_status())
                al_draw_textf(data->font, data->text_color, 0, res_height-30, 0, "fps: %.2f", 1/dt);
            al_flip_display();
            needredraw = false;
        }

        // Block until an event enters the queue
        al_wait_for_event(data->queue, &(data->event));

        while(!al_event_queue_is_empty(data->queue2))
        {
            al_get_next_event(data->queue2, &(data->event2));
            switch(data->event2.type)
            {
                case ALLEGRO_EVENT_DISPLAY_CLOSE:
                {
                    // If x button is pressed on window
                    data->exit = true;
                    data->gamestarted = false;
                }
                break;
                case ALLEGRO_EVENT_DISPLAY_RESIZE:
                {
                    al_acknowledge_resize(data->event2.display.source);
                    scale(res_width, res_height);
                }
                break;
                case ALLEGRO_EVENT_MOUSE_AXES:
                {
                    // Stores the mouse's new position and change in position
                    mouseaxes(&(data->event2.mouse));
                }
                case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
                {
                    // Stores the mouse button pressed
                    mousedown(&(data->event2.mouse));
                }
                break;
                case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
                {
                    // Stores the mouse button released
                    mouseup(&(data->event2.mouse));
                }
                break;
                case ALLEGRO_EVENT_KEY_DOWN:
                {
                    // Stores keydown keycode into keycode array for processing
                    keydown(&(data->event2.keyboard));
                }
                break;
                case ALLEGRO_EVENT_KEY_UP:
                {
                    // Stores keycode into keycode array for processing
                    keyup(&(data->event2.keyboard));
                }
                break;
                default:
                break;
            }
        }

        switch (data->event.type)
        {
            case ALLEGRO_EVENT_TIMER:
            {
                // Determine the change in time between frames, in seconds
				current_time = al_current_time();
				dt = current_time-old_time;

				// If the computer lags for some reason, don't penalize the player
				// Cap dt at 0.5 seconds
				if(dt > 0.25)
				{
                    dt = 0.25;
				}

				// Handle Mouse and Keyboard events and Button Events
				buttoncheck(&buttonhandler, data);
				keycheck(&keyhandler, data);
				mousecheck(&mousehandler, data);
				keyupdate();
                mouseupdate();

                // Check if data->quit has been set before updating and drawing
                if(data->exit) break;

                // Update the game, always
                update();

                // Skip drawing frames if computer lags
                if(current_time - data->event.timer.timestamp <= 1.0/al_get_display_refresh_rate(data->display))
                {
                    needredraw = true;
                }

				// Make the time at this frame the old time, for the next frame
				old_time = current_time;
            }
            break;
            default:
            break;
        }
    }
    return true;
}
コード例 #18
0
ファイル: main.cpp プロジェクト: pmprog/ROTMenu
int main( int argc, char* argv[] )
{
	ALLEGRO_EVENT e;
	ALLEGRO_TIMER* t;
	int64_t framesToUpdate = 0;

	if( !al_init() )
	{
		return -1;
	}
	
	al_init_font_addon();
	if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
	{
		return -1;
	}

#if NETWORK_SUPPORT != 0
	if( !install_network() )
	{
		return -1;
	}
#endif

#if HTTP_SUPPORT
	if( !install_http() )
	{
		return -1;
	}
#ifdef PANDORA
	Downloads = new HttpManager(2);
#else
	Downloads = new HttpManager(6);
#endif
#endif

#if EXIT_IF_NO_AUDIO != 0

	if( !al_install_audio() || !al_init_acodec_addon() )
	{
		return -1;
	}

	voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
	if (!voice)
		return 1;
	mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	if (!mixer)
		return 1;
	if (!al_attach_mixer_to_voice(mixer, voice))
		return 1;

#else

	if( al_install_audio() )
	{
		if( al_init_acodec_addon() )
		{
			voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
			if( voice != 0 )
			{
				mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
				if( mixer != 0 )
					al_attach_mixer_to_voice(mixer, voice);
			}
		}
	}

#endif // EXIT_IF_NO_AUDIO

	// Random number is guarenteed to be random
	srand( 5 );

	GameStack = new StageStack();
	CurrentConfiguration = new Configuration();

	if( CurrentConfiguration->FullScreen )
		al_set_new_display_flags( ALLEGRO_FULLSCREEN_WINDOW );

	al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);

	bool foundMode = false;
	int fallbackW = 640;
	int fallbackH = 480;

	if( CurrentConfiguration->ForceResolution )
	{
		foundMode = true;
	} else {
		for( int modeIdx = 0; modeIdx < al_get_num_display_modes(); modeIdx++ )
		{
			if( al_get_display_mode( modeIdx, &ScreenMode ) != NULL )
			{
				if( ScreenMode.width == CurrentConfiguration->ScreenWidth && ScreenMode.height == CurrentConfiguration->ScreenHeight )
				{
					foundMode = true;
				} else {
					fallbackW = ScreenMode.width;
					fallbackH = ScreenMode.height;
				}
			}

			if( foundMode )
				break;
		}
	}

	if( foundMode )
	{
		Screen = al_create_display( CurrentConfiguration->ScreenWidth, CurrentConfiguration->ScreenHeight );
	} else {
		Screen = al_create_display( fallbackW, fallbackH );
		CurrentConfiguration->ScreenWidth = fallbackW;
		CurrentConfiguration->ScreenHeight = fallbackH;
	}

	al_hide_mouse_cursor( Screen );

	t = al_create_timer( 1.0 / SCREEN_FPS );
  if( t == NULL )
    Quit = true;
  al_start_timer( t );

	EventQueue = al_create_event_queue();
	al_register_event_source( EventQueue, al_get_display_event_source( Screen ) );
	al_register_event_source( EventQueue, al_get_keyboard_event_source() );
	al_register_event_source( EventQueue, al_get_mouse_event_source() );
	al_register_event_source( EventQueue, al_get_timer_event_source( t ) );
#if NETWORK_SUPPORT != 0
	al_register_event_source( EventQueue, get_network_event_source() );
#endif
#if HTTP_SUPPORT
	Downloads->urlDownloads = CurrentConfiguration->MaxConcurrentDownloads;
	al_register_event_source( EventQueue, get_http_event_source() );
#endif

	Fonts = new FontManager();
	Images = new ImageManager();
	Audio = new SoundManager();

	al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA );

	GameStack->Push( (Stage*)new BootUp() );

	while( !Quit )
	{
		if( GameStack->IsEmpty() )
		{
			Quit = true;
		} else {
			while( al_get_next_event( EventQueue, &e ) )
			{
#if HTTP_SUPPORT
				Downloads->Event( &e );
#endif
				switch( e.type )
				{
					case ALLEGRO_EVENT_DISPLAY_CLOSE:
						Quit = true;
						break;
					case ALLEGRO_EVENT_JOYSTICK_CONFIGURATION:
						al_reconfigure_joysticks();
						break;
					case ALLEGRO_EVENT_TIMER:
						if( e.timer.source == t )
							framesToUpdate++;
						else if( !GameStack->IsEmpty() )
							GameStack->Current()->Event( &e );
						break;
					default:
						if( !GameStack->IsEmpty() )
							GameStack->Current()->Event( &e );
						switch( e.type )
						{
#if HTTP_SUPPORT
							case ALLEGRO_EVENT_HTTP:
#endif
#if NETWORK_SUPPORT
							case ALLEGRO_EVENT_NETWORK_CONNECTION:
							case ALLEGRO_EVENT_NETWORK_RECEIVEPACKET:
							case ALLEGRO_EVENT_NETWORK_DISCONNECTION:
#endif
							case ALLEGRO_EVENT_BUTTON_CLICK:
							case ALLEGRO_EVENT_MOUSEEX_MOVE:
							case ALLEGRO_EVENT_MOUSEEX_DOWN:
							case ALLEGRO_EVENT_MOUSEEX_UP:
							case ALLEGRO_EVENT_MOUSEEX_CLICK:
							case ALLEGRO_EVENT_MOUSEEX_DOUBLECLICK:
							case ALLEGRO_EVENT_MOUSEEX_BOXED:
							case ALLEGRO_EVENT_MOUSEEX_WHEEL:
								al_unref_user_event( &e.user );
								break;
						}
						break;
				}
			}

			if( framesToUpdate > 0 )
			{
				for( int frmUp = 0; frmUp < framesToUpdate; frmUp++ )
				{
					if( !GameStack->IsEmpty() )
						GameStack->Current()->Update();
				}
				framesToUpdate = 0;
			}

			al_clear_to_color( al_map_rgb( 128, 128, 128 ) );
			if( !GameStack->IsEmpty() )
				GameStack->Current()->Render();
			al_flip_display();

			Images->Tidy();
			Fonts->Tidy();
			Audio->Tidy();
		}
	}

	while( !GameStack->IsEmpty() )
	{
		GameStack->Pop();
	}

	delete Downloads;
	delete Fonts;
	delete Images;
	delete Audio;

	al_destroy_event_queue( EventQueue );
	al_destroy_display( Screen );

#if HTTP_SUPPORT
	uninstall_http();
#endif
#if NETWORK_SUPPORT != 0
	uninstall_network();
#endif
	al_uninstall_keyboard();
	al_uninstall_mouse();
	al_shutdown_primitives_addon();
	al_shutdown_ttf_addon();
	al_shutdown_image_addon();
	al_uninstall_audio();
	al_shutdown_font_addon();

	return 0;
}
コード例 #19
0
ファイル: _test_allegro_display.c プロジェクト: ifzz/exsdk
int main( void ) {

   ALLEGRO_DISPLAY *display;
   ALLEGRO_KEYBOARD_STATE key_state;
   Point stars[3][NUM_STARS/3];
   float speeds[3] = { 0.0001f, 0.05f, 0.15f };
   ALLEGRO_COLOR colors[3];
   long start, now, elapsed, frame_count;
   int total_frames = 0;
   double program_start;
   double length;
   int layer, star;

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

   al_install_keyboard();
   
   display = al_create_display(WIDTH, HEIGHT);
   if (!display) {
      abort_app("Could not create display.\n");
      return 1;
   }

   colors[0] = al_map_rgba(255, 100, 255, 128);
   colors[1] = al_map_rgba(255, 100, 100, 255);
   colors[2] = al_map_rgba(100, 100, 255, 255);
         
   for (layer = 0; layer < 3; layer++) {
      for (star = 0; star < NUM_STARS/3; star++) {
         Point *p = &stars[layer][star];
         p->x = rand() % WIDTH;
         p->y = rand() % HEIGHT;
      }
   }


   start = al_get_time() * 1000;
   now = start;
   elapsed = 0;
   frame_count = 0;
   program_start = al_get_time();


   while (1) {
      if (frame_count < (1000/TARGET_FPS)) {
         frame_count += elapsed;
      }
      else {
         int X, Y;

         frame_count -= (1000/TARGET_FPS);
         al_clear_to_color(al_map_rgb(0, 0, 0));
         for (star = 0; star < NUM_STARS/3; star++) {
            Point *p = &stars[0][star];
            al_draw_pixel(p->x, p->y, colors[0]);
         }
         al_lock_bitmap(al_get_backbuffer(display), ALLEGRO_PIXEL_FORMAT_ANY, 0);

         for (layer = 1; layer < 3; layer++) {
            for (star = 0; star < NUM_STARS/3; star++) {
               Point *p = &stars[layer][star];
               // put_pixel ignores blending
               al_put_pixel(p->x, p->y, colors[layer]);
            }
         }

         /* Check that dots appear at the window extremes. */
         X = WIDTH - 1;
         Y = HEIGHT - 1;
         al_put_pixel(0, 0, al_map_rgb_f(1, 1, 1));
         al_put_pixel(X, 0, al_map_rgb_f(1, 1, 1));
         al_put_pixel(0, Y, al_map_rgb_f(1, 1, 1));
         al_put_pixel(X, Y, al_map_rgb_f(1, 1, 1));

         al_unlock_bitmap(al_get_backbuffer(display));
         al_flip_display();
         total_frames++;
      }

      now = al_get_time() * 1000;
      elapsed = now - start;
      start = now;

      for (layer = 0; layer < 3; layer++) {
         for (star = 0; star < NUM_STARS/3; star++) {
            Point *p = &stars[layer][star];
            p->y -= speeds[layer] * elapsed;
            if (p->y < 0) {
               p->x = rand() % WIDTH;
               p->y = HEIGHT;
            }
         }
      }

      al_rest(0.001);

      al_get_keyboard_state(&key_state);
      if (al_key_down(&key_state, ALLEGRO_KEY_ESCAPE))
         break;
   }

   length = al_get_time() - program_start;

   if (length != 0) {
      printf("%d FPS\n", (int)(total_frames / length));
   }

   al_destroy_display(display);

   return 0;
}
コード例 #20
0
ファイル: main.cpp プロジェクト: DanielScariot/Projeto_Jogo
int main(int argc, char const *argv[])
{
    int i = 0;
    int t = 1;

    int n_mostros = 5;
    bool click = false;
    bool nova_horda = true;
    bool render = false;
    bool torre_mouse = false;

    char a;
    char b;
    int r;
    int l;

    Sistema sistema;
    Torre torre[10];
    Tiro tiro[10];
    Monstro monstro[n_mostros];
    Coord coordenada[A*B];

    //Declara�ao vair�veis 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

    //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();

    a_coord(coordenada, fonte);
    init_horda(monstro, n_mostros);
    init_system(sistema);
    initTorre(torre, tiro, t-1);



    //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.png");
    timer = al_create_timer(1.0 / fps);
    fonte = al_load_font("arial.ttf", 12, 0);    //Fonte DejaVu

    //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); //Fun�ao de teste

    //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);

        if(evento.type == ALLEGRO_EVENT_TIMER)  //Evento de renderiza�ao
        {
            i++;
            render = true;

            FireTiro(tiro, torre, monstro, t-1);
            UpdateTiro(tiro, monstro, t-1);
            update_horda(monstro, mapa, n_mostros);
            colisao_horda(tiro, monstro, n_mostros);

        }

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

        else if(evento.type == ALLEGRO_EVENT_MOUSE_AXES)
        {
            pos_x = evento.mouse.x;
            pos_y = evento.mouse.y;

            a =  coordenada[(pos_x/l_celula)].letra[0];
            b =  coordenada[(pos_x/l_celula)].letra[1];
            l =  coordenada[(pos_y/a_celula)].numero;

            r = conversao_coordenadas(coordenada, a, b);
        }

        else if(evento.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
        {
            if (mapa[pos_y/a_celula][pos_x/l_celula] == 9)
            {
                torre_mouse = true;
                torre[t].in_mouse = true;
            }
            if(torre_mouse && !click)
            {
                if (mapa[pos_y/a_celula][pos_x/l_celula] != 9)
                {
                    mapa[pos_y/a_celula][pos_x/l_celula] = 10;
                    torre_mouse = false;
                    torre[t].in_mouse = false;
                    t++;
                }
            }
            click = !click;
        }

        else if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(evento.keyboard.keycode)
            {
            case ALLEGRO_KEY_SPACE:
                start_horda(monstro, n_mostros);
                break;
            }
        }
        else if(render && al_is_event_queue_empty(fila_eventos))
        {
            render = false;

            coor_matrix(mapa, coordenada, fonte);

            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/4, 50, ALLEGRO_ALIGN_CENTRE, "Taxa de Frames: %i", i);
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y, ALLEGRO_ALIGN_LEFT, "   x:%i y:%i", pos_x, pos_y);

            draw_horda(monstro, n_mostros, imagem);

            if(torre_mouse)
            {
                draw_tower(r, l, torre, t);
            }
            drawTiro(tiro, t-1);

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

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

    return 0;
}
コード例 #21
0
int main(void)
{
	//variables
	int width = 640;
	int height = 480;
	bool done = false;

	int x = width / 2;
	int y = height / 2;

	const int maxFrame = 8;
	int curFrame = 0;
	int frameCount = 0;
	int frameDelay = 5;

	//allegro variable
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer;
	ALLEGRO_BITMAP *image[maxFrame];

	//program init
	if (!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(width, height);			//create our display object

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

	//addon init
	al_install_keyboard();
	al_init_image_addon();

	image[0] = al_load_bitmap("./images/dragon/fliegt e0000.bmp");
	image[1] = al_load_bitmap("./images/dragon/fliegt e0001.bmp");
	image[2] = al_load_bitmap("./images/dragon/fliegt e0002.bmp");
	image[3] = al_load_bitmap("./images/dragon/fliegt e0003.bmp");
	image[4] = al_load_bitmap("./images/dragon/fliegt e0004.bmp");
	image[5] = al_load_bitmap("./images/dragon/fliegt e0005.bmp");
	image[6] = al_load_bitmap("./images/dragon/fliegt e0006.bmp");
	image[7] = al_load_bitmap("./images/dragon/fliegt e0007.bmp");

	for (int i = 0; i < maxFrame; i++)
		al_convert_mask_to_alpha(image[i], al_map_rgb(106, 76, 48));

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

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

	al_start_timer(timer);

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

		if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:

				break;
			case ALLEGRO_KEY_RIGHT:

				break;
			case ALLEGRO_KEY_UP:

				break;
			case ALLEGRO_KEY_DOWN:

				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			if (++frameCount >= frameDelay)
			{
				if (++curFrame >= maxFrame)
					curFrame = 0;

				frameCount = 0;
			}

		}

		al_draw_bitmap(image[curFrame], x, y, 0);

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

	for (int i = 0; i < maxFrame; i++)al_destroy_bitmap(image[i]);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);						//destroy our display object

	return 0;
}
コード例 #22
0
int main(void)
{
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_MONITOR_INFO info;
   int w = 640, h = 480;
   bool done = false;
   bool need_redraw = true;
   bool background = false;

   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();

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

   al_get_num_video_adapters();
   
   al_get_monitor_info(0, &info);

   #ifdef ALLEGRO_IPHONE
   al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
   #endif
   al_set_new_display_option(ALLEGRO_SUPPORTED_ORIENTATIONS,
      ALLEGRO_DISPLAY_ORIENTATION_ALL, ALLEGRO_SUGGEST);

   al_set_new_display_option(ALLEGRO_DEPTH_SIZE, 8, ALLEGRO_SUGGEST);

   al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);

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

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

   example.font = al_load_font("data/DejaVuSans.ttf", 40, 0);
   if (!example.font) {
      abort_example("Error loading data/DejaVuSans.ttf\n");
      return 1;
   }

   example.font2 = al_load_font("data/DejaVuSans.ttf", 12, 0);
   if (!example.font2) {
      abort_example("Error loading data/DejaVuSans.ttf\n");
      return 1;
   }

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

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

   init();

   timer = al_create_timer(1.0 / FPS);

   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(example.display));

   al_start_timer(timer);

   while (!done) {
      ALLEGRO_EVENT event;
      w = al_get_display_width(example.display);
      h = al_get_display_height(example.display);

      if (!background && need_redraw && al_is_event_queue_empty(queue)) {
         double t = -al_get_time();

         redraw();
         
         t += al_get_time();
         example.direct_speed_measure  = t;
         al_flip_display();
         need_redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_CHAR:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_DISPLAY_HALT_DRAWING:

            background = true;
            al_acknowledge_drawing_halt(event.display.source);

            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING:
            background = false;
            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;
              
         case ALLEGRO_EVENT_TIMER:
            update();
            need_redraw = true;
            break;
      }
   }

   return 0;
}
コード例 #23
0
ファイル: engine.c プロジェクト: eliasYFGM/allegro-templates
void engine_run(struct State *first)
{
  int redraw = FALSE;

  if (engine_active)
  {
    puts("WARNING: Calling game_run() more than once");
    return;
  }

  change_state(first);

  // Generate display events
  al_register_event_source(engine.event_queue,
    al_get_display_event_source(engine.display));

  // Timer events
  al_register_event_source(engine.event_queue,
    al_get_timer_event_source(engine.timer));

  // Keyboard events
  al_register_event_source(engine.event_queue, al_get_keyboard_event_source());

  al_start_timer(engine.timer);
  engine_active = TRUE;

  // Main game loop
  while (engine_active)
  {
    ALLEGRO_EVENT event;
    al_wait_for_event(engine.event_queue, &event);

    // Event processing
    engine.states[current_state]->_events(&event);

    // If the close button was pressed...
    if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
    {
      engine_active = FALSE;
      break;
    }
    else if (event.type == ALLEGRO_EVENT_KEY_DOWN)
    {
      keys[event.keyboard.keycode] = TRUE;

      // Escape key will end the game
      if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
      {
        engine_active = FALSE;
        break;
      }
    }
    else if (event.type == ALLEGRO_EVENT_KEY_UP)
    {
      keys[event.keyboard.keycode] = FALSE;
    }
    else if (event.type == ALLEGRO_EVENT_TIMER)
    {
      engine.states[current_state]->_update();
      redraw = TRUE;
    }

    if (redraw && al_event_queue_is_empty(engine.event_queue))
    {
      redraw = FALSE;

      al_set_target_backbuffer(engine.display);

      al_clear_to_color(engine.bg_color);

      engine.states[current_state]->_draw();

      al_flip_display();
    }
  }

  while (current_state >= 0)
  {
    engine.states[current_state--]->_end();
  }

  al_destroy_display(engine.display);
  al_destroy_timer(engine.timer);
  al_destroy_event_queue(engine.event_queue);
  al_destroy_font(font);
}
コード例 #24
0
ファイル: main.cpp プロジェクト: jaonz/0blivion
int main(int argc, char **argv)
{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *tapl = NULL;
	ALLEGRO_BITMAP *tapr = NULL;
	ALLEGRO_BITMAP *bounce = NULL;
	float tapl_x = 0.0;
	float tapl_y = SCREEN_H / 2.0 - TAP_HEIGHT / 2.0;
	float tapr_x = SCREEN_W - TAP_WIDTH - 1.0;
	float tapr_y = SCREEN_H / 2.0 - TAP_HEIGHT / 2.0;
	float bounce_x = SCREEN_W / 2.0 - BOUNCE_SIZE / 2.0;
	float bounce_y = SCREEN_H / 2.0 - BOUNCE_SIZE / 2.0;
	float bounce_dx = -4.0, bounce_dy = 4.0;  
	bool key[6] = { false, false, false, false, false, false };
	bool redraw = true;
	bool doexit = false;

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

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

	timer = al_create_timer(1.0 / FPS); //criando temporizador (FPS)

	display = al_create_display(SCREEN_W, SCREEN_H); //criando o display

	tapl = al_create_bitmap(TAP_WIDTH, TAP_HEIGHT); //criando o rebatedor esquerdo (vermelho)

	tapr = al_create_bitmap(TAP_WIDTH, TAP_HEIGHT); //criando o rebatedor direito (azul)

	bounce = al_create_bitmap(BOUNCE_SIZE, BOUNCE_SIZE); //criando a bounce (branco)

	//setando cores dos bitmaps
	al_set_target_bitmap(tapl); //setando o target pro rebatedor esquerdo

	al_clear_to_color(al_map_rgb(255, 0, 0)); //setando a cor do target (rebatedor esquerdo)

	al_set_target_bitmap(tapr); //setando o target pro rebatedor direito

	al_clear_to_color(al_map_rgb(0, 0, 255)); //setando a cor do target (rebatedor direito)

	al_set_target_bitmap(bounce); //setando o target pra bounce

	al_clear_to_color(al_map_rgb(255, 255, 255)); //setando a cor do target

	al_set_target_bitmap(al_get_backbuffer(display)); //setando o target pro display


	event_queue = al_create_event_queue(); //iniciando o leitor de eventos

	al_register_event_source(event_queue, al_get_display_event_source(display)); //registrando os eventos do display

	al_register_event_source(event_queue, al_get_timer_event_source(timer)); //registrando os eventos do temporizador

	al_register_event_source(event_queue, al_get_keyboard_event_source()); //registrando os eventos do teclado

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

	al_flip_display();

	al_start_timer(timer);
	 
	while(!doexit) {
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);		
		
		if(key[KEY_ENTER]) {
			redraw = true;
		}
		
		if(key[KEY_P]) {
			redraw = false;
		}
		
		if(ev.type == ALLEGRO_EVENT_TIMER) {
			if(redraw == true){
				if(
					bounce_x - bounce_dx < tapl_x + (TAP_WIDTH + 14.0)&&
					bounce_x + bounce_dx > tapl_x - TAP_WIDTH &&
					bounce_y - bounce_dy < tapl_y + TAP_HEIGHT &&
					bounce_y + bounce_dy > tapl_y - TAP_HEIGHT 
					) 
				{

					bounce_dx = bounce_dx + 1;

				}
			
				if(
					bounce_x - bounce_dx < tapr_x + (TAP_WIDTH + 0.0)&&
					bounce_x + bounce_dx > tapr_x - (TAP_WIDTH + 15.0)&&
					bounce_y - bounce_dy < tapr_y + TAP_HEIGHT &&
					bounce_y + bounce_dy > tapr_y - TAP_HEIGHT 
					)
				{

					bounce_dx -= 11;

				}
			
				if(bounce_x < 0) { 
					al_destroy_timer(timer);

				}
			
				if(bounce_x > SCREEN_W - BOUNCE_SIZE) {
					al_destroy_timer(timer);      	 

				}
			
				if(bounce_y < 0 || bounce_y > SCREEN_H - BOUNCE_SIZE) { //aqui rebate normal no eixo da altura
					bounce_dy = -bounce_dy;
				}

				bounce_x += bounce_dx;
				bounce_y += bounce_dy;
			
				if(key[KEY_W] && tapl_y >= 4.0) {
					tapl_y -= 4.0;
				}

				if(key[KEY_S] && tapl_y <= SCREEN_H - TAP_HEIGHT - 4.0) {
					tapl_y += 4.0;
				}

				if(key[KEY_UP] && tapr_y >= 4.0) {
					tapr_y -= 4.0;
				}
			
				if(key[KEY_DOWN] && tapr_y <= SCREEN_H - TAP_HEIGHT - 4.0) {
					tapr_y += 4.0;
				}
			

			}
		
		}
		
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch(ev.keyboard.keycode) {
			case ALLEGRO_KEY_W:
			key[KEY_W] = true;
			break;

			case ALLEGRO_KEY_S:
			key[KEY_S] = true;
			break;

			case ALLEGRO_KEY_UP:
			key[KEY_UP] = true;
			break;

			case ALLEGRO_KEY_DOWN:
			key[KEY_DOWN] = true;
			break;
			
			case ALLEGRO_KEY_P:
			key[KEY_ENTER] = false;
			key[KEY_P] = true;
			break;
			
			case ALLEGRO_KEY_ENTER:
			key[KEY_P] = false;
			key[KEY_ENTER] = true;
			break;
			
			}			
		}
		
		else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch(ev.keyboard.keycode) {
			case ALLEGRO_KEY_W:
			key[KEY_W] = false;
			break;

			case ALLEGRO_KEY_S:
			key[KEY_S] = false;
			break;

			case ALLEGRO_KEY_UP: 
			key[KEY_UP] = false;
			break;

			case ALLEGRO_KEY_DOWN:
			key[KEY_DOWN] = false;
			break;
			
			case ALLEGRO_KEY_ESCAPE:
			doexit = true;
			break;

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

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

			al_draw_bitmap(tapl, tapl_x, tapl_y, 0);
		 
			al_draw_bitmap(tapr, tapr_x, tapr_y, 0);
		 
			al_draw_bitmap(bounce, bounce_x, bounce_y, 0);
		  
			al_flip_display();
		}

   }
 
   
   al_destroy_bitmap(tapl);
   al_destroy_bitmap(tapr);
   al_destroy_bitmap(bounce);
   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);
   
   return 0;
}
コード例 #25
0
ファイル: coche.cpp プロジェクト: DaniCF/Programs-in-C
int main(int argc, char **argv)
{
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_BITMAP *bouncer = NULL;
    float angle = 0;
    float length = 0;
    float vel_x, vel_y;
    float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE_Y / 2.0;
    float bouncer_y = SCREEN_H / 2.0 - BOUNCER_SIZE_Y / 2.0;
    bool key[5] = { false, false, false, false, false };
    bool redraw = true;
    bool doexit = false;



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


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

    timer = al_create_timer(1.0 / FPS);
    if(!timer) {
        fprintf(stderr, "failed to create timer!\n");
        return -1;
    }

    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display) {
        fprintf(stderr, "failed to create display!\n");
        al_destroy_timer(timer);
        return -1;
    }

    bouncer = al_create_bitmap(BOUNCER_SIZE_X,BOUNCER_SIZE_Y);

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

    al_set_target_bitmap(bouncer);

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

    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;
    }

    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_register_event_source(event_queue, al_get_keyboard_event_source());

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

    al_flip_display();

    al_start_timer(timer);

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

        if(ev.type == ALLEGRO_EVENT_TIMER) {
            if(key[KEY_UP] && length < 15) {
                length += 1;

            }
            else if(length > 0) {
                length -= 0.1;
            }

            if(key[KEY_DOWN] && length > 0) {
                length -= 1;
            }

            if(key[KEY_LEFT]) {
                angle = (angle - 0.1);
            }

            if(key[KEY_RIGHT]) {
                angle = (angle + 0.1);
            }

            if(key[KEY_SPACE]) {



            }

            vel_x = length * cos(angle);
            vel_y = length * sin(angle);
            bouncer_x += vel_x;
            bouncer_y += vel_y;

            redraw = true;
        }


        else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
            break;
        }
        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;
            case ALLEGRO_KEY_SPACE:
                key[KEY_SPACE] = true;
                break;
            }
        }
        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_SPACE:
                key[KEY_SPACE] = false;
                break;

            case ALLEGRO_KEY_ESCAPE:
                doexit = true;
                break;
            }
        }

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

            al_clear_to_color(al_map_rgb(240,240,240));

            al_draw_rotated_bitmap(bouncer, BOUNCER_SIZE_X / 2, BOUNCER_SIZE_Y / 2, bouncer_x, bouncer_y, angle, angle);




            al_flip_display();
        }
    }

    al_destroy_bitmap(bouncer);
    al_destroy_timer(timer);
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);

    return 0;
}
コード例 #26
0
ファイル: allegro.c プロジェクト: renatocf/MAC0211-EP4
void gui_window_update (int lifes)
{
    gui_river_heart(lifes);
    al_flip_display();
}
コード例 #27
0
ファイル: GameMenu.c プロジェクト: lucasteles/Heredian
void gdp_intro(){
    ALLEGRO_BITMAP *image   = NULL;
    ALLEGRO_FONT *fonte     = al_load_font(".//Fonts//font_intro.TTF", 20, 0);
    // musica de fundo
    ALLEGRO_SAMPLE *music   = al_load_sample(".//Songs//Intro//intro_music.ogg");
    al_play_sample(music, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_LOOP, NULL);
    // narrador
    ALLEGRO_SAMPLE *narrative   = al_load_sample(".//Songs//Intro//intro_narrative.ogg");
    al_play_sample(narrative, 2.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);

    char* ConfigFile = "Configs//Intro.txt";
    char* mold = "lin%i";
    char* cLine = NULL, *cLineAux=NULL;
    double speed = gdp_files_quick_getfloat(ConfigFile,"speed_text");

    int space = 45, xi=0, i=0;
    int lines = gdp_files_quick_getint(ConfigFile,"num_lines");
    char **texto = calloc(lines,sizeof(char*));
    double posicao = 0,limite = -height-(space*lines);

    for(xi=0;xi<lines;xi++)
    {
        cLine = calloc(10,sizeof(char*));

        sprintf(cLine,mold,xi+1);

        cLineAux = gdp_files_quick_getstring(ConfigFile, cLine);

        texto[xi] = cLineAux;

        free(cLine);
    }

    while(true){
        al_wait_for_event(event_queue, &evento);

        if(gdp_readclose()){
            break;
        }
        if(evento.type == ALLEGRO_EVENT_KEY_DOWN){
            break;
        }

        if(gdp_readtime() && al_is_event_queue_empty(event_queue)){
            gdp_clear();
            for(i=0;i<lines;i++)
                al_draw_textf(fonte, al_map_rgb(255, 255, 255), wigth / 2, (int)height+posicao+(space*i) ,ALLEGRO_ALIGN_CENTRE, "%s", texto[i]);

            al_flip_display();
            posicao -= speed;
            if(posicao < limite)
                break;
        }
    }

    free(texto);
    al_destroy_bitmap(image);
    al_destroy_sample(music);
    al_destroy_sample(narrative);
    al_destroy_font(fonte);
}
コード例 #28
0
ファイル: pause_menu.cpp プロジェクト: Coolcord/Trake
void Pause_Menu::show()
{
  bool paused = true;
  while (paused)
  {
    this->draw();
	al_flip_display();

    ALLEGRO_EVENT e;
    al_wait_for_event(m_event, &e);
    if (e.type == ALLEGRO_EVENT_KEY_DOWN)
    {
      switch(m_controls->get_control(e.keyboard.keycode))
      {
        case Controls::NONE:
          break;
        case Controls::PLAYER_1_LEFT:
        case Controls::PLAYER_2_LEFT:
        case Controls::PLAYER_3_LEFT:
        case Controls::PLAYER_4_LEFT:
          if (m_selection == 1)
          {
            if (m_move_sound_down) al_play_sample(m_move_sound_down, 2.5*m_sound_effects_level*0.1, 0.0, 1.2, ALLEGRO_PLAYMODE_ONCE, NULL);
            m_selection = 0;
          }
          break;
        case Controls::PLAYER_1_RIGHT:
        case Controls::PLAYER_2_RIGHT:
        case Controls::PLAYER_3_RIGHT:
        case Controls::PLAYER_4_RIGHT:
          if (m_selection == 0)
          {
            if (m_move_sound_up) al_play_sample(m_move_sound_down, 2.5*m_sound_effects_level*0.1, 0.0, 1.2, ALLEGRO_PLAYMODE_ONCE, NULL);
            m_selection = 1;
          }
          break;
        case Controls::PLAYER_1_CONFIRM:
        case Controls::PLAYER_2_CONFIRM:
        case Controls::PLAYER_3_CONFIRM:
        case Controls::PLAYER_4_CONFIRM:
          if (m_move_sound_up) al_play_sample(m_move_sound_down, 2.5*m_sound_effects_level*0.1, 0.0, 1.5, ALLEGRO_PLAYMODE_ONCE, NULL);
          if (m_selection == 0) //No
            paused = false;
          else //Yes
          {
            paused = false;
            *m_quit = true;
            *m_hide_standing = true;
            *m_rounds = m_total_rounds;
          }
          break;
        case Controls::PLAYER_1_CANCEL:
        case Controls::PLAYER_2_CANCEL:
        case Controls::PLAYER_3_CANCEL:
        case Controls::PLAYER_4_CANCEL:
          paused = false;
          break;
        default:
          break;
      }
    }
  }
}
コード例 #29
0
ファイル: main.cpp プロジェクト: khellwan/FINAL
int main(int argc, char *argv[])
{

// -------- VARIÁVEIS DO JOGO --------
ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font20 = NULL;
ALLEGRO_SAMPLE *ataque = NULL;
ALLEGRO_SAMPLE *morte_inimigo = NULL;
ALLEGRO_SAMPLE *morte_personagem = NULL;
ALLEGRO_SAMPLE *hit = NULL;
ALLEGRO_SAMPLE *item = NULL;
ALLEGRO_AUDIO_STREAM *musica = NULL;
ALLEGRO_AUDIO_STREAM *track_menu = NULL;
ALLEGRO_BITMAP *start = NULL;

bool fim = false;
bool menu = true;
int flag = 0;
bool desenha = true;
bool game_over = false;
bool teclas[] = {false, false, false, false, false, false, false};
int i;
int dificuldade;


// ___________________________________


// -------- INICIALIZAÇÃO DE OBJETOS --------
dificuldade = 0;
Personagem personagem_principal;
Projetil* balas = new Projetil [NUM_BALAS];
Projetil* balas_2 = new Projetil [NUM_BALAS];
Inimigo* inimigos = new Inimigo[NUM_INIMIGOS];
Inimigo* inimigos2 = new Inimigo [NUM_INIMIGOS];
Coracao* coracoes = new Coracao[NUM_ITENS];
Speed* speed = new Speed[NUM_ITENS];
ItemPontos* pontos = new ItemPontos[NUM_ITENS];
Estrelas estrelas_pf[NUM_PLANOS][NUM_ESTRELAS];
Selecionar select;


// __________________________________________

// -------- INICIALIZAÇÃO DA ALLEGRO E DO DISPLAY --------
    ALLEGRO_DISPLAY *display = NULL;

    if (!al_init())
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO INICIALIZAR A ALLEGRO!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    display = al_create_display(LARGURA_T, ALTURA_T);

    if (!display)
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO CRIAR O DISPLAY!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    al_set_window_title(display, "Cosmos Guardian");


// ____________________________________________________

// -------- INICIALIZAÇÃO DE ADDONS E INSTALAÇÕES --------
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_install_audio();
    al_init_acodec_addon();

    al_reserve_samples(100);

// _______________________________________________________

// -------- CRIAÇÃO DE FILAS E DEMAIS DISPOSITIVOS --------
    fila_eventos = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    font20 = al_load_font("BADABB__.ttf", 20, 0);


// ________________________________________________________

// -------- REGISTRO DE SOURCES --------
    al_register_event_source(fila_eventos, al_get_display_event_source(display));
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

// _____________________________________


// -------- FUNÇÕES INICIAIS --------
    srand(time(NULL));
    personagem_principal.InitPersonagem();

    select.InitSelecionar();

    //Inicialização de projeteis
    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].InitBalas();
        balas_2[i].InitBalas();
    }

    //Inicialização de inimigos
    for (i = 0; i < NUM_INIMIGOS; i++)
    {
        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
    }

    //Inicialização de itens
    for (i = 0; i < NUM_ITENS; i++)
    {
        coracoes[i].InitItem();
        speed[i].InitItem();
        pontos[i].InitItem();
    }

    //Inicialização do Plano de Fundo
    InitPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);

    //Setando Sons e Imagens
    select.bmp = al_load_bitmap("select.png");
    ataque = al_load_sample("laser.wav");
    morte_inimigo = al_load_sample("dead.wav");
    morte_personagem = al_load_sample("death.wav");
    hit = al_load_sample("hit.wav");
    item = al_load_sample("item.wav");
    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);
    track_menu = al_load_audio_stream("menu.ogg", 4, 1024);
    personagem_principal.bmp = al_load_bitmap("ship.png");


    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].bmp = al_load_bitmap("bala.png");
        balas_2[i].bmp = al_load_bitmap("bala.png");
    }
    for (i = 0; i < NUM_INIMIGOS; i++){
        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
    }
    start = al_load_bitmap("start.jpg");

    for (i = 0; i < NUM_ITENS; i++){
        coracoes[i].imagem = al_load_bitmap("heart.png");
        speed[i].imagem = al_load_bitmap("speed.png");
        pontos[i].imagem = al_load_bitmap("pontos.png");
    }
// __________________________________

// ----------------- LOOP PRINCIPAL -----------------
    al_start_timer(timer);

    while(!fim)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(fila_eventos, &ev);
        // -------- EVENTOS E LÓGICA DO JOGO --------
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            fim = true;
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                fim = true;
                break;
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = true;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = true;
                break;
            case ALLEGRO_KEY_SPACE:
                teclas[ESPACO] = true;
                AtiraBalas(balas, NUM_BALAS, personagem_principal, personagem_principal.y + 12);
                AtiraBalas(balas_2, NUM_BALAS, personagem_principal, personagem_principal.y + 70);
                al_play_sample(ataque, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = true;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = true;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = false;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = false;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = false;
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = false;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = false;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_TIMER)
        {
            desenha = true;

            if (teclas[CIMA])
                personagem_principal.MoveCima();
            if (teclas[BAIXO])
                personagem_principal.MoveBaixo(ALTURA_T);
            if (teclas[ESQUERDA])
                personagem_principal.MoveEsquerda();
            if (teclas[DIREITA])
                personagem_principal.MoveDireita(LARGURA_T);
            if (teclas[ESPACO])
            {
                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].AtualizaBalas(0);
                    balas_2[i].AtualizaBalas(0);
                }

            }

            // Movimentação no menu
            if(menu)
            {
                al_attach_audio_stream_to_mixer(track_menu, al_get_default_mixer());
                al_set_audio_stream_playing(track_menu, true);
                if (teclas[CIMA] && select.y!=235)
                    select.y -= 70;
                if (teclas[BAIXO] && select.y!=305)
                    select.y += 70;
                if (teclas[ENTER] && select.y==235)
                {
                    menu = false;
                    al_set_audio_stream_playing(track_menu, false);
                }

            }

            // Acontecimentos do Jogo
            if(!game_over && !menu)
            {
                al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
                al_set_audio_stream_playing(musica, true);

                AtualizaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                {
                    //Gera e atualiza inimigos
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].GeraInimigos();
                        inimigos2[i].GeraInimigos();
                        inimigos[i].AtualizaInimigos();
                        inimigos[i].InimigoColidido(personagem_principal, hit);
                        inimigos2[i].AtualizaInimigos();
                        inimigos2[i].InimigoColidido(personagem_principal, hit);
                    }
                }

                //Checa colisões de projeteis

                BalaColidida(balas, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                BalaColidida(balas, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                // Faz os testes relacionado aos itens
                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].GeraItens(inimigos[i]);
                    coracoes[i].AtualizaItens();
                    coracoes[i].ItemColidido(personagem_principal, item);

                    speed[i].GeraItens(inimigos[i]);
                    speed[i].AtualizaItens();
                    speed[i].ItemColidido(personagem_principal, item);

                    pontos[i].GeraItens(inimigos[i]);
                    pontos[i].AtualizaItens();
                    pontos[i].ItemColidido(personagem_principal, item);
                }


                if ((dificuldade+1)%16 == 0) // Dificuldade aumenta a cada 15 pontos.
                {
                    for (i = 0; i < NUM_INIMIGOS; i++){
                        inimigos[i].velocidade++;
                        inimigos2[i].velocidade++;
                    }

                    dificuldade = 0;
                }

                if (personagem_principal.vidas <= 0)
                {
                    al_play_sample(morte_personagem, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                    game_over = true;
                }
            }

            // Reinicializa o jogo
            else if (!menu)
            {
                al_set_audio_stream_playing(musica, false);
                if (teclas[ENTER])
                {
                    al_destroy_audio_stream(musica);

                    personagem_principal.InitPersonagem();

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].InitBalas();
                        balas_2[i].InitBalas();
                    }


                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
                        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
                    }

                    for (i = 0; i < NUM_ITENS; i++)
                    {
                        coracoes[i].InitItem();
                        speed[i].InitItem();
                        pontos[i].InitItem();
                    }


                    personagem_principal.bmp = al_load_bitmap("ship.png");
                    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].bmp = al_load_bitmap("bala.png");
                        balas_2[i].bmp = al_load_bitmap("bala.png");
                    }
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
                        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
                        coracoes[i].imagem = al_load_bitmap("heart.png");
                        speed[i].imagem = al_load_bitmap("heart.png");
                    }

                    game_over = false;
                }
            }

        }


        // _________________________________________

        // ---------------- DESENHO ----------------

        if(desenha && al_is_event_queue_empty(fila_eventos))
        {
            desenha = false;
            // Desenhos da Tela do Menu
            if(menu)
            {
                al_draw_bitmap(start, 0, 0, 0);
                if (select.ativo)
                    al_draw_bitmap(select.bmp, select.x, select.y, 0);

                if (teclas[ENTER] && flag == 0)
                {
                    flag = 1;
                    teclas[BACKSPACE] = false;
                    select.ativo = false;
                    start = al_load_bitmap("como_jogar.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
                else if (teclas[BACKSPACE] && flag == 1)
                {
                    flag = 0;
                    select.ativo = true;
                    start = al_load_bitmap("start.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
            }
            // Jogo normal, desenho de todos os objetos
            if(!game_over && !menu)
            {
                DesenhaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                personagem_principal.DesenhaPersonagem();

                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].DesenhaBalas();
                    balas_2[i].DesenhaBalas();
                }

                for (i = 0; i < NUM_INIMIGOS; i++){
                    inimigos[i].DesenhaInimigos();
                    inimigos2[i].DesenhaInimigos();
                }

                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].DesenhaItens();
                    speed[i].DesenhaItens();
                    pontos[i].DesenhaItens();
                }


                al_draw_textf(font20, al_map_rgb(255, 255, 255), 0, 0, 0, "VIDAS: %d / PONTOS: %d", personagem_principal.vidas, personagem_principal.pontos);
            }

            //Tela de fim de jogo
            else if (!menu)
            {
                al_draw_textf(font20, al_map_rgb(255, 255, 255), LARGURA_T / 2, ALTURA_T / 2, ALLEGRO_ALIGN_CENTRE, "FIM DE JOGO. SEUS PONTOS FORAM: %d. TECLE ENTER PARA JOGAR NOVAMENTE OU ESC PARA SAIR DO JOGO.", personagem_principal.pontos);
            }

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


        // _________________________________________
    }

// _________________________________________________

// -------- FINALIZAÇÕES DO PROGRAMA --------
    delete[] inimigos;
    delete[] inimigos2;
    delete[] balas;
    delete[] balas_2;
    delete[] coracoes;
    delete[] speed;
    delete[] pontos;

    al_destroy_bitmap(start);

    al_destroy_sample(ataque);
    al_destroy_sample(morte_inimigo);
    al_destroy_sample(morte_personagem);
    al_destroy_sample(hit);
    al_destroy_sample(item);
    al_destroy_audio_stream(musica);
    al_destroy_audio_stream(track_menu);

    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_font(font20);
    al_destroy_event_queue(fila_eventos);

//___________________________________________
    return 0;
}
コード例 #30
0
ファイル: Main.cpp プロジェクト: kckrepo/kck-repo
int main(int argc, char **argv)
{
	bool done = false;
	bool render = false;

	float gameTime = 0;
	int frames = 0;
	int gameFPS = 0;

	float evTimer = 0;

	tractor = new Tractor();
	Xml = new xml();

	int state = -1;

	ALLEGRO_BITMAP *icon;
	ALLEGRO_BITMAP *map = NULL;
	ALLEGRO_BITMAP *panel = NULL;
	ALLEGRO_BITMAP *tractorImage = NULL;
	ALLEGRO_BITMAP *titleImage = NULL;
	ALLEGRO_BITMAP *lostImage = NULL;
	ALLEGRO_SAMPLE *titleSong = NULL;
	ALLEGRO_SAMPLE *gameSong = NULL;
	ALLEGRO_SAMPLE *lostSong = NULL;
	ALLEGRO_SAMPLE *cash = NULL;

	ALLEGRO_BITMAP *L1 = NULL;
	ALLEGRO_BITMAP *L2 = NULL;
	ALLEGRO_BITMAP *L3 = NULL;
	ALLEGRO_BITMAP *L4 = NULL;
	ALLEGRO_BITMAP *L5 = NULL;
	ALLEGRO_BITMAP *L6 = NULL;
	ALLEGRO_BITMAP *L7 = NULL;

	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_DISPLAY_MODE   disp_data;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer;
	ALLEGRO_FONT *font;
	ALLEGRO_FONT *score;

	if (!al_init())
		return -1;

	al_install_keyboard();
	al_install_mouse();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_primitives_addon();
	al_install_audio();
	al_init_acodec_addon();

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

	//al_set_new_display_flags(ALLEGRO_FULLSCREEN);
	al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_REQUIRE);

	display = al_create_display(disp_data.width, disp_data.height);

	icon = al_load_bitmap("icon.png");
	al_set_display_icon(display, icon);

	float sx = (float)disp_data.width / WIDTH;
	float sy = (float)disp_data.height / HEIGHT;

	ALLEGRO_TRANSFORM trans;
	al_identity_transform(&trans);
	al_scale_transform(&trans, sx, sy);
	al_use_transform(&trans);

	if (!display)
		return -1;

	font = al_load_font("arial.ttf", 20, 0);
	score = al_load_font("score.ttf", 45, 0);
	al_reserve_samples(15);

	map = al_load_bitmap("map2.png");
	panel = al_load_bitmap("panel.png");

	L1 = al_load_bitmap("l1.png");
	L2 = al_load_bitmap("l2.png");
	L3 = al_load_bitmap("l3.png");
	L4 = al_load_bitmap("l4.png");
	L5 = al_load_bitmap("l5.png");
	L6 = al_load_bitmap("l6.png");
	L7 = al_load_bitmap("l7.png");

	Background *Map = new Background(map);
	objects.push_back(Map);

	TextBox *Task = new TextBox;

	Field *field1 = new Field(L1, L2, L3, L4, L5, L6, L7, 50, 50);
	objects.push_back(field1);
	Field *field2 = new Field(L1, L2, L3, L4, L5, L6, L7, 450, 50);
	objects.push_back(field2);
	Field *field3 = new Field(L1, L2, L3, L4, L5, L6, L7, 50, 450);
	objects.push_back(field3);
	Field *field4 = new Field(L1, L2, L3, L4, L5, L6, L7, 450, 450);
	objects.push_back(field4);

	tractorImage = al_load_bitmap("tractor.png");
	cash = al_load_sample("cash.ogg");
	tractor->Init(tractorImage, cash);
	objects.push_back(tractor);

	titleImage = al_load_bitmap("screen_Title.png");
	lostImage = al_load_bitmap("screen_Lost.png");

	titleScreen = new Background(titleImage);
	lostScreen = new Background(lostImage);

	titleSong = al_load_sample("title.ogg");
	gameSong = al_load_sample("game.ogg");
	lostSong = al_load_sample("lost.ogg");

	songInstance = al_create_sample_instance(titleSong);
	al_set_sample_instance_playmode(songInstance, ALLEGRO_PLAYMODE_LOOP);

	songInstance2 = al_create_sample_instance(gameSong);
	al_set_sample_instance_playmode(songInstance2, ALLEGRO_PLAYMODE_LOOP);

	songInstance3 = al_create_sample_instance(lostSong);
	al_set_sample_instance_playmode(songInstance3, ALLEGRO_PLAYMODE_LOOP);

	al_attach_sample_instance_to_mixer(songInstance, al_get_default_mixer());
	al_attach_sample_instance_to_mixer(songInstance2, al_get_default_mixer());
	al_attach_sample_instance_to_mixer(songInstance3, al_get_default_mixer());

	ChangeState(state, TITLE);

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

	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);
	gameTime = al_current_time();

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

		if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_ENTER:
				keys[ENTER] = true;
				if (state == TITLE)
					ChangeState(state, PLAYING);
				else if (state == PLAYING && Task->CheckText())
				{
					TextBox *text = new TextBox();
					text->SetText(Task->Send());
					history.push_back(text);

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 400)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}

					Xml->interpreter(Task->GetLast(), tractor);

					TextBox *txtxml = new TextBox();
					txtxml->SetText(Xml->wyslij());
					history.push_back(txtxml);

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 300)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}
				}
				else if (state == LOST)
					ChangeState(state, PLAYING);
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = true;
				if (state == PLAYING)
				{

					Task->SetStatus();
					if (Task->GetStatus())
					{
						TextBox *text = new TextBox();
						text->SetText("Konsola zostala wlaczona");
						history.push_back(text);
					}
					else
					{
						TextBox *text = new TextBox();
						text->SetText("Konsola zostala wylaczona");
						history.push_back(text);
					}

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 300)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}

					setTimer(evTimer);
				}
				tractor->Sell();
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPC] = true;
				if (state == PLAYING)
					Task->Add(" ");
				break;
			case ALLEGRO_KEY_BACKSPACE:
				if (state == PLAYING && Task->CheckText())
					Task->Backspace();
				break;
			case ALLEGRO_KEY_COMMA:
				keys[COM] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add(",");
				break;
			case ALLEGRO_KEY_0:
				numb[N0] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("0");
				break;
			case ALLEGRO_KEY_1:
				numb[N1] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("1");
				break;
			case ALLEGRO_KEY_2:
				numb[N2] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("2");
				break;
			case ALLEGRO_KEY_3:
				numb[N3] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("3");
				break;
			case ALLEGRO_KEY_4:
				numb[N4] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("4");
				break;
			case ALLEGRO_KEY_5:
				numb[N5] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("5");
				break;
			case ALLEGRO_KEY_6:
				numb[N6] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("6");
				break;
			case ALLEGRO_KEY_7:
				numb[N7] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("7");
				break;
			case ALLEGRO_KEY_8:
				numb[N8] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("8");
				break;
			case ALLEGRO_KEY_9:
				numb[N9] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("9");
				break;
			case ALLEGRO_KEY_A:
				letters[A] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("a");
				break;
			case ALLEGRO_KEY_B:
				letters[B] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("b");
				break;
			case ALLEGRO_KEY_C:
				letters[C] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("c");
				break;
			case ALLEGRO_KEY_D:
				letters[D] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("d");
				break;
			case ALLEGRO_KEY_E:
				letters[E] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("e");
				break;
			case ALLEGRO_KEY_F:
				letters[F] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("f");
				break;
			case ALLEGRO_KEY_G:
				letters[G] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("g");
				break;
			case ALLEGRO_KEY_H:
				letters[H] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("h");
				break;
			case ALLEGRO_KEY_I:
				letters[I] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("i");
				break;
			case ALLEGRO_KEY_J:
				letters[J] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("j");
				break;
			case ALLEGRO_KEY_K:
				letters[K] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("k");
				break;
			case ALLEGRO_KEY_L:
				letters[L] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("l");
				break;
			case ALLEGRO_KEY_M:
				letters[M] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("m");
				break;
			case ALLEGRO_KEY_N:
				letters[N] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("n");
				break;
			case ALLEGRO_KEY_O:
				letters[O] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("o");
				break;
			case ALLEGRO_KEY_P:
				letters[P] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("p");
				break;
			case ALLEGRO_KEY_Q:
				letters[Q] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("q");
				break;
			case ALLEGRO_KEY_R:
				letters[R] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("r");
				break;
			case ALLEGRO_KEY_S:
				letters[S] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("s");
				break;
			case ALLEGRO_KEY_T:
				letters[T] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("t");
				break;
			case ALLEGRO_KEY_U:
				letters[U] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("u");
				break;
			case ALLEGRO_KEY_V:
				letters[V] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("v");
				break;
			case ALLEGRO_KEY_W:
				letters[W] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("w");
				break;
			case ALLEGRO_KEY_X:
				letters[X] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("x");
				break;
			case ALLEGRO_KEY_Y:
				letters[Y] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("y");
				break;
			case ALLEGRO_KEY_Z:
				letters[Z] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("z");
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_ENTER:
				keys[ENTER] = false;
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = false;
				break;
			case ALLEGRO_KEY_BACKSPACE:
				keys[BSPC] = false;
				break;
			case ALLEGRO_KEY_COMMA:
				keys[COM] = false;
				break;
			case ALLEGRO_KEY_0:
				numb[N0] = false;
				break;
			case ALLEGRO_KEY_1:
				numb[N1] = false;
				break;
			case ALLEGRO_KEY_2:
				numb[N2] = false;
				break;
			case ALLEGRO_KEY_3:
				numb[N3] = false;
				break;
			case ALLEGRO_KEY_4:
				numb[N4] = false;
				break;
			case ALLEGRO_KEY_5:
				numb[N5] = false;
				break;
			case ALLEGRO_KEY_6:
				numb[N6] = false;
				break;
			case ALLEGRO_KEY_7:
				numb[N7] = false;
				break;
			case ALLEGRO_KEY_8:
				numb[N8] = false;
				break;
			case ALLEGRO_KEY_9:
				numb[N9] = false;
				break;
			case ALLEGRO_KEY_A:
				letters[A] = false;
				break;
			case ALLEGRO_KEY_B:
				letters[B] = false;
				break;
			case ALLEGRO_KEY_C:
				letters[C] = false;
				break;
			case ALLEGRO_KEY_D:
				letters[D] = false;
				break;
			case ALLEGRO_KEY_E:
				letters[E] = false;
				break;
			case ALLEGRO_KEY_F:
				letters[F] = false;
				break;
			case ALLEGRO_KEY_G:
				letters[G] = false;
				break;
			case ALLEGRO_KEY_H:
				letters[H] = false;
				break;
			case ALLEGRO_KEY_I:
				letters[I] = false;
				break;
			case ALLEGRO_KEY_J:
				letters[J] = false;
				break;
			case ALLEGRO_KEY_K:
				letters[K] = false;
				break;
			case ALLEGRO_KEY_L:
				letters[L] = false;
				break;
			case ALLEGRO_KEY_M:
				letters[M] = false;
				break;
			case ALLEGRO_KEY_N:
				letters[N] = false;
				break;
			case ALLEGRO_KEY_O:
				letters[O] = false;
				break;
			case ALLEGRO_KEY_P:
				letters[P] = false;
				break;
			case ALLEGRO_KEY_Q:
				letters[Q] = false;
				break;
			case ALLEGRO_KEY_R:
				letters[R] = false;
				break;
			case ALLEGRO_KEY_S:
				letters[S] = false;
				break;
			case ALLEGRO_KEY_T:
				letters[T] = false;
				break;
			case ALLEGRO_KEY_U:
				letters[U] = false;
				break;
			case ALLEGRO_KEY_V:
				letters[V] = false;
				break;
			case ALLEGRO_KEY_W:
				letters[W] = false;
				break;
			case ALLEGRO_KEY_X:
				letters[X] = false;
				break;
			case ALLEGRO_KEY_Y:
				letters[Y] = false;
				break;
			case ALLEGRO_KEY_Z:
				letters[Z] = false;
				break;
			}
		}

		else if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			render = true;

			frames++;

			if (al_current_time() - gameTime >= 1)
			{
				gameTime = al_current_time();
				gameFPS = frames;
				frames = 0;
			}

			if (state == PLAYING)
			{
				if (keys[UP])
				{
					if (Map->GetY() + Map->frameHeight > disp_data.height)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetY((*iter)->GetY() - 10);
						}
						tractor->SetDistY((tractor->GetDistY() - 10));
					}
				}
				else if (keys[DOWN])
				{
					if (Map->GetY() < 0)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetY((*iter)->GetY() + 10);
						}
						tractor->SetDistY(tractor->GetDistY() + 10);
					}
				}

				if (keys[LEFT])
				{
					if (Map->GetWidth() > (disp_data.width - al_get_bitmap_width(panel)))
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetX((*iter)->GetX() - 10);
						}
						tractor->SetDistX(tractor->GetDistX() - 10);
					}
				}
				else if (keys[RIGHT])
				{
					if (Map->GetX() < 0)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetX((*iter)->GetX() + 10);
						}
						tractor->SetDistX(tractor->GetDistX() + 10);
					}
				}

				for (iter = objects.begin(); iter != objects.end(); ++iter)
					(*iter)->Update();

				if (tractor->GetStatus())
					tractor->Move();

				field1->Change_Field();
				field1->Grow_Field();
				field2->Change_Field();
				field2->Grow_Field();
				field3->Change_Field();
				field3->Grow_Field();
				field4->Change_Field();
				field4->Grow_Field();
				field1->Action_On_Field(tractor);
				field2->Action_On_Field(tractor);
				field3->Action_On_Field(tractor);
				field4->Action_On_Field(tractor);

				if (!tractor->Get_Iminwork()){
					Xml->ZKolejki(field1, field2, field3, field4, tractor);
					if (Xml->wyslij() != ""){
						TextBox *txtxml = new TextBox();
						txtxml->SetText(Xml->wyslij());
						history.push_back(txtxml);

						for (iter2 = history.begin(); iter2 != history.end(); iter2++)
						{
							if ((*iter2)->GetY() < 300)
							{
								delete (*iter2);
								iter2 = history.erase(iter2);
							}

							(*iter2)->UpdateY();
						}
					}
				}
				if (evTimer < 60)
				{
					evTimer += 0.1;
				}
				else
				{
					if (tractor->GetPodpowiedz() == 0)
					{
						Xml->podpowiedz(field1, field2, field3, field4, tractor);
						evTimer = 0;

						TextBox *txtxml = new TextBox();
						txtxml->SetText(Xml->wyslij());
						history.push_back(txtxml);

						for (iter2 = history.begin(); iter2 != history.end(); iter2++)
						{
							if ((*iter2)->GetY() < 300)
							{
								delete (*iter2);
								iter2 = history.erase(iter2);
							}

							(*iter2)->UpdateY();
						}
					}
					
				}
			}

			if (tractor->GetMoney() <= 0)
				ChangeState(state, LOST);
		}

		for (iter = objects.begin(); iter != objects.end();)
		{
			if (!(*iter)->GetAlive())
			{
				delete (*iter);
				iter = objects.erase(iter);
			}
			else
				iter++;
		}

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

			if (state == TITLE)
			{
				titleScreen->Render();
			}
			else if (state == PLAYING)
			{
				for (iter = objects.begin(); iter != objects.end(); ++iter)
					(*iter)->Render();

				al_draw_bitmap(panel, WIDTH - al_get_bitmap_width(panel), 0, 0);
				al_draw_textf(font, al_map_rgb(255, 255, 255), Task->GetX(), Task->GetY(), 0, Task->ShowText());

				for (iter2 = history.begin(); iter2 != history.end(); iter2++)
				{
					al_draw_textf(font, al_map_rgb(255, 255, 255), (*iter2)->GetX(), (*iter2)->GetY(), 0, (*iter2)->ShowText());
				}

				if (tractor->GetHealth() < 20)
					al_draw_textf(score, RED, WIDTH - 430, 15, 0, "%i", tractor->GetHealth());
				else
					al_draw_textf(score, BLACK, WIDTH - 430, 15, 0, "%i", tractor->GetHealth());
				
				if (tractor->GetFuel() < 20)
					al_draw_textf(score, RED, WIDTH - 260, 15, 0, "%i", tractor->GetFuel());
				else
					al_draw_textf(score, BLACK, WIDTH - 260, 15, 0, "%i", tractor->GetFuel());
				
				if (tractor->GetMoney() < 200)
					al_draw_textf(score, RED, WIDTH - 400, 100, 0, "%i", tractor->GetMoney());
				else
					al_draw_textf(score, BLACK, WIDTH - 400, 100, 0, "%i", tractor->GetMoney());

				al_draw_textf(score, BLACK, WIDTH - 70, 15, 0, "%i", tractor->GetWater());

				for (int j = 0; j < 5; j++)
				{
					al_draw_textf(font, BLACK, WIDTH - 170, 85 + j * 20, 0, "%i", tractor->GetSupply(0, j));
				}

				for (int j = 0; j < 5; j++)
				{
					al_draw_textf(font, BLACK, WIDTH - 150, 85 + j * 20, 0, "%i", tractor->GetSupply(1, j));
				}

				al_draw_textf(font, al_map_rgb(255, 0, 255), 5, 5, 0, "FPS: %i", WIDTH - al_get_bitmap_width(panel) /*gameFPS*/);
			}
			else if (state == LOST)
				lostScreen->Render();

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

	for (iter = objects.begin(); iter != objects.end();)
	{
		(*iter)->Destroy();
		delete (*iter);
		iter = objects.erase(iter);
	}

	for (iter2 = history.begin(); iter2 != history.end();)
	{
		(*iter2)->Destroy();
		delete (*iter2);
		iter2 = history.erase(iter2);
	}

	//tractor->Destroy();
	Task->Destroy();
	titleScreen->Destroy();
	lostScreen->Destroy();
	delete titleScreen;
	delete lostScreen;
	al_destroy_sample(cash);
	al_destroy_sample_instance(songInstance);
	al_destroy_sample_instance(songInstance2);
	al_destroy_sample_instance(songInstance3);

	al_destroy_font(score);
	al_destroy_font(font);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
			
	return 0;
}