int main(void) { ALLEGRO_FONT *font; ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *event_queue; ALLEGRO_EVENT event; bool right_button_down = false; bool redraw = true; int fake_x = 0, fake_y = 0; ALLEGRO_COLOR white; if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_init_primitives_addon(); al_init_font_addon(); al_init_image_addon(); al_install_mouse(); al_install_keyboard(); al_set_new_display_flags(ALLEGRO_WINDOWED); display = al_create_display(width, height); if (!display) { abort_example("Could not create display.\n"); return 1; } memset(&event, 0, sizeof(event)); event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); font = al_load_font("data/fixed_font.tga", 0, 0); white = al_map_rgb_f(1, 1, 1); while (1) { if (redraw && al_is_event_queue_empty(event_queue)) { int th = al_get_font_line_height(font); al_clear_to_color(al_map_rgb_f(0, 0, 0)); if (right_button_down) { al_draw_line(width / 2, height / 2, fake_x, fake_y, al_map_rgb_f(1, 0, 0), 1); al_draw_line(fake_x - 5, fake_y, fake_x + 5, fake_y, al_map_rgb_f(1, 1, 1), 2); al_draw_line(fake_x, fake_y - 5, fake_x, fake_y + 5, al_map_rgb_f(1, 1, 1), 2); } al_draw_textf(font, white, 0, 0, 0, "x: %i y: %i dx: %i dy %i", event.mouse.x, event.mouse.y, event.mouse.dx, event.mouse.dy); al_draw_textf(font, white, width / 2, height / 2 - th, ALLEGRO_ALIGN_CENTRE, "Left-Click to warp pointer to the middle once."); al_draw_textf(font, white, width / 2, height / 2, ALLEGRO_ALIGN_CENTRE, "Hold right mouse button to constantly move pointer to the middle."); al_flip_display(); redraw = false; } al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } if (event.type == ALLEGRO_EVENT_KEY_DOWN) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) break; } if (event.type == ALLEGRO_EVENT_MOUSE_WARPED) { printf("Warp\n"); } if (event.type == ALLEGRO_EVENT_MOUSE_AXES) { if (right_button_down) { al_set_mouse_xy(display, width / 2, height / 2); fake_x += event.mouse.dx; fake_y += event.mouse.dy; } redraw = true; } if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (event.mouse.button == 1) al_set_mouse_xy(display, width / 2, height / 2); if (event.mouse.button == 2) { right_button_down = true; fake_x = width / 2; fake_y = height / 2; } } if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { if (event.mouse.button == 2) { right_button_down = false; } } } al_destroy_event_queue(event_queue); al_destroy_display(display); return 0; }
//main int main() { int letra; OpcaoBackground(letra); //primitive variables int NUM_ENEMYRED = 10; //quantidade de inimigos vermelhos int NUM_ENEMYBLUE = 10; //quantidade de inimigos azuis int NUM_BOSS = 5; int text_color = 255; //variavel para cor (animacao inicial de jogo - efeito relampago) int text_boss = 255; //variavel para cor de texto boss int FPS = 60; //frames per second bool done = false; bool redraw = true; enum KEYS {UP, DOWN, LEFT, RIGHT, Q, W, E, R}; bool keys[8] = {false, false, false, false, false, false, false, false}; //object variables struct Player player; struct Enemy_red enemyred[NUM_ENEMYRED]; struct Enemy_blue enemyblue[NUM_ENEMYBLUE]; struct Boss boss[NUM_BOSS]; struct Shoot shootQ; struct Shoot shootW; struct Shoot shootE; struct Obstacle obstacle; struct SpriteScientist scientist; struct Sprite background; struct Sprite background1; struct Sprite background2; struct Sprite background3; struct Sprite background4; struct Sprite background5; struct Sprite background6; struct Sprite enemyred_sprite; //allegro variables ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *title_font = NULL; ALLEGRO_FONT *medium_font = NULL; //////////////////////////////////////////////////////////////////////// //verificacoes de erro if(!al_init()) return -1; //caso de erro ao inicializar allegro display = al_create_display(WIDTH,HEIGHT); //criar display if(!display) return -1; //se der merda //Allegro Module Init al_init_primitives_addon(); al_init_font_addon(); if (!al_init_ttf_addon()) { printf("Falha ao inicializar addon allegro_ttf.\n"); return -1; } al_install_keyboard(); if(!al_init_image_addon()) { printf("Falha ao inicializar image addon"); return -1; } event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); medium_font = al_load_font("fonts/EHSMB.TTF", 50, 0); if (!medium_font) { al_destroy_display(display); printf("Falha ao carregar fonte.\n"); return -1; } title_font = al_load_font("fonts/French Electric Techno.ttf", 200, 0); if (!title_font) { al_destroy_display(display); printf("Falha ao carregar fonte.\n"); return -1; } int b; //Inicializacao de objetos InitPlayer(player, &text_color); //funcao que "inicia" player InitScientist(scientist); if (!scientist.bitmap) { al_destroy_display(display); printf("Falha ao carregar sprite scientist.\n"); return -1; } InitEnemyRed(enemyred, &NUM_ENEMYRED); //funcao que inicia enemyred InitEnemyBlue(enemyblue, &NUM_ENEMYBLUE); //funcao que inicia enemyblue InitShootQ(shootQ); //funcao que inicializa disparo 1 (capacitor) if(!shootQ.bitmap) { al_destroy_display(display); printf("Falha ao carregar sprite shootQ.\n"); return -1; } InitShootW(shootW); //funcao que inicializa disparo 2 (indutor) if(!shootW.bitmap) { al_destroy_display(display); printf("Falha ao carregar sprite shootW.\n"); return -1; } InitShootE(shootE); //funcao que inicializa habilidade de escudo (shield / resistor) if(!shootE.bitmap) { al_destroy_display(display); printf("Falha ao carregar sprite shield.\n"); return -1; } InitObstacle(obstacle); //funcao que inicializa obstaculos InitBoss(boss, &NUM_BOSS); //funcao que inicializa chefes (bosses) InitBackground(background, letra); //funcao que inicializa sprite de background InitBackground1(background1, letra); //funcao que inicializa sprite de background1 alternativo InitBackground2(background2, letra); //funcao que inicializa sprite de background2 alternativo InitBackground3(background3, letra); //funcao que inicializa sprite de background3 alternativo InitBackground4(background4, letra); //funcao que inicializa sprite de background4 alternativo InitBackground5(background5, letra); //funcao que inicializa sprite de background4 alternativo InitBackground6(background6, letra); //funcao que inicializa sprite de background4 alternativo InitEnemyredSprite(enemyred_sprite); // funcao que inicializa sprite de inimigo vermelho 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)); al_start_timer(timer); while (!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); //se clicar para fechar a janela if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } //evento do timer (vai entrar nesse else if sempre, a nao ser que feche a janela) else if(ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; if(keys[RIGHT] && !player.moving) { player.velx = player.speed; player.moving = true; } if(keys[LEFT] && !player.moving) { player.velx = player.speed; player.moving = true; } ChangeColor(&text_color, player, boss, &NUM_BOSS, &text_boss); PlayerJump(player, &keys[UP]); PlayerRight(player, &keys[RIGHT], scientist); PlayerLeft(player, &keys[LEFT]); //updates UpdateShootQ(shootQ, player); UpdateShootW(shootW, player); UpdateShootE(shootE, player); UpdateEnemyRed(enemyred, &NUM_ENEMYRED, player, shootQ); UpdateEnemyBlue(enemyblue, &NUM_ENEMYBLUE, player, shootW); UpdateObstacle(obstacle, medium_font, player); UpdateBoss(boss, &NUM_BOSS, &text_boss, player, enemyred, &NUM_ENEMYRED, enemyblue, &NUM_ENEMYBLUE); //colisoes ShootQColisionEnemyRed(shootQ,enemyred, &NUM_ENEMYRED, player); ShootWColisionEnemyBlue(shootW, enemyblue, &NUM_ENEMYBLUE, player); ShootColisionBoss(shootW, shootQ, boss, &NUM_BOSS, player); PlayerColisionEnemyBlue(player, enemyblue, &NUM_ENEMYBLUE); PlayerColisionEnemyRed(player, enemyred, &NUM_ENEMYRED); PlayerColisionObstacle(player,obstacle); PlayerColisionBoss(player, boss, &NUM_BOSS); ResetPlayer(player, enemyred, &NUM_ENEMYRED, enemyblue, &NUM_ENEMYBLUE, obstacle, boss, &NUM_BOSS, &text_color); } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_Q: keys[Q] = true; FireShootQ(shootQ, player); break; case ALLEGRO_KEY_W: keys[W] = true; FireShootW(shootW, player); break; case ALLEGRO_KEY_E: keys[E] = true; FireShootE(shootE, player); break; case ALLEGRO_KEY_R: keys[R] = true; break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = false; player.moving = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; player.moving = false; break; case ALLEGRO_KEY_Q: keys[Q] = false; break; case ALLEGRO_KEY_W: keys[W] = false; break; case ALLEGRO_KEY_E: keys[E] = false; break; case ALLEGRO_KEY_R: keys[R] = false; break; } } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; //desenhar objetos DrawBackground(background, letra); DrawBackground1(background1, letra); DrawBackground2(background2, letra); DrawBackground3(background3, letra); DrawBackground4(background4, letra); DrawBackground5(background5, letra); DrawBackground6(background6, letra); DrawText(title_font, medium_font, player, boss, &NUM_BOSS, &text_color, &text_boss); DrawShootQ(shootQ); DrawShootW(shootW); DrawShootE(shootE, player); DrawEnemyRed(enemyred, &NUM_ENEMYRED, player, enemyred_sprite); DrawEnemyBlue(enemyblue, &NUM_ENEMYBLUE, player); DrawBoss(boss, &NUM_BOSS, player); DrawObstacle(obstacle); DrawScientist(player, scientist, &keys[LEFT], &keys[RIGHT]); al_flip_display(); } } al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_font(title_font); al_destroy_font(medium_font); al_destroy_display(display); al_destroy_bitmap(scientist.bitmap); al_destroy_bitmap(shootE.bitmap); for(b=0; b<background.frame_max; b++) { al_destroy_bitmap(background.image[b]); } for(b=0; b<background1.frame_max; b++) { al_destroy_bitmap(background1.image[b]); } for(b=0; b<background2.frame_max; b++) { al_destroy_bitmap(background2.image[b]); } for(b=0; b<background3.frame_max; b++) { al_destroy_bitmap(background3.image[b]); } for(b=0; b<background4.frame_max; b++) { al_destroy_bitmap(background4.image[b]); } for(b=0; b<background5.frame_max; b++) { al_destroy_bitmap(background5.image[b]); } for(b=0; b<background6.frame_max; b++) { al_destroy_bitmap(background6.image[b]); } return 0; }//final da MAIN!!
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; }
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); }
int main(void) { // primitive variables bool done = false; // for game loop bool redraw = true; // for redraw. const int FPS = 60; // Frames Per Second bool isGameOver = false; // initialize // object variables SpaceShip ship, ship2; Bullet bullet[NUM_BULLETS]; Bullet bullet2[NUM_BULLETS]; // Initialize ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL ; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font18 = NULL; ALLEGRO_BITMAP *image1 = NULL , *image2 = NULL; if(!al_init()) return -1; display = al_create_display(WIDTH, HEIGHT); if(!display) return -1; // initializing primitives (for drawing ship) al_init_primitives_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); al_init_image_addon(); event_queue = al_create_event_queue(); timer = al_create_timer(1.0/FPS); // initialize objects srand(time(NULL)); // sees number generator with current time. // as time changes, the random number changes too. InitShip(ship); InitShip2(ship2); InitBullet(bullet, NUM_BULLETS); // array of bullets for ship InitBullet(bullet2, NUM_BULLETS); // array of bullets for ship2 font18 = al_load_font("Arial.ttf", 18, 0); image1 = al_load_bitmap("Ship1.bmp"); image2 = al_load_bitmap("Ship2.bmp"); // register keyboard. 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)); // START TIMER al_start_timer(timer); while(!done) { ALLEGRO_EVENT ev; // wait for event to come in from queue. al_wait_for_event(event_queue, &ev); // only happens once every 60 seconds max. if (ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; // update the position of the ship, depending if the keys are pressed. if(keys[UP]) MoveShipUp(ship2); if(keys[DOWN]) MoveShipDown(ship2); if(keys[LEFT]) MoveShip2Left(ship2); if(keys[RIGHT]) MoveShip2Right(ship2); if(keys[W]) MoveShipUp(ship); if(keys[S]) MoveShipDown(ship); if(keys[A]) MoveShipLeft(ship); if(keys[D]) MoveShipRight(ship); if(!isGameOver) { UpdateBullet(bullet, NUM_BULLETS); // update the position of the bullet UpdateBullet2(bullet2, NUM_BULLETS); // test if all the objects collide after all the objects move. CollideBullet(bullet, NUM_BULLETS, ship2, ship); CollideBullet2(bullet2, NUM_BULLETS, ship, ship2); if(ship.lives <= 0 || ship2.lives <=0) isGameOver = true; } } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) done = true; else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = true; FireBullet2(bullet2, NUM_BULLETS, ship2); // break to fire one bullet only break; case ALLEGRO_KEY_W: keys[W] = true; break; case ALLEGRO_KEY_A: keys[A] = true; break; case ALLEGRO_KEY_S: keys[S] = true; break; case ALLEGRO_KEY_D: keys[D] = true; break; case ALLEGRO_KEY_E: keys[E] = true; FireBullet(bullet, NUM_BULLETS, ship); // break to fire one bullet only break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = false; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = false; break; case ALLEGRO_KEY_W: keys[W] = false; break; case ALLEGRO_KEY_A: keys[A] = false; break; case ALLEGRO_KEY_S: keys[S] = false; break; case ALLEGRO_KEY_D: keys[D] = false; break; case ALLEGRO_KEY_E: keys[E] = false; // break to fire one bullet only break; } } // if redraw is true and no queue for event. if ( redraw && al_is_event_queue_empty(event_queue)) { redraw = false; if (!isGameOver) { // draws the latest position of bullet and ship that has been updated. DrawShip(ship, image1); // Draw ship DrawShip(ship2, image2); DrawBullet(bullet, NUM_BULLETS); // draw bullets DrawBullet(bullet2, NUM_BULLETS); al_draw_textf(font18, al_map_rgb(255,0,255), 5, 5, 0, "Player 1 Lives left: %i \nScore: %i\n", ship.lives, ship.score); al_draw_textf(font18, al_map_rgb(255,0,255), 50, 50, 0, "Player 2Lives left: %i \nScore: %i\n", ship2.lives, ship2.score); } else { al_draw_textf(font18, al_map_rgb(0,255,255), WIDTH/2, HEIGHT/2, ALLEGRO_ALIGN_CENTRE, "GAME OVER. P1 Final Score: %i\n P2 Final Score %i",ship.score, ship2.score); } al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } } al_destroy_display(display); return 0; }
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; }
int main(){ /*VARIABLES*/ /*shell variables*/ bool done=false; bool render=false; /*project variables*/ Player* player = NULL; Stick* stick = NULL; ALLEGRO_BITMAP* playerImg=NULL; ALLEGRO_BITMAP* stickImg=NULL; // ===================== /*ALLEGRO_VARIABLES*/ ALLEGRO_DISPLAY* display = NULL; ALLEGRO_EVENT_QUEUE* eq = NULL; ALLEGRO_TIMER* timer = NULL; ALLEGRO_FONT* font18 = NULL; // ===================== /*ALLEGRO_INIT*/ if(!al_init()) return -1; display = al_create_display(WIDTH,HEIGHT); if(!display) return -1; // ====================== /*ADDON_INSTALL*/ al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); // font before ttf always al_init_ttf_addon(); al_init_primitives_addon(); // ====================== /*PROJECT_INIT*/ srand(time(NULL)); font18 = al_load_font("assets/FreeMonoBold.ttf",18,0); playerImg=al_load_bitmap("assets/player.png"); stickImg=al_load_bitmap("assets/stick.png"); al_convert_mask_to_alpha(playerImg,al_map_rgb(255,0,255)); player = new Player(); player->init(playerImg); stick = new Stick(); stick->initImg(stickImg); stick->init(rand()%(WIDTH-32),rand()%(HEIGHT-32),0,0,0,0,32,32); // ====================== /* TIMER AND START_UP */ eq = al_create_event_queue(); timer = al_create_timer(1.0/60); al_start_timer(timer); /* register events */ al_register_event_source(eq,al_get_timer_event_source(timer)); al_register_event_source(eq,al_get_keyboard_event_source()); al_register_event_source(eq,al_get_display_event_source(display)); // ====================== /* THE LOOP */ while(!done){ ALLEGRO_EVENT ev; al_wait_for_event(eq,&ev); switch(ev.type){ case ALLEGRO_EVENT_KEY_DOWN: switch(ev.keyboard.keycode){ case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP]=true; break; case ALLEGRO_KEY_DOWN: keys[DOWN]=true; break; case ALLEGRO_KEY_LEFT: keys[LEFT]=true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT]=true; break; case ALLEGRO_KEY_SPACE: keys[SPACE]=true; break; } break; case ALLEGRO_EVENT_KEY_UP: switch(ev.keyboard.keycode){ case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP]=false; break; case ALLEGRO_KEY_DOWN: keys[DOWN]=false; break; case ALLEGRO_KEY_LEFT: keys[LEFT]=false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT]=false; break; case ALLEGRO_KEY_SPACE: keys[SPACE]=false; break; } break; case ALLEGRO_EVENT_DISPLAY_CLOSE: done=true; break; /*UPDATE*/ case ALLEGRO_EVENT_TIMER: render = true; if(keys[UP]){ player->moveUp(); // force one direction movement No diagonal movement keys[RIGHT]=false; keys[LEFT]=false; }else if(keys[DOWN]){ player->moveDown(); // force one direction movement No diagonal movement keys[RIGHT]=false; keys[LEFT]=false; }else // we should rest the animation for the player here player->restAnimation(1); if(keys[LEFT]){ player->moveLeft(); // force one direction movement No diagonal movement keys[UP]=false; keys[DOWN]=false; }else if(keys[RIGHT]){ player->moveRight(); // force one direction movement No diagonal movement keys[UP]=false; keys[DOWN]=false; }else // and rest it it here also. player->restAnimation(0); player->update(); stick->update(); if(stick->checkCollision(player)){ stick->collided(player); stick->init(rand()%(WIDTH-32),rand()%(HEIGHT-32),0,0,0,0,32,32); } break; // ================== } /*RENDER*/ if(render && al_is_event_queue_empty(eq)){ render = false; // do rendering here player->render(); stick->render(); al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Score: %i",player->getScore()); al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } // ================== } // ====================== /*DESTROY*/ al_destroy_display(display); al_destroy_timer(timer); al_destroy_event_queue(eq); al_destroy_font(font18); al_destroy_bitmap(playerImg); al_destroy_bitmap(stickImg); delete player; delete stick; return 0; }
//----------------------------------------------------------------------------------------------- // Nome: init // Desc: Foi criada uma função somente para inicialização dos principais componentes // Dessa forma, fica mais fácil a identificação de problemas na declaração de: // janelas // imagens // fontes //---------------------------------------------------------------------------------------------- int init() { // Inicialização da biblioteca Allegro if (al_init() == NULL) { fprintf(stderr, "Falha ao inicializar a Allegro.\n"); return -1; } janela_principal = al_create_display(LARGURA_MAX, ALTURA_MAX); // Criamos a nossa janela - dimensões de 600*400 px // Criação da janela if (janela_principal == NULL) { fprintf(stderr, "Falha ao criar janela.\n"); return -1; } // Inicialização dos addons de imagens if (al_init_image_addon() == NULL) { fprintf(stderr, "Falha ao inicializar addon de Imagens.\n"); return -1; } // Inicialização do teclado if (al_install_keyboard() == NULL) { fprintf(stderr, "Falha ao inicializar teclado.\n"); return -1; } // Inicialização dos addons primitivos if (al_init_primitives_addon() == NULL) { fprintf(stderr, "Falha ao inicializar Addon primitivos.\n"); return -1; } // Inicialização do mouse if (al_install_mouse() == NULL) { fprintf(stderr, "Falha ao inicializar Mouse.\n"); return -1; } // Inicialização do add-on para uso de fontes al_init_font_addon(); // Inicialização do add-on para uso de fontes True Type if (al_init_ttf_addon() == NULL) { fprintf(stderr, "Falha ao inicializar add-on allegro_ttf.\n"); return -1; } fonte_menu = al_load_font("fonts/ALGER.TTF", 18, 0); // Carregando o arquivo de fonte // Retorna erro caso o arquivo de fonte não seja encontrado if (fonte_menu == NULL) { al_destroy_display(janela_principal); fprintf(stderr, "Falha ao carregar fonte ALGER.\n"); return -1; } eventos = al_create_event_queue(); // Criamos o nosso evento para o teclado // Retorna erro caso ocorra algum problema ao criar a fila de eventos if (eventos == NULL) { fprintf(stderr, "Falha ao criar fila de eventos.\n"); al_destroy_display(janela_principal); return -1; } al_set_window_title(janela_principal, "Projeto Final"); // Definimos o título do programa return 0; }
//---------------------------------------------- // Nome: escreve_jogar // Desc: Esta função pede ao usuário as posições de tudo que é necessário para a execução do jogo //---------------------------------------------- void escreve_jogar(int **matriz) { // Esse vetor de (char *) foi criado para diminuir a quantidade de código (basicamente: if) da função. O vetor depende da dificuldade char *texto_inicial[5] = {"A dificuldade 1 consiste em escolher:", "A dificuldade 2 consiste em escolher:", "A dificuldade 3 consiste em escolher:", "A dificuldade 4 consiste em escolher:", "A dificuldade 5 consiste em escolher:"}; // Esse vetor de (char *) foi criado para diminuir a quantidade de código (basicamente: if) da função. O vetor depende da dificuldade char *bonus = {"> O Bonus"}; ALLEGRO_FONT *fonte_jogar = al_load_font("fonts/AGENCYB.TTF", 14, 0); // Carrega o arquivo de fonte bool parar_obstaculos = false; // A seguinte variável foi criada para facilitar a leitura do código do programa int tamanho_matriz = dificuldade * 10; // // As seguintes variáveis foram criadas para converter as coordenadas do mouse e armazenar as nas células da matriz // int pos_x; int pos_y; int linha_inicial; int coluna_inicial; int linha_final; int coluna_final; int linha_alvo; int coluna_alvo; int linha_obstaculo; int coluna_obstaculo; int linha_bonus; int coluna_bonus; int custo_total; int custo_aux; int custo_aux2; // // Fim da declaração das variáveis // al_draw_text(fonte_jogar, al_map_rgb(0, 0, 0), LARGURA_MAX / 2, 310, ALLEGRO_ALIGN_CENTRE, texto_inicial[dificuldade - 1]); // Escreve o texto central // // As seguintes funções escrevem no espaço determinado o que tem que ser escolhido pelo usuário // al_draw_text(fonte_jogar, al_map_rgb(0, 0, 0), 20, 340, NULL, "> A Posicao Inicial"); al_draw_text(fonte_jogar, al_map_rgb(0, 0, 0), 20, 375, NULL, "> A Posicao Final"); al_draw_text(fonte_jogar, al_map_rgb(0, 0, 0), 250, 340, NULL, "> Obstaculo (ENTER para cancelar)"); al_draw_text(fonte_jogar, al_map_rgb(0, 0, 0), 250, 375, NULL, bonus); // // Fim das funções que escrevem as escolhas necessárias // al_flip_display(); // Atualiza a tela // Caso a opção de existir labirinto seja verdadeira if (labirinto == true) { matriz = carrega_labirinto(dificuldade); // Chama a função responsável por gerar, aleatoriamente, um labirinto perfeito imprime_matriz(matriz, dificuldade); // Imprime o labirinto no espaço reservado al_flip_display(); // Atualiza tela } // // ---------------------------------------------------------------------------------------- // O seguinte do while é utilizado para que o usuário entre com a posição inicial do jogo // ---------------------------------------------------------------------------------------- // // O seguinte bloco de comando é executado enquanto o usuário não digita uma posição inicial válida do { pos_x = 0; // Zera a variável pos_y = 0; // Zera a variável al_draw_text(fonte_jogar, al_map_rgb(255, 0, 0), 20, 340, NULL, "> A Posicao Inicial"); // Pinta o texto para melhor visualização al_flip_display(); // Atualiza a tela inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Ativa quando o usuário clicar com algum botão do mouse { if (ev.mouse.button & 1) { // quando o usuário clicar com o botão esquerdo do mouse as coordenadas serão armazenadas em variáveis pos_x = pos_x_mouse; pos_y = pos_y_mouse; if (pos_y <= 300) { coluna_inicial = (pos_x * tamanho_matriz) / 600; // Converte a coordenada do mouse em coluna // Precisa ser verificado o nível de dificuldade 4, pois o tamanho correto seria 15x7.5 px, mas não é possível if (dificuldade == 4) linha_inicial = (pos_y * tamanho_matriz ) / 280; // Converte a coordenada do mouse em linha else linha_inicial = (pos_y * tamanho_matriz ) / 300; // Converte a coordenada do mouse em linha // Determina a posição inicial e atualiza a matriz if (matriz[linha_inicial][coluna_inicial] != PAREDE) { matriz[linha_inicial][coluna_inicial] = POS_INICIAL; imprime_matriz(matriz, dificuldade); } } } } } while ( (pos_y >= 300) || (pos_y == 0) || (matriz[linha_inicial][coluna_inicial] == PAREDE) ); // // -------------------------------------------------------------------------------------- // O seguinte do while é utilizado para que o usuário entre com a posição final do jogo // -------------------------------------------------------------------------------------- // // O seguinte bloco de comando é executado enquanto o usuário não digita uma posição final válida do { pos_x = 0; // Zera variável pos_y = 0; // Zera variável al_draw_text(fonte_jogar, al_map_rgb(0, 0, 255), 20, 375, NULL, "> A Posicao Final"); // Pinta o texto para melhor visualização al_flip_display(); // Atualiza tela inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Ativa quando o usuário clicar com algum botão do mouse { if (ev.mouse.button & 1) { // quando o usuário clicar com o borão esquerdo do mouse as coordenadas serão armazenadas em variáveis pos_x = pos_x_mouse; pos_y = pos_y_mouse; if (pos_y <= 300) { coluna_final = (pos_x * tamanho_matriz ) / 600; // Converte a coordenada do mouse em coluna // Precisa ser verificado o nível de dificuldade 4, pois o tamanho correto seria 15x7.5 px, mas não é possível if (dificuldade == 4) linha_final = (pos_y * tamanho_matriz ) / 280; // Converte a coordenada do mouse em linha else linha_final = (pos_y * tamanho_matriz) / 300; // Converte a coordenada do mouse em linha // Determina a posição final e atualiza a matriz if ( ( (linha_final != linha_inicial) || (coluna_final != coluna_inicial) ) && (matriz[linha_final][coluna_final] != PAREDE) ) { matriz[linha_final][coluna_final] = POS_FINAL; imprime_matriz(matriz, dificuldade); } } } } } while ( (pos_y >= 300) || (pos_y == 0) || ( (linha_final == linha_inicial) && (coluna_final == coluna_inicial) ) || (matriz[linha_final][coluna_final] == PAREDE) ); // // ---------------------------------------------------------------------------------------- // O seguinte do while é utilizado para que o usuário entre com a posição do alvo do jogo // ---------------------------------------------------------------------------------------- // // O seguinte bloco de comando é executado enquanto o usuário não digita uma posição válida do { pos_x = 0; // Zera variável pos_y = 0; // Zera variável //*******al_draw_text(fonte_jogar, al_map_rgb(0, 0, 255), 20, 375, NULL, "> A Posicao Final"); // Pinta o texto para melhor visualização al_flip_display(); // Atualiza tela inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Ativa quando o usuário clicar com algum botão do mouse { if (ev.mouse.button & 1) { // quando o usuário clicar com o borão esquerdo do mouse as coordenadas serão armazenadas em variáveis pos_x = pos_x_mouse; pos_y = pos_y_mouse; if (pos_y <= 300) { coluna_alvo = (pos_x * tamanho_matriz ) / 600; // Converte a coordenada do mouse em coluna // Precisa ser verificado o nível de dificuldade 4, pois o tamanho correto seria 15x7.5 px, mas não é possível if (dificuldade == 4) linha_alvo = (pos_y * tamanho_matriz ) / 280; // Converte a coordenada do mouse em linha else linha_alvo = (pos_y * tamanho_matriz) / 300; // Converte a coordenada do mouse em linha // Determina a posição do alvo e atualiza a matriz if ( ( (linha_alvo != linha_inicial) || (coluna_alvo != coluna_inicial) ) || ( (linha_alvo != linha_final) || (coluna_alvo != coluna_final) ) && (matriz[linha_alvo][coluna_alvo] != PAREDE) ) { matriz[linha_alvo][coluna_alvo] = ALVO; imprime_matriz(matriz, dificuldade); } } } } } while ( (pos_y >= 300) || (pos_y == 0) || ( (linha_alvo == linha_inicial) && (coluna_alvo == coluna_inicial) ) || ( (linha_alvo == linha_final) && (coluna_alvo == coluna_final) ) || (matriz[linha_alvo][coluna_alvo] == PAREDE) ); // // ------------------------------------------------------------------------------------------ // O seguinte for é utilizado para que o usuário entre com a posição dos obstáculos do jogo // ------------------------------------------------------------------------------------------ // // O seguinte bloco de comando será executado até que o usuário digite ENTER (para cancelar a entrada de obstáculos) do { pos_x = 0; // Zera variável pos_y = 0; // Zera variável al_draw_text(fonte_jogar, al_map_rgb(255, 165, 0), 250, 340, NULL, "> Obstaculo (ENTER para cancelar)"); // Pinta o texto para melhor visualização al_flip_display(); // Atualiza tela // O seguinte bloco de comando só será executado caso a opção obstaculo esteja habilitada if (obstaculo == true) { // O seguinte bloco de comando é executado enquanto o usuário não digita uma posição válida para o obstáculo do { inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código // O seguinte bloco de comando será executado caso o usuário entre com a tecla ENTER if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ENTER: parar_obstaculos = true; break; } // O seguinte break é necessário para que, ao apertar a tecla ENTER, o usuário não precise entrar com mais um obstáculo break; } if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Ativa quando o usuário clicar com algum botão do mouse { if (ev.mouse.button & 1) { // quando o usuário clicar com o botão esquerdo do mouse as coordenadas serão armazenadas em variáveis pos_x = pos_x_mouse; pos_y = pos_y_mouse; } if (pos_y <= 300) { coluna_obstaculo = (pos_x * tamanho_matriz) / 600; // Converte a coordenada do mouse em coluna // Precisa ser verificado o nível de dificuldade 4, pois o tamanho correto seria 15x7.5 px, mas não é possível if (dificuldade == 4) linha_obstaculo = (pos_y * tamanho_matriz) / 280; // Converte a coordenada do mouse em linha else linha_obstaculo = (pos_y * tamanho_matriz) / 300; // Converte a coordenada do mouse em linha // Determina a posição dos obstáculos e atualiza a matriz if ( ( ( (linha_obstaculo != linha_inicial) || (coluna_obstaculo != coluna_inicial) ) && ( (linha_obstaculo != linha_final) || (coluna_obstaculo != coluna_final) ) && ( (linha_obstaculo != linha_alvo) || (coluna_obstaculo != coluna_alvo) ) ) && (matriz[linha_obstaculo][coluna_obstaculo] != PAREDE) ) { if (matriz[linha_obstaculo][coluna_obstaculo] != OBSTACULO) matriz[linha_obstaculo][coluna_obstaculo] = OBSTACULO; else if (matriz[linha_obstaculo][coluna_obstaculo] == OBSTACULO) matriz[linha_obstaculo][coluna_obstaculo] = CAMPO_VAZIO; imprime_matriz(matriz, dificuldade); } } } } while( (pos_y >= 300) || (pos_y == 0) || ( (linha_obstaculo == linha_inicial) && (coluna_obstaculo == coluna_inicial) ) || ( (linha_obstaculo == linha_final) && (coluna_obstaculo == coluna_final) ) || (matriz[linha_obstaculo][coluna_obstaculo] == PAREDE) ); } // Sai do bloco de comandos caso a opção obstaculo esteja desabilitada else break; } while (parar_obstaculos == false); // // ------------------------------------------------------------------------------------- // O seguinte for é utilizado para que o usuário entre com a posição dos bônus do jogo // ------------------------------------------------------------------------------------- // // O seguinte bloco de comando será executado até que o usuário entre com o número correto de bônus do { pos_x = 0; // Zera variável pos_y = 0; // Zera variável al_draw_text(fonte_jogar, al_map_rgb(0, 186, 255), 250, 375, NULL, bonus); // Pinta o texto para melhor visualização al_flip_display(); // Atualiza tela inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Ativa quando o usuário clicar com algum botão do mouse { if (ev.mouse.button & 1) { // quando o usuário clicar com o botão esquerdo do mouse as coordenadas serão armazenadas em variáveis pos_x = pos_x_mouse; pos_y = pos_y_mouse; } if (pos_y <= 300) { coluna_bonus = (pos_x * tamanho_matriz) / 600; // Converte a coordenada do mouse em coluna // Precisa ser verificado o nível de dificuldade 4, pois o tamanho correto seria 15x7.5 px, mas não é possível if (dificuldade == 4) linha_bonus = (pos_y * tamanho_matriz) / 280; // Converte a coordenada do mouse em linha else linha_bonus = (pos_y * tamanho_matriz) / 300; // Converte a coordenada do mouse em linha // Determina a posição dos bônus e atualiza a matriz if ( ( ( ( (linha_bonus != linha_inicial) || (coluna_bonus != coluna_inicial) ) && ( (linha_bonus != linha_final) || (coluna_bonus != coluna_final) ) && ( (linha_bonus != linha_alvo) || (coluna_bonus != coluna_alvo) ) ) && (matriz[linha_bonus][coluna_bonus] != PAREDE) ) ) { matriz[linha_bonus][coluna_bonus] = BONUS; imprime_matriz(matriz, dificuldade); } } } } while( (pos_y >= 300) || (pos_y == 0) || ( (linha_bonus == linha_inicial) && (coluna_bonus == coluna_inicial) ) || ( (linha_bonus == linha_final) && (coluna_bonus == coluna_final) ) || ( (linha_bonus == linha_alvo) && (coluna_bonus == coluna_alvo) ) || ( (matriz[linha_bonus][coluna_bonus] == PAREDE) ) ); // O próximo bloco de comandos será realizado até que a variável fechar seja igual a true do { al_flip_display(); // Atualiza a tela inicializa_evento(); // Função utilizada para melhorar o programa em termos de visualização de código if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) // Quando o usuário apertar algum botão do mouse { if((ev.mouse.button & 1) && (pos_x_mouse >= 536) && (pos_x_mouse <= 595) && (pos_y_mouse >= 374) && (pos_y_mouse <= 393)) break; // Volta para o menu principal Caso seja selecionado o botão "VOLTAR" else if((ev.mouse.button & 1) && (pos_x_mouse >= 536) && (pos_x_mouse <= 595) && (pos_y_mouse >= 306) && (pos_y_mouse <= 325)) { custo_total = procura_caminho(tamanho_matriz, matriz, linha_inicial, coluna_inicial, linha_alvo, coluna_alvo, false) + procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_final, coluna_final, false); // Caso seja selecionado o botão "INICIAR" custo_aux = procura_caminho(tamanho_matriz, matriz, linha_inicial, coluna_inicial, linha_alvo, coluna_alvo, false) + procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_bonus, coluna_bonus, false) + procura_caminho(tamanho_matriz, matriz, linha_bonus, coluna_bonus, linha_final, coluna_final, false) - (BONUS * 10 * dificuldade); custo_aux2 = procura_caminho(tamanho_matriz, matriz, linha_inicial, coluna_inicial, linha_bonus, coluna_bonus, false) + procura_caminho(tamanho_matriz, matriz, linha_bonus, coluna_bonus, linha_alvo, coluna_alvo, false) + procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_final, coluna_final, false) - (BONUS * 10 * dificuldade); } if ( (custo_total <= custo_aux) && (custo_total <= custo_aux2) ) { procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_inicial, coluna_inicial, true); procura_caminho(tamanho_matriz, matriz, linha_final, coluna_final, linha_alvo, coluna_alvo, true); } else if ( (custo_aux <= custo_total) && (custo_aux <= custo_aux2) ) { procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_inicial, coluna_inicial, true); procura_caminho(tamanho_matriz, matriz, linha_bonus, coluna_bonus, linha_alvo, coluna_alvo, true); procura_caminho(tamanho_matriz, matriz, linha_final, coluna_final, linha_bonus, coluna_bonus, true); } else { procura_caminho(tamanho_matriz, matriz, linha_bonus, coluna_bonus, linha_inicial, coluna_inicial, true); procura_caminho(tamanho_matriz, matriz, linha_alvo, coluna_alvo, linha_bonus, coluna_bonus, true); procura_caminho(tamanho_matriz, matriz, linha_final, coluna_final, linha_alvo, coluna_alvo, true); } } } while(!fechar); al_destroy_font(fonte_jogar); // Finaliza a fonte }
int main(int argc, char **argv) { al_init(); al_install_mouse(); al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); al_set_new_display_flags(ALLEGRO_WINDOWED|ALLEGRO_RESIZABLE); ALLEGRO_DISPLAY *display = al_create_display(640, 480); ALLEGRO_DISPLAY *tooldisplay = al_create_display(200, 480); al_set_window_position(tooldisplay, 10, 0); al_set_window_position(display, 220, 0); ALLEGRO_DISPLAY *current_display = tooldisplay; ALLEGRO_TIMER* timer = al_create_timer(1); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display); al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)tooldisplay); 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)); ALLEGRO_FONT* font = al_load_font("data/DejaVuSans.ttf", 12, 0); if(!font) font = al_load_font("examples/data/DejaVuSans.ttf", 12, 0); Layout layout; Layout_controller layout_controller; layout_controller.Set_layout(&layout); Tree* widget_tree = layout_controller.Get_skin().Clone<Tree>("tree"); widget_tree->Set_text("Desktop"); widget_tree->Select(); Widget* root_widget = layout_controller.Get_skin().Clone<Desktop>("desktop"); root_widget->Set_position(Vector2(0, 0)); root_widget->Set_size(Vector2(640, 480)); layout_controller.Set_tree(widget_tree, root_widget); layout_controller.Set_root(root_widget); layout_controller.Set_root_tree(widget_tree); layout_controller.Select_tree(widget_tree); layout.Set_skin(&layout_controller.Get_skin()); layout.Add_widget("root", root_widget, NULL); Editor_controller editor_controller; editor_controller.Set_layout_display(display); editor_controller.Set_layout_controller(layout_controller); editor_controller.Load(layout_controller.Get_skin()); //FPS Label* fps_label = layout_controller.Get_skin().Clone<Label>("label"); fps_label->Set_text("FPS: 100"); //Main vbox Vertical_box* toolvbox = layout_controller.Get_skin().Clone<Vertical_box>("vertical box"); toolvbox->Add(editor_controller.Get_root()); toolvbox->Add(fps_label); Slider_box* slider_box = layout_controller.Get_skin().Clone<Slider_box>("slider box"); slider_box->Set_child(toolvbox); Desktop* desktop = layout_controller.Get_skin().Clone<Desktop>("desktop"); desktop->Set_child(slider_box); desktop->Set_position(Vector2(0, 0)); desktop->Set_size(Vector2(200, 480)); Widget* toolroot = desktop; al_start_timer(timer); bool quit = false; while (!quit) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if (ALLEGRO_EVENT_KEY_DOWN == event.type) { if (ALLEGRO_KEY_ESCAPE == event.keyboard.keycode) { quit=true; } } if (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type) { quit=true; } if (ALLEGRO_EVENT_DISPLAY_RESIZE == event.type) { al_acknowledge_resize(event.display.source); if(event.display.source == display) layout_controller.Get_root()->Set_size(Vector2(event.display.width-20, event.display.height-20)); } if (ALLEGRO_EVENT_DISPLAY_SWITCH_IN == event.type) { current_display = event.display.source; } if(current_display == tooldisplay) { toolroot->Handle_event(event); } if(current_display == display) { layout_controller.Get_root()->Handle_event(event); } if(ALLEGRO_EVENT_TIMER == event.type) { double dt = al_get_timer_speed(timer); editor_controller.Update(); layout_controller.Get_skin().Update(dt); al_set_target_backbuffer(display); layout_controller.Get_root()->Render(); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); al_set_target_backbuffer(tooldisplay); toolroot->Render(); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); double fps = 1 / dt; std::stringstream ss; ss<<fps; std::string fps_string; ss>>fps_string; fps_label->Set_text((std::string("FPS: ")+fps_string).c_str()); if(dt < 1 && event.timer.count < al_get_timer_count(timer) - 4) { dt = dt * 1.1; al_set_timer_speed(timer, dt); //print("Tick too fast, setting speed to " .. timer_speed); } if(event.timer.count == al_get_timer_count(timer)) { dt = dt * 0.9; al_set_timer_speed(timer, dt); //print("Tick too fast, setting speed to " .. timer_speed); } al_rest(0.001); } }
ALLEGRO_FONT* Text::load_font(char *font,int size){ return al_load_font(font,size,0); }
int MonopolyGame::loadResources() { reset(); // Normalize the paths. ALLEGRO_PATH *path = al_get_standard_path( ALLEGRO_RESOURCES_PATH ); al_append_path_component( path, "etc" ); al_change_directory( al_path_cstr( path, '/' ) ); // change the working directory // // Load the board's bitmap // al_set_path_filename(path, "board.png"); if( !fileExists( al_path_cstr(path, '/') ) ) { fprintf( stderr, "[ERROR] Cannot find bitmap: %s\n", al_path_cstr(path, '/') ); return -1; } else { m_alBoardImage = al_load_bitmap( al_path_cstr(path, '/') ); if( !m_alBoardImage ) { fprintf( stderr, "[ERROR] Failed loading board bitmap: %s\n", al_path_cstr(path, '/') ); return -1; } } // // Load the font set. // al_set_path_filename(path, "Emblem.ttf"); // Start building the fonts from 24pt. int initialSize = 24; if( !fileExists( al_path_cstr(path, '/') ) ) { fprintf( stderr, "[ERROR] Cannot find font file: %s\n", al_path_cstr(path, '/') ); return -1; } else { for( int fontCounter = 0; fontCounter < MAX_FONTS; fontCounter++ ) { m_fontCollection[fontCounter] = al_load_font( al_path_cstr(path, '/'), initialSize, 0 ); initialSize += 10; if( !m_fontCollection[fontCounter] ) { fprintf( stderr, "[ERROR] Failed loading font: %s size: %i\n", al_path_cstr(path, '/'), initialSize ); return -1; } } } // Now load the possible player pieces into memory. // The piece file locations are stored in the database. for( int pieceCounter = 0; pieceCounter < PLAYER_PIECES_COUNT; pieceCounter++ ) { std::string tempQuery = ""; std::string sFileName = ""; tempQuery = m_sqlConn.Format( "SELECT %s FROM %s WHERE %s = %i", "path", DB_PIECES_TABLE, "id", pieceCounter ); if( !m_sqlConn.SelectStr( sFileName, tempQuery.c_str() ) ) { // Append the filename to the resource path. al_set_path_filename( path, sFileName.c_str() ); if( !fileExists( al_path_cstr(path, '/') ) ) { fprintf( stderr, "[ERROR] Cannot find bitmap: %s\n", al_path_cstr(path, '/') ); return -1; } else { // Load the bitmap from the filename from above. m_alpieceImages[pieceCounter] = al_load_bitmap( al_path_cstr(path, '/') ); } if( !m_alpieceImages[pieceCounter] ) { // TODO: CURRENTLY I HAVE NO PLACE HOLDER IMAGES, SO THE APPLICATION WILL FAIL HERE! fprintf( stderr, "[ERROR] Failed loading bitmap: %s\n", al_path_cstr(path, '/') ); return -1; } } else { fprintf( stderr, "[ERROR] Error processing SQL statement: %s\n", tempQuery.c_str() ); return -1; } } // Assign random pieces to each player. for( int plCount = 0; plCount < NUM_PLAYERS; plCount++ ) { int* randomPlayerSel = rollDice( 1, PLAYER_PIECES_COUNT ); m_playerList[plCount].set_image( m_alpieceImages[randomPlayerSel[0]] ); } al_destroy_path( path ); // // Finally we will pull the property list from the database. // if( buildPropertyList() ) { fprintf( stderr, "Failure building Property List, Please ensure the database is available!\n" ); return -1; } return 0; }
int main(void) { ALLEGRO_DISPLAY *display; ALLEGRO_TIMER *timer; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_BITMAP *bmp; ALLEGRO_BITMAP *mem_bmp; ALLEGRO_BITMAP *disp_bmp; ALLEGRO_FONT *font; char *text; bool done = false; bool redraw = 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(); display = al_create_display(640, 480); if (!display) { abort_example("Error creating display.\n"); return 1; } if (!al_install_keyboard()) { abort_example("Error installing keyboard.\n"); return 1; } font = al_load_font("data/fixed_font.tga", 0, 0); if (!font) { abort_example("Error loading data/fixed_font.tga\n"); return 1; } bmp = disp_bmp = al_load_bitmap("data/mysha.pcx"); if (!bmp) { abort_example("Error loading data/mysha.pcx\n"); return 1; } text = "Display bitmap (space to change)"; al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP); mem_bmp = al_load_bitmap("data/mysha.pcx"); if (!bmp) { abort_example("Error loading data/mysha.pcx\n"); return 1; } timer = al_create_timer(INTERVAL); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); al_register_event_source(queue, al_get_display_event_source(display)); al_start_timer(timer); al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); while (!done) { ALLEGRO_EVENT event; if (redraw && al_is_event_queue_empty(queue)) { update(bmp); al_clear_to_color(al_map_rgb_f(0, 0, 0)); al_draw_tinted_bitmap(bmp, al_map_rgba_f(1, 1, 1, 0.5), bmp_x, bmp_y, bmp_flag); al_draw_text(font, al_map_rgba_f(1, 1, 1, 0.5), 0, 0, 0, text); al_flip_display(); redraw = false; } al_wait_for_event(queue, &event); switch (event.type) { case ALLEGRO_EVENT_KEY_DOWN: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) done = true; else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) { if (bmp == mem_bmp) { bmp = disp_bmp; text = "Display bitmap (space to change)"; } else { bmp = mem_bmp; text = "Memory bitmap (space to change)"; } } break; case ALLEGRO_EVENT_DISPLAY_CLOSE: done = true; break; case ALLEGRO_EVENT_TIMER: redraw = true; break; } } al_destroy_bitmap(bmp); return 0; }
void game_loop (GAME *game) { if (!game) return; ALLEGRO_KEYBOARD_STATE keyboard_state; ALLEGRO_EVENT event; ALLEGRO_FONT *font = al_load_font ("data/fixed_font.tga", 0, 0); SCENE *scene; SPRITE_ACTOR *actor; LIST_ITEM *item; AABB_COLLISIONS collisions; aabb_init_collisions (&collisions); AABB_COLLISIONS portal_collisions; aabb_init_collisions (&portal_collisions); AABB_COLLISIONS npc_collisions; aabb_init_collisions (&npc_collisions); int i = 0; bool redraw = true; float times[NTIMES] = {0}; double frame_time, current_time, new_time, mean_frame_time; double fixed_dt = 1.0 / FPS, dt; double curfps = 0.0; current_time = al_get_time (); al_start_timer (game->timer); float fadeout_duration = 0; float fadein_duration = 0; SCENE_PORTAL *dest_portal = NULL; char *arrow_path = get_resource_path_str ("data/ui/smallarrow_down.png"); ALLEGRO_BITMAP *sel_arrow = al_load_bitmap (arrow_path); while (game->running) { scene = game->current_scene; actor = game->current_actor; if (redraw) { al_clear_depth_buffer (0); tiled_draw_map_back (scene->map, game->screen.tint, game->screen.position.x, game->screen.position.y, game->screen.width, game->screen.height, 0, 0, 0); al_draw_textf (font, al_map_rgba_f (0.9, 0, 0, 1), 5, 5, 0, "FPS: %.2f", curfps); al_set_render_state (ALLEGRO_ALPHA_TEST, true); al_set_render_state (ALLEGRO_DEPTH_TEST, true); al_set_render_state (ALLEGRO_DEPTH_FUNCTION, ALLEGRO_RENDER_GREATER); al_hold_bitmap_drawing (true); sprite_draw (actor, &game->screen); item = _al_list_front (scene->npcs); while (item) { SPRITE_ACTOR *npc_actor = (SPRITE_ACTOR *)_al_list_item_data (item); sprite_draw (npc_actor, &game->screen); item = _al_list_next (scene->npcs, item); } al_hold_bitmap_drawing (false); al_set_render_state (ALLEGRO_DEPTH_TEST, false); al_set_render_state (ALLEGRO_ALPHA_TEST, false); if (false) { item = _al_list_front (portal_collisions.boxes); while (item) { BOX *box = _al_list_item_data (item); box_draw (*box, game->screen.position, al_map_rgb_f (1, 0, 0)); item = _al_list_next (portal_collisions.boxes, item); } aabb_draw (scene->portal_tree, &game->screen, al_map_rgb_f (0, 0, 1)); } tiled_draw_map_fore (scene->map, game->screen.tint, game->screen.position.x, game->screen.position.y, game->screen.width, game->screen.height, 0, 0, 0); if (game->current_npc) { float dx = game->current_npc->actor.box.center.x - game->screen.position.x; float dy = game->current_npc->actor.box.center.y - game->screen.position.y; dx -= al_get_bitmap_width (sel_arrow) * 0.5f; dy -= game->current_npc->actor.box.extent.y * 3.0f; al_draw_bitmap (sel_arrow, dx, dy, 0); } ui_draw (game->ui, &game->screen); if (game->force_vsync) al_wait_for_vsync (); al_flip_display (); redraw = false; } al_wait_for_event (game->event_queue, &event); switch (event.type) { case ALLEGRO_EVENT_TIMER: new_time = al_get_time (); frame_time = new_time - current_time; current_time = new_time; times[i] = frame_time; i = (i + 1) % NTIMES; mean_frame_time = 0.0; for (int j = 0; j < NTIMES; j++) mean_frame_time += times[j]; mean_frame_time /= NTIMES; curfps = 1.0 / mean_frame_time; dt = mean_frame_time / fixed_dt; if (fadeout_duration > 0.0f) { float fadef = fadeout_duration / TRANS_TIME; game->screen.tint = al_map_rgba_f (fadef, fadef, fadef, 1.0); fadeout_duration -= mean_frame_time; if (fadeout_duration <= 0.0f) { fadein_duration = TRANS_TIME; fadeout_duration = 0.0f; game_enter_portal (game, dest_portal); } } if (fadein_duration > 0.0f) { float fadef = 1.0 - fadein_duration / TRANS_TIME; game->screen.tint = al_map_rgba_f (fadef, fadef, fadef, 1.0); fadein_duration -= mean_frame_time; if (fadein_duration <= 0.0f) { game->paused = false; fadein_duration = 0.0f; } } if (game->paused) { redraw = true; break; } al_get_keyboard_state (&keyboard_state); if (al_key_down (&keyboard_state, ALLEGRO_KEY_ESCAPE)) { game->running = false; continue; } if (al_key_down (&keyboard_state, ALLEGRO_KEY_ENTER)) { ui_show_dialog (game->ui, NULL, NULL); } if (al_key_down (&keyboard_state, ALLEGRO_KEY_RIGHT)) { actor->event->move_right (actor, dt); } if (al_key_down (&keyboard_state, ALLEGRO_KEY_LEFT)) { actor->event->move_left (actor, dt); } if (al_key_down (&keyboard_state, ALLEGRO_KEY_UP)) { actor->event->move_up (actor, dt); } if (al_key_down (&keyboard_state, ALLEGRO_KEY_DOWN)) { actor->event->move_down (actor, dt); } BOX box = actor->box; box.center.x += actor->movement.x * dt; box.center.y += actor->movement.y * dt; aabb_collide_fill_cache (scene->collision_tree, &box, &collisions); if (scene->collision_tree->num_collisions > 0) { item = _al_list_front (collisions.boxes); while (item) { if (box_lateral (*(BOX *)_al_list_item_data (item), actor->box)) actor->movement.x = 0; else actor->movement.y = 0; item = _al_list_next (collisions.boxes, item); } } aabb_collide_fill_cache (scene->portal_tree, &box, &portal_collisions); if (scene->portal_tree->num_collisions > 0) { item = _al_list_front (portal_collisions.boxes); while (item) { BOX *colbox = _al_list_item_data (item); TILED_OBJECT *obj = colbox->data; SCENE_PORTAL *portal = scene_get_portal (game->scenes, obj->name); if (portal && portal->destiny_portal) { dest_portal = scene_get_portal (game->scenes, portal->destiny_portal); if (dest_portal) { fadeout_duration = TRANS_TIME; game->paused = true; actor->movement = (VECTOR2D){0, 0}; ui_show_dialog_cstr (game->ui, "Speaker:", "Entering portal."); break; } } item = _al_list_next (portal_collisions.boxes, item); } } box = screen_box (&game->screen); game->current_npc = NULL; item = _al_list_front (scene->npcs); float max_dist = 0; while (item) { SPRITE_NPC *npc = _al_list_item_data (item); float dist = vsqdistance (npc->actor.box.center, game->current_actor->box.center); if (dist < 128.0f * 128.0f && dist > max_dist) { game->current_npc = npc; max_dist = dist; } item = _al_list_next (scene->npcs, item); } //aabb_collide_fill_cache (scene->npc_tree, &box, &npc_collisions); //if (scene->npc_tree->num_collisions > 0) { // item = _al_list_front (npc_collisions.boxes); // float max_dist = 0; // while (item) { // BOX *colbox = _al_list_item_data (item); // SPRITE_NPC *npc = colbox->data; // float dist = vsqdistance (npc->actor.box.center, game->current_actor->box.center); // if (dist < 128.0f * 128.0f && dist > max_dist) { // game->current_npc = npc; // max_dist = dist; // } // item = _al_list_next (npc_collisions.boxes, item); // } //} screen_update (&game->screen, actor->position, scene->map, dt); sprite_update (actor, dt, mean_frame_time); item = _al_list_front (scene->npcs); while (item) { SPRITE_ACTOR *npc_actor = (SPRITE_ACTOR *)_al_list_item_data (item); sprite_update (npc_actor, dt, mean_frame_time); item = _al_list_next (scene->npcs, item); } redraw = true; break; case ALLEGRO_EVENT_DISPLAY_CLOSE: game->running = false; break; default: fprintf (stderr, "Unsupported event received: %d\n", event.type); break; } } aabb_free_collisions (&collisions); aabb_free_collisions (&portal_collisions); aabb_free_collisions (&npc_collisions); }
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; }
void InvestigationScene::setupScene() { std::vector<Point> positions; positions.push_back(pointMake(32, 48)); positions.push_back(pointMake(34, 48)); positions.push_back(pointMake(36, 48)); positions.push_back(pointMake(38, 48)); positions.push_back(pointMake(40, 49)); positions.push_back(pointMake(40, 51)); positions.push_back(pointMake(40, 53)); positions.push_back(pointMake(30, 49)); positions.push_back(pointMake(30, 51)); positions.push_back(pointMake(32, 52)); const char *fontFile = "res/AveriaSerif-Regular.ttf"; font = al_load_font(fontFile, 18, 0); if (!font) { Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile); } fontBig = al_load_font(fontFile, 26, 0); if (!fontBig) { Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile); } searchSound = al_load_sample("res/search.wav"); if (!searchSound) { Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/search.wav"); } clickSound = al_load_sample("res/click.wav"); if (!clickSound) { Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/click.wav"); } std::vector<TilemapLayer *> layers = TilemapLayer::parseTMXFile("res/mansion.tmx"); std::vector<TilemapLayer *>::iterator it; TilemapLayer *firstLayer = layers[0]; camera = new Camera(800, 600, firstLayer->getBoundsSize().width, firstLayer->getBoundsSize().height); for (it = layers.begin(); it < layers.end(); ++it) { TilemapLayer *layer = (TilemapLayer *) *it; layer->setCamera(camera); addToDisplayList(layer); if (layer->isCollision()) { collision = layer; } } playerSprite = new Spritesheet("res/professor_walk_cycle_no_hat.png", 64, 64); playerSprite->setTag(PLAYER_SPRITE_TAG); playerSprite->setCamera(camera); playerSprite->setPosition(pointMake(35 * 32, 50 * 32)); playerSprite->setAnchorPoint(pointMake(0.5, 0.9)); playerSprite->setAutoZOrder(true); addToDisplayList(playerSprite); mysterySeed = 0; do { mysteryTime = 0; mysterySeed = time(0); mystery = new Mystery("res/mansion.xml", mysterySeed, collision->getData(), collision->getSize().width, collision->getSize().height); while (!mystery->ended && mysteryTime < MAX_MYSTERY_DURATION) { mystery->step(); mysteryTime++; } if (!mystery->ended) { delete mystery; mystery = NULL; } } while (mystery == NULL); printf("Case seed: %d Total duration: %ld %s\n", mysterySeed, mysteryTime, timeToString(mysteryTime, true).c_str()); std::vector<Character *> characters = mystery->getCharacters(); std::vector<Character *>::iterator itChars; int i = 0; for (itChars = characters.begin(); itChars < characters.end(); ++itChars) { Character *character = (Character *) *itChars; int frame = i * 2; if (!character->dead) { int idx = rand() % positions.size(); Point pos = positions[idx]; character->position = pos; positions.erase(positions.begin() + idx); } else { frame++; } Spritesheet *sprite = new Spritesheet("res/characters.png", 64, 64); sprite->setTag(character->tag); sprite->setCamera(camera); sprite->setAnchorPoint(pointMake(0.5, 0.9)); sprite->setAutoZOrder(true); sprite->setFrame(frame); Rect tileRect = collision->getTileRect(character->position.x, character->position.y); sprite->setPosition(rectMidPoint(tileRect)); addToDisplayList(sprite); i++; } std::vector<POI *>::iterator itWeapons; i = 0; for (itWeapons = mystery->weapons.begin(); itWeapons < mystery->weapons.end(); ++itWeapons) { POI *weapon = (POI *) *itWeapons; Spritesheet *sprite = new Spritesheet("res/weapons.png", 32, 32); sprite->setTag(i + 20); sprite->setFrame(i); sprite->setCamera(camera); sprite->setAnchorPoint(pointMake(0.5, 0.5)); sprite->setZOrder(400); Rect tileRect = collision->getTileRect(weapon->position.x, weapon->position.y); sprite->setPosition(rectMidPoint(tileRect)); addToDisplayList(sprite); i++; } actionButton = new Button("action", font, BTN_TXT_COLOR, "res/btn_action.png", "res/btn_action_pressed.png"); actionButton->setZOrder(500); actionButton->setAnchorPoint(pointMake(0.5, 1)); actionButton->setPosition(pointMake(400, 400)); actionButton->setCamera(camera); actionButton->setHandler(this); addToDisplayList(actionButton); Spritesheet *bkgRoomLabel = new Spritesheet("res/bkg_room_name.png"); bkgRoomLabel->setAnchorPoint(pointMake(0.5, 0.5)); bkgRoomLabel->setPosition(pointMake(400, 40)); bkgRoomLabel->setZOrder(501); addToDisplayList(bkgRoomLabel); currentRoomLabel = new Label("room", font, al_map_rgb(0, 0, 0)); currentRoomLabel->setAnchorPoint(pointMake(0.5, 0.5)); currentRoomLabel->setPosition(bkgRoomLabel->getPosition()); currentRoomLabel->setZOrder(502); addToDisplayList(currentRoomLabel); Spritesheet *bkgWeaponLabel = new Spritesheet("res/bkg_room_name.png"); bkgWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5)); bkgWeaponLabel->setPosition(pointMake(720, 40)); bkgWeaponLabel->setZOrder(501); addToDisplayList(bkgWeaponLabel); crimeWeaponLabel = new Label("No weapon", font, al_map_rgb(0, 0, 0)); crimeWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5)); crimeWeaponLabel->setPosition(bkgWeaponLabel->getPosition()); crimeWeaponLabel->setZOrder(502); addToDisplayList(crimeWeaponLabel); Spritesheet *bkgAccusationLabel = new Spritesheet("res/bkg_room_name.png"); bkgAccusationLabel->setAnchorPoint(pointMake(0.5, 0.5)); bkgAccusationLabel->setPosition(pointMake(80, 40)); bkgAccusationLabel->setZOrder(501); addToDisplayList(bkgAccusationLabel); char buf[100]; sprintf(buf, "%d accusations left", MAX_ACCUSATIONS); accusationsLabel = new Label(buf, font, al_map_rgb(0, 0, 0), 120); accusationsLabel->setAnchorPoint(pointMake(0.5, 0.5)); accusationsLabel->setPosition(bkgAccusationLabel->getPosition()); accusationsLabel->setZOrder(502); addToDisplayList(accusationsLabel); bkgQuestion = new Spritesheet("res/bkg_question.png"); bkgQuestion->setAnchorPoint(pointMake(0.5, 0.5)); bkgQuestion->setPosition(pointMake(400, 300)); bkgQuestion->setZOrder(503); bkgQuestion->setVisible(false); addToDisplayList(bkgQuestion); questionLabel = new Label("question", font, al_map_rgb(0, 0, 0), 350); questionLabel->setAnchorPoint(pointMake(0.5, 0.5)); questionLabel->setPosition(pointMake(400, 120)); questionLabel->setZOrder(504); questionLabel->setVisible(false); addToDisplayList(questionLabel); whenLabel = new Label("00:00 and 00:15", fontBig, al_map_rgb(0, 0, 0)); whenLabel->setAnchorPoint(pointMake(0.5, 0.5)); whenLabel->setPosition(pointMake(400, 300)); whenLabel->setZOrder(504); whenLabel->setVisible(false); addToDisplayList(whenLabel); askQuestionButton = new Button("Ask", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png"); askQuestionButton->setZOrder(504); askQuestionButton->setAnchorPoint(pointMake(0.5, 0.5)); askQuestionButton->setPosition(pointMake(480, 490)); askQuestionButton->setHandler(this); askQuestionButton->setVisible(false); askQuestionButton->setEnabled(false); addToDisplayList(askQuestionButton); cancelQuestionButton = new Button("Cancel", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png"); cancelQuestionButton->setZOrder(504); cancelQuestionButton->setAnchorPoint(pointMake(0.5, 0.5)); cancelQuestionButton->setPosition(pointMake(300, 490)); cancelQuestionButton->setHandler(this); cancelQuestionButton->setVisible(false); cancelQuestionButton->setEnabled(false); addToDisplayList(cancelQuestionButton); bkgSpeech = new Spritesheet("res/speech.png"); bkgSpeech->setAnchorPoint(pointMake(0.35, 1)); bkgSpeech->setCamera(camera); bkgSpeech->setZOrder(503); bkgSpeech->setVisible(false); addToDisplayList(bkgSpeech); speechLabel = new Label("speech", font, al_map_rgb(0, 0, 0), 280); speechLabel->setAnchorPoint(pointMake(0.5, 0.5)); speechLabel->setCamera(camera); speechLabel->setZOrder(504); speechLabel->setVisible(false); addToDisplayList(speechLabel); speechCountLabel = new Label("1/1", font, al_map_rgb(0, 0, 0)); speechCountLabel->setAnchorPoint(pointMake(1, 0.5)); speechCountLabel->setCamera(camera); speechCountLabel->setZOrder(504); speechCountLabel->setVisible(false); addToDisplayList(speechCountLabel); speechButton = new Button(bkgSpeech->getFrameSize()); speechButton->setAnchorPoint(bkgSpeech->getAnchorPoint()); speechButton->setCamera(camera); speechButton->setZOrder(504); speechButton->setEnabled(false); speechButton->setHandler(this); addToDisplayList(speechButton); camera->setCenter(playerSprite->getPosition()); activeCharacter = NULL; activePOI = NULL; currentRoom = NULL; crimeWeapon = NULL; accusationsLeft = MAX_ACCUSATIONS; questionsAsked = 0; moving = pointMake(0, 0); moveDir = 0; curFrame = 0; endScene = false; debug = false; currentFilter.timeStart = 0; currentFilter.timeEnd = QUESTION_INTERVAL; std::string msg; msg.append(mystery->victim->name); msg.append("'s body was found around "); msg.append(timeToString(mystery->corpseFoundTime + START_TIME, false)); msg.append(" in the "); msg.append(mystery->corpseFoundRoom->name); msg.append("."); ModalDialog *dialog = new ModalDialog(msg.c_str(), font, "OK", NULL); dialog->setHandler(this); dialog->showInScene(this, 1000); music = al_load_audio_stream("res/mystery.ogg", 4, 2048); al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP); al_attach_audio_stream_to_mixer(music, al_get_default_mixer()); inDialogue = false; inputLocked = true; investigationStartTime = time(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; }
int main(void) { bool done = false; // Variavel booleana para identificar se o programa terminou de ser executado bool redraw = true; // Enquanto essa variavel for verdadeira, ira ser desenhado algo na tela bool desenha = true; int draw[5]= {0, 0, 0, 0, 0}; int pos_x = WIDTH / 2; int pos_y = HEIGHT / 2; int timer_tiros = 0; int timer_energy = 0; int timer_heats = 0; int timer_tamenho_heat = 0; int timer_componente = 0; int count = 0; Gamer(gamer); Zone zone[LINHAS][COLUNAS]; Bullet bullets[NUM_BULLETS+1]; Energy energy[NUM_ENERGYS+1]; Heat heats[NUM_HEAT+1]; Zombie zombie[NUM_ZOMBIES]; Battery battery[NUM_BATTERY]; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font18 = NULL; ALLEGRO_FONT *font_maior = NULL; ALLEGRO_BITMAP *resistor = NULL; ALLEGRO_BITMAP *capacitor = NULL; ALLEGRO_BITMAP *indutor = NULL; ALLEGRO_BITMAP *diodo = NULL; ALLEGRO_BITMAP *bateria = NULL; ALLEGRO_BITMAP *protoboard = NULL; ALLEGRO_BITMAP *fogo = NULL; ALLEGRO_BITMAP *zombie_bitmap = NULL; ALLEGRO_BITMAP *ataque_eletromagnetico = NULL; ALLEGRO_BITMAP *energia_capacitor = NULL; ALLEGRO_BITMAP *logo = NULL; if(!al_init()) //initialize Allegro return -1; display = al_create_display(WIDTH, HEIGHT); //create our display object if(!display) //test display object return -1; al_init_primitives_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); al_install_mouse(); al_init_image_addon(); resistor = al_load_bitmap("Resistor.png"); capacitor = al_load_bitmap("Capacitor.png"); indutor = al_load_bitmap("Indutor.png"); diodo = al_load_bitmap("Diodo.png"); bateria = al_load_bitmap("Bateria.png"); protoboard = al_load_bitmap("Protoboard.png"); fogo = al_load_bitmap("fogo_resistor/fire1.png"); zombie_bitmap = al_load_bitmap("Zombie.png"); ataque_eletromagnetico = al_load_bitmap("eletromagnetismo.jpg"); energia_capacitor = al_load_bitmap("energia_capacitor.png"); logo = al_load_bitmap("logo_EvsZ.jpg"); al_convert_mask_to_alpha(resistor, al_map_rgb(255, 0, 255)); al_convert_mask_to_alpha(capacitor, al_map_rgb(255, 0, 255)); al_convert_mask_to_alpha(indutor, al_map_rgb(255, 0, 255)); al_convert_mask_to_alpha(diodo, al_map_rgb(255, 0, 255)); al_convert_mask_to_alpha(bateria, al_map_rgb(255, 0, 255)); al_convert_mask_to_alpha(zombie_bitmap, al_map_rgb(255, 255, 255)); al_convert_mask_to_alpha(ataque_eletromagnetico, al_map_rgb(255, 255, 255)); event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); InitGamer(gamer); InitZone(zone, LINHAS, COLUNAS); InitBullet(bullets, NUM_BULLETS+1); InitHeat(heats, NUM_HEAT+1); InitZombie(zombie, NUM_ZOMBIES); InitEnergy(energy, NUM_ENERGYS+1); InitBattery(battery, NUM_BATTERY); font18 = al_load_font("arial.ttf", 18, 0); font_maior = al_load_font("arial.ttf", 24, 0); 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_timer_event_source(timer)); al_register_event_source(event_queue, al_get_display_event_source(display)); al_hide_mouse_cursor(display); al_start_timer(timer); while(!done) { ALLEGRO_EVENT ev; /*===============================================================================================================================================*/ if(state == MENU) { al_wait_for_event(event_queue, &ev); al_draw_bitmap(logo, WIDTH / 2 - 145, HEIGHT - 500, 0); al_draw_text(font18, al_map_rgb(255, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Os Zombies querem roubar seu diploma, proteja-o"); al_draw_text(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2 + 100, ALLEGRO_ALIGN_CENTRE, "Pressione Space para jogar"); al_draw_text(font_maior, al_map_rgb(0, 255, 0), WIDTH / 2, HEIGHT / 2 + 150, ALLEGRO_ALIGN_CENTRE, "Tecla 1 = Resistor Tecla 2 = Capacitor Tecla 3 = Indutor Tecla 4 = Diodo"); if(ev.type == ALLEGRO_EVENT_KEY_DOWN) if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE) state = PLAYING; if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) done = true; al_flip_display(); } /*===============================================================================================================================================*/ if(state == PLAYING) { al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) done = true; if(ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; for(int i = 0; i < LINHAS; i++) for(int j=0; j<COLUNAS; j++) if(zone[i][j].x < pos_x && zone[i][j].x + ZONEX > pos_x && zone[i][j].y < pos_y && zone[i][j].y + ZONEY > pos_y) if(desenha) if(zone[i][j].draw == 0) { if(keys[KEY_1] && gamer.energy >= 100) { zone[i][j].draw = draw[1]; gamer.energy -=100; draw[1] = 0; } if(keys[KEY_2] && gamer.energy >= 50) { zone[i][j].draw = draw[2]; gamer.energy -=50; draw[2] = 0; } if(keys[KEY_3] && gamer.energy >= 100) { zone[i][j].draw = draw[3]; gamer.energy -=100; draw[3] = 0; } if(keys[KEY_4] && gamer.energy >= 100) { zone[i][j].draw = draw[4]; gamer.energy -=100; draw[4] = 0; } } timer_battery_speed++; timer_battery_start++; if(timer_battery_start >= 360) // diminui a frequencia com que nasce uma bateria nova { StartBattery(battery, NUM_BATTERY); timer_battery_start = 0; } if(timer_battery_speed >= 2) // reduz um pouco a velocidade da bateria { UpdateBattery(battery, NUM_BATTERY); timer_battery_speed = 0; } timer_heats++; for(int i=0; i<LINHAS; i++) for(int j=0; j<COLUNAS; j++) if(zone[i][j].draw == 1) if(timer_heats >= 200) { FireHeat(heats, NUM_HEAT+1, zone); timer_heats = 0; } timer_energy++; timer_energy_cap_death++; for(int i=0; i<LINHAS; i++) for(int j=0; j<COLUNAS; j++) if(zone[i][j].draw == 2) { if(timer_energy >= 420) { CreateEnergy(energy, NUM_ENERGYS+1, zone); timer_energy = 0; } } timer_tiros++; for(int i=0; i<LINHAS; i++) for(int j=0; j<COLUNAS; j++) if(zone[i][j].draw == 3) if(timer_tiros >= 200) // faz os Electronics atirarem numa velocidade constante { FireBullet(bullets, NUM_BULLETS+1, zone); timer_tiros = 0; } timer_zombie_start++; timer_zombie_speed++; timer_dificuldade++; if(timer_zombie_start >= 3) { StartZombie(zombie, NUM_ZOMBIES); timer_zombie_start = 0; } if(dificuldade >20 && dificuldade <=500) { if(timer_dificuldade >= 300) { dificuldade -= 30; timer_dificuldade = 0; } } if(timer_zombie_speed >= 3) { UpdateZombie(zombie, NUM_ZOMBIES); timer_zombie_speed = 0; } UpdateBullet(bullets, NUM_BULLETS+1); CollideBullet(bullets, NUM_BULLETS, zombie, NUM_ZOMBIES, gamer); CollideHeat(heats, NUM_HEAT, zombie, NUM_ZOMBIES, gamer, timer_tamenho_heat); CollideZone(zone, LINHAS, COLUNAS, zombie, NUM_ZOMBIES); CollideZoneDiodo(zone, LINHAS, COLUNAS, zombie, NUM_ZOMBIES); for(int i = 0; i < NUM_ENERGYS; i++) if(energy[i].live) if(energy[i].x - energy[i].boundx < pos_x && energy[i].x + energy[i].boundx > pos_x && energy[i].y - energy[i].boundy < pos_y && energy[i].y + energy[i].boundy > pos_y) { energy[i].live = false; gamer.energy += 25; } } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_1: keys[KEY_1] = true; break; case ALLEGRO_KEY_2: keys[KEY_2] = true; break; case ALLEGRO_KEY_3: keys[KEY_3] = true; break; case ALLEGRO_KEY_4: keys[KEY_4] = true; break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_1: keys[KEY_1] = false; break; case ALLEGRO_KEY_2: keys[KEY_2] = false; break; case ALLEGRO_KEY_3: keys[KEY_3] = false; break; case ALLEGRO_KEY_4: keys[KEY_4] = false; break; } } else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (ev.mouse.button & 2) done = true; } else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES) { pos_x = ev.mouse.x; pos_y = ev.mouse.y; CaptureBattery(battery, NUM_BATTERY, ev.mouse.x, ev.mouse.y, gamer); } timer_componente++; if(timer_componente >= 10) { if(keys[KEY_1]) draw[1] = 1; if(keys[KEY_2]) draw[2] = 2; if(keys[KEY_3]) draw[3] = 3; if(keys[KEY_4]) draw[4] = 4; } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; DrawZone(zone, LINHAS, COLUNAS, resistor, capacitor, indutor, diodo); DrawBullet(bullets, NUM_BULLETS+1, ataque_eletromagnetico); DrawEnergy(energy, NUM_ENERGYS+1, energia_capacitor); DrawZombie(zombie, NUM_ZOMBIES, zombie_bitmap); DrawBattery(battery, NUM_BATTERY, bateria); timer_tamenho_heat++; DrawHeat(heats, NUM_HEAT+1, timer_tamenho_heat, fogo); if(timer_tamenho_heat > 80) for(int i=0; i<NUM_HEAT; i++) { heats[i].live = false; timer_tamenho_heat = 0; } al_draw_filled_rectangle(pos_x, pos_y, pos_x + 10, pos_y + 10, al_map_rgb(0, 0, 0)); count++; al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/16, 85, 0, "Time: %i", count/60); al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/300, 85, 0, "Energy: %i", gamer.energy); al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/25, 85, 0, "Score: %i", gamer.score); al_flip_display(); al_draw_bitmap(protoboard, 0, 0, 0); } } /*================================================================================================================================================*/ if(state == GAMEOVER) { al_wait_for_event(event_queue, &ev); al_clear_to_color(al_map_rgb(0,0,0)); al_draw_text(font18, al_map_rgb(255, 168, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Os Zombies roubaram seu diploma"); al_draw_text(font18, al_map_rgb(255, 255, 255), WIDTH / 2, HEIGHT / 2 +40, ALLEGRO_ALIGN_CENTRE, "Pressione Space para sair"); al_draw_textf(font_maior, al_map_rgb(255, 0, 0), WIDTH*13/28, 85, 0, "Score: %i", gamer.score); al_flip_display(); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) done = true; if(ev.type == ALLEGRO_EVENT_KEY_DOWN) if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE) { al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_font(font18); al_destroy_bitmap(resistor); al_destroy_bitmap(capacitor); al_destroy_bitmap(indutor); al_destroy_bitmap(diodo); al_destroy_bitmap(bateria); al_destroy_bitmap(protoboard); al_destroy_bitmap(zombie_bitmap); al_destroy_display(display); } } } return 0; }
void SplashScreen::LoadContent() { font = al_load_font("arial.ttf", 30, NULL); }
int main() { const float FPS = 60.0; if(!al_init()) { al_show_native_message_box(NULL, "Fatal Error", NULL, "No se pudo inicializar Allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } al_set_new_display_flags(ALLEGRO_WINDOWED); // Pone la ventana en modo Windowed ALLEGRO_DISPLAY *display = al_create_display(ScreenWidth, ScreenHeight); // Pone la posición en la que debe salir l`a ventana //al_set_window_position(display, 0, 30); // Pone el título de la ventana al_set_window_title(display, "Killer Bunny"); if(!display) // Si no se pudo crear la ventana, entonces pone un mensaje de error { al_show_native_message_box(NULL, "Error", NULL, "No se pudo crear la pantalla", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } al_install_keyboard(); al_install_mouse(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); // ----------------------------------------------------------------- ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS); ALLEGRO_KEYBOARD_STATE keyState; // Utilizado para debugging ALLEGRO_FONT *font = al_load_font("sprites/DroidSans.ttf", 10, 0); ALLEGRO_BITMAP *fondo1 = al_load_bitmap("sprites/fondo1.png"); bool done = false; // ---------Estructuras del juego----------------------------------- struct Player player; player.image = al_load_bitmap("sprites/player.png"); al_convert_mask_to_alpha(player.image, al_map_rgb(255,255,255)); player.x = ScreenWidth / 2; player.y = ScreenHeight / 2; player.w = al_get_bitmap_width(player.image); player.h = al_get_bitmap_height(player.image); player.moveSpeed = 3; player.degrees = -ALLEGRO_PI/2; player.alive = true; player.clip = 6; player.vida = 100; struct Bala bala; //~ void Bala::update() //~ { //~ bala.dx = cosf(player.xmouse - player.x); //~ bala.dy = senf(player.ymouse - player.y); //~ //~ if(bala.shot){ //~ //~ bala.x += bala.dx; //~ bala.y += bala.dy; //~ } //~ //~ } bala.image = al_load_bitmap("sprites/bullet.png"); bala.x = player.x+50; bala.y = player.y+25; bala.shot = false; struct Enemigo robot; robot.image = al_load_bitmap("sprites/Robot_sprites.png"); robot.death = al_load_bitmap("sprites/explosiondelrobot.png"); al_convert_mask_to_alpha(robot.death, al_map_rgb(255, 255, 255)); //al_convert_mask_to_alpha(robot.image, al_map_rgb(255,255,255)); robot.x = 50; robot.y = 50; robot.w = al_get_bitmap_width(robot.image); robot.h = al_get_bitmap_height(robot.image); robot.velocidad_x = 0.23; robot.velocidad_y = 0.23; robot.fuerza= 0.5; robot.vida=50; //~ void Weapon::recargar() //~ { //~ for(int i = 0; i < 6; i++) //~ { //~ bullets[i] = bala; //~ } //~ } // ----------------------------------------------------------------- // Esta variable guardará los eventos del mouse ALLEGRO_MOUSE_STATE mouseState; // Registro varias fuentes de eventos 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)); al_register_event_source(event_queue, al_get_mouse_event_source()); // Inicializo el temporizador principal al_start_timer(timer); while(!done) { // La variable de los eventos ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); // Y aquí espero por los eventos if(ev.type == ALLEGRO_EVENT_TIMER) { // Dos funciones para pasar eventos del mouse y del teclado al_get_keyboard_state(&keyState); al_get_mouse_state(&mouseState); // Esto detecta la posición del mouse y lo guarda a un par de variables player.xmouse = al_get_mouse_state_axis(&mouseState, 0); player.ymouse = al_get_mouse_state_axis(&mouseState, 1); // Si presiono Esc entonces me saca del juego if(al_key_down(&keyState, ALLEGRO_KEY_ESCAPE)) { done = true; } // Si presiono A entonces el valor x se reduce, osea, se va a la izquierda if(al_key_down(&keyState, ALLEGRO_KEY_A)) { player.x -= player.moveSpeed; } // Si... meh, ya sabes lo que sigue if(al_key_down(&keyState, ALLEGRO_KEY_D)) { player.x += player.moveSpeed; } // ... if(al_key_down(&keyState, ALLEGRO_KEY_W)) { player.y -= player.moveSpeed; } // ... if(al_key_down(&keyState, ALLEGRO_KEY_S)) { player.y += player.moveSpeed; } // Mata al robot if(al_key_down(&keyState, ALLEGRO_KEY_K)) { robot.vida -= 10; } } // Esto permite que el jugador se mueva con el mouse player.degrees = atan2((player.ymouse-player.y),(player.xmouse-player.x)); // La Inteligencia Artificial del enemigo if(robot.alive && player.alive){ if(robot.x < player.x) robot.x += robot.velocidad_x; if(robot.x > player.x) robot.x -= robot.velocidad_x; if(robot.y > player.y) robot.y -= robot.velocidad_y; if(robot.y < player.y) robot.y += robot.velocidad_y; } // Uso de las funciones para las colisiones //if(Collision(player.x, player.y, 50, 50, robot.x, robot.y, 34, 34)) player.alive = false; if(PixelCol(player.image, robot.image, player.x-(player.w/2), player.y-(player.h/2), player.w, player.h, robot.x, robot.y, robot.w/7, robot.h)) player.vida -= robot.fuerza; if(player.vida==0) player.alive = false; if(robot.vida<=0){ robot.vida = 0; robot.alive = false; } al_clear_to_color(al_map_rgb(255, 255, 255)); // Se pinta todo a negro al_draw_scaled_bitmap(fondo1,0, 0, 256, 256, 0, 0, ScreenWidth, ScreenHeight, 0); // Se dibuja el fondo if(player.alive){ // Si el jugador está vivo al_draw_rotated_bitmap(player.image, 25, 25, player.x, player.y, player.degrees, 0); // Dibujo el jugador al_draw_rotated_bitmap(bala.image, 0, 0, player.x+5, player.y+5, player.degrees, 0); // Dibujo la bala (esto hay que quitarlo) } if(robot.alive){ al_draw_bitmap_region(robot.image, 0, 0, 60, 52, robot.x, robot.y, 0); // Dibujo el robot } else { robot.w = al_get_bitmap_width(robot.death); robot.h = al_get_bitmap_width(robot.death); al_draw_bitmap_region(robot.death, 0, 0, robot.w/4, robot.h, robot.x, robot.y, 0); } // Esto es para el debugging // Dibujo rectángulos para las colisiones al_draw_rectangle(player.x-(player.w/2), player.y-(player.h/2), (player.x+player.w)-(player.w/2), (player.y+player.h)-(player.h/2), al_map_rgb(0, 255, 0), 1.0); al_draw_rectangle(robot.x, robot.y, robot.x+(robot.w/7), robot.y+robot.h, al_map_rgb(0, 255, 0), 1.0); // Escribo en una esquina de la pantalla, información respecto al personaje al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 2, ALLEGRO_ALIGN_RIGHT, "Player x, y : %.1f %.1f", player.x, player.y); al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 12, ALLEGRO_ALIGN_RIGHT, "Rotation (rad): %.5f", player.degrees); al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 22, ALLEGRO_ALIGN_RIGHT, "Rotation (degrees): %.2f", (player.degrees*180)/ALLEGRO_PI); // Status bar al_draw_filled_rectangle(0,0,player.vida*2,15, al_map_rgb(0,255,0)); // Actualizo la pantalla (flip) al_flip_display(); } //-----After party (hay que limpiar)-------------------------------- // A destruirlo todo!! BAM BAM BAM, KABOOM!! al_destroy_font(font); al_destroy_bitmap(fondo1); al_destroy_bitmap(robot.image); al_destroy_display(display); al_destroy_event_queue(event_queue); al_destroy_bitmap(player.image); al_destroy_timer(timer); return 0; }
int main(int argc, char **argv) { //============================================== //SHELL VARIABLES //============================================== bool done = false; bool render = false; float gameTime = 0; int frames = 0; int gameFPS = 0; //============================================== //PROJECT VARIABLES //============================================== int state = MENU; //============================================== //ALLEGRO VARIABLES //============================================== ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer; ALLEGRO_FONT *font18 = NULL; //============================================== //ALLEGRO INIT FUNCTIONS //============================================== if(!al_init()) //initialize Allegro return -1; display = al_create_display(WIDTH, HEIGHT); //create our display object if(!display) //test display object return -1; //============================================== //ADDON INSTALL //============================================== al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); //============================================== //PROJECT INIT //============================================== font18 = al_load_font("arial.ttf", 18, 0); //============================================== //TIMER INIT AND STARTUP //============================================== event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / 60); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_start_timer(timer); gameTime = al_current_time(); while(!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); //============================================== //INPUT //============================================== if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: keys[ESCAPE] = 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_SPACE: keys[SPACE] = true; break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: keys[ESCAPE] = 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_SPACE: keys[SPACE] = false; break; } } //============================================== //GAME UPDATE //============================================== else if(ev.type == ALLEGRO_EVENT_TIMER) { render = true; //UPDATE FPS============ frames ++; if (al_current_time() - gameTime >= 1){ gameTime = al_current_time(); gameFPS = frames; frames = 0; } //============ if(state == MENU){ if(keys[SPACE]){ state = PLAYING; } } else if(state == PLAYING){ if(keys[ESCAPE]){ state = GAMEOVER; } } else if (state == GAMEOVER){ if(keys[SPACE]){ done = true; } } } //============================================== //RENDER //============================================== if(render && al_is_event_queue_empty(event_queue)) { render = false; al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "FPS: %i", gameFPS); // display game FPS on screen //BEGIN PROJECT RENDER============= if(state == MENU){ al_draw_text(font18, al_map_rgb(255,255,255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Press space to play"); } else if(state == PLAYING){ al_draw_text(font18, al_map_rgb(255,255,255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Press escape to end"); } else if (state == GAMEOVER){ al_draw_text(font18, al_map_rgb(255,255,255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Press space to exit the game"); } //FLIP BUFFERS============= al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } } //============================================== //DESTROY ALLEGRO OBJECTS //============================================== al_destroy_font(font18); al_destroy_timer(timer); al_destroy_event_queue(event_queue); al_destroy_display(display); return 0; }
/* Initialize game and all Allegro objects */ Tetris::Tetris() { // Initialize settings variables targetFPS = 60.0; screenWidth = 800; screenHeight = 600; fontName = "res/fnt/minecraftia.ttf"; showFPS = true; simplog.writeLog( LOG_VERBOSE, "Target FPS: %.2f", targetFPS ); simplog.writeLog( LOG_VERBOSE, "Screen Width: %d", screenWidth ); simplog.writeLog( LOG_VERBOSE, "Screen Height: %d", screenHeight ); simplog.writeLog( LOG_VERBOSE, "Font Name: %s", fontName ); simplog.writeLog( LOG_VERBOSE, "Display FPS set to '%s'", showFPS ? "true" : "false" ); // Begin initializing Allegro objects display = NULL; main_queue = NULL; input_queue = NULL; font18 = NULL; timer = NULL; // Initialize Allegro if( !al_init() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize Allegro!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Allegro successfully initiallized" ); } // Create the display display = al_create_display( screenWidth, screenHeight); if( !display ) { simplog.writeLog( LOG_FATAL, "Failed to create display!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Display created successfully" ); } // Initialize the keyboard if( !al_install_keyboard() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize the keyboard!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Keyboard initialized successfully" ); } // Initialize the mouse if( !al_install_mouse() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize the mouse!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Mouse initialized successfully" ); } // Create the main event queue main_queue = al_create_event_queue(); if( !main_queue ) { simplog.writeLog( LOG_FATAL, "Failed to create main event queue!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Main event Queue created susscessfully" ); } // Create the input event queue input_queue = al_create_event_queue(); if( !input_queue ) { simplog.writeLog( LOG_FATAL, "Failed to create input event queue!" ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Input event Queue created susscessfully" ); } // Register the display with the event queue al_register_event_source( main_queue, al_get_display_event_source( display ) ); simplog.writeLog( LOG_VERBOSE, "Display event registered" ); // Register the keyboard with the event queue al_register_event_source( input_queue, al_get_keyboard_event_source() ); simplog.writeLog( LOG_VERBOSE, "Keyboard event registered" ); // Register the mouse with the event queue al_register_event_source( input_queue, al_get_mouse_event_source() ); simplog.writeLog( LOG_VERBOSE, "Mouse event registered" ); // Initialize Allegro's image addon for handling images if( !al_init_image_addon() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize image addon!" ); throw -1; } else { simplog.writeLog( LOG_VERBOSE, "Image addon initialized" ); } // Initialize Allegro's primitives addon for handling images if( !al_init_primitives_addon() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize primitives addon!" ); throw -1; } else { simplog.writeLog( LOG_VERBOSE, "Primitives addon initialized" ); } // Initialize Allegro's font addon for handling fonts al_init_font_addon(); simplog.writeLog( LOG_VERBOSE, "Font addon initialized" ); // Initialize Allegro's TTF addon for handling TTF fonts if( !al_init_ttf_addon() ) { simplog.writeLog( LOG_FATAL, "Failed to initialize TTF addon!" ); throw -1; } else { simplog.writeLog( LOG_VERBOSE, "TTF addon initialized" ); } // Load a size 18 font font18 = al_load_font( fontName, 18, 0 ); if( !font18 ) { simplog.writeLog( LOG_FATAL, "Failed to load font '%s' at size %d!", fontName, 18 ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Font '%s' loaded at size %d", fontName, 18 ); } // Load a size 12 font font12 = al_load_font( fontName, 12, 0 ); if( !font12 ) { simplog.writeLog( LOG_FATAL, "Failed to load font '%s' at size %d!", fontName, 12 ); throw -1; } else { simplog.writeLog( LOG_DEBUG, "Font '%s' loaded at size %d", fontName, 12 ); } // Create a timer to cap the game FPS timer = al_create_timer( 1.0 / targetFPS ); if( !timer ) { simplog.writeLog( LOG_FATAL, "Failed to create timer with resolution of %.2f seconds!", 1.0 / targetFPS ); throw -1; } else { simplog.writeLog( LOG_VERBOSE, "Timer created with resolution of %.2f seconds", 1.0 / targetFPS ); } // Register the timer with the event queue al_register_event_source( main_queue, al_get_timer_event_source( timer ) ); simplog.writeLog( LOG_VERBOSE, "Timer event registered" ); // Clear the screen to black al_clear_to_color( al_map_rgb( 0, 0, 0 ) ); // Push menu state onto the stack states = new std::stack<BaseState*>(); states->push( new MenuState( display, input_queue, states ) ); }
void Environment::drawGrid(bool showCenter) { if (!withGrid) { printf( "Environment::drawGrid(): do setGrid(true,<slotSize>) to perform grid operations\n"); } // calculate rows and columns of the grid int rows = height / slotSize; int columns = width / slotSize; // top left corner of the grid float y = dispHeight - height; // (displayHeight - rows*slotSize) / 2 ; float x = dispWidth - width; // (displayWidth - columns*slotSize) / 2 ; int line_size = 3; al_draw_rectangle(x, y, x + columns * slotSize, y + rows * slotSize, al_map_rgb(0, 255, 0), 5); // vertical lines for (int i = 1; i <= columns - 1; i++) { al_draw_line(x + i * slotSize, y, x + i * slotSize, y + rows * slotSize, al_map_rgb(0, 255, 0), line_size); } // horizontal lines for (int i = 1; i <= rows - 1; i++) { al_draw_line(x, y + i * slotSize, x + columns * slotSize, y + i * slotSize, al_map_rgb(0, 255, 0), line_size); } if (showCenter) { ALLEGRO_FONT* font = al_load_font("arial.ttf", 12, 0); if (!font) { printf("Environment::drawGrid(): font couldn't be loaded\n"); return; } // find slot centre for each row and column // and add text there for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { Point p = getGridSlotCenter(i, j); //al_draw_filled_circle(p.x, p.y, 5.0, al_map_rgb(255, 0, 0)); al_draw_textf(font, al_map_rgb(255, 255, 255), p.x, p.y, ALLEGRO_ALIGN_CENTER, "%d,%d", i, j); } } al_destroy_font(font); } /* //draw slant lines in each slot for(int i = 0; i < rows; i++){ for(int j = 0; j < columns; j++){ if(!is_obstacle(j, rows - i - 1) && ( (j != target.x) || ((rows - i - 1) != target.y) ) ){ // draw leftward slant lines al_draw_line(x + j*slotSize,y + i*slotSize, x + (j+1)*slotSize, y + (i+1)*slotSize, al_map_rgb(255,255,255),line_size); // draw rightward slant lines al_draw_line(x + j*slotSize, y + (i+1)*slotSize, x + (j+1)*slotSize, y + (i)*slotSize, al_map_rgb(255,255,255),line_size); } } } */ }
int main(void) { ALLEGRO_DISPLAY *display; ALLEGRO_FONT *font; ALLEGRO_CONFIG *config; ALLEGRO_EVENT_QUEUE *queue; bool write = false; bool flip = false; bool quit; if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_init_font_addon(); al_init_image_addon(); al_install_keyboard(); al_install_mouse(); /* Read parameters from ex_vsync.ini. */ config = al_load_config_file("ex_vsync.ini"); if (!config) { config = al_create_config(); write = true; } /* 0 -> Driver chooses. * 1 -> Force vsync on. * 2 -> Force vsync off. */ vsync = option(config, "vsync", 0); fullscreen = option(config, "fullscreen", 0); frequency = option(config, "frequency", 0); /* Write the file back (so a template is generated on first run). */ if (write) { al_save_config_file("ex_vsync.ini", config); } al_destroy_config(config); /* Vsync 1 means force on, 2 means forced off. */ if (vsync) al_set_new_display_option(ALLEGRO_VSYNC, vsync, ALLEGRO_SUGGEST); /* Force fullscreen mode. */ if (fullscreen) { al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW); /* Set a monitor frequency. */ if (frequency) al_set_new_display_refresh_rate(frequency); } display = al_create_display(640, 480); if (!display) { abort_example("Error creating display.\n"); } font = al_load_font("data/a4_font.tga", 0, 0); if (!font) { abort_example("Failed to load a4_font.tga\n"); } 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)); quit = display_warning(queue, font); al_flush_event_queue(queue); while (!quit) { ALLEGRO_EVENT event; /* With vsync, this will appear as a 50% gray screen (maybe * flickering a bit depending on monitor frequency). * Without vsync, there will be black/white shearing all over. */ if (flip) al_clear_to_color(al_map_rgb_f(1, 1, 1)); else al_clear_to_color(al_map_rgb_f(0, 0, 0)); al_flip_display(); flip = !flip; while (al_get_next_event(queue, &event)) { switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: quit = true; case ALLEGRO_EVENT_KEY_DOWN: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) quit = true; } } /* Let's not go overboard and limit flipping at 1000 Hz. Without * this my system locks up and requires a hard reboot :P */ al_rest(0.001); } al_destroy_font(font); al_destroy_event_queue(queue); return 0; }
int main(int argc, char **argv) { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return errno; } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ std::cout << cCurrentPath << std::endl; int newsw = 771 , newsh = 600; float _sx = (float)newsw / (float)SCREEN_W, _sy = (float)newsh / (float)SCREEN_H; float _offx = (SCREEN_W - newsw)/2, _offy = (SCREEN_H - newsh)/2; rGUI::Init_Allegro(); rGUI::Init_rGUI(); //rGUI::Init_rGUI(_sx, _sy, _offx, _offy); ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_BITMAP *bouncer = NULL; float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE / 2.0; float bouncer_y = SCREEN_H / 2.0 - BOUNCER_SIZE / 2.0; bool redraw = true; ALLEGRO_FONT *font = al_load_font("Calibri.ttf", 35, 0); timer = al_create_timer(1.0 / FPS); if(!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); //display = al_create_display(newsw, newsh); al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); if(!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE); if(!bouncer) { fprintf(stderr, "failed to create bouncer bitmap!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_set_target_bitmap(bouncer); al_clear_to_color(al_map_rgb(255, 0, 255)); al_set_target_bitmap(al_get_backbuffer(display)); event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_bitmap(bouncer); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_clear_to_color(al_map_rgb(0,0,0)); al_flip_display(); al_start_timer(timer); tmh.c_text = al_map_rgba(255,255,255,0); tmh.c_outline = al_map_rgba(0,200,0,255); tmh.c_background = al_map_rgba(255,0,0,255); tmh.c_movablepart = al_map_rgb(200,0,0); tmh.c_clicking = al_map_rgba(0,0,0,125); tmh.thickness = 2; tmh.added_thickness = 2; tmh.roundx = 0; tmh.roundy = 0; ALLEGRO_FONT *fnt = al_load_ttf_font("Calibri.ttf",30,0); widgets.push_back(new rGUI::Button(10,40,100,50,"wwwLong text", "Calibri.ttf",&tmh)); tmh.roundx = 3; tmh.roundy = 3; widgets.push_back(new rGUI::CheckBox(160, 40, 50,50,&tmh, false)); widgets.push_back(new rGUI::SlideBar(10,100,100,30,0,1,&tmh, (rGUI::bf_HORIZONTAL | rGUI::bf_HAS_FRAME) )); widgets.push_back(new rGUI::SlideBar(115,40,30,50,0,5, &tmh, (rGUI::bf_VERTICAL | rGUI::bf_HAS_FRAME) )); widgets.push_back(new rGUI::BitmapButton(10,140,100,45, "button.png",&tmh, 0)); widgets.push_back(new rGUI::ScrollBar(220, 5, 30, 185, 800, &tmh, (rGUI::bf_VERTICAL))); widgets.push_back(new rGUI::ScrollBar(10, 195, 240, 30, 800, &tmh, (rGUI::bf_HORIZONTAL))); widgets.push_back(new rGUI::InputField(115,100,95,40, "Calibri.ttf",&tmh, FPS)); widgets.push_back(new rGUI::SingleKeyInputField(115,145,95,40, ALLEGRO_KEY_BACKQUOTE, "Calibri.ttf",&tmh)); //Callback example int progressbar = widgets.size(); widgets.push_back(new rGUI::ProgressBar(10,5,200,30,0,&tmh)); widgets[progressbar]->wd_md->md_callback_data = widgets[progressbar]; widgets[progressbar]->wd_md->Just_clicked_callback = pbar_callback; widgets.push_back(new rGUI::ScrollableArea(10,240,440,440,2000,2000,&tmh,20, (rGUI::bf_VERTICAL | rGUI::bf_HORIZONTAL | rGUI::bf_ZOOMABLE))); int scbapoz = widgets.size()-1; widgets[scbapoz]->widgets.push_back(new rGUI::Button(10,10,100,30, "Text", "Calibri.ttf", &tmh)); widgets[scbapoz]->widgets.push_back(new rGUI::BitmapButton(10,50,100,45, "button.png",&tmh, 0)); widgets[scbapoz]->widgets.push_back(new rGUI::CheckBox(120, 30, 50,50,&tmh, false)); widgets[scbapoz]->widgets.push_back(new rGUI::SlideBar(10,100,120,30,0,300,&tmh, (rGUI::bf_HORIZONTAL | rGUI::bf_HAS_FRAME) )); widgets[scbapoz]->widgets.push_back(new rGUI::ScrollBar(10, 160, 120, 30, 800, &tmh, (rGUI::bf_HORIZONTAL))); widgets[scbapoz]->widgets.push_back(new rGUI::InputField(10,2000,100,40, "Calibri.ttf",&tmh, FPS)); widgets[scbapoz]->widgets.push_back(new rGUI::TextBox(2000,1200,300,120, "Big box", "Calibri.ttf", 200,&tmh, (rGUI::bf_HAS_FRAME | rGUI::bf_RESIZE_CONTENT))); widgets[scbapoz]->widgets.push_back(new rGUI::SlideBar(1000,100,200,40,0,20,&tmh, (rGUI::bf_HORIZONTAL | rGUI::bf_HAS_FRAME) )); widgets[scbapoz]->widgets.push_back(new rGUI::BitmapButton(300,300,0,0, "image.jpg",&tmh, (rGUI::bf_RESIZE_WIDGET | rGUI::bf_DISABLE_CLICKING_SHADOW))); ((rGUI::ScrollableArea*)widgets[scbapoz])->I_added_new_widgets(); //roundXY widgets.push_back(new rGUI::TextBox(680,5,300,40, "RoundXY", "Calibri.ttf",15, &tmh, (rGUI::bf_HAS_FRAME))); int poz_roundXY = widgets.size(); widgets.push_back(new rGUI::SlideBar(800,10,100,30,0,10,&tmh, (rGUI::bf_HORIZONTAL))); //Thickness widgets.push_back(new rGUI::TextBox(680,50,300,40, "Thickness", "Calibri.ttf",15, &tmh, (rGUI::bf_HAS_FRAME))); int poz_thickness = widgets.size(); widgets.push_back(new rGUI::SlideBar(800,55,100,30,0,10,&tmh, (rGUI::bf_HORIZONTAL))); //Added thickness widgets.push_back(new rGUI::TextBox(680,95,300,40, "Added Thickness", "Calibri.ttf",10, &tmh, (rGUI::bf_HAS_FRAME))); int poz_addedthickness = widgets.size(); widgets.push_back(new rGUI::SlideBar(800,100,100,30,0,10,&tmh, (rGUI::bf_HORIZONTAL))); //Update Button int poz_updatebutton = widgets.size(); widgets.push_back(new rGUI::Button(680,140,180,40,"Update Theme","Calibri.ttf", &tmh)); //Reset Button int poz_rb = widgets.size(); widgets.push_back(new rGUI::TextBox(862,140,36,40,"Reset theme","Calibri.ttf", 12, &tmh, (rGUI::bf_AS_BUTTON | rGUI::bf_HAS_FRAME | rGUI::bf_MULTILINE))); //widgets.push_back(new rGUI::Button(865,140,30,40,"Reset colors","Calibri.ttf", &tmh)); //Color selector int poz_colscba = widgets.size(); widgets.push_back(new rGUI::ScrollableArea(400,5,275,180,2000,2000,&tmh,0,0)); //red int poz_colsba_R = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::SlideBar(5,5,30,140,0,255,&tmh, rGUI::bf_VERTICAL)); //Green int poz_colsba_G = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::SlideBar(40,5,30,140,0,255,&tmh, rGUI::bf_VERTICAL)); //Blue int poz_colsba_B = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::SlideBar(75,5,30,140,0,255,&tmh, rGUI::bf_VERTICAL)); //Alpha int poz_colsba_A = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::SlideBar(110,5,30,140,0,255,&tmh, rGUI::bf_VERTICAL)); //cols int poz_colsba_cols = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::TextBox(15,150,120,20, "R G B A", "Calibri.ttf", 20, &tmh, rGUI::bf_HAS_FRAME)); //TextC int poz_colsba_c_T = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::Button(150,5,120,30, "Text color", "Calibri.ttf", &tmh)); //BackgroundC int poz_colsba_c_B = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::Button(150,40,120,30, "Background color", "Calibri.ttf", &tmh)); //OutlineC int poz_colsba_c_O = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::Button(150,75,120,30, "Outline color", "Calibri.ttf", &tmh)); //ClickingC int poz_colsba_c_C = widgets[poz_colscba]->widgets.size(); widgets[poz_colscba]->widgets.push_back(new rGUI::Button(150,110,120,30, "Clicking color", "Calibri.ttf", &tmh)); ((rGUI::ScrollableArea*)widgets[poz_colscba])->I_added_new_widgets(); //Drag&drop int poz_dbm = widgets.size(); widgets.push_back(new rGUI::DropBoxManager()); rGUI::DropBox_Item dpi; dpi.load_bmp_fom_file = true; dpi.bmp_str = "button.png"; dpi.print_x = 10; dpi.print_y = 10; dpi.print_w = 30; dpi.print_h = 30; widgets.push_back(new rGUI::DropBox(600,400,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm],&dpi)); dpi.load_bmp_fom_file = false; dpi.bmp = al_load_bitmap("button.png"); al_set_target_bitmap(dpi.bmp); al_draw_tinted_bitmap(dpi.bmp, al_map_rgba(255,0,0,100),0,0,0); std::vector<ALLEGRO_COLOR*> colvect; widgets[scbapoz]->widgets.push_back(new rGUI::DropBox(600,400,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm],&dpi)); for(int a = 0;a < 5;a++) { for(int b = 0;b < 5;b++) { if(a == 0 && b == 0) { continue; } ALLEGRO_COLOR tmpc = al_map_rgba(rand()%256,rand()%256,rand()%256,255); colvect.push_back(new ALLEGRO_COLOR); colvect[colvect.size()-1]->r = tmpc.r; colvect[colvect.size()-1]->g = tmpc.g; colvect[colvect.size()-1]->b = tmpc.b; colvect[colvect.size()-1]->a = tmpc.a; al_clear_to_color(tmpc); dpi.data = colvect[colvect.size()-1]; widgets.push_back(new rGUI::DropBox(600 + a*55,400 + b*55,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm], nullptr)); widgets[scbapoz]->widgets.push_back(new rGUI::DropBox(600 + a*55,400 + b*55,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm], &dpi)); } } al_set_target_backbuffer(display); int poz_backgroundDB = widgets.size(); widgets.push_back(new rGUI::DropBox(710,345,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm], nullptr)); int poz_scba_DP = widgets[scbapoz]->widgets.size(); widgets[scbapoz]->widgets.push_back(new rGUI::DropBox(710,345,50,50,&tmh, (rGUI::DropBoxManager*)widgets[poz_dbm], nullptr)); ((rGUI::ScrollableArea*)widgets[scbapoz])->I_added_new_widgets(); //Group int poz_ext = widgets.size(); widgets.push_back(new rGUI::Button(SCREEN_W - 50, SCREEN_H - 17,40,12,"Exit", "Calibri.ttf", &tmh)); int poz_group = widgets.size(); widgets.push_back(new rGUI::Group()); ((rGUI::Group*)widgets[poz_group])->Add_Widgets(widgets, 0, widgets.size()-1); int poz_ext_scba = widgets.size(); widgets.push_back(new rGUI::ScrollableArea( (SCREEN_W/2)-200, (SCREEN_H/2)-100, 400, 200,400,200,&tmh,14, 0)); widgets[poz_ext_scba]->widgets.push_back(new rGUI::Button(10,150,100,45,"Yes", "Calibri.ttf", &tmh)); widgets[poz_ext_scba]->widgets.push_back(new rGUI::Button(290,150,100,45,"No", "Calibri.ttf", &tmh)); widgets[poz_ext_scba]->widgets.push_back(new rGUI::TextBox(0,0,400,120, "Do you rly wanna go ?", "Calibri.ttf",100, &tmh, (rGUI::bf_HORIZONTAL_CENTER | rGUI::bf_VERTICAL_CENTER | rGUI::bf_RESIZE_CONTENT) )); ((rGUI::ScrollableArea*)widgets[poz_ext_scba])->I_added_new_widgets(); int poz_ext_group = widgets.size(); widgets.push_back(new rGUI::Group()); ((rGUI::Group*)widgets[poz_ext_group])->Add_Widgets(widgets, poz_ext_scba, widgets.size()-1); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Inputing(false); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Printing(false); ALLEGRO_TRANSFORM trans; al_identity_transform(&trans); al_scale_transform(&trans, _sx, _sy); al_translate_transform(&trans, _offx, _offy); //al_use_transform(&trans); int progresval = 0, progressadd = 1; ALLEGRO_COLOR backgroundcollor = al_map_rgb(255,255,255); float scale = 1.0f; while(1) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); rGUI::GetStatesAdnEvents(ev); if(ev.type == ALLEGRO_EVENT_TIMER) { progresval++; redraw = true; if(progresval >= 3) { progresval = 0; ((rGUI::ProgressBar*)widgets[progressbar])->Set_value( ((rGUI::ProgressBar*)widgets[progressbar])->Get_value() + progressadd); } } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES || ev.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) { bouncer_x = ev.mouse.x; bouncer_y = ev.mouse.y; } for(int a = 0;a < (int)widgets.size();a++) { widgets[a]->Input(); } if(widgets[poz_ext]->wd_md->md_clicked == true) { widgets[poz_ext]->wd_md->md_clicked = false; ((rGUI::Group*)widgets[poz_group])->Set_all_Inputing(false); ((rGUI::Group*)widgets[poz_group])->Set_all_Printing(false); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Inputing(true); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Printing(true); } if(widgets[poz_ext_scba]->widgets[0]->wd_md->md_clicked == true) { break; } else if(widgets[poz_ext_scba]->widgets[1]->wd_md->md_clicked == true) { widgets[poz_ext_scba]->widgets[1]->wd_md->md_clicked = false; ((rGUI::Group*)widgets[poz_group])->Set_all_Inputing(true); ((rGUI::Group*)widgets[poz_group])->Set_all_Printing(true); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Inputing(false); ((rGUI::Group*)widgets[poz_ext_group])->Set_all_Printing(false); } if(widgets[poz_updatebutton]->wd_md->md_clicked == true || widgets[poz_rb]->wd_md->md_clicked == true) { widgets[poz_updatebutton]->wd_md->md_clicked = false; tmh.thickness = ((rGUI::SlideBar*)widgets[poz_thickness])->value; tmh.added_thickness = ((rGUI::SlideBar*)widgets[poz_addedthickness])->value; tmh.roundx = tmh.roundy = ((rGUI::SlideBar*)widgets[poz_roundXY])->value; if(widgets[poz_rb]->wd_md->md_clicked == true) { widgets[poz_rb]->wd_md->md_clicked = false; thmreset(); } for(int a = 0;a < (int)widgets.size();a++) { widgets[a]->Update_theme(&tmh); } widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background = al_premul_rgba(((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_R])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_G])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_B])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_A])->Get_value()); } else if(widgets[poz_colscba]->widgets[poz_colsba_R]->wd_md->md_mouse_on_it == true || widgets[poz_colscba]->widgets[poz_colsba_G]->wd_md->md_mouse_on_it == true || widgets[poz_colscba]->widgets[poz_colsba_B]->wd_md->md_mouse_on_it == true || widgets[poz_colscba]->widgets[poz_colsba_A]->wd_md->md_mouse_on_it == true) { widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background = al_premul_rgba(((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_R])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_G])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_B])->Get_value(), ((rGUI::SlideBar*)widgets[poz_colscba]->widgets[poz_colsba_A])->Get_value()); } else if(widgets[poz_colscba]->widgets[poz_colsba_c_T]->wd_md->md_clicked == true) { tmh.c_text = widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background; widgets[poz_colscba]->widgets[poz_colsba_c_T]->wd_md->md_clicked = false; } else if(widgets[poz_colscba]->widgets[poz_colsba_c_O]->wd_md->md_clicked == true) { tmh.c_outline = widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background; widgets[poz_colscba]->widgets[poz_colsba_c_O]->wd_md->md_clicked = false; } else if(widgets[poz_colscba]->widgets[poz_colsba_c_B]->wd_md->md_clicked == true) { tmh.c_background = widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background; widgets[poz_colscba]->widgets[poz_colsba_c_B]->wd_md->md_clicked = false; } else if(widgets[poz_colscba]->widgets[poz_colsba_c_C]->wd_md->md_clicked == true) { tmh.c_clicking = widgets[poz_colscba]->widgets[poz_colsba_cols]->wd_theme.c_background; widgets[poz_colscba]->widgets[poz_colsba_c_C]->wd_md->md_clicked = false; } if(((rGUI::DropBox*)widgets[poz_backgroundDB])->changed) { if(((rGUI::DropBox*)widgets[poz_backgroundDB])->db_item != nullptr && ((rGUI::DropBox*)widgets[poz_backgroundDB])->db_item->data != nullptr) { ((rGUI::DropBox*)widgets[poz_backgroundDB])->changed = false; rGUI::DropBox *tmpdb = ((rGUI::DropBox*)widgets[poz_backgroundDB]); backgroundcollor.r = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->r; backgroundcollor.g = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->g; backgroundcollor.b = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->b; backgroundcollor.a = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->a; } else { backgroundcollor = al_map_rgb(255,255,255); } } if(((rGUI::DropBox*)(widgets[scbapoz]->widgets[poz_scba_DP]))->db_item != nullptr && ((rGUI::DropBox*)(widgets[scbapoz]->widgets[poz_scba_DP]))->db_item->data != nullptr && ((rGUI::DropBox*)(widgets[scbapoz]->widgets[poz_scba_DP]))->changed) { ((rGUI::DropBox*)(widgets[scbapoz]->widgets[poz_scba_DP]))->changed = false; rGUI::DropBox *tmpdb = ((rGUI::DropBox*)(widgets[scbapoz]->widgets[poz_scba_DP])); widgets[scbapoz]->wd_theme.c_background.r = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->r; widgets[scbapoz]->wd_theme.c_background.g = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->g; widgets[scbapoz]->wd_theme.c_background.b = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->b; widgets[scbapoz]->wd_theme.c_background.a = ((ALLEGRO_COLOR*)(tmpdb->db_item->data))->a; } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; al_clear_to_color(backgroundcollor); al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0); for(int a = 0;a < (int)widgets.size();a++) { widgets[a]->Print(); } widgets[poz_dbm]->Print(); al_flip_display(); } } for(int a = 0;a < (int)widgets.size();a++) { delete widgets[a]; } widgets.clear(); for(int a = 0;a < (int)colvect.size();a++) { delete colvect[a]; } colvect.clear(); rGUI::End(); al_destroy_bitmap(bouncer); al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); al_destroy_font(fnt); al_destroy_font(font); return 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(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; }
ScreenPlay::ScreenPlay(Button *ext_b) : but(ext_b) { n_font = al_load_font("resources/fonts/Asimov.otf",40,0); m_font = al_load_font("resources/fonts/Calibri.ttf",30,0); std::string bnames[SCREENPLAY_NMB] = {"Back", "New game", "OK"}; int bpoz[SCREENPLAY_NMB][4] = { {1300, global::dHeight -70, 120, 50}, {(global::dWidth-120)/2, global::dHeight -70, 120, 50}, {(global::dWidth-120)/2, (global::dHeight-50)/2 +45, 120, 50} }; for(int a = 0;a < SCREENPLAY_NMB;a++) { buttons.push_back(new Button("resources/fonts/Calibri.ttf", bpoz[a][0], bpoz[a][1], bpoz[a][0] + bpoz[a][2],bpoz[a][1] + bpoz[a][3], bnames[a], al_map_rgb(0,0,128))); } buttons[OK]->Active(false); buttons[OK]->Print_active(false); scba = new ScrollableArea(((float)global::dWidth - 500.0f)/2.0f ,100, 500 ,global::dHeight-200); scba->background_col = al_map_rgba(50,50,50,120); //graphic background trash zemak_bitmpa = al_load_bitmap("resources/graphics/zemiacik.png"); if(zemak_bitmpa == nullptr) { error_message("Could not load image : resources/graphics/zemiacik.png"); } std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count()); std::uniform_int_distribution<int> distribution(1,5); std::uniform_real_distribution<float> change(-10, 10); std::uniform_int_distribution<int> width(0,global::dWidth - ZEMIAK_SIZE); std::uniform_int_distribution<int> height(0,global::dHeight-ZEMIAK_SIZE); number_of_zemaky = distribution(generator); zemaky = new float[number_of_zemaky*4]; for(int a = 0;a < number_of_zemaky*4;a+=4) { zemaky[a] = width(generator); zemaky[a+1] = height(generator); zemaky[a+2] = round(change(generator)); zemaky[a+3] = round(change(generator)); } //------------------------------------------ //Saves loading gms = new GameSave(); std::string dum; int a = 0; ALLEGRO_FS_ENTRY* dir = al_create_fs_entry("saves/"); if(al_open_directory(dir) == false) { al_make_directory("saves/"); } if(al_open_directory(dir)) { ALLEGRO_FS_ENTRY* file; while(file = al_read_directory(dir)) { dum = al_get_fs_entry_name(file); if( al_get_fs_entry_mode(file) == ALLEGRO_FILEMODE_ISDIR || dum.substr(dum.size()-4,4) != ".sav") { continue; } gms->Load(dum); savefiles.push_back(dum); scba->AddText(5, a * 100 +10, gms->Get_player_name(), al_map_rgb(255,215,0), &n_font); scba->AddButton("resources/fonts/Calibri.ttf", 400, a * 100 + 60, 75, 30, "Load", al_map_rgb(0,0,139)); scba->AddRectangle(1,a * 100 , 500, 100, 2, al_map_rgb(10,10,10)); scba->AddText(10, a * 100 + 60, "Mission: " + std::to_string(gms->Get_mission_number()), al_map_rgb(255,255,250), &m_font); a++; gms->Save(); } al_destroy_fs_entry(file); } al_destroy_fs_entry(dir); }
ALLEGRO_FONT *load_font(const char *file, int font) { auto tmp = al_load_font(file, font, ALLEGRO_TTF_MONOCHROME); assert(tmp && printf("Loaded %s\n", file)); return tmp; }
int main(void) { //primitive variable bool done = false; bool redraw = true; const int FPS = 60; bool isGameOver = false; //object variables SpaceShip ship; Bullet bullets[NUM_BULLETS]; Comet comets[NUM_COMETS]; //Allegro variables ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font18 = NULL; //Initialization Functions if(!al_init()) //initialize Allegro return -1; display = al_create_display(WIDTH, HEIGHT); //create our display object if(!display) //test display object return -1; al_init_primitives_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); srand(time(NULL)); InitShip(ship); InitBullet(bullets, NUM_BULLETS); InitComet(comets, NUM_COMETS); font18 = al_load_font("arial.ttf", 18, 0); 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)); al_start_timer(timer); while(!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; if(keys[UP]) MoveShipUp(ship); if(keys[DOWN]) MoveShipDown(ship); if(keys[LEFT]) MoveShipLeft(ship); if(keys[RIGHT]) MoveShipRight(ship); if(!isGameOver) { UpdateBullet(bullets, NUM_BULLETS); StartComet(comets, NUM_COMETS); UpdateComet(comets, NUM_COMETS); CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship); CollideComet(comets, NUM_COMETS, ship); if(ship.lives <= 0) isGameOver = true; } } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = true; FireBullet(bullets, NUM_BULLETS, ship); break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = false; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = false; break; } } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; if(!isGameOver) { DrawShip(ship); DrawBullet(bullets, NUM_BULLETS); DrawComet(comets, NUM_COMETS); al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score); } else { al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score); } al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } } al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_font(font18); al_destroy_display(display); //destroy our display object return 0; }