Example #1
0
void Game::cleanup()
{
	//delete the timers
	delete mpLoopTimer;
	mpLoopTimer = NULL;
	delete mpMasterTimer;
	mpMasterTimer = NULL;

	//delete the graphics system
	delete mpGraphicsSystem;
	mpGraphicsSystem = NULL;

	delete mpGraphicsBufferManager;
	mpGraphicsBufferManager = NULL;
	delete mpSpriteManager;
	mpSpriteManager = NULL;

	al_destroy_font(mpFont);
	mpFont = NULL;

	//shutdown components
	al_uninstall_audio();
	al_shutdown_image_addon();
	al_shutdown_font_addon();
	al_shutdown_ttf_addon();
	al_uninstall_keyboard();
	al_uninstall_mouse();
	al_shutdown_primitives_addon();
}
Example #2
0
void shutdown() {
    al_shutdown_image_addon();
    al_shutdown_ttf_addon();
    al_shutdown_font_addon();
    al_shutdown_primitives_addon();
    al_uninstall_keyboard();
    al_uninstall_mouse();
    al_uninstall_audio();
    al_uninstall_system();
}
void mw2_Application::Exit()
{
	mIsExit = true;
	al_shutdown_image_addon();
	al_shutdown_primitives_addon();
	al_shutdown_font_addon();

	// from unknown reasons this causes a crash
	//al_shutdown_ttf_addon();

	al_destroy_display(mWindow);
}
Example #4
0
void shutdown(void)
{
    if (timer)
        al_destroy_timer(timer);
    
    if (display)
        al_destroy_display(display);
 
    if (event_queue)
        al_destroy_event_queue(event_queue);

    al_shutdown_primitives_addon();
}
Example #5
0
void
finalize_video (void)
{
  destroy_bitmap (icon);
  destroy_bitmap (uscreen);
  destroy_bitmap (effect_buffer);
  destroy_bitmap (black_screen);
  al_destroy_font (builtin_font);
  al_destroy_timer (video_timer);
  al_destroy_display (display);
  al_shutdown_image_addon ();
  al_shutdown_font_addon ();
  al_shutdown_primitives_addon ();
}
Example #6
0
GUI::~GUI()
{
	al_stop_timer(timer);
	al_unregister_event_source(queue, al_get_keyboard_event_source());
	al_unregister_event_source(queue, al_get_display_event_source(display));
	al_unregister_event_source(queue, al_get_timer_event_source(timer));
	al_destroy_event_queue(queue);

	al_destroy_bitmap(tiles);
	al_destroy_display(display);

	al_uninstall_keyboard();
	al_shutdown_font_addon();
	al_shutdown_primitives_addon();
	al_shutdown_image_addon();

    al_uninstall_system();
}
Example #7
0
void main_close_allegro_library() {
  regular_message("shutdown primitive addon");
  al_shutdown_primitives_addon();

  regular_message("shutdown native dialog addon");
  al_shutdown_native_dialog_addon();

  regular_message("shutdown image addon");
  al_shutdown_image_addon();

  regular_message("uninstall audio");
  al_uninstall_audio();

  regular_message("uninstall keyboard");
  al_uninstall_keyboard();

  regular_message("uinstall mouse");
  al_uninstall_mouse();

  regular_message("uninstll allegro system");
  al_uninstall_system();
}
Example #8
0
Framework::~Framework()
{

  Settings->Save( "settings.cfg" );

#ifdef WRITE_LOG
  printf( "Framework: Shutdown\n" );
#endif

  al_destroy_event_queue( eventQueue );
  al_destroy_display( displaySurface );
  al_destroy_mutex( extraEventsMutex );

  delete imageMgr;
  delete audioMgr;
  delete fontMgr;
  delete networkMgr;
  delete downloadMgr;

  // Shutdown Allegro
  if( mixer != 0 )
  {
    al_destroy_mixer( mixer );
  }
  if( voice != 0 )
  {
    al_destroy_voice( voice );
  }

	al_uninstall_keyboard();
	al_uninstall_mouse();
	al_shutdown_primitives_addon();
	al_shutdown_ttf_addon();
	al_shutdown_image_addon();
	al_shutdown_font_addon();
	al_uninstall_audio();
  al_uninstall_joystick();
}
Example #9
0
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;
}
int main() {
  bool menu = true;
  char pontuacao[100];
  char vida[100];
  ALLEGRO_COLOR  font_color;
  ALLEGRO_FONT *font,*font2;
  ALLEGRO_AUDIO_STREAM *musica = NULL;
  
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");
  int x = 0, y =  0;
  int largura = cam->largura;
  int altura = cam->altura;
  int fps = 0,tempo = 5;
  int ndisco = 9;
 
  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  al_init_font_addon();
  al_init_ttf_addon();

    font_color = al_map_rgb(0, 0, 0);
    
    font = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 20, 0);
    font2 = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 50, 0);
    


  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(2 * largura,altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

   if (!al_install_audio())
    {
        fprintf(stderr, "Falha ao inicializar áudio.\n");
        return false;
    }
 
    if (!al_init_acodec_addon())
    {
        fprintf(stderr, "Falha ao inicializar codecs de áudio.\n");
        return false;
    }
    if (!al_reserve_samples(1))
    {
        fprintf(stderr, "Falha ao alocar canais de áudio.\n");
        return false;
    }

  musica = al_load_audio_stream("Audio/elementary.ogg", 4, 1024);
  if(!musica)
        erro("Erro na alocação da musica de fundo\n");

  al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
  al_set_audio_stream_playing(musica, true);

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);
  
  unsigned char ***matriz = camera_aloca_matriz(cam);
  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);
  ALLEGRO_BITMAP *fundo = al_load_bitmap("Imagens/Elementary2.png");

  if(!fundo)
    erro("erro ao carregar Elementary.png");

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

  /**********/
  Disco *discos[9];
  bool perdeu = false;
  carregarDiscos(discos);
  int pontos=0,velo = 1;
  int aux1 = 1;
  int vidas = 10;
  int ultimoDisco = 0;
  int distance = 0;
  int desenhar = 0;
  int terminar = 0;
  al_set_target_bitmap(esquerda);
  al_draw_bitmap(fundo,0,0,0);
  while(1) {

    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;
      break;
    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;
   
    }

    if(terminar)
      break;

    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);
      mediana(cam);
      /**********/
      al_set_target_bitmap(esquerda);
      al_draw_bitmap(fundo,0,0,0);
      
      if(!menu){
        while(aux1 <= ndisco){
          if(discos[aux1]->status == false){
            if(distance > 50 || ultimoDisco==0  ){
              printf("%d\n",aux1 );
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
              discos[aux1]->status = true;
              distance = 0;
              ultimoDisco = aux1;
              break;
            }else
             aux1++;
          }else{
              discos[aux1]->pos_y+=(10+velo);
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
            aux1++;
              
            }
        }
        distance = discos[ultimoDisco]->pos_y;
        for(aux1 = 1;aux1<ndisco;aux1++){
          if(discos[aux1]->pos_x >= x-30 && discos[aux1]->pos_x <= x+30 && discos[aux1]->pos_y >= y-30 &&  discos[aux1]->pos_y <= y+30){
            if(discos[aux1]->tipo == 2){ // Tipo do fogo(Necessario para vencer o jogo)
            pontos +=10;
            velo += 1;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }else if(discos[aux1]->tipo == 1){ //Tipo da agua(Perde o jogo se destruir esse disco)
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else if(discos[aux1]->tipo == 3){//Tipo planta(Aumenta velocidade de queda das peças)
            velo *= 2;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }

        }else if( discos[aux1]->pos_y > 480){
          if(discos[aux1]->tipo == 2){ //Tipo da agua e Planta(Não perde se deixar cair)
               discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else{
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }
        }
      }

        aux1 = 1;
      sprintf(pontuacao,"PONTUAÇÃO: %d",pontos);
      al_draw_text(font, al_map_rgb(255, 255, 255), 50, 5, 0,pontuacao);
       sprintf(vida,"VIDAS: %d",vidas);
      al_draw_text(font, al_map_rgb(255, 255, 255), 300, 5, 0,vida);
      al_flip_display();

      }
       if(perdeu){
        al_draw_text(font2, al_map_rgb(255, 0, 0), 50, 100, 0,"PONTUAÇÃO FINAL");
        sprintf(pontuacao,"%d",pontos);
        al_draw_text(font2, al_map_rgb(255, 0, 0), 250, 170, 0,pontuacao);
        al_flip_display();
        al_rest(3);
        break;
      }
       
      if(vidas == 0){
        perdeu = true;
      }

      if(menu){
        if(abrirJogo(x,y,&fps,&tempo,font,font2, font_color)){
          fundo = al_load_bitmap("Imagens/galaxia.png");
          menu = false;
        }
      }
      cameraRastreia(cam,&x,&y);
   

      al_set_target_bitmap(direita);
      camera_copia(cam, cam->quadro, direita);
      al_flip_display();
    }
  }
  al_destroy_bitmap(direita);
  al_destroy_bitmap(fundo);
  al_destroy_bitmap(esquerda);
  camera_libera_matriz(cam, matriz);
