int main() { const int SCREEN_W = 1280, SCREEN_H = 768; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE* queue; ALLEGRO_FONT* century_gothic40; ALLEGRO_FONT* century_gothic24; ALLEGRO_BITMAP* MenuBackground; ALLEGRO_BITMAP* ArenaBackground; ALLEGRO_BITMAP* Ball; //ALLEGRO_SAMPLE* BackgroundMusic; //ALLEGRO_SAMPLE* Boop; //ALLEGRO_SAMPLE* Score; //ALLEGRO_SAMPLE* Intro; ALLEGRO_TIMER* timer; Gamemode gamemode = Menu; std::string player_text = "PLAYER : 0", ai_text = "BOT : 0"; unsigned int player_score = 0, ai_score = 0; if(!al_init()) { printf("al_init Failed!\n"); return -1; } //if(!al_install_audio()) //{ //fprintf(stderr, "Failed to initialize audio!\n"); //return -1; //} //if(!al_init_acodec_addon()) //{ //fprintf(stderr, "Failed to initialize audio codecs!\n"); //return -1; //} //if (!al_reserve_samples(1)) //{ //fprintf(stderr, "Failed to reserve samples!\n"); //return -1; //} if(!al_install_mouse()) { fprintf(stderr, "Failed to initialize the mouse!\n"); return -1; } if(!al_init_primitives_addon()) { printf("al_init_primitives_addon Failed!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { printf("al_create_display Failed!\n"); return -1; } srand(time(NULL)); al_init_font_addon(); al_init_ttf_addon(); al_install_keyboard(); al_init_image_addon(); queue = al_create_event_queue(); timer = al_create_timer(1.0 / 60); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_timer_event_source(timer)); al_start_timer(timer); century_gothic40 = al_load_ttf_font("C:\\Windows\\Fonts\\GOTHIC.TTF" , 40, ALLEGRO_ALIGN_CENTRE); century_gothic24 = al_load_ttf_font("C:\\Windows\\Fonts\\GOTHIC.TTF" , 24, ALLEGRO_ALIGN_CENTRE); MenuBackground = LoadB("res\\menu.png"); ArenaBackground = LoadB("res\\arena.png"); Ball = LoadB("res\\ball.png"); //BackgroundMusic = LoadS("res\\rain.wav"); //Boop = LoadS("res\\boop.ogg"); //Score = LoadS("res\\score.wav"); //Intro = LoadS("res\\intro.ogg"); //ALLEGRO_VOICE *audioDevice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2); //ALLEGRO_MIXER *mixerMaster = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2); //ALLEGRO_MIXER *mixerMusic = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2); //ALLEGRO_MIXER *mixerSounds = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32 , ALLEGRO_CHANNEL_CONF_2); //if (audioDevice == NULL || mixerMaster == NULL || mixerMusic == NULL || mixerSounds == NULL) //{ //printf("Failed to start audio devices"); //} /* Attempt of Audio al_attach_sample_instance_to_mixer(Boop, mixerSounds); al_attach_sample_instance_to_mixer(BackgroundMusic, mixerMusic); al_attach_sample_instance_to_mixer(Score, mixerSounds); al_attach_sample_instance_to_mixer(Intro, mixerSounds); al_attach_mixer_to_mixer(mixerMusic, mixerMaster); al_attach_mixer_to_mixer(mixerSounds, mixerMaster); al_attach_mixer_to_voice(mixerMaster, audioDevice); //ALLEGRO_SAMPLE_INSTANCE BoopI = al_create_sample_instance(Boop); //ALLEGRO_SAMPLE_INSTANCE ScoreI = al_create_sample_instance(Score); //al_play_sample(BackgroundMusic, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);*/ float player_y = 0, player_y_vel = 0, ai_y_vel = 0, ai_y = 0, ball_x = (SCREEN_W/2)-12, ball_x_vel = (rand() % 2) ? 5 : -5, ball_y = (SCREEN_H/2)-15, ball_y_vel = 0, multiplier = 1; bool render , scored, executing = true; //al_play_sample(Intro, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL); while (executing) { ALLEGRO_EVENT event; al_wait_for_event(queue, &event); switch(event.type) { case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: switch (gamemode) { case Menu: if ((event.mouse.x >= (SCREEN_W / 2) - 150) && (event.mouse.x <= (SCREEN_W / 2) + 150)) { if ((event.mouse.y >= 205) && (event.mouse.y <= 280)) { gamemode = Game; } else if ((event.mouse.y >= 305) && (event.mouse.y <= 380)) { gamemode = Description; } else if ((event.mouse.y >= 405) && (event.mouse.y <= 480)) { executing = false; } } break; case Description: break; case Conclusion: if ((event.mouse.x >= (SCREEN_W/2)-150) && (event.mouse.x <= (SCREEN_W/2)+150)) { if ((event.mouse.y >= 305) && (event.mouse.y <= 380)) { player_score = ai_score = player_y = player_y_vel = ai_y_vel = ai_y = ball_y_vel = 0; ball_x_vel = (rand() % 2) ? 5 : -5; ball_x = (SCREEN_W / 2) - 12; ball_y = (SCREEN_H / 2) - 15; multiplier = 1; player_text = "PLAYER : 0"; ai_text = "BOT : 0"; gamemode = Menu; } else if ((event.mouse.y >= 405) && (event.mouse.y <= 480)) { executing = false; } } break; } break; case ALLEGRO_EVENT_DISPLAY_CLOSE: executing = false; break; case ALLEGRO_EVENT_KEY_DOWN: switch(event.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: switch (gamemode) { case Game: executing = false; break; } break; case ALLEGRO_KEY_UP: case ALLEGRO_KEY_W: player_y_vel = -10; break; case ALLEGRO_KEY_DOWN: case ALLEGRO_KEY_S: player_y_vel = 10; break; case ALLEGRO_KEY_ENTER: executing = false; break; } gamemode = Game; break; case ALLEGRO_EVENT_KEY_UP: player_y_vel = 0; break; case ALLEGRO_EVENT_TIMER: render = true; switch(gamemode) { case Game: // Scoring bool scored = false; if (ball_x >= SCREEN_W) { player_score++; scored = true; std::stringstream ss; ss << "PLAYER : " << player_score; player_text = ss.str(); } if (ball_x <= 0) { ai_score++; scored = true; std::stringstream ss; ss << "BOT : " << ai_score; ai_text = ss.str(); } if (scored) { //al_play_sample(Score, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL); //al_play_sample_instance(ScoreI); ball_x = (SCREEN_W/2)-12; ball_y = (SCREEN_H/2)-15; ball_x_vel = (rand() % 2) ? 5.75 : -5.75; ball_y_vel = 0; ai_y = 0; player_y = 0; multiplier = 1; } // Collision if (((((SCREEN_H/2)-50)+player_y)<=0)&&(player_y_vel<0)) player_y_vel = 0; if (((((SCREEN_H/2)+50)+player_y)>=SCREEN_H)&&(player_y_vel>0)) player_y_vel = 0; if ((ball_y <= 0) || (ball_y >= SCREEN_H)) ball_y_vel = -ball_y_vel; if (((ball_y <= (((SCREEN_H / 2) + 50) + player_y) && (ball_y >= (((SCREEN_H / 2) - 50) + player_y))) && ((ball_x <= 90) && (ball_x >= 75))) || (((ball_y <= (((SCREEN_H / 2) + 50) + ai_y)) && (ball_y >= (((SCREEN_H / 2) - 50) + ai_y))) && (((ball_x >= SCREEN_W - 110)) && (ball_x <= SCREEN_W - 75)))) { //al_play_sample(Boop, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL); //al_play_sample_instance(BoopI); ball_x_vel = -ball_x_vel * multiplier; multiplier += 0.005f; ball_y_vel = (rand() % 10) - 5; } // AI if (ball_x_vel > 0) // Ball comming towards AI { if ((ai_y <= 340) && (ai_y >= -340)) // AI is in game bounds { if ((SCREEN_H/2)+ai_y < ball_y) ai_y_vel = abs(ball_y_vel) < 3 ? abs(ball_y_vel) : 5; else if ((SCREEN_H/2)+ai_y == ball_y) ai_y_vel = 0; else ai_y_vel = abs(ball_y_vel) < 3 ? -abs(ball_y_vel) : -5; } else if (ai_y > 340) ai_y_vel = -3; else if (ai_y < -340) ai_y_vel = 3; else ai_y_vel = 0; } else // Go towards center { if (ai_y > 10) ai_y_vel = -1; else if (ai_y < 10) ai_y_vel = 1; else ai_y_vel = 0; } // Movement player_y += player_y_vel; ai_y += ai_y_vel; ball_x += ball_x_vel; ball_y += ball_y_vel; if (player_score >= 10 || ai_score >= 10) gamemode = Conclusion; break; } break; } if (al_is_event_queue_empty(queue) && render) { al_clear_to_color(al_map_rgb(0,0,0)); al_set_target_bitmap(al_get_backbuffer(display)); //////////////////////////////////////////////////////////////////// switch(gamemode) { case Menu: al_draw_bitmap(MenuBackground, 0, 0, 0); al_draw_text(century_gothic40, al_map_rgb(250,250,250), SCREEN_W/2, 40, ALLEGRO_ALIGN_CENTRE, "Ultimate Pong"); al_draw_rectangle((SCREEN_W / 2) - 150, 205, (SCREEN_W / 2) + 150, 280, al_map_rgb(255, 255, 255), 3); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 220, ALLEGRO_ALIGN_CENTRE, "Play"); al_draw_rectangle((SCREEN_W / 2) - 150, 305, (SCREEN_W / 2) + 150, 380, al_map_rgb(255, 255, 255), 3); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 320, ALLEGRO_ALIGN_CENTRE, "About"); al_draw_rectangle((SCREEN_W / 2) - 150, 405, (SCREEN_W / 2) + 150, 480, al_map_rgb(255, 255, 255), 3); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 420, ALLEGRO_ALIGN_CENTRE, "Quit"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 200, SCREEN_H - 50, ALLEGRO_ALIGN_CENTRE, "Game by Thomas Steinholz"); break; case Description: al_draw_bitmap(MenuBackground, 0, 0, 0); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 40, ALLEGRO_ALIGN_CENTRE, "About Ultimate Pong"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 240, ALLEGRO_ALIGN_LEFT, "This is the game of Ultimate Pong! The game consists of 2 paddles knocking a ball back and"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 260, ALLEGRO_ALIGN_LEFT, "forth until one misses it and it goes into the goal. The point of the game is to score 10 "); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 280, ALLEGRO_ALIGN_LEFT, "points. You can score a point by getting the ball in the other player's goal (right behind"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 300, ALLEGRO_ALIGN_LEFT, "the enemy paddle). You control the game by using either the UP and DOWN arrow or the W and"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 320, ALLEGRO_ALIGN_LEFT, "S key. As you can guess, the up arrow brings your player up while the down arrow brings "); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 340, ALLEGRO_ALIGN_LEFT, "your player down. The W key functions the same as the UP arrow as the S key functions the"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 360, ALLEGRO_ALIGN_LEFT, "same as the DOWN key. The game ends once either the player of AI has reached a point value"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 380, ALLEGRO_ALIGN_LEFT, "of 10. You play as the left paddle and the AI plays as the right paddle. You can see the "); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 400, ALLEGRO_ALIGN_LEFT, "corresponding scores above the side you play as if you get lost or confused. To get "); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 100, 420, ALLEGRO_ALIGN_LEFT, "started, hit the ESC button. DISCLAIMER : IF YOU GET HURT, ITS NOT PONGS FAULT SO DONT SUE"); al_draw_text(century_gothic24, al_map_rgb(250,250,250), 200, SCREEN_H - 50, ALLEGRO_ALIGN_CENTRE, "PRESS sESC TO PLAY"); break; case Game: al_draw_bitmap(ArenaBackground, 0, 0, 0); al_draw_line((SCREEN_W/2)-3,0,(SCREEN_W/2)-3,SCREEN_H,al_map_rgb(255,255,255), 2); al_draw_circle((SCREEN_W/2)-5,(SCREEN_H/2)-5, 150, al_map_rgb(255,255,255), 2); al_draw_filled_rectangle(75,((SCREEN_H/2)-50)+player_y,90,((SCREEN_H/2)+50)+player_y,al_map_rgb(255,255,255)); //Player al_draw_filled_rectangle(SCREEN_W-75,((SCREEN_H/2)-50)+ai_y,SCREEN_W-90,((SCREEN_H/2)+50)+ai_y,al_map_rgb(255,255,255)); //AI al_draw_scaled_bitmap( Ball, 0, 0, al_get_bitmap_width(Ball), al_get_bitmap_height(Ball), ball_x, ball_y, 15, 15, 0); al_draw_text(century_gothic40, al_map_rgb(250,250,250), 140, 40, ALLEGRO_ALIGN_CENTRE, player_text.c_str()); al_draw_text(century_gothic40, al_map_rgb(250,250,250), SCREEN_W-100, 40, ALLEGRO_ALIGN_CENTRE, ai_text.c_str()); break; case Conclusion: al_draw_bitmap(MenuBackground, 0, 0, 0); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 40, ALLEGRO_ALIGN_CENTRE, "Game Over!"); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 80, ALLEGRO_ALIGN_CENTRE, ai_score < player_score ? "You Win!" : "You Lose!"); al_draw_textf(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 120, ALLEGRO_ALIGN_CENTRE, "%d : %d", player_score, ai_score); al_draw_rectangle((SCREEN_W/2)-150, 305, (SCREEN_W/2)+150, 380, al_map_rgb(255, 255, 255), 3); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 320, ALLEGRO_ALIGN_CENTRE, "Restart"); al_draw_rectangle((SCREEN_W / 2) - 150, 405, (SCREEN_W / 2) + 150, 480, al_map_rgb(255, 255, 255), 3); al_draw_text(century_gothic40, al_map_rgb(250, 250, 250), SCREEN_W / 2, 420, ALLEGRO_ALIGN_CENTRE, "Quit"); break; } //////////////////////////////////////////////////////////////////// al_flip_display(); } render = false; } al_destroy_bitmap(MenuBackground); al_destroy_bitmap(ArenaBackground); al_destroy_bitmap(Ball); //al_destroy_sample(BackgroundMusic); //al_destroy_sample(Boop); //al_destroy_sample(Score); al_destroy_display(display); return 0; }
int inicializadores(int *LARGURA_TELA, int *ALTURA_TELA, float *FPS, ALLEGRO_DISPLAY *janela , ALLEGRO_EVENT_QUEUE *fila_eventos, ALLEGRO_BITMAP *poderes, ALLEGRO_FONT *fonte_equacao, ALLEGRO_FONT *fonte_pontos, ALLEGRO_TIMER *timer){ if (!al_init()){ fprintf(stderr, "Falha ao inicializar a Allegro.\n"); return -1; } al_init_image_addon(); // 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()){ fprintf(stderr, "Falha ao inicializar add-on allegro_ttf.\n"); return -1; } janela = al_create_display(LARGURA_TELA, ALTURA_TELA); if (!janela){ fprintf(stderr, "Falha ao criar janela.\n"); return -1; } timer = al_create_timer(1.0 / FPS); if(!timer){ fprintf(stderr, "failed to create timer!\n"); return -1; } // Configura o título da janela al_set_window_title(janela, "PENAS - Telas de Poderes -"); fonte_equacao = al_load_font("fontes/letra_equacao.ttf", 36, 0); if (!fonte_equacao){ al_destroy_display(janela); fprintf(stderr, "Falha ao carregar fonte.\n"); return -1; } fonte_pontos = al_load_font("fontes/letra_equacao.ttf", 26, 0); if (!fonte_pontos){ al_destroy_display(janela); fprintf(stderr, "Falha ao carregar fonte.\n"); return -1; } // Torna apto o uso de mouse na aplicação if (!al_install_mouse()){ fprintf(stderr, "Falha ao inicializar o mouse.\n"); al_destroy_display(janela); return -1; } // Atribui o cursor padrão do sistema para ser usado if (!al_set_system_mouse_cursor(janela, ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT)){ fprintf(stderr, "Falha ao atribuir ponteiro do mouse.\n"); al_destroy_display(janela); return -1; } fila_eventos = al_create_event_queue(); if (!fila_eventos){ fprintf(stderr, "Falha ao inicializar o fila de eventos.\n"); al_destroy_display(janela); return -1; } if (!al_init_primitives_addon()){ fprintf(stderr, "Falha ao inicializar add-on de primitivas.\n"); return false; } // Dizemos que vamos tratar os eventos vindos do mouse al_register_event_source(fila_eventos, al_get_mouse_event_source()); al_register_event_source(fila_eventos, al_get_display_event_source(janela)); al_register_event_source(fila_eventos, al_get_timer_event_source(timer)); }
int main() { //shell vars bool render = false; //allegro vars ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; //allegro init functions printf ("Initializing allegro\n"); if (!al_init()) { al_show_native_message_box(NULL, NULL, NULL, "failed", NULL, 0); return -1; } printf("Creating display\n"); display = al_create_display(WIDTH, HEIGHT); if (!display) { al_show_native_message_box(NULL, NULL, NULL, "failed", NULL, 0); return -1; } printf("Installing addons\n"); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); al_init_image_addon(); al_install_keyboard(); al_install_mouse(); al_install_audio(); al_init_acodec_addon(); al_reserve_samples(10); //project inits srand(time(NULL)); printf("Initializing timer\n"); event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); printf("Registering event sources\n"); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_start_timer(timer); printf("Init mouse and keyboard\n"); init_keyboard(); init_mouse(); printf("Loading assets\n"); load_bitmaps(); load_fonts(); load_samples(); printf ("Creating manager\n"); push_state(new TitleMenu()); printf("Beginning game\n"); while (!is_game_over()) { //declare an event ALLEGRO_EVENT event; //monitor event sources al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { end_game(); } else if (event.type == ALLEGRO_EVENT_TIMER) { render = true; update_mouse(); update_keyboard(); handle_key(); update_game(); } // Render screen if (render && al_event_queue_is_empty(event_queue)) { render = false; render_game(); al_flip_display(); } } unload_assets(); al_destroy_event_queue(event_queue); al_destroy_display(display); al_destroy_timer(timer); return 0; }
int init::init_all() { //this->display; srand (time(NULL)); if(!al_init()) { fprintf(stderr, "failed to initialize randomness!\n"); return -1; } if(!al_init_primitives_addon()) { fprintf(stderr, "failed to initialize primitives addon!\n"); return -1; } if(!al_install_keyboard()) { fprintf(stderr, "failed to initialize keyboard!\n"); return -1; } if(!al_install_mouse()) { fprintf(stderr, "failed to initialize mouse!\n"); return -1; } if(FULLSCREEN) { ALLEGRO_DISPLAY_MODE disp_data; al_get_display_mode(0, &disp_data); al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW | ALLEGRO_OPENGL); fprintf(stderr,"%i %i",disp_data.width,disp_data.height); this->screenWidth = disp_data.width; this->screenHeight = disp_data.height; this->display = al_create_display(disp_data.width, disp_data.height); } else { this->display = al_create_display(screenWidth,screenHeight); } if(!display) { fprintf(stderr, "failed to create display!\n"); return -1; } al_set_new_bitmap_flags(ALLEGRO_MAG_LINEAR | ALLEGRO_MIN_LINEAR); al_init_font_addon(); if(!al_init_ttf_addon()) { fprintf(stderr, "failed to initialize font addon!\n"); return -1; } this->timer = al_create_timer(1.0 / FPS); if(!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } this->font = al_load_ttf_font("resources/pirulen.ttf",14,0); if (!font) { fprintf(stderr, "Could not load 'pirulen.ttf'.\n"); return -1; } if (!al_init_image_addon()) { fprintf(stderr, "Could not initialize image addon.\n"); return -1; } this->event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); } al_register_event_source(this->event_queue, al_get_timer_event_source(this->timer)); al_register_event_source(this->event_queue, al_get_keyboard_event_source()); al_register_event_source(this->event_queue, al_get_display_event_source(this->display)); al_register_event_source(this->event_queue, al_get_mouse_event_source()); al_start_timer(timer); return 0; }
int main (int argc, char *argv[]) { al_init(); ALLEGRO_DISPLAY *display = al_create_display(640, 480); al_init_primitives_addon(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); srand(time(NULL)); char* disappointed[] = {" Razocharovana sum!", " Tolkova losho kontrolno ne sum vijdala!", "Golqm murzel vi e nalegnal...", " Potresavashto!!"}; ALLEGRO_BITMAP *image = al_load_bitmap("pic.bmp"); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_TIMER *timer = al_create_timer(1/60.0); al_register_event_source(event_queue, al_get_timer_event_source(timer)); ALLEGRO_FONT *font = al_load_font("Arial.ttf", 20, 0); int done = 0; int render = 0; int x = 375; int y = 340; int traveled_y = 0; int delay = 120; int time_elapsed = 0; int dir = -1; int move_left = 0; int traveled_x = 0; int time_elapsed2 = 0; int draw_text = 0; int random = 0; int should_draw_text = 0; al_start_timer(timer); while(!done) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if(event.type == ALLEGRO_EVENT_TIMER) { if(x < 50) done = 1; if(traveled_y >= 75) { if(!draw_text) { random = rand() % 4; if(y < 350) should_draw_text = 1; } draw_text = 1; if(++time_elapsed >= delay) { traveled_y = 0; time_elapsed = 0; if(y <= 60 || y >= 375) { if(!move_left) { if(y <= 60) { if(traveled_x >= 50) { if(++time_elapsed2 >= delay) { traveled_x = 0; time_elapsed2 = 0; move_left = 1; } } else { x -= 3; traveled_x += 3; } } else if(y >= 375) { should_draw_text = 0; if(traveled_x >= 140) { if(++time_elapsed2 >= delay) { traveled_x = 0; time_elapsed2 = 0; move_left = 1; } } else { x -= 3; traveled_x += 3; } } time_elapsed = 120; traveled_y = 75; } else { dir *= -1; move_left = 0; } } } } else { draw_text = 0; should_draw_text = 0; y += 3 * dir; traveled_y += 3; } render = 1; } if(render) { al_draw_bitmap(image, 0, 0, 0); al_draw_pixel(x, y, al_map_rgb(255, 0, 0)); if(should_draw_text) { al_draw_text(font, al_map_rgb(255, 255, 255), 10, 450, 0, disappointed[random]); } al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); render = 0; } } al_destroy_display(display); al_destroy_bitmap(image); al_destroy_event_queue(event_queue); al_destroy_timer(timer); return 0; }
int main() { // don't forget to put allegro-5.0.10-monolith-md-debug.lib const float FPS = 60.0f; ALLEGRO_DISPLAY *display; if(!al_init()) { al_show_native_message_box(NULL,"Error","Error", "Cannot initialize Allegro", NULL, NULL); return -1; } display = al_create_display(ScreenWidth, ScreenHeight); if(!display) { al_show_native_message_box(NULL,"Error","Error", "Cannot create dsiplay", NULL, NULL); return -1; } al_set_window_position(display, 100, 100); al_install_keyboard(); al_install_mouse(); al_init_image_addon(); //al_init_acodec_addon(); al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_TIMER *timer = al_create_timer(1.0f / FPS); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_KEYBOARD_STATE keyState; al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_display_event_source(display)); bool done = false; InputManager input; ScreenManager::GetInstance().Initialize(); ScreenManager::GetInstance().LoadContent(); std::vector<int> keys; //these two below plus the IsKeyReleased are example how to use simultaneous keys keys.push_back(ALLEGRO_KEY_DOWN); keys.push_back(ALLEGRO_KEY_ESCAPE); float fade = 0.0f; al_start_timer(timer); while (!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); al_get_keyboard_state(&keyState); if(input.IsKeyReleased(ev,keys)) done=true; //closes the game //barnhen to check begin if(input.IsKeyPressed(ev, ALLEGRO_KEY_RIGHT)) fade++; else if(input.IsKeyPressed(ev, ALLEGRO_KEY_LEFT)) fade--; //barnhen to check end ScreenManager::GetInstance().Update(ev); ScreenManager::GetInstance().Draw(display); al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } ScreenManager::GetInstance().UnloadContent(); //Destroyers al_destroy_display(display); al_destroy_timer(timer); al_destroy_event_queue(event_queue); //std::cin.get(); return 0; }
int main() { bool done = false; bool redraw = true; bool is_game_over = false; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *events = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font20 = NULL; ALLEGRO_FONT *font40 = NULL; if (!al_init()) return 1; display = al_create_display(DISPLAY_WIDTH, DISPLAY_HEIGHT); if (!display) return 1; // Initialize add-ons al_init_primitives_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); timer = al_create_timer(1.0 / FPS); events = al_create_event_queue(); al_register_event_source(events, al_get_keyboard_event_source()); al_register_event_source(events, al_get_timer_event_source(timer)); font20 = al_load_font("arial.ttf", 20, 0); font40 = al_load_font("arial.ttf", 40, 0); al_start_timer(timer); while (!done) { // Events handling ALLEGRO_EVENT ev; al_wait_for_event(events, &ev); if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_J: keys[J] = false; break; case ALLEGRO_KEY_K: keys[K] = false; break; case ALLEGRO_KEY_S: keys[S] = false; break; case ALLEGRO_KEY_D: keys[D] = false; break; case ALLEGRO_KEY_ESCAPE: done = true; break; } } else if (ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; if (!is_game_over) { updateBall(*ball); updateLeftBar(*bar1); updateRightBar(*bar2); handleCollision(*bar1, *bar2, *ball); if (score1 == WINNING_SCORE || score2 == WINNING_SCORE) is_game_over = true; } } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_J: keys[J] = true; break; case ALLEGRO_KEY_K: keys[K] = true; break; case ALLEGRO_KEY_S: keys[S] = true; break; case ALLEGRO_KEY_D: keys[D] = true; break; } } if (redraw && al_is_event_queue_empty(events)) { redraw = false; if (!is_game_over) { // Rendering al_clear_to_color(al_map_rgb(0, 0, 0)); ball->render(); bar1->render(); bar2->render(); al_draw_textf(font20, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT - 40, ALLEGRO_ALIGN_CENTRE, "%d : %d", score1, score2); al_flip_display(); } else { al_clear_to_color(al_map_rgb(0, 0, 0)); if (score1 == WINNING_SCORE) al_draw_text(font40, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 20, ALLEGRO_ALIGN_CENTRE, "PLAYER 1 WON"); else if (score2 == WINNING_SCORE) al_draw_text(font40, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 20, ALLEGRO_ALIGN_CENTRE, "PLAYER 2 WON"); al_draw_text(font20, al_map_rgb(255, 255, 255), DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 + 40, ALLEGRO_ALIGN_CENTRE, "Press 'r' to start a new game"); al_flip_display(); } } } // House cleaning delete ball; delete bar1; delete bar2; al_destroy_font(font20); al_destroy_font(font40); al_destroy_display(display); al_destroy_event_queue(events); 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) { 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; }
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(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; }
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; }
bool GameLogic::InitializeAllegro() { if(!al_init()) { fprintf(stderr, "Failed to initialize allegro!\n"); return false; } if(Debug) { fprintf(stderr, "Allegro 5 initialized.\n"); } if(!al_install_keyboard()) { fprintf(stderr, "Failed to initialize the keyboard!\n"); return false; } if(Debug) { fprintf(stderr, "Keyboard initialized.\n"); } if(!al_install_mouse()) { fprintf(stderr, "Failed to initialize the mouse!\n"); return false; } if(Debug) { fprintf(stderr, "Mouse initialized.\n"); } Timer = al_create_timer(TimerStep); if(!Timer) { fprintf(stderr, "Failed to create Timer!\n"); return false; } if(Debug) { fprintf(stderr, "Timer initialized.\n"); } if(!al_init_image_addon()) { fprintf(stderr, "Failed to initialize images loading!\n"); return false; } if(Debug) { fprintf(stderr, "Image loading initialized.\n"); } if(!al_init_primitives_addon()) { fprintf(stderr, "Failed to initialize primitives!\n"); return false; } if(Debug) { fprintf(stderr, "Primitives addon initialized.\n"); } al_init_font_addon(); if(!al_init_ttf_addon()) { fprintf(stderr, "Failed to initialize TrueType!\n"); return false; } if(Debug) { fprintf(stderr, "TTF font loading initialized.\n"); } if(!al_install_audio()) { fprintf(stderr, "Failed to initialize audio!\n"); return false; } if(Debug) { fprintf(stderr, "Audio initialized.\n"); } if(!al_init_acodec_addon()) { fprintf(stderr, "Failed to initialize audio codecs!\n"); return false; } if(Debug) { fprintf(stderr, "Ogg/FLAC initialized.\n"); } // create and confirm allegro Display Display = al_create_display(DisplayWidth, DisplayHeight); if(!Display) { fprintf(stderr, "Failed to create Display!\n"); return false; } if(Debug) { fprintf(stderr, "Display initialized.\n"); } // Make sure we are on the backbuffer al_set_target_bitmap(al_get_backbuffer(Display)); Voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if (!Voice) { fprintf(stderr, "Could not create ALLEGRO_VOICE.\n"); return 1; } if(Debug) { fprintf(stderr, "Voice created.\n"); } Mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,ALLEGRO_CHANNEL_CONF_2); if (!Mixer) { fprintf(stderr, "Could not create ALLEGRO_MIXER.\n"); return 1; } if(Debug) { fprintf(stderr, "Mixer created.\n"); } if (!al_attach_mixer_to_voice(Mixer, Voice)) { fprintf(stderr, "Attaching Mixer to Voice failed.\n"); return 1; } if(Debug) { fprintf(stderr, "Mixer attached to Voice.\n"); } // create and confirm event queue EventQueue = al_create_event_queue(); if(!EventQueue) { fprintf(stderr, "Failed to create EventQueue!\n"); return false; } if(Debug) { fprintf(stderr, "Event queue created successfully.\n"); } al_register_event_source(EventQueue, al_get_display_event_source(Display)); al_register_event_source(EventQueue, al_get_timer_event_source(Timer)); al_register_event_source(EventQueue, al_get_mouse_event_source()); al_register_event_source(EventQueue, al_get_keyboard_event_source()); // blank the Display al_clear_to_color(al_map_rgb(0,0,0)); al_flip_display(); // actually start our Timer al_start_timer(Timer); return true; }
static bool init(void) { if(!al_init()) { fprintf(stderr, "failed to initialize allegro.\n"); return false; } if(!al_install_keyboard()) { fprintf(stderr, "failed to initialize keyboard.\n"); return false; } if(!al_init_image_addon()) { fprintf(stderr, "failed to initialize image system.\n"); return false; } al_init_font_addon(); if(!al_init_ttf_addon()) { fprintf(stderr, "failed to initialize ttf system.\n"); return false; } /* sound */ if(!al_install_audio()) { fprintf(stderr, "failed to initialize audio system.\n"); return false; } if(!al_init_acodec_addon()) { fprintf(stderr, "failed to initialize audio codecs.\n"); return false; } if(!al_reserve_samples(10)) { fprintf(stderr, "failed to reserve audio samples.\n"); return false; } /* fonts */ asteroids.small_font = al_load_ttf_font("data/vectorb.ttf", 12, 0); asteroids.large_font = al_load_ttf_font("data/vectorb.ttf", 24, 0); /* lives sprite */ asteroids.lives_sprite = al_load_bitmap("data/sprites/ship/ship.png"); if(!asteroids.lives_sprite) { fprintf(stderr, "failed to load lives sprite.\n"); return false; } /* sprite preloading */ if(!level_init()) return false; if(!ship_init()) return false; if(!missile_init()) return false; if(!saucer_init()) return false; if(!asteroid_init()) return false; if(!explosion_init()) return false; asteroids.timer = al_create_timer(1.0 / FPS); if(!asteroids.timer) { fprintf(stderr, "failed to create timer.\n"); return false; } asteroids.event_queue = al_create_event_queue(); if(!asteroids.event_queue) { fprintf(stderr, "failed to create event queue.\n"); return false; } if(FULLSCREEN) al_set_new_display_flags(ALLEGRO_FULLSCREEN); al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST); al_set_new_display_option(ALLEGRO_SAMPLES, 8, ALLEGRO_SUGGEST); asteroids.display = al_create_display(SCREEN_W, SCREEN_H); if(!asteroids.display) { fprintf(stderr, "failed to create display.\n"); return false; } /* TODO: show on mouse movement */ al_hide_mouse_cursor(asteroids.display); al_register_event_source(asteroids.event_queue, al_get_display_event_source(asteroids.display)); al_register_event_source(asteroids.event_queue, al_get_timer_event_source(asteroids.timer)); al_register_event_source(asteroids.event_queue, al_get_keyboard_event_source()); return true; }
int main(int argc, char const *argv[]) { const int FPS = 60; const int MAX_BULLETS = 10; const int MAX_ASTEROIDS = 10; const int MAX_EXPLOSIONS = 10; srand(time(NULL)); int done = 0; int redraw = 1; if(!al_init()) { al_show_native_message_box(NULL, "Error", "Error", "Could not initialize Allegro 5.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } ALLEGRO_DISPLAY *display = al_create_display(screen_width, screen_height); if(!display) { al_show_native_message_box(NULL, "Error", "Error", "Could not create display.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); if(!event_queue) { al_show_native_message_box(display, "Error", "Error", "Could not create event queue.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS); if(!timer) { al_show_native_message_box(display, "Error", "Error", "Could not create timer.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } if(!al_install_keyboard()) { al_show_native_message_box(display, "Error", "Error", "Could not install keyboard.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } if(!al_install_mouse()) { al_show_native_message_box(display, "Error", "Error", "Could not install mouse.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } if(!al_init_image_addon()) { al_show_native_message_box(display, "Error", "Error", "Could not initialize image addon.", 0, ALLEGRO_MESSAGEBOX_ERROR); return -1; } if(!al_init_primitives_addon()) { al_show_native_message_box(display, "Error", "Error", "Could not initialize primitives addon.", 0, ALLEGRO_MESSAGEBOX_ERROR); } al_init_font_addon(); // for whatever reason this function is void returning if(!al_init_ttf_addon()) { al_show_native_message_box(display, "Error", "Error", "Could not initialize ttf addon.", 0, ALLEGRO_MESSAGEBOX_ERROR); } al_hide_mouse_cursor(display); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); ALLEGRO_FONT *font18 = al_load_font("Arial.ttf", 18, 0); int prev_x = screen_width, prev_y = screen_height; int fps_counter = 0; int fps_counter2 = 0; int i, j, k; struct spaceship ship; init_ship(&ship); struct bullet bullets[MAX_BULLETS]; for(i = 0; i < MAX_BULLETS; i++) { init_bullet(&bullets[i]); } struct asteroid asteroids[MAX_ASTEROIDS]; for(i = 0; i < MAX_ASTEROIDS; i++) { init_asteroid(&asteroids[i]); } struct explosion explosions[MAX_EXPLOSIONS]; for(i = 0; i < MAX_EXPLOSIONS; i++) { init_explosion(&explosions[i]); } al_start_timer(timer); while(!done) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if(event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = 1; } if(event.type == ALLEGRO_EVENT_KEY_DOWN) { switch(event.keyboard.keycode) { case ALLEGRO_KEY_Q: done = 1; break; case ALLEGRO_KEY_ESCAPE: done = 1; break; } } if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if(event.mouse.button & 1) { for(i = 0; i < MAX_BULLETS; i++) { if(!bullets[i].live) { fire_bullet(&bullets[i], ship); break; } } } } if(event.type == ALLEGRO_EVENT_MOUSE_AXES || event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) { set_ship_coordinates(&ship, event.mouse.x, event.mouse.y); } if(event.type == ALLEGRO_EVENT_TIMER) { if(ship.x > prev_x) { ship.sprite.dir_horizontal = RIGHT; } else if(ship.x == prev_x) { ship.sprite.dir_horizontal = CENTER; } else if(ship.x < prev_x) { ship.sprite.dir_horizontal = LEFT; } if(ship.y > prev_y) { ship.sprite.dir_vertical = BACK; } else if(ship.y == prev_y) { ship.sprite.dir_vertical = NEUTRAL; } else if(ship.y < prev_y) { ship.sprite.dir_vertical = FORWARD; } if(++fps_counter >= FPS / 5) { fps_counter = 0; prev_x = ship.x; prev_y = ship.y; } if(++fps_counter2 >= 2 * FPS) { for(i = 0; i < MAX_ASTEROIDS; i++) { if(!asteroids[i].live) { start_asteroid(&asteroids[i]); break; } } fps_counter2 = 0; } for(i = 0; i < MAX_BULLETS; i++) { if(bullets[i].live) { update_bullet(&bullets[i]); } } for(i = 0; i < MAX_ASTEROIDS; i++) { if(asteroids[i].live) { update_asteroid(&asteroids[i], &ship); } } for(i = 0; i < MAX_EXPLOSIONS; i++) { if(explosions[i].live) { update_explosion(&explosions[i]); } } update_ship_boundaries(&ship); for(i = 0; i < MAX_BULLETS; i++) { if(bullets[i].live) { for(j = 0; j < MAX_ASTEROIDS; j++) { if(asteroids[j].live) { if(bullet_and_asteroid_collision(bullets[i], asteroids[j])) { bullets[i].live = 0; asteroids[j].live = 0; ship.score += 20; for(k = 0; k < MAX_EXPLOSIONS; k++) { if(!explosions[k].live) { start_explosion(&explosions[k], bullets[i].x, bullets[i].y); break; } } } } } } } for(i = 0; i < MAX_ASTEROIDS; i++) { if(asteroids[i].live) { if(ship_and_asteroid_collision(ship, asteroids[i])) { asteroids[i].live = 0; for(k = 0; k < MAX_EXPLOSIONS; k++) { if(!explosions[k].live) { start_explosion(&explosions[k], ship.x, ship.y); break; } } ship.lives--; } } } if(!ship.lives) { done = true; } redraw = 1; } if(redraw) { redraw = 0; draw_ship_sprite(ship.sprite, ship.x, ship.y); for(i = 0; i < MAX_BULLETS; i++) { if(bullets[i].live) { draw_bullet(bullets[i]); } } for(i = 0; i < MAX_ASTEROIDS; i++) { if(asteroids[i].live) { draw_asteroid(asteroids[i]); } } for(i = 0; i < MAX_EXPLOSIONS; i++) { if(explosions[i].live) { draw_explosion(explosions[i]); } } al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 5, 0, "Score: %d ", ship.score); // I have no idea why it doesn't print the S... al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 25, 0, "Lives: %d", ship.lives); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } } for(i = 0; i < MAX_ASTEROIDS; i++) { destroy_asteroid(&asteroids[i]); } for(i = 0; i < MAX_EXPLOSIONS; i++) { destroy_explosion(&explosions[i]); } destroy_sprite(&ship.sprite); al_destroy_display(display); al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_font(font18); return 0; }
int main(int argc, char *argv[]) { // -------- VARIÁVEIS DO JOGO -------- ALLEGRO_EVENT_QUEUE *fila_eventos = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font20 = NULL; ALLEGRO_SAMPLE *ataque = NULL; ALLEGRO_SAMPLE *morte_inimigo = NULL; ALLEGRO_SAMPLE *morte_personagem = NULL; ALLEGRO_SAMPLE *hit = NULL; ALLEGRO_SAMPLE *item = NULL; ALLEGRO_AUDIO_STREAM *musica = NULL; ALLEGRO_AUDIO_STREAM *track_menu = NULL; ALLEGRO_BITMAP *start = NULL; bool fim = false; bool menu = true; int flag = 0; bool desenha = true; bool game_over = false; bool teclas[] = {false, false, false, false, false, false, false}; int i; int dificuldade; // ___________________________________ // -------- INICIALIZAÇÃO DE OBJETOS -------- dificuldade = 0; Personagem personagem_principal; Projetil* balas = new Projetil [NUM_BALAS]; Projetil* balas_2 = new Projetil [NUM_BALAS]; Inimigo* inimigos = new Inimigo[NUM_INIMIGOS]; Inimigo* inimigos2 = new Inimigo [NUM_INIMIGOS]; Coracao* coracoes = new Coracao[NUM_ITENS]; Speed* speed = new Speed[NUM_ITENS]; ItemPontos* pontos = new ItemPontos[NUM_ITENS]; Estrelas estrelas_pf[NUM_PLANOS][NUM_ESTRELAS]; Selecionar select; // __________________________________________ // -------- INICIALIZAÇÃO DA ALLEGRO E DO DISPLAY -------- ALLEGRO_DISPLAY *display = NULL; if (!al_init()) { al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO INICIALIZAR A ALLEGRO!", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } display = al_create_display(LARGURA_T, ALTURA_T); if (!display) { al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO CRIAR O DISPLAY!", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } al_set_window_title(display, "Cosmos Guardian"); // ____________________________________________________ // -------- INICIALIZAÇÃO DE ADDONS E INSTALAÇÕES -------- al_init_primitives_addon(); al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_install_audio(); al_init_acodec_addon(); al_reserve_samples(100); // _______________________________________________________ // -------- CRIAÇÃO DE FILAS E DEMAIS DISPOSITIVOS -------- fila_eventos = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); font20 = al_load_font("BADABB__.ttf", 20, 0); // ________________________________________________________ // -------- REGISTRO DE SOURCES -------- al_register_event_source(fila_eventos, al_get_display_event_source(display)); al_register_event_source(fila_eventos, al_get_keyboard_event_source()); al_register_event_source(fila_eventos, al_get_timer_event_source(timer)); // _____________________________________ // -------- FUNÇÕES INICIAIS -------- srand(time(NULL)); personagem_principal.InitPersonagem(); select.InitSelecionar(); //Inicialização de projeteis for (i = 0; i < NUM_BALAS; i++) { balas[i].InitBalas(); balas_2[i].InitBalas(); } //Inicialização de inimigos for (i = 0; i < NUM_INIMIGOS; i++) { inimigos[i].InitInimigo(7, 46, 85, 1 , 0); inimigos2[i].InitInimigo(3, 55, 94, 3, 0); } //Inicialização de itens for (i = 0; i < NUM_ITENS; i++) { coracoes[i].InitItem(); speed[i].InitItem(); pontos[i].InitItem(); } //Inicialização do Plano de Fundo InitPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS); //Setando Sons e Imagens select.bmp = al_load_bitmap("select.png"); ataque = al_load_sample("laser.wav"); morte_inimigo = al_load_sample("dead.wav"); morte_personagem = al_load_sample("death.wav"); hit = al_load_sample("hit.wav"); item = al_load_sample("item.wav"); musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024); track_menu = al_load_audio_stream("menu.ogg", 4, 1024); personagem_principal.bmp = al_load_bitmap("ship.png"); for (i = 0; i < NUM_BALAS; i++) { balas[i].bmp = al_load_bitmap("bala.png"); balas_2[i].bmp = al_load_bitmap("bala.png"); } for (i = 0; i < NUM_INIMIGOS; i++){ inimigos[i].bmp = al_load_bitmap("enemyRed.png"); inimigos2[i].bmp = al_load_bitmap("enemyWhite.png"); } start = al_load_bitmap("start.jpg"); for (i = 0; i < NUM_ITENS; i++){ coracoes[i].imagem = al_load_bitmap("heart.png"); speed[i].imagem = al_load_bitmap("speed.png"); pontos[i].imagem = al_load_bitmap("pontos.png"); } // __________________________________ // ----------------- LOOP PRINCIPAL ----------------- al_start_timer(timer); while(!fim) { ALLEGRO_EVENT ev; al_wait_for_event(fila_eventos, &ev); // -------- EVENTOS E LÓGICA DO JOGO -------- if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { fim = true; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: fim = true; break; case ALLEGRO_KEY_UP: teclas[CIMA] = true; break; case ALLEGRO_KEY_DOWN: teclas[BAIXO] = true; break; case ALLEGRO_KEY_LEFT: teclas[ESQUERDA] = true; break; case ALLEGRO_KEY_RIGHT: teclas[DIREITA] = true; break; case ALLEGRO_KEY_SPACE: teclas[ESPACO] = true; AtiraBalas(balas, NUM_BALAS, personagem_principal, personagem_principal.y + 12); AtiraBalas(balas_2, NUM_BALAS, personagem_principal, personagem_principal.y + 70); al_play_sample(ataque, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL); break; case ALLEGRO_KEY_ENTER: teclas[ENTER] = true; break; case ALLEGRO_KEY_BACKSPACE: teclas[BACKSPACE] = true; break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: teclas[CIMA] = false; break; case ALLEGRO_KEY_DOWN: teclas[BAIXO] = false; break; case ALLEGRO_KEY_LEFT: teclas[ESQUERDA] = false; break; case ALLEGRO_KEY_RIGHT: teclas[DIREITA] = false; break; case ALLEGRO_KEY_ENTER: teclas[ENTER] = false; break; case ALLEGRO_KEY_BACKSPACE: teclas[BACKSPACE] = false; break; } } else if (ev.type == ALLEGRO_EVENT_TIMER) { desenha = true; if (teclas[CIMA]) personagem_principal.MoveCima(); if (teclas[BAIXO]) personagem_principal.MoveBaixo(ALTURA_T); if (teclas[ESQUERDA]) personagem_principal.MoveEsquerda(); if (teclas[DIREITA]) personagem_principal.MoveDireita(LARGURA_T); if (teclas[ESPACO]) { for (i = 0; i < NUM_BALAS; i++) { balas[i].AtualizaBalas(0); balas_2[i].AtualizaBalas(0); } } // Movimentação no menu if(menu) { al_attach_audio_stream_to_mixer(track_menu, al_get_default_mixer()); al_set_audio_stream_playing(track_menu, true); if (teclas[CIMA] && select.y!=235) select.y -= 70; if (teclas[BAIXO] && select.y!=305) select.y += 70; if (teclas[ENTER] && select.y==235) { menu = false; al_set_audio_stream_playing(track_menu, false); } } // Acontecimentos do Jogo if(!game_over && !menu) { al_attach_audio_stream_to_mixer(musica, al_get_default_mixer()); al_set_audio_stream_playing(musica, true); AtualizaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS); { //Gera e atualiza inimigos for (i = 0; i < NUM_INIMIGOS; i++) { inimigos[i].GeraInimigos(); inimigos2[i].GeraInimigos(); inimigos[i].AtualizaInimigos(); inimigos[i].InimigoColidido(personagem_principal, hit); inimigos2[i].AtualizaInimigos(); inimigos2[i].InimigoColidido(personagem_principal, hit); } } //Checa colisões de projeteis BalaColidida(balas, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo); BalaColidida(balas_2, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo); BalaColidida(balas, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo); BalaColidida(balas_2, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo); // Faz os testes relacionado aos itens for (i = 0; i < NUM_ITENS; i++) { coracoes[i].GeraItens(inimigos[i]); coracoes[i].AtualizaItens(); coracoes[i].ItemColidido(personagem_principal, item); speed[i].GeraItens(inimigos[i]); speed[i].AtualizaItens(); speed[i].ItemColidido(personagem_principal, item); pontos[i].GeraItens(inimigos[i]); pontos[i].AtualizaItens(); pontos[i].ItemColidido(personagem_principal, item); } if ((dificuldade+1)%16 == 0) // Dificuldade aumenta a cada 15 pontos. { for (i = 0; i < NUM_INIMIGOS; i++){ inimigos[i].velocidade++; inimigos2[i].velocidade++; } dificuldade = 0; } if (personagem_principal.vidas <= 0) { al_play_sample(morte_personagem, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL); game_over = true; } } // Reinicializa o jogo else if (!menu) { al_set_audio_stream_playing(musica, false); if (teclas[ENTER]) { al_destroy_audio_stream(musica); personagem_principal.InitPersonagem(); for (i = 0; i < NUM_BALAS; i++) { balas[i].InitBalas(); balas_2[i].InitBalas(); } for (i = 0; i < NUM_INIMIGOS; i++) { inimigos[i].InitInimigo(7, 46, 85, 1 , 0); inimigos2[i].InitInimigo(3, 55, 94, 3, 0); } for (i = 0; i < NUM_ITENS; i++) { coracoes[i].InitItem(); speed[i].InitItem(); pontos[i].InitItem(); } personagem_principal.bmp = al_load_bitmap("ship.png"); musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024); for (i = 0; i < NUM_BALAS; i++) { balas[i].bmp = al_load_bitmap("bala.png"); balas_2[i].bmp = al_load_bitmap("bala.png"); } for (i = 0; i < NUM_INIMIGOS; i++) { inimigos[i].bmp = al_load_bitmap("enemyRed.png"); inimigos2[i].bmp = al_load_bitmap("enemyWhite.png"); coracoes[i].imagem = al_load_bitmap("heart.png"); speed[i].imagem = al_load_bitmap("heart.png"); } game_over = false; } } } // _________________________________________ // ---------------- DESENHO ---------------- if(desenha && al_is_event_queue_empty(fila_eventos)) { desenha = false; // Desenhos da Tela do Menu if(menu) { al_draw_bitmap(start, 0, 0, 0); if (select.ativo) al_draw_bitmap(select.bmp, select.x, select.y, 0); if (teclas[ENTER] && flag == 0) { flag = 1; teclas[BACKSPACE] = false; select.ativo = false; start = al_load_bitmap("como_jogar.jpg"); al_draw_bitmap(start, 0, 0, 0); } else if (teclas[BACKSPACE] && flag == 1) { flag = 0; select.ativo = true; start = al_load_bitmap("start.jpg"); al_draw_bitmap(start, 0, 0, 0); } } // Jogo normal, desenho de todos os objetos if(!game_over && !menu) { DesenhaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS); personagem_principal.DesenhaPersonagem(); for (i = 0; i < NUM_BALAS; i++) { balas[i].DesenhaBalas(); balas_2[i].DesenhaBalas(); } for (i = 0; i < NUM_INIMIGOS; i++){ inimigos[i].DesenhaInimigos(); inimigos2[i].DesenhaInimigos(); } for (i = 0; i < NUM_ITENS; i++) { coracoes[i].DesenhaItens(); speed[i].DesenhaItens(); pontos[i].DesenhaItens(); } al_draw_textf(font20, al_map_rgb(255, 255, 255), 0, 0, 0, "VIDAS: %d / PONTOS: %d", personagem_principal.vidas, personagem_principal.pontos); } //Tela de fim de jogo else if (!menu) { al_draw_textf(font20, al_map_rgb(255, 255, 255), LARGURA_T / 2, ALTURA_T / 2, ALLEGRO_ALIGN_CENTRE, "FIM DE JOGO. SEUS PONTOS FORAM: %d. TECLE ENTER PARA JOGAR NOVAMENTE OU ESC PARA SAIR DO JOGO.", personagem_principal.pontos); } al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } // _________________________________________ } // _________________________________________________ // -------- FINALIZAÇÕES DO PROGRAMA -------- delete[] inimigos; delete[] inimigos2; delete[] balas; delete[] balas_2; delete[] coracoes; delete[] speed; delete[] pontos; al_destroy_bitmap(start); al_destroy_sample(ataque); al_destroy_sample(morte_inimigo); al_destroy_sample(morte_personagem); al_destroy_sample(hit); al_destroy_sample(item); al_destroy_audio_stream(musica); al_destroy_audio_stream(track_menu); al_destroy_display(display); al_destroy_timer(timer); al_destroy_font(font20); al_destroy_event_queue(fila_eventos); //___________________________________________ return 0; }
int main( int argc, char* argv[] ) { ALLEGRO_EVENT e; ALLEGRO_TIMER* t; int64_t framesToUpdate = 0; if( !al_init() ) { return -1; } al_init_font_addon(); if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() ) { return -1; } #if NETWORK_SUPPORT != 0 if( !install_network() ) { return -1; } #endif #if HTTP_SUPPORT if( !install_http() ) { return -1; } #ifdef PANDORA Downloads = new HttpManager(2); #else Downloads = new HttpManager(6); #endif #endif #if EXIT_IF_NO_AUDIO != 0 if( !al_install_audio() || !al_init_acodec_addon() ) { return -1; } voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if (!voice) return 1; mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if (!mixer) return 1; if (!al_attach_mixer_to_voice(mixer, voice)) return 1; #else if( al_install_audio() ) { if( al_init_acodec_addon() ) { voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if( voice != 0 ) { mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if( mixer != 0 ) al_attach_mixer_to_voice(mixer, voice); } } } #endif // EXIT_IF_NO_AUDIO // Random number is guarenteed to be random srand( 5 ); GameStack = new StageStack(); CurrentConfiguration = new Configuration(); if( CurrentConfiguration->FullScreen ) al_set_new_display_flags( ALLEGRO_FULLSCREEN_WINDOW ); al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST); bool foundMode = false; int fallbackW = 640; int fallbackH = 480; if( CurrentConfiguration->ForceResolution ) { foundMode = true; } else { for( int modeIdx = 0; modeIdx < al_get_num_display_modes(); modeIdx++ ) { if( al_get_display_mode( modeIdx, &ScreenMode ) != NULL ) { if( ScreenMode.width == CurrentConfiguration->ScreenWidth && ScreenMode.height == CurrentConfiguration->ScreenHeight ) { foundMode = true; } else { fallbackW = ScreenMode.width; fallbackH = ScreenMode.height; } } if( foundMode ) break; } } if( foundMode ) { Screen = al_create_display( CurrentConfiguration->ScreenWidth, CurrentConfiguration->ScreenHeight ); } else { Screen = al_create_display( fallbackW, fallbackH ); CurrentConfiguration->ScreenWidth = fallbackW; CurrentConfiguration->ScreenHeight = fallbackH; } al_hide_mouse_cursor( Screen ); t = al_create_timer( 1.0 / SCREEN_FPS ); if( t == NULL ) Quit = true; al_start_timer( t ); EventQueue = al_create_event_queue(); al_register_event_source( EventQueue, al_get_display_event_source( Screen ) ); al_register_event_source( EventQueue, al_get_keyboard_event_source() ); al_register_event_source( EventQueue, al_get_mouse_event_source() ); al_register_event_source( EventQueue, al_get_timer_event_source( t ) ); #if NETWORK_SUPPORT != 0 al_register_event_source( EventQueue, get_network_event_source() ); #endif #if HTTP_SUPPORT Downloads->urlDownloads = CurrentConfiguration->MaxConcurrentDownloads; al_register_event_source( EventQueue, get_http_event_source() ); #endif Fonts = new FontManager(); Images = new ImageManager(); Audio = new SoundManager(); al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA ); GameStack->Push( (Stage*)new BootUp() ); while( !Quit ) { if( GameStack->IsEmpty() ) { Quit = true; } else { while( al_get_next_event( EventQueue, &e ) ) { #if HTTP_SUPPORT Downloads->Event( &e ); #endif switch( e.type ) { case ALLEGRO_EVENT_DISPLAY_CLOSE: Quit = true; break; case ALLEGRO_EVENT_JOYSTICK_CONFIGURATION: al_reconfigure_joysticks(); break; case ALLEGRO_EVENT_TIMER: if( e.timer.source == t ) framesToUpdate++; else if( !GameStack->IsEmpty() ) GameStack->Current()->Event( &e ); break; default: if( !GameStack->IsEmpty() ) GameStack->Current()->Event( &e ); switch( e.type ) { #if HTTP_SUPPORT case ALLEGRO_EVENT_HTTP: #endif #if NETWORK_SUPPORT case ALLEGRO_EVENT_NETWORK_CONNECTION: case ALLEGRO_EVENT_NETWORK_RECEIVEPACKET: case ALLEGRO_EVENT_NETWORK_DISCONNECTION: #endif case ALLEGRO_EVENT_BUTTON_CLICK: case ALLEGRO_EVENT_MOUSEEX_MOVE: case ALLEGRO_EVENT_MOUSEEX_DOWN: case ALLEGRO_EVENT_MOUSEEX_UP: case ALLEGRO_EVENT_MOUSEEX_CLICK: case ALLEGRO_EVENT_MOUSEEX_DOUBLECLICK: case ALLEGRO_EVENT_MOUSEEX_BOXED: case ALLEGRO_EVENT_MOUSEEX_WHEEL: al_unref_user_event( &e.user ); break; } break; } } if( framesToUpdate > 0 ) { for( int frmUp = 0; frmUp < framesToUpdate; frmUp++ ) { if( !GameStack->IsEmpty() ) GameStack->Current()->Update(); } framesToUpdate = 0; } al_clear_to_color( al_map_rgb( 128, 128, 128 ) ); if( !GameStack->IsEmpty() ) GameStack->Current()->Render(); al_flip_display(); Images->Tidy(); Fonts->Tidy(); Audio->Tidy(); } } while( !GameStack->IsEmpty() ) { GameStack->Pop(); } delete Downloads; delete Fonts; delete Images; delete Audio; al_destroy_event_queue( EventQueue ); al_destroy_display( Screen ); #if HTTP_SUPPORT uninstall_http(); #endif #if NETWORK_SUPPORT != 0 uninstall_network(); #endif al_uninstall_keyboard(); al_uninstall_mouse(); al_shutdown_primitives_addon(); al_shutdown_ttf_addon(); al_shutdown_image_addon(); al_uninstall_audio(); al_shutdown_font_addon(); return 0; }
int main(void) { int vMapa = 0; int vMatriz_Mapa[21][27],i=0,j=0; FILE *fMapa = fopen("dormitorio_masculino.txt", "r"); // Carrega o arquivo de texto da fase em questão; char vLe_Char; while((vLe_Char = getc(fMapa) ) != EOF ) // Grava Caracter enquanto não chegar ao final do arquivo; { if ( i < 27 ) // Enquanto estivar na linha; { vMatriz_Mapa[j][i] = atoi(&vLe_Char); // Carrega a matriz com os caracteres que representam as imagens; i++; } else // senao passa para a proxima linha; { j++; i=0; } } fclose(fMapa); for (j=0;j<19;j++){ for (i=0;i<27;i++){ // if(vMatriz_Mapa[j/32][i/32]==2){ printf("%d",vMatriz_Mapa[j][i]); } printf("\n"); } bool sair = false; int tecla = 0,top = 0, left = 0, right = 0, down=0; int x=192,y=64; if (!al_init()) { fprintf(stderr, "Falha ao inicializar a Allegro.\n"); return false; } al_init_font_addon(); if (!al_init_ttf_addon()) { fprintf(stderr, "Falha ao inicializar add-on allegro_ttf.\n"); return false; } if (!al_init_image_addon()) { fprintf(stderr, "Falha ao inicializar add-on allegro_image.\n"); return false; } if (!al_install_keyboard()) { fprintf(stderr, "Falha ao inicializar o teclado.\n"); return false; } janela = al_create_display(LARGURA_TELA, ALTURA_TELA); if (!janela) { fprintf(stderr, "Falha ao criar janela.\n"); return false; } al_set_window_title(janela, "Utilizando o Teclado"); fila_eventos = al_create_event_queue(); if (!fila_eventos) { fprintf(stderr, "Falha ao criar fila de eventos.\n"); al_destroy_display(janela); return false; } fundo = al_load_bitmap("dormitorio_masculino.bmp"); if (!fundo) { fprintf(stderr, "Falha ao carregar imagem de fundo.\n"); al_destroy_display(janela); al_destroy_event_queue(fila_eventos); return false; } timer = al_create_timer(6/60.0); al_register_event_source(fila_eventos, al_get_timer_event_source(timer)); al_register_event_source(fila_eventos, al_get_keyboard_event_source()); al_register_event_source(fila_eventos, al_get_display_event_source(janela)); al_draw_bitmap(fundo, 0, 0, 0); ALLEGRO_BITMAP *peterSET = al_load_bitmap("sabrina3.bmp"); al_convert_mask_to_alpha(peterSET,al_map_rgb(255,0,255)); ALLEGRO_BITMAP *peterCHAR[12]; peterCHAR[0] = al_create_bitmap(32,32); peterCHAR[0] = al_create_sub_bitmap(peterSET, 0, 0, 32, 32); peterCHAR[1] = al_create_bitmap(32,32); peterCHAR[1] = al_create_sub_bitmap(peterSET, 32, 0, 32, 32); peterCHAR[2] = al_create_bitmap(32,32); peterCHAR[2] = al_create_sub_bitmap(peterSET, 64, 0, 32, 32); peterCHAR[3] = al_create_bitmap(32,32); peterCHAR[3] = al_create_sub_bitmap(peterSET, 0, 32, 32, 32); peterCHAR[4] = al_create_bitmap(32,32); peterCHAR[4] = al_create_sub_bitmap(peterSET, 32, 32, 32, 32); peterCHAR[5] = al_create_bitmap(32,32); peterCHAR[5] = al_create_sub_bitmap(peterSET, 64, 32, 32, 32); peterCHAR[6] = al_create_bitmap(32,32); peterCHAR[6] = al_create_sub_bitmap(peterSET, 0, 64, 32, 32); peterCHAR[7] = al_create_bitmap(32,32); peterCHAR[7] = al_create_sub_bitmap(peterSET, 32, 64, 32, 32); peterCHAR[8] = al_create_bitmap(32,32); peterCHAR[8] = al_create_sub_bitmap(peterSET, 64, 64, 32, 32); peterCHAR[9] = al_create_bitmap(32,32); peterCHAR[9] = al_create_sub_bitmap(peterSET, 0, 96, 32, 32); peterCHAR[10] = al_create_bitmap(32,32); peterCHAR[10] = al_create_sub_bitmap(peterSET, 32, 96, 32, 32); peterCHAR[11] = al_create_bitmap(32,32); peterCHAR[11] = al_create_sub_bitmap(peterSET, 64, 96, 32, 32); al_draw_bitmap(fundo, 0, 0, 0); al_draw_bitmap(peterCHAR[10],x,y,0); al_flip_display(); al_start_timer(timer); while (!sair) { while(!al_is_event_queue_empty(fila_eventos)) { ALLEGRO_EVENT evento; al_wait_for_event(fila_eventos, &evento); if (evento.type == ALLEGRO_EVENT_KEY_DOWN) { switch(evento.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: sair = 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[SELECT]=true; break; } }else if (evento.type == ALLEGRO_EVENT_KEY_UP) { switch(evento.keyboard.keycode) { 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[SELECT]=false; break; } } else if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { sair = true; } else if (evento.type == ALLEGRO_EVENT_TIMER){ if(keys[SELECT]){ if(vMatriz_Mapa[y/32][(x+32)/32]==4){ return 0; } } if (keys[UP]){ if(vMatriz_Mapa[(y-32)/32][x/32]==0){ al_draw_bitmap(fundo, 0, 0, 0); if(top == 0) { y=y-32; al_draw_bitmap(peterCHAR[10],x,y,0); top = 1; } else if(top == 1) { y=y-32; al_draw_bitmap(peterCHAR[9],x,y,0); top=2; } else if (top == 2) { y=y-32; al_draw_bitmap(peterCHAR[11],x,y,0); top =0; } printf("x = %d e y = %d\n",x,y); al_flip_display(); } } if (keys[DOWN]){ if(vMatriz_Mapa[(y+32)/32][x/32]==0){ al_draw_bitmap(fundo, 0, 0, 0); if(down == 0) { y=y+32; al_draw_bitmap(peterCHAR[1],x,y,0); down = 1; } else if(down == 1) { y=y+32; al_draw_bitmap(peterCHAR[0],x,y,0); down = 2; } else if (down == 2) { y=y+32; al_draw_bitmap(peterCHAR[2],x,y,0); down = 0; } } } printf("x = %d e y = %d\n",x,y); al_flip_display(); } if (keys[LEFT]){ if(vMatriz_Mapa[y/32][(x-32)/32]==0){ al_draw_bitmap(fundo, 0, 0, 0); if(left == 0) { x=x-32; al_draw_bitmap(peterCHAR[4],x,y,0); left = 1; } else if(left == 1) { x=x-32; al_draw_bitmap(peterCHAR[3],x,y,0); left=2; } else if (left == 2) { x=x-32; al_draw_bitmap(peterCHAR[5],x,y,0); left =0; } al_flip_display(); printf("x = %d e y = %d\n",x,y); } } if (keys[RIGHT]){ if(vMatriz_Mapa[y/32][(x+32)/32]==0){ al_draw_bitmap(fundo, 0, 0, 0); if(right == 0) { x=x+32; al_draw_bitmap(peterCHAR[7],x,y,0); right = 1; } else if(right == 1) { x=x+32; al_draw_bitmap(peterCHAR[6],x,y,0); right=2; } else if (right == 2) { x=x+32; al_draw_bitmap(peterCHAR[8],x,y,0); right =0; } printf("x = %d e y = %d\n",x,y); al_flip_display(); } } } } al_destroy_display(janela); al_destroy_event_queue(fila_eventos); return 0; }
int main(int argc, char const *argv[]) { int i = 0; int t = 1; int n_mostros = 5; bool click = false; bool nova_horda = true; bool render = false; bool torre_mouse = false; char a; char b; int r; int l; Sistema sistema; Torre torre[10]; Tiro tiro[10]; Monstro monstro[n_mostros]; Coord coordenada[A*B]; //Declara�ao vair�veis allegro ALLEGRO_DISPLAY *janela = NULL; //Vari�vel para a janela ALLEGRO_EVENT_QUEUE *fila_eventos = NULL; // '' para eventos ALLEGRO_BITMAP *imagem = NULL; // '' para imagem ALLEGRO_TIMER *timer = NULL; // '' para o tempo (fps) ALLEGRO_FONT *fonte = NULL; // '' para fonte //Inicializa o allegro, mouse e add-ons al_init(); al_install_mouse(); al_init_primitives_addon(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); a_coord(coordenada, fonte); init_horda(monstro, n_mostros); init_system(sistema); initTorre(torre, tiro, t-1); //Atribui atributos às variáveis allegro janela = al_create_display(LARGURA_TELA, ALTURA_TELA); fila_eventos = al_create_event_queue(); imagem = al_load_bitmap("virus.png"); timer = al_create_timer(1.0 / fps); fonte = al_load_font("arial.ttf", 12, 0); //Fonte DejaVu //Inicializa o mouse e tempo al_set_system_mouse_cursor(janela, ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT); al_start_timer(timer); al_install_keyboard(); init_fail(janela, fonte, fila_eventos, imagem, timer); //Fun�ao de teste //Regista os eventos da janela, mouse e timer na vari�vel de eventos (fila_eventos) al_register_event_source(fila_eventos, al_get_display_event_source(janela)); al_register_event_source(fila_eventos, al_get_mouse_event_source()); al_register_event_source(fila_eventos, al_get_keyboard_event_source()); al_register_event_source(fila_eventos, al_get_timer_event_source(timer)); al_clear_to_color(al_map_rgb(235, 235, 235)); //Limpa a tela al_flip_display(); //Atualiza a tela //Loop principal while (!GameOver) { ALLEGRO_EVENT evento; //Variavel para eventos al_wait_for_event(fila_eventos, &evento); if(evento.type == ALLEGRO_EVENT_TIMER) //Evento de renderiza�ao { i++; render = true; FireTiro(tiro, torre, monstro, t-1); UpdateTiro(tiro, monstro, t-1); update_horda(monstro, mapa, n_mostros); colisao_horda(tiro, monstro, n_mostros); } if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { GameOver = true; } else if(evento.type == ALLEGRO_EVENT_MOUSE_AXES) { pos_x = evento.mouse.x; pos_y = evento.mouse.y; a = coordenada[(pos_x/l_celula)].letra[0]; b = coordenada[(pos_x/l_celula)].letra[1]; l = coordenada[(pos_y/a_celula)].numero; r = conversao_coordenadas(coordenada, a, b); } else if(evento.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (mapa[pos_y/a_celula][pos_x/l_celula] == 9) { torre_mouse = true; torre[t].in_mouse = true; } if(torre_mouse && !click) { if (mapa[pos_y/a_celula][pos_x/l_celula] != 9) { mapa[pos_y/a_celula][pos_x/l_celula] = 10; torre_mouse = false; torre[t].in_mouse = false; t++; } } click = !click; } else if(evento.type == ALLEGRO_EVENT_KEY_DOWN) { switch(evento.keyboard.keycode) { case ALLEGRO_KEY_SPACE: start_horda(monstro, n_mostros); break; } } else if(render && al_is_event_queue_empty(fila_eventos)) { render = false; coor_matrix(mapa, coordenada, fonte); al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/4, 50, ALLEGRO_ALIGN_CENTRE, "Taxa de Frames: %i", i); al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y, ALLEGRO_ALIGN_LEFT, " x:%i y:%i", pos_x, pos_y); draw_horda(monstro, n_mostros, imagem); if(torre_mouse) { draw_tower(r, l, torre, t); } drawTiro(tiro, t-1); al_flip_display(); al_clear_to_color(al_map_rgb(255,255,255)); } } destroy_al(janela, fonte, fila_eventos, imagem, timer); //Destroi as vari�veis allegro return 0; }
int main(short int argc, char** argv) { al_init(); al_install_keyboard(); al_install_mouse(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_MONITOR_INFO oMonitorInfo; al_get_monitor_info(0, &oMonitorInfo); short int iDisplayWidth = oMonitorInfo.x2 * 0.70f; short int iDisplayHeight = oMonitorInfo.y2 * 0.70f; short int iAppWidth = iDisplayWidth * 0.95f; short int iAppHeight = iDisplayHeight * 0.95f; short int iMarginHorizontal = (iDisplayWidth - iAppWidth) / 2; short int iMarginVertical = ((iDisplayHeight - iAppHeight) / 2); int iGenerations = 0; short int iFPS = 30; float iLifeMin = 3.0f; float iLifeMax = 37.0f; short int iFontSize = (iDisplayWidth > 1024) ? 12 : 10; if (iDisplayWidth < 800) { iFontSize = 8; } long int iSimulations = 1; std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<double> dist(iLifeMin, iLifeMax); int iLifeScarcity = std::round(dist(mt)); bool** pCells = new bool*[iAppWidth]; bool** pNextGenCells = new bool*[iAppWidth]; initCells(pCells, pNextGenCells, iAppWidth, iAppHeight, iLifeScarcity); ALLEGRO_DISPLAY* pDisplay = al_create_display(iDisplayWidth, iDisplayHeight); ALLEGRO_EVENT_QUEUE* pQueue = al_create_event_queue(); ALLEGRO_TIMER* pTimer = al_create_timer(1.0f / iFPS); ALLEGRO_TIMER* pSecondBySecondTimer = al_create_timer(1.0f); ALLEGRO_BITMAP* pBuffer = al_create_bitmap(iAppWidth, iAppHeight); ALLEGRO_COLOR oBackgroundColor = al_map_rgb(0, 0, 0); ALLEGRO_COLOR oCellColor = al_map_rgb(randr(150, 255), randr(150, 255), randr(150, 255)); ALLEGRO_FONT* oFont = al_load_ttf_font("VeraMono.ttf", iFontSize, 0); ALLEGRO_FONT* oFontLarge = al_load_ttf_font("VeraMono.ttf", (iFontSize * 3), 0); al_inhibit_screensaver(true); al_register_event_source(pQueue, al_get_keyboard_event_source()); al_register_event_source(pQueue, al_get_mouse_event_source()); al_register_event_source(pQueue, al_get_timer_event_source(pTimer)); al_register_event_source(pQueue, al_get_timer_event_source(pSecondBySecondTimer)); al_set_target_backbuffer(pDisplay); al_clear_to_color(oBackgroundColor); al_flip_display(); al_start_timer(pTimer); al_start_timer(pSecondBySecondTimer); ALLEGRO_EVENT oEvent; short int iBufferUsed = 0; short int iBufferDrawn = 0; bool bRedraw = false; std::string sHeaderStatistics = "GEN [GENXXXXX] FPS [FPSXXXXX] CELLS [CELLSXXXXX] GENS/S [GENSSXXXXX] SCARCTY [SCARXXXXX] TIME [TIMEXXXXX]"; std::string sHeaderStats = ""; /* std::string sHeaderText_2 = ""; std::string sHeaderText_3 = ""; std::string sHeaderText_4 = ""; std::string sHeaderText_5 = ""; std::string sHeaderText_6 = ""; */ std::string sCountdownText = ""; std::string sSimulations = ""; std::string sStats = "CELLS: "; sStats.append(std::to_string((iAppWidth * iAppHeight))); sStats.append(", MAP SIZE (KB): "); sStats.append(std::to_string((iAppWidth * iAppHeight * sizeof(bool)) / 1024)); sStats.append(" (SPACE) Pause (C)olor, (R)eload, (S)carcity, (F) +1 FPS, (G) -1 FPS, (ESC) Exit"); long int iTotalAlive = 0; int iPatternStableBuffer = (iFPS * 4); long int* iTotalPatternStable = new long int[iPatternStableBuffer]; short int iTotalPatternCounter = 0; long int iSecondsRunning = 0; float fPosText2 = (iAppWidth * 0.15); float fPosText3 = (iAppWidth * 0.30); float fPosText4 = (iAppWidth * 0.50); float fPosText5 = (iAppWidth * 0.70); float fPosText6 = (iAppWidth * 0.85); float fPosTextSim = (iAppWidth * 0.75); bool bPatternIsStable = false; int iCountdownSeconds = 10; bool bDrawingOn = false; bool bTimerStopped = false; ALLEGRO_COLOR oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255)); while (true) { al_wait_for_event(pQueue, &oEvent); if (oEvent.type == ALLEGRO_EVENT_TIMER) { if (!bTimerStopped) { if (oEvent.timer.source == pTimer) { iTotalAlive = 0; redrawCells(pBuffer, pCells, pNextGenCells, iAppWidth, iAppHeight, oCellColor, oBackgroundColor); nextGeneration(pCells, pNextGenCells, iAppWidth, iAppHeight, iTotalAlive); al_set_target_backbuffer(pDisplay); al_clear_to_color(oBackgroundColor); al_draw_bitmap(pBuffer, iMarginHorizontal, iMarginVertical, 0); sHeaderStats = ReplaceString(sHeaderStatistics, "[GENXXXXX]", std::to_string(iGenerations)); sHeaderStats = ReplaceString(sHeaderStats, "[FPSXXXXX]", std::to_string(iFPS)); sHeaderStats = ReplaceString(sHeaderStats, "[CELLSXXXXX]", std::to_string(iTotalAlive)); sHeaderStats = ReplaceString(sHeaderStats, "[SCARXXXXX]", std::to_string(iLifeScarcity)); sHeaderStats = ReplaceString(sHeaderStats, "[TIMEXXXXX]", std::to_string(iSecondsRunning)); if (iGenerations > 0 && iSecondsRunning > 0) { sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", std::to_string(iGenerations / iSecondsRunning)); } else { sHeaderStats = ReplaceString(sHeaderStats, "[GENSSXXXXX]", "0"); } sSimulations = "SIMS "; sSimulations.append(std::to_string(iSimulations)); int iLengthSims = al_get_text_width(oFont, sSimulations.c_str()); int iLengthStats = al_get_text_width(oFont, sHeaderStats.c_str()); al_draw_text(oFont, oCellColor, ((iAppWidth - iLengthStats) / 2), 1.0f, 0, sHeaderStats.c_str()); al_draw_text(oFont, oCellColor, (iDisplayWidth - (iLengthSims + 25.0f)), (iAppHeight + iMarginVertical + 5.0f), 0, sSimulations.c_str()); al_draw_text(oFont, oCellColor, 25.0f, (iAppHeight + iMarginVertical + 5.0f), 0, sStats.c_str()); if (bPatternIsStable == true) { sCountdownText.clear(); sCountdownText.append("PATTERN STABILIZED, RESTARTING IN... "); int iLengthStr = al_get_text_width(oFontLarge, sCountdownText.c_str()); sCountdownText.append(std::to_string(iCountdownSeconds)); al_draw_text(oFontLarge, oRandColor, ((iAppWidth - iLengthStr) / 2), (iAppHeight * 0.45f), 0, sCountdownText.c_str()); } al_flip_display(); ++iGenerations; copyCells(pCells, pNextGenCells, iAppWidth, iAppHeight); if (iTotalPatternCounter == iPatternStableBuffer) { bPatternIsStable = isPatternStable(iTotalPatternStable, iPatternStableBuffer); delete iTotalPatternStable; iTotalPatternStable = new long int[iPatternStableBuffer]; iTotalPatternCounter = 0; } iTotalPatternStable[iTotalPatternCounter] = iTotalAlive; ++iTotalPatternCounter; } if (oEvent.timer.source == pSecondBySecondTimer) { if (bPatternIsStable == true) { if (iCountdownSeconds > 1) { --iCountdownSeconds; } else { bPatternIsStable = false; iTotalPatternCounter = 0; iGenerations = 0; iSecondsRunning = 0; iCountdownSeconds = 10; ++iSimulations; clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight); randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity); } } else { iCountdownSeconds = 10; } ++iSecondsRunning; oRandColor = al_map_rgb(randr(0, 255), randr(0, 255), randr(0, 255)); } } } if (oEvent.type == ALLEGRO_EVENT_KEY_DOWN) { if (oEvent.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } if (oEvent.keyboard.keycode == ALLEGRO_KEY_SPACE) { if (!bTimerStopped) { bTimerStopped = true; al_stop_timer(pTimer); } else { bTimerStopped = false; al_start_timer(pTimer); } } if (oEvent.keyboard.keycode == ALLEGRO_KEY_R) { bPatternIsStable = false; iTotalPatternCounter = 0; iGenerations = 0; iSecondsRunning = 0; iCountdownSeconds = 10; ++iSimulations; clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight); randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_S) { bPatternIsStable = false; iTotalPatternCounter = 0; iGenerations = 0; iSecondsRunning = 0; iCountdownSeconds = 10; iLifeScarcity = randr(iLifeMin, iLifeMax); ++iSimulations; clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight); randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_M) { bPatternIsStable = false; iTotalPatternCounter = 0; iGenerations = 0; iSecondsRunning = 0; iCountdownSeconds = 10; iLifeScarcity = iLifeMin; ++iSimulations; clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight); randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_N) { bPatternIsStable = false; iTotalPatternCounter = 0; iGenerations = 0; iSecondsRunning = 0; iCountdownSeconds = 10; iLifeScarcity = iLifeMax; ++iSimulations; clearCells(pCells, pNextGenCells, iAppWidth, iAppHeight); randomCells(pCells, iAppWidth, iAppHeight, iLifeScarcity); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_F) { ++iFPS; al_set_timer_speed(pTimer, (1.0f / iFPS)); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_G) { if(iFPS > 3) { --iFPS; } al_set_timer_speed(pTimer, (1.0f / iFPS)); } if (oEvent.keyboard.keycode == ALLEGRO_KEY_C) { int iRCell = randr(0, 255); int iGCell = randr(0, 255); int iBCell = randr(0, 255); oCellColor = al_map_rgb(iRCell, iGCell, iBCell); } } } // End main loop al_destroy_event_queue(pQueue); al_destroy_display(pDisplay); delete iTotalPatternStable; for (short int i = 0; i < iAppWidth; i++) { delete pCells[i]; delete pNextGenCells[i]; } delete[] pCells; delete[] pNextGenCells; return 0; }
int main(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; 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(); if (!al_init_ttf_addon()) { abort_example("Failed to init TTF addon.\n"); return 1; } 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); al_set_new_display_option(ALLEGRO_DEPTH_SIZE, 8, ALLEGRO_SUGGEST); al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); example.display = al_create_display(w, h); if (!example.display) { abort_example("Error creating display.\n"); return 1; } if (!al_install_keyboard()) { abort_example("Error installing keyboard.\n"); return 1; } example.font = al_load_font("data/DejaVuSans.ttf", 40, 0); if (!example.font) { abort_example("Error loading data/DejaVuSans.ttf\n"); return 1; } example.font2 = al_load_font("data/DejaVuSans.ttf", 12, 0); if (!example.font2) { abort_example("Error loading data/DejaVuSans.ttf\n"); return 1; } example.mysha = al_load_bitmap("data/mysha.pcx"); if (!example.mysha) { abort_example("Error loading data/mysha.pcx\n"); return 1; } example.obp = al_load_bitmap("data/obp.jpg"); if (!example.obp) { abort_example("Error loading data/obp.jpg\n"); return 1; } init(); 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_timer_event_source(timer)); al_register_event_source(queue, al_get_display_event_source(example.display)); al_start_timer(timer); while (!done) { 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(); 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: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) done = true; 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; } } return 0; }
//MAIN// int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_BITMAP *image = NULL, *image1 = NULL, *image2 = NULL, *image3 = NULL; ALLEGRO_FONT *font1 = NULL, *font2 = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; if(!al_init()) { return -1; } if(!al_install_keyboard()) { return -1; } if(!al_install_mouse()) { return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { return -1; } event_queue = al_create_event_queue(); if(!event_queue) { return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_mouse_event_source()); al_init_primitives_addon(); al_init_font_addon(); al_init_ttf_addon(); if(!al_init_image_addon()) { printf("Problema com inicialização image_addon"); return -1; } font1 = al_load_ttf_font("pirulen.ttf",12,0 ); if (!font1) { printf("Problema ao carregar pirulen.ttf"); return -1; } image = al_load_bitmap("iceblue2.png"); if(!image) { printf("Problema ao carregar iceblue2.png"); return -1; } image1 = al_load_bitmap("IceBlue1.png"); if(!image1) { printf("Problema ao carregar IceBlue1.png"); return -1; } image2 = al_load_bitmap("NG.png"); if(!image2) { printf("Problema ao carregar NG.png"); return -1; } image3 = al_load_bitmap("retanrosa.png"); if(!image3) { printf("Problema ao carregar retanrosa.png"); return -1; } al_draw_bitmap(image,0,0,0); al_draw_bitmap(image1,10,10,10); al_draw_bitmap(image2,180,45,15); al_draw_bitmap(image3,310,45,15); //FUNÇÃO GERA RETANGULO// x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240; x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193)); y1=y1+80; y2=y2+80; } y1=y1_ini; y2=y2_ini; x1=x1+80; x2=x2+80; } font2 = al_load_ttf_font("pirulen.ttf",23,0 ); if (!font2) { return -1; } al_flip_display(); //LOGICA// while(!doexit) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: for (coluna=0; coluna<5; coluna++) { for (i=3; i>=0; i--) { for (linha=4; linha>=1; linha--) { if ((matriz[linha][coluna]!=0) && (matriz[linha-1][coluna]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha-1][coluna]; matriz[linha-1][coluna]=nt; } } } } for (coluna=0; coluna<5; coluna++) { for (linha=0; linha<4; linha++) { if ((matriz[linha][coluna]==matriz[linha+1][coluna])&&(matriz[linha][coluna]!=0)) { matriz[linha+1][coluna]+=matriz[linha][coluna]; matriz[linha][coluna]=0; linha++; } } } for (coluna=0; coluna<5; coluna++) { for (i=3; i>=0; i--) { for (linha=4; linha>=1; linha--) { if ((matriz[linha][coluna]!=0) && (matriz[linha-1][coluna]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha-1][coluna]; matriz[linha-1][coluna]=nt; } } } } break; case ALLEGRO_KEY_DOWN: for (coluna=0; coluna<5; coluna++) { for (i=3; i>=0; i--) { for (linha=0; linha<4; linha++) { if ((matriz[linha][coluna]!=0) && (matriz[linha+1][coluna]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha+1][coluna]; matriz[linha+1][coluna]=nt; } } } } for (coluna=0; coluna<5; coluna++) { for (linha=4; linha>=1; linha--) { if ((matriz[linha][coluna]==matriz[linha-1][coluna])&&(matriz[linha][coluna]!=0)) { matriz[linha][coluna]+=matriz[linha-1][coluna]; matriz[linha-1][coluna]=0; linha--; } } } for (coluna=0; coluna<5; coluna++) { for (i=3; i>=0; i--) { for (linha=0; linha<4; linha++) { if ((matriz[linha][coluna]!=0) && (matriz[linha+1][coluna]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha+1][coluna]; matriz[linha+1][coluna]=nt; } } } } break; case ALLEGRO_KEY_LEFT: for (linha=0; linha<5; linha++) { for (i=3; i>=0; i--) { for (coluna=4; coluna>=1; coluna--) { if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna-1]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha][coluna-1]; matriz[linha][coluna-1]=nt; } } } } for (linha=0; linha<5; linha++) { for (coluna=0; coluna<4; coluna++) { if ((matriz[linha][coluna]==matriz[linha][coluna+1])&&(matriz[linha][coluna]!=0)) { matriz[linha][coluna+1]+=matriz[linha][coluna]; matriz[linha][coluna]=0; coluna++; } } } for (linha=0; linha<5; linha++) { for (i=3; i>=0; i--) { for (coluna=4; coluna>=1; coluna--) { if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna-1]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha][coluna-1]; matriz[linha][coluna-1]=nt; } } } } break; case ALLEGRO_KEY_RIGHT: for (linha=0; linha<5; linha++) { for (i=3; i>=0; i--) { for (coluna=0; coluna<4; coluna++) { if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna+1]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha][coluna+1]; matriz[linha][coluna+1]=nt; } } } } for (linha=0; linha<5; linha++) { for (coluna=4; coluna>=1; coluna--) { if ((matriz[linha][coluna]==matriz[linha][coluna-1])&&(matriz[linha][coluna]!=0)) { matriz[linha][coluna-1]+=matriz[linha][coluna]; matriz[linha][coluna]=0; coluna--; } } } for (linha=0; linha<5; linha++) { for (i=3; i>=0; i--) { for (coluna=0; coluna<4; coluna++) { if ((matriz[linha][coluna]!=0) && (matriz[linha][coluna+1]==0)) { nt=matriz[linha][coluna]; matriz[linha][coluna]=matriz[linha][coluna+1]; matriz[linha][coluna+1]=nt; } } } } break; case ALLEGRO_KEY_ESCAPE: doexit = true; break; } //GERADOR RANDOM// random(&rcoluna,&rlinha); while (matriz[rlinha][rcoluna]!=0) { random(&rcoluna,&rlinha); } matriz[rlinha][rcoluna]= (rand()%4 == 3)? 4 : 2; for (linha=0; linha<=4; linha++) { for (coluna=0; coluna<=4; coluna++) { if (matriz[linha][coluna]!=0) i++; } } if (i==25) break; //SCORE// al_draw_bitmap(image3,310,45,15); score=0; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { score+=matriz[ql][qc]; } } al_draw_textf(font1, al_map_rgb(255,255,255),365,68,ALLEGRO_ALIGN_CENTRE,"%i",score); } //FUNÇÃO GERA RETANGULO// x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240; x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { if(matriz[ql][qc]==0) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193)); } else if(matriz[ql][qc]==2) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 182, 151)); } else if(matriz[ql][qc]==4) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 141, 132)); } else if(matriz[ql][qc]==8) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 100)); } else if(matriz[ql][qc]==16) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 128, 1)); } else if(matriz[ql][qc]==32) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 128)); } else if(matriz[ql][qc]==64) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 30)); } else if(matriz[ql][qc]==128) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(108, 128, 255)); } else if(matriz[ql][qc]==256) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(108, 188, 255)); } else if(matriz[ql][qc]==512) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(15, 203, 80)); } else if(matriz[ql][qc]==1024) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(140, 255, 198)); } else if(matriz[ql][qc]==2048) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 255, 26)); } else if(matriz[ql][qc]==4069) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 0, 0)); } else { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 225, 255)); } y1=y1+80; y2=y2+80; } y1=y1_ini; y2=y2_ini; x1=x1+80; x2=x2+80; } //FUNÇÃO GERA MATRIZ// text2x_ini=64, text2y_ini=192; text2x=text2x_ini, text2y=text2y_ini; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { if (matriz[ql][qc]==0) { c1=255, c2=211, c3=193; } else { c1=255, c2=255, c3=255; } al_draw_textf(font2, al_map_rgb(c1,c2,c3),text2x,text2y,ALLEGRO_ALIGN_CENTRE, "%i",matriz[ql][qc]); text2y=text2y+80; } text2y=text2y_ini; text2x=text2x+80; al_flip_display(); } //MOUSE EVENT// if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { if(ev.mouse.x >= al_get_bitmap_width(image2) && ev.mouse.x <= SCREEN_W -10 && ev.mouse.y <= SCREEN_H - 10 && ev.mouse.y >= al_get_bitmap_height(image2) - 10) { al_draw_bitmap(image3,310,45,15); score=0; text2x_ini=64, text2y_ini=192; text2x=text2x_ini, text2y=text2y_ini; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { c1=255, c2=211, c3=193; matriz[ql][qc]=0; al_draw_textf(font2, al_map_rgb(c1,c2,c3),text2x,text2y,ALLEGRO_ALIGN_CENTRE, "%i",matriz[ql][qc]); text2y=text2y+80; } text2y=text2y_ini; text2x=text2x+80; } x1_ini=30.0, y1_ini=170.0, x2_ini=100.0, y2_ini=240; x1 = x1_ini,y1= y1_ini,x2 = x2_ini,y2 = y2_ini; for(qc=0; qc<5; qc++) { for (ql=0; ql<5; ql++) { al_draw_filled_rectangle(x1, y1, x2, y2, al_map_rgb(255, 211, 193)); y1=y1+80; y2=y2+80; } y1=y1_ini; y2=y2_ini; x1=x1+80; x2=x2+80; } al_flip_display(); } } } system("cls"); printf("GAME OVER!"); al_destroy_event_queue(event_queue); al_destroy_display(display); return 0; }
static SCM game_init (SCM game_smob, SCM s_width, SCM s_height, SCM s_fullscreen) { Game *game = check_game(game_smob); int width = scm_to_int (s_width); int height = scm_to_int (s_height); bool fullscreen = scm_to_bool (s_fullscreen); /* Initialize Allegro things */ /* TODO: Handle these errors in a proper way */ if(!al_init ()) { fprintf (stderr, "failed to initialize allegro!\n"); exit (-1); } if (!al_init_image_addon ()) { fprintf (stderr, "failed to initialize image addon!\n"); exit (-1); } al_init_font_addon (); if(!al_init_ttf_addon ()) { fprintf (stderr, "failed to initialize ttf addon!\n"); exit (-1); } if(!al_install_audio ()) { fprintf (stderr, "failed to initialize audio addon!\n"); exit (-1); } if(!al_init_acodec_addon ()) { fprintf (stderr, "failed to initialize audio codecs addon!\n"); exit (-1); } if (!al_reserve_samples (16)) { fprintf (stderr, "failed to reserve samples!\n"); exit (-1); } if(!al_install_keyboard ()) { fprintf (stderr, "failed to initialize keyboard!\n"); exit (-1); } if (fullscreen) { al_set_new_display_flags (ALLEGRO_FULLSCREEN); } game->display = al_create_display (width, height); if (!game->display) { fprintf (stderr, "failed to create display!\n"); } game->timer = al_create_timer (game->timestep); game->event_queue = al_create_event_queue (); al_register_event_source (game->event_queue, al_get_display_event_source (game->display)); al_register_event_source (game->event_queue, al_get_timer_event_source (game->timer)); al_register_event_source (game->event_queue, al_get_keyboard_event_source ()); return SCM_UNSPECIFIED; }
int main(int argc, char **argv) { // Initialize Allegro if (!al_init()) { fprintf(stderr, "Fatal Error: Allegro initialization failed!\n"); return -1; } // Initialize the Allegro Image addon, used to load sprites and maps if (!al_init_image_addon()) { fprintf(stderr, "Fatal Error: Allegro Image Addon initialization failed!\n"); return -1; } // Initialize primitives for drawing if (!al_init_primitives_addon()) { fprintf(stderr, "Fatal Error: Could not initialize primitives module!"); throw -1; } // Initialize keyboard modules if (!al_install_keyboard()) { fprintf(stderr, "Fatal Error: Could not initialize keyboard module!"); throw -1; } // Initialize mouse if (!al_install_mouse()) { fprintf(stderr, "Fatal Error: Could not initialize mouse module!"); throw -1; } // Initialize networking system if (enet_initialize()) { fprintf(stderr, "Fatal Error: Could not initialize enet!"); throw -1; } // Create a display ALLEGRO_DISPLAY *display; al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE); al_set_new_display_flags(ALLEGRO_OPENGL | ALLEGRO_RESIZABLE); display = al_create_display(1280, 720); if(!display) { // FIXME: Make the error argument mean anything? fprintf(stderr, "Fatal Error: Could not create display\n"); throw -1; } //load font //gg2 font as placeholder for now i guess al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_FONT *font = al_load_font("Vanguard Main Font.ttf", 12, ALLEGRO_TTF_MONOCHROME); if (!font) { fprintf(stderr, "Could not load 'gg2bold.ttf'.\n"); throw -1; } // MainMenu *mainmenu = new MainMenu(display); bool isserver; if (argc >= 2) { // If there are any arguments isserver = false; } else { isserver = true; } // double lasttimeupdated = al_get_time(); // bool run = true; // while (run) // { // if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP) // { // run = mainmenu->run(display, &gametype); // lasttimeupdated = al_get_time(); // } // } // delete mainmenu; Engine engine(isserver); Renderer renderer; InputCatcher inputcatcher(display); Gamestate renderingstate(&engine); std::unique_ptr<Networker> networker; if (isserver) { networker = std::unique_ptr<Networker>(new ServerNetworker()); } else { networker = std::unique_ptr<Networker>(new ClientNetworker()); } engine.loadmap("lijiang"); // FIXME: Hack to make sure the oldstate is properly initialized engine.update(&(networker->sendbuffer), 0); EntityPtr myself(0); if (isserver) { myself = engine.currentstate->addplayer(); engine.currentstate->get<Player>(myself)->spawntimer.active = true; } else { ClientNetworker *n = reinterpret_cast<ClientNetworker*>(networker.get()); while (not n->isconnected()) { n->receive(engine.currentstate.get()); } myself = engine.currentstate->playerlist[engine.currentstate->playerlist.size()-1]; } InputContainer held_keys; double mouse_x; double mouse_y; double enginetime = al_get_time(); double networkertime = al_get_time(); while (true) { try { while (al_get_time() - enginetime >= ENGINE_TIMESTEP) { networker->receive(engine.currentstate.get()); inputcatcher.run(display, &held_keys, &mouse_x, &mouse_y); if (not isserver) { Character *c = engine.currentstate->get<Player>(myself)->getcharacter(engine.currentstate.get()); if (c != 0) { ClientNetworker *n = reinterpret_cast<ClientNetworker*>(networker.get()); n->sendinput(held_keys, mouse_x/renderer.zoom+renderer.cam_x, mouse_y/renderer.zoom+renderer.cam_y); } } engine.setinput(myself, held_keys, mouse_x/renderer.zoom+renderer.cam_x, mouse_y/renderer.zoom+renderer.cam_y); engine.update(&(networker->sendbuffer), ENGINE_TIMESTEP); networker->sendeventdata(engine.currentstate.get()); enginetime += ENGINE_TIMESTEP; } if (isserver) { if (al_get_time() - networkertime >= NETWORKING_TIMESTEP) { ServerNetworker *n = reinterpret_cast<ServerNetworker*>(networker.get()); n->sendframedata(engine.currentstate.get()); networkertime = al_get_time(); } } renderingstate.interpolate(engine.oldstate.get(), engine.currentstate.get(), (al_get_time()-enginetime)/ENGINE_TIMESTEP); renderer.render(display, &renderingstate, myself, networker.get()); } catch (int e) { if (e != 0) { fprintf(stderr, "\nError during regular loop."); fprintf(stderr, "\nExiting.."); } al_destroy_display(display); return 0; } } al_shutdown_font_addon(); al_shutdown_ttf_addon(); al_destroy_display(display); enet_deinitialize(); return 0; }
int main(void) { ALLEGRO_DISPLAY *display; ALLEGRO_TIMER *timer; ALLEGRO_EVENT_QUEUE *queue; int redraw = 0, i; bool quit = false; if (!al_init()) { abort_example("Could not initialise Allegro\n"); return 1; } al_init_primitives_addon(); al_install_mouse(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); srand(time(NULL)); white = al_map_rgba_f(1, 1, 1, 1); display = al_create_display(640, 480); if (!display) { abort_example("Could not create display\n"); return 1; } al_set_window_title(display, "Allegro Logo Generator"); al_install_keyboard(); /* Read logo parameters from logo.ini (if it exists). */ config = al_load_config_file("logo.ini"); if (!config) config = al_create_config(); for (i = 0; param_names[i]; i++) { char const *value = al_get_config_value(config, "logo", param_names[i]); if (value) strncpy(param_values[i], value, sizeof(param_values[i])); } font = al_load_font("data/DejaVuSans.ttf", 12, 0); if (!font) { abort_example("Could not load font\n"); return 1; } timer = al_create_timer(1.0 / 60); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_timer_event_source(timer)); al_start_timer(timer); while (!quit) { ALLEGRO_EVENT event; al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) break; if (event.type == ALLEGRO_EVENT_KEY_CHAR) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { quit = true; } else if (event.keyboard.keycode == ALLEGRO_KEY_ENTER) { if (editing) { regenerate = true; editing = false; } else { cursor = 0; editing = true; } } else if (event.keyboard.keycode == ALLEGRO_KEY_UP) { if (selection > 0) { selection--; cursor = 0; editing = false; } } else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) { if (param_names[selection + 1]) { selection++; cursor = 0; editing = false; } } else { int c = event.keyboard.unichar; if (editing) { if (c >= 32) { ALLEGRO_USTR *u = al_ustr_new(param_values[selection]); al_ustr_set_chr(u, cursor, c); cursor++; al_ustr_set_chr(u, cursor, 0); strncpy(param_values[selection], al_cstr(u), sizeof param_values[selection]); al_ustr_free(u); } } else { if (c == 'r') randomize(); if (c == 's') save(); } } } if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (event.mouse.button == 1) { mouse_click(event.mouse.x, event.mouse.y); } } if (event.type == ALLEGRO_EVENT_TIMER) redraw++; if (redraw && al_is_event_queue_empty(queue)) { redraw = 0; render(); al_flip_display(); } } /* Write modified parameters back to logo.ini. */ for (i = 0; param_names[i]; i++) { al_set_config_value(config, "logo", param_names[i], param_values[i]); } al_save_config_file("logo.ini", config); al_destroy_config(config); return 0; }
int main(void) { srand(static_cast<int>(time(nullptr) % 100 )); bool keys[10] = {false, false, false, false, false, false, false, false, false, false}; bool done = false; bool redraw = true; int FPS = 60; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; //initialize allegro if(!al_init()) { al_show_native_message_box(NULL, NULL, NULL, "failed to initialize allegro!", NULL, NULL); return -1; } //create our display object display = al_create_display(app_width, app_height); //test display object if(!display) { al_show_native_message_box(NULL, NULL, NULL, "failed to initialize display!", NULL, NULL); return -1; } al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_FONT *font12 = al_load_font("arial.ttf", 12, 0); ALLEGRO_FONT *font24 = al_load_font("arial.ttf", 24, 0); ALLEGRO_FONT *font36 = al_load_font("arial.ttf", 36, 0); ALLEGRO_FONT *font18 = al_load_font("arial.ttf", 18, 0); al_init_primitives_addon(); al_install_keyboard(); al_install_mouse(); event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / 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_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); //al_hide_mouse_cursor(display); al_start_timer(timer); Tilemap tilemap; /*int mountain_index = rand() % (tilemap_size_num_tiles_x * tilemap_size_num_tiles_y); tilemap.tile_[300].height_ = 10; tilemap.tile_[300].erosion_givingness = 0; int deep_index = rand() % (tilemap_size_num_tiles_x * tilemap_size_num_tiles_y); tilemap.tile_[301].height_ = -10; tilemap.tile_[301].erosion_givingness = 0;*/ std::vector<Sprite> tree; Sprite p1(tile_render_size*1.5,tile_render_size*1.5,color_p1); Sprite p2(tile_render_size*2.5,tile_render_size*1.5,color_p2); Timer tilemap_time; int num_natural_erosions = 0; int sec_per_natural_erosion = 1; int num_tree_periods = 0; int sec_per_tree_period = 0.3; while(!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if(ev.mouse.button & 1) { p1.x = ev.mouse.x; p1.y = ev.mouse.y; } else if (ev.mouse.button & 2) { p2.x = ev.mouse.x; p2.y = ev.mouse.y; } } else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES) { } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; 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; std::cout << "E:\n"; //std::cout << "\n" << tilemap.tile[1][1].height() << "\n"; ErodeTilemap(tilemap); //std::cout << "\n" << tilemap.tile[1][1].height() << "\n"; break; case ALLEGRO_KEY_N: keys[N] = true; Tilemap new_tilemap; //for ( int i = 0; i < 10; i++ ) new_tilemap = ErodeTilemap(new_tilemap); tilemap = new_tilemap; tree.clear(); break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = 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; case ALLEGRO_KEY_N: keys[N] = false; break; case ALLEGRO_KEY_ESCAPE: done = true; break; } } else if(ev.type == ALLEGRO_EVENT_TIMER) { if ( keys[UP] ) p1.y -= 1; if ( keys[DOWN] ) p1.y += 1; if ( keys[RIGHT] ) p1.x += 1; if ( keys[LEFT] ) p1.x -= 1; if ( keys[W] ) p2.y -= 1; if ( keys[S] ) p2.y += 1; if ( keys[D] ) p2.x += 1; if ( keys[A] ) p2.x -= 1; /*ALLEGRO_MOUSE_STATE MouseState; al_get_mouse_state(&MouseState); if ( MouseState.buttons & 1 ) { p1.x = ev.mouse.x; }*/ if ( tilemap_time.now() > num_natural_erosions * sec_per_natural_erosion ) { ErodeTilemap(tilemap); num_natural_erosions++; //kill underwater and beach trees: for( int i = 0; i < tree.size(); i++ ) { if ( 0.2 > tilemap.tile_[(int)tree[i].x%tile_render_size,(int)tree[i].y/tile_render_size].height() ) { tree.erase(tree.begin()+i); } } } if ( tilemap_time.now() > num_tree_periods * sec_per_tree_period ) { for ( int i = 0; i < tilemap_size_num_tiles_x * tilemap_size_num_tiles_y; i++) { if ( tilemap.tile_[i].height_ > 1 ) { if ( 0.05 > (float)(rand() % 10000) / 100 ) { int x = i_t_x(i)*tile_render_size + rand()%tile_render_size; int y = i_t_y(i)*tile_render_size + rand()%tile_render_size; int g = 102+rand()%102; tree.push_back(Sprite(x,y,Color(0,g,0))); } } } } if ( collision(p1,p2) ) std::cout << "collision!\n"; redraw = true; } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; // Draw tilemap tiles: // i and j changes are hack that will cause problems later for ( int i = 1; i < view_tile_count_x+1; i++ ) { for ( int j = 1; j < view_tile_count_y+1; j++ ) { al_draw_filled_rectangle(i*tile_render_size,j*tile_render_size,i*tile_render_size+tile_render_size,j*tile_render_size+tile_render_size, al_map_rgb(tilemap.tile_[xy_t_i(i,j)].color_.r,tilemap.tile_[xy_t_i(i,j)].color_.g,tilemap.tile_[xy_t_i(i,j)].color_.b)); //al_draw_textf(font12, al_map_rgb(255,255,255), i*tile_render_size + tile_render_size/2,j*tile_render_size, ALLEGRO_ALIGN_CENTRE, "%.1fm", tilemap.tile_[xy_t_i(i,j)].height() ); //al_draw_textf(font12, al_map_rgb(255,255,255), i*tile_render_size + tile_render_size/2,(j+.5)*tile_render_size, ALLEGRO_ALIGN_CENTRE, "%d", i + j * tilemap_size_num_tiles_x ); } } // Draw player 1 //al_draw_filled_rectangle(p1.x-p1.radius, p1.y-p1.radius, p1.x+p1.radius, p1.y+p1.radius, al_map_rgb(204, 0, 0)); al_draw_filled_circle(p1.x, p1.y, p1.radius, al_map_rgb(p1.color.r, p1.color.g, p1.color.b)); al_draw_text(font24, al_map_rgb(0,0,0), p1.x, p1.y-p1.radius, ALLEGRO_ALIGN_CENTRE, "1"); // Draw player 2 //al_draw_filled_rectangle(p2.x-p2.radius, p2.y-p2.radius, p2.x+p2.radius, p2.y+p2.radius, al_map_rgb(0, 102, 204)); al_draw_filled_circle(p2.x, p2.y, p2.radius, al_map_rgb(p2.color.r, p2.color.g, p2.color.b)); al_draw_text(font24, al_map_rgb(0,0,0), p2.x, p2.y-p2.radius, ALLEGRO_ALIGN_CENTRE, "2"); // Draw trees for( int i = 0; i < tree.size(); i++ ) { al_draw_filled_circle(tree[i].x, tree[i].y, tree[i].radius, al_map_rgb(tree[i].color.r, tree[i].color.g, tree[i].color.b)); } // Draw info al_draw_textf(font12, al_map_rgb(255,255,255), tilemap_size_num_tiles_x*tile_render_size,0,0, "tilemap_time.now(): %.1f --- ErodeTilemap occurs every 10s!", tilemap_time.now() ); al_draw_textf(font12, al_map_rgb(255,255,255), tilemap_size_num_tiles_x*tile_render_size,12,0, "ErodeTilemap occurs every %ds!", sec_per_natural_erosion ); al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } } al_destroy_font(font12); al_destroy_font(font18); al_destroy_font(font24); al_destroy_font(font36); al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_display(display); //destroy our display object return 0; }
int main(int argc, char** argv) { time_t t; srand((unsigned) time(&t)); if (!al_init()) { std::cout << "Failed to start Allegro."; return -1; } if (!al_init_image_addon()) { std::cout << "Failed to start Allegro Imagea person who gives information to the police or to some other authority about the bad behavior or criminal activity of someone else Addon.\n"; return -1; } if (!al_init_primitives_addon()) { std::cout << "Failed to start Allegro Primitives Addon.\n"; return -1; } if (!al_init_font_addon()) { std::cout << "Failed to start Allegro Font Addon.\n"; return -1; } if (!al_init_ttf_addon()) { std::cout << "Failed to start Allegro TTF Addon.\n"; return -1; } ALLEGRO_DISPLAY* main_window = al_create_display(800, 600); if (!main_window) { std::cout << "Failed to create display."; return -1; } ALLEGRO_EVENT_QUEUE* eq = al_create_event_queue(); if (!eq) { std::cout << "Failed to create event queue."; return -1; } ALLEGRO_TIMER* fps_timer = al_create_timer(1.0 / 60); if (!fps_timer) { std::cout << "Failed to create timer."; return -1; } ALLEGRO_TIMER* count_timer = al_create_timer(1.0); if (!count_timer) { std::cout << "Failed to create count timer."; return -1; } if (!al_install_keyboard()) { std::cout << "Failed to install keyboard."; return -1; } if (!al_install_mouse() || !al_set_mouse_cursor(main_window, al_create_mouse_cursor(al_load_bitmap("resources/sprites/UI/cursor/clicker.png"), 16, 31))) { std::cout << "Failed to install mouse."; return -1; } al_register_event_source(eq, al_get_timer_event_source(fps_timer)); al_register_event_source(eq, al_get_timer_event_source(count_timer)); al_register_event_source(eq, al_get_keyboard_event_source()); al_register_event_source(eq, al_get_mouse_event_source()); al_register_event_source(eq, al_get_display_event_source(main_window)); Game base; if (!base.init()) { std::cout << "Failed to initialise game! Quitting...\n"; return -1; } bool ready_to_draw = false; bool ready_to_draw_fps = false; al_start_timer(fps_timer); al_start_timer(count_timer); int fps_count = 0; ALLEGRO_FONT* fps_font = al_load_ttf_font("resources/fonts/MontereyFLF.ttf", 11, 0); if (!fps_font) { std::cout << "Failed to load font for fps counter!"; return -1; } while (true) { while (!al_event_queue_is_empty(eq)) { ALLEGRO_EVENT ev; al_get_next_event(eq, &ev); if (ev.type == ALLEGRO_EVENT_TIMER) { if (ev.timer.source == fps_timer) { ready_to_draw = true; } else if (ev.timer.source == count_timer) { ready_to_draw_fps = true; } } else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { std::cout << "Safely quitting."; al_destroy_display(main_window); al_destroy_event_queue(eq); al_destroy_timer(fps_timer); return 0; } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) //current keyboard input section { std::cout << "Safely quitting."; al_destroy_display(main_window); al_destroy_event_queue(eq); al_destroy_timer(fps_timer); return 0; } } base.runEvents(ev); } if (ready_to_draw) { fps_count++; base.runLogic(); base.runDisplay(); char buffer[25]; if (ready_to_draw_fps) { sprintf(buffer, "%d", fps_count); fps_count = 0; ready_to_draw_fps = false; } al_draw_text(fps_font, al_map_rgb(0,255,0), 5, 5, 0, buffer); al_flip_display(); ready_to_draw = false; } } }
void inic_biblioteca_allegro_ttf (void) { if (!al_init_ttf_addon()) { fprintf(stderr, "Falha ao inicializar o Allegro TrueType!\n"); exit(-1); } }
void StateControl::Initialize() { cout << endl; cout << "* * * * * * * * * * * * *" << endl; cout << "* *" << endl; cout << "* STARTING RADIO *" << endl; cout << "* *" << endl; cout << "* * * * * * * * * * * * *" << endl; cout << endl; cout << "-------------" << endl; cout << "Activity Log:" << endl; cout << "-------------" << endl; cout << "Getting time seed for random numbers..." << endl; srand ((unsigned int) time(NULL)); cout << "Starting Allegro 5..." << endl; if (!al_init()) { al_show_native_message_box(NULL, NULL, "Could not initialize Allegro 5", NULL, NULL, NULL); } cout << "Initializing addons..." << endl; al_init_image_addon(); al_init_primitives_addon(); al_init_acodec_addon(); al_init_font_addon(); al_init_ttf_addon(); cout << "Installing devices..." << endl; al_install_mouse(); al_install_keyboard(); al_install_audio(); cout << "Creating display..." << endl; CreateAllegroDisplay(); cout << "Loading fonts..." << endl; LoadFonts(); cout << "Creating timers..." << endl; timer = al_create_timer(1.0 / FPS); cout << "Creating event queues..." << endl; event_queue = al_create_event_queue(); cout << "Registring event sources..." << endl; 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()); cout << "Initializing variables..." << endl; left_mouse_button_pressed = false; left_mouse_button_released = false; right_mouse_button_pressed = false; right_mouse_button_released = false; playing_music = false; possible_double_press = false; double_press_counter = 0; player_interface_y_coord = 380; music_time_counter = 0; cout << "Starting timers..." << endl; al_start_timer(timer); }