void scene_map(World * w) { //pre scene routine while (scene == scene_map) { game_update(w); } //post scene routine }
// Engine ---------------------------------------------------------------------- // ----------------------------------------------------------------------------- int engine_create(const int width, const int height, const int scale, const int fps) { engine = (struct Engine*)malloc(sizeof(struct Engine)); if (!engine_init(width, height, scale, fps)) { free(engine); return 1; } game_init(); // Main Loop, o'rly? int render_start = 0, render_diff = 0, render_wait = 0; int fps_count = 0, fps_time = 0; while (engine->running) { render_start = SDL_GetTicks(); engine_events(); if (key_pressed(SDLK_p)) { engine_pause(!engine->paused); } if (!engine->paused) { game_update(); } engine_clear_keys(); engine_clear_mouse(); game_render(engine->screen); SDL_Flip(engine->screen->bg); // Limit FPS render_diff = SDL_GetTicks() - render_start; if (render_diff > 0) { render_wait = engine->fps_wait - render_diff; if (render_wait > 0) { SDL_Delay(render_wait); } if (!engine->paused) { engine->time += SDL_GetTicks() - render_start; } } // Count FPS if (!engine->paused) { fps_count++; if (fps_count >= 10) { engine->fps_current = 1000 / ((engine->time - fps_time) / fps_count); fps_count = 0; fps_time = engine->time; } } } // Cleanup game_quit(); engine_cleanup(); return 0; }
int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } // closing... // Deallocate textures texture_free(&g_up_texture); texture_free(&g_down_texture); texture_free(&g_left_texture); texture_free(&g_right_texture); texture_free(&g_press_texture); SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
enum state wiimote_send_event(enum state state, struct game* game, SDLKey key, key_event_t key_event) { switch (state) { case GAME: assert(game); return(game_update(state, game, key, key_event)); break; default: break; } return(menu_update(state, key, key_event)); }
/* update local objects (shrapnells,extras,explosions...) and communicate * every client_comm_delay seconds either with real or fake server */ static void update_game( int ms ) { int i; /* run the fake server game */ if ( game->game_type == GT_LOCAL ) { game_set_current( local_game ); game_update( ms ); game_set_current( game ); } /* local animations and movements */ for ( i = 0; i < game->paddle_count; i++ ) client_paddle_update( game->paddles[i], ms ); client_shots_update( ms ); client_balls_update( ms ); client_extras_update( ms ); client_walls_update( ms ); shrapnells_update( ms ); frame_warp_icon_update( ms ); shine_update( ms ); exps_update( ms ); displays_update( ms ); credit_update( ms ); /* communicate */ if ( (no_comm_since+=ms) >= client_comm_delay ) { no_comm_since -= client_comm_delay; /* send paddle state */ comm_send_paddle( l_paddle ); /* receive game data from local or remote server and * apply it to the game context. */ comm_recv(); /* update score displays */ if (!showing_best) display_set_value( display_score[0], game->paddles[0]->player->stats.total_score + game->paddles[0]->score ); if ( game->game_type == GT_NETWORK ) display_set_value( display_score[1], game->paddles[1]->player->stats.total_score + game->paddles[1]->score ); /* update bonus level information */ if (bl_display) update_bonus_level_display(); } }
void Engine::Update() { static Timer timedUpdate; //calculate core framerate p_frameCount_core++; if (p_coreTimer.stopwatch(999)) { p_frameRate_core = p_frameCount_core; p_frameCount_core = 0; } //update input devices p_input->Update(); this->UpdateKeyboard(); this->UpdateMouse(); //fast update with no timing game_update(); //update with 60fps timing if (!timedUpdate.stopwatch(14)) { if (!this->getMaximizeProcessor()) { Sleep(1); } } else { //calculate real framerate p_frameCount_real++; if (p_realTimer.stopwatch(999)) { p_frameRate_real = p_frameCount_real; p_frameCount_real = 0; } //begin rendering this->RenderStart(); //let game do it's own 3D this->SetIdentity(); game_render3d(); //2D rendering Render2D_Start(); game_render2d(); Render2D_Stop(); //done rendering this->RenderStop(); } }
void main(void){ appInit(); initGame(); //#ifndef SIMULATOR graphic_initialize(); //#endif while(!game_finished){ controls(); game_update(); graphic_render(); difficulty(); //delay_milli(50); } }
int main() { int i; game_init(); lvl_create_menu(); lvl_create_lvl1(); game_init_player(); while (1) { game_update(); } return 0; }
void retro_run(void) { key_state_t ks; input_poll_cb(); ks.up = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP); ks.right = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT); ks.down = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN); ks.left = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT); ks.start = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START); ks.select = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT); game_update(frame_time, &ks); game_render(); }
bool game_init(game_t * game, const char fen[]) { ASSERT(game!=NULL); ASSERT(fen!=NULL); if (!board_from_fen(game->start_board,fen)) return false; game->size = 0; board_copy(game->board,game->start_board); game->pos = 0; game_update(game); return true; }
int dgreed_main(int argc, const char** argv) { params_init(argc, argv); rand_init(time(NULL)); layouts_init(); layouts_set("dvorak"); bool fullscreen = true; if(params_find("-windowed") != ~0) fullscreen = false; video_init_ex(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, "KeyMingler", fullscreen); font = font_load(FONT_FILE); float text_width = font_width(font, LOADING_TEXT); float text_height = font_height(font); Vector2 pos = vec2((SCREEN_WIDTH - text_width) / 2.0f, (SCREEN_HEIGHT - text_height) / 2.0f); font_draw(font, LOADING_TEXT, 0, &pos, COLOR_WHITE); video_present(); system_update(); game_init(); sounds_init(); music = sound_load_stream(MUSIC_FILE); sound_play(music); while(system_update()) { game_update(); game_render(); video_present(); sound_update(); if(key_up(KEY_QUIT)) break; } font_free(font); sound_free(music); sounds_close(); game_close(); video_close(); layouts_close(); return 0; }
void engine_update() { // do smth here // update tweens list_t* it = tweens; list_t* safe; while (it) { safe = it->next; tween_update((tween*)(it->value)); it = safe; } game_update(); }
/* This function ask a moves, save it, apply it and return 0 if the game is finish (won or tie) */ int next_move(struct game *myGame){ struct move currMove; /* this is need for game_state_transtiction */ // struct state s1; printf("Player: %c\n", myGame->players[myGame->current_player]); /* continue to ask until the move is correct */ while(!move_is_valid(myGame, &currMove)); game_update(myGame, &currMove); // game_state_transition(&myGame->state, &currMove, &s1, myGame); /* update the moves history */ // TODO this can be used as history replay mode // if(update_moves(&currMove) !=0) // return 1; /* print the table */ game_print(myGame); /* check if there is a winner or it is tie */ return is_finish(myGame, &currMove); }
void game_goto(game_t * game, int pos) { int i; ASSERT(game!=NULL); ASSERT(pos>=0&&pos<=game->size); if (pos < game->pos) { // going backward => replay the whole game board_copy(game->board,game->start_board); game->pos = 0; } for (i = game->pos; i < pos; i++) move_do(game->board,game->move[i]); ASSERT(i==pos); game->pos = pos; game_update(game); }
void Apep::run(){ assert("You must initialize engine before run!" && back_buffer != nullptr); clean_screen(); if (!game_setup()) return; while (game_update()) { while (_kbhit()) key(_getch()); game_draw(); flush(); Sleep(10); } game_cleanup(); }
void game_add_move(game_t * game, int move) { ASSERT(game!=NULL); ASSERT(move_is_ok(move)); ASSERT(move_is_legal(move,game->board)); if (game->pos >= GameSize) my_fatal("game_add_move(): game overflow\n"); game->move[game->pos] = move; game->key[game->pos] = game->board->key; move_do(game->board,move); game->pos++; game->size = game->pos; // truncate game, HACK: before calling game_is_ok() in game_update() game_update(game); }
int main(int argc, char *argv[]) { struct game* game = game_new(); window_create(SIZE_BLOC * MAP_WIDTH, SIZE_BLOC * MAP_HEIGHT + BANNER_HEIGHT + LINE_HEIGHT); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // to obtain the DEFAULT_GAME_FPS, we have to reach a loop duration of (1000 / DEFAULT_GAME_FPS) ms int ideal_speed = 1000 / DEFAULT_GAME_FPS; int timer, execution_speed; // game loop // fixed time rate implementation int done = menu_display(game); while (!done) { timer = SDL_GetTicks(); done = game_update(game); game_display(game); if ( player_get_dead(game_get_player(game))) { // Reset the game if the player is dead game_free(game); game=game_new(); } if(game_get_win(game) == 1) done=1; execution_speed = SDL_GetTicks() - timer; if (execution_speed < ideal_speed) SDL_Delay(ideal_speed - execution_speed); // we are ahead of ideal time. let's wait. } window_free(); game_free(game); SDL_Quit(); return EXIT_SUCCESS; }
/** Main entry point for the game. I kept it as simple as I could. */ int main(int argc, char* argv[]) { global = new_globals(); config_handle(); args_handle(argc, argv); engine_init(); atexit(engine_exit); /* no need to call it when quitting */ game_s game = new_game(); engine_draw(&game); while (!game.quit) { int c = engine_get_input(game.speed); game_handle_input(&game, c); game_update(&game); /* THIS WILL BE UNCOMMENTED SOON */ /* if (game.show_help) */ /* { */ /* engine_draw_help(); */ /* engine_wait_for_keypress(); */ /* game.show_help = false; */ /* } */ if (game.is_over) { game_over(&game); engine_draw_gameover(&game); engine_wait_for_keypress(); game = new_game(); } engine_draw(&game); } return EXIT_SUCCESS; }
void Game::update(){ //std::cout<<"Game::update() 1"<<std::endl; input->update(); handle_game_signal(); //std::cout<<"Game::update() 2"<<std::endl; //===========game update=============== game_update(); Scene* cur_scene=get_cur_scene(); //std::cout<<"Game::update() cur_scene="<<cur_scene->scene_name()<<std::endl; //===============system pre_update======================= //std::cout<<"Game::update() controller_system->pre_update()"<<std::endl; controller_system->pre_update(); //std::cout<<"Game::update() controller_system->pre_update() end"<<std::endl; //===============scene_update()====================== //std::cout<<"Game::update() cur_scene="<<cur_scene->scene_name()<<std::endl; cur_scene->update(); //std::cout<<"Game::update() cur_scene->update() end"<<std::endl; //===========system update============= controller_system->update(); //std::cout<<"Game::update() controller_system->update() end"<<std::endl; //===========update end================ cur_scene->scene_update_end(); //===========draw start================ //std::cout<<"Game::update() cur_scene->draw_scene(); start"<<std::endl; cur_scene->draw_scene(); //std::cout<<"Game::update() cur_scene->draw_scene(); end"<<std::endl; //===========render start============== //std::cout<<"Game::update() renderer->render() start"<<std::endl; renderer->render(); //std::cout<<"Game::update() renderer->render() end"<<std::endl; //===========wait for render end======= //render_thread->join(); draw->clear_tmp_data(); //std::cout<<"Game::update() draw->clear_tmp_data()"<<std::endl; swap_buffer();//swap screen buffer //std::cout<<"Game::update() end"<<std::endl; }
void Engine::Update() { static Timer timedUpdate; //calculate core framerate p_frameCount_core++; if (p_coreTimer.stopwatch(999)) { p_frameRate_core = p_frameCount_core; p_frameCount_core = 0; } //fast update with no timing game_update(); //update with 60fps timing if (!timedUpdate.stopwatch(14)) { if (!this->getMaximizeProcessor()) { Sleep(1); } } else { //calculate real framerate p_frameCount_real++; if (p_realTimer.stopwatch(999)) { p_frameRate_real = p_frameCount_real; p_frameCount_real = 0; } //begin rendering this->RenderStart(); //done rendering this->RenderStop(); } }
int main(void) { physics_init(LCD_WIDTH, LCD_HEIGHT); input_init(); display_init(); segment_init(); players_init(); playerA = players_get(0); playerB = players_get(1); ball = physics_create(LCD_WIDTH / 2, LCD_HEIGHT / 2, BALL_RADIUS, BALL_MASS); for (;;) { input_update(); players_update(0.01f); physics_update(0.01f); game_update(); game_draw(); } return 0; }
void Engine::Update() { //calculate core framerate p_frameCount_core++; if (p_coreTimer.stopwatch(999)) { p_frameRate_core = p_frameCount_core; p_frameCount_core = 0; } //fast update with no timing game_update(); //update entities if (!p_pauseMode) UpdateEntities(); //perform global collision testing at 20 Hz if (!p_pauseMode && collisionTimer.stopwatch(50)) { TestForCollisions(); } //update with 60fps timing if (!timedUpdate.stopwatch(14)) { if (!this->getMaximizeProcessor()) { Sleep(1); } } else { //calculate real framerate p_frameCount_real++; if (p_realTimer.stopwatch(999)) { p_frameRate_real = p_frameCount_real; p_frameCount_real = 0; } //update input devices p_input->Update(); this->UpdateKeyboard(); this->UpdateMouse(); //update audio system audio->Update(); //begin rendering this->RenderStart(); //call game 3d rendering game_render3d(); //render 3D entities if (!p_pauseMode) Draw3DEntities(); //begin 2d rendering Render2D_Start(); //render 2D entities if (!p_pauseMode) Draw2DEntities(); //let game do 2d rendering game_render2d(); //done with 2d rendering Render2D_Stop(); //done rendering this->RenderStop(); } //remove dead entities from the list BuryEntities(); }
// the main game loop which will run until the game is done void game_loop() { SDL_Event event, e; SDL_TimerID timer; int last_game_update = 0; int last_particle_update = 0; int last_render = 0; int previous_level = 0; debug_print("Loading media..."); load_media(); // check if we want to show score increments game.show_score_increments = atoi(config_getValue("show_score_increments")); // setup input input_init(); // create & show menu ui_menuInit(); ui_toggleMenuVisible(); SDL_SetEventFilter(ui_handleEvents); // loop forever debug_print("Entering main game loop..."); while (1) { // see if its time to trigger an update (make sure we're not paused either) if (!game.paused && SDL_GetTicks() - last_game_update > game_getGameUpdateFreq()) { last_game_update = SDL_GetTicks(); // remember time of last update game_update(); } if (game.show_score_increments) { // at the moment we just have the one particle set // see if its time to trigger a particle update if (SDL_GetTicks() - last_particle_update > PARTICLE_UPDATE_INTERVAL) { last_particle_update = SDL_GetTicks(); particle_update(); } } // check for any events waiting while (SDL_PollEvent(&event)) { switch(event.type) { // key presses are handled in input.c case SDL_KEYDOWN: input_onKeyDown(event.key.keysym.sym); break; case LEFT_KEY: tetromino_moveLeft(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveRight(current_tetromino); } break; case RIGHT_KEY: tetromino_moveRight(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveLeft(current_tetromino); } break; case DOWN_KEY: // uses the key repeat interval to accelerate the tetromino down tetromino_moveDown(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveUp(current_tetromino); } break; case UP_KEY: // rotate to a new position tetromino_setNextPosition(current_tetromino); tetromino_setShape(current_tetromino, current_tetromino->type, current_tetromino->position); // make sure the new position doesn't cause any collisions // if it does, reverse the rotation if (grid_checkCollision(grid, current_tetromino)) { tetromino_setPrevPosition(current_tetromino); tetromino_setShape(current_tetromino, current_tetromino->type, current_tetromino->position); } break; case SPACE_KEY: tetromino_moveDown(current_tetromino); // move the tetromino down until it causes a collision while (!grid_checkCollision(grid, current_tetromino)) { tetromino_moveDown(current_tetromino); } // once we have a collision, move it back into place tetromino_moveUp(current_tetromino); break; case PAUSE_KEY: debug_print("Pausing game"); game.paused = !game.paused; // stop the game timer if (game.paused) { SDL_RemoveTimer(timer); timer = NULL; } else { // start it again timer = SDL_AddTimer(1000, game_updateTime, NULL); } break; case ESCAPE_KEY: // pause game updates debug_print("Escape key pressed."); // toggle paused game state if we're in game if (grid && current_tetromino) { game.paused = !game.paused; if (game.paused) { // stop couting time played SDL_RemoveTimer(timer); timer = NULL; } // starting timer again, only if we're still in a game else if (grid && current_tetromino) { timer = SDL_AddTimer(1000, game_updateTime, NULL); } } // show or hide the menu if (grid && current_tetromino) { ui_toggleMenuVisible(); } // enable ui message pump if its visible if (ui_isMenuVisible()) { // if we're in game, show in-game menu if (grid && current_tetromino) { ui_menuPageSetCurrentById(MENU_IN_GAME); } // otherwise show main menu else { ui_menuPageSetCurrentById(MENU_MAIN); } SDL_SetEventFilter(ui_handleEvents); } break; case GAME_START_NEW: // set some game variables game.level = 0; game.score = 0; game.lines = 0; game.paused = 0; // time variables game.hours = 0; game.minutes = 0; game.seconds = 0; // create the grid grid = grid_createNew(GRID_WIDTH, GRID_HEIGHT); // create the first tetromino current_tetromino = tetromino_createNew(); current_tetromino->x = 0; current_tetromino->y = 0; // update time SDL_Init(SDL_INIT_TIMER); if (timer) { SDL_RemoveTimer(timer); timer = NULL; } ui_toggleMenuVisible(); timer = SDL_AddTimer(1000, game_updateTime, NULL); game.paused = 0; break; case GAME_END: // called by either the menu or game over scenario // destroy timer, grid and tetromino SDL_RemoveTimer(timer); timer = NULL; grid_destroy(grid); grid = NULL; tetromino_destroy(current_tetromino); current_tetromino = NULL; // show menu if it isn't already visible ui_menuPageSetCurrentById(MENU_MAIN); if (!ui_isMenuVisible()) { SDL_SetEventFilter(ui_handleEvents); ui_toggleMenuVisible(); } break; case TETROMINO_CREATE: // assumes that the old one has already been discarded current_tetromino = tetromino_createNew(); current_tetromino->x = 0; current_tetromino->y = 0; // check if we have an immediate collision (game over) if (grid_checkCollision(grid, current_tetromino)) { SDL_RemoveTimer(timer); timer = NULL; e.type = GAME_END; SDL_PushEvent(&e); } break; case GRID_REMOVE_LINE: if (game.show_score_increments) { // animated score increment game_showScoreIncrement(event.user.code, (game.level + 1) * 10); } grid_removeLine(grid, event.user.code); // increment number of complete lines game.lines += 1; // +10 per block and x10 per level game.score += (game.level + 1) * 10 * GRID_WIDTH; // increment the game level every 10 lines previous_level = game.level; game.level = game.lines / 10; if (previous_level != game.level) { game_showLevelIncrement(); } break; case GAME_QUIT: SDL_RemoveTimer(timer); // stop gameplay timer timer = NULL; game_shutdown(); break; // unhandled events are ignored default: break; } } // update the display // without this delay gfx card tries to commit suicide by melting if (SDL_GetTicks() - last_render > 3) { display_update(); last_render= SDL_GetTicks(); } } }
//------------------------------------------------------------ // La función principal main() //------------------------------------------------------------ int main(int argc, char **argv) { // Iniciar Allegro (y añadidos) al_init(); al_init_image_addon(); al_init_primitives_addon(); // Instalar el mouse, teclado, etc. al_install_keyboard(); al_install_mouse(); if (FULLSCREEN) al_set_new_display_flags(ALLEGRO_FULLSCREEN); // Crear el "display" display = al_create_display(SCREEN_W, SCREEN_H); if (!SHOW_CURSOR) al_hide_mouse_cursor(display); // Poner el título de la ventana al_set_window_title(display, WINDOW_TITLE); // Creamos el timer (controlador de FPS) timer = al_create_timer(1.0 / FRAMERATE); // Creamos la 'pila' de eventos event_queue = al_create_event_queue(); // Preparamos el juego game_setup(); // Los eventos que usaremos al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_start_timer(timer); // Si esta variable se pone a 0, el juego terminará de inmediato game_is_running = 1; ALLEGRO_EVENT event; // El 'loop' principal del juego while (game_is_running) { al_wait_for_event(event_queue, &event); // Si el botón para cerrar fue presionado... if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) break; // Actualizamos las teclas if (event.type == ALLEGRO_EVENT_KEY_DOWN) { // Al presionar <Esc> el juego terminará if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) game_is_running = 0; if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) key[KEY_LEFT] = 1; if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) key[KEY_RIGHT] = 1; if (event.keyboard.keycode == ALLEGRO_KEY_UP) key[KEY_UP] = 1; if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) key[KEY_DOWN] = 1; if (event.keyboard.keycode == ALLEGRO_KEY_X) key[KEY_X] = 1; } // Actualizamos las teclas if (event.type == ALLEGRO_EVENT_KEY_UP) { if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) key[KEY_LEFT] = 0; if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) key[KEY_RIGHT] = 0; if (event.keyboard.keycode == ALLEGRO_KEY_UP) key[KEY_UP] = 0; if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) key[KEY_DOWN] = 0; if (event.keyboard.keycode == ALLEGRO_KEY_X) key[KEY_X] = 0; } if (event.type == ALLEGRO_EVENT_TIMER) { game_update(); redraw = 1; } if (redraw) { redraw = 0; al_clear_to_color(al_map_rgb(0, 0, 0)); game_render(); al_flip_display(); } } al_destroy_display(display); al_destroy_timer(timer); al_destroy_event_queue(event_queue); game_shutdown(); return 0; }
// entry point void _main(void) { // some variables for the main loop unsigned int lasttick = 0; void *keyqueue = kbd_queue(); unsigned short key; // initiate all the stuff init(); // start at the menu switchgs(GS_MENU); // main loop while (gs != GS_NONE) { // run at 20 fps if (FiftyMsecTick != lasttick) { // Check for keypresses if (!OSdequeue(&key, keyqueue)) { if (key == KEY_ON) off(); else if (key == KEY_QUIT) switchgs(GS_NONE); else { switch (gs) { case GS_MENU: if (key == KEY_ENTER) switchgs(GS_GAME); else if (key == KEY_ESC) switchgs(GS_NONE); break; case GS_GAME: if (key == KEY_ENTER) game_flap(); else if (key == KEY_ESC) switchgs(GS_MENU); break; case GS_GAMEOVER: if (key == KEY_ENTER) switchgs(GS_GAME); else if (key == KEY_ESC) switchgs(GS_MENU); break; default: break; } } } // draw to the buffers GrayClearScreen2B(lightbuffer, darkbuffer); switch (gs) { case GS_MENU: menu_update(); menu_draw(); break; case GS_GAME: game_update(); game_draw(); break; case GS_GAMEOVER: gameover_update(); game_draw(); gameover_draw(); break; default: break; } // flip the buffers FastCopyScreen(darkbuffer, darkplane); FastCopyScreen(lightbuffer, lightplane); lasttick = FiftyMsecTick; framecounter++; } } // important! deinit(); }
/* game_loop() has been turned into a SDL based loop. The code for one iteration of the original game_loop is in game_loop_iter. */ static void game_loop() { /* FPS */ int fps = 0; int fps_ema = 0; int fps_target = 25; const float ema_alpha = 0.003; int drag_button = 0; unsigned int last_down[3] = {0}; unsigned int last_click[3] = {0}; unsigned int current_ticks = SDL_GetTicks(); unsigned int accum = 0; unsigned int accum_frames = 0; SDL_Event event; gui_event_t ev; game_loop_run = 1; while (game_loop_run) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEBUTTONUP: if (drag_button == event.button.button) { ev.type = GUI_EVENT_TYPE_DRAG_END; ev.x = event.button.x; ev.y = event.button.y; ev.button = drag_button; gui_object_handle_event((gui_object_t *)&interface, &ev); drag_button = 0; } ev.type = GUI_EVENT_TYPE_BUTTON_UP; ev.x = event.button.x; ev.y = event.button.y; ev.button = event.button.button; gui_object_handle_event((gui_object_t *)&interface, &ev); if (event.button.button <= 3 && current_ticks - last_down[event.button.button-1] < MOUSE_SENSITIVITY) { ev.type = GUI_EVENT_TYPE_CLICK; ev.x = event.button.x; ev.y = event.button.y; ev.button = event.button.button; gui_object_handle_event((gui_object_t *)&interface, &ev); if (current_ticks - last_click[event.button.button-1] < MOUSE_SENSITIVITY) { ev.type = GUI_EVENT_TYPE_DBL_CLICK; ev.x = event.button.x; ev.y = event.button.y; ev.button = event.button.button; gui_object_handle_event((gui_object_t *)&interface, &ev); } last_click[event.button.button-1] = current_ticks; } break; case SDL_MOUSEBUTTONDOWN: ev.type = GUI_EVENT_TYPE_BUTTON_DOWN; ev.x = event.button.x; ev.y = event.button.y; ev.button = event.button.button; gui_object_handle_event((gui_object_t *)&interface, &ev); if (event.button.button <= 3) last_down[event.button.button-1] = current_ticks; break; case SDL_MOUSEMOTION: if (drag_button == 0) { /* Move pointer normally. */ interface_set_cursor(&interface, event.motion.x, event.motion.y); } for (int button = 1; button <= 3; button++) { if (event.motion.state & SDL_BUTTON(button)) { if (drag_button == 0) { drag_button = button; ev.type = GUI_EVENT_TYPE_DRAG_START; ev.x = event.motion.x; ev.y = event.motion.y; ev.button = drag_button; gui_object_handle_event((gui_object_t *)&interface, &ev); } ev.type = GUI_EVENT_TYPE_DRAG_MOVE; ev.x = event.motion.x; ev.y = event.motion.y; ev.button = drag_button; gui_object_handle_event((gui_object_t *)&interface, &ev); break; } } break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_CTRL)) { game_loop_quit(); break; } switch (event.key.keysym.sym) { /* Map scroll */ case SDLK_UP: { viewport_t *viewport = interface_get_top_viewport(&interface); viewport_move_by_pixels(viewport, 0, -1); } break; case SDLK_DOWN: { viewport_t *viewport = interface_get_top_viewport(&interface); viewport_move_by_pixels(viewport, 0, 1); } break; case SDLK_LEFT: { viewport_t *viewport = interface_get_top_viewport(&interface); viewport_move_by_pixels(viewport, -1, 0); } break; case SDLK_RIGHT: { viewport_t *viewport = interface_get_top_viewport(&interface); viewport_move_by_pixels(viewport, 1, 0); } break; /* Panel click shortcuts */ case SDLK_1: { panel_bar_t *panel = interface_get_panel_bar(&interface); panel_bar_activate_button(panel, 0); } break; case SDLK_2: { panel_bar_t *panel = interface_get_panel_bar(&interface); panel_bar_activate_button(panel, 1); } break; case SDLK_3: { panel_bar_t *panel = interface_get_panel_bar(&interface); panel_bar_activate_button(panel, 2); } break; case SDLK_4: { panel_bar_t *panel = interface_get_panel_bar(&interface); panel_bar_activate_button(panel, 3); } break; case SDLK_5: { panel_bar_t *panel = interface_get_panel_bar(&interface); panel_bar_activate_button(panel, 4); } break; /* Game speed */ case SDLK_PLUS: case SDLK_KP_PLUS: if (game.game_speed < 40) game.game_speed += 1; LOGI("main", "Game speed: %u", game.game_speed); break; case SDLK_MINUS: case SDLK_KP_MINUS: if (game.game_speed >= 1) game.game_speed -= 1; LOGI("main", "Game speed: %u", game.game_speed); break; case SDLK_0: game.game_speed = DEFAULT_GAME_SPEED; LOGI("main", "Game speed: %u", game.game_speed); break; case SDLK_p: if (game.game_speed == 0) game_pause(0); else game_pause(1); break; /* Audio */ case SDLK_s: sfx_enable(!sfx_is_enabled()); break; case SDLK_m: midi_enable(!midi_is_enabled()); break; /* Misc */ case SDLK_ESCAPE: if (BIT_TEST(interface.click, 7)) { /* Building road */ interface_build_road_end(&interface); } else if (interface.clkmap != 0) { interface_close_popup(&interface); } break; /* Debug */ case SDLK_g: interface.viewport.layers ^= VIEWPORT_LAYER_GRID; break; case SDLK_j: { int current = 0; for (int i = 0; i < 4; i++) { if (interface.player == game.player[i]) { current = i; break; } } for (int i = (current+1) % 4; i != current; i = (i+1) % 4) { if (PLAYER_IS_ACTIVE(game.player[i])) { interface.player = game.player[i]; LOGD("main", "Switched to player %i.", i); break; } } } break; case SDLK_z: if (event.key.keysym.mod & KMOD_CTRL) { save_game(0); } break; default: break; } break; case SDL_QUIT: game_loop_quit(); break; } } unsigned int new_ticks = SDL_GetTicks(); int delta_ticks = new_ticks - current_ticks; current_ticks = new_ticks; accum += delta_ticks; while (accum >= TICK_LENGTH) { game_update(); /* Autosave periodically */ if ((game.const_tick % AUTOSAVE_INTERVAL) == 0 && game.game_speed > 0) { int r = save_game(1); if (r < 0) LOGW("main", "Autosave failed."); } /* FPS */ fps = 1000*((float)accum_frames / accum); if (fps_ema > 0) fps_ema = ema_alpha*fps + (1-ema_alpha)*fps_ema; else if (fps > 0) fps_ema = fps; if ((game.const_tick % (10*TICKS_PER_SEC)) == 0) { LOGV("main", "FPS: %i", fps_ema); } accum -= TICK_LENGTH; accum_frames = 0; } /* Update and draw interface */ interface_update(&interface); interface.flags &= ~BIT(4); interface.flags &= ~BIT(7); gui_object_redraw((gui_object_t *)&interface, game.frame); /* TODO very crude dirty marking algortihm: mark everything. */ sdl_mark_dirty(0, 0, sdl_frame_get_width(game.frame), sdl_frame_get_height(game.frame)); /* Swap video buffers */ sdl_swap_buffers(); accum_frames += 1; /* Reduce framerate to target */ if (fps_target > 0) { int delay = 0; if (fps_ema > 0) delay = (1000/fps_target) - (1000/fps_ema); if (delay > 0) SDL_Delay(delay); } } }
void game_loop(void) { game_update(); game_draw(); if (stat == STAT_PLAYING) game_step(); }
int main() { if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK ) < 0 ) { SYS_BREAK( "SDL_Init failed!\n" ); } SDL_SetVideoMode( ScreenWidth, ScreenHeight, 0u, SDL_OPENGL /*| SDL_FULLSCREEN */ ); #ifndef FONT_EDITOR SDL_ShowCursor( SDL_DISABLE ); #endif SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1 ); SDL_AudioSpec audioSpec; audioSpec.freq = SoundSampleRate; audioSpec.format = AUDIO_S16SYS; audioSpec.channels = SoundChannelCount; audioSpec.silence = 0; audioSpec.samples = SoundBufferSampleCount; audioSpec.size = 0; audioSpec.callback = soundCallback; audioSpec.userdata = s_soundBuffer; SDL_OpenAudio( &audioSpec, NULL ); game_init(); SDL_PauseAudio( 0 ); uint32 lastTime = SDL_GetTicks(); uint32 buttonMask = 0u; uint32 joystickButtonMask = 0u; #ifndef SYS_BUILD_MASTER uint32 lastTimingTime = lastTime; uint32 timingFrameCount = 0u; #endif SDL_JoystickEventState( SDL_ENABLE ); SDL_Joystick* pJoystick0 = SDL_JoystickOpen( 0 ); SYS_USE_ARGUMENT(pJoystick0); int16 joystickAxis0 = 0; int16 joystickAxis1 = 0; float2 mousePos; float2_set(&mousePos, 0.0f, 0.0f); int leftMouseDown=0; int leftMousePressed=0; int rightMouseDown=0; int rightMousePressed=0u; int quit = 0; do { uint32 currentTime = SDL_GetTicks(); const float timeStep = ( float )( currentTime - lastTime ) / 1000.0f; lastTime = currentTime; #ifndef SYS_BUILD_MASTER if( currentTime - lastTimingTime > 500u ) { const float timingTimeSpan = ( float )( currentTime - lastTimingTime ) / 1000.0f; const float currentFps = ( float )( timingFrameCount ) / timingTimeSpan; char windowTitle[ 100u ]; sprintf( windowTitle, "fps=%f cb=%i", currentFps, s_callbackCount ); SDL_WM_SetCaption( windowTitle, 0 ); lastTimingTime = currentTime; timingFrameCount = 0u; } #endif // get local user input: SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_JOYAXISMOTION: if( event.jaxis.axis == 0u ) { joystickAxis0 = event.jaxis.value; } else if( event.jaxis.axis == 1u ) { joystickAxis1 = event.jaxis.value; } break; case SDL_JOYBUTTONDOWN: if( event.jbutton.button == 0 ) { updateButtonMask( &joystickButtonMask, ButtonMask_PlaceBomb, 1 ); } break; case SDL_JOYBUTTONUP: if( event.jbutton.button == 0 ) { updateButtonMask( &joystickButtonMask, ButtonMask_PlaceBomb, 0 ); } break; case SDL_MOUSEMOTION: float2_set(&mousePos, (float)event.motion.x, (float)event.motion.y); break; case SDL_MOUSEBUTTONDOWN: SYS_TRACE_DEBUG("down=%i\n", event.button.button); if( event.button.button == 1 ) { leftMouseDown = 1; leftMousePressed = 1; } else if( event.button.button == 3) { rightMouseDown = 1; rightMousePressed = 1; } break; case SDL_MOUSEBUTTONUP: if(event.button.button == 1) { leftMouseDown = 0; } else if(event.button.button == 3) { rightMouseDown = 0; } break; case SDL_KEYDOWN: case SDL_KEYUP: { const int ctrlPressed = ( event.key.keysym.mod & KMOD_CTRL ) != 0; switch( event.key.keysym.sym ) { case SDLK_ESCAPE: quit = 1; break; case SDLK_LEFT: updateButtonMask( &buttonMask, ctrlPressed ? ButtonMask_CtrlLeft : ButtonMask_Left, event.type == SDL_KEYDOWN ); break; case SDLK_RIGHT: updateButtonMask( &buttonMask, ctrlPressed ? ButtonMask_CtrlRight : ButtonMask_Right, event.type == SDL_KEYDOWN ); break; case SDLK_UP: updateButtonMask( &buttonMask, ctrlPressed ? ButtonMask_CtrlUp : ButtonMask_Up, event.type == SDL_KEYDOWN ); break; case SDLK_DOWN: updateButtonMask( &buttonMask, ctrlPressed ? ButtonMask_CtrlDown : ButtonMask_Down, event.type == SDL_KEYDOWN ); break; case SDLK_SPACE: updateButtonMask( &buttonMask, ButtonMask_PlaceBomb, event.type == SDL_KEYDOWN ); break; case SDLK_c: updateButtonMask( &buttonMask, ButtonMask_Client, event.type == SDL_KEYDOWN ); break; case SDLK_s: updateButtonMask( &buttonMask, ButtonMask_Server, event.type == SDL_KEYDOWN ); break; case SDLK_l: updateButtonMask( &buttonMask, ButtonMask_Leave, event.type == SDL_KEYDOWN ); break; default: break; } } break; case SDL_QUIT: quit = 1; break; } } updateButtonMaskFromJoystick( &joystickButtonMask, ButtonMask_Right, joystickAxis0, 16000 ); updateButtonMaskFromJoystick( &joystickButtonMask, ButtonMask_Left, -joystickAxis0, 16000 ); updateButtonMaskFromJoystick( &joystickButtonMask, ButtonMask_Down, joystickAxis1, 3200 ); updateButtonMaskFromJoystick( &joystickButtonMask, ButtonMask_Up, -joystickAxis1, 3200 ); #ifdef FONT_EDITOR static uint currentChar = '0'; static uint dataChar = '\0'; static float2 charPoints[ 128u ]; static uint charPointCount = 0u; static uint32 lastButtonMask = 0u; static int currentPointIndex = -1; static float2 oldMousePagePos; const uint32 buttonPressMask = buttonMask & ~lastButtonMask; lastButtonMask = buttonMask; float2 mousePagePos; mousePagePos.x=64.0f*mousePos.x/(float)ScreenWidth; mousePagePos.y=36.0f+-36.0f*mousePos.y/(float)ScreenHeight; if( buttonPressMask & ButtonMask_Right ) { currentChar=font_getNextGlyphCharCode(currentChar,1); } if( buttonPressMask & ButtonMask_Left ) { currentChar=font_getNextGlyphCharCode(currentChar,-1); } if( currentChar != dataChar ) { if( dataChar != '\0' ) { char filename[128u]; sprintf(filename,"./source/font/char_%i.h",dataChar); SYS_TRACE_DEBUG("writing char to file '%s'\n", filename); FILE* pFile=fopen(filename, "w"); if(pFile) { fprintf(pFile,"static const float2 s_points_%i[] =\n{\n",dataChar); for( uint i=0u;i<charPointCount;++i) { fprintf(pFile,"\t{%ff,%ff},\n",charPoints[i].x,charPoints[i].y); } fprintf(pFile,"};\n\n"); fclose(pFile); } else { SYS_TRACE_ERROR("Could not open file '%s'\n", filename); } } const FontGlyph* pGlyph=font_getGlyph((uint)currentChar); if(pGlyph) { charPointCount = uint_min(SYS_COUNTOF(charPoints),pGlyph->pointCount); memcpy(charPoints,pGlyph->pPoints,charPointCount*sizeof(float2)); dataChar = currentChar; } else { charPointCount = 0u; } currentPointIndex = -1; } if( dataChar && ( buttonPressMask & ButtonMask_Down ) ) { // add a point: if(charPointCount>0) { charPointCount--; } } if( dataChar && ( buttonPressMask & ButtonMask_Up ) ) { // add a point: if(charPointCount<SYS_COUNTOF(charPoints)) { float2_set(&charPoints[charPointCount],0.0f,0.0f); charPointCount++; } } if( renderer_isPageDone() ) { // new page: renderer_flipPage(); renderer_setPen( Pen_Font ); /* const float2 worldOffset = { 32.0f, 16.0f }; const float2 position = { 0.0f, 0.0f };*/ renderer_setVariance( 0.0f ); renderer_setTransform( 0 ); const float fontSize=3.0f; float2 textPos; float2_set(&textPos,32.0f,16.0f); if( charPointCount > 0u ) { float2x3 transform; float2x2_identity(&transform.rot); float2x2_scale1f(&transform.rot,&transform.rot,fontSize); transform.pos=textPos; renderer_setTransform( &transform ); renderer_addQuadraticStroke(charPoints,charPointCount); transform.pos.x -= 10.0f; renderer_setTransform( &transform ); renderer_addQuadraticStroke(charPoints,charPointCount); } // draw control points: const float cpSize=0.5f; int inRangePoint=-1; for(uint i = 0u; i < charPointCount; ++i) { float2 pos; float2_set(&pos,32.0f,16.0f); float2_addScaled1f(&pos,&pos,&charPoints[i],fontSize); const int inRange = float2_distance(&mousePagePos,&pos)<cpSize; if( inRange && inRangePoint==-1) { inRangePoint=(int)i; } if(currentPointIndex==-1&&inRange&&leftMousePressed) { currentPointIndex=(int)i; } else if(currentPointIndex!=-1) { if(!leftMouseDown) { currentPointIndex=-1; } else if( currentPointIndex==(int)i ) { // move cp to be under the mouse cursor: float2 newCpPos; float2_sub(&newCpPos,&mousePagePos,&textPos); float2_scale1f(&charPoints[i],&newCpPos,1.0f/fontSize); } } float3 color; if((int)i==currentPointIndex) { float3_set(&color,0.2f,1.0f,0.2f); } else if(inRange) { float3_set(&color,0.5f,0.5f,0.2f); } else { float3_set(&color,0.8f,0.2f,0.2f); } renderer_drawCircle(&pos,cpSize,&color); } oldMousePagePos=mousePagePos; leftMousePressed=0; rightMousePressed=0; float2_set(&textPos,5.0f,4.0f); font_drawText(&textPos,1.0f,0.0f,"0123456789A" ); } renderer_updatePage( timeStep ); FrameData frame; //memset( &frame, 0u, sizeof( frame ) ); //frame.time = s_game.gameTime; //frame.playerPos = s_game.player[ 0u ].position; renderer_drawFrame( &frame ); #elif defined( TEST_RENDERER ) if( renderer_isPageDone() ) { // new page: renderer_flipPage(); /*float2 points[] = { { -4.0f, 0.0f }, { -4.0f, -4.0f }, { 0.0f, -4.0f }, { 4.0f, -4.0f }, { 4.0f, 0.0f }, { 4.0f, 4.0f }, { 0.0f, 4.0f }, { -4.0f, 4.0f }, { -4.0f, 0.0f } { -0.2f, 1.0f } };*/ renderer_setPen( Pen_DebugGreen ); const float2 worldOffset = { 32.0f, 16.0f }; const float2 position = { 0.0f, 0.0f }; float2x3 bombTransform; float2x2_rotationY( &bombTransform.rot, 0.0f ); float2x2_scale1f( &bombTransform.rot, &bombTransform.rot, 1.0f ); float2_add( &bombTransform.pos, &position, &worldOffset ); renderer_setTransform( &bombTransform ); //renderer_addQuadraticStroke(&points[0u],&points[1u],&points[2u]); //renderer_addQuadraticStroke(points,SYS_COUNTOF(points)); float2 textPos; float2_set(&textPos,5.0f,4.0f); font_drawText(&textPos,2.0f,0.0f,"P"); } renderer_updatePage( timeStep ); FrameData frame; //memset( &frame, 0u, sizeof( frame ) ); //frame.time = s_game.gameTime; //frame.playerPos = s_game.player[ 0u ].position; renderer_drawFrame( &frame ); #else renderer_setVariance(0.0f); GameInput gameInput; memset( &gameInput, 0u, sizeof( gameInput ) ); gameInput.timeStep = timeStep; gameInput.buttonMask = buttonMask | joystickButtonMask; game_update( &gameInput ); game_render(); #endif SDL_GL_SwapBuffers(); #ifndef SYS_BUILD_MASTER timingFrameCount++; #endif } while( !quit ); // :TODO: nicer fade out.. SDL_PauseAudio( 1 ); game_done(); }
int main(int argc, char *argv[]) { float tick; /* Server defaults */ server.port = DEFAULT_PORT; server.fps = DEFAULT_FPS; server.max_clients = DEFAULT_MAXCLIENTS; server.clients = 0; server.exit_when_empty = 0; strncpy(server.name, "Chickens With Attitude", 32); /* Game defaults */ game.changelevel = 0; game.fraglimit = 0; game.timelimit = 0; game.mode = HOLYWAR; game.objective = GAME_EXIT_LEVEL; strncpy(game.map_name, "unfinished_sympathy.map", NETMSG_STRLEN); /* Command line arguments */ if( argc > 1 ) handle_cl_args(argc, argv); calc_lookup_tables(DEGREES); entity_init(); weapon_init(); /* Initilaise networking. TRY to use server.port, but return the actual port we manage to get */ if( (server.port = sv_net_init(server.port)) >= 0 ) printf("Waiting for connections on port %d\n", server.port); else { printf("Unable to initialise network. Exiting.\n"); return EXIT_FAILURE; } if( sv_map_changelevel(game.map_name, game.mode) < 0 ) { printf("Error, unable to load map\n"); return EXIT_FAILURE; } tick = 1.0 / server.fps; server.quit = 0; /* Server main loop */ while( !server.quit ) { /* printf("Press to continue.....\n"); fflush(NULL); getchar(); */ server.now = gettime(); sv_net_get_client_input(); world_update( tick ); game_update(); sv_net_send_start_frames(); /* Begin each clients frames */ sv_net_update_clients(); cap_fps(server.fps); } return EXIT_SUCCESS; }
int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_11.html if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "main: SDL_mixer Error: %s\n", Mix_GetError() ); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } /** closing **/ // Deallocate textures texture_free(&g_current_texture); // joystick // SDL_JoystickClose(g_gamepad); // g_gamepad = 0; // sfx Mix_FreeChunk( g_scratch ); Mix_FreeChunk( g_hig ); Mix_FreeChunk( g_med ); Mix_FreeChunk( g_low ); g_scratch = 0; g_hig = 0; g_med = 0; g_low = 0; // music Mix_FreeMusic( g_music ); g_music = 0; SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }