Пример #1
0
void action_decrreloadtime(uint32_t keymod)
{ 
    if(ssConfig.automatic_reload_time) {
        if(ssConfig.automatic_reload_time > 0) {
            ssConfig.automatic_reload_time -= ssConfig.automatic_reload_step;
        }
        if( ssConfig.automatic_reload_time <= 0 ) {
            al_stop_timer(reloadtimer);
            ssConfig.automatic_reload_time = 0;
        } else {
            initAutoReload();
        }
        paintboard();
    }
}
Пример #2
0
int dot_menu_proc_music_no(void * data, int i, void * pp)
{
	APP_INSTANCE * app = (APP_INSTANCE *)data;

	app->music_enabled = false;
	al_set_config_value(t3f_config, "Game Data", "Music Enabled", "false");
	if(t3f_get_music_state() == T3F_MUSIC_STATE_PLAYING)
	{
		al_stop_timer(t3f_timer);
		t3f_stop_music();
		al_resume_timer(t3f_timer);
	}
	app->current_menu = DOT_MENU_MAIN;
	dot_update_first_run();
	return 1;
}
Пример #3
0
int dot_menu_proc_leaderboard(void * data, int i, void * pp)
{
	APP_INSTANCE * app = (APP_INSTANCE *)data;

	al_stop_timer(t3f_timer);
	dot_show_message(data, "Downloading leaderboard...");
	app->leaderboard = t3net_get_leaderboard(DOT_LEADERBOARD_RETRIEVE_URL, "dot_to_dot_sweep", DOT_LEADERBOARD_VERSION, "normal", "none", 10, 0);
	if(app->leaderboard)
	{
		app->leaderboard_spot = -1;
		app->state = DOT_STATE_LEADERBOARD;
		app->current_menu = DOT_MENU_LEADERBOARD;
	}
	al_resume_timer(t3f_timer);
	return 1;
}
Пример #4
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();
}
Пример #5
0
Файл: gfx.c Проект: juliords/ai1
void gfx_step(void)
{
	int i;
	static int toogle=0;
	ALLEGRO_EVENT ev;

	for (i = 0; i < MOVE_FRAMES; i++) {
		do {
			al_wait_for_event(G.ev, &ev);
			switch (ev.type) {
			case ALLEGRO_EVENT_KEY_DOWN:
				if (toogle ^= 1) al_stop_timer(G.tick);
				else al_start_timer(G.tick);
				break;
			default:
				break;
			}
		} while (ev.type != ALLEGRO_EVENT_TIMER);
		gfx_render(i);
	}
}
Пример #6
0
char * select_file(const char * initial, const char * title, const char * types, int flags)
{
	al_stop_timer(t3f_timer);
	ALLEGRO_FILECHOOSER * file_selector = NULL;
	const char * rpath = NULL;
	file_selector = al_create_native_file_dialog(initial, title, types, flags);
	al_show_native_file_dialog(t3f_display, file_selector);
	if(al_get_native_file_dialog_count(file_selector))
	{
		rpath = al_get_native_file_dialog_path(file_selector, 0);
	}
	if(rpath)
	{
		strcpy(mapper_filename, rpath);
	}
	al_destroy_native_file_dialog(file_selector);
	al_start_timer(t3f_timer);
	if(rpath)
	{
		return mapper_filename;
	}
	return NULL;
}
Пример #7
0
int main(void)
{
	//Initialize allegro--------------------------------
	if (InitAllegro())
	{
		return -1;
	}

	srand(time(NULL));

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

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

	Display MainDisplay(Event_Queue);

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

	return 0;
}
Пример #8
0
int main(short int argc, char** argv) {

	al_init();
	al_install_keyboard();
	al_install_mouse();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();

	ALLEGRO_MONITOR_INFO oMonitorInfo;
	al_get_monitor_info(0, &oMonitorInfo);

	short int iDisplayWidth = oMonitorInfo.x2 * 0.70f;
	short int iDisplayHeight = oMonitorInfo.y2 * 0.70f;
	short int iAppWidth = iDisplayWidth * 0.95f;
	short int iAppHeight = iDisplayHeight * 0.95f;
	short int iMarginHorizontal = (iDisplayWidth - iAppWidth) / 2;
	short int iMarginVertical = ((iDisplayHeight - iAppHeight) / 2);
	int iGenerations = 0;
	short int iFPS = 30;
	float iLifeMin = 3.0f;
	float iLifeMax = 37.0f;	
	short int iFontSize = (iDisplayWidth > 1024) ? 12 : 10;
	if (iDisplayWidth < 800) {
		iFontSize = 8;
	}
	long int iSimulations = 1;

	std::random_device rd;
	std::mt19937 mt(rd());
	std::uniform_real_distribution<double> dist(iLifeMin, iLifeMax);
	
	int iLifeScarcity = std::round(dist(mt));

	bool** pCells = new bool*[iAppWidth];
	bool** pNextGenCells = new bool*[iAppWidth];

	initCells(pCells, pNextGenCells, iAppWidth, iAppHeight, iLifeScarcity);

	ALLEGRO_DISPLAY* pDisplay = al_create_display(iDisplayWidth, iDisplayHeight);	
	ALLEGRO_EVENT_QUEUE* pQueue = al_create_event_queue();	
	ALLEGRO_TIMER* pTimer = al_create_timer(1.0f / iFPS);
	ALLEGRO_TIMER* pSecondBySecondTimer = al_create_timer(1.0f);
	ALLEGRO_BITMAP* pBuffer = al_create_bitmap(iAppWidth, iAppHeight);
	ALLEGRO_COLOR oBackgroundColor = al_map_rgb(0, 0, 0);
	ALLEGRO_COLOR oCellColor = al_map_rgb(randr(150, 255), randr(150, 255), randr(150, 255));
	ALLEGRO_FONT* oFont = al_load_ttf_font("VeraMono.ttf", iFontSize, 0);
	ALLEGRO_FONT* oFontLarge = al_load_ttf_font("VeraMono.ttf", (iFontSize * 3), 0);

	al_inhibit_screensaver(true);
	
	al_register_event_source(pQueue, al_get_keyboard_event_source());
	al_register_event_source(pQueue, al_get_mouse_event_source());	
	al_register_event_source(pQueue, al_get_timer_event_source(pTimer));
	al_register_event_source(pQueue, al_get_timer_event_source(pSecondBySecondTimer));
	al_set_target_backbuffer(pDisplay);
	al_clear_to_color(oBackgroundColor);
	al_flip_display();

	al_start_timer(pTimer);
	al_start_timer(pSecondBySecondTimer);

	ALLEGRO_EVENT oEvent;

	short int iBufferUsed = 0;
	short int iBufferDrawn = 0;
	bool bRedraw = false;
	std::string sHeaderStatistics = "GEN  [GENXXXXX]     FPS  [FPSXXXXX]     CELLS  [CELLSXXXXX]    GENS/S  [GENSSXXXXX]    SCARCTY  [SCARXXXXX]    TIME  [TIMEXXXXX]";
	std::string sHeaderStats = "";
	/* std::string sHeaderText_2 = "";
	std::string sHeaderText_3 = "";
	std::string sHeaderText_4 = "";
	std::string sHeaderText_5 = "";
	std::string sHeaderText_6 = ""; */
	std::string sCountdownText = "";
	std::string sSimulations = "";
	std::string sStats = "CELLS: ";

	sStats.append(std::to_string((iAppWidth * iAppHeight)));
	sStats.append(", MAP SIZE (KB): ");
	sStats.append(std::to_string((iAppWidth * iAppHeight * sizeof(bool)) / 1024));
	sStats.append("  (SPACE) Pause (C)olor, (R)eload, (S)carcity, (F) +1 FPS, (G) -1 FPS, (ESC) Exit");

	long int iTotalAlive = 0;
	int iPatternStableBuffer = (iFPS * 4);
	long int* iTotalPatternStable = new long int[iPatternStableBuffer];
	short int iTotalPatternCounter = 0;
	long int iSecondsRunning = 0;

	float fPosText2 = (iAppWidth * 0.15);
	float fPosText3 = (iAppWidth * 0.30);
	float fPosText4 = (iAppWidth * 0.50);	
	float fPosText5 = (iAppWidth * 0.70);
	float fPosText6 = (iAppWidth * 0.85);

	float fPosTextSim = (iAppWidth * 0.75);

	bool bPatternIsStable = false;
	int iCountdownSeconds = 10;

	bool bDrawingOn = false;
	bool bTimerStopped = false;

	ALLEGRO_COLOR oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255));

	while (true) {
		
		al_wait_for_event(pQueue, &oEvent);

		if (oEvent.type == ALLEGRO_EVENT_TIMER) {
			if (!bTimerStopped) {
				if (oEvent.timer.source == pTimer) {

					iTotalAlive = 0;
					redrawCells(pBuffer, pCells, pNextGenCells, iAppWidth, iAppHeight, oCellColor, oBackgroundColor);
					nextGeneration(pCells, pNextGenCells, iAppWidth, iAppHeight, iTotalAlive);
					al_set_target_backbuffer(pDisplay);
					al_clear_to_color(oBackgroundColor);
					al_draw_bitmap(pBuffer, iMarginHorizontal, iMarginVertical, 0);

					sHeaderStats = ReplaceString(sHeaderStatistics, "[GENXXXXX]", std::to_string(iGenerations));
					sHeaderStats = ReplaceString(sHeaderStats, "[FPSXXXXX]", std::to_string(iFPS));
					sHeaderStats = ReplaceString(sHeaderStats, "[CELLSXXXXX]", std::to_string(iTotalAlive));
					sHeaderStats = ReplaceString(sHeaderStats, "[SCARXXXXX]", std::to_string(iLifeScarcity));
					sHeaderStats = ReplaceString(sHeaderStats, "[TIMEXXXXX]", std::to_string(iSecondsRunning));
					if (iGenerations > 0 && iSecondsRunning > 0) {
						sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", std::to_string(iGenerations / iSecondsRunning));
					}
					else {
						sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", "0");
					}					
					sSimulations = "SIMS ";
					sSimulations.append(std::to_string(iSimulations));
					int iLengthSims = al_get_text_width(oFont, sSimulations.c_str());
					int iLengthStats = al_get_text_width(oFont, sHeaderStats.c_str());
					al_draw_text(oFont, oCellColor, ((iAppWidth - iLengthStats) / 2), 1.0f, 0, sHeaderStats.c_str());
					al_draw_text(oFont, oCellColor, (iDisplayWidth - (iLengthSims + 25.0f)), (iAppHeight + iMarginVertical + 5.0f), 0, sSimulations.c_str());
					al_draw_text(oFont, oCellColor, 25.0f, (iAppHeight + iMarginVertical + 5.0f), 0, sStats.c_str());

					if (bPatternIsStable == true) {
						sCountdownText.clear();
						sCountdownText.append("PATTERN STABILIZED, RESTARTING IN... ");
						int iLengthStr = al_get_text_width(oFontLarge, sCountdownText.c_str());
						sCountdownText.append(std::to_string(iCountdownSeconds));
						al_draw_text(oFontLarge, oRandColor, ((iAppWidth - iLengthStr) / 2), (iAppHeight * 0.45f), 0, sCountdownText.c_str());
					}

					al_flip_display();
					++iGenerations;
					copyCells(pCells, pNextGenCells, iAppWidth, iAppHeight);

					if (iTotalPatternCounter == iPatternStableBuffer) {
						bPatternIsStable = isPatternStable(iTotalPatternStable, iPatternStableBuffer);
						delete iTotalPatternStable;
						iTotalPatternStable = new long int[iPatternStableBuffer];
						iTotalPatternCounter = 0;
					}
					iTotalPatternStable[iTotalPatternCounter] = iTotalAlive;
					++iTotalPatternCounter;
				}

				if (oEvent.timer.source == pSecondBySecondTimer) {
					if (bPatternIsStable == true) {
						if (iCountdownSeconds > 1) {
							--iCountdownSeconds;
						}
						else {
							bPatternIsStable = false;
							iTotalPatternCounter = 0;
							iGenerations = 0;
							iSecondsRunning = 0;
							iCountdownSeconds = 10;
							++iSimulations;
							clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
							randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
						}
					}
					else {
						iCountdownSeconds = 10;
					}
					++iSecondsRunning;
					oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255));
				}
			}
		}

		if (oEvent.type == ALLEGRO_EVENT_KEY_DOWN) {
			
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {				
				break;
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_SPACE) {
				if (!bTimerStopped) {					
					bTimerStopped = true;
					al_stop_timer(pTimer);
				}
				else {					
					bTimerStopped = false;
					al_start_timer(pTimer);
				}				
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_R) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_S) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = randr(iLifeMin, iLifeMax);
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);				
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_M) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = iLifeMin;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_N) {
				bPatternIsStable = false;
				iTotalPatternCounter = 0;
				iGenerations = 0;
				iSecondsRunning = 0;
				iCountdownSeconds = 10;
				iLifeScarcity = iLifeMax;
				++iSimulations;
				clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight);
				randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity);
			}

			if (oEvent.keyboard.keycode == ALLEGRO_KEY_F) {
				++iFPS;				
				al_set_timer_speed(pTimer, (1.0f / iFPS));
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_G) {
				if(iFPS > 3) {
					--iFPS;
				}
				al_set_timer_speed(pTimer, (1.0f / iFPS));
			}
			if (oEvent.keyboard.keycode == ALLEGRO_KEY_C) {				
				int iRCell = randr(0, 255);
				int iGCell = randr(0, 255);
				int iBCell = randr(0, 255);
				oCellColor = al_map_rgb(iRCell, iGCell, iBCell);
			}
		}

	}	// End main loop

	al_destroy_event_queue(pQueue);	
	al_destroy_display(pDisplay);

	delete iTotalPatternStable;
	for (short int i = 0; i < iAppWidth; i++) {
		delete pCells[i];
		delete pNextGenCells[i];
	}
	delete[] pCells;
	delete[] pNextGenCells;
	return 0;
}
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;
}
Пример #10
0
 /**
     Stops the timer.
  */
 void stop() {
     al_stop_timer(get());
 }
