int main(void) { board = board_create(); white = player_create( WHITE ); black = player_create( BLACK ); play(); return 0; }
Test(Player, inv_add) { player_t *pl = player_create(); cr_assert(pl); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); player_inventory_add(pl, FOOD); cr_expect_eq(player_inventory_get(pl, FOOD), 10); player_inventory_add(pl, SIBUR); player_inventory_add(pl, THYSTAME); player_inventory_add(pl, THYSTAME); player_inventory_add(pl, THYSTAME); player_inventory_add(pl, THYSTAME); player_inventory_add(pl, DERAUMERE); player_inventory_add(pl, DERAUMERE); cr_expect_eq(player_inventory_get(pl, FOOD), 10); cr_expect_eq(player_inventory_get(pl, SIBUR), 1); cr_expect_eq(player_inventory_get(pl, THYSTAME), 4); cr_expect_eq(player_inventory_get(pl, DERAUMERE), 2); player_delete(pl); }
Test(Player, create) { player_t *pl = player_create(); cr_assert(pl); player_delete(pl); }
Test(Player, lifespan_check_positive) { player_t *pl = player_create(); chrono_init(&pl->p_lifespan, 0); player_lifespan_check(pl, 1); cr_expect_str_eq(pl->p_queued_msgs->l_end->n_data, "quit"); }
void game_init(){ int8u no; int8u count; display_off(); pattern_fill(0x3800, 0, (BG_HIGH + BG_PAL1 + BG_TOP), 32 * 28 * 2); actors_clear(); scene_wait = 0; player_create(0); alive_players = 1; smoke_wait = 0; scene_type = SCENE_GAME_PLAYING; vram_store(0x3000, fopen("bmp/font.ptn"), 0x0800); /* load pattern */ switch(stage){ case 0: vram_store(0x2000, fopen("bmp/castle.ptn"), 0x1000); vram_store(0x0000, fopen("bmp/sp_castle.ptn"), 0x2000); break; case 1: vram_store(0x2000, fopen("bmp/summer.ptn"), 0x1000); vram_store(0x0000, fopen("bmp/sp_summer.ptn"), 0x2000); break; case 2: vram_store(0x2000, fopen("bmp/jungle.ptn"), 0x1000); vram_store(0x0000, fopen("bmp/sp_castle.ptn"), 0x2000); break; default: vram_store(0x2000, fopen("bmp/winter.ptn"), 0x1000); vram_store(0x0000, fopen("bmp/sp_castle.ptn"), 0x2000); break; } /* load palette */ load_palette(stage, 0); /* set enemy */ enemies_rotation_count = level << 3; for(count = stage; count != 0; count--){ /* 8 charactors * 3 levels * stage 2 */ enemies_rotation_count += 8 * 3; } enemies_rotation_limit = enemies_rotation_count + 8; enemies_count = ACTORS_INITINAL_COUNT; enemies_alive = 0; enemies_left = 6 + stage; for(count = 0; count < enemies_count; count++){ no = actors_get_null(); actor_create_random(no); } display_on(); }
struct Player player_create_position(float x, float y, float z) { struct Player p = player_create(); p.x = x; p.y = y; p.z = z; player_refresh_bbox(&p); return p; }
Test(Player, lifespan_check_neg) { player_t *pl = player_create(); chrono_init(&pl->p_lifespan, 1000); player_lifespan_check(pl, 1); chrono_init(&pl->p_lifespan, 0); pl->p_inventory[FOOD] = 1; player_lifespan_check(pl, 1); cr_assert_eq(pl->p_inventory[FOOD], 0); cr_expect_eq(pl->p_queued_msgs->l_size, 0); }
void play(void) { Player *player = NULL; StarSystem *sys = NULL; set_seed(); putchar('\n'); player = player_create(); sys = starsys_create(); LINE(80, '-'); player_move_toSystem(player, sys); while (!player->wantToExit) { cmd_get(player); } player_destroy(player); }
/* ** Creation of a client - by default always a player. ** upon team seleciton, the client can change its type to GFX. */ int client_create(selector_t *stor, int sock) { handle_t *hdl = selector_get_new_handle(stor); if (!hdl) { close(sock); return (SELECTOR_RET_ERR); } hdl->h_data = player_create(); if (!hdl->h_data) { hdl->h_delete = NULL; close(sock); list_find_and_delete_addr(stor->s_handles, hdl); return (SELECTOR_RET_ERR); } hdl->h_fd = sock; hdl->h_type = H_PLAYER; hdl->h_read = client_read; hdl->h_on_cycle = player_on_cycle; hdl->h_delete = player_delete; dprintf(sock, "%s\n", "WELCOME"); return (SELECTOR_RET_OK); }
/** \brief Creates a new, empty object. * \param obj Object handle * \param gs Game state handle * \param pos Initial position * \param vel Initial velocity */ void object_create(object *obj, game_state *gs, vec2i pos, vec2f vel) { // State obj->gs = gs; // Position related obj->pos = vec2i_to_f(pos); // remember the place we were spawned, the x= and y= tags are relative to that obj->start = vec2i_to_f(pos); obj->vel = vel; obj->direction = OBJECT_FACE_RIGHT; obj->y_percent = 1.0; // Physics obj->layers = OBJECT_DEFAULT_LAYER; obj->group = OBJECT_NO_GROUP; obj->gravity = 0.0f; // Video effect stuff obj->video_effects = 0; // Attachment stuff obj->attached_to = NULL; // Fire orb wandering obj->orbit = 0; obj->orbit_tick = MATH_PI/2.0f; obj->orbit_dest = obj->start; obj->orbit_pos = obj->start; obj->orbit_pos_vary = vec2f_create(0, 0); // Animation playback related obj->cur_animation_own = OWNER_EXTERNAL; obj->cur_animation = NULL; obj->cur_sprite = NULL; obj->sprite_override = 0; obj->sound_translation_table = NULL; obj->cur_surface = NULL; obj->cur_remap = -1; obj->pal_offset = 0; obj->halt = 0; obj->halt_ticks = 0; obj->stride = 1; obj->cast_shadow = 0; obj->age = 0; player_create(obj); obj->custom_str = NULL; random_seed(&obj->rand_state, rand_intmax()); // For enabling hit on the current and the next n-1 frames obj->hit_frames = 0; obj->can_hit = 0; // Callbacks & userdata obj->userdata = NULL; obj->dynamic_tick = NULL; obj->static_tick = NULL; obj->free = NULL; obj->act = NULL; obj->collide = NULL; obj->finish = NULL; obj->move = NULL; obj->serialize = NULL; obj->unserialize = NULL; obj->debug = NULL; obj->pal_transform = NULL; }
/* * Unserializes the data from buffer to a specialized object. * Should return 1 on error, 0 on success. * Serial reder position should be set to correct position before calling this. */ int object_unserialize(object *obj, serial *ser, game_state *gs) { obj->pos.x = serial_read_float(ser); obj->pos.y = serial_read_float(ser); obj->vel.x = serial_read_float(ser); obj->vel.y = serial_read_float(ser); float gravity = serial_read_float(ser); obj->direction = serial_read_int8(ser); obj->group = serial_read_int8(ser); obj->layers = serial_read_int8(ser); uint8_t stride = serial_read_int8(ser); uint8_t repeat = serial_read_int8(ser); obj->sprite_override = serial_read_int8(ser); obj->age = serial_read_int32(ser); random_seed(&obj->rand_state, serial_read_int32(ser)); uint8_t animation_id = serial_read_int8(ser); uint8_t pal_offset = serial_read_int8(ser); int8_t hit_frames = serial_read_int8(ser); int8_t can_hit = serial_read_int8(ser); // Other stuff not included in serialization obj->y_percent = 1.0; obj->cur_animation_own = OWNER_EXTERNAL; obj->cur_animation = NULL; obj->cur_sprite = NULL; obj->sound_translation_table = NULL; obj->cur_surface = NULL; obj->cur_remap = 0; obj->halt = 0; obj->halt_ticks = 0; obj->cast_shadow = 0; player_create(obj); // Read animation state uint16_t anim_str_len = serial_read_int16(ser); char anim_str[anim_str_len+1]; if(anim_str_len > 0) { serial_read(ser, anim_str, anim_str_len); } obj->animation_state.current_tick = (uint16_t)serial_read_int16(ser); obj->animation_state.previous_tick = (uint16_t)serial_read_int16(ser); uint8_t reverse = serial_read_int8(ser); // Read the specialization ID from ther serial "stream". // This should be an int. int specialization_id = serial_read_int8(ser); // This should automatically bootstrap the object so that it has at least // unserialize function callback and local memory allocated object_auto_specialize(obj, specialization_id); // Now, if the object has unserialize function, call it with // serialization data. serial object should be pointing to the // start of that data. if(obj->unserialize != NULL) { obj->unserialize(obj, ser, animation_id, gs); } else { DEBUG("object has no special unserializer"); } // Init animation with correct string and tick if(anim_str_len > 0) { // server is using a custom string DEBUG("serialized object has custom animation string %s", anim_str); player_reload_with_str(obj, anim_str); } if(reverse) { object_set_playback_direction(obj, PLAY_BACKWARDS); } // deserializing hars can reset these, so we have to set this late obj->stride = stride; object_set_gravity(obj, gravity); object_set_repeat(obj, repeat); object_set_pal_offset(obj, pal_offset); obj->hit_frames = hit_frames; obj->can_hit = can_hit; /*DEBUG("Animation state: [%d] %s, ticks = %d stride = %d direction = %d pos = %f,%f vel = %f,%f gravity = %f", strlen(player_get_str(obj))+1, player_get_str(obj), obj->animation_state.ticks, obj->stride, obj->animation_state.reverse, obj->pos.x, obj->pos.y, obj->vel.x, obj->vel.y, obj->gravity);*/ // Return success return 0; }
/* ----------------------------------------------------------------------------------- */ void intro_ending_main(){ int8u scene; int8u scene_counter; int8u c; int8u *sour; int8u *dist; basic_init_for_intro(); scene = 0; scene_counter = 240; sour = fopen("map/intro.map"); sour += 32 * (24 + 3) * 2; dist = map_cache; for(c = 32 * 5; c != 0; c--){ *dist++ = *sour++; *dist++ = *sour++; } serif = map_cache; psg_set_bgm(fopen("sound/demo.sn7"), FALSE); while(373){ sprites_clear(); port_read(); switch(scene){ case 0: /* */ ninja_cake_create(0); actors_x[0] = 40; actors_y[0] = 140; actors_angle[0] = ANGLE_RIGHT; scene++; break; case 1: /* ケーキを持って冷蔵庫の前まで来る */ if(actors_x[0] >= 114){ actors_type[0] = ACTOR_NULL; actors_x[0] = 115; actors_y[0] = 144; scene_counter = 120; scene++; } if(actors_y[0] < 32){ actors_speed_y[0] = 32; } break; case 2: /* ケーキを持って「もうこりごりだ」 */ actor_set_sprite(0, 16, VRAM_NINJA_CAKE + 4, 0); if(scene_counter == 0){ serif += 64; scene_counter = 120; scene++; } break; case 3: /* 「ここにケーキを入れる!」 */ actor_set_sprite(0, 16, VRAM_NINJA + 4, 0); if(scene_counter == 0){ ninja_create(0); actors_x[0] = 115; actors_y[0] = 144; actors_angle[0] = ANGLE_RIGHT; serif += 64; scene_counter = 120; scene++; } break; case 4: /* 忍者が去る */ if(actors_x[0] > 208){ actors_type[0] = ACTOR_NULL; scene_counter = 120; scene++; } break; case 5: /* 誰も居ない間 */ //scene_counter--; if(scene_counter == 0){ player_create(0); actors_x[0] = 40; actors_y[0] = 144; scene_counter = 120; scene++; } break; case 6: /* ぷんぷん丸が来る */ ports[0].button |= BUTTON_RIGHT; if(actors_x[0] >= 88){ scene_counter = 240; scene++; } break; case 7: /* 「なんだ俺のケーキあるじゃないか」 */ if(scene_counter == 120){ serif += 64; } if(scene_counter == 0){ boar_create(1); actors_x[1] = 40; actors_y[1] = 144; actors_angle[1] = ANGLE_RIGHT; scene++; } break; case 8: /* イノシシが来る */ if(actors_x[1] > 108){ actors_speed_x[0] = 32 + 31; actors_speed_y[0] = 32 - 32; scene++; } break; case 9: /* 突き飛ばされる */ if(actors_x[0] > 208){ psg_stop(); return; } break; } scene_counter--; basic_update_for_intro(); } }
int main( int argc, char * argv[] ) { if( argc != 2 ) { fprintf( stdout, "Usage: server port\n" ); return 0; } debug_printf( "Start server\n" ); ts_queue * queue = ts_queue_create(); pthread_t * accept_thread = create_accept_thread( queue, argv[1] ); player_queue * players = player_queue_create(); int game_state = -1; float ball_x, ball_y; float bvx, bvy; float tick; srand( clock() ); for( ;; ) { usleep( 10000 ); generic_packet * packet; while( ( packet = ts_queue_try_pop( queue ) ) != NULL ) { if( packet->packet_type == PACKET_CLIENT_REQUEST ) { player * ply = player_create( queue, packet->cl_request.sockfd ); player_queue_push( players, ply ); generic_packet * pkt = create_client_info_request( ply->sockfd ); send_to_player( ply, pkt ); debug_printf( "Sent info request packet to client\n" ); } if( packet->packet_type == PACKET_CLIENT_INFO ) { player * ply = player_queue_search_by_fd( players, packet->cl_info.sockfd ); strcpy( ply->name, packet->cl_info.name ); debug_printf( "%d told us that their name is %s\n", ply->sockfd, ply->name ); } if( packet->packet_type == PACKET_CLIENT_DISCONNECT ) { player_queue_remove_by_fd( players, packet->cl_disconnect.sockfd ); } if( packet->packet_type == PACKET_CLIENT_MOVE_UPDATE ) { player * ply; ply = player_queue_search_by_fd( players, packet->cl_mv_update.sockfd ); if( ( players->tail == ply || players->tail->next == ply ) && game_state == 1 ) { int sockfd; float y; ply->y += packet->cl_mv_update.y * 0.01; } } free( packet ); } if( players->tail != NULL && players->tail->next != NULL ) { if( game_state == 0 ) { if( players->tail->next->name[0] == '\0' || players->tail->name[0] == '\0' ) { game_state = 0; } else { send_to_all_players( players, create_client_start_message( players->tail->name, players->tail->next->name ) ); game_state = 1; players->tail->y = 0; players->tail->next->y = 0; ball_x = 0; ball_y = 0; bvx = -0.01; bvy = 0; tick = 0; } } if( !( (int)tick % 100 ) ) send_to_all_players( players, create_client_start_countdown( 5 - (tick / 100) ) ); if( tick > 400 ) { if( abs( ball_y + bvy ) >= 1 ) bvy *= -1; if( ball_x <= -0.85 ) { if( ball_y > ( players->tail->y + 0.35 ) || ball_y < ( players->tail->y - 0.35 ) ) { player_queue_first_to_last( players ); game_state = 0; } else { bvx = 0.07; bvy = ball_y - players->tail->y; float h = pow( ( pow( bvx, 2 ) + pow( bvy, 2 ) ), 0.5 ) * 100; bvx /= h; bvy /= h; } } if( ball_x >= 0.85 ) { if( ball_y > ( players->tail->next->y + 0.35 ) || ball_y < ( players->tail->next->y - 0.35 ) ) { player_queue_second_to_last( players ); game_state = 0; } else { bvx = -0.07; bvy = ball_y - players->tail->next->y; float h = pow( ( pow( bvx, 2 ) + pow( bvy, 2 ) ), 0.5 ) * 100; bvx /= h; bvy /= h; } } ball_x += bvx; ball_y += bvy; } else { tick++; } send_to_all_players( players, create_client_game_state( players->tail->y, players->tail->next->y, ball_x, ball_y ) ); } else { game_state = 0; } } return 0; }
/* ----------------------------------------------------------------------------------- */ void intro_main(){ int8u scene; int8u scene_counter; int8u c; int8u *sour; int8u *dist; basic_init_for_intro(); scene = 0; scene_counter = 240; sour = fopen("map/intro.map"); sour += 32 * (24 + 0) * 2; dist = map_cache; for(c = 32 * 3; c != 0; c--){ *dist++ = *sour++; *dist++ = *sour++; } serif = map_cache; psg_set_bgm(fopen("sound/demo.sn7"), FALSE); while(373){ sprites_clear(); port_read(); if(ports[0].button & BUTTON_AB){ scene_type = SCENE_LOAD; break; } switch(scene){ case 0: ninja_create(0); actors_x[0] = 40; actors_y[0] = 140; actors_angle[0] = ANGLE_RIGHT; scene++; break; case 1: if(actors_x[0] == 116){ ninja_cake_create(0); actors_x[0] = 115; actors_y[0] = 140; actors_angle[0] = ANGLE_RIGHT; scene++; } break; case 2: if(actors_x[0] > 208){ actors_type[0] = ACTOR_NULL; scene_counter = 60; scene++; } break; case 3: if(scene_counter == 0){ player_create(0); actors_x[0] = 40; actors_y[0] = 144; scene++; } break; case 4: /* player go to right */ ports[0].button |= BUTTON_RIGHT; if(actors_x[0] >= 88){ scene_counter = 60; scene++; } break; case 5: if(scene_counter == 0){ serif += 64; scene_counter = 120; scene++; } case 6: if(scene_counter == 0){ serif += 64; scene_counter = 120; scene++; } case 7: if(scene_counter == 0){ return; } } scene_counter--; basic_update_for_intro(); } psg_stop(); }
/* ----------------------------------------------------------------------------------- */ void ending_main(){ int8u actor_no; int8u scene_counter; char *text; int8u text_row; int8u c; actors_clear(); actor_no = ENDING_ACTOR_START; scene_counter = 1; text = ending_text; scroll_y = 0; /* clear bottom 4 rows */ print_init(); for(c = 24; c < 28; c++){ vsync_wait(); store_pattern_name_buffer(c); } psg_set_bgm(fopen("sound/summer.sn7"), TRUE); while(373){ sprites_clear(); port_read(); /* generate text */ text_row = scroll_y >> 3; text_row--; scene_counter--; if(scene_counter == 0){ scene_counter = 255; text_row--; c = print(text, 4); if(c < 2) break; text += c; }else{ print_init(); } /* actors */ if(scene_counter == 1){ if(actor_no <= ENDING_ACTOR_END){ switch(actor_no){ case ACTOR_PLAYER: player_create(0); actors_speed_y[0] = 32 - 32; break; case ACTOR_NINJA: ninja_create(0); break; case ACTOR_NINJA_CAKE: actors_type[0] = ACTOR_NINJA_CAKE; break; case ACTOR_BOAR: boar_create(0); break; case ACTOR_DARUMA: daruma_create(0); break; case ACTOR_TENGU: tengu_create(0); break; case ACTOR_HIME: hime_create(0); break; case ACTOR_BIRD: bird_create(0); break; case ACTOR_FLOG: flog_create(0); break; case ACTOR_GOAST: goast_create(0); actors_y[0] = 192; actors_x[0] = 250; break; case ACTOR_NASU: nasu_create(0); break; } }else{ actors_type[0] = ACTOR_NULL; } actor_no++; } /* scroll */ if(frame_count & 0x01){ scroll_y++; if(scroll_y > 224){ scroll_y = 0; } } /* updates */ actors_update(); vsync_wait(); sprites_store(); store_pattern_name_buffer(text_row); scroll_store(); psg_play(); frame_count++; } psg_stop(); }
static int proto_server_hello_handler(Proto_Session *s){ int rc = 1; int x; Player* p; Proto_Msg_Hdr sh; Proto_Session *us; p = player_create(); bzero(&sh, sizeof(sh)); sh.type = proto_session_hdr_unmarshall_type(s); sh.type += PROTO_MT_REP_BASE_RESERVED_FIRST; x = player_find_empty_home(p,nextTeam, Server_ObjectMap, pidx); // x = !gamefull; if(x){ gamestate_add_player(Server_Gamestate,p); printf("New player joining:\n"); printf("Location: %d,%d\n", p->pcell->x, p->pcell->y); player_dump(p); sh.pstate.v0.raw = 1; sh.pstate.v1.raw = p->id; gamestate_dump(Server_Gamestate); proto_session_body_marshall_gamestate(s,Server_Gamestate); // proto_session_body_marshall_map(s,Server_Map); if(nextTeam == TEAM1){ nextTeam = TEAM2; numPlayers1++; } else{ nextTeam = TEAM1; numPlayers2++; } pidx = player_find_next_id(Server_Gamestate->plist); if(pidx<0) gamefull = 1; s->player = p; } else { sh.pstate.v0.raw = 0; } proto_session_hdr_marshall(s, &sh); // proto_dump_msghdr(&(s->shdr)); rc = proto_session_send_msg(s,1); if(x){ //if new player joining, tell everyone us = proto_server_event_session(); bzero(&sh, sizeof(sh)); sh.type = PROTO_MT_EVENT_BASE_PLAYER_JOIN; sh.pstate.v0.raw = p->id; sh.pstate.v1.raw = p->pcell->x; sh.pstate.v2.raw = p->pcell->y; proto_session_hdr_marshall(us, &sh); proto_session_body_marshall_player(us,p); proto_server_post_event(); } return rc; }
int main(int argc, char *argv[]) { struct options options; clock_t start; bool create_db; GError *error = NULL; bool success; daemonize_close_stdin(); #ifdef HAVE_LOCALE_H /* initialize locale */ setlocale(LC_CTYPE,""); #endif g_set_application_name("Music Player Daemon"); /* enable GLib's thread safety code */ g_thread_init(NULL); winsock_init(); idle_init(); dirvec_init(); songvec_init(); tag_pool_init(); config_global_init(); success = parse_cmdline(argc, argv, &options, &error); if (!success) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } glue_daemonize_init(&options); stats_global_init(); tag_lib_init(); log_init(options.verbose, options.log_stderr); success = listen_global_init(&error); if (!success) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } daemonize_set_user(); main_task = g_thread_self(); main_loop = g_main_loop_new(NULL, FALSE); main_cond = g_cond_new(); event_pipe_init(); event_pipe_register(PIPE_EVENT_IDLE, idle_event_emitted); path_global_init(); glue_mapper_init(); initPermissions(); playlist_global_init(); spl_global_init(); #ifdef ENABLE_ARCHIVE archive_plugin_init_all(); #endif decoder_plugin_init_all(); update_global_init(); create_db = !glue_db_init_and_load(); glue_sticker_init(); command_init(); initialize_decoder_and_player(); volume_init(); initAudioConfig(); audio_output_all_init(); client_manager_init(); replay_gain_global_init(); if (!input_stream_global_init(&error)) { g_warning("%s", error->message); g_error_free(error); return EXIT_FAILURE; } playlist_list_global_init(); daemonize(options.daemon); setup_log_output(options.log_stderr); initSigHandlers(); initZeroconf(); player_create(); if (create_db) { /* the database failed to load: recreate the database */ unsigned job = update_enqueue(NULL, true); if (job == 0) g_error("directory update failed"); } glue_state_file_init(); success = config_get_bool(CONF_AUTO_UPDATE, false); #ifdef ENABLE_INOTIFY if (success && mapper_has_music_directory()) mpd_inotify_init(); #else if (success) g_warning("inotify: auto_update was disabled. enable during compilation phase"); #endif config_global_check(); /* enable all audio outputs (if not already done by playlist_state_restore() */ pc_update_audio(); /* run the main loop */ g_main_loop_run(main_loop); /* cleanup */ g_main_loop_unref(main_loop); #ifdef ENABLE_INOTIFY mpd_inotify_finish(); #endif state_file_finish(); pc_kill(); finishZeroconf(); client_manager_deinit(); listen_global_finish(); playlist_global_finish(); start = clock(); db_finish(); g_debug("db_finish took %f seconds", ((float)(clock()-start))/CLOCKS_PER_SEC); #ifdef ENABLE_SQLITE sticker_global_finish(); #endif g_cond_free(main_cond); event_pipe_deinit(); playlist_list_global_finish(); input_stream_global_finish(); audio_output_all_finish(); volume_finish(); mapper_finish(); path_global_finish(); finishPermissions(); pc_deinit(); command_finish(); update_global_finish(); decoder_plugin_deinit_all(); #ifdef ENABLE_ARCHIVE archive_plugin_deinit_all(); #endif config_global_finish(); tag_pool_deinit(); songvec_deinit(); dirvec_deinit(); idle_deinit(); stats_global_finish(); daemonize_finish(); #ifdef WIN32 WSACleanup(); #endif close_log_files(); return EXIT_SUCCESS; }
int main (int argc, char **argv) { // variables SDL_Surface *screen; // pantalla SDL_Event event; // para los eventos de SDL (teclado y/o mouse) Uint8 *keystates = SDL_GetKeyState(NULL); // para detectar teclas mantenidas presionadas Uint8 salir = 0; // para determinar cuando se cierra la ventana int mouse_x=0, mouse_y=0; // coordenadas del mouse char info1[100]; // texto para mostrar informacion variada linea 1 char info2[100]; // texto para mostrar informacion variada linea 2 short int time; // variable para la hora short int ticks; // variable para mover elementos independiente de los FPS // cargar configuracion struct conf *conf = conf_load(); if (!conf) return EXIT_FAILURE; // verificar a donde nos queremos conectar // se indicó el servidor como 1er parametro if(argc>=2) { free(conf->SERVER); conf->SERVER = malloc(strlen(argv[1])); strcpy(conf->SERVER, argv[1]); } // se indicó el puerto como 2do parametro if(argc>=3) { conf->PORT = atoi(argv[2]); } // conectar al servidor int connection = client_init(conf); if (!connection) return EXIT_FAILURE; // buffer para transferencia entre servidor y cliente char buffer[BUFFER_SIZE]; // obtener id del jugador int playerID = atoi(query("get;id", connection)); // recibir y actualizar configuraciones desde el servidor conf_update(conf, query("get;conf", connection)); // inicializar sistema sdl_init(&screen); // cargar fuente TTF_Font *fuente = ttf_load(FONT_NAME, FONT_SIZE, FONT_STYLE); // cargar todos los posibles objetos de un mapa MapObject *mapobjects = mapobjects_load(screen); if (!mapobjects) return EXIT_FAILURE; // cargar mapa char **map = map_open(conf->MAP); if (!map) return EXIT_FAILURE; // cargar armas Weapon *weapons = weapons_load(); if (!weapons) return EXIT_FAILURE; // crear personaje jugador Player *pj = player_create(playerID, conf->PLAYER_NAME, conf->PLAYER_CHARACTER, screen, weapons, conf); // asignar armas al personaje player_change_weapon(&pj, conf->WEAPON_PRIMARY, 1); player_change_weapon(&pj, conf->WEAPON_SECONDARY, 2); // ubicar personaje en el mapa player_set_position(&pj, map, -1, -1, mapobjects); // informar estado del usuario bzero(buffer, sizeof(buffer)); sprintf(buffer, "info;%s;%s", conf->PLAYER_CHARACTER, conf->PLAYER_NAME); write(connection, buffer, strlen(buffer)); // crear bots y ubicar en el mapa Player *bots = bots_create(screen, weapons, conf); int i; for(i=0; i<conf->BOTS; ++i) { Player *aux = &bots[i]; player_set_position(&aux, map, -1, -1, mapobjects); } // guardar ticks ticks = SDL_GetTicks(); // ciclo infinito para refrescar la imagen de la pantalla while (!salir) { // solicitar informacion de todos los jugadores (menos el mio) char *enemies = query("get;players", connection); // enviar posicion del jugador al servidor sprintf(buffer, "position;%d;%d", (int)(pj->y), (int)(pj->x)); write(connection, buffer, strlen(buffer)); // time time = SDL_GetTicks()/1000; // dibujar mapa map_draw(screen, map, mapobjects, conf->BACKGROUND); // revisar si existen eventos de SDL while (SDL_PollEvent(&event)) { // salir del programa if(event.type==SDL_QUIT) salir = 1; // si se presiona una tecla else if(event.type==SDL_KEYDOWN) { // cambiar a pantalla completa if(event.key.keysym.sym==SDLK_f) SDL_WM_ToggleFullScreen(screen); // salir del juego else if(event.key.keysym.sym==SDLK_ESCAPE) salir = 1; // cambiar arma primaria else if(event.key.keysym.sym>=48&&event.key.keysym.sym<=57) player_change_weapon(&pj, event.key.keysym.sym-48, 1); } // si se mueve el mouse else if(event.type==SDL_MOUSEMOTION) { // guardar coordenadas del mouse mouse_x = event.motion.x; mouse_y = event.motion.y; } // si se presiona el mouse else if(event.type == SDL_MOUSEBUTTONDOWN ) { // guardar coordenadas del mouse mouse_x = event.button.x; mouse_y = event.button.y; // resetear flag de armas disparadas pj->primary->fired = 0; pj->secondary->fired = 0; // si se presiono el boton izquierdo if(event.button.button==SDL_BUTTON_LEFT && pj->primary->ammo) { Mix_PlayChannel(-1, pj->primary->sound, 0); pj->primary->fired = pj->primary->ammo--; } // si se presiono el boton derecho else if(event.button.button==SDL_BUTTON_RIGHT && pj->secondary->ammo) { Mix_PlayChannel(-1, pj->secondary->sound, 0); pj->secondary->fired = pj->secondary->ammo--; } // si se mueve el scroll se cambia el arma principal else if (event.button.button==SDL_BUTTON_WHEELUP) { player_change_weapon(&pj, WEAPON_PREV, 1); } else if (event.button.button==SDL_BUTTON_WHEELDOWN) { player_change_weapon(&pj, WEAPON_NEXT, 1); } // determinar si personaje fue herido if(mouse_x >= pj->x && mouse_x <= pj->x+SPRITE_SIZE && mouse_y >= pj->y && mouse_y <= pj->y+SPRITE_SIZE) { // hacer daño al personaje if(event.button.button==SDL_BUTTON_LEFT && pj->primary->fired) { pj->health -= pj->primary->damage; // reproducir sonido de dolor Mix_PlayChannel(-1, pj->sounds[PLAYER_SOUND_DAMAGED], 0); } else if(event.button.button==SDL_BUTTON_RIGHT && pj->secondary->fired) { pj->health -= pj->secondary->damage; // reproducir sonido de dolor Mix_PlayChannel(-1, pj->sounds[PLAYER_SOUND_DAMAGED], 0); } // si la salud quedo menor o igual a 0 el personaje muere if(pj->health<1) { // incrementar contador de muerte ++pj->dead; pj->health = conf->PLAYER_HEALTH; // descontar vida if(conf->PLAYER_LIFE!=0) { --pj->life; if(pj->life==0) { // GAME OVER } } // reposicionar personaje muerto player_set_position(&pj, map, -1, -1, mapobjects); } } } // si se suelta el mouse else if(event.type==SDL_MOUSEBUTTONUP) { // guardar coordenadas del mouse mouse_x = event.button.x; mouse_y = event.button.y; // si se solto el boton izquierdo if(event.button.button==SDL_BUTTON_LEFT) { } // si se solto el boton derecho else if(event.button.button==SDL_BUTTON_RIGHT) { } } } // mover jugador player_move(&pj, keystates, map, mapobjects, conf, SDL_GetTicks()-ticks); player_get_object(&pj, map, conf); // primera linea informacion sprintf(info1, "time: %02d:%02d, mouse: (%04d,%04d)", time/60, time%60, mouse_x, mouse_y); SDL_Surface *s_info1 = TTF_RenderText_Blended(fuente, info1, (SDL_Color) {255,255,255,255}); SDL_Rect rect = (SDL_Rect) { 10, 0, 100, 20 }; SDL_BlitSurface(s_info1, NULL, screen, &rect); SDL_FreeSurface(s_info1); // segunda linea informacion sprintf(info2, "[%s] +%03d, life: %02d, dead: %02d, weapon: [%d/%03d/%03d] [%d/%03d/%03d]", conf->PLAYER_NAME, pj->health, pj->life, pj->dead, pj->primary->id, pj->primary->damage, pj->primary->ammo, pj->secondary->id, pj->secondary->damage, pj->secondary->ammo); SDL_Surface *s_info2 = TTF_RenderText_Blended(fuente, info2, (SDL_Color) {255,255,255,255}); rect.y += 12; SDL_BlitSurface(s_info2, NULL, screen, &rect); SDL_FreeSurface(s_info2); // dibujar enemigos enemies_draw(screen, enemies); // dibujar bots /*for(i=0; i<conf->BOTS; ++i) { Player *aux = &bots[i]; SDL_BlitSurface(aux->images[PLAYER_IMAGE_SPRITE], &aux->src, screen, &aux->sprite); }*/ // dibujar jugador SDL_BlitSurface(pj->images[PLAYER_IMAGE_SPRITE], &pj->src, screen, &pj->sprite); // actualizar screen sdl SDL_Flip(screen); SDL_Delay(1000/FPS); // resetear ticks ticks = SDL_GetTicks(); } // cerrar conexion al servidor close(connection); // liberar jugador player_free(&pj); // liberar armas weapons_free(&weapons); // libear objetos del mapa mapobjects_free(&mapobjects); // cerrar fuentes TTF_CloseFont(fuente); TTF_Quit(); // cerrar SDL SDL_FreeSurface(screen); SDL_Quit(); // retorno del sistema return EXIT_SUCCESS; }