Beispiel #1
0
int main(int argc, char const *argv[])
{
    int n_hordas = 0;             //Numero de hordas chamadas
    bool nova_horda = true;       //Chama nova horda

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

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

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

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

    int gamestate = 0;            //Gamestates

    //Setup inicial
    Sistema sistema;

    Monstro monstro[tipos_monstros][n_monstros];

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

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

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

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

    setup_torre1(tipo1);
    setup_torre2(tipo2);

    upgrade1_tower1(upgrade1_torre1);

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        al_flip_display();
    }
}

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

return 0;
}
Beispiel #2
0
int main(){


// variables {{{1

    int fps=50;

    bool redraw=true;

    int x=10;
    int y=10;
    int mx=0;
    int my=0;
    int estado=INTRO;

    ALLEGRO_DISPLAY *Screen;
    ALLEGRO_EVENT_QUEUE *qu;
    ALLEGRO_EVENT Event;
    ALLEGRO_TIMER *timer;
    ALLEGRO_BITMAP *Image = NULL; 
    ALLEGRO_BITMAP *background= NULL;

    ALLEGRO_FONT *font;
    ALLEGRO_FONT *bigfont;
   
    string registro;

    bool Exit = false;

//}}}1


// Iniciando allegro {{{1

    if(!al_init()){
	    cout<<"error iniciando allegro"<<endl;
	    return -1;
    }
    if(!al_init_image_addon()){
	    cout<<"error iniciando addon de imagenes"<<endl;
	    return -1;
    }
    if(!al_init_primitives_addon()){
        cout<<"Couldn't initialize primitives addon!\n";
        return -1;
    }

    if(!al_install_keyboard()){
	    cout<<"error iniciando teclado"<<endl;
	    return -1;
    }

    if(!al_install_mouse()){
	    cout<<"error iniciando raton"<<endl;
	    return -1;
    }

    al_init_font_addon();
    al_init_ttf_addon();

    font=al_load_font("data/helvetica.ttf",24,0);
    bigfont=al_load_font("data/helvetica.ttf", 48,0);

    if(!font){
	    cout<<"font esta vacio"<<endl;
	    return -1;
    }

    if(!bigfont){
	   cout<<"big font esta vacio"<<endl;
	   return -1;
	}

//}}}1


    // pantalla y resoluciones {{{1

    ALLEGRO_DISPLAY_MODE   disp_data;

    int n=al_get_num_display_modes();
    bool continuar_resolucion_w=false;
    bool continuar_resolucion_h=false;

    for(int i=0;i<n;i++){

	    al_get_display_mode(i, &disp_data);

	    int w=disp_data.width;
	    int h=disp_data.height;

	    if(w==SWIDTH){
		    continuar_resolucion_w=true;
	    }
	    if(h==SHEIGHT){
		    continuar_resolucion_h=true;
	    }

    }
    
    if(continuar_resolucion_w==false && continuar_resolucion_h==false){
		
	    cerr<<"resolucion no soportada"<<endl;
	    return -1;
		    
    }

    //al_set_new_display_flags(ALLEGRO_FULLSCREEN);
    Screen = al_create_display(SWIDTH,SHEIGHT);

    if(!Screen){
	    cout<<"no se pudo crear el display"<<endl;
    }

 //}}}1
   

// crear queue - timer screen keyboard {{{1

    qu= al_create_event_queue();

    if(!qu){
	    cout<<"error creando queue"<<endl;
    }

    al_register_event_source(qu, al_get_display_event_source(Screen));

    timer = al_create_timer(1.0 /fps);

    if(!timer){
	    cout<<"error iniciando timer"<<endl;
    }

    al_register_event_source(qu, al_get_timer_event_source(timer));

    al_register_event_source(qu, al_get_keyboard_event_source());

    al_register_event_source(qu, al_get_mouse_event_source());

//}}}1


// iniciar clases y timer{{{1
    // 0 inicio
    // 1 menu
    // 2 core

    Inicio inicio;
    Menu menu_principal;
    Menu_juego menu_juego;
    Menu_carreras menu_carreras;
    Core core;
    Tienda tienda;
    Registros registros;

    inicio.Iniciar();
//    core.Iniciar(Screen);

    al_start_timer(timer);

     Image = al_load_bitmap("data/test.png"); ///load the bitmap from a file
     background= al_load_bitmap("data/background.png");

    // ALLEGRO_COLOR clearcol=al_map_rgb(255,255,255);
//}}}1


// main loop {{{1


    while(Exit == false){

        al_wait_for_event(qu, &Event);

	//if(al_is_event_queue_empty(qu)){


	if(Event.type == ALLEGRO_EVENT_DISPLAY_CLOSE){
            Exit = true;
        }




	if(Event.type==ALLEGRO_EVENT_KEY_DOWN){

		cout<<Event.keyboard.keycode<<endl;

		if(Event.keyboard.keycode==59){
			Exit=true;
		}

		if(Event.keyboard.keycode==1){  // a
			fps+=10;
			cout<<"fps actual "<<fps<<endl;
		}

		if(Event.keyboard.keycode==2){  // b
			fps-=10;
			cout<<"fps actual "<<fps<<endl;
		}

		if(Event.keyboard.keycode==16){
		//	core.runner.animando=true;
		}

		//cout<<fps<<endl;
	}

	if(Event.type==ALLEGRO_EVENT_MOUSE_AXES){
		mx=Event.mouse.x;
		my=Event.mouse.y;
	}

	if(Event.type==ALLEGRO_EVENT_MOUSE_BUTTON_DOWN){
		//cout<<Event.mouse.x<<endl;
	}

	

	if(Event.type == ALLEGRO_EVENT_TIMER){

		if(estado==MENU_PRINCIPAL){menu_principal.Display(Screen, font,mx,my);
};
		if(estado==MENU_JUEGO){menu_juego.Display(Screen, font, mx,my);
	};
		if(estado==MENU_CARRERAS){menu_carreras.Display(Screen, font, mx,my);
 };
		if(estado==TIENDA){ tienda.Display();};
		if(estado==REGISTROS){ registros.Display(); } ;
		if(estado==MAIN){
			x+=1;
			core.Animar();
			core.Mover();
			core.Gestion(Event);
			al_draw_bitmap(background,0,0,0);
			core.Display(Screen, bigfont);
			al_draw_bitmap(Image,x,y,0);
 		};


		redraw=true;
	}



	if(estado==INTRO){

		inicio.Display(Screen);


		// en este estado, cargar todo
		//
		// intentar hacer un thread para que que vea la
		// barra de progreso de carga

		menu_juego.Iniciar(Screen);
		menu_carreras.Iniciar(Screen);
    		core.Iniciar(Screen);
		tienda.Iniciar();
		registros.Iniciar();

		int n=menu_principal.Iniciar_menu(Screen);

		if(n==1){
			estado=MENU_PRINCIPAL;
		}
	}


	if(estado==MENU_PRINCIPAL){

		//menu_principal.Display(Screen, font,mx,my);
		int next=menu_principal.Gestion(Event);

		switch(next){

			case 0: // estado=CONFIGURACION
				break;

			case 1:
				estado=MENU_JUEGO;
				break;

			case 2:	// estado=CONTINUAR
				break;

			case 3: // estado=GUARDAR
				break;

			case 4: Exit=true;
				break;

			default:  
				break;

		}
	}
     
	// en menu juego estan la tienda, las carreras, los registros, etc.
	if(estado==MENU_JUEGO){

		//menu_juego.Display(Screen, font, mx,my);
		int next=menu_juego.Gestion(Event);

		switch(next){

			case 0: // tienda
				break;
			case 1: estado=MENU_CARRERAS;
				break;
			case 2: // records
				break;
			case 3: estado=MENU_PRINCIPAL;
				break;
			default:
				break;
		}
	}

	if(estado==MENU_CARRERAS){

		//menu_carreras.Display(Screen, font, mx,my);
		int next=menu_carreras.Gestion(Event);

		if(next>-1 && next<99){
			estado=MAIN;
		}
		if(next==99){
			estado=MENU_JUEGO;
		}

	}

	if(estado==TIENDA){

		//tienda.Display();

	}

	if(estado==REGISTROS){

		//registros.Display();

	}

	if(estado==MAIN){

		core.Gestion(Event);
		//x+=1;
		//core.Animar();

		//al_draw_bitmap(background,0,0,0);
		//core.Display(Screen);
		//al_draw_bitmap(Image,x,y,0);

	}

	/*
	ALLEGRO_COLOR c=al_map_rgb( 25, 25, 25);

	string s= static_cast<ostringstream*>( &(ostringstream() << fps) )->str();

	cout<<"antes del texto"<<endl;
	al_draw_text(font,c,20,20,0,s.c_str());
	cout<<"despues"<<endl;
	*/

//}

   	if(redraw && al_is_event_queue_empty(qu)) { 

		redraw=false;
		al_flip_display();	

	}
	 


  //  }

   }

    return 0;
}
Beispiel #3
0
int main(void)
{
   ALLEGRO_DISPLAY *display[2];
   ALLEGRO_EVENT event;
   ALLEGRO_EVENT_QUEUE *events;
   ALLEGRO_BITMAP *pictures[2];
   ALLEGRO_BITMAP *target;
   int width, height;
   int i;

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

   open_log();

   al_install_keyboard();
   al_install_mouse();
   al_init_image_addon();

   events = al_create_event_queue();

   al_set_new_display_flags(ALLEGRO_WINDOWED|ALLEGRO_RESIZABLE);

   /* Create two windows. */
   display[0] = al_create_display(W, H);
   if (!display[0]) {
      abort_example("Error creating display\n");
   }
   pictures[0] = al_load_bitmap("data/mysha.pcx");
   if (!pictures[0]) {
      abort_example("failed to load mysha.pcx\n");
   }

   display[1] = al_create_display(W, H);
   if (!display[1]) {
      abort_example("Error creating display\n");
   }
   pictures[1] = al_load_bitmap("data/allegro.pcx");
   if (!pictures[1]) {
      abort_example("failed to load allegro.pcx\n");
   }

   /* This is only needed since we want to receive resize events. */
   al_register_event_source(events, al_get_display_event_source(display[0]));
   al_register_event_source(events, al_get_display_event_source(display[1]));
   al_register_event_source(events, al_get_keyboard_event_source());

   while (1) {
      /* read input */
      while (!al_is_event_queue_empty(events)) {
         al_get_next_event(events, &event);
         if (event.type == ALLEGRO_EVENT_KEY_DOWN) {
            ALLEGRO_KEYBOARD_EVENT *key = &event.keyboard;
            if (key->keycode == ALLEGRO_KEY_ESCAPE) {
               goto done;
            }
         }
         if (event.type == ALLEGRO_EVENT_DISPLAY_RESIZE) {
            ALLEGRO_DISPLAY_EVENT *de = &event.display;
            al_acknowledge_resize(de->source);
         }
         if (event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_IN) {
            log_printf("%p switching in\n", event.display.source);
         }
         if (event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_OUT) {
            log_printf("%p switching out\n", event.display.source);
         }
         if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
            int i;
            for (i = 0; i < 2; i++) {
               if (display[i] == event.display.source)
                  display[i] = 0;
            }
            al_destroy_display(event.display.source);
            for (i = 0; i < 2; i++) {
               if (display[i])
                  goto not_done;
            }
            goto done;
         not_done:
            ;
         }
      }

      for (i = 0; i < 2; i++) {
         if (!display[i])
            continue;

         target = al_get_backbuffer(display[i]);
         width = al_get_bitmap_width(target);
         height = al_get_bitmap_height(target);

         al_set_target_bitmap(target);
         al_draw_scaled_bitmap(pictures[0], 0, 0,
            al_get_bitmap_width(pictures[0]),
            al_get_bitmap_height(pictures[0]),
            0, 0,
            width / 2, height,
            0);
         al_draw_scaled_bitmap(pictures[1], 0, 0,
            al_get_bitmap_width(pictures[1]),
            al_get_bitmap_height(pictures[1]),
            width / 2, 0,
            width / 2, height,
            0);

         al_flip_display();
      }

      al_rest(0.001);
   }