Пример #11
0
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);
    }
}
Пример #12
0
void drawWorld()
{
    al_clear_to_color(al_map_rgb(0, 0, 0));

    /******************* Dessin de la ligne pointillé ****************/
    for (int i = 0; i < GAME_HEIGHT; i+= 20)
        al_draw_line(GAME_WIDTH/2, i, GAME_WIDTH/2, i + 10, WHITE, 3);

    //Dessin des deux raquettes virtuelles

    if(player1.y < 0)
        player1.y = 0;
    if(player1.y > GAME_HEIGHT - 60)
        player1.y = GAME_HEIGHT - 60;
    if(player2.y < 0)
        player2.y = 0;
    if(player2.y > GAME_HEIGHT - 60)
        player2.y = GAME_HEIGHT - 60;

    al_draw_bitmap(player1.img, player1.x, player1.y, 0);
    al_draw_bitmap(player2.img, player2.x, player2.y, 0);

    //Dessin de la balle

    /****** Test si la ball a atteint le bas ou le haut de l'ecran si c'est le case je change ca direction ******/
    if(ball.y < 0)
    {
        ball.y = 0;
        ball.dy *= -1;
    }
    if(ball.y > GAME_HEIGHT - 14)
    {
        ball.y = GAME_HEIGHT - 14;
        ball.dy *= -1;
    }

    /********* gestion des collisions ********/
    if(ball.x <= player1.x + 10 && ball.x >= player1.x && ball.y >= player1.y && ball.y + 7 <= player1.y + 60)
    {
        ball.dx *= -1;
    }
    if(ball.x + 14 <= player2.x + 10 && ball.x + 14 >= player2.x && ball.y >= player2.y && ball.y + 7 <= player2.y + 60)
    {
        ball.dx *= -1;
    }

    al_draw_bitmap(ball.img, ball.x, ball.y, 0);

    if(ball.x + 14 < 0)
    {
        al_stop_timer(timer);
        if(mode == MULTI)
            al_show_native_message_box(al_get_current_display(),"Bravo !", "Bravo !", "Vous avez gagné !",NULL,0);
        else
            al_show_native_message_box(al_get_current_display(),"Pas de chance !", "Pad de chance !", "Vous avez perdu :( !",NULL,0);
        player2.score++;
        lunchBall();
        al_start_timer(timer);
    }
    else if(ball.x > GAME_WIDTH)
    {
        al_stop_timer(timer);
        al_show_native_message_box(al_get_current_display(),"Bravo !", "Bravo !", "Vous avez gagné !",NULL,0);
        player1.score++;
        lunchBall();
        al_start_timer(timer);
    }

    //Affichage des scores
    updatesScorePlayers();

    al_flip_display();
}
Пример #13
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;
}
Пример #14
0
void Renderer::run()
{
	NBT_Debug("begin");

	al_hide_mouse_cursor(dpy_);

	al_identity_transform(&camera_transform_);

	float x = -camera_pos_.x, y = -camera_pos_.y, z = -camera_pos_.z;
	//x = -dim0_->spawnX();
	//z = -dim0_->spawnZ();

	al_translate_transform_3d(&camera_transform_, x, y, z);

	al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, DEG_TO_RAD(180));

	memset(key_state_, 0, sizeof(key_state_) * sizeof(key_state_[0]));

	al_start_timer(tmr_);

	NBT_Debug("run!");

	//al_use_shader(nullptr);

	/*ALLEGRO_TRANSFORM trans;
	al_identity_transform(&trans);
	al_orthographic_transform(&trans, 0, 0, -1, al_get_display_width(dpy_), al_get_display_height(dpy_), 1);
	al_set_projection_transform(dpy_, &trans);
	al_identity_transform(&trans);
	al_use_transform(&trans);

	if(!resManager_->getAtlas()->getSheet(0)->alBitmap())
		NBT_Debug("no sheet bitmap????");
	*/
	//al_draw_bitmap(resManager_->getAtlas()->getSheet(0)->alBitmap(), 0, 0, 0);

	//al_flip_display();
	//sleep(10);

	bool redraw = false;
	bool doUpdateLookPos = false;
	bool cleared = false;
	
	while(1)
	{
		ALLEGRO_EVENT ev;
      al_wait_for_event(queue_, &ev);

      if(ev.type == ALLEGRO_EVENT_TIMER)
		{
         redraw = true;
			//cam_.rx = 1.0;
			float x = 0.0, y = 0.0, z = 0.0;
			float translate_diff = 0.3;
			float ry = 0.0;
			float rotate_diff = 0.04;
			bool changeTranslation = false;
			bool changeRotation = false;

			if(key_state_[ALLEGRO_KEY_W])
			{
				z += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_S])
			{
				z -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_A])
			{
				x += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_D])
			{
				x -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_SPACE])
			{
				y -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_LSHIFT])
			{
				y += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_LEFT])
			{
				ry += rotate_diff;
				changeRotation = true;
			}

			if(key_state_[ALLEGRO_KEY_RIGHT])
			{
				ry -= rotate_diff;
				changeRotation = true;
			}

			if(changeTranslation)
			{
				//camera_pos_.translate(x, y, z);
				al_translate_transform_3d(&camera_transform_, x, y, z);
				doUpdateLookPos = true;
			}

			if(changeRotation)
			{
				al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, ry);
				doUpdateLookPos = true;
			}

			if(doUpdateLookPos)
				updateLookPos();

      }
      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			NBT_Debug("display close");
         break;
      }
      else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			//NBT_Debug("key down");
			//NBT_Debug("pos: %fx%f", -camera_transform_.m[2][0], -camera_transform_.m[2][2]);
			key_state_[ev.keyboard.keycode] = true;

			if (ev.keyboard.keycode == ALLEGRO_KEY_Q)
			{
				break;
			}
			else if(ev.keyboard.keycode == ALLEGRO_KEY_C)
			{
				NBT_Debug("CLEAR CHUNKS");
				glBindVertexArray(vao_);
				for(auto ch: chunkData_)
				{
					delete ch.second;
				}
				glBindVertexArray(0);
				chunkData_.clear();

				glDeleteBuffers(1, &vao_);
				
				cleared = true;
			}
			else if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
			{
				grab_mouse_ = !grab_mouse_;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			//NBT_Debug("pos: %fx%f", -camera_transform_.m[2][0], -camera_transform_.m[2][2]);
			key_state_[ev.keyboard.keycode] = false;
		}
		else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
		{
				grab_mouse_ = true;
		}
		else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES && grab_mouse_)
		{
			float dx = ev.mouse.dx, dy = ev.mouse.dy;

			if(dy > 0 && dy < 1.5)
				dy = 0.0;

			if(dy < 0 && dy > -1.5)
				dy = 0.0;

			if(dx > 0 && dx < 1.5)
				dy = 0.0;

			if(dx < 0 && dx > -1.5)
				dx = 0.0;

			float ry = dx / al_get_display_width(dpy_), rx = dy / al_get_display_height(dpy_);

			rx_look += rx;
			al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, ry);