int fri = 9;
while(fri != 0){
  free(discos[fri]);
  fri--;

}


  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);
  al_destroy_audio_stream(musica);
  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
Example #11
0
void finalizar(){

    al_shutdown_primitives_addon(); // Finalizar el addon de primitivas
    al_destroy_display(dis); // Destruir la ventana
}
Example #12
0
int main(void)
{
int X_ROOMS=13;
int Y_ROOMS=16;
int X_ROOM_SIZE=256;
int Y_ROOM_SIZE=128;
int SCALE_FACTOR=4;
int X_TILE_SIZE=8;
int Y_TILE_SIZE=8;
int LAST_OBJECT=0;
int actid=0;
int error=0;
ALLEGRO_CONFIG *cfg;
ALLEGRO_BITMAP *bmp,*virt,*tmp=NULL;
ALLEGRO_DISPLAY *display;
ALLEGRO_KEYBOARD_STATE key;
ALLEGRO_FONT *font;
signed int xcursor=0;
signed int ycursor=0;
signed char x=0;
signed char y=0;
signed char finex=0;
signed char finey=0;
char finish=0;
ALLEGRO_COLOR black,white,red,color;
int scale_cursor_x=0;
int scale_cursor_y=0;
int i=0;
int a=0;
unsigned char r,g,b=0;
char pngfilename[20];
char *tmpbuf;
char buf[5];
char buf2[5];

	/* Iniciar el rollo */
	tmpbuf=(char *)malloc(sizeof(char)*X_ROOM_SIZE*Y_ROOM_SIZE);
	memset(tmpbuf,0,sizeof(char)*X_ROOM_SIZE*Y_ROOM_SIZE);
	al_init();
	al_init_image_addon();
	al_init_primitives_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	cfg=al_load_config_file("sacagraf.cfg");
	if (cfg==NULL)
	{
		cfg=al_create_config();
		al_add_config_section(cfg,"Ajustes");
		al_add_config_section(cfg,"Objetos");
		al_set_config_value(cfg,"Ajustes","Habitaciones en horizontal","13");
		al_set_config_value(cfg,"Ajustes","Habitaciones en vertical","16");
		al_set_config_value(cfg,"Ajustes","Ancho de la habitacion original en pixels","256");
		al_set_config_value(cfg,"Ajustes","Alto de la habitacion original en pixels","128");
		al_set_config_value(cfg,"Ajustes","Ancho minimo del caracter original","8");
		al_set_config_value(cfg,"Ajustes","Alto minimo del caracter original","8");
		al_set_config_value(cfg,"Ajustes","Factor de escalado","4");
		al_set_config_value(cfg,"Objetos","Ultimo","0");
		al_save_config_file("sacagraf.cfg",cfg);
	}

	X_ROOMS=atoi(al_get_config_value(cfg,"Ajustes","Habitaciones en horizontal"));
	Y_ROOMS=atoi(al_get_config_value(cfg,"Ajustes","Habitaciones en vertical"));
	X_ROOM_SIZE=atoi(al_get_config_value(cfg,"Ajustes","Ancho de la habitacion original en pixels"));
	Y_ROOM_SIZE=atoi(al_get_config_value(cfg,"Ajustes","Alto de la habitacion original en pixels"));
	SCALE_FACTOR=atoi(al_get_config_value(cfg,"Ajustes","Factor de escalado"));
	X_TILE_SIZE=atoi(al_get_config_value(cfg,"Ajustes","Alto minimo del caracter original"));
	Y_TILE_SIZE=atoi(al_get_config_value(cfg,"Ajustes","Ancho minimo del caracter original"));
	LAST_OBJECT=atoi(al_get_config_value(cfg,"Objetos","Ultimo"));
	actid=LAST_OBJECT;

	al_set_new_display_flags(ALLEGRO_OPENGL | ALLEGRO_WINDOWED);
	display=al_create_display(X_ROOM_SIZE*SCALE_FACTOR,192*SCALE_FACTOR);
	bmp=al_load_bitmap("map.png");
	virt=al_create_bitmap(X_ROOM_SIZE*SCALE_FACTOR,Y_ROOM_SIZE*SCALE_FACTOR);
	font=al_load_ttf_font("proggy.ttf",6*SCALE_FACTOR,0);
	al_install_keyboard();
	black=al_map_rgb(0,0,0);
	white=al_map_rgba_f(1,1,1,1);
	red=al_map_rgba_f(1,0,0,0.7);

	/* Que empiece la fiesta */
	while(!finish)
	{
		al_get_keyboard_state(&key);
		if (al_key_down(&key,ALLEGRO_KEY_ESCAPE))
		{
			finish=1;
		}

		if (al_key_down(&key,ALLEGRO_KEY_LCTRL))
		{
			finex=0;
			finey=0;
			if (al_key_down(&key,ALLEGRO_KEY_RIGHT))
			{
				x++;
				if (x==X_ROOMS) x=X_ROOMS-1;
			}
			if (al_key_down(&key,ALLEGRO_KEY_LEFT))
			{
				x--;
				if (x<0) x=0;
			}
			if (al_key_down(&key,ALLEGRO_KEY_UP))
			{
				y--;
				if (y<0) y=0;
			}
			if (al_key_down(&key,ALLEGRO_KEY_DOWN))
			{
				y++;
				if (y>Y_ROOMS-1) y=Y_ROOMS-1;
			}
		}
		else if (al_key_down(&key,ALLEGRO_KEY_LSHIFT))
		{
			if (al_key_down(&key,ALLEGRO_KEY_RIGHT))
			{
				finex++;
				if (finex>X_TILE_SIZE) finex=X_TILE_SIZE;
			}
			if (al_key_down(&key,ALLEGRO_KEY_LEFT))
			{
				finex--;
				if (finex<-X_TILE_SIZE) finex=-X_TILE_SIZE;
			}
			if (al_key_down(&key,ALLEGRO_KEY_UP))
			{
				finey--;
				if (finey<-Y_TILE_SIZE) finey=-Y_TILE_SIZE;
			}
			if (al_key_down(&key,ALLEGRO_KEY_DOWN))
			{
				finey++;
				if (finey>Y_TILE_SIZE) finey=Y_TILE_SIZE;
			}
		}
		else if (al_key_down(&key,ALLEGRO_KEY_ALT))
		{
			if (al_key_down(&key,ALLEGRO_KEY_RIGHT))
			{
				scale_cursor_x++;
				//if (finex>8) finex=8;
			}
			if (al_key_down(&key,ALLEGRO_KEY_LEFT))
			{
				scale_cursor_x--;
				//if (finex<0) finex=0;
			}
			if (al_key_down(&key,ALLEGRO_KEY_UP))
			{
				scale_cursor_y--;
				//if (finey<0) finey=0;
			}
			if (al_key_down(&key,ALLEGRO_KEY_DOWN))
			{
				scale_cursor_y++;
				//if (finey>8) finey=8;
			}
		}
		else
		{
			if (al_key_down(&key,ALLEGRO_KEY_RIGHT))
			{
				xcursor+=X_TILE_SIZE*SCALE_FACTOR;
			}
			if (al_key_down(&key,ALLEGRO_KEY_LEFT))
			{
				xcursor-=X_TILE_SIZE*SCALE_FACTOR;
			}
			if (al_key_down(&key,ALLEGRO_KEY_UP))
			{
				ycursor-=Y_TILE_SIZE*SCALE_FACTOR;
			}
			if (al_key_down(&key,ALLEGRO_KEY_DOWN))
			{
				ycursor+=Y_TILE_SIZE*SCALE_FACTOR;
			}
		}

		al_clear_to_color(black);
		al_set_target_bitmap(virt);
		//al_set_blender(ALLEGRO_ALPHA,ALLEGRO_INVERSE_ALPHA,white);
		al_draw_bitmap_region(bmp,0+(x*X_ROOM_SIZE)+finex,0+(y*Y_ROOM_SIZE)+finey,X_ROOM_SIZE,Y_ROOM_SIZE,0,0,0);
		al_set_target_bitmap(al_get_backbuffer(display));
		al_draw_scaled_bitmap(virt,0,0,X_ROOM_SIZE,Y_ROOM_SIZE,0,0,X_ROOM_SIZE*SCALE_FACTOR,Y_ROOM_SIZE*SCALE_FACTOR,0);
		al_draw_line(0,512,1024,512,white,0);
		al_draw_textf(font,al_map_rgba(200,200,200,200),0,520,0,"mapa x: %d  mapa y: %d  habitacion nº: %d  ajuste fino x: %d  ajuste fijo y: %d",x,y,x+(y*13),finex,finey);
		if (error)
		{
			al_draw_textf(font,al_map_rgba(200,200,200,200),0,540,0,"Patron repetido");
			al_flip_display();
			al_rest(1);
			error=0;
		}


		if (al_key_down(&key,ALLEGRO_KEY_ENTER))
		{
			tmp=al_create_bitmap((X_TILE_SIZE*SCALE_FACTOR)+(X_TILE_SIZE*SCALE_FACTOR*scale_cursor_x),(Y_TILE_SIZE*SCALE_FACTOR)+(Y_TILE_SIZE*SCALE_FACTOR*scale_cursor_y));
			al_set_target_bitmap(tmp);
			al_draw_bitmap_region(al_get_backbuffer(display),xcursor,ycursor,(X_TILE_SIZE*SCALE_FACTOR*scale_cursor_x)+(X_TILE_SIZE*SCALE_FACTOR),(Y_TILE_SIZE*SCALE_FACTOR*scale_cursor_y)+(Y_TILE_SIZE*SCALE_FACTOR),0,0,0);

			memset(tmpbuf,0,sizeof(char)*X_ROOM_SIZE*Y_ROOM_SIZE);
			memset(buf,0,5);

			for (i=0;i<(Y_TILE_SIZE*scale_cursor_y*SCALE_FACTOR)+(Y_TILE_SIZE*SCALE_FACTOR);i+=SCALE_FACTOR)
			{
				for (a=0;a<(X_TILE_SIZE*scale_cursor_x*SCALE_FACTOR)+(X_TILE_SIZE*SCALE_FACTOR);a+=SCALE_FACTOR)
				{
					color=al_get_pixel(tmp,a,i);
					al_unmap_rgb(color,&r,&g,&b);
					if (!r && !g && !b)
					{
						strcat(tmpbuf,"0");
					}
					else
					{
						strcat(tmpbuf,"1");
					}
				}
			}

			/* Ya está la secuencia del gráfico en tmpbuf, examinamos todas las secuencias anteriores */

			error=0;
			for (i=0;i<actid;i++)
			{
				memset(buf2,0,5);
				sprintf(buf2,"%d",i);

				if (!strcmp(al_get_config_value(cfg,"Objetos",buf2),tmpbuf))
				{
					error=i;
				}
			}

			/* Si no hay secuencias repetidas lo grabamos */
			if (!error)
			{
				sprintf(buf,"%d",actid);
				al_set_config_value(cfg,"Objetos",buf,tmpbuf);
				memset(pngfilename,0,20);
				sprintf(pngfilename,"dec%d.png",actid);
				al_save_bitmap(pngfilename,tmp);
				actid++;
			}

			al_destroy_bitmap(tmp);
		}

		al_set_target_bitmap(al_get_backbuffer(display));
		//al_set_blender(ALLEGRO_ALPHA,ALLEGRO_INVERSE_ALPHA,red);
		al_draw_filled_rectangle(xcursor,ycursor,xcursor+((X_TILE_SIZE*SCALE_FACTOR)+(X_TILE_SIZE*SCALE_FACTOR*scale_cursor_x)),ycursor+((Y_TILE_SIZE*SCALE_FACTOR)+(Y_TILE_SIZE*SCALE_FACTOR*scale_cursor_y)),red);
		al_flip_display();
		al_rest(0.1);
	}

	memset(buf,0,5);
	sprintf(buf,"%d",actid);
	al_set_config_value(cfg,"Objetos","Ultimo",buf);
	al_save_config_file("sacagraf.cfg",cfg);
	al_destroy_font(font);
	al_uninstall_keyboard();
	al_destroy_bitmap(bmp);
	al_destroy_bitmap(virt);
	al_destroy_display(display);
	al_destroy_config(cfg);
	al_shutdown_ttf_addon();
	al_shutdown_font_addon();
	al_shutdown_image_addon();
	al_shutdown_primitives_addon();
	free(tmpbuf);
	return 0;
}
int main() {
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("nao foi possivel inicializar camera");

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

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

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

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

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

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

  al_register_event_source(queue, al_get_display_event_source(display));

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

  al_register_event_source(queue, al_get_timer_event_source(timer));

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

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

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

  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);

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

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

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

  sniper = al_load_bitmap("semi.png");

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

  int continuar = 1;
  int atualizar = 0;

  al_start_timer(timer);

  while(continuar) {
    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

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

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

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

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

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

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

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

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

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

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

      al_flip_display();

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

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

  al_destroy_bitmap(direita);

  al_destroy_bitmap(esquerda);

  camera_libera_matriz(cam, matriz);

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

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

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

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

  camera_finaliza(cam);

  return EXIT_SUCCESS;


}
int main() {
  //inicialização
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");

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

  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(largura, altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);

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

  unsigned char ***matriz = camera_aloca_matriz(cam);
  int ***background = alocaHsvMatriz(cam->largura, cam->altura);

  fila *f = aloca();

  //cor para desenhar o círculo
  ALLEGRO_COLOR cor = al_map_rgb_f(0, 0, 1);

  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);

  //tela exibindo img normal
  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);

  //tela mostrando como o computador enxerga
  //ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura/2, 0, largura/2, altura/2);
  ALLEGRO_BITMAP *silhueta = al_create_bitmap(largura, altura);

  /**********/
  srand(time(NULL));
  int desenhar = 0;
  int terminar = 0;

  int cycle = 0;
  int hitx = rand() % (largura);
  int hity = rand() % (altura);

  int x, y;

  float cyr, cxr, cnr, lastCx, lastCy;

  int r, g, b, r2, g2, b2;

  int h, s, v, h2, s2, v2;
  int fh, fs, fv;

  int dh, ds, dv;
  int tempH;

  int token;

  double value;
  int dist;

  al_rest(1);

  for(y = 0; y < altura; y++)
    for(x = 0; x < largura; x++){
      rgbToHsv(cam->quadro[y][x][0], cam->quadro[y][x][1], cam->quadro[y][x][2], 
        &background[y][x][0], &background[y][x][1], &background[y][x][2]);

      if(background[y][x][0] > 180){
        background[y][x][0] -= 360;
        background[y][x][0] = -background[y][x][0];
      }
        
    }

  al_rest(1);

  for(y = 0; y < altura; y++)
    for(x = 0; x < largura; x++){
      rgbToHsv(cam->quadro[y][x][0], cam->quadro[y][x][1], cam->quadro[y][x][2], 
        &fh, &fs, &fv);

      if(fh > 180){
        fh -= 360;
        fh = -fh;
      }

      background[y][x][0] += fh;
      background[y][x][0] /=2;

      background[y][x][1] += fs;
      background[y][x][1] /=2;
      
      background[y][x][2] += fv;
      background[y][x][2] /=2;  
    }

  //gameloop
  while(1) {
    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;

      break;

    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;

    default:
      printf("evento desconhecido\n");
    }

    if(terminar)
      break;

    //interpretar img e realizar transformações
    printf("%d\n", al_is_event_queue_empty(queue));
    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);

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

      int bx, by, bn;

      cyr = 0;
      cxr = 0;
      cnr = 0;

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

          rgbToHsv(r, g, b, &h, &s, &v);

          if(h < 15 || h > 345)
            if(s > 75 && v > 75){
              cyr += y;
              cxr += x;
              cnr++;
            }

          //Silhueta (REFINAR!!!)
          if(h > 180)
            tempH = -(h - 360);

          else
            tempH = h;

          dh = tempH - background[y][x][0];
          if(dh < 0)
            dh = -dh;

          ds = s - background[y][x][1];
          if(ds < 0)
            ds = -ds;

          dv = v - background[y][x][2];
          if(dv < 0)
            dv = -dv;

          //dh > 15 && ds > 10 para tirar a interfencia de iluminacao, mas gera mtuiro ruido
          //ds > 25 é o mais preciso, mas sofre de interferencia de iluminacao
          if(dv > 25){
            //valores para teste!
            matriz[y][x][0] = 37;
            matriz[y][x][1] = 50;
            matriz[y][x][2] = 248;
          }

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

          //Escudo
          if(h < 135 && h > 105 && s > 50 && v > 75){
            by += y;
            bx += x;
            bn++;

            matriz[y][x][0] = 0;
            matriz[y][x][1] = 255;
            matriz[y][x][2] = 0;
          }
        }
      }

     /*for(y = 1; y < altura-1; y++)
        for(x = 1; x < largura-1; x++){
          token = 4;

          if(255 != matriz[y+1][x][0])
            token--;
          if(255 != matriz[y-1][x][0])
            token--;
          if(255 != matriz[y][x+1][0])
            token--;
          if(255 != matriz[y][x-1][0])
            token--;

          if(token == 0){
            matriz[y][x][0] = 0;
            matriz[y][x][1] = 0;
            matriz[y][x][2] = 0;
          }*/

      cycle++;
      if(cycle > 50 && bn > 0){
        value = (pow(hitx - (bx / 2 /bn), 2) + pow(hity - (by / 2 / bn), 2));
        dist = sqrt(value) - 7;

        if(dist < 100 && dist > -100 && bn > 0)
          printf("block!\n");

        else{
          if(matriz[hity][hitx][0] == 255)
            printf("hit\n");

          else
            printf("miss\n");
        }

        cycle = 0;
        hitx = rand() % (largura/2);
        hity = rand() % (altura/2);
      }

      /**********/
      camera_copia(cam, cam->quadro, esquerda);

      //Copia img editada na img direita
      camera_copia(cam, matriz, silhueta);
      //cor para teste!
      al_convert_mask_to_alpha(silhueta, al_map_rgb(37, 50, 248));
      al_draw_bitmap(silhueta, 0, 0, 0);
      /**********/

      if(bn > 0)
        al_draw_circle(bx / bn, by / bn, 100, al_map_rgb(0, 0, 255), 1);

      if(cycle >= 40){
        if(cycle < 48){
          al_draw_circle(hitx, hity, 15, al_map_rgb(0, 0, 255), 30);
          al_draw_circle(hitx + largura, hity, 6, al_map_rgb(0, 0, 255), 3);
        }

        else
          al_draw_circle(hitx, hity, 15, al_map_rgb(255, 0, 0), 30);
      }

      if(cnr > 10){
        lastCx = cxr / cnr;
        lastCy = cyr / cnr;

        al_draw_circle(lastCx, lastCy, 100, al_map_rgb(255, 0, 0), 1);

        insere(f, lastCx, lastCy);
      }

      else
        insere(f, lastCx, lastCy);

      if(f->count > 10)
          retira(f);

      drawAtk(f);

      al_flip_display();
    }
  }

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

  libera(f);

  al_destroy_bitmap(silhueta);

  al_destroy_bitmap(esquerda);

  camera_libera_matriz(cam, matriz);
  liberaHsvMatriz(background, cam->largura, cam->altura);

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

  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);

  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
