bool update_game() { int in = get_input(get_map_window()); if(in == INPUT_ACTION && get_last_action() == ACTION_QUIT) return false; else if(in == INPUT_ACTION && (get_last_action() == ACTION_SCROLL_UP || get_last_action() == ACTION_SCROLL_DOWN)) { log_scroll(get_last_action() == ACTION_SCROLL_UP); draw_log(); } else if(!dead) { update_player(); if(get_current_floor() != current_level) { set_current_map(world[get_current_floor()], current_level < get_current_floor(), current_level > get_current_floor()); current_level = get_current_floor(); } update_map(1, world[current_level]); if(is_dead()) { add_message(COLOR_HP_CRIT, "Oh dear, you've died!"); add_message(COLOR_DEFAULT, "Press q to return to the main menu"); dead = true; } if(game_won()) dead = true; draw_log(); } return true; }
int main(object me, string file) { int i; object obj, *inv; string err; mixed files; string dir; string* temp; seteuid( geteuid(me) ); if (!file) file = me->query("cwf"); if (!file) return notify_fail("你要重新编译什麽档案?\n"); if( (obj = present(file, environment(me))) && interactive(obj) ) return update_player(obj); if( file == "me" ) return update_player(me); if (file[strlen(file)-1]=='/') { file = file[0..strlen(file)-2]; dir = resolve_path(me->query("cwd"), file); dir += "/"; } else { dir = resolve_path(me->query("cwd"), file); // write("adir= "+dir+"\n"); if (file_size(dir) > 0) return updatefile(me,dir); else if (file_size(dir+".c") > 0) return updatefile(me,dir+".c"); // write("bdir= "+dir+"\n"); } if( file_size(dir)==-2 && dir[strlen(dir)-1] != '/' ) dir += "/"; // write("cdir= "+dir+"\n"); files = get_dir(dir, -1); if( !sizeof(files) ) { if (file_size(dir) == -2) return notify_fail("目录是空的。\n"); else return notify_fail("没有这个文件或目录。\n"); } if (dir[sizeof(dir)-1]!='/') { temp = explode(dir,"/"); temp -= ({temp[sizeof(temp)-1]});
void tick() { process_events(); update_enemies(); update_towers(); update_player(); }
void update_world(input* in, world* game_world) { collectible* pellet = game_world->pellet; update_player(in, game_world->walls, game_world->num_walls, pellet, game_world->game_player); update_collectible(pellet); if (pellet->used) { random_inbounds_pos(game_world, pellet->pos); reset_collectible(pellet->pos->x, pellet->pos->y, 1, pellet); } }
void GameScene::update(float dt) { for (Entity* d : decorations_) { d->update(dt); } for (Entity* p : platforms_) { p->update(dt); } for (Entity* g : goalflags_) { g->update(dt); } update_effects(dt); for (Entity* c : collectibles_) { c->update(dt); sf::FloatRect bbox(c->collision_area()); if (!c->animation().hidden() && bbox.Intersects(player_.collision_area())) { explode(c,true); collectsnd_.Play(); } } update_player(dt); bool out_of_bounds = true; for (Entity* p : platforms_) { if (vector_magnitude( p->position() - player_.position()) < 1000) { out_of_bounds = false; } } if (out_of_bounds) { init_world(); } update_camera(dt); }
int main () { double prev_time = 0.0; double accum_sim_time = 0.0; if (!start_gl (800, 800)) { fprintf (stderr, "ERROR: could not start opengl\n"); return 1; } init_cam (); init_terrain (); init_dash (); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LESS); glClearColor (0.0, 0.5, 0.5, 1.0); prev_time = glfwGetTime (); while (!glfwWindowShouldClose (gl_window)) { // work out how much time has passed double curr_time = glfwGetTime (); double elapsed = curr_time - prev_time; prev_time = curr_time; accum_sim_time += elapsed; // work out simulation time steps while (accum_sim_time > TIME_STEP_SIZE) { accum_sim_time -= TIME_STEP_SIZE; update_player (TIME_STEP_SIZE); } glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport (0, 0, gl_width, gl_height); draw_terrain (); // i dont want the dashboard to ever intersect with background so // i do a clear of the depth buffer glClear (GL_DEPTH_BUFFER_BIT); draw_dash (); // can expect everything has updated camera matrices by now cam_P_dirty = false; cam_V_dirty = false; glfwPollEvents (); glfwSwapBuffers (gl_window); } return 0; }
void update_game(t_game *game, t_time *time, Uint32 elapse) { read_keyboard(game); update_player(game->player, elapse, time); calculPlayTime(time); if (game->velocityBack < 25) game->velocityBack = 1+((time->playTime / 1020)/8); else game->velocityBack = 25; return; }
void update_world(world_data* world) { if (world->mode != WORLD_PLAY_MODE) { return; } for (auto& i : world->chunks) { update_chests(world, &i.second.chests); update_warps(world, &i.second.warps); update_npcs(world, &i.second.npcs); } update_monsters(world, &world->monsters); update_player(world, &world->player); update_attacks(world); remove_dead_monsters(world); }
void track_handler(uv_idle_t* handle) { int i; luv_game_t *game = handle->data; if (!game->in_progress) return; if (--(game->delay) > 0) return; game->delay = DELAY; luv_server_t *server = game->server; luv_client_t **clients = server->clients; int rand_num = (rand() % MAX_SPEED) + 1; for (i = 0; i < server->num_clients; i++) update_player(rand_num, clients[i]->data); }
int main(object me, string file) { int i; object obj, *inv; string err; seteuid( geteuid(me) ); if (!file) file = me->query("cwf"); if (!file) return notify_fail("─у╥к╓╪╨┬▒р╥ы╩▓ўс╡╡░╕г┐\n"); if( (obj = present(file, environment(me))) && interactive(obj) ) return update_player(obj); if( file == "me" ) return update_player(me); else { file = resolve_path(me->query("cwd"), file); if( !sscanf(file, "%*s.c") ) file += ".c"; } if( file_size(file)==-1 ) return notify_fail("├╗╙╨╒т╕Ў╡╡░╕бг\n"); if (wiz_level(me)<4) return notify_fail("─у╡─╚и╧▐▓╗─▄╓╪╨┬▒р╥ы╬─╝■бг\n"); me->set("cwf", file); if (obj = find_object(file)) { if( obj==environment(me) ) { if( file_name(obj)==VOID_OB ) return notify_fail("─у▓╗─▄╘┌ VOID_OB └я╓╪╨┬▒р╥ы VOID_OBбг\n"); } inv = all_inventory(obj); i = sizeof(inv); while(i--) { if(userp(inv[i])|| inv[i]->query("possessed")) { inv[i]->move(VOID_OB, 1); } else { destruct(inv[i]); } } destruct(obj); } if (obj) return notify_fail("╬▐╖и╟х│¤╛╔│╠╩╜┬ыбг\n"); write("╓╪╨┬▒р╥ы " + file + "г║"); err = catch( call_other(file, "???") ); if (err) printf( "╖в╔·┤э╬єг║\n%s\n", err ); else { write("│╔╣жгб\n"); log_file( "UPDATE_LOG", sprintf("(%s) %s updated %s\n", ctime(time()), me->query("name"), file)); if( (i=sizeof(inv)) && (obj = find_object(file))) { while(i--) { if( inv[i] && (userp(inv[i]) || inv[i]->query("possessed"))) inv[i]->move(obj, 1); } } } return 1; }
/** ********************************************************** * @brief Draws the gems changing location * * This function draws gems changing location * * **********************************************************/ void changing_location(){ SDL_Event event; int i, min, max,temp; SDL_Rect dest, dest_gem; //moving vertically if (game_state.x_first == game_state.x_second) { min = game_state.y_first > game_state.y_second ? game_state.y_second : game_state.y_first; max = game_state.y_first < game_state.y_second ? game_state.y_second : game_state.y_first; dest.x = game_state.x_first*DIAMOND_WIDTH +BOARD_OFFSETX; dest.w = DIAMOND_WIDTH; dest.y = min*DIAMOND_HEIGHT+BOARD_OFFSETY; dest.h = 2*DIAMOND_HEIGHT; dest_gem.x = dest.x; dest_gem.w = DIAMOND_WIDTH; dest_gem.h = DIAMOND_HEIGHT; for(i=0; i<=DIAMOND_HEIGHT; i += 3){ SDL_BlitSurface(bg, &dest, screen, &dest); dest_gem.y = i+min*DIAMOND_HEIGHT+BOARD_OFFSETY; SDL_BlitSurface(diamond[matrix[min][game_state.x_second]], NULL, screen, &dest_gem); dest_gem.y = max*DIAMOND_HEIGHT+BOARD_OFFSETY-i; SDL_BlitSurface(diamond[matrix[max][game_state.x_first]], NULL, screen, &dest_gem); //drawing the selection dest_gem.w = 0; dest_gem.h = 0; dest_gem.x = game_state.x_first * DIAMOND_WIDTH + BOARD_OFFSETX; dest_gem.y = game_state.y_first * DIAMOND_HEIGHT + BOARD_OFFSETY; SDL_BlitSurface(selection, NULL, screen, &dest_gem); dest_gem.y = game_state.y_second * DIAMOND_HEIGHT + BOARD_OFFSETY; SDL_BlitSurface(selection, NULL, screen, &dest_gem); SDL_Update(dest.x, dest.y,dest.w,dest.h); update_player(); time_tick(); } temp=matrix[max][game_state.x_first]; matrix[max][game_state.x_first]=matrix[min][game_state.x_second]; matrix[min][game_state.x_second]=temp; } //moving horizontally else { min = game_state.x_first > game_state.x_second ? game_state.x_second : game_state.x_first; max = game_state.x_first < game_state.x_second ? game_state.x_second : game_state.x_first; dest.x = min*DIAMOND_WIDTH +BOARD_OFFSETX; dest.w = 2*DIAMOND_WIDTH; dest.y = game_state.y_first*DIAMOND_HEIGHT+BOARD_OFFSETY; dest.h = DIAMOND_HEIGHT; dest_gem.y = dest.y; dest_gem.w = DIAMOND_WIDTH; dest_gem.h = DIAMOND_HEIGHT; for(i=0; i<=DIAMOND_HEIGHT; i += 3){ SDL_BlitSurface(bg, &dest, screen, &dest); dest_gem.x = i+min*DIAMOND_WIDTH+BOARD_OFFSETX; SDL_BlitSurface(diamond[matrix[game_state.y_second][min]], NULL, screen, &dest_gem); dest_gem.x = max*DIAMOND_WIDTH+BOARD_OFFSETX-i; SDL_BlitSurface(diamond[matrix[game_state.y_first][max]], NULL, screen, &dest_gem); //drawing the selection dest_gem.w = 0; dest_gem.h = 0; dest_gem.x = game_state.x_first * DIAMOND_WIDTH + BOARD_OFFSETX; dest_gem.y = game_state.y_first * DIAMOND_HEIGHT + BOARD_OFFSETY; SDL_BlitSurface(selection, NULL, screen, &dest_gem); dest_gem.x = game_state.x_second * DIAMOND_WIDTH + BOARD_OFFSETX; SDL_BlitSurface(selection, NULL, screen, &dest_gem); SDL_Update(dest.x, dest.y,dest.w,dest.h); update_player(); time_tick(); } temp=matrix[game_state.y_first][max]; matrix[game_state.y_first][max]=matrix[game_state.y_second][min]; matrix[game_state.y_second][min]=temp; } while (SDL_PollEvent(&event)); }
int main(void) { PlayerState player_state_0, player_state_1; SDL_Event event; SDL_Renderer *renderer; SDL_Window *window; double current_time_s, last_tick_time_s; unsigned int frequency_divider_counter, player_move_frequency_divider; unsigned int current_time, last_time; SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_WIDTH, 0, &window, &renderer); SDL_SetWindowTitle(window, "asdw: move red | jkli: move blue | space: move faster | esc: restart | q: quit"); main_loop: init_state( &player_state_0, &player_state_1, &last_tick_time_s, &frequency_divider_counter, &player_move_frequency_divider ); while (1) { while (SDL_PollEvent(&event) == 1) { if (event.type == SDL_QUIT) { goto quit; } else if (event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_ESCAPE: goto main_loop; case SDLK_q: goto quit; default: break; } } } const Uint8 *keystate = SDL_GetKeyboardState(NULL); if (keystate[SDL_SCANCODE_SPACE]) { player_move_frequency_divider = FAST_FREQUENCY_DIVIDER; } else { player_move_frequency_divider = NORMAL_FREQUENCY_DIVIDER; } /* Player 0. */ player_state_0.speed_x = 0; player_state_0.speed_y = 0; if (keystate[SDL_SCANCODE_A]) { player_state_0.speed_x = -1; } if (keystate[SDL_SCANCODE_D]) { player_state_0.speed_x = 1; } if (keystate[SDL_SCANCODE_W]) { player_state_0.speed_y = -1; } if (keystate[SDL_SCANCODE_S]) { player_state_0.speed_y = 1; } /* Player 1. */ player_state_1.speed_x = 0; player_state_1.speed_y = 0; if (keystate[SDL_SCANCODE_J]) { player_state_1.speed_x = -1; } if (keystate[SDL_SCANCODE_L]) { player_state_1.speed_x = 1; } if (keystate[SDL_SCANCODE_I]) { player_state_1.speed_y = -1; } if (keystate[SDL_SCANCODE_K]) { player_state_1.speed_y = 1; } current_time = SDL_GetTicks(); current_time_s = current_time / 1000.0; if (current_time != last_time) { if (current_time_s - last_tick_time_s > FASTEST_TICK_PERIOD_S) { /* Draw world. */ SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); SDL_RenderClear(renderer); draw_player( &player_state_0, renderer, 255, 0, 0 ); draw_player( &player_state_1, renderer, 0, 0, 255 ); SDL_RenderPresent(renderer); /* Update state. */ if (frequency_divider_counter % GRAVITY_FREQUENCY_DIVIDER == 0) { player_state_0.speed_y += 1; player_state_1.speed_y += 1; } if (frequency_divider_counter % player_move_frequency_divider == 0) { update_player(&player_state_0); update_player(&player_state_1); } /* Update time tracking. */ last_tick_time_s = current_time_s; frequency_divider_counter++; if (frequency_divider_counter == MCD_FREQUENCY_DIVIDER) frequency_divider_counter = 0; /* Ticks per second. Equls 1 / FASTEST_TICK_PERIOD_S if no processing is done. */ common_fps_update_and_print(); } } last_time = current_time; } quit: SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (argc == 2 || argc == 3) { char *hostname = argv[1]; int port = DEFAULT_PORT; if (argc == 3) { port = atoi(argv[2]); } db_disable(); client_enable(); client_connect(hostname, port); client_start(); } if (!glfwInit()) { return -1; } create_window(); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(VSYNC); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, on_key); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); load_png_texture("texture.png"); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); GLuint item_position_buffer = 0; GLuint item_normal_buffer = 0; GLuint item_uv_buffer = 0; int previous_block_type = 0; Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; Player players[MAX_PLAYERS]; int player_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; double px = 0; double py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetCursorPos(window, &px, &py); double previous = glfwGetTime(); while (!glfwWindowShouldClose(window)) { update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive && (px || py)) { double mx, my; glfwGetCursorPos(window, &mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetCursorPos(window, &px, &py); } int sz = 0; int sx = 0; ortho = glfwGetKey(window, 'F'); fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0; if (glfwGetKey(window, 'Q')) break; if (glfwGetKey(window, 'W')) sz--; if (glfwGetKey(window, 'S')) sz++; if (glfwGetKey(window, 'A')) sx--; if (glfwGetKey(window, 'D')) sx++; float m = dt * 1.0; if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m; if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m; if (glfwGetKey(window, GLFW_KEY_UP)) ry += m; if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m; float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); if (glfwGetKey(window, GLFW_KEY_SPACE)) { if (flying) { vy = 1; } else if (dy == 0) { dy = 8; } } if (glfwGetKey(window, 'Z')) { vx = -1; vy = 0; vz = 0; } if (glfwGetKey(window, 'X')) { vx = 1; vy = 0; vz = 0; } if (glfwGetKey(window, 'C')) { vx = 0; vy = -1; vz = 0; } if (glfwGetKey(window, 'V')) { vx = 0; vy = 1; vz = 0; } if (glfwGetKey(window, 'B')) { vx = 0; vy = 0; vz = -1; } if (glfwGetKey(window, 'N')) { vx = 0; vy = 0; vz = 1; } float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } if (y < 0) { y = highest_block(chunks, chunk_count, x, z) + 2; } for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; chunk->dirty = 0; } if (left_click) { left_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (hy > 0 && is_destructable(hw)) { set_block(chunks, chunk_count, hx, hy, hz, 0, 1); } } if (right_click) { right_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type, 1); } } } if (middle_click) { middle_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_selectable(hw)) { block_type = hw; } } if (teleport) { teleport = 0; if (player_count) { int index = rand_int(player_count); Player *player = players + index; x = player->x; y = player->y; z = player->z; rx = player->rx; ry = player->ry; ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); } } client_position(x, y, z, rx, ry); char buffer[RECV_BUFFER_SIZE]; while (client_recv(buffer, RECV_BUFFER_SIZE)) { float ux, uy, uz, urx, ury; if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f", &ux, &uy, &uz, &urx, &ury) == 5) { x = ux; y = uy; z = uz; rx = urx; ry = ury; ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); y = highest_block(chunks, chunk_count, x, z) + 2; } int bx, by, bz, bw; if (sscanf(buffer, "B,%*d,%*d,%d,%d,%d,%d", &bx, &by, &bz, &bw) == 4) { set_block(chunks, chunk_count, bx, by, bz, bw, 0); if ((int)roundf(x) == bx && (int)roundf(z) == bz) { y = highest_block(chunks, chunk_count, x, z) + 2; } } int pid; float px, py, pz, prx, pry; if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f", &pid, &px, &py, &pz, &prx, &pry) == 6) { Player *player = find_player(players, player_count, pid); if (!player && player_count < MAX_PLAYERS) { player = players + player_count; player_count++; player->id = pid; player->position_buffer = 0; player->normal_buffer = 0; player->uv_buffer = 0; printf("%d other players are online\n", player_count); } if (player) { update_player(player, px, py, pz, prx, pry); } } if (sscanf(buffer, "D,%d", &pid) == 1) { delete_player(players, &player_count, pid); printf("%d other players are online\n", player_count); } } for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk->dirty) { update_chunk(chunk); } } int p = floorf(roundf(x) / CHUNK_SIZE); int q = floorf(roundf(z) / CHUNK_SIZE); ensure_chunks(chunks, &chunk_count, p, q, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); update_matrix_3d(matrix, x, y, z, rx, ry); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (!chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render players for (int i = 0; i < player_count; i++) { Player *player = players + i; draw_player(player, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; int hw = hit_test( chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint cube_buffer = make_cube_buffer(hx, hy, hz, 0.51); draw_lines(cube_buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &cube_buffer); glDisable(GL_COLOR_LOGIC_OP); } update_matrix_2d(matrix); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint line_buffer = make_line_buffer(); draw_lines(line_buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &line_buffer); glDisable(GL_COLOR_LOGIC_OP); // render selected item update_matrix_item(matrix); if (block_type != previous_block_type) { previous_block_type = block_type; make_single_cube( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, 0, 0, 5); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); glDisable(GL_DEPTH_TEST); draw_single_cube( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); glEnable(GL_DEPTH_TEST); glfwSwapBuffers(window); glfwPollEvents(); } client_stop(); db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }
int main (int argc, char* args[]) { //SDL Window setup if (init(SCREEN_WIDTH, SCREEN_HEIGHT) == 1) { return 0; } int i = 0; int j = 0; int offset = 0; struct vector2d translation = {-SCREEN_WIDTH / 2, -SCREEN_HEIGHT / 2}; //set up icons used to represent player lives for (i = 0; i < LIVES; i++) { init_player(&lives[i]); lives[i].lives = 1; //shrink lives for (j = 0; j < P_VERTS; j++) { divide_vector(&lives[i].obj_vert[j], 2); } //convert screen space vector into world space struct vector2d top_left = {20 + offset, 20}; add_vector(&top_left, &translation); lives[i].location = top_left; update_player(&lives[i]); offset += 20; } //set up player and asteroids in world space init_player(&p); init_asteroids(asteroids, ASTEROIDS); int sleep = 0; int quit = 0; SDL_Event event; Uint32 next_game_tick = SDL_GetTicks(); //render loop while(quit == 0) { //check for new events every frame SDL_PumpEvents(); const Uint8 *state = SDL_GetKeyboardState(NULL); if (state[SDL_SCANCODE_ESCAPE]) { quit = 1; } if (state[SDL_SCANCODE_UP]) { struct vector2d thrust = get_direction(&p); multiply_vector(&thrust, .06); apply_force(&p.velocity, thrust); } if (state[SDL_SCANCODE_LEFT]) { rotate_player(&p, -4); } if (state[SDL_SCANCODE_RIGHT]) { rotate_player(&p, 4); } while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_SPACE: if (p.lives > 0) { shoot_bullet(&p); } break; } } } //draw to the pixel buffer clear_pixels(pixels, 0x00000000); draw_player(pixels, &p); draw_player(pixels, &lives[0]); draw_player(pixels, &lives[1]); draw_player(pixels, &lives[2]); draw_asteroids(pixels, asteroids, ASTEROIDS); update_player(&p); bounds_player(&p); bounds_asteroids(asteroids, ASTEROIDS); int res = collision_asteroids(asteroids, ASTEROIDS, &p.location, p.hit_radius); if (res != -1) { p.lives--; p.location.x = 0; p.location.y = 0; p.velocity.x = 0; p.velocity.y = 0; int i = LIVES - 1; for ( i = LIVES; i >= 0; i--) { if(lives[i].lives > 0) { lives[i].lives = 0; break; } } } int i = 0; struct vector2d translation = {-SCREEN_WIDTH / 2, -SCREEN_HEIGHT / 2}; for (i = 0; i < BULLETS; i++) { //only check for collision for bullets that are shown on screen if (p.bullets[i].alive == TRUE) { //convert bullet screen space location to world space to compare //with asteroids world space to detect a collision struct vector2d world = add_vector_new(&p.bullets[i].location, &translation); int index = collision_asteroids(asteroids, ASTEROIDS, &world, 1); //collision occured if (index != -1) { asteroids[index].alive = 0; p.bullets[i].alive = FALSE; if (asteroids[index].size != SMALL) { spawn_asteroids(asteroids, ASTEROIDS, asteroids[index].size, asteroids[index].location); } } } } update_asteroids(asteroids, ASTEROIDS); //draw buffer to the texture representing the screen SDL_UpdateTexture(screen, NULL, pixels, SCREEN_WIDTH * sizeof (Uint32)); //draw to the screen SDL_RenderClear(renderer); SDL_RenderCopy(renderer, screen, NULL, NULL); SDL_RenderPresent(renderer); //time it takes to render 1 frame in milliseconds next_game_tick += 1000 / 60; sleep = next_game_tick - SDL_GetTicks(); if( sleep >= 0 ) { SDL_Delay(sleep); } } //free the screen buffer free(pixels); //Destroy window SDL_DestroyWindow(window); //Quit SDL subsystems SDL_Quit(); return 0; }
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (argc == 2 || argc == 3) { char *hostname = argv[1]; int port = DEFAULT_PORT; if (argc == 3) { port = atoi(argv[2]); } db_disable(); client_enable(); client_connect(hostname, port); client_start(); } if (!glfwInit()) { return -1; } create_window(); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(VSYNC); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, on_key); glfwSetCharCallback(window, on_char); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); load_png_texture("texture.png"); GLuint font; glGenTextures(1, &font); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, font); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); load_png_texture("font.png"); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); GLuint text_program = load_program( "shaders/text_vertex.glsl", "shaders/text_fragment.glsl"); GLuint text_matrix_loc = glGetUniformLocation(text_program, "matrix"); GLuint text_sampler_loc = glGetUniformLocation(text_program, "sampler"); GLuint text_position_loc = glGetAttribLocation(text_program, "position"); GLuint text_uv_loc = glGetAttribLocation(text_program, "uv"); GLuint item_position_buffer = 0; GLuint item_normal_buffer = 0; GLuint item_uv_buffer = 0; int previous_block_type = 0; char messages[MAX_MESSAGES][TEXT_BUFFER_SIZE] = {0}; int message_index = 0; Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; Player players[MAX_PLAYERS]; int player_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; double px = 0; double py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, x, y, z, 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetCursorPos(window, &px, &py); double previous = glfwGetTime(); while (!glfwWindowShouldClose(window)) { int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive && (px || py)) { double mx, my; glfwGetCursorPos(window, &mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetCursorPos(window, &px, &py); } int sz = 0; int sx = 0; if (!typing) { float m = dt * 1.0; ortho = glfwGetKey(window, CRAFT_KEY_ORTHO); fov = glfwGetKey(window, CRAFT_KEY_ZOOM) ? 15.0 : 65.0; if (glfwGetKey(window, CRAFT_KEY_QUIT)) break; if (glfwGetKey(window, CRAFT_KEY_FORWARD)) sz--; if (glfwGetKey(window, CRAFT_KEY_BACKWARD)) sz++; if (glfwGetKey(window, CRAFT_KEY_LEFT)) sx--; if (glfwGetKey(window, CRAFT_KEY_RIGHT)) sx++; if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m; if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m; if (glfwGetKey(window, GLFW_KEY_UP)) ry += m; if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m; } float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); if (!typing) { if (glfwGetKey(window, CRAFT_KEY_JUMP)) { if (flying) { vy = 1; } else if (dy == 0) { dy = 8; } } if (glfwGetKey(window, CRAFT_KEY_XM)) { vx = -1; vy = 0; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_XP)) { vx = 1; vy = 0; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_YM)) { vx = 0; vy = -1; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_YP)) { vx = 0; vy = 1; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_ZM)) { vx = 0; vy = 0; vz = -1; } if (glfwGetKey(window, CRAFT_KEY_ZP)) { vx = 0; vy = 0; vz = 1; } } float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } if (y < 0) { y = highest_block(chunks, chunk_count, x, z) + 2; } if (left_click) { left_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (hy > 0 && is_destructable(hw)) { set_block(chunks, chunk_count, hx, hy, hz, 0); int above = get_block(chunks, chunk_count, hx, hy + 1, hz); if (is_plant(above)) { set_block(chunks, chunk_count, hx, hy + 1, hz, 0); } } } if (right_click) { right_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type); } } } if (middle_click) { middle_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_selectable(hw)) { block_type = hw; } } if (teleport) { teleport = 0; if (player_count) { int index = rand_int(player_count); Player *player = players + index; x = player->x; y = player->y; z = player->z; rx = player->rx; ry = player->ry; ensure_chunks(chunks, &chunk_count, x, y, z, 1); } } client_position(x, y, z, rx, ry); char buffer[RECV_BUFFER_SIZE]; while (client_recv(buffer, RECV_BUFFER_SIZE)) { float ux, uy, uz, urx, ury; if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f", &ux, &uy, &uz, &urx, &ury) == 5) { x = ux; y = uy; z = uz; rx = urx; ry = ury; ensure_chunks(chunks, &chunk_count, x, y, z, 1); y = highest_block(chunks, chunk_count, x, z) + 2; } int bp, bq, bx, by, bz, bw; if (sscanf(buffer, "B,%d,%d,%d,%d,%d,%d", &bp, &bq, &bx, &by, &bz, &bw) == 6) { _set_block(chunks, chunk_count, bp, bq, bx, by, bz, bw); if (player_intersects_block(2, x, y, z, bx, by, bz)) { y = highest_block(chunks, chunk_count, x, z) + 2; } } int pid; float px, py, pz, prx, pry; if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f", &pid, &px, &py, &pz, &prx, &pry) == 6) { Player *player = find_player(players, player_count, pid); if (!player && player_count < MAX_PLAYERS) { player = players + player_count; player_count++; player->id = pid; player->position_buffer = 0; player->normal_buffer = 0; player->uv_buffer = 0; } if (player) { update_player(player, px, py, pz, prx, pry); } } if (sscanf(buffer, "D,%d", &pid) == 1) { delete_player(players, &player_count, pid); } if (buffer[0] == 'T' && buffer[1] == ',') { char *text = buffer + 2; printf("%s\n", text); snprintf( messages[message_index], TEXT_BUFFER_SIZE, "%s", text); message_index = (message_index + 1) % MAX_MESSAGES; } } int p = chunked(x); int q = chunked(z); ensure_chunks(chunks, &chunk_count, x, y, z, 0); // RENDER 3-D SCENE // glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); set_matrix_3d(matrix, width, height, x, y, z, rx, ry, fov, ortho); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (y < 100 && !chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render players for (int i = 0; i < player_count; i++) { Player *player = players + i; draw_player(player, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; int hw = hit_test( chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint wireframe_buffer = gen_wireframe_buffer(hx, hy, hz, 0.51); draw_lines(wireframe_buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &wireframe_buffer); glDisable(GL_COLOR_LOGIC_OP); } // RENDER 2-D HUD PARTS // glClear(GL_DEPTH_BUFFER_BIT); set_matrix_2d(matrix, width, height); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint crosshair_buffer = gen_crosshair_buffer(width, height); draw_lines(crosshair_buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &crosshair_buffer); glDisable(GL_COLOR_LOGIC_OP); // render text glUseProgram(text_program); glUniformMatrix4fv(text_matrix_loc, 1, GL_FALSE, matrix); glUniform1i(text_sampler_loc, 1); char text_buffer[1024]; float ts = 12; float tx = ts / 2; float ty = height - ts; snprintf( text_buffer, 1024, "%d, %d, %.2f, %.2f, %.2f [%d, %d]", p, q, x, y, z, player_count, chunk_count); print( text_position_loc, text_uv_loc, tx, ty, ts, text_buffer); for (int i = 0; i < MAX_MESSAGES; i++) { int index = (message_index + i) % MAX_MESSAGES; if (strlen(messages[index])) { ty -= ts * 2; print( text_position_loc, text_uv_loc, tx, ty, ts, messages[index]); } } if (typing) { ty -= ts * 2; snprintf(text_buffer, 1024, "> %s", typing_buffer); print( text_position_loc, text_uv_loc, tx, ty, ts, text_buffer); } // RENDER 3-D HUD PARTS // set_matrix_item(matrix, width, height); // render selected item if (block_type != previous_block_type) { previous_block_type = block_type; if (is_plant(block_type)) { gen_plant_buffers( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } else { gen_cube_buffers( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } } glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, 0, 0, 5); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); if (is_plant(block_type)) { draw_plant( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); } else { draw_cube( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); } // swap buffers glfwSwapBuffers(window); glfwPollEvents(); } client_stop(); db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }
int main(int argc, char** argv) { if(!glfwInit()) { error("Failed to intialize GLFW."); return 1; } GLFWwindow* win; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); win = glfwCreateWindow(800, 600, "Halberd", NULL, NULL); if(!win) { error("Unable to create window."); return 1; } glfwSetFramebufferSizeCallback(win, sizeCallback); glfwMakeContextCurrent(win); glewExperimental = 1; if(glewInit() != GLEW_OK) { error("glewInit() failed."); glfwDestroyWindow(win); return 1; } glGetError(); // Because GLEW is silly. <http://stackoverflow.com/questions/20034615/why-does-glewinit-result-in-gl-invalid-enum-after-making-some-calls-to-glfwwin> GLuint VAO; // FIXME: Stupid Hack. <http://stackoverflow.com/questions/13403807/glvertexattribpointer-raising-gl-invalid-operation> glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); init_graphics(); update_camera(800, 600); init_input(win); init_player(0, 0); init_ui(); init_settings(); /*init_maps();*/ // TODO: Figure out the correct way to start up /*get_tileset_id("Plains.png");*/ /*load_maps("test");*/ float delta = 0; glfwSetTime(0); do { delta = glfwGetTime(); glfwSetTime(0); glfwPollEvents(); if(!ui_present()) update_player(delta); update_actors(delta); update_ui(delta); update_input_states(delta); render_game(); glfwSwapBuffers(win); } while(!glfwWindowShouldClose(win) && get_input_state(4) != 2); destroy_player_actor(); destroy_actors(); /*destroy_maps();*/ destroy_ui(); destroy_graphics(); cleanup_settings(); glfwDestroyWindow(win); glfwTerminate(); return 0; }
int main(object me, string file) { int i; object obj, *inv; string err; seteuid( geteuid(me) ); if (!file) file = me->query("cwf"); if (!file) return notify_fail("你要重新编译什么档案?\n"); if( (obj = present(file, environment(me))) && interactive(obj) ) { if(wizardp(obj) && wiz_level(me) < wiz_level(obj)) return notify_fail("你不能更新等级比你高的巫师状态。\n"); return update_player(obj); } if( file == "me" ) return update_player(me); else { file = resolve_path(me->query("cwd"), file); if( !sscanf(file, "%*s.c") ) file += ".c"; } if( file_size(file)==-1 ) return notify_fail("没有这个档案。\n"); me->set("cwf", file); if (obj = find_object(file)) { if( obj==environment(me) ) { if( file_name(obj)==VOID_OB ) return notify_fail("你不能在 VOID_OB 里重新编译 VOID_OB。\n"); inv = all_inventory(obj); i = sizeof(inv); while(i--) if( userp(inv[i]) ) inv[i]->move(VOID_OB, 1); else inv[i] = 0; } destruct(obj); } if (obj) return notify_fail("无法清除旧程式码。\n"); write("重新编译 " + file + ":"); err = catch( call_other(file, "???") ); if (err) printf( "发生错误:\n%s\n", err ); else { write("成功!\n"); log_file("/static/update", sprintf("%s(%s) update %s on %s\n", me->name(1), geteuid(me), file, ctime(time()) ) ); if( (i=sizeof(inv)) && (obj = find_object(file))) { while(i--) if( inv[i] && userp(inv[i]) ) inv[i]->move(obj, 1); } } return 1; }
/* the main game function */ static int play_game() { ALLEGRO_TIMER *inc_counter; int gameover = 0; int cyclenum = 0; /* init */ score = 0; init_view(); init_player(); init_badguys(); init_bullets(); init_explode(); init_message(); #define TIMER_SPEED ALLEGRO_BPS_TO_SECS(30*(cyclenum+2)) inc_counter = al_create_timer(TIMER_SPEED); al_start_timer(inc_counter); while (!gameover) { /* move everyone */ while ((al_get_timer_count(inc_counter) > 0) && (!gameover)) { update_view(); update_bullets(); update_explode(); update_message(); if (update_badguys()) { if (advance_view()) { cyclenum++; al_set_timer_count(inc_counter, 0); lay_attack_wave(TRUE); advance_player(TRUE); } else { lay_attack_wave(FALSE); advance_player(FALSE); } } gameover = update_player(); al_set_timer_count(inc_counter, al_get_timer_count(inc_counter)-1); } /* take a screenshot? */ if (key[ALLEGRO_KEY_PRINTSCREEN]) { static int ss_count = 0; char fname[80]; sprintf(fname, "speed%03d.tga", ++ss_count); al_save_bitmap(fname, al_get_backbuffer(screen)); while (key[ALLEGRO_KEY_PRINTSCREEN]) poll_input_wait(); al_set_timer_count(inc_counter, 0); } /* toggle fullscreen window */ if (key[ALLEGRO_KEY_F]) { int flags = al_get_display_flags(screen); al_set_display_flag(screen, ALLEGRO_FULLSCREEN_WINDOW, !(flags & ALLEGRO_FULLSCREEN_WINDOW)); while (key[ALLEGRO_KEY_F]) poll_input_wait(); } /* draw everyone */ draw_view(); } /* cleanup */ al_destroy_timer(inc_counter); shutdown_view(); shutdown_player(); shutdown_badguys(); shutdown_bullets(); shutdown_explode(); shutdown_message(); if (gameover < 0) { sfx_ping(1); return FALSE; } return TRUE; }
void run_play() { sp1_ClearRectInv(&cr, BRIGHT | INK_WHITE | PAPER_BLACK, 32, SP1_RFLAG_TILE | SP1_RFLAG_COLOUR); sp1_UpdateNow(); sp1_SetPrintPos(&ps0, 0, 0); sp1_PrintString(&ps0, ptiles); // setup the game sprites[PLAYER].x = 15 * 8; sprites[PLAYER].y = 20 * 8; sprites[PLAYER].frame = 0; sprites[PLAYER].delay = 0; sprites[PLAYER].sprite = player; update_player(); horde_count = 0; wave_delay = 0; wave = 0; score = 0; lives = 3; invulnerable = 0; update_score(); while(1) { // TODO: pause/resume if (in_inkey() == 12) // exit current game break; key = (joyfunc)(&joy_k); if (key & IN_STICK_LEFT && !(key & IN_STICK_RIGHT)) { if (sprites[PLAYER].x - 4 > ORIGINX) { sprites[PLAYER].x -= 4; sprites[PLAYER].frame = 2; sprites[PLAYER].delay = 4; update_player(); } } if (key & IN_STICK_RIGHT && !(key & IN_STICK_LEFT)) { if (sprites[PLAYER].x + 16 + 8 + 4 < WIDTH) { sprites[PLAYER].x += 4; sprites[PLAYER].frame = 1; sprites[PLAYER].delay = 4; update_player(); } } if (cooldown > 0) --cooldown; if (key & IN_STICK_FIRE && !cooldown) { // fire rate cooldown = 10; add_bullet(ST_BULLET, sprites[PLAYER].x + 4, sprites[PLAYER].y - 2); playfx(FX_FIRE); } // change the frame to normal? if (sprites[PLAYER].delay) { if (!--sprites[PLAYER].delay) { sprites[PLAYER].frame = 0; update_player(); } } update_horde(); update_sprites(); update_script(); if (invulnerable > 0) { // will be 0, but in case of "the unexpected" if (lives <= 0) { // GAME OVER // some noise playfx(FX_EXPLO); playfx(FX_EXPLO); playfx(FX_EXPLO); // we don't want the player to miss the game over music in_wait_nokey(); sp1_SetPrintPos(&ps0, 11, 8); sp1_PrintString(&ps0, "\x14\x46" "G A M E O V E R"); sp1_UpdateNow(); dzx7_standard(song2, TEMPMEM); ntropic_play(TEMPMEM, 0); for (i = 0; i < 32; ++i) wait(); // leave the game break; } --invulnerable; update_player(); } wait(); intrinsic_halt(); // inline halt without impeding optimizer sp1_UpdateNow(); } destroy_type_sprite(ST_ALL); collect_sprites(); // the player sprite is never destroyed, so hide it sp1_MoveSprAbs(sprites[PLAYER].s, &cr, NULL, 0, 34, 0, 0); sp1_UpdateNow(); sp1_ClearRectInv(&cr, BRIGHT | INK_BLACK | PAPER_BLACK, 32, SP1_RFLAG_TILE | SP1_RFLAG_COLOUR); sp1_UpdateNow(); }
void loop(s4 &game_state) { ICameraSceneNode* camera = irrlicht->smgr->addCameraSceneNode(); matrix4 ortho; ortho.buildProjectionMatrixOrthoLH( irrlicht->driver->getScreenSize().Width/ortho_scale, irrlicht->driver->getScreenSize().Height/ortho_scale,-1.0,1000.0); camera->setProjectionMatrix(ortho); camera->setPosition({0,0,-100}); camera->setTarget({0,0,0}); irrlicht->hud->setActiveCamera(camera); IBillboardSceneNode* qnode = irrlicht->smgr->addBillboardSceneNode(); qnode->setMaterialFlag(EMF_WIREFRAME,true); // -------------------------------------- p("---- Game loop start ----"); d32 dt = 0.0f; const d32 maxDelta = 1.0f/60.0f * 5.0f; const d32 tick_ms = 0.01666f; // TODO: change this back to 30ms? d32 render_dt = 0.0f; const d32 render_ms = RENDER_TIME_STEP; uint32 time_physics_prev = btclock->getTimeMicroseconds(); while(irrlicht->device->run() && game_state == GAME_STATE_PLAY) { const uint32 time_physics_curr = btclock->getTimeMicroseconds(); const d32 frameTime = ((d32)(time_physics_curr - time_physics_prev)) / 1000000.0; // todo: is this truncated correctly? time_physics_prev = time_physics_curr; d32 capped_dt = frameTime; if (capped_dt > maxDelta) { capped_dt = maxDelta; } render_dt += capped_dt; if ( render_dt >= render_ms ) { render_dt = 0.0f; update_player(); update_enemies(); update_missiles(ply->missiles,ply->num_missile); irrlicht->hud->getRootSceneNode()->setPosition(camera->getPosition() + vector3df(0,0,100)); irrlicht->driver->beginScene(true, true, SColor(255,59,120,140)); irrlicht->smgr->drawAll(); irrlicht->driver->clearZBuffer(); irrlicht->hud->drawAll(); irrlicht->driver->endScene(); } dt += capped_dt; while( dt >= tick_ms ) { dt -= tick_ms; receiver->input(); clear_quads(quadtree); step_player(); step_enemies(); step_missiles(ply->missiles, ply->num_missile); QuadTree::Quad* fq = get_quad_from_pos(quadtree,ply->curr_pos); qnode->setSize(dimension2d<f32>(1,1)); qnode->setPosition(fq->pos.irr()); qnode->setSize(dimension2d<f32>(fq->width,fq->width)); if (receiver->debug_key.state) { for (s4 i = 0; i < fleet->num_squad; i++) { if (fleet->squads[i].mode != scatter) fleet->squads[i].mode = scatter; else fleet->squads[i].mode = to_positions; } } if (receiver->restart.state) { game_state = GAME_STATE_RESET; return; } if (receiver->QUIT) { game_state = GAME_STATE_QUIT; return; } empty_transient_soft(memory); } alpha = dt / tick_ms; core::stringw str = L"Coquelicot // score: "; str += score; str += L" // FPS: "; str += (s32)irrlicht->driver->getFPS(); irrlicht->device->setWindowCaption(str.c_str()); } }
// Main loop the game int game_loop() { SDL_Rect dest; int x, y, aux; SDL_Event event; unsigned long t1, t2; int no_unselect = 0; // Main loop t1 = SDL_GetTicks(); while (1) { // Restart the game if (game_state.state == NEW_GAME){ if (gm == GM_MULTIPLAYER) { aux = BOARD_RESTARTED; write_socket(&aux, sizeof(int)); new_game(false, GM_MULTIPLAYER, false); } else { new_game(false, GM_SINGLE, false); } } else if (game_state.state == GAME_LOSE || game_state.state == GAME_WIN || game_state.state == GAME_EXIT) { if (gm == GM_MULTIPLAYER) { if (game_state.state == GAME_EXIT) { aux = END_GAME; write_socket(&aux, sizeof(int)); } finish_attack(game_state.state == GAME_WIN); } dest.x = 386; dest.y = 151; dest.w = dest.h = 0; if (game_state.state != GAME_EXIT) { SDL_BlitSurface(game_state.state == GAME_WIN ? win : lose, NULL, screen, &dest); SDL_Update(386, 151, 365, 178); SDL_Delay(4000); } return (game_state.state == GAME_LOSE); } if (SDL_PollEvent(&event)) { switch (event.type) { // Key pressed case SDL_KEYDOWN: if (event.key.state == SDL_PRESSED) { // Quit if (event.key.keysym.sym == SDLK_ESCAPE || event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_F4 || event.key.keysym.sym == SDLK_F5 || event.key.keysym.sym == SDLK_F6) { game_state.state = GAME_EXIT; } } // Quit the game case SDL_QUIT: game_state.state = GAME_EXIT; break; // Window focus change #if 0 case SDL_ACTIVEEVENT: if (event.active.gain == 0 && gm != GM_MULTIPLAYER) { game_state.state = GAME_EXIT; } break; #endif // Button pressed case SDL_MOUSEBUTTONUP: case SDL_FINGERUP: no_unselect = 1; if (game_state.state == UNSELECTED_FIRST) { game_state.state = IDLE; break; } case SDL_MOUSEBUTTONDOWN: case SDL_FINGERDOWN: if (event.type == SDL_FINGERDOWN) { event.button.x = event.tfinger.x; event.button.y = event.tfinger.y; } // Diamond area if (event.button.x >= BOARD_OFFSETX && event.button.x < BOARD_WIDTH * DIAMOND_WIDTH + BOARD_OFFSETX && event.button.y >= BOARD_OFFSETY && event.button.y < BOARD_HEIGHT * DIAMOND_HEIGHT + BOARD_OFFSETY) { x = (event.button.x - BOARD_OFFSETX) / DIAMOND_WIDTH; y = (event.button.y - BOARD_OFFSETY) / DIAMOND_HEIGHT; if (game_state.state == IDLE) { game_state.state = SELECTED_FIRST; game_state.x_first = x; game_state.y_first = y; draw = true; } else if (game_state.state == SELECTED_FIRST) { if(game_state.x_first == x && game_state.y_first == y && !no_unselect) { game_state.state = UNSELECTED_FIRST; draw = true; } else if ((abs(game_state.x_first - x) == 1 && (game_state.y_first == y)) || ((game_state.x_first == x) && (abs(game_state.y_first - y) == 1))){ game_state.state = SELECTED_SECOND; game_state.x_second = x; game_state.y_second = y; draw = true; } else { game_state.x_first = x; game_state.y_first = y; draw = true; } } } else if (event.button.x >= BACK2_OFFSETX && event.button.y >= BACK2_OFFSETY && event.button.x < BACK2_OFFSETX2 && event.button.y < BACK2_OFFSETY2) { game_state.state = GAME_EXIT; break; } no_unselect = 0; break; } } // Update screen and reset timer time_tick(); if (draw_screen()) { t1 = SDL_GetTicks(); } // Calculate time and send attack for multiplayer if (gm == GM_MULTIPLAYER) { update_player(); if (ss == SS_CLOSE) { return 0; } else { t2 = SDL_GetTicks(); if (t2 - t1 >= 3500 || combo_score > 310) { t1 = t2; total_score += combo_score; // Update life if (combo_score) { if (total_score >= 1400) { total_score = 1400; game_state.state = GAME_WIN; } else start_attack(1); dest.x = LIFE_ENEMYX - total_score / 10; dest.y = LIFEY; dest.w = total_score / 10; dest.h = LIFE_HEIGHT; SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, 255, 0, 0)); SDL_Update(LIFE_ENEMYX - LIFE_WIDTH, LIFEY, LIFE_WIDTH, LIFE_HEIGHT); write_socket(&combo_score, sizeof(int)); combo_score = 0; // Erase progress bar dest.x = 21; dest.y = 335; dest.w = 311; dest.h = 36; SDL_BlitSurface(bg, &dest, screen, &dest); SDL_Update(dest.x, dest.y, dest.w, dest.h); } } } // Timer for single player } else { t2 = SDL_GetTicks(); if (t2 - t1 >= timer_delay) { t1 = t2; single_timer -= 2; if (single_timer <= 0) game_state.state = GAME_LOSE; draw_timer_bar(true); } } } }