//			al_rotate_transform_3d(&camera_transform_, 1.0, 0.0, 0.0, rx);

			//cam_.rx += dy / al_get_display_height(dpy_);

			al_set_mouse_xy(dpy_, al_get_display_width(dpy_)/2.0, al_get_display_height(dpy_)/2.0);

			doUpdateLookPos = true;
		}

      if(redraw && al_is_event_queue_empty(queue_))
		{
			if(!loadChunkQueue.empty())
			{
				NBT_Debug("%i chunks to load", loadChunkQueue.size());

				std::pair<int32_t, int32_t> pos = loadChunkQueue.front();
				loadChunkQueue.pop();

				processChunk(pos.first, pos.second);
			}
			else
			{
				if(!cleared)
				{
					//NBT_Debug("pos: %fx%fx%f", camera_pos_.getX(), camera_pos_.getZ(), camera_pos_.getY());
					autoLoadChunks(camera_pos_.getX() / 16.0, camera_pos_.getZ() / 16.0);
				}
			}

			ALLEGRO_STATE state;
			al_store_state(&state, ALLEGRO_STATE_ALL);
			al_set_projection_transform(dpy_, &al_proj_transform_);

			glClear(GL_DEPTH_BUFFER_BIT);

         redraw = false;
			al_clear_to_color(al_map_rgb(255,255,255));
         draw();

			al_restore_state(&state);
			al_set_projection_transform(dpy_, &al_proj_transform_);

			drawHud();

			al_restore_state(&state);
         al_flip_display();
      }


	}

	NBT_Debug("stop timer");
	al_stop_timer(tmr_);

	NBT_Debug("end");


	NBT_Debug("sizeof GL_FLOAT: %i", sizeof(GLfloat));
}
Пример #15
0
void GameManager::start()
{
	do
	{
		//Initializing current activity objects
		initCurrentActObjs();
		
		for (int i = 0; i < 6; i++)
			keys[i] = false;
		
		al_start_timer(timer);

		/* ===============================================
						      GAME LOOP
		   =============================================== */

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

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

				currentActObj->onKeyReleased();
			}
			else if (event.type == ALLEGRO_EVENT_TIMER)
			{
				if (keys[SPACE])
					currentActObj->onKeySpace();
				if(keys[LEFT])
					currentActObj->onKeyLeft();
				if (keys[RIGHT])
					currentActObj->onKeyRight();
				if (keys[UP])
					currentActObj->onKeyUp();
				if (keys[DOWN])
					currentActObj->onKeyDown();
				if (keys[ESCAPE])
					currentActObj->onKeyEscape();

				currentActObj->update();
				
				draw = true;
			}
			if (draw)
				currentActObj->render();
			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
			
		}

		if (!gameDone && actSwitched)
		{
			al_stop_timer(timer);
			delete currentActObj;
		}

	} while (!gameDone);
}
Пример #16
0
int main(int argc, char **argv)

