int main(int argc, char *argv[]) { if(init() == false) { printf("Failed to initialize!\n"); return 1; } if(load_media() == false) { printf("Failed to load media!\n"); return 1; } bool quit = false; SDL_Event e; while(!quit) { while(SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } } SDL_SetRenderDrawColor(g_renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(g_renderer); render_texture(g_renderer, g_sprite, 0, 0, &g_spriteclips[0]); render_texture(g_renderer, g_sprite, SCREEN_WIDTH - g_spriteclips[1].w, 0, &g_spriteclips[1]); render_texture(g_renderer, g_sprite, 0, SCREEN_HEIGHT - g_spriteclips[2].h, &g_spriteclips[2]); render_texture(g_renderer, g_sprite, SCREEN_WIDTH - g_spriteclips[3].w, SCREEN_HEIGHT - g_spriteclips[3].h, &g_spriteclips[3]); SDL_RenderPresent(g_renderer); } close(); return 0; }
int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } // closing... // Deallocate textures texture_free(&g_up_texture); texture_free(&g_down_texture); texture_free(&g_left_texture); texture_free(&g_right_texture); texture_free(&g_press_texture); SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
int main() { std::srand(std::time(NULL)); allegro_init(); install_timer(); install_keyboard(); // install_mouse(); install_joystick(JOY_TYPE_AUTODETECT); override_config_file(redir("defnot.ini").c_str()); gfx_widescreen = get_config_int("Game", "Widescreen", gfx_widescreen); gfx_fullscreen = get_config_int("Game", "Fullscreen", gfx_fullscreen); if (!setup_gfx() != 0) { allegro_message("Unable to setup the graphics mode\n"); return 1; } // if (gfx_capabilities & GFX_HW_CURSOR) { // enable_hardware_cursor(); // select_mouse_cursor(MOUSE_CURSOR_ARROW); // show_mouse(screen); // } if (!load_media()) { allegro_message("Unable to load data files to play the game\n"); return 1; } // install the timer to control the game speed LOCK_VARIABLE(beats); LOCK_FUNCTION(timer_control); beats = 0; install_int_ex(timer_control, BPS_TO_TIMER(BPS)); // insert the callback routine for the close-button LOCK_VARIABLE(continuing); LOCK_FUNCTION(close_button); set_close_button_callback(close_button); // play the game game_loop(); set_config_int("Game", "Widescreen", gfx_widescreen); set_config_int("Game", "Fullscreen", gfx_fullscreen); remove_int(timer_control); allegro_exit(); return 0; }
int main(int argc, char *argv[]) { // Initialize GLFW (and GLU too) if (!glfwInit()) { perror("ERROR: Could not intialize GLFW!"); return 1; } glfwSwapInterval(1); // Time between buffer swaps glfwSetErrorCallback(error_callback); GLFWwindow* window = glfwCreateWindow(640, 480, "OpenGL Randomness", NULL, NULL); if (!window) { glfwTerminate(); return 2; } glfwGetFramebufferSize(window, &window_width, &window_height); // Loads the window's dimensions into the variables glfwMakeContextCurrent(window); // Uses the window's OpenGL context glfwSetKeyCallback(window, key_callback); // Set up OpenGL glViewport(0.0, 0.0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 640, 480, 0.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0, 0.0, 0.0, 1.0); GLenum gl_error = glGetError(); if (gl_error != GL_NO_ERROR) { printf("ERROR: Could not initialize OpenGL! %s\n", gluErrorString(gl_error)); return 4; } load_media(); // Main loop while(!glfwWindowShouldClose(window)) { main_loop(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
/* perform initialization and start up game loop */ int main(int argc, char *argv[]) { int rval; /* start up SDL and create window */ if (init() < 0) { fprintf(stderr, "failed to initialize!\n"); rval = 1; goto exit; } /* load media */ if (load_media() < 0) { fprintf(stderr, "failed to load media!\n"); rval = 1; goto exit; } /* networking setup */ /* these definitions need to be put in the global space */ IPaddress ip; TCPsocket server = NULL; TCPsocket client = NULL; if (SDLNet_ResolveHost(&ip, NULL, 9999) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); rval = 1; goto exit; } server = SDLNet_TCP_Open(&ip); if (!server) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); rval = 1; goto exit; } /* now listen for client */ goto exit; while (!client) { SDL_Delay(0); client = SDLNet_TCP_Accept(server); } /* start game loop */ printf("starting loop\n"); game_loop(); rval = 0; exit: /* free resources and close SDL */ cleanup(); return rval; }
int main(int argc, char *argv[]) { if(init() == false) { printf("Failed to initialize!\n"); } else { if(load_media() == false) { printf("Failed to load media!\n"); } else { SDL_BlitSurface(g_helloworld, NULL, g_screensurface, NULL); SDL_UpdateWindowSurface(g_window); SDL_Delay(2000); } } close(); return 0; }
int main(int argc, char *argv[]) { int quit = 0; /* event handler */ SDL_Event event; /* modulation components */ Uint8 r = 255; Uint8 g = 255; Uint8 b = 255; /* starts up SDL and create window */ if (init_sdl() == -1) { fprintf(stderr, "Failed to initialize SDL!\n"); return -1; } /* load media */ if (load_media() == -1) { fprintf(stderr, "Failed to load media!\n"); return -2; } /* main loop */ while (quit == 0) { /* handle events on queue */ while (SDL_PollEvent(&event) != 0) { /* users request quit */ if (event.type == SDL_QUIT) quit = 1; /* on key press change rgb values */ else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_q: /* increase red */ r += 32; break; case SDLK_w: /* increase green */ g += 32; break; case SDLK_e: /* increase blue */ b += 32; break; case SDLK_a: /* decrease red */ r -= 32; break; case SDLK_s: /* decrease green */ g -= 32; break; case SDLK_d: /* decrease blue */ b -= 32; break; } } } /* clear screen */ SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); /* modulate and render texture */ gModulatedTexture.setColor(r, g, b); gModulatedTexture.render(0, 0); /* update screen */ SDL_RenderPresent(gRenderer); } /* free resources and close */ close_sdl(); return 0; }
int main(int argc, char* argv[]) { // SDL Event handler SDL_Event event; int key_press; int game_over, score; int game_grid[CELLS] = {0}; int row_test, last_row, drop_count, lock_in, key_count; int first_hold = 1; tetromino * falling; tetromino * next; tetromino * hold; tetromino * temp; set_rand(); lock_in = 0; drop_count = 1; game_over = 0; key_count = 0; score = 0; falling = tetromino_new(ACTIVE); next = tetromino_new(INACTIVE); hold = tetromino_new(INACTIVE); temp = NULL; //log = fopen("Log.txt","w"); //fprintf(log, "Begin Main\n"); if(init() == 0) {//printf(log, "SDL did not initialize.\n" ); return 0; } if(load_media() == 0) {//printf(log, "Media Loading failed\n" ); return 0; } gridRect.x = 0; gridRect.y = 0; fallingRect.x = 0; fallingRect.y = 0; prevRect.x = (BLOCK_SIZE*MAXCOL) + PREVIEW_OFFSET; prevRect.y = 100; scoreRect.x = SCORE_X; scoreRect.y = SCORE_Y; // Preview = PreviewSurfaces[SQUARE_BLOCK]; // set a dummy default //anim = 0; //fprintf(log, "Game Loop entry\n" ); while(game_over == 0) { /*if(anim == 0) tetromino_drop(falling, game_grid); anim = (anim == 200)? 0: anim+1;*/ drop_count = auto_drop(falling, game_grid, drop_count, score); key_press = 100; if(SDL_PollEvent(&event) != 0) { switch(event.type) { case SDL_QUIT: game_over = 1; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_UP: key_press = UP; break; case SDLK_DOWN: key_press = DOWN; break; case SDLK_LEFT: key_press = LEFT; break; case SDLK_RIGHT: key_press = RIGHT; break; case SDLK_ESCAPE: key_press = ESC; break; case SDLK_SPACE: key_press = SPACE; break; } break; } } //if(key_count == 0) //{ switch(key_press) { case UP: tetromino_rotate(falling, game_grid); break; case DOWN: tetromino_drop(falling, game_grid); break; case RIGHT: tetromino_shift_right(falling, game_grid); break; case LEFT: tetromino_shift_left(falling, game_grid); break; case ESC: game_over = 1; break; case SPACE: // this still would be nice with visuals... if(first_hold == 1) { temp = hold; tetromino_mod(temp); hold = falling; falling = next; tetromino_activate(falling); next = temp; temp = NULL; first_hold = 0; } else { temp = falling; falling = hold; tetromino_activate(falling); hold = temp; temp = NULL; } break; } //} key_count = (key_count < KEY_RATE) ? key_count + 1: 0; lock_in = (tetromino_lock(falling, game_grid) == 1)? lock_in+1:0; if(lock_in == 200) { tetromino_into_grid(falling, game_grid); score += falling->shape + 2 * 3; score += row_check(game_grid); // manage the tetrominos temp = falling; falling = next; tetromino_activate(falling); tetromino_mod(temp); next = temp; temp = NULL; lock_in = 0; } if(grid_row_any(game_grid,0) == 1) game_over = 1; //blit to screen SDL_FillRect(ScreenSurface, 0, 0); // so the images don't trail blit_preview(next->shape); blit_grid(game_grid); blit_tetromino(falling); blit_score(score); SDL_UpdateWindowSurface(MainWin); } game_close(); free(falling); free(next); free(hold); return 0; }
/**************************************** * TitleScreen: Display the title screen * ***************************************** * display title screen, get input */ void TitleScreen(void) { Uint32 frame = 0; Uint32 start = 0; /* NOTE for 'depth', think pages like a restaurant menu, */ /* not heirarchical depth - choice of term is misleading */ int menu_depth; // how deep we are in the menu int i, j, tux_frame = 0; int done = 0; int firstloop = 1; int menu_opt = NONE; int sub_menu = NONE; int update_locs = 1; int redraw = 0; int key_menu = 1; int old_key_menu = 5; if (settings.sys_sound) { settings.menu_sound = 1; settings.menu_music = 1; } start = SDL_GetTicks(); /* * Display the Standby screen.... */ show_logo(); snd_welcome = LoadSound("harp.wav"); if (snd_welcome && settings.menu_sound) { PlaySound(snd_welcome); } /* Load media and menu data: */ if (!load_media()) { fprintf(stderr, "TitleScreen - load_media() failed!"); return; } SDL_WM_GrabInput(SDL_GRAB_ON); // User input goes to TuxType, not window manager /*************************** * Tux and Title animations * ***************************/ LOG( "->Now Animating Tux and Title onto the screen\n" ); Tuxdest.x = 0; Tuxdest.y = screen->h; Tuxdest.w = Tux->frame[0]->w; Tuxdest.h = Tux->frame[0]->h; Titledest.x = screen->w; Titledest.y = 10; Titledest.w = title->w; Titledest.h = title->h; spkrdest.x = screen->w - speaker->w - 10; spkrdest.y = screen->h - speaker->h - 10; spkrdest.w = speaker->w; spkrdest.h = speaker->h; /* --- wait if the first time in the game --- */ if (settings.show_tux4kids) { while ((SDL_GetTicks() - start) < 2000) { SDL_Delay(50); } settings.show_tux4kids = 0; } SDL_ShowCursor(1); /* FIXME not sure the next line works in Windows: */ TransWipe(CurrentBkgd(), RANDOM_WIPE, 10, 20); /* Make sure background gets drawn (since TransWipe() doesn't */ /* seem to work reliably as of yet): */ SDL_BlitSurface(CurrentBkgd(), NULL, screen, NULL); SDL_UpdateRect(screen, 0, 0, 0, 0); /* --- Pull tux & logo onscreen --- */ for (i = 0; i <= (PRE_ANIM_FRAMES * PRE_FRAME_MULT); i++) { start = SDL_GetTicks(); SDL_BlitSurface(CurrentBkgd(), &Tuxdest, screen, &Tuxdest); SDL_BlitSurface(CurrentBkgd(), &Titledest, screen, &Titledest); Tuxdest.y -= Tux->frame[0]->h / (PRE_ANIM_FRAMES * PRE_FRAME_MULT); Titledest.x -= (screen->w) / (PRE_ANIM_FRAMES * PRE_FRAME_MULT); /* Don't go past 0; */ if (Tuxdest.y < 0) Tuxdest.y = 0; if (Titledest.x < 0) Titledest.x = 0; SDL_BlitSurface(Tux->frame[0], NULL, screen, &Tuxdest); SDL_BlitSurface(title, NULL, screen, &Titledest); SDL_UpdateRect(screen, Tuxdest.x, Tuxdest.y, Tuxdest.w, Tuxdest.h); SDL_UpdateRect(screen, Titledest.x, Titledest.y, Titledest.w + 40, Titledest.h); while ((SDL_GetTicks() - start) < 33) { SDL_Delay(2); } } recalc_rects(); /* Pick speaker graphic according to whether music is on: */ if ( settings.menu_music ) SDL_BlitSurface(speaker, NULL, screen, &spkrdest); else SDL_BlitSurface(speakeroff, NULL, screen, &spkrdest); /* Start playing menu music if desired: */ if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); LOG( "Tux and Title are in place now\n" ); SDL_WM_GrabInput(SDL_GRAB_OFF); /**************************** * Main Loop Starts Here ... * ****************************/ menu_depth = 1; firstloop = 1; Tuxdest.y = screen->h - Tux->frame[0]->h; while (!done) { start = SDL_GetTicks(); /* ---process input queue --- */ menu_opt = NONE; // clear the option so we don't change twice! old_key_menu = key_menu; /* Retrieve any user interface events: */ while (SDL_PollEvent(&event)) { switch (event.type) { /* Update "selection" if mouse moves within a menu entry: */ case SDL_MOUSEMOTION: { cursor.x = event.motion.x; cursor.y = event.motion.y; for (j = 1; j <= TITLE_MENU_ITEMS; j++) if (inRect(menu_button[j], cursor.x, cursor.y)) key_menu = j; break; } /* Handle mouse clicks based on mouse location: */ case SDL_MOUSEBUTTONDOWN: { cursor.x = event.motion.x; cursor.y = event.motion.y; for (j = 1; j <= TITLE_MENU_ITEMS; j++) { if (inRect(menu_button[j], cursor.x, cursor.y)) { menu_opt = menu_item[j][menu_depth]; if (settings.menu_sound) { PlaySound(snd_select); } DEBUGCODE { fprintf(stderr, "->>BUTTON CLICK menu_opt = %d\n", menu_opt); fprintf(stderr, "->J = %d menu_depth=%d\n", j, menu_depth); } } } /* If mouse over speaker, toggle menu music off or on: */ if (inRect(spkrdest, cursor.x, cursor.y)) { if (settings.menu_music) { MusicUnload(); settings.menu_music = 0; } else { settings.menu_music = 1; MusicLoad("tuxi.ogg", -1); } redraw = 1; } break; } case SDL_QUIT: { menu_opt = QUIT_GAME; break; } /* Handle key press events based on key value: */ case SDL_KEYDOWN: { switch (event.key.keysym.sym) { case SDLK_ESCAPE: { /* Go to main menu (if in submenu) or quit: */ if (menu_depth != 1) menu_opt = MAIN; else menu_opt = QUIT_GAME; if (settings.menu_sound) PlaySound(snd_select); break; } /* Toggle screen mode: */ case SDLK_F10: { SwitchScreenMode(); recalc_rects(); redraw = 1; break; } /* Toggle menu music: */ case SDLK_F11: { if (settings.menu_music) { MusicUnload( ); settings.menu_music = 0; } else { settings.menu_music = 1; MusicLoad("tuxi.ogg", -1); } redraw = 1; break; } /* --- reload translation/graphics/media: for themers/translaters --- */ case SDLK_F12: { unload_media(); LoadLang(); load_media(); redraw = 1; break; } case SDLK_UP: case SDLK_k: { if (settings.menu_sound) PlaySound(snd_move); key_menu--; if (key_menu < 1) key_menu = 5; break; } case SDLK_DOWN: case SDLK_j: { key_menu++; if (settings.menu_sound) PlaySound(snd_move); if (key_menu > 5) key_menu = 1; break; } case SDLK_RETURN: { if (key_menu) { menu_opt = menu_item[key_menu][menu_depth]; if (settings.menu_sound) PlaySound(snd_select); } break; } default: /* Some other key pressed - do nothing: */ { break; } } /* End of switch(event.key.keysym.sym) statement */ } /* End of case: SDL_KEYDOWN: */ default: /* Some other type of SDL event - do nothing; */ { break; } } /* End of switch(event.type) statement */ } /* End of while (SDL_PollEvent(&event)) loop */ /* --- do menu processing --- */ if (menu_opt == QUIT_GAME) done = 1; if (menu_opt == LASER) { menu_depth = LASER_SUBMENU; sub_menu = LASER; update_locs = 1; redraw = 1; } if (menu_opt == CASCADE) { menu_depth = CASCADE_SUBMENU; sub_menu = CASCADE; update_locs = 1; redraw=1; } if (menu_opt == OPTIONS) { menu_depth = OPTIONS_SUBMENU; sub_menu = OPTIONS; update_locs = 1; redraw = 1; } if (menu_opt == MAIN) { menu_depth = ROOTMENU; update_locs = 1; redraw = 1; } if (menu_opt == EDIT_WORDLIST) { ChooseListToEdit(); redraw = 1; } if (menu_opt == PROJECT_INFO) { ProjectInfo(); redraw = 1; } if (menu_opt == LESSONS) { // not_implemented(); SDL_BlitSurface(CurrentBkgd(), NULL, screen, NULL); SDL_Flip(screen); unload_media(); if (settings.menu_music) MusicUnload( ); XMLLesson(); load_media(); redraw = 1; if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); } if (menu_opt == SET_LANGUAGE) { unload_media(); ChooseTheme(); LoadLang(); LoadKeyboard(); load_media(); redraw = 1; if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); } if (menu_opt == LEVEL1) { if (chooseWordlist()) { unload_media(); switch (sub_menu) { case CASCADE: PlayCascade( EASY ); break; case LASER: PlayLaserGame( EASY ); break; } } load_media(); if (settings.menu_music) MusicLoad("tuxi.ogg", -1); redraw = 1; } if (menu_opt == LEVEL2) { if (chooseWordlist()) { unload_media(); switch (sub_menu) { case CASCADE: PlayCascade( MEDIUM ); break; case LASER: PlayLaserGame( MEDIUM ); break; } if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); } load_media(); redraw = 1; } if (menu_opt == LEVEL3) { if (chooseWordlist()) { unload_media(); switch (sub_menu) { case CASCADE: PlayCascade( HARD ); break; case LASER: PlayLaserGame( HARD ); break; } if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); } load_media(); redraw = 1; } if (menu_opt == LEVEL4) { if (chooseWordlist()) { unload_media(); switch (sub_menu) { case CASCADE: PlayCascade( INSANE ); break; case LASER: PlayLaserGame( INSANE ); break; } if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); } load_media(); redraw = 1; } if (menu_opt == INSTRUCT) { // not_implemented(); unload_media(); switch (sub_menu) { case CASCADE: InstructCascade(); break; case LASER: InstructLaser(); break; } load_media(); if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); redraw = 1; } if (menu_opt == PHRASE_TYPING) { // not_implemented(); unload_media(); Phrases(NULL); load_media(); if (settings.menu_music) MusicLoad( "tuxi.ogg", -1 ); redraw = 1; } /* ------ End menu_opt processing ----------- */ if (redraw) { LOG("TitleScreen() - redraw requested\n"); recalc_rects(); SDL_BlitSurface(CurrentBkgd(), NULL, screen, NULL); SDL_BlitSurface(title, NULL, screen, &Titledest); if ( settings.menu_music ) SDL_BlitSurface(speaker, NULL, screen, &spkrdest); else SDL_BlitSurface(speakeroff, NULL, screen, &spkrdest); /* Screen will be updated due to update_locs - see ~30 lines down: */ // SDL_UpdateRect(screen, 0, 0, 0, 0); frame = redraw = 0; // so we redraw tux update_locs = 1; // so we redraw menu firstloop = 1; } /* --- create new menu screen when needed --- */ if (update_locs) { LOG("TitleScreen() - update_locs requested\n"); /* --- erase the last menu --- */ for (i = 1; i <= TITLE_MENU_ITEMS; i++) { text_dst[i].x = screen->w/2 - 70;//290; text_dst[i].w = reg_text[i][menu_depth]->w; text_dst[i].h = reg_text[i][menu_depth]->h; SDL_BlitSurface(CurrentBkgd(), &menu_button[i], screen, &menu_button[i]); menu_button[i].w = menu_width[menu_depth] + 20; } update_locs = 0; /* --- draw the full menu --- */ for (j = 1; j <= TITLE_MENU_ITEMS; j++) { DOUT(j); DrawButton(&menu_button[j], 10, REG_RGBA); if (reg_text[j][menu_depth] != NULL) SDL_BlitSurface(reg_text[j][menu_depth], NULL, screen, &text_dst[j]); if (menu_gfx[j][menu_depth] != NULL) SDL_BlitSurface(menu_gfx[j][menu_depth]->default_img, NULL, screen, &menu_gfxdest[j]); } SDL_UpdateRect(screen, 0, 0, 0, 0); LOG("TitleScreen() - update_locs completed\n"); } /* --- make tux blink --- */ switch (frame % TUX6) { case 0: tux_frame = 1; break; case TUX1: tux_frame = 2; break; case TUX2: tux_frame = 3; break; case TUX3: tux_frame = 4; break; case TUX4: tux_frame = 3; break; case TUX5: tux_frame = 2; break; default: tux_frame = 0; } if (tux_frame) { SDL_Rect blink_src, blink_dest; blink_src.x = 0; blink_src.y = 0; blink_src.w = Tuxdest.w; blink_src.h = Tuxdest.h; blink_dest.x = Tuxdest.x + blink_src.x; blink_dest.y = Tuxdest.y + blink_src.y; blink_dest.w = blink_src.w; blink_dest.h = blink_src.h; // SDL_BlitSurface(CurrentBkgd(), , screen, &Tuxdest); SDL_BlitSurface(Tux->frame[tux_frame - 1], &blink_src, screen, &blink_dest); } /* --- check if mouse is in a menu option --- */ // key_menu = 0; /* for (j = 1; j <= TITLE_MENU_ITEMS; j++) { if ((cursor.x >= menu_button[j].x && cursor.x <= (menu_button[j].x + menu_button[j].w)) && (cursor.y >= menu_button[j].y && cursor.y <= (menu_button[j].y + menu_button[j].h))) { key_menu = j; // update menu to point break; // Don't need to check rest of menu } }*/ /* --- return old selection to unselected state --- */ if (old_key_menu && (key_menu != old_key_menu)) { SDL_BlitSurface(CurrentBkgd(), &menu_button[old_key_menu], screen, &menu_button[old_key_menu]); DrawButton(&menu_button[old_key_menu], 10, REG_RGBA); SDL_BlitSurface(reg_text[old_key_menu][menu_depth], NULL, screen, &text_dst[old_key_menu]); SDL_BlitSurface(menu_gfx[old_key_menu][menu_depth]->default_img, NULL, screen, &menu_gfxdest[old_key_menu]); } /* --- draw current selection --- */ if ((key_menu != 0) && ((old_key_menu != key_menu) || (frame % 5 == 0))) // Redraw every fifth frame? { if (key_menu != old_key_menu) { REWIND(menu_gfx[key_menu][menu_depth]); PlaySound(snd_move); } SDL_BlitSurface(CurrentBkgd(), &menu_button[key_menu], screen, &menu_button[key_menu]); DrawButton(&menu_button[key_menu], 10, SEL_RGBA); SDL_BlitSurface(sel_text[key_menu][menu_depth], NULL, screen, &text_dst[key_menu]); SDL_BlitSurface(menu_gfx[key_menu][menu_depth]->frame[menu_gfx[key_menu][menu_depth]->cur], NULL, screen, &menu_gfxdest[key_menu]); NEXT_FRAME(menu_gfx[key_menu][menu_depth]); } // HACK This is still more than we need to update every frame but // it cuts cpu on my machine %60 so it seems better... if ( settings.menu_music ) SDL_BlitSurface(speaker, NULL, screen, &spkrdest); else SDL_BlitSurface(speakeroff, NULL, screen, &spkrdest); SDL_UpdateRect(screen, spkrdest.x, spkrdest.y, spkrdest.w, spkrdest.h); for (i = 1; i < 6; i++) { SDL_UpdateRect(screen, menu_button[i].x, menu_button[i].y, menu_button[i].w, menu_button[i].h); } if (tux_frame) SDL_UpdateRect(screen, Tuxdest.x, Tuxdest.y, Tuxdest.w, Tuxdest.h); if (firstloop) SDL_UpdateRect(screen, Tuxdest.x, Tuxdest.y, Tuxdest.w, Tuxdest.h); firstloop = 0; /* Wait so we keep frame rate constant: */ while ((SDL_GetTicks() - start) < 33) { SDL_Delay(20); } frame++; } /* ----------- End of 'while(!done)' loop ------------ */
// the main game loop which will run until the game is done void game_loop() { SDL_Event event, e; SDL_TimerID timer; int last_game_update = 0; int last_particle_update = 0; int last_render = 0; int previous_level = 0; debug_print("Loading media..."); load_media(); // check if we want to show score increments game.show_score_increments = atoi(config_getValue("show_score_increments")); // setup input input_init(); // create & show menu ui_menuInit(); ui_toggleMenuVisible(); SDL_SetEventFilter(ui_handleEvents); // loop forever debug_print("Entering main game loop..."); while (1) { // see if its time to trigger an update (make sure we're not paused either) if (!game.paused && SDL_GetTicks() - last_game_update > game_getGameUpdateFreq()) { last_game_update = SDL_GetTicks(); // remember time of last update game_update(); } if (game.show_score_increments) { // at the moment we just have the one particle set // see if its time to trigger a particle update if (SDL_GetTicks() - last_particle_update > PARTICLE_UPDATE_INTERVAL) { last_particle_update = SDL_GetTicks(); particle_update(); } } // check for any events waiting while (SDL_PollEvent(&event)) { switch(event.type) { // key presses are handled in input.c case SDL_KEYDOWN: input_onKeyDown(event.key.keysym.sym); break; case LEFT_KEY: tetromino_moveLeft(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveRight(current_tetromino); } break; case RIGHT_KEY: tetromino_moveRight(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveLeft(current_tetromino); } break; case DOWN_KEY: // uses the key repeat interval to accelerate the tetromino down tetromino_moveDown(current_tetromino); if (grid_checkCollision(grid, current_tetromino)) { tetromino_moveUp(current_tetromino); } break; case UP_KEY: // rotate to a new position tetromino_setNextPosition(current_tetromino); tetromino_setShape(current_tetromino, current_tetromino->type, current_tetromino->position); // make sure the new position doesn't cause any collisions // if it does, reverse the rotation if (grid_checkCollision(grid, current_tetromino)) { tetromino_setPrevPosition(current_tetromino); tetromino_setShape(current_tetromino, current_tetromino->type, current_tetromino->position); } break; case SPACE_KEY: tetromino_moveDown(current_tetromino); // move the tetromino down until it causes a collision while (!grid_checkCollision(grid, current_tetromino)) { tetromino_moveDown(current_tetromino); } // once we have a collision, move it back into place tetromino_moveUp(current_tetromino); break; case PAUSE_KEY: debug_print("Pausing game"); game.paused = !game.paused; // stop the game timer if (game.paused) { SDL_RemoveTimer(timer); timer = NULL; } else { // start it again timer = SDL_AddTimer(1000, game_updateTime, NULL); } break; case ESCAPE_KEY: // pause game updates debug_print("Escape key pressed."); // toggle paused game state if we're in game if (grid && current_tetromino) { game.paused = !game.paused; if (game.paused) { // stop couting time played SDL_RemoveTimer(timer); timer = NULL; } // starting timer again, only if we're still in a game else if (grid && current_tetromino) { timer = SDL_AddTimer(1000, game_updateTime, NULL); } } // show or hide the menu if (grid && current_tetromino) { ui_toggleMenuVisible(); } // enable ui message pump if its visible if (ui_isMenuVisible()) { // if we're in game, show in-game menu if (grid && current_tetromino) { ui_menuPageSetCurrentById(MENU_IN_GAME); } // otherwise show main menu else { ui_menuPageSetCurrentById(MENU_MAIN); } SDL_SetEventFilter(ui_handleEvents); } break; case GAME_START_NEW: // set some game variables game.level = 0; game.score = 0; game.lines = 0; game.paused = 0; // time variables game.hours = 0; game.minutes = 0; game.seconds = 0; // create the grid grid = grid_createNew(GRID_WIDTH, GRID_HEIGHT); // create the first tetromino current_tetromino = tetromino_createNew(); current_tetromino->x = 0; current_tetromino->y = 0; // update time SDL_Init(SDL_INIT_TIMER); if (timer) { SDL_RemoveTimer(timer); timer = NULL; } ui_toggleMenuVisible(); timer = SDL_AddTimer(1000, game_updateTime, NULL); game.paused = 0; break; case GAME_END: // called by either the menu or game over scenario // destroy timer, grid and tetromino SDL_RemoveTimer(timer); timer = NULL; grid_destroy(grid); grid = NULL; tetromino_destroy(current_tetromino); current_tetromino = NULL; // show menu if it isn't already visible ui_menuPageSetCurrentById(MENU_MAIN); if (!ui_isMenuVisible()) { SDL_SetEventFilter(ui_handleEvents); ui_toggleMenuVisible(); } break; case TETROMINO_CREATE: // assumes that the old one has already been discarded current_tetromino = tetromino_createNew(); current_tetromino->x = 0; current_tetromino->y = 0; // check if we have an immediate collision (game over) if (grid_checkCollision(grid, current_tetromino)) { SDL_RemoveTimer(timer); timer = NULL; e.type = GAME_END; SDL_PushEvent(&e); } break; case GRID_REMOVE_LINE: if (game.show_score_increments) { // animated score increment game_showScoreIncrement(event.user.code, (game.level + 1) * 10); } grid_removeLine(grid, event.user.code); // increment number of complete lines game.lines += 1; // +10 per block and x10 per level game.score += (game.level + 1) * 10 * GRID_WIDTH; // increment the game level every 10 lines previous_level = game.level; game.level = game.lines / 10; if (previous_level != game.level) { game_showLevelIncrement(); } break; case GAME_QUIT: SDL_RemoveTimer(timer); // stop gameplay timer timer = NULL; game_shutdown(); break; // unhandled events are ignored default: break; } } // update the display // without this delay gfx card tries to commit suicide by melting if (SDL_GetTicks() - last_render > 3) { display_update(); last_render= SDL_GetTicks(); } } }
int main(int argc, char *argv[]) { int quit = 0; /* event handler */ SDL_Event event; /* modulation components */ Uint8 alpha = 255; /* starts up SDL and create window */ if (init_sdl() == -1) { fprintf(stderr, "Failed to initialize SDL!\n"); return -1; } /* load media */ if (load_media() == -1) { fprintf(stderr, "Failed to load media!\n"); return -2; } /* main loop */ while (quit == 0) { /* handle events on queue */ while (SDL_PollEvent(&event) != 0) { /* users request quit */ if (event.type == SDL_QUIT) quit = 1; /* on key press change alpha values */ else if (event.type == SDL_KEYDOWN) { /* increase alpha on w */ if (event.key.keysym.sym == SDLK_w) { if (alpha + 32 > 255) alpha = 255; else alpha += 32; /* decrease alpha on s */ } else if (event.key.keysym.sym == SDLK_s) { if (alpha - 32 < 0) alpha = 0; else alpha -= 32; } } } /* clear screen */ SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); /* render background */ gBackgroundTexture.render(0, 0); /* render front blended */ gModulatedTexture.setAlpha(alpha); gModulatedTexture.render(0, 0); /* update screen */ SDL_RenderPresent(gRenderer); } /* free resources and close */ close_sdl(); return 0; }
/* * get_media - get the media mounted. * * entry - * drive->mutex should be held. This mutex * can be released during processing, but will be held * on return. * * returns - * 0 - ok * 1 - some sort of error, dispose of event * Note: The catalog mutex is held on this condition. * 2 - event was requeued. * -1 - same as 1 cept that the drive should be downed * * in all cases, dev_ent activity count will be incremented. */ int get_media( library_t *library, drive_state_t *drive, robo_event_t *event, /* the event (can be NULL) */ struct CatalogEntry *ce) /* catalog entry to be loaded */ { char *d_mess = drive->un->dis_mes[DIS_MES_NORM]; dev_ent_t *un = drive->un; int status = 0; mutex_lock(&un->mutex); INC_ACTIVE(un); mutex_unlock(&un->mutex); /* is the media is already mounted */ if (drive->status.b.full && (un->slot == ce->CeSlot)) { if (DBG_LVL(SAM_DBG_DEBUG)) sam_syslog(LOG_DEBUG, "get_media:(%d)%s:%d.", un->eq, __FILE__, __LINE__); } else { /* get the media loaded */ /* * Make sure the source storage element has media in it. * If the element is empty, external requests * will be put back on the library's work list with the * hope that it will be picked up later. Internal * requests will return an error to the caller. If the in_use * flag is not set, then the slot is * "really" empty and the request will be disposed of. */ if (DBG_LVL(SAM_DBG_TMOVE)) sam_syslog(LOG_DEBUG, "get_media:(%d)%s:%d.", un->eq, __FILE__, __LINE__); if (!(ce->CeStatus & CES_occupied)) { /* Should this be put back on the library's list? */ if ((ce->CeStatus & CES_inuse) && event != NULL && event->type != EVENT_TYPE_INTERNAL && !event->status.b.dont_reque) { event->next = NULL; add_to_end(library, event); /* Do not dispose of event */ return (RET_GET_MEDIA_REQUEUED); } if (DBG_LVL(SAM_DBG_TMOVE)) sam_syslog(LOG_DEBUG, "get_media:(%d)%s:%d.", un->eq, __FILE__, __LINE__); return (RET_GET_MEDIA_DISPOSE); } else { status &= ~CES_occupied; (void) CatalogSetFieldByLoc(library->un->eq, ce->CeSlot, 0, CEF_Status, status, CES_occupied); } if (drive->status.b.full) { mutex_lock(&un->mutex); un->status.bits |= DVST_UNLOAD; mutex_unlock(&un->mutex); /* * Save off what information we know about this volume * before we spin down the drive and clear out the un. */ memmove(un->i.ViMtype, sam_mediatoa(un->type), sizeof (un->i.ViMtype)); memmove(un->i.ViVsn, un->vsn, sizeof (un->i.ViVsn)); un->i.ViEq = un->fseq; un->i.ViSlot = un->slot; un->i.ViPart = 0; if (un->status.b.ready) { (void) spin_drive(drive, SPINDOWN, NOEJECT); sprintf(d_mess, "unloading %s", un->vsn); } mutex_lock(&un->mutex); close_unit(un, &drive->open_fd); un->status.bits = (DVST_REQUESTED | DVST_PRESENT) | (un->status.bits & DVST_CLEANING); clear_un_fields(un); mutex_unlock(&un->mutex); #if defined(USEDISMOUNT) sprintf(d_mess, "dismounting %s", un->vsn); if (dismount_media(library, drive) != MC_REQ_OK) { if (DBG_LVL(SAM_DBG_TMOVE)) sam_syslog(LOG_DEBUG, "get_media:(%d)%s:%d.", un->eq, __FILE__, __LINE__); return (RET_GET_MEDIA_DOWN_DRIVE); } #endif /* defined(USEDISMOUNT) */ /* clean up the old entries */ if (*un->i.ViMtype != '\0') un->i.ViFlags |= VI_mtype; if (*un->i.ViVsn != '\0') un->i.ViFlags |= VI_vsn; CatalogVolumeUnloaded(&un->i, ""); mutex_lock(&un->mutex); un->slot = ROBOT_NO_SLOT; un->mid = un->flip_mid = ROBOT_NO_SLOT; un->label_time = 0; mutex_unlock(&un->mutex); /* clear the drive information */ drive->status.b.full = FALSE; drive->status.b.bar_code = FALSE; } #if !defined(USEDISMOUNT) if (*un->i.ViVsn != '\0') sprintf(d_mess, "dismount %s/mount %s", un->i.ViVsn, un->vsn); else sprintf(d_mess, "mount %s", ce->CeVsn); #else sprintf(d_mess, "mount %s", ce->CeVsn); #endif if (load_media(library, drive, ce, 0) != MC_REQ_OK) { /* * Process error and return status to caller. * Requeue the event if not internal otherwise * return status to caller. */ req_comp_t err; int ret = RET_GET_MEDIA_DISPOSE; IBM_query_info_t *info; if (DBG_LVL(SAM_DBG_DEBUG)) sam_syslog(LOG_DEBUG, "load of %s failed.", ce->CeVsn); sprintf(d_mess, "mount of %s failed.", ce->CeVsn); if (DBG_LVL(SAM_DBG_TMOVE)) sam_syslog(LOG_DEBUG, "get_media:(%d)%s:%d.", un->eq, __FILE__, __LINE__); /* * Attempt some sort of recovery: * Check the state of the volume itself */ err = view_media(library, ce->CeBarCode, (void *)&info); if (err != MC_REQ_OK) { status |= CES_occupied; (void) CatalogSetFieldByLoc(library->un->eq, ce->CeSlot, 0, CEF_Status, status, 0); /* If internal event, then dont requeue it */ if (event == NULL || event->type == EVENT_TYPE_INTERNAL) ret = RET_GET_MEDIA_DISPOSE; } else if (info != NULL) { ushort_t vol_status, category; memcpy(&vol_status, &info-> data.expand_vol_data.volume_status[0], sizeof (vol_status)); memcpy(&category, &info->data.expand_vol_data.cat_assigned[0], sizeof (category)); if (vol_status & MT_VLI) sam_syslog(LOG_INFO, "get_media(%d):" " %s Present but inaccessible.", LIBEQ, ce->CeVsn); if (vol_status & (MT_VM | MT_VQM | MT_VPM | MT_VQD | MT_VPD)) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Mounting/Dismounting " " or queued.", LIBEQ, ce->CeVsn); if (vol_status & (MT_VQE | MT_VPE)) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Ejecting.", LIBEQ, ce->CeVsn); if (vol_status & MT_VMIS) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Misplaced.", LIBEQ, ce->CeVsn); if (vol_status & MT_VUU) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Unreadable label.", LIBEQ, ce->CeVsn); if (vol_status & MT_VMM) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Used during manual mode.", LIBEQ, ce->CeVsn); if (vol_status & MT_VME) sam_syslog(LOG_INFO, "get_media(%d):" " %s, Manually Ejected.", LIBEQ, ce->CeVsn); if (category == MAN_EJECTED_CAT) set_media_category(library, ce->CeVsn, MAN_EJECTED_CAT, PURGE_VOL_CATEGORY); if (vol_status & (MT_VLI | MT_VQE | MT_VPE | MT_VMIS | MT_VUU | MT_VME)) { ret = RET_GET_MEDIA_DISPOSE; sam_syslog(LOG_INFO, "rec_cat(%d): %s, ce->CeSlot %d:" " removed from catalog", LIBEQ, ce->CeVsn, ce->CeSlot); } free(info); } return (ret); } } mutex_lock(&un->mutex); drive->status.b.full = TRUE; drive->status.b.valid = TRUE; memmove(un->vsn, ce->CeVsn, sizeof (un->vsn)); un->slot = ce->CeSlot; un->mid = ce->CeMid; un->flip_mid = ROBOT_NO_SLOT; un->status.b.labeled = FALSE; un->status.b.ready = FALSE; drive->status.b.bar_code = TRUE; memcpy(drive->bar_code, ce->CeBarCode, BARCODE_LEN + 1); un->space = ce->CeSpace; switch (un->type & DT_CLASS_MASK) { case DT_OPTICAL: un->dt.od.ptoc_fwa = ce->m.CePtocFwa; break; case DT_TAPE: un->dt.tp.position = ce->m.CeLastPos; break; } mutex_unlock(&un->mutex); return (RET_GET_MEDIA_SUCCESS); }
int main(int argc, char *argv[]) { int quit = 0; /* event handler */ SDL_Event event; /* the dot that will be moving around the screen */ Dot dot; /* set the wall */ SDL_Rect wall; wall.x = 300; wall.y = 40; wall.w = 40; wall.h = 400; /* starts up SDL and create window */ if (init_sdl() == -1) { fprintf(stderr, "Failed to initialize SDL!\n"); return -1; } /* load media */ if (load_media() == -1) { fprintf(stderr, "Failed to load media!\n"); return -2; } /* main loop */ while (quit == 0) { /* handle events on queue */ while (SDL_PollEvent(&event) != 0) { /* users request quit */ if (event.type == SDL_QUIT) quit = 1; /* handle user key press */ dot.handleEvent(event); } /* move the dot and check collision */ dot.move(wall); /* clear screen */ SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); /* render wall */ SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderDrawRect(gRenderer, &wall); /* render dot */ dot.render(); /* update screen */ SDL_RenderPresent(gRenderer); } /* free resources and close */ close_sdl(); return 0; }
int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_11.html if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "main: SDL_mixer Error: %s\n", Mix_GetError() ); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } /** closing **/ // Deallocate textures texture_free(&g_current_texture); // joystick // SDL_JoystickClose(g_gamepad); // g_gamepad = 0; // sfx Mix_FreeChunk( g_scratch ); Mix_FreeChunk( g_hig ); Mix_FreeChunk( g_med ); Mix_FreeChunk( g_low ); g_scratch = 0; g_hig = 0; g_med = 0; g_low = 0; // music Mix_FreeMusic( g_music ); g_music = 0; SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { int quit = 0; /* event handler */ SDL_Event event; /* set text color as black */ SDL_Color textColor = { 0, 0, 0, 255 }; /* current time start time */ Uint32 startTime = 0; char timeText[128]; /* starts up SDL and create window */ if (init_sdl() == -1) { fprintf(stderr, "Failed to initialize SDL!\n"); return -1; } /* load media */ if (load_media() == -1) { fprintf(stderr, "Failed to load media!\n"); return -2; } /* main loop */ while (quit == 0) { /* handle events on queue */ while (SDL_PollEvent(&event) != 0) { /* users request quit */ if (event.type == SDL_QUIT) quit = 1; /* reset start time on return key press */ else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) { startTime = SDL_GetTicks(); } } /* set text to be rendered */ snprintf(timeText, sizeof(timeText), "%d", SDL_GetTicks() - startTime); /* render text */ if (gTimeTextTexture.loadFromRenderedText(timeText, textColor) == -1) fprintf(stderr, "Unable to render time texture!\n"); /* clear screen */ SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(gRenderer); /* render texture */ gPromptTexture.render((SCREEN_WIDTH - gPromptTexture.getWidth()) / 2, 0); gTimeTextTexture.render((SCREEN_WIDTH - gTimeTextTexture.getWidth()) / 2, (SCREEN_HEIGHT - gTimeTextTexture.getHeight()) / 2); /* update screen */ SDL_RenderPresent(gRenderer); } /* free resources and close */ close_sdl(); return 0; }