Example #15
0
int execAlleg()
{
	// init variables from lua

		lua_getglobal(L, "Screen");
		SCREEN_W = getfield(L, "width");
		SCREEN_H = getfield(L, "height");
		lua_pop(L, 1);

		printf("screen height= %d width= %d\n", SCREEN_H, SCREEN_W);

		lua_getglobal(L, "Car");
		CAR_WIDTH = getfield(L, "width");
		lua_pop(L, 1);

		printf("car width= %d\n", CAR_WIDTH);

		lua_getglobal(L, "Track");
		TRACKS_NUM = getfield(L, "number");
		TRACKS_BEGIN = getfield(L, "begin");
		TRACKS_FINISH = getfield(L, "finish");
		lua_pop(L, 1);

		// register C function to Lua
		lua_pushcfunction(L, getCar);
		lua_setglobal(L, "sendCar");

	// end of lua intialization

	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *world;
	
	bool doexit = false;
	bool redraw = true;
	bool KEY_LEFT = false, KEY_RIGHT = 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;
	}
	
	if(!al_install_mouse()) {
      fprintf(stderr, "failed to initialize the mouse!\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;
	}

	if (!al_init_primitives_addon()) {
		fprintf(stderr, "failed to init primitives addon!\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;
	}
	
	world = al_create_bitmap(SCREEN_W, SCREEN_H);
	if(!world) {
		fprintf(stderr, "failed to create world bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}
	
	cars_num = (unsigned*)malloc(BAR_W*sizeof(unsigned));
	cars_col = (float*)malloc(BAR_W*sizeof(float));
	int n;
	for (n = 0; n < BAR_W; n++) {
		cars_num[n] = 0;
		cars_col[n] = 1;
	}
	
 
	al_set_target_bitmap(world);
	al_clear_to_color(al_map_rgb(0, 0, 0));
	al_set_target_bitmap(al_get_backbuffer(display));

	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_register_event_source(event_queue, al_get_mouse_event_source());
	
	al_start_timer(timer);

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

		if(ev.type == ALLEGRO_EVENT_TIMER && 
			al_is_event_queue_empty(event_queue) &&
			!PAUSE) {
		
			al_set_target_bitmap(world);
			al_clear_to_color(al_map_rgb(0,0,0));

			// your code here
			
			drawTracks();
			
			lua_getglobal(L, "simulate");
			lua_call(L,0,0);
			
			drawBar();
			// end of your code
			
		}
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch(ev.keyboard.keycode) {
				case ALLEGRO_KEY_LEFT: KEY_LEFT = true; break;
				case ALLEGRO_KEY_RIGHT: KEY_RIGHT = true; break;
				case ALLEGRO_KEY_P: PAUSE = (PAUSE) ? false : true; break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch(ev.keyboard.keycode) {
				case ALLEGRO_KEY_LEFT: KEY_LEFT = false; break;
				case ALLEGRO_KEY_RIGHT: KEY_RIGHT = false; break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
			world_x = ((SCREEN_W - TRACKS_BEGIN - TRACKS_FINISH)*ev.mouse.x)/SCREEN_W;
		}
		/*
		if (ev.type == ALLEGRO_EVENT_MOUSE_AXES || 
			ev.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) {
			al_flush_event_queue(event_queue);
		}
		*/
		if (KEY_LEFT) {
			if (world_x + 20 <= 0) world_x += 20;
		}
		if (KEY_RIGHT) {
			if (world_x - 20 >= SCREEN_W - TRACKS_BEGIN - TRACKS_FINISH) world_x -= 20;
		}
		
		if (redraw) {
			al_set_target_bitmap(al_get_backbuffer(display));
			al_draw_bitmap(world, 0, 0, 0);
			al_flip_display();
		}
	}

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

	return 0;
}
 void LL_SHARED uninstall_primitives()
 {
     al_shutdown_primitives_addon();
 }
Example #17
0
File: game.c Project: ooonak/cmess
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;
}