{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *pared2 = NULL;
	ALLEGRO_BITMAP *carretera = NULL;
	ALLEGRO_BITMAP *fondo = NULL;
	ALLEGRO_BITMAP *tierra = NULL;
	ALLEGRO_BITMAP *coche = NULL;
	ALLEGRO_BITMAP *coche2 = NULL;
	ALLEGRO_BITMAP *otros = NULL;
	ALLEGRO_BITMAP *porche1 = NULL;
	ALLEGRO_BITMAP *porche2 = NULL;
	ALLEGRO_BITMAP *porche3 = NULL;
	ALLEGRO_BITMAP *porche4 = NULL;
	ALLEGRO_BITMAP *porche5 = NULL;
	ALLEGRO_BITMAP *porche6 = NULL;
	ALLEGRO_BITMAP *freno = NULL;
	ALLEGRO_BITMAP *ciudad = NULL;
	ALLEGRO_BITMAP *ganas = NULL;
	ALLEGRO_BITMAP *pierdes = NULL;
	ALLEGRO_FONT *font = NULL;
	int i = 3;
	int objetivo = 10000;
	int tiempo = 3600;
	float velocidad = 0;
	float carreteray = 0;
	float carreteray2 = 720;
	float bouncer_x = 360;
	float bouncer_y = (SCREEN_H / 10) * 9;
	int camaraX;
	float carreterax1;
	float carreterax2;
	float angulo = 1.571;
	float velocidadt = -10;
	float veltraficox, veltraficoy;
	float centro = 695;
	float ladoizq = 620;
	float ladoder = 790;
	float frenosi = 3;
	float hasganao = 5000;
	float hasperdio = 5000;
	bool key[5] = { false, false, false, false, false};
	bool redraw = true;
	bool doexit = false;

	struct Trafico trafico1 = {1000, 300, 1000, 5, 1};
	struct Trafico trafico2 = {850, 200, 850, 5 , 2};
	struct Trafico trafico3 = {1170, 0, 1170, 5, 3};
	struct Trafico trafico4 = {1000, 400, 1000, 5, 4};
	struct Trafico trafico5 = {850, 100, 850, 5, 1};
	struct Trafico trafico6 = {1170, 500, 1170, 5, 2};


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

	if (!al_init_image_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

	if (!al_init_primitives_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de primitivos", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

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

	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("djc2.otf", 60, 0);

	pared2 = al_create_bitmap(PARED2_X, PARED2_Y);

	carretera = al_load_bitmap("road22.png");

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

	fondo = al_load_bitmap("cielo2.png");
	tierra = al_load_bitmap("camino4.png");
	coche = al_load_bitmap("outrun2.png");
	otros = al_load_bitmap("outruntrprueba5.png");
	ciudad = al_load_bitmap("ciudad3.png");
	freno = al_load_bitmap("freno.png");

	ganas = al_load_bitmap("youwin.png");
	pierdes = al_load_bitmap("youlose.png");
	
	al_convert_mask_to_alpha(coche, al_map_rgb(186, 254, 202));
	al_convert_mask_to_alpha(otros, al_map_rgb(186, 254, 202));

	
	if (!fondo) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	if (!coche) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	al_set_target_bitmap(pared2);

	al_clear_to_color(al_map_rgb(150, 150, 150));

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

			tiempo -= 1;

			/*Spawn del trafico*/

			srand(time(NULL));
			int distancia = rand() % (950 - 750) + 750;
			int distancia2 = rand() % (950 - 750) + 750;
			int distancia3 = rand() % (950 - 750) + 750;
			int distancia4 = rand() % (1201 - 1050) + 1050;
			int distancia5 = rand() % (1201 - 1050) + 1050;
			int distancia6 = rand() % (1201 - 1050) + 1050;

			/*Teclas, movimiento y cambio de sprites en coche principal*/

			if (key[KEY_UP] && velocidad < 25) {
				velocidad += 0.5;
				velocidadt += 0.5;
			}
			else if (velocidad > 0) {
				velocidad -= 0.1;
				velocidadt -= 0.1;
			}

			if (key[KEY_DOWN]) {
				velocidad -= 0.3;
				velocidadt -= 0.3;
				frenosi = SCREEN_W / 2;
			}
			else{
				frenosi = 3000;
			}

			if (key[KEY_LEFT] && velocidad > 0) {
				bouncer_x -= 4;
				frenosi = frenosi + 3;
			}
			if (key[KEY_LEFT] && i > 1 && velocidad > 0) {
				i -= 1;
			}
			else if (!key[KEY_LEFT] && i < 4) {
				i += 1;
			}

			if (key[KEY_RIGHT] && velocidad > 0) {
				bouncer_x += 4;
				frenosi = frenosi - 3;
			}
			if (key[KEY_RIGHT] && i < 5 && velocidad > 0) {
				i += 1;
			}
			else if (!key[KEY_RIGHT] && i > 3) {
				i -= 1;
			}

			objetivo -= velocidad / 10;

			/*Carretera*/

			carreteray += velocidad;
			carreteray2 += velocidad;

			if (carreteray > 1080) {
				carreteray = carreteray2 - 720;
			}
			if (carreteray2 > 1080) {
				carreteray2 = carreteray -720;
			}
			
			/*Limites de sprite y velocidad segun posición*/

			if (velocidad < 0){
				velocidad = 0;
				i = 3;
			}

			if (bouncer_x < 140 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			if (bouncer_x > 590 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			/*Formulas para velocidad y posicion del trafico*/

			veltraficox = (velocidadt / 5) * cos(angulo);
			veltraficoy = (velocidadt / 5) * sin(angulo);
			trafico1.traficox += veltraficox;
			trafico1.traficoy += veltraficoy;
			trafico2.traficox += veltraficox;
			trafico2.traficoy += veltraficoy - 1;
			trafico3.traficox += veltraficox;
			trafico3.traficoy += veltraficoy - 1;
			trafico4.traficox += veltraficox;
			trafico4.traficoy += veltraficoy;
			trafico5.traficox += veltraficox;
			trafico5.traficoy += veltraficoy - 1;
			trafico6.traficox += veltraficox;
			trafico6.traficoy += veltraficoy - 1;

			/*Reaparicion del trafico.*/

			if (trafico1.traficoy > distancia) {
				trafico1.traficoy = 200;
				trafico1.traficox = trafico1.spawnp;
				trafico1.otrosi = 5;
				trafico1.otrosy = rand() % 4;
			}
			if (trafico2.traficoy > distancia2) {
				trafico2.otrosi = 5;
				trafico2.traficoy = 200;
				trafico2.traficox = trafico2.spawnp;
				trafico2.otrosy = rand() % 4;
			}

			if (trafico3.traficoy > distancia3) {
				trafico3.otrosi = 5;
				trafico3.traficoy = 200;
				trafico3.traficox = trafico3.spawnp;
				trafico3.otrosy = rand() % 4;
			}

			if (trafico4.traficoy > distancia4) {
				trafico4.otrosi = 5;
				trafico4.traficoy = 200;
				trafico4.traficox = trafico4.spawnp;
				trafico4.otrosy = rand() % 4;
			}
			if (trafico5.traficoy > distancia5) {
				trafico5.otrosi = 5;
				trafico5.traficoy = 200;
				trafico5.traficox = trafico5.spawnp;
				trafico5.otrosy = rand() % 4;
			}

			if (trafico6.traficoy > distancia6) {
				trafico6.otrosi = 5;
				trafico6.traficoy = 200;
				trafico6.traficox = trafico6.spawnp;
				trafico6.otrosy = rand() % 4;
			}


			/*Perspectiva - Falso 3D*/

			camaraX = bouncer_x;

			carreterax1 = 650 - (camaraX / 2);
			carreterax2 = 1130 - (camaraX / 2);

			if (carreterax1 < 820 - camaraX){
				carreterax1 = 820 - camaraX;
			}

			if (carreterax1 > 860 - camaraX) {
				carreterax1 = 860 - camaraX;
			}

			if (carreterax2 > 1320 - camaraX) {
				carreterax2 = 1320 - camaraX;
			}

			if (carreterax2 < 1280 - camaraX) {
				carreterax2 = 1280 - camaraX;
			}

			/*Creacion de sprites*/

			coche2 = al_create_sub_bitmap(coche, i * 130, 0, 130, 74);
			porche1 = al_create_sub_bitmap(otros, trafico1.otrosi * 130, trafico1.otrosy * 62, 130, 62);
			porche2 = al_create_sub_bitmap(otros, trafico2.otrosi * 130, trafico2.otrosy * 62, 130, 62);
			porche3 = al_create_sub_bitmap(otros, trafico3.otrosi * 130, trafico3.otrosy * 62, 130, 62);
			porche4 = al_create_sub_bitmap(otros, trafico4.otrosi * 130, trafico4.otrosy * 62, 130, 62);
			porche5 = al_create_sub_bitmap(otros, trafico5.otrosi * 130, trafico5.otrosy * 62, 130, 62);
			porche6 = al_create_sub_bitmap(otros, trafico6.otrosi * 130, trafico6.otrosy * 62, 130, 62);

			/*Cambio de sprites en Trafico*/

			/*porche1*/
			if (trafico1.traficoy > 370) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 5;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 6;
				}
			}

			if (trafico1.traficoy > 420){
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 4;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 7;
				}
			}

			if (trafico1.traficoy > 470) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 3;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 8;
				}
			}

			if (trafico1.traficoy > 520) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 2;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 9;
				}
			}

			if (trafico1.traficoy > 570) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 1;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 10;
				}

			}
			if (trafico1.traficoy > 620) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 0;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 11;
				}

			}

			/*porche2*/
			if (trafico2.traficoy > 370) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 5;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 6;
				}
			}

			if (trafico2.traficoy > 420) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 4;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 7;
				}
			}

			if (trafico2.traficoy > 470) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 3;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 8;
				}
			}

			if (trafico2.traficoy > 520) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 2;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 9;
				}
			}

			if (trafico2.traficoy > 570) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 1;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 10;
				}

			}
			if (trafico2.traficoy > 620) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 0;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 11;
				}

			}

			/*porche3*/
			if (trafico3.traficoy > 370) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 5;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 6;
				}
			}

			if (trafico3.traficoy > 420) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 4;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 7;
				}
			}

			if (trafico3.traficoy > 470) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 3;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 8;
				}
			}

			if (trafico3.traficoy > 520) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 2;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 9;
				}
			}

			if (trafico3.traficoy > 570) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 1;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 10;
				}

			}
			if (trafico3.traficoy > 620) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 0;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 11;
				}

			}

			/*porche4*/
			if (trafico4.traficoy > 370) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 5;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 6;
				}
			}

			if (trafico4.traficoy > 420) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 4;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 7;
				}
			}

			if (trafico4.traficoy > 470) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 3;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 8;
				}
			}

			if (trafico4.traficoy > 520) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 2;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 9;
				}
			}

			if (trafico4.traficoy > 570) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 1;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 10;
				}

			}
			if (trafico4.traficoy > 620) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 0;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 11;
				}

			}

			/*porche5*/
			if (trafico5.traficoy > 370) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 5;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 6;
				}
			}

			if (trafico5.traficoy > 420) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 4;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 7;
				}
			}

			if (trafico5.traficoy > 470) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 3;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 8;
				}
			}

			if (trafico5.traficoy > 520) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 2;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 9;
				}
			}

			if (trafico5.traficoy > 570) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 1;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 10;
				}

			}
			if (trafico5.traficoy > 620) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 0;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 11;
				}

			}

			/*porche6*/
			if (trafico6.traficoy > 370) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 5;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 6;
				}
			}

			if (trafico6.traficoy > 420) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 4;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 7;
				}
			}

			if (trafico6.traficoy > 470) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 3;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 8;
				}
			}

			if (trafico6.traficoy > 520) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 2;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 9;
				}
			}

			if (trafico6.traficoy > 570) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 1;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 10;
				}

			}
			if (trafico6.traficoy > 620) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 0;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 11;
				}

			}

			/*Colisiones*/

			if (ladoizq < trafico1.traficox + 65 - camaraX && trafico1.traficox + 65 - camaraX < ladoder && bouncer_y < trafico1.traficoy && trafico1.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			if (ladoizq < trafico2.traficox + 65 - camaraX && trafico2.traficox + 65 - camaraX < ladoder && bouncer_y < trafico2.traficoy && trafico2.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico3.traficox + 65 - camaraX && trafico3.traficox + 65 - camaraX < ladoder && bouncer_y < trafico3.traficoy && trafico3.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico4.traficox + 65 - camaraX && trafico4.traficox + 65 - camaraX < ladoder && bouncer_y < trafico4.traficoy && trafico4.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico5.traficox + 65 - camaraX && trafico5.traficox + 65 - camaraX < ladoder && bouncer_y < trafico5.traficoy && trafico5.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico6.traficox + 65 - camaraX && trafico6.traficox + 65 - camaraX < ladoder && bouncer_y < trafico6.traficoy && trafico6.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			/*Funcionamiento de la Camara*/

			if (camaraX > mundoAncho - SCREEN_W) {
				camaraX = mundoAncho - SCREEN_W;
			}

			if (camaraX < 0) {
				camaraX = 0;
			}

			if (bouncer_x > mundoAncho - SCREEN_W) {
				bouncer_x = mundoAncho - SCREEN_W;
			}

			if (bouncer_x < 0) {
				bouncer_x = 0;
			}

			/*Fin de partida*/

			if (tiempo < 0 & objetivo > 0){
				al_stop_timer(timer);
				hasperdio = 292.5;
			}

			if (objetivo < 0 & tiempo > 0) {
				al_stop_timer(timer);
				hasganao = 292.5;
			}

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

			al_draw_bitmap(carretera, 640 - camaraX, carreteray, 0);
			al_draw_bitmap(carretera, 640 - camaraX, carreteray2, 0);

			al_draw_bitmap(tierra, 640 - camaraX, 0, 0);

			al_draw_filled_triangle(820 - camaraX, 720, 775 - camaraX, 400, carreterax1, 400, al_map_rgb(0, 0, 0));
			al_draw_filled_triangle(1320 - camaraX, 720, 1365 - camaraX, 400, carreterax2, 400, al_map_rgb(0, 0, 0));

			al_draw_line(820 - camaraX, 720, carreterax1, 400, al_map_rgb(0, 255, 255), 6);
			al_draw_line(1320 - camaraX, 720, carreterax2, 400, al_map_rgb(0, 255, 255), 6);

			al_draw_line(640 - camaraX, 425, carreterax1 - 4, 425, al_map_rgb(0, 255, 255), 10);
			al_draw_line(1485 - camaraX, 425, carreterax2 + 4, 425, al_map_rgb(0, 255, 255), 10);

			al_draw_bitmap(porche1, trafico1.traficox - camaraX, trafico1.traficoy, 0);
			al_draw_bitmap(porche2, trafico2.traficox - camaraX, trafico2.traficoy, 0);
			al_draw_bitmap(porche3, trafico3.traficox - camaraX, trafico3.traficoy, 0);
			al_draw_bitmap(porche4, trafico4.traficox - camaraX, trafico4.traficoy, 0);
			al_draw_bitmap(porche5, trafico5.traficox - camaraX, trafico5.traficoy, 0);
			al_draw_bitmap(porche6, trafico6.traficox - camaraX, trafico6.traficoy, 0);

			al_draw_bitmap(fondo, 640 - camaraX, 5, 0);

			al_draw_bitmap(ciudad, 640 - camaraX, 65, 0);

			al_draw_bitmap(pared2, 1485 - camaraX, 0, 0);
			al_draw_bitmap(pared2, 630 - camaraX, 0, 0);

			al_draw_bitmap(coche2, SCREEN_W / 2, bouncer_y - 10, 0);
			al_draw_bitmap(freno, frenosi, bouncer_y - 10, 0);

			al_draw_textf(font, al_map_rgb(255, 0, 0), SCREEN_W / 2 + 200, 50, 0, "%i", objetivo / 2);
			al_draw_textf(font, al_map_rgb(0, 255, 255), SCREEN_W / 2, 50, 0, "%i", tiempo / 60);

			al_draw_bitmap(ganas, hasganao, 200, 0);
			al_draw_bitmap(pierdes, hasperdio, 200, 0);

			al_flip_display();
		}
	}

	al_destroy_bitmap(fondo);
	al_destroy_bitmap(coche);
	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);

	return 0;
}
Пример #17
0
Файл: main.c Проект: dos1/bttbw
int main(int argc, char **argv){
	signal(SIGSEGV, derp);

	srand(time(NULL));

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

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

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

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

	struct Game game;

	InitConfig(&game);

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

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

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

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

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

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

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

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

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

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

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

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

	SetupViewport(&game);

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

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

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

	al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR);

	game._priv.gamestates = NULL;

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

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

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

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

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

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

	setlocale(LC_NUMERIC, "C");

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

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

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

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

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

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

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

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

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

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

	bool redraw = false;

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

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

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

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

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

			double t = -1;

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

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

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

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

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

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

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

						int p = 0;

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

						t = al_get_time();

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

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

				tmp=tmp->next;
			}

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

			while (tmp) {

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

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

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

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

		} else {
Пример #18
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;


}