Timer::Timer(){ Set(500); running = false; remainingTime = 0; coreTimer = NULL; coreTimer = al_create_timer(1.0 / 60); startingTime = al_get_timer_count(coreTimer); lastTick = al_get_timer_count(coreTimer); al_start_timer(coreTimer); }
Timer::Timer(double duration){ Set(duration); running = false; remainingTime = 0; coreTimer = NULL; coreTimer = al_create_timer(1.0 / 60); startingTime = al_get_timer_count(coreTimer); lastTick = al_get_timer_count(coreTimer); al_start_timer(coreTimer); lastFrameTimeStamp = al_get_timer_count(coreTimer); globalDeltaTime = 0; }
double Timer::Start(){ if(running) return remainingTime; startingTime = al_get_timer_count(coreTimer); remainingTime = startingTime + duration; running = true; return remainingTime; }
int64_t TimerEvent::get_count(void) { RAGE_CHECK_DISPOSED_RET(disposed, 0); if (timer != nullptr) return al_get_timer_count(timer); else return -1; }
//Calculates the player score according to the timed calculation //In - // int NewXPosition - the new x position for the player // int CurrentGameScale - the current game scale number //Out - // int - the calculated timed score for the player int PlayerScoreCalculator::CalculateTimedScore(const ALLEGRO_TIMER* InputTimer, int CurrentGameScale) { //get the time in seconds int TimerTime = (al_get_timer_count(InputTimer) / 60); //calculate the final score int CalculatedScore = m_CurrentPlayerScore - (TimerTime / CurrentGameScale); if(CalculatedScore < 0) { CalculatedScore = 0; } //return calculated score return CalculatedScore; }
void fb_logic(){ bird->calc_bounds(); if(!has_lost){ bird->im.img_data=bird_frames[bird->im.rotation<0]; } bird->im.rotation_vel=(1.0f/30.0f)*(PI/2-bird->im.rotation); bird->y_vel=13.6f*sin(bird->im.rotation); if(bird->y<=0||bird->y>=DISPLAY_HEIGHT) loss_handle(); if(background->x<=0) background->x+=DISPLAY_WIDTH; for(std::list< my_pipe* >::iterator iter = pipes.begin();iter!=pipes.end();){ if((*iter)->x <= -50){ delete *iter; pipes.pop_front(); iter=pipes.begin(); }else{ if(!(*iter)->has_passed&&(*iter)->x<=bird_x){ (*iter)->has_passed=true; if((*iter)->is_pair_leader&&!has_lost){ ++score; } } (*iter)->calc_bounds(); if(col_intersect(*bird,**iter)){ loss_handle(); } ++iter; } } snprintf(score_string->text,14,"Score: %ld", score); #ifdef NDEBUG snprintf(tick_string->text,20,"Tick: %d", al_get_timer_count(timer)); snprintf(vel_string->text,20,"Y Velocity: %d", -int(bird->y_vel)); #endif }
LEVEL * level_update(LEVEL *level, SHIP *ship, bool keys[], ALLEGRO_TIMER *timer) { int64_t time_count = al_get_timer_count(timer); uint8_t next_saucer = abs(level->number + (-LEVEL_MAX)) * 1.3; /* is it time to introduce a new saucer? */ if(!level->saucer) if(seconds_elapsed(time_count - level->saucer_seen) > next_saucer) level->saucer = saucer_new(SAUCER_LARGE, level->number, timer); if(level->saucer) { level->saucer = saucer_update(level->saucer, ship, timer); level->saucer_seen = time_count; /* saucer missiles */ if(!level->saucer->missile->active) saucer_fire(level->saucer, ship, timer); } asteroid_update_list(level->asteroids); return level; }
double Timer::Reset(double newDuration){ remainingTime = duration = newDuration; startingTime = al_get_timer_count(coreTimer); Update(); return duration; }
void Timer::Update(){ deltaTime = al_get_timer_count(coreTimer) - lastTick; if(running) remainingTime -= deltaTime; lastTick = al_get_timer_count(coreTimer); }
void Root::start() { al_init(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); al_install_keyboard(); al_install_mouse(); m_windowWidth = 1024; m_windowHeight = 768; m_display = al_create_display(m_windowWidth, m_windowHeight); m_drawTimer = al_create_timer(1.0 / FPS); m_tickTimer = al_create_timer(1.0 / TPS); m_fpsLimit = false; /* Initializing assets */ m_assets = new Assets(); /* Initializing spritesheets */ m_spritesheetDatabase = new SpritesheetDatabase(); m_spritesheetDatabase->load(m_assets); /* Initializing tiles */ m_tileDatabase = new TileDatabase(); addBaseTilesToDatabase(); m_tileDatabase->load(m_assets); /* World generator */ //temporarly it will be hardcoded world generator path/handle/id std::vector<std::string> generators = m_assets->worldGenerators(); if(generators.empty()) { std::cout << "No world generators found. Exiting."; return; } Configuration worldGeneratorConfig = Configuration(generators[0]); m_worldGenerator = new WorldGenerator(worldGeneratorConfig); /* Creating world */ m_world = new World(m_worldGenerator); al_start_timer(m_tickTimer); al_start_timer(m_drawTimer); int framesThisSecond = 0; int ticksThisSecond = 0; int lastTicks = al_get_timer_count(m_tickTimer); int lastFPSTicks = al_get_timer_count(m_drawTimer); for(;;) { ALLEGRO_KEYBOARD_STATE currentKeyboardState; al_get_keyboard_state(¤tKeyboardState); int nowTicks = al_get_timer_count(m_tickTimer); int nowDrawTicks = al_get_timer_count(m_drawTimer); if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_ESCAPE)) { return; } if(nowTicks != lastTicks && !(nowTicks % TPS)) { m_currentFps = framesThisSecond; framesThisSecond = 0; m_currentTps = ticksThisSecond; ticksThisSecond = 0; std::cout << "FPS: " << m_currentFps << "\nTPS: " << m_currentTps << "\n\n"; } if(nowTicks != lastTicks) { lastTicks = nowTicks; ++m_ticks; ++ticksThisSecond; #define HIGH_SPEED_CAMERA #ifndef HIGH_SPEED_CAMERA /* low camera speed */ if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_LEFT)) { m_world->moveCamera(Vec2D(-3, 0)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_RIGHT)) { m_world->moveCamera(Vec2D(3, 0)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_UP)) { m_world->moveCamera(Vec2D(0, -3)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_DOWN)) { m_world->moveCamera(Vec2D(0, 3)); } #else /* high camera speed */ if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_LEFT)) { m_world->moveCamera(Vec2F(-20.3, 0)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_RIGHT)) { m_world->moveCamera(Vec2F(20.3, 0)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_UP)) { m_world->moveCamera(Vec2F(0, -20.3)); } if(al_key_down(¤tKeyboardState, ALLEGRO_KEY_DOWN)) { m_world->moveCamera(Vec2F(0, 20.3)); } #endif // HIGH_SPEED_CAMERA m_world->update(); } if(nowDrawTicks != lastFPSTicks || !m_fpsLimit) { lastFPSTicks = nowDrawTicks; ++framesThisSecond; al_clear_to_color(al_map_rgb(64, 128, 255)); m_world->draw(); al_flip_display(); } } }
int game_loop(){ unsigned redraw = 0; game_rect t; rect_Zero(&t); sprite_sheet = gamespr_create("ski1.bmp"); animation_init(); init_player(); start_new_game(0); while(!mainloop){ ALLEGRO_EVENT e; ALLEGRO_TIMEOUT timeout; int i; al_init_timeout(&timeout, 0.06); bool late = al_wait_for_event_until(g_queue, &e, &timeout); if(late){ switch(e.type){ case ALLEGRO_EVENT_DISPLAY_CLOSE: mainloop = 1; break; case ALLEGRO_EVENT_KEY_UP: player_poll_kbd_up(&e); break; case ALLEGRO_EVENT_KEY_DOWN: player_poll_kbd_dn(&e); break; case ALLEGRO_EVENT_TIMER: /* main clock updates 1/60ms (60FPS LOCK) */ if(e.timer.source == g_timer){ particle_list = particles_clean(particle_list, 0); particles_update(particle_list); player_update_screen(); player_update(&ski_player, &playfield); for(i = 1; i < MAX_SPRITES; i++){ update_enemy(i); } update_enemy_behavior(gobj_list, &playfield); redraw = 1; } /* update for the chronomenter run every 100ms only) */ if( e.timer.source == timer_chrono){ HUD_UpdateChrono(); DMSG("%d", al_get_timer_count(timer_chrono)); } break; } if( redraw == 1 && al_event_queue_is_empty(g_queue)){ redraw = 0; al_clear_to_color(WHITE_COLOR); particles_draw(NULL, particle_list); player_draw(ski_player.object->position.x, ski_player.object->position.y ); for(i = 1; i < MAX_OBJECTS; i++){ int enemy_type = gobj_list[i].type; draw_enemy(enemy_type, i, 0,0, gobj_list[i].position.x, gobj_list[i].position.y, 32,32); } HUD_create_stats_box(); al_flip_display(); } } } HUD_destroy(); unload_spritesheets(); window_deinit(); particle_list = particles_clean(particle_list, PARTICLES_ALL_CLEAN); return EXIT_SUCCESS; }
int main(int argc, char **argv) { al_init(); al_install_mouse(); al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); al_set_new_display_flags(ALLEGRO_WINDOWED|ALLEGRO_RESIZABLE); ALLEGRO_DISPLAY *display = al_create_display(640, 480); ALLEGRO_DISPLAY *tooldisplay = al_create_display(200, 480); al_set_window_position(tooldisplay, 10, 0); al_set_window_position(display, 220, 0); ALLEGRO_DISPLAY *current_display = tooldisplay; ALLEGRO_TIMER* timer = al_create_timer(1); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display); al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)tooldisplay); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_timer_event_source(timer)); ALLEGRO_FONT* font = al_load_font("data/DejaVuSans.ttf", 12, 0); if(!font) font = al_load_font("examples/data/DejaVuSans.ttf", 12, 0); Layout layout; Layout_controller layout_controller; layout_controller.Set_layout(&layout); Tree* widget_tree = layout_controller.Get_skin().Clone<Tree>("tree"); widget_tree->Set_text("Desktop"); widget_tree->Select(); Widget* root_widget = layout_controller.Get_skin().Clone<Desktop>("desktop"); root_widget->Set_position(Vector2(0, 0)); root_widget->Set_size(Vector2(640, 480)); layout_controller.Set_tree(widget_tree, root_widget); layout_controller.Set_root(root_widget); layout_controller.Set_root_tree(widget_tree); layout_controller.Select_tree(widget_tree); layout.Set_skin(&layout_controller.Get_skin()); layout.Add_widget("root", root_widget, NULL); Editor_controller editor_controller; editor_controller.Set_layout_display(display); editor_controller.Set_layout_controller(layout_controller); editor_controller.Load(layout_controller.Get_skin()); //FPS Label* fps_label = layout_controller.Get_skin().Clone<Label>("label"); fps_label->Set_text("FPS: 100"); //Main vbox Vertical_box* toolvbox = layout_controller.Get_skin().Clone<Vertical_box>("vertical box"); toolvbox->Add(editor_controller.Get_root()); toolvbox->Add(fps_label); Slider_box* slider_box = layout_controller.Get_skin().Clone<Slider_box>("slider box"); slider_box->Set_child(toolvbox); Desktop* desktop = layout_controller.Get_skin().Clone<Desktop>("desktop"); desktop->Set_child(slider_box); desktop->Set_position(Vector2(0, 0)); desktop->Set_size(Vector2(200, 480)); Widget* toolroot = desktop; al_start_timer(timer); bool quit = false; while (!quit) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if (ALLEGRO_EVENT_KEY_DOWN == event.type) { if (ALLEGRO_KEY_ESCAPE == event.keyboard.keycode) { quit=true; } } if (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type) { quit=true; } if (ALLEGRO_EVENT_DISPLAY_RESIZE == event.type) { al_acknowledge_resize(event.display.source); if(event.display.source == display) layout_controller.Get_root()->Set_size(Vector2(event.display.width-20, event.display.height-20)); } if (ALLEGRO_EVENT_DISPLAY_SWITCH_IN == event.type) { current_display = event.display.source; } if(current_display == tooldisplay) { toolroot->Handle_event(event); } if(current_display == display) { layout_controller.Get_root()->Handle_event(event); } if(ALLEGRO_EVENT_TIMER == event.type) { double dt = al_get_timer_speed(timer); editor_controller.Update(); layout_controller.Get_skin().Update(dt); al_set_target_backbuffer(display); layout_controller.Get_root()->Render(); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); al_set_target_backbuffer(tooldisplay); toolroot->Render(); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); double fps = 1 / dt; std::stringstream ss; ss<<fps; std::string fps_string; ss>>fps_string; fps_label->Set_text((std::string("FPS: ")+fps_string).c_str()); if(dt < 1 && event.timer.count < al_get_timer_count(timer) - 4) { dt = dt * 1.1; al_set_timer_speed(timer, dt); //print("Tick too fast, setting speed to " .. timer_speed); } if(event.timer.count == al_get_timer_count(timer)) { dt = dt * 0.9; al_set_timer_speed(timer, dt); //print("Tick too fast, setting speed to " .. timer_speed); } al_rest(0.001); } }
int main(int argc, char **argv){ ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_BITMAP *bouncer = NULL; ALLEGRO_BITMAP *buses[NUM_RUAS]; int playing = 1; int collision = 0; //posicoes x e y iniciais do frog float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE / 2.0; float bouncer_y = SCREEN_H - BOUNCER_SIZE; //o quanto as posicoes x e y vao variar ao longo do tempo. No t=1, se x do bouncer eh 40, no t=2, x do bouncer eh 40 + bouncer_dx = 36 float bouncer_dx = SCREEN_W /20.0, bouncer_dy = (float)SCREEN_H / NUM_RUAS; float TAM_RUA = (float) SCREEN_H / NUM_RUAS; float LARGURA_BUS = TAM_RUA * 0.8; //automoveis float buses_x[NUM_RUAS]; float buses_y[NUM_RUAS]; float buses_comp[NUM_RUAS]; float buses_dx[NUM_RUAS]; int i; int j; //----------------------- rotinas de inicializacao --------------------------------------- if(!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } timer = al_create_timer(1.0 / FPS); if(!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } //cria um bitmap quadrangular de tamanho BOUNCER_SIZE (variavel global declarada acima) bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE); if(!bouncer) { fprintf(stderr, "failed to create bouncer bitmap!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } //buses for(i=0; i<NUM_RUAS; i++) { buses_y[i] = i*TAM_RUA + 0.1*TAM_RUA; buses_x[i] = 0; buses_comp[i] = rand()%(SCREEN_W/4) + 10; buses_dx[i] = 3*(float)rand()/(float)RAND_MAX; buses[i] = al_create_bitmap(buses_comp[i], LARGURA_BUS); al_set_target_bitmap(buses[i]); al_clear_to_color(al_map_rgb(rand()%256, rand()%256, rand()%256)); } al_install_keyboard(); //avisa o allegro que eu quero modificar as propriedades do bouncer al_set_target_bitmap(bouncer); //altera a cor do bouncer para rgb(255,0,255) al_clear_to_color(al_map_rgb(0, 255, 0)); //avisa o allegro que agora eu quero modificar as propriedades da tela al_set_target_bitmap(al_get_backbuffer(display)); //colore a tela de preto (rgb(0,0,0)) al_clear_to_color(al_map_rgb(0,0,0)); //cria a fila de eventos event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_bitmap(bouncer); al_destroy_display(display); al_destroy_timer(timer); return -1; } //registra na fila de eventos que eu quero identificar quando a tela foi alterada al_register_event_source(event_queue, al_get_display_event_source(display)); //registra na fila de eventos que eu quero identificar quando o tempo alterou de t para t+1 al_register_event_source(event_queue, al_get_timer_event_source(timer)); //registra que a fila de eventos deve detectar quando uma tecla for pressionada no teclado al_register_event_source(event_queue, al_get_keyboard_event_source()); //reinicializa a tela al_flip_display(); //inicia o temporizador al_start_timer(timer); //enquanto playing for verdadeiro, faca: while(playing) { ALLEGRO_EVENT ev; //espera por um evento e o armazena na variavel de evento ev al_wait_for_event(event_queue, &ev); //se o tipo do evento for uma tecla pressionada if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { //verifica qual tecla foi switch(ev.keyboard.keycode) { //se a tecla for o W case ALLEGRO_KEY_W: bouncer_y -= bouncer_dy; if(bouncer_y < 0) playing = 0; break; //se a tecla for o S case ALLEGRO_KEY_S: if(bouncer_y < SCREEN_H - BOUNCER_SIZE) bouncer_y += bouncer_dy; break; case ALLEGRO_KEY_A: if(bouncer_x > 0) bouncer_x -= bouncer_dx; break; case ALLEGRO_KEY_D: if(bouncer_x < SCREEN_W - BOUNCER_SIZE) bouncer_x += bouncer_dx; break; case ALLEGRO_KEY_ESCAPE: playing = 0; break; } } //se o tipo de evento for um evento do temporizador, ou seja, se o tempo passou de t para t+1 if(ev.type == ALLEGRO_EVENT_TIMER) { //limpo a tela al_clear_to_color(al_map_rgb(0,0,0)); //desenho o bouncer nas novas posicoes x e y al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0); for(i=0; i<NUM_RUAS; i++) { buses_x[i] += buses_dx[i]; if(buses_x[i] > SCREEN_W) buses_x[i] = 0; al_draw_bitmap(buses[i], buses_x[i], buses_y[i], 0); if( (bouncer_x + BOUNCER_SIZE > buses_x[i] && bouncer_x < buses_x[i] + buses_comp[i]) && (bouncer_y < buses_y[i] + LARGURA_BUS && bouncer_y > buses_y[i]) ) { playing = 0; collision = 1; } } //reinicializo a tela al_flip_display(); } //se o tipo de evento for o fechamento da tela (clique no x da janela) else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { //interrompe o while(1) break; } } //fim do while //inicializa o modulo allegro que carrega as fontes al_init_font_addon(); //inicializa o modulo allegro que entende arquivos tff de fontes al_init_ttf_addon(); //carrega o arquivo arial.ttf da fonte Arial e define que sera usado o tamanho 32 (segundo parametro) ALLEGRO_FONT *size_32 = al_load_font("arial.ttf", 32, 1); char my_text[20]; //colore toda a tela de preto al_clear_to_color(al_map_rgb(0,0,0)); //imprime o texto armazenado em my_text na posicao x=10,y=10 e com a cor rgb(128,200,30) if(collision) al_draw_text(size_32, al_map_rgb(200, 0, 30), SCREEN_W/3, SCREEN_H/2, 0, "Perdeu :("); else { sprintf(my_text, "Ganhou: %.2f segundos", al_get_timer_count(timer)/FPS); al_draw_text(size_32, al_map_rgb(0, 200, 30), SCREEN_W/3, SCREEN_H/2, 0, my_text); } //reinicializa a tela al_flip_display(); al_rest(3); //procedimentos de fim de jogo (fecha a tela, limpa a memoria, etc) for(i=0; i<NUM_RUAS; i++) al_destroy_bitmap(buses[i]); al_destroy_bitmap(bouncer); al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; }
/* emulate 'retrace_count' variable */ int64_t retrace_count() { return al_get_timer_count(retrace_counter); }
/** Returns the timer count. @return the timer count. */ int64_t getCount() const { return al_get_timer_count(get()); }
int main(int argc, char **argv) { if (!al_init()) { printf("failed to initialize allegro!\n"); return -1; } if (!al_init_image_addon()) { printf("failed to initialize image I/O addon!\n"); return -1; } if (!al_init_primitives_addon()) { printf("failed to initialize primitives addon!\n"); return -1; } ALLEGRO_DISPLAY *display = al_create_display(arena_width, arena_height); if (!display) { printf("failed to create display!\n"); return -1; } if (!al_install_keyboard()) { printf("failed to install keyboard!\n"); return -1; } bad_guy_timer = al_create_timer(ALLEGRO_BPS_TO_SECS(100)); if (!bad_guy_timer) { printf("failed to create timer!\n"); return -1; } al_start_timer(bad_guy_timer); black = al_color_name("black"); hero_x = arena_width / 4; hero_y = arena_height / 4; hero_bitmap = al_load_bitmap("hero.png"); bad_guy_x = bad_guy_starting_x; bad_guy_y = bad_guy_starting_y; bad_guy_color = al_color_name("red"); while (!al_key_down(keyboard_state, ALLEGRO_KEY_ESCAPE)) { al_get_keyboard_state(keyboard_state); while (al_get_timer_count(bad_guy_timer) > bad_guy_count) { if (al_key_down(keyboard_state, ALLEGRO_KEY_LEFT) && hero_x > hero_half_size) { hero_x -= hero_speed; } if (al_key_down(keyboard_state, ALLEGRO_KEY_RIGHT) && hero_x < arena_width - hero_half_size) { hero_x += hero_speed; } if (al_key_down(keyboard_state, ALLEGRO_KEY_UP) && hero_y > hero_half_size) { hero_y -= hero_speed; } if (al_key_down(keyboard_state, ALLEGRO_KEY_DOWN) && hero_y < arena_height - hero_half_size) { hero_y += hero_speed; } // Some trigonometry to move toward the hero double bad_guy_angle = atan2(hero_y - bad_guy_y, hero_x - bad_guy_x); bad_guy_x += bad_guy_speed * cos(bad_guy_angle); bad_guy_y += bad_guy_speed * sin(bad_guy_angle); bad_guy_speed += bad_guy_acceleration; // Reset bad guy when he hits the hero if (abs(hero_x - bad_guy_x) < bad_guy_half_size && abs(hero_y - bad_guy_y) < bad_guy_half_size) { bad_guy_x = bad_guy_starting_x; bad_guy_y = bad_guy_starting_y; bad_guy_speed = bad_guy_starting_speed; } al_add_timer_count(bad_guy_timer, -1); } al_clear_to_color(black); al_draw_bitmap(hero_bitmap, hero_x - hero_half_size, hero_y - hero_half_size, 0); al_draw_filled_circle(bad_guy_x, bad_guy_y, bad_guy_half_size, bad_guy_color); al_flip_display(); } return 0; }
/* the main game function */ static int play_game() { ALLEGRO_TIMER *inc_counter; int gameover = 0; int cyclenum = 0; /* init */ score = 0; init_view(); init_player(); init_badguys(); init_bullets(); init_explode(); init_message(); #define TIMER_SPEED ALLEGRO_BPS_TO_SECS(30*(cyclenum+2)) inc_counter = al_create_timer(TIMER_SPEED); al_start_timer(inc_counter); while (!gameover) { /* move everyone */ while ((al_get_timer_count(inc_counter) > 0) && (!gameover)) { update_view(); update_bullets(); update_explode(); update_message(); if (update_badguys()) { if (advance_view()) { cyclenum++; al_set_timer_count(inc_counter, 0); lay_attack_wave(TRUE); advance_player(TRUE); } else { lay_attack_wave(FALSE); advance_player(FALSE); } } gameover = update_player(); al_set_timer_count(inc_counter, al_get_timer_count(inc_counter)-1); } /* take a screenshot? */ if (key[ALLEGRO_KEY_PRINTSCREEN]) { static int ss_count = 0; char fname[80]; sprintf(fname, "speed%03d.tga", ++ss_count); al_save_bitmap(fname, al_get_backbuffer(screen)); while (key[ALLEGRO_KEY_PRINTSCREEN]) poll_input_wait(); al_set_timer_count(inc_counter, 0); } /* toggle fullscreen window */ if (key[ALLEGRO_KEY_F]) { int flags = al_get_display_flags(screen); al_set_display_flag(screen, ALLEGRO_FULLSCREEN_WINDOW, !(flags & ALLEGRO_FULLSCREEN_WINDOW)); while (key[ALLEGRO_KEY_F]) poll_input_wait(); } /* draw everyone */ draw_view(); } /* cleanup */ al_destroy_timer(inc_counter); shutdown_view(); shutdown_player(); shutdown_badguys(); shutdown_bullets(); shutdown_explode(); shutdown_message(); if (gameover < 0) { sfx_ping(1); return FALSE; } return TRUE; }
int main(void) { //Initialize allegro-------------------------------- if (InitAllegro()) { return -1; } srand(time(NULL)); //variables----------------------------------------- const int FPS = 60;//how many frames the game should run at bool StartScreen = true; //start screen while loop bool bool QuitGame = false; int NumberOfAI = 30; //Allegro variables--------------------------------- ALLEGRO_EVENT_QUEUE *Event_Queue = NULL; ALLEGRO_TIMER *Timer = NULL; Event_Queue = al_create_event_queue(); Timer = al_create_timer(1.0 / FPS); Display MainDisplay(Event_Queue); if (!MainDisplay.TestDisplay()) { return -1; } ALLEGRO_BITMAP *AIImage = al_load_bitmap("AI_Sprite.png"); ALLEGRO_BITMAP *StartImage = al_load_bitmap("Start_Screen.jpg"); ALLEGRO_BITMAP *GameOverImage = al_load_bitmap("GameOver_Screen.jpg"); Player MainPlayer(Event_Queue); Camera MainCamera(Event_Queue, MainDisplay.Get_ScreenWidth(), MainDisplay.Get_ScreenHeight()); AI_Group TestAIGroup(Event_Queue); // Instance of an AI_Group GUILayer MainGUILayer(MainDisplay.Get_ScreenWidth(), MainDisplay.Get_ScreenHeight()); DungeonGenerator Dungeon(Event_Queue, &MainPlayer); Dungeon.GenerateDungeon(MainDisplay); MainPlayer.SetXPosition(Dungeon.GetStartPosition().x()); MainPlayer.SetYPosition(Dungeon.GetStartPosition().y()); TestAIGroup.RandomSetup(NumberOfAI, Dungeon); // Generates AI with random attributes in the group. Their spawn points will also be set randomly. al_register_event_source(Event_Queue, al_get_timer_event_source(Timer)); al_register_event_source(Event_Queue, al_get_keyboard_event_source()); al_register_event_source(Event_Queue, al_get_mouse_event_source()); al_start_timer(Timer); //Main game loop------------------------------------ while (!QuitGame) { while (StartScreen) { //allegro event and queue ALLEGRO_EVENT ev; al_wait_for_event(Event_Queue, &ev); //if space pressed end start screen if (ev.keyboard.keycode == ALLEGRO_KEY_SPACE) { StartScreen = false; al_add_timer_count(Timer, al_get_timer_count(Timer) * -1); } if (al_is_event_queue_empty(Event_Queue)) { //draw title image al_draw_bitmap(StartImage, 0, 0, NULL); //Draw display last MainDisplay.Draw(); } } ALLEGRO_EVENT ev; al_wait_for_event(Event_Queue, &ev); Dungeon.Event_Handler(ev); TestAIGroup.EventHandler(ev); TestAIGroup.ProcessAll(ev, MainPlayer); // Process each AI in the group MainPlayer.EventHandler(ev, MainCamera.GetMouseXWorldCoordinate(), MainCamera.GetMouseYWorldCoordinate()); MainCamera.EventHandler(ev, MainPlayer.GetXPosition(), MainPlayer.GetYPosition()); if (MainDisplay.Event_Handler(ev)) QuitGame = true; //Current Dungeon complete move on to the next one if (ev.type == DUNGEON_COMPLETE_EVENT) { al_stop_timer(Timer); //Pause the timer while all the new level loads Dungeon.GenerateDungeon(MainDisplay); TestAIGroup.RandomSetup(30, Dungeon); MainPlayer.SetXPosition(Dungeon.GetStartPosition().x()); MainPlayer.SetYPosition(Dungeon.GetStartPosition().y()); MainPlayer.ScaleGameUp(Dungeon.Get_DungeonLevel()); al_start_timer(Timer); //resume the timer after the new level loads } // Collide with AI if (TestAIGroup.CollideWithAI(MainPlayer.GetCollisionXBoundOne(), MainPlayer.GetCollisionYBoundOne())) MainPlayer.MovementCollidingBoundOne(); if (TestAIGroup.CollideWithAI(MainPlayer.GetCollisionXBoundTwo(), MainPlayer.GetCollisionYBoundTwo())) MainPlayer.MovementCollidingBoundTwo(); // Hit the AI TestAIGroup.HitAI(MainPlayer.GetWeaponHitBoxXBoundOne(), MainPlayer.GetWeaponHitBoxYBoundOne(), MainPlayer.GetWeaponDamage()); TestAIGroup.HitAI(MainPlayer.GetWeaponHitBoxXBoundTwo(), MainPlayer.GetWeaponHitBoxYBoundTwo(), MainPlayer.GetWeaponDamage()); if (Dungeon.Get_Map()->CheckMapCollision(Vec2f(MainPlayer.GetCollisionXBoundOne(), MainPlayer.GetCollisionYBoundOne()))) MainPlayer.MovementCollidingBoundOne(); if (Dungeon.Get_Map()->CheckMapCollision(Vec2f(MainPlayer.GetCollisionXBoundTwo(), MainPlayer.GetCollisionYBoundTwo()))) MainPlayer.MovementCollidingBoundTwo(); if (MainPlayer.IsDead()) { MainCamera.ResetTranslate(); bool GameOverScreen = true; //bool for game over screen sequence int PlayerFinalScore = MainPlayer.GetFinalTimedScore(Timer); while (GameOverScreen) { //allegro event and queue ALLEGRO_EVENT ev; al_wait_for_event(Event_Queue, &ev); //if space pressed end start screen if (ev.keyboard.keycode == ALLEGRO_KEY_ENTER) { StartScreen = true; GameOverScreen = false; } else if (ev.keyboard.keycode == ALLEGRO_KEY_SPACE) { GameOverScreen = false; } if (al_is_event_queue_empty(Event_Queue)) { //draw title image al_draw_bitmap(GameOverImage, 0, 0, NULL); MainGUILayer.DrawFinalScoreScreen(PlayerFinalScore); //Draw display last MainDisplay.Draw(); } } MainPlayer.ResetPlayer(); Dungeon.Set_DungeonLevel(1); Dungeon.GenerateDungeon(MainDisplay); TestAIGroup.RandomSetup(NumberOfAI += Random(2,5), Dungeon); MainPlayer.SetXPosition(Dungeon.GetStartPosition().x()); MainPlayer.SetYPosition(Dungeon.GetStartPosition().y()); MainPlayer.ScaleGameUp(Dungeon.Get_DungeonLevel()); al_add_timer_count(Timer, al_get_timer_count(Timer) * -1); } //Code Dealing with drawing to the screen goes within this if statement if (al_is_event_queue_empty(Event_Queue)) { Dungeon.Draw(1); //Draw the bottom layers of the dungeon MainPlayer.DrawPlayer(); //Draw the player TestAIGroup.DrawAll(); // Draw all AI. Dungeon.Draw(0); //Draw the top layers of the dungeon MainGUILayer.DrawPlayerInformation(MainCamera, MainPlayer.GetCurrentLevel(), MainPlayer.GetCurrentHealth()); MainGUILayer.DrawScoreInformation(MainCamera, MainPlayer.GetCurrentScore()); MainGUILayer.DrawGameTimeInformation(MainCamera, Timer); //Draw display last MainDisplay.Draw(); } } //Game Ending-------------------------------------- return 0; }