done:
   al_destroy_bitmap(pictures[0]);
   al_destroy_bitmap(pictures[1]);
   al_destroy_display(display[0]);
   al_destroy_display(display[1]);

   close_log(true);

   return 0;
}
Beispiel #4
0
int main(int argc, char **argv)
{
  ALLEGRO_DISPLAY *display = NULL;
  ALLEGRO_EVENT_QUEUE *event_queue = NULL;
  ALLEGRO_TIMER *timer = NULL;
  ALLEGRO_FONT *font_arial_36 = NULL;
  ALLEGRO_FONT *font_arial_24 = NULL;
  ALLEGRO_TRANSFORM transform;
  bool key[6] = { false, false, false, false, false, true };
  bool redraw = true;
  bool doexit = false;
  char display_score[20];
  char display_lives[20];
  char display_ammo[20];
  char display_countdown[20];
  int ammo = 99;

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

  al_init_font_addon();
  if (!al_init_ttf_addon()) {
    fprintf(stderr, "failed to initialize ttf addon!\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;
  }

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

  font_arial_36 = al_load_ttf_font("arial.ttf", 36, 0);
  if (!font_arial_36){
    fprintf(stderr, "arial 36 not loaded!\n" );
    return -1;
  }

  font_arial_24 = al_load_ttf_font("arial.ttf", 24, 0);
  if (!font_arial_36){
    fprintf(stderr, "arial 24 not loaded!\n" );
    return -1;
  }

  al_init_primitives_addon();

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

  /* Start game */
  Spaceship* ship = new_ship();
  last = make_roids(ROIDS);
  Blast **blasts = new_blasts();
  
  int countdown = 10;
  while(countdown && !DEBUG_MODE) {
    al_clear_to_color(al_map_rgb(0,0,0));
    /* Welcome - Ugly code, write nicer function. */
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_36, 
                 al_map_rgb(255,0,0), 
                 SCREEN_W/2, 
                 100,
                 ALLEGRO_ALIGN_CENTRE, 
                 "Welcome to Casper's BLASTEROIDS!");
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 150,
                 ALLEGRO_ALIGN_CENTRE, 
                 "You got three lives, 100 shots and a lot of asteroids to blast.");
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 170,
                 ALLEGRO_ALIGN_CENTRE, 
                 "Fire with space, steer with the arrow keys and hit escape");
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 190,
                 ALLEGRO_ALIGN_CENTRE, 
                 "if you don't dare to play to the end...");
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 230,
                 ALLEGRO_ALIGN_CENTRE, 
                 "(If you get hit by and asteroid, you will die,"); 
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 250,
                 ALLEGRO_ALIGN_CENTRE, 
                 "the first five seconds of a new life, they won't hurt you.)");
    sprintf(display_countdown, "%d", countdown);
    al_identity_transform(&transform);
    al_use_transform(&transform);
    al_draw_text(font_arial_24, 
                 al_map_rgb(230,230,230), 
                 SCREEN_W/2, 
                 300,
                 ALLEGRO_ALIGN_CENTRE, 
                 display_countdown);

    al_flip_display();
    sleep(1);
    countdown--;
  }

  al_start_timer(timer);

  while(!doexit) {
    ALLEGRO_EVENT ev;
    al_wait_for_event(event_queue, &ev);
    if(ev.type == ALLEGRO_EVENT_TIMER) {
      redraw = true;
      if(ship->timer > 0)
      ship->timer--;
    }

    else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
      break;
    }

    else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
      switch(ev.keyboard.keycode) {
        case ALLEGRO_KEY_K:
        case ALLEGRO_KEY_UP:
          key[KEY_UP] = true;
          move_ship(ship, KEY_UP);
          break;
        case ALLEGRO_KEY_J:
        case ALLEGRO_KEY_DOWN:
          key[KEY_DOWN] = true;
          move_ship(ship, KEY_DOWN);
          break;
        case ALLEGRO_KEY_H:
        case ALLEGRO_KEY_LEFT:
          key[KEY_LEFT] = true;
          move_ship(ship, KEY_LEFT);
          break;
        case ALLEGRO_KEY_L:
        case ALLEGRO_KEY_RIGHT:
          key[KEY_RIGHT] = true;
          move_ship(ship, KEY_RIGHT);
          break;
        case ALLEGRO_KEY_SPACE:
          key[KEY_SPACE] = true;
          if (ammo>0) {
            shoot_blast(blasts[ammo], ship);
            ammo--;
          }
          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));

      move_ship(ship, NONE);
      draw_ship(ship);

      move_blasts(blasts);
      draw_blasts(blasts);

      check_collision(last, ship, blasts);

      move_roids(last);
      draw_roids(last);

      if(!ship->lives || !ammo) {
        /* Game over. */
        al_identity_transform(&transform);
        al_use_transform(&transform);
        al_draw_text(font_arial_36, 
                     al_map_rgb(200,200,200), 
                     SCREEN_W/2, 
                     SCREEN_H/2-100, 
                     ALLEGRO_ALIGN_CENTRE, 
                     "GAME OVER");
        doexit = "true";
      }

      if(!ROIDS_ALIVE) {
        /* You Won. */
        al_identity_transform(&transform);
        al_use_transform(&transform);
        al_draw_text(font_arial_36, 
                     al_map_rgb(200,200,200), 
                     SCREEN_W/2, 
                     SCREEN_H/2-100, 
                     ALLEGRO_ALIGN_CENTRE, 
                     "YOU WON");
        doexit = "true";
      }

      /* Score */
      al_identity_transform(&transform);
      al_use_transform(&transform);

      sprintf(display_score, "%d", score);
      al_draw_text(font_arial_24, 
                   al_map_rgb(200,200,200), 
                   50, 
                   10, 
                   ALLEGRO_ALIGN_CENTRE, 
                   display_score);
      /* Lives */
      sprintf(display_lives, "%d", ship->lives);
      al_draw_text(font_arial_24, 
                   al_map_rgb(200,200,200), 
                   SCREEN_W-50, 
                   10, 
                   ALLEGRO_ALIGN_CENTRE, 
                   display_lives);
      /* Ammo */
      al_identity_transform(&transform);
      al_use_transform(&transform);

      sprintf(display_ammo, "%d", ammo);
      al_draw_text(font_arial_24, 
                   al_map_rgb(200,200,200), 
                   50, 
                   SCREEN_H-50,
                   ALLEGRO_ALIGN_CENTRE, 
                   display_ammo);

      al_flip_display();
      if (doexit)
        sleep(3);
    }
  }

  destroy_ship(ship);
  destroy_roids(last);
  destroy_blasts(blasts);

  /* End game. */

  al_shutdown_primitives_addon();
  al_destroy_timer(timer);
  al_destroy_display(display);
  al_destroy_event_queue(event_queue);

  return 0;
}