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

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

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

   al_hide_mouse_cursor();

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

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

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

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

         case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            down = true;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            down = false;
            break;

         case ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY:
            in = true;
            break;

         case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
            in = false;
            break;

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

done:

   al_destroy_event_queue(queue);

   return 0;
}
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;
}
Exemple #3
0
//MAIN//
int main(int argc, char **argv)
{
    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_BITMAP  *image   = NULL, *image1  = NULL, *image2  = NULL, *image3  = NULL;
    ALLEGRO_FONT *font1 = NULL, *font2 = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    if(!al_init())
    {
        return -1;
    }
    if(!al_install_keyboard())
    {
        return -1;
    }
    if(!al_install_mouse())
    {
        return -1;
    }
    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display)
    {
        return -1;
    }
    event_queue = al_create_event_queue();
    if(!event_queue)
    {
        return -1;
    }
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_mouse_event_source());
    al_init_primitives_addon();
    al_init_font_addon();
    al_init_ttf_addon();
    if(!al_init_image_addon())
    {
	printf("Problema com inicialização image_addon");
        return -1;
    }
    font1 = al_load_ttf_font("pirulen.ttf",12,0 );
    if (!font1)
    {
	printf("Problema ao carregar pirulen.ttf");
        return -1;
    }
    image = al_load_bitmap("iceblue2.png");
    if(!image)
    {
	printf("Problema ao carregar iceblue2.png");
        return -1;
    }
    image1 = al_load_bitmap("IceBlue1.png");
    if(!image1)
    {
	printf("Problema ao carregar IceBlue1.png");
        return -1;
    }
    image2 = al_load_bitmap("NG.png");
    if(!image2)
    {
	printf("Problema ao carregar NG.png");
        return -1;
    }
    image3 = al_load_bitmap("retanrosa.png");
    if(!image3)
    {
	printf("Problema ao carregar retanrosa.png");
        return -1;
    }
    al_draw_bitmap(image,0,0,0);
    al_draw_bitmap(image1,10,10,10);
    al_draw_bitmap(image2,180,45,15);
    al_draw_bitmap(image3,310,45,15);
//FUNÇÃO GERA RETANGULO//
    x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240;
    x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini;
    for(qc=0; qc<5; qc++)
    {
        for (ql=0; ql<5; ql++)
        {
            al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193));
            y1=y1+80;
            y2=y2+80;
        }
        y1=y1_ini;
        y2=y2_ini;
        x1=x1+80;
        x2=x2+80;
    }
    font2 = al_load_ttf_font("pirulen.ttf",23,0 );
    if (!font2)
    {
        return -1;
    }
    al_flip_display();
//LOGICA//
    while(!doexit)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);
        if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                for (coluna=0; coluna<5; coluna++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (linha=4; linha>=1; linha--)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha-1][coluna]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha-1][coluna];
                                matriz[linha-1][coluna]=nt;
                            }
                        }
                    }
                }
                for (coluna=0; coluna<5; coluna++)
                {
                    for (linha=0; linha<4; linha++)
                    {
                        if ((matriz[linha][coluna]==matriz[linha+1][coluna])&&(matriz[linha][coluna]!=0))
                        {
                            matriz[linha+1][coluna]+=matriz[linha][coluna];
                            matriz[linha][coluna]=0;
                            linha++;
                        }
                    }
                }
                for (coluna=0; coluna<5; coluna++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (linha=4; linha>=1; linha--)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha-1][coluna]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha-1][coluna];
                                matriz[linha-1][coluna]=nt;
                            }
                        }
                    }
                }
                break;
            case ALLEGRO_KEY_DOWN:
                for (coluna=0; coluna<5; coluna++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (linha=0; linha<4; linha++)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha+1][coluna]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha+1][coluna];
                                matriz[linha+1][coluna]=nt;
                            }
                        }
                    }
                }
                for (coluna=0; coluna<5; coluna++)
                {
                    for (linha=4; linha>=1; linha--)
                    {
                        if ((matriz[linha][coluna]==matriz[linha-1][coluna])&&(matriz[linha][coluna]!=0))
                        {
                            matriz[linha][coluna]+=matriz[linha-1][coluna];
                            matriz[linha-1][coluna]=0;
                            linha--;
                        }
                    }
                }
                for (coluna=0; coluna<5; coluna++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (linha=0; linha<4; linha++)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha+1][coluna]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha+1][coluna];
                                matriz[linha+1][coluna]=nt;
                            }
                        }
                    }
                }
                break;
            case ALLEGRO_KEY_LEFT:
                for (linha=0; linha<5; linha++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (coluna=4; coluna>=1; coluna--)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna-1]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha][coluna-1];
                                matriz[linha][coluna-1]=nt;
                            }
                        }
                    }
                }
                for (linha=0; linha<5; linha++)
                {
                    for (coluna=0; coluna<4; coluna++)
                    {
                        if ((matriz[linha][coluna]==matriz[linha][coluna+1])&&(matriz[linha][coluna]!=0))
                        {
                            matriz[linha][coluna+1]+=matriz[linha][coluna];
                            matriz[linha][coluna]=0;
                            coluna++;
                        }
                    }
                }
                for (linha=0; linha<5; linha++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (coluna=4; coluna>=1; coluna--)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna-1]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha][coluna-1];
                                matriz[linha][coluna-1]=nt;
                            }
                        }
                    }
                }
                break;
            case ALLEGRO_KEY_RIGHT:
                for (linha=0; linha<5; linha++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (coluna=0; coluna<4; coluna++)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna+1]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha][coluna+1];
                                matriz[linha][coluna+1]=nt;
                            }
                        }
                    }
                }
                for (linha=0; linha<5; linha++)
                {
                    for (coluna=4; coluna>=1; coluna--)
                    {
                        if ((matriz[linha][coluna]==matriz[linha][coluna-1])&&(matriz[linha][coluna]!=0))
                        {
                            matriz[linha][coluna-1]+=matriz[linha][coluna];
                            matriz[linha][coluna]=0;
                            coluna--;
                        }
                    }
                }
                for (linha=0; linha<5; linha++)
                {
                    for (i=3; i>=0; i--)
                    {
                        for (coluna=0; coluna<4; coluna++)
                        {
                            if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna+1]==0))
                            {
                                nt=matriz[linha][coluna];
                                matriz[linha][coluna]=matriz[linha][coluna+1];
                                matriz[linha][coluna+1]=nt;
                            }
                        }
                    }
                }
                break;
            case ALLEGRO_KEY_ESCAPE:
                doexit = true;
                break;
            }
//GERADOR RANDOM//
            random(&rcoluna,&rlinha);
            while (matriz[rlinha][rcoluna]!=0)
            {
                random(&rcoluna,&rlinha);
            }
            matriz[rlinha][rcoluna]=  (rand()%4 == 3)? 4 : 2;

            for (linha=0; linha<=4; linha++)
            {
                for (coluna=0; coluna<=4; coluna++)
                {
                    if (matriz[linha][coluna]!=0)
                        i++;
                }
            }
            if (i==25)
                break;
//SCORE//
            al_draw_bitmap(image3,310,45,15);
            score=0;
            for(qc=0; qc<5; qc++)
            {
                for (ql=0; ql<5; ql++)
                {
                    score+=matriz[ql][qc];
                }
            }
            al_draw_textf(font1, al_map_rgb(255,255,255),365,68,ALLEGRO_ALIGN_CENTRE,"%i",score);
        }
//FUNÇÃO GERA RETANGULO//
        x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240;
        x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini;
        for(qc=0; qc<5; qc++)
        {
            for (ql=0; ql<5; ql++)
            {
                if(matriz[ql][qc]==0)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193));
                }
                else if(matriz[ql][qc]==2)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 182, 151));
                }
                else if(matriz[ql][qc]==4)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 141, 132));
                }
                else if(matriz[ql][qc]==8)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 100));
                }
                else if(matriz[ql][qc]==16)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 128, 1));
                }
                else if(matriz[ql][qc]==32)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 128));
                }
                else if(matriz[ql][qc]==64)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 30));
                }
                else if(matriz[ql][qc]==128)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(108, 128, 255));
                }
                else if(matriz[ql][qc]==256)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(108, 188, 255));
                }
                else if(matriz[ql][qc]==512)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(15, 203, 80));
                }
                else if(matriz[ql][qc]==1024)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(140, 255, 198));
                }
                else if(matriz[ql][qc]==2048)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 255, 26));
                }
                else if(matriz[ql][qc]==4069)
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 0));
                }
                else
                {
                    al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 225, 255));
                }
                y1=y1+80;
                y2=y2+80;
            }
            y1=y1_ini;
            y2=y2_ini;
            x1=x1+80;
            x2=x2+80;
        }
//FUNÇÃO GERA MATRIZ//
        text2x_ini=64, text2y_ini=192;
        text2x=text2x_ini, text2y=text2y_ini;
        for(qc=0; qc<5; qc++)
        {
            for (ql=0; ql<5; ql++)
            {
                if (matriz[ql][qc]==0)
                {
                    c1=255, c2=211, c3=193;
                }
                else
                {
                    c1=255, c2=255, c3=255;
                }
                al_draw_textf(font2, al_map_rgb(c1,c2,c3),text2x,text2y,ALLEGRO_ALIGN_CENTRE, "%i",matriz[ql][qc]);
                text2y=text2y+80;
            }

            text2y=text2y_ini;
            text2x=text2x+80;
            al_flip_display();
        }
