void apmotors_servo_get(struct servos *servo) { servo->valid = true; servo->servo1 = motors.motor_out[0]; servo->servo2 = motors.motor_out[1]; servo->servo3 = motors.motor_out[2]; servo->servo4 = motors.motor_out[3]; servo->time = (uint32_t)timer_get_ticks(); }
/** * Send data without buffer */ void can_send_message2(tExtendedCAN *message) { uint32_t send_ms = timer_get_ms(); while (mcp2515_send_extmessage(message) == 0) { if ((timer_get_ticks() - send_ms) > 10) return; } }
void timer_setup(timer_list_t *timer, timer_ticks_t expires, timer_ticks_t period, timer_callback_t callback, void *argument) { enter_critical_section(); timer_ticks_t now = timer_get_ticks(); timer->scheduled_expiry = now + expires; timer->period = period; timer->periods_expired = 0; timer->callback = callback; timer->argument = argument; timer_enqueue(timer, now); exit_critical_section(); }
/* * Wait the given number of ticks for an interrupt. If the timeout was too * short such that we didn't need to receive an interrupt (because our setup * time exceeded the wait time), 'interrupt_received' will be 0. Otherwise, * it will be 1. */ static void clock_pause(uint64_t ticks, int *interrupt_received) { /* Wait for the timeout. */ uint64_t time = timer_get_ticks(timer_device.ti); int already_passed = timer_timeout(timer_device.ti, time + ticks); if (already_passed) { /* If it happened while we were still setting up, just return. */ *interrupt_received = 0; return; } /* Otherwise, wait for an interrupt. */ while (!device_interrupt(timer_device.di, okn_syscall_interrupt_wait())); *interrupt_received = 1; }
/* * player_render() * player를 생성하는 함수. */ void player_render(player_t *player, v2d_t camera_position) { actor_t *act = player->actor; int i, behind_player[PLAYER_MAX_INVSTAR]; float ang; for(i=0;i<PLAYER_MAX_INVSTAR && player->invincible;i++) behind_player[i] = (int)((180*4) * timer_get_ticks()*0.001 + (i+1)*(360/PLAYER_MAX_INVSTAR)) % 360 >= 180; for(i=0;i<PLAYER_MAX_INVSTAR && player->invincible;i++) { if(behind_player[i]) actor_render(player->invstar[i], camera_position); } /* player를 생성 */ switch(physicsactor_get_movmode(player->pa)) { case MM_FLOOR: act->position.y -= 1; break; case MM_LEFTWALL: act->position.x += 3; break; case MM_RIGHTWALL: act->position.x -= 1; break; case MM_CEILING: act->position.y += 3; break; } act->angle = old_school_angle(ang = act->angle); actor_render(act, camera_position); act->angle = ang; switch(physicsactor_get_movmode(player->pa)) { case MM_FLOOR: act->position.y += 1; break; case MM_LEFTWALL: act->position.x -= 3; break; case MM_RIGHTWALL: act->position.x += 1; break; case MM_CEILING: act->position.y -= 3; break; } /* 방패를 생성 */ if(player->shield_type != SH_NONE) actor_render(player->shield, camera_position); /* 무적의 별 II */ for(i=0;i<PLAYER_MAX_INVSTAR && player->invincible;i++) { if(!behind_player[i]) actor_render(player->invstar[i], camera_position); } #ifdef SHOW_SENSORS /* 센서 */ physicsactor_render_sensors(player->pa, camera_position); #endif }
void blink(SDL_Renderer *renderer, int* lines, int line_nb, fontmap *p_fontmap){ bool done=false; timer* p_timer = timer_init(); timer_start(p_timer); //number of times the lines must blink int blink_time = 5; //number of times the lines has blinked int blink_cur = 0; //time in milliseconds of the blink speed int blink_duration = 200; //show full line or empty line char show=1; int i; while (!done){ if(timer_get_ticks(p_timer) >= blink_duration){ if(blink_cur == blink_time)done = true; else{ show = (blink_cur%2 == 0)?1:0; for(i=0;i<line_nb;i++){ memset(level+lines[i], show, sizeof(char) * LEVEL_WIDTH); } blink_cur++; p_timer->start_ticks = SDL_GetTicks(); } } //draw the level SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0, 42, 0, 255); level_draw(renderer, NULL, p_fontmap); SDL_RenderPresent(renderer); } free(p_timer); }
game_status state_game_over(SDL_Renderer* renderer, game* p_game) { bool done=false; timer* p_timer = timer_init(); timer_start(p_timer); int total=0; for(int i=0;i<3;i++)total += p_game->state[i]; while (!done) { if(timer_get_ticks(p_timer) >= 5 * 1000){ done = true; } SDL_Event event; SDL_JoystickUpdate(); while(SDL_PollEvent(&event)){ if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) || (event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 5)){ done = true; } } //print the score fontmap_printf(p_game->p_fontmap, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, renderer, "%d", p_game->score); SDL_RenderPresent(renderer); } free(p_timer); return IN_GAME; }
void main_task(void *args) { debug_uart_init(); debug_puts("\r\nTimer Test\r\n"); timer_init(); for (;;) { timer_tick_t ticks = timer_get_ticks(); debug_printf("time: %llu usec (%.3f sec)\r\n", ticks, (double)ticks / 1000000.0); uint16_t ppm[PPM_MAX_CHANNELS]; size_t len = timer_get_ppm(ppm, PPM_MAX_CHANNELS, NULL); debug_printf("ppm: "); for (int i = 0; i < len; ++i) debug_printf("%u ", ppm[i]); debug_printf("\r\n\r\n"); vTaskDelay(1000); } }
void editor(world * gameWorld) { int quit = 0; int pre_property = 0; int object_data = 1; int left_ctrl=0; int moving = 0; int old_mouse_x; int old_mouse_y; init_editor(gameWorld); object_data = mapLoad(gameWorld, MAP_FILE); //fps struct timer_t2 fps; //wait for user to continue or exit while( quit != 1 ) { //Start the frame timer timer_start(&fps); //While there are events to handle while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) { mapSave(gameWorld, MAP_FILE); //exit clean_up(); exit(0); } if(event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_LCTRL://is left ctrl being pressed? left_ctrl = 1; break; default: break; } } //set property, handle keyevents if(event.type == SDL_KEYUP) { switch(event.key.keysym.sym) { case SDLK_1: pre_property = 1; break; case SDLK_2: pre_property = 2; break; case SDLK_3: pre_property = 3; break; case SDLK_4: pre_property = 4; break; case SDLK_5: pre_property = 5; break; case SDLK_6: pre_property = 6; break; case SDLK_7: pre_property = 7; break; case SDLK_8: pre_property = 8; break; case SDLK_s: pre_property = 's'; break; case SDLK_e: pre_property = 'e'; break; case SDLK_LCTRL: left_ctrl = 0; break; case SDLK_z: if(left_ctrl == 1) { if(object_data>=2) { editor_undo(object_data,gameWorld); object_data--; } break; } else { break; } //save the map before quiting case SDLK_ESCAPE: mapSave(gameWorld, MAP_FILE); quit = 1; break; default: break; } break; } if(moving == 1) { editor_update_move_object(event.button.x, event.button.y, &old_mouse_x, &old_mouse_y,gameWorld); } if( event.type == SDL_MOUSEBUTTONDOWN) { switch(event.button.button) { case SDL_BUTTON_RIGHT: moving = 1; editor_start_move_object(event.button.x, event.button.y, &old_mouse_x, &old_mouse_y); break; } } if( event.type == SDL_MOUSEBUTTONUP) { switch(event.button.button) { case SDL_BUTTON_LEFT: editor_create_object(event.button.x, event.button.y, pre_property, &object_data,gameWorld); break; case SDL_BUTTON_RIGHT: moving = 0; break; } } } //draw editor editor_show(SCREEN_WIDTH, SCREEN_HEIGHT,gameWorld); if( timer_get_ticks(&fps) < 1000 / FRAMES_PER_SECOND ) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - timer_get_ticks(&fps) ); } } }
int main(int argc, int *argv[]) { bool quit = false; /* quit flag */ int i, j; int play_stat = 0; Timer fps; /* cap frame rate */ SDL_Event event; SDL_Surface *mouseother; SDL_Surface *wintitle[3]; SDL_Surface *screen; /* main screen */ SDL_Surface *chessboard; /* chess board */ Button pieces[CHESSBOARD_ROW][CHESSBOARD_COLUMN] = {{0}}; SDL_Surface *piece_stat_img[PIECE_STAT + 1] = {NULL}; /* pieces image */ int mouse_map[CHESSBOARD_ROW][CHESSBOARD_COLUMN] = {{0}}; /* click or not */ int pieces_map[CHESSBOARD_ROW][CHESSBOARD_COLUMN] = {{0}}; /* pieces state */ /* Init SDL lib*/ if(SDL_Init(SDL_INIT_EVERYTHING) == -1){ return 1; } /* Init screen */ screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE); if(screen == NULL){ return 1; } SDL_WM_SetCaption("XO_OX", NULL); /* Load resource */ piece_stat_img[1] = load_image("xooxres/chess1.png"); piece_stat_img[2] = load_image("xooxres/chess2.png"); piece_stat_img[3] = piece_stat_img[1]; /* for special show, but no time to do */ piece_stat_img[4] = piece_stat_img[2]; /* for special show, but no time to do */ chessboard = load_image("xooxres/chessboard.png"); mouseother = load_image("xooxres/mouseother.png"); wintitle[0] = load_image("xooxres/wintitle1.png"); wintitle[1] = load_image("xooxres/wintitle2.png"); wintitle[2] = load_image("xooxres/wintitle3.png"); /* Init timer */ timer_init(&fps); /* Init button */ for(i = 0; i < CHESSBOARD_ROW; i++){ for(j = 0; j < CHESSBOARD_COLUMN; j++){ button_init(&pieces[i][j], SUBBOARD_WIDTH * i, SUBBOARD_HEIGHT * j, SUBBOARD_WIDTH , SUBBOARD_HEIGHT ); button_set_stat_img(&pieces[i][j], BUTTON_MOUSEOVER, NULL); button_set_stat_img(&pieces[i][j], BUTTON_MOUSEOUT, mouseother); button_set_stat_img(&pieces[i][j], BUTTON_MOUSEUP, mouseother); button_set_stat_img(&pieces[i][j], BUTTON_MOUSEDOWN, mouseother); } } /* Main loop */ while(quit == false){ /* timer start */ timer_start(&fps); while(SDL_PollEvent(&event)){ /* Pieces input handle */ pieces_handle_event(pieces, mouse_map, &event); /* User quit */ if(event.type == SDL_QUIT){ quit = true; } } /* logic function */ play_stat = mouse_to_piece_map(mouse_map, pieces_map); /* show chessboard */ subchessboard_show(piece_stat_img[get_leader()], mouseother, mouse_map, screen); /* show pieces */ pieces_show(piece_stat_img, pieces_map, screen); /* */ if(play_stat != 0){ printf("play_stat = %d\n", play_stat); apply_surface((SCREEN_WIDTH - wintitle[play_stat - 1]->w) / 2, (SCREEN_HEIGHT - wintitle[play_stat - 1]->h) / 2, wintitle[play_stat - 1], screen); } /* Update screen */ if(SDL_Flip(screen) == -1){ return 1; } if(play_stat != 0){ SDL_Delay(3000); quit = true; } /* cap frame rate */ if(timer_get_ticks(&fps) < 1000 / FRAME_PER_SECOND){ SDL_Delay((1000 / FRAME_PER_SECOND) - timer_get_ticks(&fps)); } } /* Free resource */ SDL_FreeSurface(chessboard); SDL_FreeSurface(mouseother); for(i = 0; i < 2; i++){ SDL_FreeSurface(piece_stat_img[i]); } for(i = 0; i < 3; i++){ SDL_FreeSurface(wintitle[i]); } SDL_Quit(); return 0; }
void graphicsMenu(world * gameWorld, char *server_ip) { int in_menu = 1; int mouse_pressed = 0; int menu_choice = 0; //fps struct timer_t2 fps; printf("Before trying to load the menu in load manu\n"); init_draw(); //load menu if ( load_menu("menu/main_menu_background.png", "menu/play_inactiv.png", "menu/options_inactiv.png", "menu/editor_inactiv.png", "menu/exit_inactiv.png", "menu/back_inactiv.png", SCREEN_WIDTH, SCREEN_HEIGHT) == -1) { clean_up(); printf("couldn't read texture, quitting\n"); exit(-3); } load_level(); printf("After load menu\n"); //wait for user to continue or exit while( in_menu != 0 ) { //Start the frame timer timer_start(&fps); //While there are events to handle while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) { //exit clean_up(); exit(0); } if (mouse_pressed != 1) { mouse_over_menu(event.button.x, event.button.y); } if( event.type == SDL_MOUSEBUTTONDOWN) { switch(event.button.button) { case SDL_BUTTON_LEFT: mouse_pressed = mouse_down_menu(event.button.x, event.button.y); break; } } //is mousebuttom being pressed if( event.type == SDL_MOUSEBUTTONUP) { switch(event.button.button) { case SDL_BUTTON_LEFT: menu_choice = press_menu(event.button.x, event.button.y); break; } } } //draw menu drawMenu(SCREEN_WIDTH, SCREEN_HEIGHT); switch(menu_choice) { case 1: printf("quitting menu, trying to play\n"); in_menu = 0; drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT); break; case 2: menu_choice = 0; options(server_ip); break; case 3: menu_choice = 0; editor(gameWorld); break; case 4: clean_up(); exit(0); break; default: break; } if( timer_get_ticks(&fps) < 1000 / FRAMES_PER_SECOND ) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - timer_get_ticks(&fps) ); } } }
int state_in_game(SDL_Surface *screen) { SDL_Rect srcrect = {0, 0, 480, 480}; //the part of the screen to be stretched, must be sup 0 and inf screen surface Height and Width SDL_Rect dstrect = set_rect(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH); //equals screen resolution int bomb_nb=0; int flame_nb=0; bool done = false; int i=0; //generic accumulator 1 int j=0; //generic accumulator 2 int k=0; //unit accumulator int tick_count=0; int tick_trigger=0; int time_elapsed=0; //time elapsed in this round (in secondes) int last_time=0; int current_game_status=-1; timer *timer_battle = timer_init(); timer_start(timer_battle); // load sample.wav in to sample Mix_Chunk *sample = sample_load("res/boom.wav"); Mix_Music* music = music_load("res/music.xm"); music_play(music); //initialize map map *p_map = malloc(sizeof(map)); p_map->tile_height = 32; p_map->tile_width = 32; map_load_level(p_map, "res/level_01.map"); p_map->p_chipset = image_load("res/classic.png"); SDL_Surface* surface_menu = IMG_Load("./res/menu.png"); SDL_SetColorKey(surface_menu, SDL_SRCCOLORKEY, SDL_MapRGB(surface_menu->format, 255, 0, 255)); for (k=0;k<g_game.unit_nb;k++) { unit_tile_protect(g_game.v_unit+k, p_map); } int block_nb = map_block_add(p_map, g_game.block_fill, .5); ///@todo the disp % is not implemented yet int panel_nb = panel_add(g_game.v_panel, p_map, block_nb); int random_comment = rand() % 9; char sz_comment[32]; SDL_Rect pos_comment = set_rect(10, 465, 0, 0); int comment_time_elapsed; timer *timer_comment = timer_init(); //Menu TTF_Font *font_menu = font_load("res/asia.ttf", 20); TTF_Font *font_result = font_load("res/asia.ttf", 75); SDL_Rect cur_pos; cur_pos.x = 42; cur_pos.y = 425; char sz_time[10]; while (!done) { SDL_Event event; SDL_JoystickUpdate(); while(SDL_PollEvent(&event)){ for (k=0;k<g_game.unit_nb;k++) { if (!g_game.v_unit[k].is_dead) { unit_handle_key(g_game.v_unit+k, &event, k, g_game.v_bomb, p_map, &bomb_nb); } } if(event.type == SDL_QUIT || ((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_ESCAPE)) || (event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 6)){ done = true; current_game_status = MAIN_MENU; } else if((event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN)|| (event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 5)){ Mix_PauseMusic(); state_paused(screen); Mix_ResumeMusic(); } } for (k=0;k<g_game.unit_nb;k++){ if(!g_game.v_unit[k].use_keyboard){ int joystate = SDL_JoystickGetHat(g_game.v_unit[k].joystick, 0); switch (joystate){ case SDL_HAT_DOWN: unit_set_vel_y(g_game.v_unit+k, g_game.v_unit[k].speed); unit_set_vel_x(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->animation_current = DOWN; break; case SDL_HAT_UP: unit_set_vel_y(g_game.v_unit+k, -g_game.v_unit[k].speed); unit_set_vel_x(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->animation_current = UP; break; case SDL_HAT_RIGHT: unit_set_vel_x(g_game.v_unit+k, g_game.v_unit[k].speed); unit_set_vel_y(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->animation_current = RIGHT; break; case SDL_HAT_LEFT: unit_set_vel_x(g_game.v_unit+k, -g_game.v_unit[k].speed); unit_set_vel_y(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->animation_current = LEFT; break; default: if ( g_game.v_unit[k].vel_x != 0 ){ unit_set_vel_x(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->v_anim[g_game.v_unit[k].p_sprite->animation_current].frame_current = 1; } if ( g_game.v_unit[k].vel_y != 0 ){ unit_set_vel_y(g_game.v_unit+k, 0); g_game.v_unit[k].p_sprite->v_anim[g_game.v_unit[k].p_sprite->animation_current].frame_current = 1; } break; } } } tick_count = SDL_GetTicks(); if (tick_count > tick_trigger / 60){ tick_trigger = tick_count; SDL_FillRect(backbuffer, 0, SDL_MapRGB(backbuffer->format, 10, 20, 80)); //draw the map map_draw(p_map, backbuffer); for (i=0;i<panel_nb;i++) { if(p_map->pp_tile[g_game.v_panel[i]->p_sprite->y / TILE_SIZE][g_game.v_panel[i]->p_sprite->x / TILE_SIZE].type != BLOCK)panel_draw(g_game.v_panel[i], backbuffer); } //check panels for (i=0;i<panel_nb;i++) { // for all units for (k=0;k<g_game.unit_nb;k++) { //Check for bonus if (g_game.v_panel[i]->p_sprite->y / TILE_SIZE == unit_get_bounding_index_center_y(g_game.v_unit+k) && (g_game.v_panel[i]->p_sprite->x / TILE_SIZE == unit_get_bounding_index_center_x(g_game.v_unit+k))) { panel_apply(g_game.v_panel[i], g_game.v_unit+k); panel_free(g_game.v_panel[i]); panel_nb--; //Left shift the vector for (j=i;j<panel_nb;j++) { g_game.v_panel[j] = g_game.v_panel[j+1]; } } } } //Draw and update bombs for (i=0;i<bomb_nb;i++) { bomb_draw(g_game.v_bomb[i], backbuffer); anim_sprite_update_frame(g_game.v_bomb[i]->p_sprite); bomb_update_timer(g_game.v_bomb[i]); if ((g_game.v_bomb[i]->time_left <= 0) || (p_map->pp_tile[g_game.v_bomb[i]->p_sprite->y / TILE_SIZE][g_game.v_bomb[i]->p_sprite->x / TILE_SIZE].type == FLAME)) { sample_play(sample); bomb_explode(g_game.v_bomb[i], p_map, g_game.v_flame, &flame_nb); bomb_nb--; bomb_free(g_game.v_bomb[i]); //Left shift the vector for (j=i;j<bomb_nb;j++) { g_game.v_bomb[j] = g_game.v_bomb[j+1]; } } } //Check flame for (i=0;i<p_map->height;i++) { for (j=0;j<p_map->width[i];j++) { // for all units, check if hitten (if unit center is on a tile with a flame flag) for (k=0;k<g_game.unit_nb;k++) { if ((p_map->pp_tile[i][j].type == FLAME) && ((unit_get_index_x(g_game.v_unit+k) == j) && (unit_get_index_y(g_game.v_unit+k) == i)) && g_game.v_unit[k].is_dead == false) { g_game.v_unit[k].is_dead = true; timer_start(timer_comment); switch(random_comment) { case(0):sprintf(sz_comment, "Say goodbye, %s ", g_game.v_unit[k].name); break; case(1):sprintf(sz_comment, "burn %s, burn ! ", g_game.v_unit[k].name); break; case(2):sprintf(sz_comment, "%s vanished !!!!!! ", g_game.v_unit[k].name); break; case(3):sprintf(sz_comment, "unit_free(%s); //^^ ", g_game.v_unit[k].name); break; case(4):sprintf(sz_comment, "%s ? Where are you ? ", g_game.v_unit[k].name); break; case(5):sprintf(sz_comment, "%s was a good guy ", g_game.v_unit[k].name); break; case(6):sprintf(sz_comment, "HE says : \"HELLO, %s\" ", g_game.v_unit[k].name); break; case(7):sprintf(sz_comment, "%s has meet his programmer ", g_game.v_unit[k].name); break; case(8):sprintf(sz_comment, "$ %s>/dev/null ", g_game.v_unit[k].name); break; case(9):sprintf(sz_comment, "%s was not ignifugated ", g_game.v_unit[k].name); break; } } } } } //Draw and update flames for (i=0;i<flame_nb;i++) { flame_draw(g_game.v_flame[i], p_map, backbuffer); g_game.v_flame[i]->time_left--; if (g_game.v_flame[i]->time_left <= 0) { flame_free(g_game.v_flame[i], p_map); flame_nb--; //Left shift the vector for (j=i;j<flame_nb;j++) { g_game.v_flame[j] = g_game.v_flame[j+1]; } } } for (k=0;k<g_game.unit_nb;k++) { if (!g_game.v_unit[k].is_dead) { unit_calc_bounding_box(g_game.v_unit+k); unit_update(g_game.v_unit+k, p_map); } } // draw and update units unit_draw_from_z_index(g_game.v_unit, g_game.unit_nb, backbuffer); //Change every 1 second time_elapsed = timer_get_ticks (timer_battle) / 1000; if (time_elapsed != last_time){ last_time = time_elapsed; //Update current time /* Check if any unit won This function is performed every second in order to dont call it to often, and have a little delay if two or more units died almost in the same time (even ms, in the case a unit is at the left of a bomb and an other at the right, the right unit win because the flame is first put to the left...) */ int unit_win; unit_win = unit_check_victory(g_game.v_unit, g_game.unit_nb); if (unit_win >= 0) { //print win, sound, etc g_game.v_unit[unit_win].victory++; time_elapsed = 0; ///@todo set a victories limit (from 1 to 5) and display a special image if win... for the moment, another battle font_printf(font_result, TILE_SIZE * 2, TILE_SIZE * 5, 50, 150, 100, backbuffer, "%s wins", g_game.v_unit[unit_win].name); done = true; current_game_status = IN_GAME; SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect); SDL_Flip(screen); SDL_Delay(2000); break; } else if (unit_win == -1) { font_printf(font_result, (3)*TILE_SIZE, (6)*TILE_SIZE, 50, 150, 100, backbuffer, "DRAW !"); done = true; current_game_status = IN_GAME; SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect); SDL_Flip(screen); SDL_Delay(2000); } if (g_game.time - time_elapsed <= 0) { cur_pos.x = 240; cur_pos.y = 140; font_printf(font_result, (3)*TILE_SIZE, (6)*TILE_SIZE, 50, 150, 100, backbuffer, "TIMES UP !"); done = true; ///@todo select action in times up (blocks falling, etc) for the moment, just a draw... current_game_status = IN_GAME; SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect); SDL_Flip(screen); SDL_Delay(2000); } } //////////////////// MENU //////////////////// //TIME sprintf(sz_time, "%.3d", g_game.time - time_elapsed); SDL_Surface *surface_time = font_create_surface(font_menu, 200, 200, 200, 10, 100, 100, 100, 0, sz_time, SOLID); SDL_BlitSurface(surface_time, NULL, backbuffer, &cur_pos); SDL_FreeSurface(surface_time); SDL_Rect menu_src, menu_dest; menu_src.h = 32; menu_src.w = 32; menu_src.x = 0; menu_src.y = 0; menu_dest.x = 5; menu_dest.y = 420; SDL_BlitSurface(surface_menu, &menu_src, backbuffer, &menu_dest); //VICTORIES for (k=0;k<g_game.unit_nb;k++) { char sz_victory_nb[20]; SDL_Rect vic_pos = set_rect(10, 450, 0, 0); sprintf(sz_victory_nb, "%s: %d", g_game.v_unit[k].name, g_game.v_unit[k].victory); vic_pos.x += k * 100; SDL_Surface *surface_victory = font_create_surface(font_menu, 200, 200, 200, 10, 100, 100, 100, 0, sz_victory_nb, SOLID); SDL_BlitSurface(surface_victory, NULL, backbuffer, &vic_pos); SDL_FreeSurface(surface_victory); } //Comment if(timer_comment->started){ comment_time_elapsed = timer_get_ticks(timer_comment) / 1000; if (comment_time_elapsed < 3) //Display the comment 3 seconds { font_printf(font_menu, pos_comment.x, pos_comment.y, 200, 200, 200, backbuffer, sz_comment); } else{ //done timer_stop(timer_comment); random_comment = rand() % 9; } } //DEBUG #ifdef DEBUG font_printf(font_menu, 10, 10, 255, 255, 200, backbuffer, "flame nb : %d", flame_nb); font_printf(font_menu, 10, 30, 255, 255, 200, backbuffer, "bomb nb : %d", bomb_nb); font_printf(font_menu, 10, 50, 255, 255, 200, backbuffer, "unit nb : %d", g_game.unit_nb); font_printf(font_menu, 10, 70, 255, 255, 200, backbuffer, "fill nb : %.2f", g_game.block_fill); font_printf(font_menu, 10, 90, 255, 255, 200, backbuffer, "Blocks at startup : %d", block_nb); font_printf(font_menu, 10, 110, 255, 255, 200, backbuffer, "Time elapsed : %d", timer_get_ticks(timer_battle)/1000); font_printf(font_menu, 10, 130, 255, 255, 200, backbuffer, "unit 1 index: %d %d", unit_get_bounding_index_center_x(g_game.v_unit+0), unit_get_bounding_index_center_y(g_game.v_unit+0)); SDL_Rect rect = unit_get_bounding_box(g_game.v_unit+0); SDL_FillRect(backbuffer, &rect, SDL_MapRGB(backbuffer->format, 255, 255, 0)); #endif SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect); SDL_Flip(screen); }//end thick } //end while //Free the memory for (i=0;i<bomb_nb;i++) { bomb_free(g_game.v_bomb[i]); } for (i=0;i<panel_nb;i++) { panel_free(g_game.v_panel[i]); } for (i=0;i<flame_nb;i++) { flame_free(g_game.v_flame[i], p_map); } map_free(p_map); free(timer_battle); free(timer_comment); Mix_FreeChunk(sample); Mix_FreeMusic(music); TTF_CloseFont(font_menu); font_menu=NULL; // to be safe... TTF_CloseFont(font_result); font_result=NULL; // to be safe... return current_game_status; }
int main(int argc, char *argv[]) { int c = 0; unsigned char k; int opt; #ifndef WINDOWS char fname[1024]; #endif cfg_init(argv[0]); #ifdef WINDOWS if (cfg_readconfig("cgchat.cfg") < 0) { return(1); } if (cfg_read == 0) { cfg_writeconfig(default_cgchat_cfg, "cgchat.cfg"); if (cfg_readconfig("cgchat.cfg") < 0) { return(1); } } #else strncpy(fname, cfg_homedir, 1000); strcat(fname, "/.cgchatrc"); if (cfg_file_exists(fname)) { if (cfg_readconfig(fname) < 0) { return(1); } } else { strncpy(fname, cfg_prefix, 1000); strcat(fname, "/etc/cgchat.cfg"); if (cfg_readconfig(fname) < 0) { return(1); } } if (cfg_read == 0) { strncpy(fname, cfg_homedir, 1000); strcat(fname, "/.cgchatrc"); cfg_writeconfig(default_cgchat_cfg, fname); } #endif while ((opt = getopt(argc, argv, "z:k:fs48")) != -1) { switch (opt) { case '4': cfg_columns = 40; break; case '8': cfg_columns = 80; break; case 'f': cfg_fullscreen = 1; break; case 'k': cfg_keyboard = optarg; break; case 's': cfg_sound = 0; break; case 'z': if ((cfg_zoom = strtol(optarg, (char **)NULL, 10)) == 0) { usage(); return(1); } break; case 'h': default: usage(); return(1); } } argc -= optind; argv += optind; if (crc_init()) { return(1); } if (gfx_init(cfg_fullscreen, "CGChat")) { return(1); } if (kbd_init(cfg_keyboard)) { return(1); } if (kernal_init()) { return(1); } if (cfg_sound && sound_init()) { printf("Sound init failed, sound disabled\n"); } else { #ifdef WINDOWS if ((sound_bell = sound_load_sample("bell.wav")) < 0) { printf("Couldn't load bell.wav\n"); return(1); } #else strncpy(fname, cfg_prefix, 1000); strcat(fname, "/share/cgterm/bell.wav"); if ((sound_bell = sound_load_sample(fname)) < 0) { printf("Couldn't load %s\n", fname); return(1); } #endif } print_banner(cfg_columns); if (argc == 0) { if (!cfg_host) { if (cfg_columns == 80) { print(" "); } print(" \x96pRESS\x9e eSC\x96 FOR MENU\x05\x0d\x0d"); } } else if (argc == 1 || argc == 2) { if (strchr(argv[0], '.') == NULL) { printf("Invalid hostname: %s\n", argv[0]); return(1); } cfg_host = argv[0]; if (argc == 2) { cfg_port = (int)strtol(argv[1], (char **)NULL, 10); } } else { usage(); return(1); } cfg_rows = 24; chat_init(); if (cfg_host) { net_connect(cfg_host, cfg_port, &chat_print_net_status); cfg_nextreconnect = timer_get_ticks() + cfg_reconnect * 1000; } data_len = 0; data_buffer[0] = 0; for (;;) { if (timer_get_ticks() > lastvbl + 20) { if (timer_get_ticks() > lastvbl + 40) { lastvbl = timer_get_ticks(); } else { lastvbl += 20; } gfx_vbl(); } if (!net_connected() && cfg_host && cfg_reconnect && cfg_nextreconnect) { if (timer_get_ticks() > cfg_nextreconnect) { net_connect(cfg_host, cfg_port, &chat_print_net_status); cfg_nextreconnect = timer_get_ticks() + cfg_reconnect * 1000; } } k = ffe4(); c = -1; if (net_connected()) { c = net_receive(); } if (c == -2) { if (timer_get_ticks() < cfg_nextreconnect) { cfg_nextreconnect = timer_get_ticks() + cfg_reconnect * 1000; } else { cfg_nextreconnect = 0; } } if (k || c >= 0) { if (k) { chat_inputkey(k); } if (c >= 0) { if (data_len == data_maxlen) { chat_print_msg("locl:lINEBUFFER FULL"); data_len = 0; } if (c == 13) { if (data_len) { chat_print_msg(data_buffer); data_len = 0; } } else { data_buffer[data_len++] = c; data_buffer[data_len] = 0; } } } else { timer_delay(1); } } }
int main( int argc, char *argv[] ) { int quit = 0; //Initialize if( init() == 0 ) return 1; SDL_Event event; struct square_t red_square; square_set_xy (&red_square, 100, 100); square_set_destination (&red_square, 100, 100); square_set_velocity (&red_square,0,0); square_set_rgb (&red_square, 1, 0, 0); struct square_t blue_square; square_set_xy (&blue_square, 200, 100); square_set_destination (&blue_square, 200, 100); square_set_velocity(&blue_square, 0, 0); square_set_rgb(&blue_square, 0, 0, 1); //The frame rate regulator struct timer_t2 fps; //Wait for user exit while( quit == 0 ) { //Start the frame timer timer_start(&fps); //While there are events to handle while( SDL_PollEvent( &event ) ) { //Handle events: switch(event.type) { case SDL_MOUSEBUTTONDOWN: switch(event.button.button) { case SDL_BUTTON_LEFT: // Change direction of red square square_set_destination ( &red_square, event.button.x, event.button.y); break; case SDL_BUTTON_RIGHT: // Change direction of blue square square_set_destination ( &blue_square, event.button.x, event.button.y ); break; } break; } if( event.type == SDL_QUIT ) { quit = 1; } } //Move the squares move(&red_square); move(&blue_square); //Clear the screen glClear( GL_COLOR_BUFFER_BIT ); //Show the squares show(&red_square); show(&blue_square); glFlush(); //Update screen SDL_GL_SwapBuffers(); //Capture the frame rate if( timer_get_ticks(&fps) < 1000 / FRAMES_PER_SECOND ) { SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - timer_get_ticks(&fps) ); } } clean_up(); return 0; }
/** * Author: Joel Denke * Description: Listen for input * Params: keysHeld Key statements for all buttons */ void listenInput(int * keysHeld) { struct timer_t2 fps; if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN : keysHeld[event.key.keysym.sym] = 1; break; case SDL_KEYUP : keysHeld[event.key.keysym.sym] = 0; break; case SDL_QUIT : state = gExit; break; } } if (keysHeld[SDLK_ESCAPE]) { state = gExit; } if (keysHeld[SDLK_LEFT]) { movePlayer("left"); } if (keysHeld[SDLK_RIGHT]) { movePlayer("right"); } if (keysHeld[SDLK_UP]) { movePlayer("up"); } if (keysHeld[SDLK_1] || keysHeld[SDLK_2] || keysHeld[SDLK_3] || keysHeld[SDLK_m]) { timer_start(&fps); if (keysHeld[SDLK_m]) { pauseMusic(); } else { int k; if (keysHeld[SDLK_1]) { k = 0; } else if (keysHeld[SDLK_2]) { k = 1; } else if (keysHeld[SDLK_3]) { k = 2; } playMusic(k); } if (timer_get_ticks(&fps) < 1000) { //delay the as much time as we need to get desired frames per second SDL_Delay((1000) - timer_get_ticks(&fps)); } } }
/** * Get the miliseconds since power on. * * @returns The time in ms. */ uint32_t timer_get_ms(void) { return timer_get_ticks() * TIMER_RES ; }
/* return the time in nanoseconds */ uint64_t clock_read(void) { uint64_t ticks = ticks_to_us(timer_device.frequency, timer_get_ticks(timer_device.ti)); return ticks; }
/** PPM decoder state machine. */ static void timer_ppm_decode(uint16_t sr) { /* Note that there is an assumption here that the timer will not * updated more than once in between captures or the math will be * incorrect (but should still work unless the timer frequency is * changed). */ uint16_t count = TIMER_DEV->CCR_PPM; uint16_t width = count - g_ppm_state.last_edge; uint16_t value; /* Start over if we overflowed the capture. */ if (sr & SR_CCOF_PPM) goto error; g_ppm_state.last_edge = count; /* If the pulse is large enough to start a new frame, push any * values captured the last time around to the shadow buffer and * reset the state machine. */ if (width >= PPM_START_MIN) { if (g_ppm_state.current_len > 4) { for (size_t i = 0; i < g_ppm_state.current_len; ++i) g_ppm_state.sample_buf[i] = g_ppm_state.current_buf[i]; } g_ppm_state.sample_time = timer_get_ticks(); g_ppm_state.sample_len = g_ppm_state.current_len; g_ppm_state.current_len = 0; g_ppm_state.state = ARMING; return; } switch (g_ppm_state.state) { case SYNC: /* Continue waiting for a start pulse. */ return; case ARMING: if (width > PPM_LOW_MAX) goto error; /* pulse was too long */ g_ppm_state.last_mark = count; g_ppm_state.state = INACTIVE; return; case INACTIVE: g_ppm_state.state = ACTIVE; return; case ACTIVE: value = count - g_ppm_state.last_mark; g_ppm_state.last_mark = count; /* If the value is invalid, abandon the frame. */ if ((value < PPM_HIGH_MIN) || (value > PPM_HIGH_MAX)) goto error; /* Store the value in the current frame buffer. */ if (g_ppm_state.current_len < PPM_MAX_CHANNELS) g_ppm_state.current_buf[g_ppm_state.current_len++] = value; g_ppm_state.state = INACTIVE; return; } /* fall through if state is invalid */ error: g_ppm_state.state = SYNC; g_ppm_state.current_len = 0; }
int main(int argc, char *argv[]) { //Network vars int udpSd, tcpSd; char buffer[5]; int myId; //SDL vars SDL_Event event; //Screen SDL_Surface* screen = NULL; //Tanks SDL_Surface* blueTank = NULL; SDL_Surface* blueCannon = NULL; SDL_Surface* redTank = NULL; SDL_Surface* redCannon = NULL; //Bullet SDL_Surface* bullet = NULL; //WorldMap SDL_Surface* worldMap = NULL; //rotation Images //SDL_Surface* rotatedTank[6] = {NULL,NULL,NULL,NULL,NULL,NULL}; //SDL_Surface* rotatedCannon[6] = {NULL,NULL,NULL,NULL,NULL,NULL}; SDL_Surface* rotatedBullet[6] = {NULL,NULL,NULL,NULL,NULL,NULL}; //SDL_Rect Tankoffset[6] = {400,300,0,0}; //SDL_Rect Cannonoffset[6] = {400,300,0,0}; //UserInterface vars SDL_Surface* UIhealth; SDL_Surface* UIreload; SDL_Surface* UIredPoints; SDL_Surface* UIbluePoints; TTF_Font *font = NULL; TTF_Font *reloadFont = NULL; SDL_Color textColor = { 255, 255, 255 }; char textBuffer[32]; char reload[32] = "FIRE: "; //Thread vars pthread_t reciveUdpData; //Game vars int run; struct playerInfo player[6]; struct timerInfo fps; struct cameraInfo camera; int bulletAngle[6]; //int oldCannonAngle[6]; //int oldTankAngle[6]; //Other vars int i; //Inits the player struct for (i = 0; i < MAX_PLAYERS; i++) { player[i].slot = -1; player[i].connected = 0; } //inits Sdl and opens the screen screen = init_sdl(); if(screen == 0) { printf("Error initializing SDL\n"); return 0; } //Makes the connection to the server if(!(init_udp_tcp(&udpSd, &tcpSd, argv[1], argv[2]))) { printf("Error making connection\n"); return 0; } //load the images (Function maybe) blueTank = load_image( "./images/blueTank.bmp" ); blueCannon = load_image( "./images/blueCannon.bmp" ); redTank = load_image( "./images/redTank.bmp" ); redCannon = load_image( "./images/redCannon.bmp" ); worldMap = load_image( "./images/worldMap.bmp" ); bullet = load_image( "./images/bullet.bmp" ); //Load the fonts font = TTF_OpenFont( "./fonts/Army.ttf", 24 ); reloadFont = TTF_OpenFont( "./fonts/Armyfat.ttf", 24 ); //Moves udp info to global var udpInfo.udpSd = udpSd; strcpy(udpInfo.serverIp, argv[1]); //Recives the first information from the server recv(tcpSd, buffer, sizeof(buffer), 0); myId = atoi(buffer); //Starts the Recive data thread pthread_create( &reciveUdpData, NULL, recive_udp_data, &(player)); while (run) { //Start the timer timer_start(&fps); while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE) { run = FALSE; } handel_input(&event, tcpSd ); } camera.xCord = -player[myId].xCord; camera.yCord = -player[myId].yCord; //From here we draw stuff on the screen SDL_FillRect(screen,NULL, 0x000000); //Draws WorldMAps draw_map(player[myId].xCord,player[myId].yCord, worldMap, screen); //DISPLAYES YOUR TANK+++++++++++++++++++++++++++++ if (player[myId].team == 1) { draw_tank_self(player[myId].tankAngle, blueTank, screen); draw_cannon_self(player[myId].cannonAngle, blueCannon, screen); } else { draw_tank_self(player[myId].tankAngle, redTank, screen); draw_cannon_self(player[myId].cannonAngle, redCannon, screen); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //DISPLAYES OTHER TANKS+++++++++++++++++++++++++++++ for (i = 0; i < MAX_PLAYERS; i++) { if (player[i].slot == myId) { continue; } if (player[i].slot > -1 && player[i].connected == 1) { if (player[i].team == 1) { draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,blueTank,screen); if (player[i].dead == 0) draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,blueCannon,screen); } else { draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,redTank,screen); if (player[i].dead == 0) draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,redCannon,screen); } } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //DRAWS ALL THE BULLETS ON THE SCREEEN+++++++++++++++++++++++++++ for (i = 0; i < MAX_PLAYERS; i++) { if (player[i].slot > -1 && player[i].connected == 1) { if (player[i].fire > 0) { if (bulletAngle[i] == 0) { SDL_FreeSurface( rotatedBullet[i] ); rotatedBullet[i] = rotozoomSurface(bullet,player[i].cannonAngle,1.0,0); playSound(soundShoot); } draw_bullet(&player[i], &camera, rotatedBullet[i], screen ); bulletAngle[i] = 1; } if (player[i].fire == 0) { bulletAngle[i]=0; } } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //DRAWS THE USER INTERFACE ON SCREEN+++++++++++++++++++++++++++++ textColor.r=0; textColor.g=0; textColor.b=255; sprintf(textBuffer, "BLUE POINTS: %d", bluePoints); UIbluePoints = TTF_RenderText_Solid( font, textBuffer, textColor ); draw_UI( 10, 10, UIbluePoints, screen); textColor.r=255; textColor.g=0; textColor.b=0; sprintf(textBuffer, "RED POINTS: %d", redPoints); UIredPoints = TTF_RenderText_Solid( font, textBuffer, textColor ); draw_UI( 600, 10, UIredPoints, screen); textColor.r=255; textColor.g=0; textColor.b=0; sprintf(textBuffer, "HP: %d", player[myId].healthPoints); UIhealth = TTF_RenderText_Solid( font, textBuffer, textColor ); draw_UI( 20, 570, UIhealth, screen); textColor.r=255; textColor.g=0; textColor.b=0; if (player[myId].fire == 0) { strcpy(reload, "FIRE: READY"); UIreload = TTF_RenderText_Solid( font, reload, textColor ); } else { strcpy(reload, "FIRE: RELOADING"); UIreload = TTF_RenderText_Solid( font, reload, textColor ); } draw_UI( 580, 570, UIreload, screen); //Update Screen SDL_Flip( screen ); //Cap the frame rate if( timer_get_ticks(&fps) < 1000 / FPS ) { SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) ); } } pthread_cancel(reciveUdpData); return 0; }
void * recive_udp_data(void * parameters) { struct timerInfo timeOut[MAX_PLAYERS]; int i; char buffer[128]; struct stcInfo moveInfo; struct playerInfo * player = (struct playerInfo*) parameters; //Init the timer for (i = 0; i < MAX_PLAYERS; i++) { timer_init(&timeOut[i]); } while (1) { recvfrom(udpInfo.udpSd, buffer, sizeof(buffer), 0, udpInfo.serverIp, sizeof(udpInfo.serverIp)); //printf("recived from server: %s \n", buffer); sscanf(buffer, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &moveInfo.team,&moveInfo.x, &moveInfo.y , &moveInfo.player, &moveInfo.mouseX, &moveInfo.mouseY,&moveInfo.fire, &moveInfo.bulletX, &moveInfo.bulletY, &moveInfo.tankAngle, &moveInfo.cannonAngle, &moveInfo.dead, &moveInfo.healthPoints, &moveInfo.redPoints, &moveInfo.bluePoints); timer_start(&timeOut[moveInfo.player]); //Saves the incoming data in the players struct. player[moveInfo.player].slot = moveInfo.player; player[moveInfo.player].team = moveInfo.team; player[moveInfo.player].xCord = moveInfo.x; player[moveInfo.player].yCord = moveInfo.y; player[moveInfo.player].mouseX = moveInfo.mouseX; player[moveInfo.player].mouseY = moveInfo.mouseY; player[moveInfo.player].bulletX = moveInfo.bulletX; player[moveInfo.player].bulletY = moveInfo.bulletY; player[moveInfo.player].fire = moveInfo.fire; player[moveInfo.player].tankAngle = -1*moveInfo.tankAngle; player[moveInfo.player].cannonAngle = -1*moveInfo.cannonAngle; player[moveInfo.player].healthPoints = moveInfo.healthPoints; player[moveInfo.player].dead = moveInfo.dead; player[moveInfo.player].connected = 1; redPoints = moveInfo.redPoints; bluePoints = moveInfo.bluePoints; //If no new udp from a client it disconnects after 0.5 sec for (i = 0; i < MAX_PLAYERS; i++) { if (timer_get_ticks(&timeOut[i]) > 500) { player[i].connected = 0; timer_stop(&timeOut[i]); } } sleep(0); } }
int main(int argc, char* args[]) { // This will be the window we'll be rendering to SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; TTF_Font *font; SDL_Texture *sheet = NULL; Text text; init_sprites(); event_init(); if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_ERROR: %s\n", SDL_GetError()); } else { //if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 1)) { // printf("Warning: Linear texture filtering not enabled"); //} window = SDL_CreateWindow("Piggle", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); } else { renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { printf("Renderer couldn't be created. Shit's f****d, becuase %s" ", dude.\n", SDL_GetError()); } else { SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { printf("SDL_image couldn't be initialized. Shit's f****d, " "because %s, dude.\n", IMG_GetError()); } if (TTF_Init() == -1) { printf("SDL_ttf couldn't initialize. Shit's f****d, becuase" " %s, dude.\n", TTF_GetError()); } } font = TTF_OpenFont("DroidSansMono.ttf", 16); if (font == NULL) { printf("Failed to load lazy font. Shit's f****d, because %s, " "dude.", TTF_GetError()); } sheet = loadTexture("img/sprites.png", renderer); // When quit is set to true, we'll stop running bool quit = false; piggle_scene_over = false; // Event handler SDL_Event sdl_event; // Set the current scene to the start scene piggle_scene_update = start_scene_update; while (!quit) { timer_start(); EventList events = EventList_new(); while (SDL_PollEvent(&sdl_event) != 0) { Event event; // If the user presses that little "x" if (sdl_event.type == SDL_QUIT) { quit = true; event.type = QUIT; } else if (sdl_event.type == SDL_KEYDOWN) { event.type = KEYDOWN; int key = sdl_event.key.keysym.sym; event.value = event_value_from_key(key); } else if (sdl_event.type == SDL_KEYUP) { event.type = KEYUP; int key = sdl_event.key.keysym.sym; event.value = event_value_from_key(key); } else { continue; } events.add_event(&events, event); } SDL_RenderClear(renderer); DrawActionList actions = DrawActionList_new(); piggle_scene_update(&events, &actions); events.destroy(&events); int i; for (i = 0; i < actions.length; i++) { DrawAction action = actions.actions[i]; if (action.type == SPRITE) { SDL_Rect *sprite = &sprites[action.sprite]; SDL_Rect dest; dest.x = action.x; dest.y = action.y; dest.w = sprite->w; dest.h = sprite->h; SDL_RenderCopy(renderer, sheet, sprite, &dest); } else if (action.type == TEXT) { SDL_Color color = {action.text.red, action.text.green, action.text.blue}; textureFromText(action.text.text, color, &text, font, renderer); SDL_Rect textRect; textRect.x = action.x; textRect.y = action.y; textRect.w = text.width; textRect.h = text.height; SDL_RenderCopy(renderer, text.texture, NULL, &textRect); SDL_DestroyTexture(text.texture); } else if (action.type == RECTANGLE) { SDL_Rect rect = {.x = action.x, .y = action.y, .w = action.rect.width, .h = action.rect.height}; SDL_SetRenderDrawColor(renderer, action.rect.red, action.rect.green, action.rect.blue, 255); SDL_RenderFillRect(renderer, &rect); } } SDL_RenderPresent(renderer); actions.destroy(&actions); if (piggle_scene_over) { piggle_scene_update = piggle_scene_next; piggle_scene_over = false; } if (timer_get_ticks() < 1000 / 60) { SDL_Delay((1000 / 60) - timer_get_ticks()); } } } } SDL_DestroyTexture(sheet); SDL_DestroyTexture(text.texture); text.texture = NULL; sheet = NULL; TTF_CloseFont(font); font = NULL; SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); window = NULL; renderer = NULL; // Quit SDL subsystems TTF_Quit(); IMG_Quit(); SDL_Quit(); event_uninit(); return 0; }
/* * player_update() * player를 업데이트하는 함수. */ void player_update(player_t *player, player_t **team, int team_size, brick_list_t *brick_list, item_list_t *item_list, enemy_list_t *enemy_list) { int i; actor_t *act = player->actor; float dt = timer_get_delta(); act->hot_spot = v2d_new(image_width(actor_image(act))/2, image_height(actor_image(act))-20); /* physics */ if(!player->disable_movement) { player->pa_old_state = physicsactor_get_state(player->pa); physics_adapter(player, team, team_size, brick_list, item_list, enemy_list); } /* player 깜빡거림 */ if(player->blinking) { player->blink_timer += timer_get_delta(); if(player->blink_timer - player->blink_visibility_timer >= 0.067f) { player->blink_visibility_timer = player->blink_timer; act->visible = !act->visible; } if(player->blink_timer >= PLAYER_MAX_BLINK) { player->blinking = FALSE; act->visible = TRUE; } } if(physicsactor_get_state(player->pa) != PAS_GETTINGHIT && player->pa_old_state == PAS_GETTINGHIT) { player->blinking = TRUE; player->blink_timer = 0.0f; player->blink_visibility_timer = 0.0f; } /* 방패 */ if(player->shield_type != SH_NONE) update_shield(player); /* 수중에서 */ if(!(player->underwater) && player->actor->position.y >= level_waterlevel()) player_enter_water(player); else if(player->underwater && player->actor->position.y < level_waterlevel()) player_leave_water(player); /* 수중인지 확인 */ if(player->underwater) { player->speedshoes_timer = max(player->speedshoes_timer, PLAYER_MAX_SPEEDSHOES); /* disable speed shoes */ if(player->shield_type != SH_WATERSHIELD) player->underwater_timer += dt; else player->underwater_timer = 0.0f; if(player_seconds_remaining_to_drown(player) <= 0.0f) player_drown(player); } /* 무적의 별 */ if(player->invincible) { int maxf = sprite_get_animation("SD_INVSTAR", 0)->frame_count; int invangle[PLAYER_MAX_INVSTAR]; v2d_t starpos; player->invtimer += dt; for(i=0; i<PLAYER_MAX_INVSTAR; i++) { invangle[i] = (180*4) * timer_get_ticks()*0.001 + (i+1)*(360/PLAYER_MAX_INVSTAR); starpos.x = 25*cos(invangle[i]*PI/180); starpos.y = ((timer_get_ticks()+i*400)%2000)/40; /*starpos = v2d_rotate(starpos, act->angle);*/ player->invstar[i]->position.x = act->position.x - act->hot_spot.x + image_width(actor_image(act))/2 + starpos.x; player->invstar[i]->position.y = act->position.y - act->hot_spot.y + image_height(actor_image(act)) - starpos.y + 5; actor_change_animation_frame(player->invstar[i], random(maxf)); } if(player->invtimer >= PLAYER_MAX_INVINCIBILITY) player->invincible = FALSE; } /* speed shoes */ if(player->got_speedshoes) { physicsactor_t *pa = player->pa; if(player->speedshoes_timer == 0) { physicsactor_set_acc(pa, physicsactor_get_acc(pa) * 2.0f); physicsactor_set_frc(pa, physicsactor_get_frc(pa) * 2.0f); physicsactor_set_topspeed(pa, physicsactor_get_topspeed(pa) * 2.0f); physicsactor_set_air(pa, physicsactor_get_air(pa) * 2.0f); physicsactor_set_rollfrc(pa, physicsactor_get_rollfrc(pa) * 2.0f); player->speedshoes_timer += dt; } else if(player->speedshoes_timer >= PLAYER_MAX_SPEEDSHOES) { physicsactor_set_acc(pa, physicsactor_get_acc(pa) / 2.0f); physicsactor_set_frc(pa, physicsactor_get_frc(pa) / 2.0f); physicsactor_set_topspeed(pa, physicsactor_get_topspeed(pa) / 2.0f); physicsactor_set_air(pa, physicsactor_get_air(pa) / 2.0f); physicsactor_set_rollfrc(pa, physicsactor_get_rollfrc(pa) / 2.0f); player->got_speedshoes = FALSE; } else player->speedshoes_timer += dt; } /* 애니메이션 */ update_animation(player); /* CPU가 제어하는 player인지 확인 */ if(player != level_player()) { for(i=0; i<IB_MAX; i++) input_simulate_button_up(act->input, (inputbutton_t)i); } /* 승리 포즈 */ if(level_has_been_cleared()) physicsactor_enable_winning_pose(player->pa); }
/** * Author: Joel Denke, Marcus Isaksson * Description: Run the game on client */ int main(int argc, char *argv[]) { int i, j, no, yb, keysHeld[323] = {0}; int result = 0; SDL_Thread * eventBuffer; SDL_Thread * runBuffer; struct timer_t2 fps; char * server_ip = malloc(sizeof(char) * 16); char * elem = malloc(sizeof(char) * MESSAGE_SIZE); pColor = malloc(sizeof(SDL_Color)); oColor = malloc(sizeof(SDL_Color)); connection = malloc(sizeof(connection_data)); for (i = 0; i < NO_BUFFERS; i++) { cb[i] = malloc(sizeof(cBuffer)); b_lock[i] = SDL_CreateMutex(); } strcpy(server_ip, "127.0.0.1"); pColor->r = 0; pColor->g = 255; pColor->b = 255; oColor->r = 0; oColor->g = 0; oColor->b = 255; initGraphics(); initSound(); printf("Render menu\n"); graphicsMenu(&gameWorld, server_ip); initSlots(cb[0], BUFFER_SIZE); initSlots(cb[1], NO_OBJECTS); initSlots(cb[2], BUFFER_SIZE); state = gStart; if (clientConnect(connection, server_ip) == 0) { eventBuffer = SDL_CreateThread(listenEventBuffer, &connection); while (1) { switch (state) { case gStart: runData(2); break; case gInit: timer_start(&fps); startDraw(); drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT); endDraw(); initWorld(); if (timer_get_ticks(&fps) < 1000 / FPS) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) ); } break; case gRunning : timer_start(&fps); drawGraphics(); listenInput(keysHeld); // i = 0: players; i = 1: objects; i = 2: messages for (i = 0; i < NO_BUFFERS; i++) { runData(i); } if (timer_get_ticks(&fps) < 1000 / FPS) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) ); } break; case gExit : //sprintf(string, "%d,quit", connection->client_id); printf("Freeing music now\n"); pauseMusic(); freeMusic(); end_session(connection); printf("Player is exit game now\n"); exitClient(eventBuffer); break; default : printf("test\n"); break; } } } else { printf("Misslyckade med att kontakta servern på ip-adress: '%s'\n", server_ip); state = gExit; pauseMusic(); freeMusic(); exitClient(eventBuffer); } return 0; }
void options(char ip[]) { int quit = 0; int menu_choice = 0; //fps struct timer_t2 fps; init_options(); init_font(); //wait for user to continue or exit while( quit != 1 ) { //Start the frame timer timer_start(&fps); //While there are events to handle while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) { //exit clean_up(); exit(0); } if( event.type == SDL_KEYDOWN ) { switch(event.key.keysym.sym) { case SDLK_ESCAPE: quit = 1; break; } } mouse_over_options(event.button.x, event.button.y); if( event.type == SDL_MOUSEBUTTONDOWN) { switch(event.button.button) { case SDL_BUTTON_LEFT: press_options(event.button.x, event.button.y); break; } } if( event.type == SDL_MOUSEBUTTONUP) { switch(event.button.button) { case SDL_BUTTON_LEFT: menu_choice = press_options(event.button.x, event.button.y); break; } } switch(menu_choice) { case 1: handle_input(event,ip); printf("String in graphics.c (%s)\n",ip); break; case 2: quit = 1; printf("Försöker bryta ut ur options\n"); break; default: break; } } apply_letter(ip); apply_texture(); startDraw(); //draw menu drawOptions(SCREEN_WIDTH, SCREEN_HEIGHT); drawBack(); endDraw(); if( timer_get_ticks(&fps) < 1000 / FRAMES_PER_SECOND ) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - timer_get_ticks(&fps) ); } } }