//MOUSE EVENT//
        if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
        {
            if(ev.mouse.x >= al_get_bitmap_width(image2) &&
                    ev.mouse.x <= SCREEN_W -10 && ev.mouse.y <= SCREEN_H - 10 &&
                    ev.mouse.y >= al_get_bitmap_height(image2) - 10)
            {
                al_draw_bitmap(image3,310,45,15);
                score=0;
                text2x_ini=64, text2y_ini=192;
                text2x=text2x_ini, text2y=text2y_ini;

                for(qc=0; qc<5; qc++)
                {
                    for (ql=0; ql<5; ql++)
                    {
                        c1=255, c2=211, c3=193;
                        matriz[ql][qc]=0;
                        al_draw_textf(font2, al_map_rgb(c1,c2,c3),text2x,text2y,ALLEGRO_ALIGN_CENTRE, "%i",matriz[ql][qc]);
                        text2y=text2y+80;
                    }
                    text2y=text2y_ini;
                    text2x=text2x+80;
                }

                x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240;
                x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini;
                for(qc=0; qc<5; qc++)
                {
                    for (ql=0; ql<5; ql++)
                    {
                        al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193));
                        y1=y1+80;
                        y2=y2+80;
                    }
                    y1=y1_ini;
                    y2=y2_ini;
                    x1=x1+80;
                    x2=x2+80;
                }
                al_flip_display();
            }
        }
    }
    system("cls");
    printf("GAME OVER!");
    al_destroy_event_queue(event_queue);
    al_destroy_display(display);
    return 0;
}
Exemple #4
0
int main(int argc, char *argv[])
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_FONT *font;

   (void)argc;
   (void)argv;

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

   al_init_font_addon();
   al_init_image_addon();

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

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

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

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

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

   al_destroy_font(font);

   return 0;
}
int main(void)
{
	bool done = false;
	int curFrame = 0;
	int frameCount = 0;
	int frameDelay = 5;
	const int maxFrame = 8;
	
	//Initialisers
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *bouncer = NULL;
	ALLEGRO_BITMAP *image[maxFrame];

	if (!al_init())											//initialize and check Allegro
	{
		fprintf(stderr, "failed to initialize allegro!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	display = al_create_display(scrn_W, scrn_H);			//create our display object
	if (!display)											//Check display
	{
		fprintf(stderr, "failed to create display!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE);		//create box limit
	if (!bouncer) {												//Check creation of box limit
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	timer = al_create_timer(1.0 / FPS);							//Create Timer
	if (!timer)													//Check timer creation
	{
		fprintf(stderr, "failed to create timer!\n");
		al_destroy_bitmap(bouncer);
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

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

	al_init_primitives_addon();
	al_install_keyboard();
	al_install_mouse();
	
	al_init_image_addon();
	//Init bitmap
	image[0] = al_load_bitmap("./images/dragon/fliegt e0000.bmp");
	image[1] = al_load_bitmap("./images/dragon/fliegt e0001.bmp");
	image[2] = al_load_bitmap("./images/dragon/fliegt e0002.bmp");
	image[3] = al_load_bitmap("./images/dragon/fliegt e0003.bmp");
	image[4] = al_load_bitmap("./images/dragon/fliegt e0004.bmp");
	image[5] = al_load_bitmap("./images/dragon/fliegt e0005.bmp");
	image[6] = al_load_bitmap("./images/dragon/fliegt e0006.bmp");
	image[7] = al_load_bitmap("./images/dragon/fliegt e0007.bmp");
	
	for (int i = 0; i < maxFrame; i++)
	{
		al_convert_mask_to_alpha(image[i], al_map_rgb(106, 76, 48));
	}

	//end bitmap

	//Event queue - register listeners
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_display_event_source(display));
	//end event queue

	//Colours
	black = al_map_rgb(0, 0, 0);
	white = al_map_rgb(255, 255, 255);
	red = al_map_rgb(255, 0, 0);
	green = al_map_rgb(0, 255, 0);
	blue = al_map_rgb(0, 0, 255);
	//End Colours

	al_start_timer(timer);


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

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

				break;
			case ALLEGRO_KEY_RIGHT:

				break;
			case ALLEGRO_KEY_UP:

				break;
			case ALLEGRO_KEY_DOWN:

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

		al_draw_bitmap(image[curFrame], 200, 100, 0);


		al_flip_display();
		al_clear_to_color(black);
	}


	//Destruction
	
	for (int i = 0; i < maxFrame; i++)
	{
		al_destroy_bitmap(image[i]);
	}
	al_destroy_bitmap(bouncer);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
	al_destroy_timer(timer);
	//end Distruction

	return 0;
}
Exemple #6
0
int engine_init(struct Engine_Conf *conf)
{
  if (engine.initialized)
    {
      return 1;
    }

  // Initialize Allegro and stuff
  al_init();

  if (!al_install_keyboard())
    {
      puts("engine_init(): Failed to initialize the keyboard...");
      return 0;
    }

  if (!al_install_mouse())
    {
      puts("engine_init(): Failed to initialize the mouse...");
      return 0;
    }

  if (al_install_audio())
    {
      if (!al_init_acodec_addon())
        {
          puts("engine_init(): Failed to initialize codecs...");
        }

      al_reserve_samples(1);
    }
  else
    {
      puts("engine_init(): Failed to initialize audio...");
    }

  // Add-ons
  if (!al_init_image_addon())
    {
      puts("engine_init(): Failed to initialize image addon...");
      return 0;
    }

  al_init_font_addon();
  al_init_primitives_addon();

  if (conf->fullscreen)
    {
      al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
    }

  // Initialize variables...
  engine.display = al_create_display(conf->width, conf->height);

  if (!engine.display)
    {
      puts("engine_init(): Failed to create a display window...");
      return 0;
    }

  al_set_window_title(engine.display, conf->title);

  MAINCONF = conf;
  aspect_ratio_transform();

  al_add_new_bitmap_flag(ALLEGRO_MAG_LINEAR);

  if (conf->buffer)
    {
      engine.buffer = al_create_bitmap(conf->width, conf->height);
      al_set_new_bitmap_flags(0);
    }

  font = al_create_builtin_font();

  engine.timer = al_create_timer(1.0 / conf->framerate);
  engine.event_queue = al_create_event_queue();

  engine.sm.change_state = change_state;
  engine.sm.push_state = push_state;
  engine.sm.pop_state = pop_state;

  set_bg_color(al_map_rgb(192, 192, 192));

  srand(time(NULL));

  engine.initialized = TRUE;

  return 1;
}
Exemple #7
0
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   int redraw = 0, i;
   bool quit = false;

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

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

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

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

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

   timer = al_create_timer(1.0 / 60);

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

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

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

         render();

         al_flip_display();
      }
   }

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

   return 0;
}
bool GameLogic::InitializeAllegro() {
	if(!al_init()) {
        fprintf(stderr, "Failed to initialize allegro!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Allegro 5 initialized.\n"); }

	if(!al_install_keyboard()) {
      fprintf(stderr, "Failed to initialize the keyboard!\n");
      return false;
    }
    if(Debug) { fprintf(stderr, "Keyboard initialized.\n"); }

    if(!al_install_mouse()) {
        fprintf(stderr, "Failed to initialize the mouse!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Mouse initialized.\n"); }

    Timer = al_create_timer(TimerStep);
    if(!Timer) {
        fprintf(stderr, "Failed to create Timer!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Timer initialized.\n"); }

    if(!al_init_image_addon()) {
        fprintf(stderr, "Failed to initialize images loading!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Image loading initialized.\n"); }

	if(!al_init_primitives_addon()) {
        fprintf(stderr, "Failed to initialize primitives!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Primitives addon initialized.\n"); }

    al_init_font_addon();
	
    if(!al_init_ttf_addon()) {
        fprintf(stderr, "Failed to initialize TrueType!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "TTF font loading initialized.\n"); }
    
    if(!al_install_audio()) {
        fprintf(stderr, "Failed to initialize audio!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Audio initialized.\n"); }

    if(!al_init_acodec_addon()) {
        fprintf(stderr, "Failed to initialize audio codecs!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Ogg/FLAC initialized.\n"); }

    // create and confirm allegro Display
    Display = al_create_display(DisplayWidth, DisplayHeight);
    if(!Display) {
        fprintf(stderr, "Failed to create Display!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Display initialized.\n"); }

    // Make sure we are on the backbuffer
    al_set_target_bitmap(al_get_backbuffer(Display));
    
    Voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
    if (!Voice) {
        fprintf(stderr, "Could not create ALLEGRO_VOICE.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Voice created.\n"); }

    Mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,ALLEGRO_CHANNEL_CONF_2);
    if (!Mixer) {
        fprintf(stderr, "Could not create ALLEGRO_MIXER.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Mixer created.\n"); }

    if (!al_attach_mixer_to_voice(Mixer, Voice)) {
        fprintf(stderr, "Attaching Mixer to Voice failed.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Mixer attached to Voice.\n"); }
    
    // create and confirm event queue
    EventQueue = al_create_event_queue();
    if(!EventQueue) {
        fprintf(stderr, "Failed to create EventQueue!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Event queue created successfully.\n"); }

    al_register_event_source(EventQueue, al_get_display_event_source(Display));
    al_register_event_source(EventQueue, al_get_timer_event_source(Timer));
    al_register_event_source(EventQueue, al_get_mouse_event_source());
    al_register_event_source(EventQueue, al_get_keyboard_event_source());

    // blank the Display
    al_clear_to_color(al_map_rgb(0,0,0));
    al_flip_display();

	// actually start our Timer
    al_start_timer(Timer);

	return true;
}
Exemple #9
0
VALUE rbal_mouse_init(VALUE rself) {
  return RBH_INT_BOOL(al_install_mouse());
}
bool input::initInput() {
	sCBKeyMap[0] = 0;
	sCBKeyMap[1] = ALLEGRO_KEY_ESCAPE;
	sCBKeyMap[2] = ALLEGRO_KEY_1;
	sCBKeyMap[3] = ALLEGRO_KEY_2;
	sCBKeyMap[4] = ALLEGRO_KEY_3;
	sCBKeyMap[5] = ALLEGRO_KEY_4;
	sCBKeyMap[6] = ALLEGRO_KEY_5;
	sCBKeyMap[7] = ALLEGRO_KEY_6;
	sCBKeyMap[8] = ALLEGRO_KEY_7;
	sCBKeyMap[9] = ALLEGRO_KEY_8;
	sCBKeyMap[10] = ALLEGRO_KEY_9;
	sCBKeyMap[11] = ALLEGRO_KEY_0;
	sCBKeyMap[12] = ALLEGRO_KEY_EQUALS;
	sCBKeyMap[13] = ALLEGRO_KEY_OPENBRACE;
	sCBKeyMap[14] = ALLEGRO_KEY_BACKSPACE;
	sCBKeyMap[15] = ALLEGRO_KEY_TAB;
	sCBKeyMap[16] = ALLEGRO_KEY_Q;
	sCBKeyMap[17] = ALLEGRO_KEY_W;
	sCBKeyMap[18] = ALLEGRO_KEY_E;
	sCBKeyMap[19] = ALLEGRO_KEY_R;
	sCBKeyMap[20] = ALLEGRO_KEY_T;
	sCBKeyMap[21] = ALLEGRO_KEY_Y;
	sCBKeyMap[22] = ALLEGRO_KEY_U;
	sCBKeyMap[23] = ALLEGRO_KEY_I;
	sCBKeyMap[24] = ALLEGRO_KEY_O;
	sCBKeyMap[25] = ALLEGRO_KEY_P;
	sCBKeyMap[26] = ALLEGRO_KEY_CLOSEBRACE;
	sCBKeyMap[27] = ALLEGRO_KEY_SEMICOLON;
	sCBKeyMap[28] = ALLEGRO_KEY_ENTER;
	sCBKeyMap[29] = ALLEGRO_KEY_LCTRL;
	sCBKeyMap[30] = ALLEGRO_KEY_A;
	sCBKeyMap[31] = ALLEGRO_KEY_S;
	sCBKeyMap[32] = ALLEGRO_KEY_D;
	sCBKeyMap[33] = ALLEGRO_KEY_F;
	sCBKeyMap[34] = ALLEGRO_KEY_G;
	sCBKeyMap[35] = ALLEGRO_KEY_H;
	sCBKeyMap[36] = ALLEGRO_KEY_J;
	sCBKeyMap[37] = ALLEGRO_KEY_K;
	sCBKeyMap[38] = ALLEGRO_KEY_L;
	sCBKeyMap[39] = ALLEGRO_KEY_TILDE;
	sCBKeyMap[40] = ALLEGRO_KEY_QUOTE;
	sCBKeyMap[41] = ALLEGRO_KEY_BACKSLASH;
	sCBKeyMap[42] = ALLEGRO_KEY_LSHIFT;
	sCBKeyMap[43] = ALLEGRO_KEY_SLASH;
	sCBKeyMap[44] = ALLEGRO_KEY_Z;
	sCBKeyMap[45] = ALLEGRO_KEY_X;
	sCBKeyMap[46] = ALLEGRO_KEY_C;
	sCBKeyMap[47] = ALLEGRO_KEY_V;
	sCBKeyMap[48] = ALLEGRO_KEY_B;
	sCBKeyMap[49] = ALLEGRO_KEY_N;
	sCBKeyMap[50] = ALLEGRO_KEY_M;
	sCBKeyMap[51] = ALLEGRO_KEY_COMMA;
	sCBKeyMap[52] = ALLEGRO_KEY_FULLSTOP;
	sCBKeyMap[53] = ALLEGRO_KEY_MINUS;
	sCBKeyMap[54] = ALLEGRO_KEY_RSHIFT;
	sCBKeyMap[55] = ALLEGRO_KEY_PAD_ASTERISK;
	sCBKeyMap[56] = ALLEGRO_KEY_ALT;
	sCBKeyMap[57] = ALLEGRO_KEY_SPACE;
	sCBKeyMap[58] = ALLEGRO_KEY_CAPSLOCK;
	sCBKeyMap[59] = ALLEGRO_KEY_F1;
	sCBKeyMap[60] = ALLEGRO_KEY_F2;
	sCBKeyMap[61] = ALLEGRO_KEY_F3;
	sCBKeyMap[62] = ALLEGRO_KEY_F4;
	sCBKeyMap[63] = ALLEGRO_KEY_F5;
	sCBKeyMap[64] = ALLEGRO_KEY_F6;
	sCBKeyMap[65] = ALLEGRO_KEY_F7;
	sCBKeyMap[66] = ALLEGRO_KEY_F8;
	sCBKeyMap[67] = ALLEGRO_KEY_F9;
	sCBKeyMap[68] = ALLEGRO_KEY_F10;
	sCBKeyMap[69] = ALLEGRO_KEY_PAUSE;
	sCBKeyMap[70] = ALLEGRO_KEY_SCROLLLOCK;
	sCBKeyMap[71] = ALLEGRO_KEY_PAD_7;
	sCBKeyMap[72] = ALLEGRO_KEY_PAD_8;
	sCBKeyMap[73] = ALLEGRO_KEY_PAD_9;
	sCBKeyMap[74] = ALLEGRO_KEY_PAD_MINUS;
	sCBKeyMap[75] = ALLEGRO_KEY_PAD_4;
	sCBKeyMap[76] = ALLEGRO_KEY_PAD_5;
	sCBKeyMap[77] = ALLEGRO_KEY_PAD_6;
	sCBKeyMap[78] = ALLEGRO_KEY_PAD_PLUS;
	sCBKeyMap[79] = ALLEGRO_KEY_PAD_1;
	sCBKeyMap[80] = ALLEGRO_KEY_PAD_2;
	sCBKeyMap[81] = ALLEGRO_KEY_PAD_3;
	sCBKeyMap[82] = ALLEGRO_KEY_PAD_0;
	sCBKeyMap[83] = ALLEGRO_KEY_PAD_DELETE;
	sCBKeyMap[86] = ALLEGRO_KEY_BACKSLASH2;
	sCBKeyMap[87] = ALLEGRO_KEY_F11;
	sCBKeyMap[88] = ALLEGRO_KEY_F12;
	sCBKeyMap[156] = ALLEGRO_KEY_PAD_ENTER;
	sCBKeyMap[157] = ALLEGRO_KEY_RCTRL;
	sCBKeyMap[181] = ALLEGRO_KEY_PAD_SLASH;
	sCBKeyMap[183] = ALLEGRO_KEY_PRINTSCREEN;
	sCBKeyMap[184] = ALLEGRO_KEY_ALTGR;
	sCBKeyMap[197] = ALLEGRO_KEY_NUMLOCK;
	sCBKeyMap[199] = ALLEGRO_KEY_HOME;
	sCBKeyMap[200] = ALLEGRO_KEY_UP;
	sCBKeyMap[201] = ALLEGRO_KEY_PGUP;
	sCBKeyMap[203] = ALLEGRO_KEY_LEFT;
	sCBKeyMap[205] = ALLEGRO_KEY_RIGHT;
	sCBKeyMap[207] = ALLEGRO_KEY_END;
	sCBKeyMap[208] = ALLEGRO_KEY_DOWN;
	sCBKeyMap[209] = ALLEGRO_KEY_PGDN;
	sCBKeyMap[210] = ALLEGRO_KEY_INSERT;
	sCBKeyMap[211] = ALLEGRO_KEY_DELETE;
	sCBKeyMap[219] = ALLEGRO_KEY_LWIN;
	sCBKeyMap[220] = ALLEGRO_KEY_RWIN;
	sCBKeyMap[221] = ALLEGRO_KEY_MENU;
	if (!(al_install_keyboard() && al_install_mouse())) return false;
	al_register_event_source(Window::instance()->eventQueue(), al_get_keyboard_event_source());
	al_register_event_source(Window::instance()->eventQueue(), al_get_mouse_event_source());
	return true;
}
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP* bkg;
   ALLEGRO_COLOR black;
   ALLEGRO_EVENT_QUEUE *queue;

   // Initialize Allegro 5 and addons
   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   al_init_image_addon();
   al_init_font_addon();
   al_init_primitives_addon();
   
   // Create a window to display things on: 640x480 pixels
   display = al_create_display(ScreenW, ScreenH);
   if (!display) {
      abort_example("Error creating display.\n");
      return 1;
   }
   
   // Install the keyboard handler
   if (!al_install_keyboard()) {
      abort_example("Error installing keyboard.\n");
      return 1;
   }

   if (!al_install_mouse()) {
      abort_example("Error installing mouse.\n");
      return 1;
   }
   
   // Load a font
   Font = al_load_font("data/fixed_font.tga", 0, 0);
   if (!Font) {
      abort_example("Error loading \"data/fixed_font.tga\".\n");
      return 1;
   }
   
   solid_white = al_map_rgba_f(1, 1, 1, 1);
   
   bkg = al_load_bitmap("data/bkg.png");

   Texture = al_load_bitmap("data/texture.tga");
   
   // Make and set some color to draw with
   black = al_map_rgba_f(0.0, 0.0, 0.0, 1.0);
   
   // Start the event queue to handle keyboard input and our timer
   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));
   al_register_event_source(queue, al_get_mouse_event_source());
   
   al_set_window_title(display, "Primitives Example");
   
   {
   int refresh_rate = 60;
   int frames_done = 0;
   double time_diff = al_get_time();
   double fixed_timestep = 1.0f / refresh_rate;
   double real_time = al_get_time();
   double game_time = al_get_time();
   int ii;
   int cur_screen = 0;
   bool done = false;
   int clip = 0;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *timer_queue;
   int old;

   timer = al_create_timer(ALLEGRO_BPS_TO_SECS(refresh_rate));
   al_start_timer(timer);
   timer_queue = al_create_event_queue();
   al_register_event_source(timer_queue, al_get_timer_event_source(timer));
   
   old = al_get_new_bitmap_flags();
   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   Buffer = al_create_bitmap(ScreenW, ScreenH);
   al_set_new_bitmap_flags(old);
   
   al_identity_transform(&Identity);
   
   Screens[0] = LowPrimitives;
   Screens[1] = IndexedPrimitives;
   Screens[2] = HighPrimitives;
   Screens[3] = TransformationsPrimitives;
   Screens[4] = FilledPrimitives;
   Screens[5] = IndexedFilledPrimitives;
   Screens[6] = HighFilledPrimitives;
   Screens[7] = TexturePrimitives;
   Screens[8] = FilledTexturePrimitives;
   Screens[9] = CustomVertexFormatPrimitives;

   ScreenName[0] = "Low Level Primitives";
   ScreenName[1] = "Indexed Primitives";
   ScreenName[2] = "High Level Primitives";
   ScreenName[3] = "Transformations";
   ScreenName[4] = "Low Level Filled Primitives";
   ScreenName[5] = "Indexed Filled Primitives";
   ScreenName[6] = "High Level Filled Primitives";
   ScreenName[7] = "Textured Primitives";
   ScreenName[8] = "Filled Textured Primitives";
   ScreenName[9] = "Custom Vertex Format";

   for (ii = 0; ii < NUM_SCREENS; ii++)
      Screens[ii](INIT);
      
   while (!done) {
      double frame_duration = al_get_time() - real_time;
      al_rest(fixed_timestep - frame_duration); //rest at least fixed_dt
      frame_duration = al_get_time() - real_time;
      real_time = al_get_time();
      
      if (real_time - game_time > frame_duration) { //eliminate excess overflow
         game_time += fixed_timestep * floor((real_time - game_time) / fixed_timestep);
      }
      
      while (real_time - game_time >= 0) {
         ALLEGRO_EVENT key_event;
         double start_time = al_get_time();
         game_time += fixed_timestep;
         
         Screens[cur_screen](LOGIC);
         
         while (al_get_next_event(queue, &key_event)) {
            switch (key_event.type) {
               case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: {
                  cur_screen++;
                  if (cur_screen >= NUM_SCREENS) {
                     cur_screen = 0;
                  }
                  break;
               }

               case ALLEGRO_EVENT_DISPLAY_CLOSE: {
                  done = true;
                  break;
               }
               case ALLEGRO_EVENT_KEY_CHAR: {
                  switch (key_event.keyboard.keycode) {
                     case ALLEGRO_KEY_ESCAPE: {
                        done = true;
                        break;
                     }
                     case ALLEGRO_KEY_S: {
                        Soft = !Soft;
                        time_diff = al_get_time();
                        frames_done = 0;
                        break;
                     }
                     case ALLEGRO_KEY_C: {
                        clip = !clip;
                        time_diff = al_get_time();
                        frames_done = 0;
                        break;
                     }
                     case ALLEGRO_KEY_L: {
                        Blend = !Blend;
                        time_diff = al_get_time();
                        frames_done = 0;
                        break;
                     }
                     case ALLEGRO_KEY_B: {
                        Background = !Background;
                        time_diff = al_get_time();
                        frames_done = 0;
                        break;
                     }
                     case ALLEGRO_KEY_LEFT: {
                        Speed -= ROTATE_SPEED;
                        break;
                     }
                     case ALLEGRO_KEY_RIGHT: {
                        Speed += ROTATE_SPEED;
                        break;
                     }
                     case ALLEGRO_KEY_PGUP: {
                        Thickness += 0.5f;
                        if (Thickness < 1.0f)
                           Thickness = 1.0f;
                        break;
                     }
                     case ALLEGRO_KEY_PGDN: {
                        Thickness -= 0.5f;
                        if (Thickness < 1.0f)
                           Thickness = 0.0f;
                        break;
                     }
                     case ALLEGRO_KEY_UP: {
                        cur_screen++;
                        if (cur_screen >= NUM_SCREENS) {
                           cur_screen = 0;
                        }
                        break;
                     }
                     case ALLEGRO_KEY_SPACE: {
                        Speed = 0;
                        break;
                     }
                     case ALLEGRO_KEY_DOWN: {
                        cur_screen--;
                        if (cur_screen < 0) {
                           cur_screen = NUM_SCREENS - 1;
                        }
                        break;
                     }
                  }
               }
            }
         }
         
         if (al_get_time() - start_time >= fixed_timestep) { //break if we start taking too long
            break;
         }
      }

      al_clear_to_color(black);            

      if (Soft == 1) {
         al_set_target_bitmap(Buffer);
         al_clear_to_color(black);
      }
      
      if (Background && bkg) {
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);
         al_draw_scaled_bitmap(bkg, 0, 0, al_get_bitmap_width(bkg), al_get_bitmap_height(bkg), 0, 0, ScreenW, ScreenH, 0);
      }
      
      if (clip == 1) {
         al_set_clipping_rectangle(ScreenW / 2, ScreenH / 2, ScreenW / 2, ScreenH / 2);
      }
      
      Screens[cur_screen](DRAW);
      
      al_set_clipping_rectangle(0, 0, ScreenW, ScreenH);

      if (Soft == 1) {
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);
         al_set_target_backbuffer(display);
         al_draw_bitmap(Buffer, 0, 0, 0);
      }

      al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
      al_draw_textf(Font, solid_white, ScreenW / 2, ScreenH - 20, ALLEGRO_ALIGN_CENTRE, "%s", ScreenName[cur_screen]);
      al_draw_textf(Font, solid_white, 0, 0, 0, "FPS: %f", (float)frames_done / (al_get_time() - time_diff));
      al_draw_textf(Font, solid_white, 0, 20, 0, "Change Screen (Up/Down). Esc to Quit.");
      al_draw_textf(Font, solid_white, 0, 40, 0, "Rotation (Left/Right/Space): %f", Speed);
      al_draw_textf(Font, solid_white, 0, 60, 0, "Thickness (PgUp/PgDown): %f", Thickness);
      al_draw_textf(Font, solid_white, 0, 80, 0, "Software (S): %d", Soft);
      al_draw_textf(Font, solid_white, 0, 100, 0, "Blending (L): %d", Blend);
      al_draw_textf(Font, solid_white, 0, 120, 0, "Background (B): %d", Background);
      al_draw_textf(Font, solid_white, 0, 140, 0, "Clip (C): %d", clip);

      al_flip_display();
      frames_done++;
   }
   }
   
   return 0;
}
/*metodo principal, gerencia a janela*/
int main(int argc, char argv[]) {	
	/*janela principal*/
    ALLEGRO_DISPLAY *janela = NULL;

	/*fila de eventos*/
	ALLEGRO_EVENT_QUEUE *filaEvento = NULL;

	/*evento atual*/
	ALLEGRO_EVENT evento;
	
	ALLEGRO_BITMAP *botao_gravar = NULL, *botao_carregar = NULL, *botao_girar_horario = NULL, *botao_girar_antihorario = NULL;
	
	/*ponteiro para um arquivo no dico*/
	FILE *arquivo;
	
	/*definicoes do arquivo*/
	int altura = 0,//altura da imagem
		largura = 0, //largura da imagem
		maxCor = 0;//inteiro que representa tonalidade de cor maxima
	
	char tipo[3];//tipo de PGM
	
	/*estrutura para armazenar os bits do arquivo*/
	unsigned char **data = NULL;
	
	/*sinaliza fechamento da janela*/
	bool fechaJanela = false;
	
	/*sinaliza existencia de arquivo aberto*/
	bool arquivoAberto = false;
 
    /*inicializa bibliotecas*/
    if(!(al_init() && 
		al_install_mouse()&&
		al_init_image_addon()&&
		al_install_keyboard()&&
		al_init_primitives_addon()&&
		(filaEvento = al_create_event_queue()))){
        printf("Erro ao inicializar biblioteca(s)!\n"); 
        return 0;
    }

 // Alocamos o botão para fechar a aplicação
    
    criaBotao(botoes[0], "carregar.bmp");
    
    
    botao_carregar = al_load_bitmap("carregar.bmp"); 
    
    if (!botao_carregar)
    {
        fprintf(stderr, "Falha ao criar botão de carregar a imagem.\n");
        al_destroy_display(janela);
        
        return -1; 
    }
    
        // Alocamos o botão para fechar a aplicação
    botao_gravar = al_load_bitmap("salvar.bmp");
    if (!botao_gravar)
    {
        fprintf(stderr, "Falha ao criar botão de salvar a imagem.\n");
        al_destroy_bitmap(botao_carregar);
        al_destroy_display(janela);
        return -1;
    }
        // Alocamos o botão para fechar a aplicação
    botao_girar_horario = al_load_bitmap("girar_horario.bmp");
    if (!botao_girar_horario)
    {
        fprintf(stderr, "Falha ao criar botão de girar a imagem 90º sentido horario.\n");
       al_destroy_bitmap(botao_carregar);
        al_destroy_bitmap(botao_gravar);
        al_destroy_display(janela);
        return -1;
    }
        // Alocamos o botão para fechar a aplicação
    botao_girar_antihorario = al_load_bitmap("girar_anti.bmp");
    if (!botao_girar_antihorario)
    {
        fprintf(stderr, "Falha ao criar botão de girar a imagem 90º sentido anti-horario.\n");
        al_destroy_bitmap(botao_carregar);
        al_destroy_bitmap(botao_gravar);
        al_destroy_bitmap(botao_girar_horario);
        al_destroy_display(janela);
        return -1;
    }

    /*cria uma janela 640x480*/
    janela = al_create_display(640, 50);

    /*registra os eventos*/
	al_register_event_source(filaEvento, al_get_display_event_source(janela));
	al_register_event_source(filaEvento, al_get_mouse_event_source());
	al_register_event_source(filaEvento, al_get_keyboard_event_source());

	/*preenche a janela com a cor branca*/
    al_clear_to_color(al_map_rgb(255, 255, 255));         

	/*atualiza tela*/
    al_flip_display();
    
	/*fluxo principal da janela*/
	while(fechaJanela == false){
		
        /*pega evento da fila*/
		al_wait_for_event(filaEvento, &evento);

		switch (evento.type) {			
			/*fecha a janela (termina aplicacao)*/
			case ALLEGRO_EVENT_DISPLAY_CLOSE:
				fechaJanela = true;
			break;
			
			/*carrega imagem em mostra na tela*/
			case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
          
           if (evento.mouse.x >= 0 && evento.mouse.x <= 70 && evento.mouse.y <= 50 && evento.mouse.y >= 0) {
				/*caso algum arquivo estiver aberto, limpa dados*/
				if(arquivoAberto==true) {
					desalocaMatriz(data, altura);
					altura =0;
					largura =0;
					maxCor =0;
					arquivoAberto = false;
				}
				if(arquivoAberto==false) {
					/*carrega imagem na matriz*/
                        if(carregaImagem (janela, &altura,&largura, &maxCor, tipo, &data)==-1) {
                            printf("Erro ao desenhar imagem!\n");
                            break;
                        }

					/*sinaliza como arquivo aberto*/
					arquivoAberto = true;

					/*desenha a imagem na janela*/
					desenha(janela, data, altura, largura);
					
					 
				}	
            }
            
            
            if (evento.mouse.x >= 71 && evento.mouse.x <= 140 && evento.mouse.y <= 50 && evento.mouse.y >= 0 && arquivoAberto== true){
                if(arquivoAberto == true) {
					if(gravaImagem(janela, tipo, altura, largura, maxCor, data)==-1) {
						printf("Erro ao salvar imagem!\n");
						break;
					}
				}
				else {
					printf("Nenhum arquivo aberto!\n");			
				}
            }
            
             if (evento.mouse.x >= 141 && evento.mouse.x <= 210 && evento.mouse.y <= 50 && evento.mouse.y >= 0 && arquivoAberto== true)
             {
                 data = rotacao(data, &altura, &largura, 'D');
                 desenha(janela, data, altura, largura);
             }
            
             if (evento.mouse.x >= 211 && evento.mouse.x <= 280 && evento.mouse.y <= 50 && evento.mouse.y >= 0 && arquivoAberto== true){
                                  data = rotacao(data, &altura, &largura, 'E');
                 desenha(janela, data, altura, largura);
                                }
            
			break;
			
		
         case ALLEGRO_EVENT_KEY_DOWN:
		 switch(evento.keyboard.keycode) 
        {
            case ALLEGRO_KEY_ENTER:
               if(arquivoAberto == true) {
					if(gravaImagem(janela, tipo, altura, largura, maxCor, data)==-1) {
						printf("Erro ao salvar imagem!\n");
						break;
					}
				}
				else {
					printf("Nenhum arquivo aberto!\n");			
				}
               break;
 
            case ALLEGRO_KEY_SPACE:
                 data = rotacao(data, &altura, &largura, 'D');
                 desenha(janela, data, altura, largura);
  
            break;

         }
		
            default:
			break;
			
		}
		
		al_set_target_bitmap(botao_gravar);
        al_set_target_bitmap(botao_carregar);
        al_set_target_bitmap(botao_girar_horario);
        al_set_target_bitmap(botao_girar_antihorario);
    
        al_set_target_bitmap(al_get_backbuffer(janela));
        al_draw_bitmap(botao_carregar, 0,0, 0);
        al_draw_bitmap(botao_gravar, 71,0, 0);
        al_draw_bitmap(botao_girar_horario, 141,0, 0);
        al_draw_bitmap(botao_girar_antihorario, 211,0, 0);
    
    	/*atualiza tela*/
        al_flip_display();
	}

	/*limpeza*/
	if(data!=NULL && arquivoAberto == true){
		desalocaMatriz(data, altura);
	}
    al_destroy_event_queue(filaEvento);
	al_uninstall_mouse();
    al_uninstall_keyboard();
    al_destroy_bitmap(botao_carregar);
    al_destroy_bitmap(botao_gravar);
    al_destroy_bitmap(botao_girar_horario);
    al_destroy_bitmap(botao_girar_antihorario);
	al_destroy_display(janela);

    return 0;
}
Exemple #13
0
int main()
{
    const int SCREEN_W = 1280, SCREEN_H = 768;

    ALLEGRO_DISPLAY *display = NULL;

    ALLEGRO_EVENT_QUEUE* queue;

    ALLEGRO_FONT* century_gothic40;
    ALLEGRO_FONT* century_gothic24;

    ALLEGRO_BITMAP* MenuBackground;
    ALLEGRO_BITMAP* ArenaBackground;
    ALLEGRO_BITMAP* Ball;

    //ALLEGRO_SAMPLE* BackgroundMusic;
    //ALLEGRO_SAMPLE* Boop;
    //ALLEGRO_SAMPLE* Score;
    //ALLEGRO_SAMPLE* Intro;

    ALLEGRO_TIMER* timer;

    Gamemode gamemode = Menu;

    std::string player_text = "PLAYER : 0", ai_text = "BOT : 0";
    unsigned int player_score = 0, ai_score = 0;

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

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

    //if (!al_reserve_samples(1))
    //{
        //fprintf(stderr, "Failed to reserve samples!\n");
        //return -1;
    //}
    if(!al_install_mouse())
    {
        fprintf(stderr, "Failed to initialize the mouse!\n");
        return -1;
    }
    if(!al_init_primitives_addon())
    {
        printf("al_init_primitives_addon Failed!\n");
        return -1;
    }
    display = al_create_display(SCREEN_W, SCREEN_H);

    if(!display)
    {
        printf("al_create_display Failed!\n");
        return -1;
    }

    srand(time(NULL));

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

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

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

    al_start_timer(timer);

    century_gothic40  = al_load_ttf_font("C:\\Windows\\Fonts\\GOTHIC.TTF" , 40, ALLEGRO_ALIGN_CENTRE);
    century_gothic24  = al_load_ttf_font("C:\\Windows\\Fonts\\GOTHIC.TTF" , 24, ALLEGRO_ALIGN_CENTRE);

    MenuBackground = LoadB("res\\menu.png");
    ArenaBackground = LoadB("res\\arena.png");
    Ball = LoadB("res\\ball.png");

    //BackgroundMusic = LoadS("res\\rain.wav");
    //Boop = LoadS("res\\boop.ogg");
    //Score = LoadS("res\\score.wav");
    //Intro = LoadS("res\\intro.ogg");

    //ALLEGRO_VOICE *audioDevice = al_create_voice(44100,  ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2);
    //ALLEGRO_MIXER *mixerMaster = al_create_mixer(44100,  ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2);
    //ALLEGRO_MIXER *mixerMusic = al_create_mixer(44100,  ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2);
    //ALLEGRO_MIXER *mixerSounds = al_create_mixer(44100,  ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2);

    //if (audioDevice == NULL || mixerMaster == NULL || mixerMusic == NULL || mixerSounds == NULL)
    //{
        //printf("Failed to start audio devices");
    //}

/*  Attempt of Audio
    al_attach_sample_instance_to_mixer(Boop, mixerSounds);
    al_attach_sample_instance_to_mixer(BackgroundMusic, mixerMusic);
    al_attach_sample_instance_to_mixer(Score, mixerSounds);
    al_attach_sample_instance_to_mixer(Intro, mixerSounds);

    al_attach_mixer_to_mixer(mixerMusic, mixerMaster);
    al_attach_mixer_to_mixer(mixerSounds, mixerMaster);
    al_attach_mixer_to_voice(mixerMaster, audioDevice);

    //ALLEGRO_SAMPLE_INSTANCE BoopI = al_create_sample_instance(Boop);
    //ALLEGRO_SAMPLE_INSTANCE ScoreI = al_create_sample_instance(Score);
    //al_play_sample(BackgroundMusic, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);*/

    float player_y = 0, player_y_vel = 0,
          ai_y_vel = 0, ai_y = 0,
          ball_x = (SCREEN_W/2)-12, ball_x_vel = (rand() % 2) ? 5 : -5,
          ball_y = (SCREEN_H/2)-15, ball_y_vel = 0,
          multiplier = 1;

    bool render , scored, executing = true;
    //al_play_sample(Intro, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL);
    while (executing)
    {
        ALLEGRO_EVENT event;
        al_wait_for_event(queue, &event);
        switch(event.type)
        {
        case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            switch (gamemode)
            {
            case Menu:
                if ((event.mouse.x >= (SCREEN_W / 2) - 150) && (event.mouse.x <= (SCREEN_W / 2) + 150))
                {
                    if ((event.mouse.y >= 205) && (event.mouse.y <= 280))
                    {
                        gamemode = Game;
                    }
                    else if ((event.mouse.y >= 305) && (event.mouse.y <= 380))
                    {
                        gamemode = Description;
                    }
                    else if ((event.mouse.y >= 405) && (event.mouse.y <= 480))
                    {
                        executing = false;
                    }
                }
                break;
            case Description:

                break;
            case Conclusion:
                if ((event.mouse.x >= (SCREEN_W/2)-150) && (event.mouse.x <= (SCREEN_W/2)+150))
                {
                    if ((event.mouse.y >= 305) && (event.mouse.y <= 380))
                    {
                        player_score = ai_score = player_y = player_y_vel = ai_y_vel = ai_y = ball_y_vel = 0;
                        ball_x_vel = (rand() % 2) ? 5 : -5;
                        ball_x = (SCREEN_W / 2) - 12;
                        ball_y = (SCREEN_H / 2) - 15;
                        multiplier = 1;
                        player_text = "PLAYER : 0";
                        ai_text = "BOT : 0";
                        gamemode = Menu;
                    }
                    else if ((event.mouse.y >= 405) && (event.mouse.y <= 480))
                    {
                        executing = false;
                    }
                }
                break;
            }
            break;
        case ALLEGRO_EVENT_DISPLAY_CLOSE:
            executing = false;
            break;
        case ALLEGRO_EVENT_KEY_DOWN:
            switch(event.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                switch (gamemode)
                {
                case Game:
                    executing = false;
                    break;
                }
                break;
            case ALLEGRO_KEY_UP:
            case ALLEGRO_KEY_W:
                player_y_vel = -10;
                break;
            case ALLEGRO_KEY_DOWN:
            case ALLEGRO_KEY_S:
                player_y_vel = 10;
                break;
            case ALLEGRO_KEY_ENTER:
                executing = false;
                break;
            }
            gamemode = Game;
            break;
        case ALLEGRO_EVENT_KEY_UP:
            player_y_vel = 0;
            break;
        case ALLEGRO_EVENT_TIMER:
            render = true;
            switch(gamemode)
            {
            case Game:
                // Scoring
                bool scored = false;
                if (ball_x >= SCREEN_W)
                {
                    player_score++;
                    scored = true;
                    std::stringstream ss;
                    ss << "PLAYER : " << player_score;
                    player_text = ss.str();
                }
                if (ball_x <= 0)
                {
                    ai_score++;
                    scored = true;
                    std::stringstream ss;
                    ss << "BOT : " << ai_score;
                    ai_text = ss.str();
                }
                if (scored)
                {
                    //al_play_sample(Score, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL);
                    //al_play_sample_instance(ScoreI);
                    ball_x = (SCREEN_W/2)-12;
                    ball_y = (SCREEN_H/2)-15;
                    ball_x_vel = (rand() % 2) ? 5.75 : -5.75;
                    ball_y_vel = 0;
                    ai_y = 0;
                    player_y = 0;
                    multiplier = 1;
                }
                // Collision
                if (((((SCREEN_H/2)-50)+player_y)<=0)&&(player_y_vel<0)) player_y_vel = 0;
                if (((((SCREEN_H/2)+50)+player_y)>=SCREEN_H)&&(player_y_vel>0)) player_y_vel = 0;
                if ((ball_y <= 0) || (ball_y >= SCREEN_H)) ball_y_vel = -ball_y_vel;
                if (((ball_y <= (((SCREEN_H / 2) + 50) + player_y) && (ball_y >= (((SCREEN_H / 2) - 50) + player_y))) && ((ball_x <= 90) && (ball_x >= 75))) || (((ball_y <= (((SCREEN_H / 2) + 50) + ai_y)) && (ball_y >= (((SCREEN_H / 2) - 50) + ai_y))) && (((ball_x >= SCREEN_W - 110)) && (ball_x <= SCREEN_W - 75))))
                {
                    //al_play_sample(Boop, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL);
                    //al_play_sample_instance(BoopI);
                    ball_x_vel = -ball_x_vel * multiplier;
                    multiplier += 0.005f;
                    ball_y_vel = (rand() % 10) - 5;
                }
                // AI
                if (ball_x_vel > 0)                                                 // Ball comming towards AI
                {
                    if ((ai_y <= 340) && (ai_y >= -340))                              // AI is in game bounds
                    {
                        if ((SCREEN_H/2)+ai_y < ball_y) ai_y_vel = abs(ball_y_vel) < 3 ? abs(ball_y_vel) : 5;
                        else if ((SCREEN_H/2)+ai_y == ball_y) ai_y_vel = 0;
                        else ai_y_vel = abs(ball_y_vel) < 3 ? -abs(ball_y_vel) : -5;
                    }
                    else if (ai_y >  340) ai_y_vel = -3;
                    else if (ai_y < -340) ai_y_vel = 3;
                    else ai_y_vel = 0;
                }
                else                                                                 // Go towards center
                {
                    if (ai_y > 10) ai_y_vel = -1;
                    else if (ai_y < 10) ai_y_vel = 1;
                    else ai_y_vel = 0;
                }
                // Movement
                player_y += player_y_vel;
                ai_y += ai_y_vel;
                ball_x += ball_x_vel;
                ball_y += ball_y_vel;
                if (player_score >= 10 || ai_score >= 10) gamemode = Conclusion;
                break;
            }
            break;
        }

        if (al_is_event_queue_empty(queue) && render)
        {
            al_clear_to_color(al_map_rgb(0,0,0));
            al_set_target_bitmap(al_get_backbuffer(display));
            ////////////////////////////////////////////////////////////////////

            switch(gamemode)
            {
            case Menu:
                al_draw_bitmap(MenuBackground, 0, 0, 0);
                al_draw_text(century_gothic40, al_map_rgb(250,250,250), SCREEN_W/2, 40, ALLEGRO_ALIGN_CENTRE, "Ultimate Pong");
                al_draw_rectangle((SCREEN_W / 2) - 150, 205, (SCREEN_W / 2) + 150, 280, al_map_rgb(255, 255, 255), 3);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 220, ALLEGRO_ALIGN_CENTRE, "Play");
                al_draw_rectangle((SCREEN_W / 2) - 150, 305, (SCREEN_W / 2) + 150, 380, al_map_rgb(255, 255, 255), 3);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 320, ALLEGRO_ALIGN_CENTRE, "About");
                al_draw_rectangle((SCREEN_W / 2) - 150, 405, (SCREEN_W / 2) + 150, 480, al_map_rgb(255, 255, 255), 3);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 420, ALLEGRO_ALIGN_CENTRE, "Quit");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 200, SCREEN_H - 50, ALLEGRO_ALIGN_CENTRE, "Game by Thomas Steinholz");

                break;
            case Description:
                al_draw_bitmap(MenuBackground, 0, 0, 0);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 40, ALLEGRO_ALIGN_CENTRE, "About Ultimate Pong");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 240, ALLEGRO_ALIGN_LEFT, "This is the game of Ultimate Pong! The game consists of 2 paddles knocking a ball back and");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 260, ALLEGRO_ALIGN_LEFT, "forth until one misses it and it goes into the goal. The point of the game is to score 10 ");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 280, ALLEGRO_ALIGN_LEFT, "points. You can score a point by getting the ball in the other player's goal (right behind");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 300, ALLEGRO_ALIGN_LEFT, "the enemy paddle). You control the game by using either the UP and DOWN arrow or the W and");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 320, ALLEGRO_ALIGN_LEFT, "S key. As you can guess, the up arrow brings your player up while the down arrow brings   ");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 340, ALLEGRO_ALIGN_LEFT, "your player down. The W key functions the same as the UP arrow as the S key functions the");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 360, ALLEGRO_ALIGN_LEFT, "same as the DOWN key. The game ends once either the player of AI has reached a point value");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 380, ALLEGRO_ALIGN_LEFT, "of 10. You play as the left paddle and the AI plays as the right paddle. You can see the  ");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 400, ALLEGRO_ALIGN_LEFT, "corresponding scores above the side you play as if you get lost or confused. To get       ");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 420, ALLEGRO_ALIGN_LEFT, "started, hit the ESC button. DISCLAIMER : IF YOU GET HURT, ITS NOT PONGS FAULT SO DONT SUE");
                al_draw_text(century_gothic24, al_map_rgb(250,250,250), 200, SCREEN_H - 50, ALLEGRO_ALIGN_CENTRE, "PRESS sESC TO PLAY");

                break;
            case Game:
                al_draw_bitmap(ArenaBackground, 0, 0, 0);
                al_draw_line((SCREEN_W/2)-3,0,(SCREEN_W/2)-3,SCREEN_H,al_map_rgb(255,255,255), 2);
                al_draw_circle((SCREEN_W/2)-5,(SCREEN_H/2)-5, 150, al_map_rgb(255,255,255), 2);
                al_draw_filled_rectangle(75,((SCREEN_H/2)-50)+player_y,90,((SCREEN_H/2)+50)+player_y,al_map_rgb(255,255,255));              //Player
                al_draw_filled_rectangle(SCREEN_W-75,((SCREEN_H/2)-50)+ai_y,SCREEN_W-90,((SCREEN_H/2)+50)+ai_y,al_map_rgb(255,255,255));    //AI
                al_draw_scaled_bitmap(
                    Ball,
                    0, 0,
                    al_get_bitmap_width(Ball), al_get_bitmap_height(Ball),
                    ball_x, ball_y,
                    15, 15,
                    0);
                al_draw_text(century_gothic40, al_map_rgb(250,250,250), 140, 40, ALLEGRO_ALIGN_CENTRE, player_text.c_str());
                al_draw_text(century_gothic40, al_map_rgb(250,250,250), SCREEN_W-100, 40, ALLEGRO_ALIGN_CENTRE, ai_text.c_str());
                break;
            case Conclusion:
                al_draw_bitmap(MenuBackground, 0, 0, 0);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 40, ALLEGRO_ALIGN_CENTRE, "Game Over!");
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 80, ALLEGRO_ALIGN_CENTRE, ai_score < player_score ? "You Win!" : "You Lose!");
                al_draw_textf(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 120, ALLEGRO_ALIGN_CENTRE, "%d : %d", player_score, ai_score);
                al_draw_rectangle((SCREEN_W/2)-150, 305, (SCREEN_W/2)+150, 380, al_map_rgb(255, 255, 255), 3);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 320, ALLEGRO_ALIGN_CENTRE, "Restart");
                al_draw_rectangle((SCREEN_W / 2) - 150, 405, (SCREEN_W / 2) + 150, 480, al_map_rgb(255, 255, 255), 3);
                al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 420, ALLEGRO_ALIGN_CENTRE, "Quit");
                break;
            }

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

    al_destroy_bitmap(MenuBackground);
    al_destroy_bitmap(ArenaBackground);
    al_destroy_bitmap(Ball);
    //al_destroy_sample(BackgroundMusic);
    //al_destroy_sample(Boop);
    //al_destroy_sample(Score);
    al_destroy_display(display);

    return 0;
}
Exemple #14
0
int main(void)
{
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_MONITOR_INFO info;
   int w = 640, h = 480;
   bool done = false;
   bool need_redraw = true;
   bool background = false;
   example.show_help = true;

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

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

   al_init_font_addon();

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

   #ifdef ALLEGRO_IPHONE
   al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
   #endif
   al_set_new_display_option(ALLEGRO_SUPPORTED_ORIENTATIONS,
                             ALLEGRO_DISPLAY_ORIENTATION_ALL, ALLEGRO_SUGGEST);
   example.display = al_create_display(w, h);
   w = al_get_display_width(example.display);
   h = al_get_display_height(example.display);

   if (!example.display) {
      abort_example("Error creating display.\n");
      return 1;
   }

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

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

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

   example.white = al_map_rgb_f(1, 1, 1);
   example.half_white = al_map_rgba_f(1, 1, 1, 0.5);
   example.dark = al_map_rgb(15, 15, 15);
   example.red = al_map_rgb_f(1, 0.2, 0.1);
   change_size(256);
   add_sprite();
   add_sprite();

   timer = al_create_timer(1.0 / FPS);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_timer_event_source(timer));
   
   if (al_install_touch_input())
      al_register_event_source(queue, al_get_touch_input_event_source());
   al_register_event_source(queue, al_get_display_event_source(example.display));

   al_start_timer(timer);

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

      if (!background && need_redraw && al_is_event_queue_empty(queue)) {
         double t = -al_get_time();
         add_time();
         al_clear_to_color(al_map_rgb_f(0, 0, 0));
         redraw();
         t += al_get_time();
         example.direct_speed_measure  = t;
         al_flip_display();
         need_redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_CHAR: /* includes repeats */
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            else if (event.keyboard.keycode == ALLEGRO_KEY_UP) {
               add_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) {
               remove_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) {
               change_size(example.bitmap_size - 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) {
               change_size(example.bitmap_size + 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_F1) {
               example.show_help ^= 1;
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               example.use_memory_bitmaps ^= 1;
               change_size(example.bitmap_size);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_B) {
               example.blending++;
               if (example.blending == 4)
                  example.blending = 0;
            }
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_DISPLAY_HALT_DRAWING:

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

            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING:
            background = false;
            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;
              
         case ALLEGRO_EVENT_TIMER:
            update();
            need_redraw = true;
            break;
         
         case ALLEGRO_EVENT_TOUCH_BEGIN:
            x = event.touch.x;
            y = event.touch.y;
            goto click;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            x = event.mouse.x;
            y = event.mouse.y;
            goto click;
            
         click:
         {
            int fh = al_get_font_line_height(example.font);
            
            if (x < 80 && y >= h - fh * 10) {
               int button = (y - (h - fh * 10)) / (fh * 2);
               if (button == 0) {
                  example.use_memory_bitmaps ^= 1;
                  change_size(example.bitmap_size);
               }
               if (button == 1) {
                  example.blending++;
                  if (example.blending == 4)
                     example.blending = 0;
               }
               if (button == 3) {
                  if (x < 40)
                     remove_sprites(example.sprite_count / 2);
                  else
                     add_sprites(example.sprite_count);
               }
               if (button == 2) {
                  int s = example.bitmap_size * 2;
                  if (x < 40)
                     s = example.bitmap_size / 2;
                  change_size(s);
               }
               if (button == 4) {
                  example.show_help ^= 1;
               }
                
            }
            break;
         }
      }
   }

   al_destroy_bitmap(example.bitmap);

   return 0;
}
Exemple #15
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;
}
 //------------------------------------------------------------
 // La función principal main()
 //------------------------------------------------------------
 int main(int argc, char **argv)
 {
     // Iniciar Allegro (y añadidos)
     al_init();
     al_init_image_addon();
     al_init_primitives_addon();
  
     // Instalar el mouse, teclado, etc.
     al_install_keyboard();
     al_install_mouse();
  
     if (FULLSCREEN)
         al_set_new_display_flags(ALLEGRO_FULLSCREEN);
  
     // Crear el "display"
     display = al_create_display(SCREEN_W, SCREEN_H);
  
     if (!SHOW_CURSOR)
         al_hide_mouse_cursor(display);
  
     // Poner el título de la ventana
     al_set_window_title(display, WINDOW_TITLE);
  
     // Creamos el timer (controlador de FPS)
     timer = al_create_timer(1.0 / FRAMERATE);
  
     // Creamos la 'pila' de eventos
     event_queue = al_create_event_queue();
  
     // Preparamos el juego
     game_setup();
  
     // Los eventos que usaremos
     al_register_event_source(event_queue, al_get_keyboard_event_source());
     al_register_event_source(event_queue, al_get_mouse_event_source());
     al_register_event_source(event_queue, al_get_display_event_source(display));
     al_register_event_source(event_queue, al_get_timer_event_source(timer));
  
     al_start_timer(timer);
  
     // Si esta variable se pone a 0, el juego terminará de inmediato
     game_is_running = 1;
  
     ALLEGRO_EVENT event;
  
     // El 'loop' principal del juego
     while (game_is_running)
     {
         al_wait_for_event(event_queue, &event);
  
         // Si el botón para cerrar fue presionado...
         if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
             break;
  
         // Actualizamos las teclas
         if (event.type == ALLEGRO_EVENT_KEY_DOWN)
         {
             // Al presionar <Esc> el juego terminará
             if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
                 game_is_running = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
                 key[KEY_LEFT] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT)
                 key[KEY_RIGHT] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_UP)
                 key[KEY_UP] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_DOWN)
                 key[KEY_DOWN] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_X)
                 key[KEY_X] = 1;
         }
  
         // Actualizamos las teclas
         if (event.type == ALLEGRO_EVENT_KEY_UP)
         {
             if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
                 key[KEY_LEFT] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT)
                 key[KEY_RIGHT] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_UP)
                 key[KEY_UP] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_DOWN)
                 key[KEY_DOWN] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_X)
                 key[KEY_X] = 0;
         }
  
         if (event.type == ALLEGRO_EVENT_TIMER)
         {
             game_update();
             redraw = 1;
         }
  
         if (redraw)
         {
             redraw = 0;
  
             al_clear_to_color(al_map_rgb(0, 0, 0));
  
             game_render();
  
             al_flip_display();
         }
     }
  
     al_destroy_display(display);
     al_destroy_timer(timer);
     al_destroy_event_queue(event_queue);
  
     game_shutdown();
  
     return 0;
 }
Exemple #17
0
int main(int argc, char const *argv[])
{
    int i = 0;
    int t = 1;

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

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

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

    //Declara�ao vair�veis allegro
    ALLEGRO_DISPLAY *janela = NULL;	            //Vari�vel para a janela
    ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;   //  ''     para eventos
    ALLEGRO_BITMAP *imagem = NULL;              //  ''     para imagem
    ALLEGRO_TIMER *timer = NULL;                //  ''     para o tempo (fps)
    ALLEGRO_FONT *fonte = NULL;                 //  ''     para fonte

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

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



    //Atribui atributos às variáveis allegro

    janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
    fila_eventos = al_create_event_queue();
    imagem = al_load_bitmap("virus.png");
    timer = al_create_timer(1.0 / fps);
    fonte = al_load_font("arial.ttf", 12, 0);    //Fonte DejaVu

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

    init_fail(janela, fonte, fila_eventos, imagem, timer); //Fun�ao de teste

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

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

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

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

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

        }

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

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

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

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

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

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

            coor_matrix(mapa, coordenada, fonte);

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

            draw_horda(monstro, n_mostros, imagem);

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

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

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

    return 0;
}
void Engine::init(const char* title, int width, int height, bool fullscreen){

	// initialize ALLEGRO
	al_init();
    al_init_font_addon();
    al_init_ttf_addon();
    al_init_primitives_addon();
    al_init_image_addon();
    al_init_acodec_addon();
    al_install_keyboard();
    al_install_mouse();
    al_install_audio();

    if(fullscreen){
		al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
	}else{
        al_set_new_display_flags(ALLEGRO_WINDOWED);
	}
    display = al_create_display(screenWidth, screenHeight);
    al_set_window_title(display, title);

    bigFont = al_load_font("fonts/pixelFont.ttf", 48, 0);
    defaultFont = al_load_font("fonts/pixelFont.ttf", 24, 0);
    smallFont = al_load_font("fonts/pixelFont.ttf", 16, 0);

    cursorImage = al_load_bitmap("graphics/cursorImage.png");
    playerImage = al_load_bitmap("graphics/playerImage.png");
    groundImage1 = al_load_bitmap("graphics/groundImage1.png");
    groundImage2 = al_load_bitmap("graphics/groundImage2.png");
    brokenWallImage = al_load_bitmap("graphics/brokenWallImage.png");

    al_reserve_samples(0);

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

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

    al_hide_mouse_cursor(display);

	m_fullscreen = fullscreen;
    m_running = true;

    //Pointer Lists +
    networkList.clear();
    populationList.clear();
    //Pointer Lists -

    //Variables +
    versionNumber = "v1.0";

    fpsTimeNew = 0, fpsCounter = 0, fpsTimeOld = 0;

    drawScreen = false, timerEvent = false, done = false, mouseButtonLeft = false, mouseButtonLeftClick = false, mouseButtonRight = false, mouseButtonRightClick = false, updateTick = false, inGame = false;
    mouseX = 0, mouseY = 0;
    lastKeyPress = 0, mouseWheel = 0;

    score = 0, updateTickTime = 64, updateTickTimeHelper = 0;

    logicSpeed = 64, rockSpawnChance = 0, activationResponse = 0, neuronBias = 0, crossoverRate = 0, mutationRate = 0, maxPerturbation = 0;
    numHiddenLayers = 0, neuronsPerHiddenLayer = 0, numElite = 0, numCopiesElite = 0, populationSize = 0, currentNetwork = 0, currentGeneration = 0;

    for(int x = 0; x < mapArrayWidth; x++){
        for(int y = 0; y < mapArrayHeight; y++){
            mapArray[x][y] = 0;
            mapTileArray[x][y] = rand() % 8;
        }
    }

    al_start_timer(timer);
}
Exemple #19
0
// Initializes the the GDATA struct
_Bool data_init(void)
{
    // Create a window to display things on: 800x600 pixels
    al_set_new_display_flags(ALLEGRO_RESIZABLE | ALLEGRO_OPENGL);
    al_set_new_display_refresh_rate(60);
    data->display = al_create_display(res_width, res_height);
    if(data->display == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Display Error:", "Failed to create window!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Sets the physfs file interface to be used for loading files
    al_set_physfs_file_interface();
    PHYSFS_mount("images", NULL, 1);
    PHYSFS_mount("fonts", NULL, 1);
    PHYSFS_mount("buttons", NULL, 1);

    // Well, looks like we're gonna have to draw our own mouse *SIGH*
    al_hide_mouse_cursor(data->display);
    data->cursor = al_load_bitmap("cursor_darkgrey.png");
    if(data->cursor == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Cursor Error:", "Failed to locate cursor!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Set the title of the window
    al_set_window_title(data->display, "SpeedRun!");

    // Sets the window's icon
    data->icon = al_load_bitmap("speedrundisplayicon.png");
    if(data->icon == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Icon Error:", "Failed to locate icon!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }
    al_set_display_icon(data->display, data->icon);

    // Load a font
    data->font = al_load_ttf_font("times.ttf", 25, 0);
    data->b_font = al_load_ttf_font("impact.ttf", 25, 0);
    if(data->font == NULL || data->b_font == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Font Error:", "Failed to load font!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Make and set a color to draw with
    data->text_color = al_map_rgba(80, 112, 255, 255);

    // Set background color
    data->background_color = al_map_rgba(0, 0, 0, 0);

    // Install the keyboard handler
    if(!al_install_keyboard())
    {
        al_show_native_message_box(data->display, "Error!", "Keyboard Error:", "Failed to install keyboard handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Install the mouse handler
    if(!al_install_mouse())
    {
        al_show_native_message_box(data->display, "Error!", "Mouse Error:", "Failed to install mouse handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Detect and set refresh rate
    int refresh_rate = al_get_display_refresh_rate(data->display);
    if(refresh_rate == 0)
    {
        refresh_rate = 60;
    }

    // Install timer with refresh rate
    data->timer = al_create_timer(1.0/refresh_rate);
    if(data->timer == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Timer Error:", "Failed to initialize timer!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return 1;
    }
    al_start_timer(data->timer);


    // Start the event queues to handle keyboard input, mouse input, display input and timer input
    data->queue = al_create_event_queue();
    al_register_event_source(data->queue, (ALLEGRO_EVENT_SOURCE*)data->timer);
    data->queue2 = al_create_event_queue();
    al_register_event_source(data->queue2, al_get_keyboard_event_source());
    al_register_event_source(data->queue2, (ALLEGRO_EVENT_SOURCE*)data->display);
    al_register_event_source(data->queue2, al_get_mouse_event_source());

    // Set the quit and gamestarted flags to false initially
    data->exit = false;
    data->gamestarted = false;
    data->options = false;
    data->highscores = false;
    data->howtoplay = false;

    al_start_timer(data->timer);

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

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

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

    al_install_mouse();
    al_install_keyboard();

    al_init_image_addon();

    display = al_create_display(640, 480);
    if (!display) {
       abort_example("Error creating display\n");
    }
    
    al_set_window_title(display, filename);
    
    t0 = al_get_time();
    bitmap = al_load_bitmap(filename);
    t1 = al_get_time();
    if (!bitmap) {
       abort_example("%s not found or failed to load\n", filename);
    }

    printf("Loading took %.4f seconds\n", t1 - t0);

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

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

    al_destroy_bitmap(bitmap);

    return 0;
}
Exemple #21
0
int main(int argc, char** argv)
{
    time_t t;

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

    }
}
Exemple #22
0
int main(int argc, char **argv)
{
	bool done = false;
	bool render = false;

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

	float evTimer = 0;

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

	int state = -1;

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

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

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

	if (!al_init())
		return -1;

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

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

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

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

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

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

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

	if (!display)
		return -1;

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

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

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

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

	TextBox *Task = new TextBox;

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

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

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

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

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

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

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

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

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

	ChangeState(state, TITLE);

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

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

	al_start_timer(timer);
	gameTime = al_current_time();

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

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

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

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

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

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

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

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

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

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

			frames++;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	al_destroy_font(score);
	al_destroy_font(font);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
			
	return 0;
}
Exemple #23
0
int main()
{
	// don't forget to put allegro-5.0.10-monolith-md-debug.lib
	const float FPS = 60.0f;

	ALLEGRO_DISPLAY *display;

	if(!al_init())
	{
		al_show_native_message_box(NULL,"Error","Error",
									"Cannot initialize Allegro", NULL, NULL);
		return -1;
	}

	display = al_create_display(ScreenWidth, ScreenHeight);

	if(!display)
	{
		al_show_native_message_box(NULL,"Error","Error",
									"Cannot create dsiplay", NULL, NULL);
		return -1;
	}

	al_set_window_position(display, 100, 100);

	al_install_keyboard();
	al_install_mouse();

	al_init_image_addon();
	//al_init_acodec_addon();

	al_init_font_addon();
	al_init_ttf_addon();

	ALLEGRO_TIMER *timer  = al_create_timer(1.0f / FPS);
	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	ALLEGRO_KEYBOARD_STATE keyState;

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

	bool done = false;

	InputManager input;
	ScreenManager::GetInstance().Initialize();
	ScreenManager::GetInstance().LoadContent();



	std::vector<int> keys;

	//these two below plus the IsKeyReleased are example how to use simultaneous keys
	keys.push_back(ALLEGRO_KEY_DOWN);
	keys.push_back(ALLEGRO_KEY_ESCAPE);

	float fade = 0.0f;

	al_start_timer(timer);

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

		if(input.IsKeyReleased(ev,keys))
			done=true; //closes the game
		//barnhen to check begin
		if(input.IsKeyPressed(ev, ALLEGRO_KEY_RIGHT))
			fade++;
		else if(input.IsKeyPressed(ev, ALLEGRO_KEY_LEFT))
			fade--;
		//barnhen to check end

		ScreenManager::GetInstance().Update(ev);
		ScreenManager::GetInstance().Draw(display);

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

	ScreenManager::GetInstance().UnloadContent();

	//Destroyers
	al_destroy_display(display);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);

	//std::cin.get();
	return 0;
}
Exemple #24
0
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *displays[2];
   ALLEGRO_MONITOR_INFO *info;
   int adapter_count;
   int x, y;
   ALLEGRO_FONT *myfont;
   ALLEGRO_EVENT_QUEUE *events;
   ALLEGRO_EVENT event;
   int i;

   (void)argc;
   (void)argv;

   srand(time(NULL));

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

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

   adapter_count = al_get_num_video_adapters();

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

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

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

   al_set_new_window_position(x, y);

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

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

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

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

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

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

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

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

   al_destroy_event_queue(events);

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

   free(info);

   return 0;
}
Exemple #25
0
void
init_mouse (void)
{
  if (! al_install_mouse ())
    error (0, 0, "%s (void): cannot install mouse", __func__);
}
int main(int argc, char const *argv[])
{
	const int FPS = 60;
	const int MAX_BULLETS = 10;
	const int MAX_ASTEROIDS = 10;
	const int MAX_EXPLOSIONS = 10;
	srand(time(NULL));
	int done = 0;
	int redraw = 1;

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

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

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

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

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

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

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

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

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

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

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

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

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

	struct spaceship ship;
	init_ship(&ship);

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

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

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

	al_start_timer(timer);

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

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

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

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

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

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

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

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

			update_ship_boundaries(&ship);

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

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

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

			redraw = 1;
		}

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

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

	return 0;
}
Exemple #27
0
int init::init_all()
{
    //this->display;

    srand (time(NULL));



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

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

    if(!al_install_keyboard()) {
        fprintf(stderr, "failed to initialize keyboard!\n");
        return -1;
    }
    if(!al_install_mouse()) {
        fprintf(stderr, "failed to initialize mouse!\n");
        return -1;
    }
    if(FULLSCREEN) {
        ALLEGRO_DISPLAY_MODE   disp_data;
        al_get_display_mode(0, &disp_data);
        al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW | ALLEGRO_OPENGL);

        fprintf(stderr,"%i  %i",disp_data.width,disp_data.height);
        this->screenWidth = disp_data.width;
        this->screenHeight = disp_data.height;
        this->display = al_create_display(disp_data.width, disp_data.height);

    }
    else {
        this->display = al_create_display(screenWidth,screenHeight);
    }
    if(!display) {
        fprintf(stderr, "failed to create display!\n");
        return -1;
    }


    al_set_new_bitmap_flags(ALLEGRO_MAG_LINEAR | ALLEGRO_MIN_LINEAR);

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

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

    this->font = al_load_ttf_font("resources/pirulen.ttf",14,0);
    if (!font) {
        fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
        return -1;
    }
    if (!al_init_image_addon()) {
        fprintf(stderr, "Could not initialize image addon.\n");
        return -1;
    }

    this->event_queue = al_create_event_queue();
    if(!event_queue) {
        fprintf(stderr, "failed to create event_queue!\n");
    }
    al_register_event_source(this->event_queue, al_get_timer_event_source(this->timer));
    al_register_event_source(this->event_queue, al_get_keyboard_event_source());
    al_register_event_source(this->event_queue, al_get_display_event_source(this->display));
    al_register_event_source(this->event_queue, al_get_mouse_event_source());

    al_start_timer(timer);


    return 0;
}
Exemple #28
0
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_TIMER *timer;
   ALLEGRO_CONFIG *config;
   char const *value;
   char str[256];

   (void)argc;
   (void)argv;

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

   /* Read supersampling info from ex_draw.ini. */
   ex.samples = 0;
   config = al_load_config_file("ex_draw.ini");
   if (!config)
      config = al_create_config();
   value = al_get_config_value(config, "settings", "samples");
   if (value)
      ex.samples = strtol(value, NULL, 0);
   sprintf(str, "%d", ex.samples);
   al_set_config_value(config, "settings", "samples", str);
   al_save_config_file("ex_draw.ini", config);
   al_destroy_config(config);

   if (ex.samples) {
      al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_REQUIRE);
      al_set_new_display_option(ALLEGRO_SAMPLES, ex.samples, ALLEGRO_SUGGEST);
   }
   display = al_create_display(640, 640);
   if (!display) {
      abort_example("Unable to create display.\n");
   }

   init();

   timer = al_create_timer(1.0 / ex.FPS);

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

   al_start_timer(timer);
   run();

   al_destroy_event_queue(ex.queue);  

   return 0;
}
Exemple #29
0
int main(int, char**)
{
    // Setup Allegro
    al_init();
    al_install_keyboard();
    al_install_mouse();
    al_init_primitives_addon();
    al_set_new_display_flags(ALLEGRO_RESIZABLE);
    ALLEGRO_DISPLAY* display = al_create_display(1280, 720);
    al_set_window_title(display, "Dear ImGui Allegro 5 example");
    ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue();
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_mouse_event_source());

    // Setup Dear ImGui binding
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  // Enable Keyboard Controls
    ImGui_ImplAllegro5_Init(display);

    // Setup style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. 
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. 
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'misc/fonts/README.txt' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    bool running = true;
    while (running)
    {
        // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        ALLEGRO_EVENT ev;
        while (al_get_next_event(queue, &ev))
        {
            ImGui_ImplAllegro5_ProcessEvent(&ev);
            if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) 
                running = false;
            if (ev.type == ALLEGRO_EVENT_DISPLAY_RESIZE)
            {
                ImGui_ImplAllegro5_InvalidateDeviceObjects();
                al_acknowledge_resize(display);
                ImGui_ImplAllegro5_CreateDeviceObjects();
            }
        }

        // Start the Dear ImGui frame
        ImGui_ImplAllegro5_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f    
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        al_clear_to_color(al_map_rgba_f(clear_color.x, clear_color.y, clear_color.z, clear_color.w));
        ImGui_ImplAllegro5_RenderDrawData(ImGui::GetDrawData());
        al_flip_display();
    }

    // Cleanup
    ImGui_ImplAllegro5_Shutdown();
    ImGui::DestroyContext();
    al_destroy_event_queue(queue);
    al_destroy_display(display);

    return 0;
}
Exemple #30
0
int main(int, char**)
{
    // Setup Allegro 
    al_init();
    al_install_keyboard();
    al_install_mouse();
    al_init_primitives_addon();
    al_set_new_display_flags(ALLEGRO_RESIZABLE);
    ALLEGRO_DISPLAY* display = al_create_display(1280, 720);
    al_set_window_title(display, "ImGui Allegro 5 example");
    ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue();
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_mouse_event_source());

    // Setup ImGui binding
    ImGui_ImplA5_Init(display);

    // Load Fonts
    // (see extra_fonts/README.txt for more details)
    //ImGuiIO& io = ImGui::GetIO();
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
    //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());

    // Merge glyphs from multiple fonts into one (e.g. combine default font with another with Chinese glyphs, or add icons)
    //ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 };
    //ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true;
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 18.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/fontawesome-webfont.ttf", 18.0f, &icons_config, icons_ranges);

    bool show_test_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImColor(114, 144, 154);

    // Main loop
    bool running = true;
    while (running) 
    {
        ALLEGRO_EVENT ev;
        while (al_get_next_event(queue, &ev))
        {
            ImGui_ImplA5_ProcessEvent(&ev);
            if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) running = false;
            if (ev.type == ALLEGRO_EVENT_DISPLAY_RESIZE)
            {
                ImGui_ImplA5_InvalidateDeviceObjects();
                al_acknowledge_resize(display);
                Imgui_ImplA5_CreateDeviceObjects();
            }
        }
        ImGui_ImplA5_NewFrame();

        // 1. Show a simple window
        // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
        {
            static float f;
            ImGui::Text("Hello, world!");
            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
            ImGui::ColorEdit3("clear color", (float*)&clear_color);
            if (ImGui::Button("Test Window")) show_test_window ^= 1;
            if (ImGui::Button("Another Window")) show_another_window ^= 1;
            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f/ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
        }

        // 2. Show another simple window, this time using an explicit Begin/End pair
        if (show_another_window) 
        {
            ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
            ImGui::Begin("Another Window", &show_another_window);
            ImGui::Text("Hello");
            ImGui::End();
        }

        // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
        if (show_test_window) 
        {
            ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
            ImGui::ShowTestWindow(&show_test_window);
        }

        // Rendering
        al_clear_to_color(al_map_rgba_f(clear_color.x, clear_color.y, clear_color.z, clear_color.w));
        ImGui::Render();
        al_flip_display();
    }

    // Cleanup
    ImGui_ImplA5_Shutdown();
    al_destroy_event_queue(queue);
    al_destroy_display(display);

    return 0;
}