int main( int argc, char* args[] ) { //Init SDL if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { return 10; } //Creates a SDL Window if((window = SDL_CreateWindow("Image Loading", 100, 100, 500/*WIDTH*/, 250/*HEIGHT*/, SDL_WINDOW_RESIZABLE | SDL_RENDERER_PRESENTVSYNC)) == NULL) { return 20; } //SDL Renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED ); if (renderer == NULL) { std::cout << SDL_GetError() << std::endl; return 30; } //Init textures int w=0,h=0; background = IMG_LoadTexture(renderer,"fondo.png"); SDL_QueryTexture(background, NULL, NULL, &w, &h); rect_background.x = 0; rect_background.y = 0; rect_background.w = w; rect_background.h = h; character = IMG_LoadTexture(renderer, "personaje.png"); SDL_QueryTexture(character, NULL, NULL, &w, &h); rect_character.x = 0; rect_character.y = 100; rect_character.w = w; rect_character.h = h; char2 = IMG_LoadTexture(renderer, "char2.png"); SDL_QueryTexture(character, NULL, NULL, &w, &h); rect_character2.x = 100; rect_character2.y = 100; rect_character2.w = w; rect_character2.h = h; //Main Loop while(true) { while(SDL_PollEvent(&Event)) { if(Event.type == SDL_QUIT) { return 0; } if(Event.type == SDL_KEYDOWN) { if(Event.key.keysym.sym == SDLK_d) rect_character.x+=2; else if(Event.key.keysym.sym == SDLK_a) rect_character.x-=2; else if(Event.key.keysym.sym == SDLK_w) rect_character.y-=2; else if(Event.key.keysym.sym == SDLK_s) rect_character.y+=2; if(Event.key.keysym.sym == SDLK_RIGHT) rect_character2.x+=2; else if(Event.key.keysym.sym == SDLK_LEFT) rect_character2.x-=2; else if(Event.key.keysym.sym == SDLK_UP) rect_character2.y-=2; else if(Event.key.keysym.sym == SDLK_DOWN) rect_character2.y+=2; } } SDL_RenderCopy(renderer, background, NULL, &rect_background); SDL_RenderCopy(renderer, character, NULL, &rect_character); SDL_RenderCopy(renderer, char2, NULL, &rect_character2); SDL_RenderPresent(renderer); } return 0; }
ManifestBasedResources(std::string manifest, SDL_Renderer* renderer) { auto configuration = LoadLuaConfiguration(manifest); auto images = configuration.Get<LuaTable>("images"); images.ForAllIntegerKeys([&](int key, LuaType::Value type) { if (type == LuaType::table) { auto value = images.Get<LuaTable>(key); auto id = value.Get<int>("id"); auto path = value.Get<std::string>("path"); auto x = value.Get<int>("x"); auto y = value.Get<int>("y"); auto w = value.Get<int>("w"); auto h = value.Get<int>("h"); SDL_Rect rect; rect.x = x; rect.y = y; rect.w = w; rect.h = h; auto texture = texturesByName.find(path); if (texture == texturesByName.end()) { texturesByName[path] = std::shared_ptr<SDL_Texture>(IMG_LoadTexture(renderer, path.c_str()), SDL_DestroyTexture); texture = texturesByName.find(path); if (!texture->second) { printlog("Image '%s' IMG:%s\n", path.c_str(), IMG_GetError()); } } imageResources[id] = std::shared_ptr<ImageDesc>(new ImageDesc(texture->second, rect)); } }); auto sprites = configuration.Get<LuaTable>("sprites"); sprites.ForAllIntegerKeys([&](int key, LuaType::Value type) { if (type == LuaType::table) { auto sprite = sprites.Get<LuaTable>(key); auto id = sprite.Get<int>("id"); auto imageIds = sprite.Get<LuaTable>("imageIds"); unsigned int delay = sprite.Get<int>("delay"); std::vector< std::shared_ptr<ImageDesc> > imageList; imageIds.ForAllIntegerKeys([&](int key, LuaType::Value type) { auto imageId = imageIds.Get<int>(key); imageList.push_back(GetImage(imageId)); }); SDL_Rect rect = *(imageList[0]->GetRect()); spriteResources[id] = std::shared_ptr<SpriteDesc>(new SpriteDesc(imageList, rect, delay)); } }); auto fonts = configuration.Get<LuaTable>("fonts"); fonts.ForAllIntegerKeys([&](int key, LuaType::Value type) { if (type == LuaType::table) { auto font = fonts.Get<LuaTable>(key); auto id = font.Get<int>("id"); auto path = font.Get<std::string>("path"); auto color = font.Get<LuaTable>("color"); auto ptsize = font.Get<int>("ptsize"); std::stringstream ss; ss << path << "@" << ptsize; auto fontFile = fontsByName.find(ss.str()); if (fontFile == fontsByName.end()) { fontsByName[path] = std::shared_ptr<TTF_Font>(TTF_OpenFont(path.c_str(), ptsize), TTF_CloseFont); fontFile = fontsByName.find(path); TTF_SetFontHinting(fontFile->second.get(), 1); TTF_SetFontKerning(fontFile->second.get(), 1); } SDL_Color c; c.a = 0xff; c.r = (Uint8)color.Get<int>("r"); c.g = (Uint8)color.Get<int>("g"); c.b = (Uint8)color.Get<int>("b"); fontResources[id] = std::shared_ptr<TTFFontDesc>(new TTFFontDesc(fontFile->second, c)); } }); }
void Sprite::load_image(){ image = SDL_Texture_ptr(IMG_LoadTexture(renderer.get(), filename.c_str()), SDL_DestroyTexture); }
TextResources(SDL_Renderer *ren) : mRen(ren) { mTexture = IMG_LoadTexture(mRen, "Resources/TextResources.png"); if (mTexture == nullptr) throw std::runtime_error("IMG_LoadTexture Error: " + std::string{ SDL_GetError() }); }
/** * Loads an image into a texture on the rendering device * @param file The image file to load * @param ren The renderer to load the texture onto * @return the loaded texture, or nullptr if something went wrong. */ SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){ SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str()); if (texture == nullptr) logSDLError(std::cout, "LoadTexture"); return texture; }
// tank creation Tank::Tank(SDL_Renderer *renderer, int pNum, string filePath, string audioPath, float x, float y) { // load the health GUI back = IMG_LoadTexture(renderer, (filePath + "health_1.png").c_str()); mid = IMG_LoadTexture(renderer, (filePath + "health_2.png").c_str()); front = IMG_LoadTexture(renderer, (filePath + "health_3.png").c_str()); empty = IMG_LoadTexture(renderer, (filePath + "emptyKeyGUI.png").c_str()); one = IMG_LoadTexture(renderer, (filePath + "oneKeyGUI.png").c_str()); two = IMG_LoadTexture(renderer, (filePath + "twoKeyGUI.png").c_str()); none = IMG_LoadTexture(renderer, (filePath + "tLegNoneGUI.png").c_str()); One = IMG_LoadTexture(renderer, (filePath + "tLegOneGUI.png").c_str()); Two = IMG_LoadTexture(renderer, (filePath + "tLegTwoGUI.png").c_str()); Three = IMG_LoadTexture(renderer, (filePath + "tLegThreeGUI.png").c_str()); // bring in the rock landing sound // sound effect for the rock hit //rockLand = Mix_LoadWAV((audioPath + "rockClatter.wav").c_str()); // set win condition to false win1 = false; win2 = false; key = 0; emptyR.x = oneR.x = twoR.x = 10; emptyR.y = oneR.y = twoR.y = 10; emptyR.w = oneR.w = twoR.w = 100; emptyR.h = oneR.h = twoR.h = 100; noneR.x = OneR.x = TwoR.x = ThreeR.x = 800; noneR.y = OneR.y = TwoR.y = ThreeR.y = 10; noneR.w = OneR.w = TwoR.w = ThreeR.w = 200; noneR.h = OneR.h = TwoR.h = ThreeR.h = 100; backR.x = midR.x = frontR.x = 350; backR.y = midR.y = frontR.y = 10; backR.w = midR.w = frontR.w = 300; backR.h = midR.h = frontR.h = 60; // player health playerHealth = 100.0f; maxHealth = 100.0f; active = true; playerNum = pNum; speed = 100.0f; // number of rocks Bibble starts with rocks = 3; // tank firing sound //fire = Mix_LoadWAV((audioPath + "fire.wav").c_str()); playerPath = filePath + "Bibble.png"; texture = IMG_LoadTexture(renderer, playerPath.c_str()); if(texture == NULL) { printf("Could not get image: %s\n", SDL_GetError()); } posRect.x = x; posRect.y = y; int w, h; SDL_QueryTexture(texture, NULL, NULL, &w, &h); posRect.w = w; posRect.h = h; pos_X = x; pos_Y = y; xDir = 0; yDir = 0; xDirOld = 1; yDirOld = 0; center.x = posRect.w/2; center.y = posRect.h/2; string bulletPath; if(playerNum == 0) { bulletPath = filePath + "rockItem.png"; } //create the player's bullet pool for (int i = 0; i < 10; i++) { //create the bullet and move offscreen, out of the gameplayer area Rocks tmpBullet(renderer, bulletPath, -1000, -1000, 0, 0); //add to bulletList bulletList.push_back(tmpBullet); } lockX = false; lockY = false; // create a pool of explosions - 10 for (int i = 0; i < 10; i++) { // create the enemy RockHit tmpExplode(renderer, filePath, -1000, -1000, 0); // add to the enemyList rockHitList.push_back(tmpExplode); } // create the rects for the rock ammo indicators oneRock.w = twoRock.w = threeRock.w = 80; oneRock.h = twoRock.h = threeRock.h = 80; oneRock.x = 10; twoRock.x = 90; threeRock.x = 170; oneRock.y = twoRock.y = threeRock.y = 700; }
CellularNetworkDemonstration::ViewWelcome::ViewWelcome(SDL_Renderer* renderer, int viewCode) :ViewBase(renderer, viewCode) { m_pWelcomeImage = IMG_LoadTexture(m_pRenderer, "view-welcome.png"); SDL_SetTextureBlendMode(m_pWelcomeImage, SDL_BLENDMODE_BLEND); }
int ihm1() { SDL_Texture *tmp_Tx; SDL_Event event; SDL_Rect rectLabelCoup = { 10 * CASE, 16 * CASE + 16, 0, 0 }; SDL_Rect rectSendMoves = { 7 * CASE, 17 * CASE, 64, 64 }; SDL_Rect rectReset = { 10 * CASE, 17 * CASE, 64, 64 }; SDL_Rect rectCoup = { 12 * CASE, 17 * CASE, CASE * 4, 64 }; SDL_Rect rectEmpty = { 0, 0, 64, 32 }; SDL_Rect rectUser = { 512, 32, 256, 32 }; SDL_Rect rectTime = { 3 * CASE, 17 * CASE, 2 * CASE, 32 }; SDL_Rect rectVoir = { 19 * CASE, 17 * CASE, 64, 64 }; SDL_Rect rectArret = { 16 * CASE, 17 * CASE, 64, 64 }; SDL_Rect rectSuivant = { 22 * CASE, 17 * CASE, 64, 64 }; Direction direction; int robotSelected; bool_t focusCoup, preFocusCoup; bool_t focusUser, preFocusUser; int userSelected; char message[256]; char move[3]; char timeChaine[32]; int lenCoups; char* labelCoup = "Veuillez entrer le nombre de coups :"; int x, y, i; /*initialisation*/ SDLS_init(768, 608, &win, &ren); if (TTF_Init() == -1) { fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError()); } empty_Tx = IMG_LoadTexture(ren, "assets/inputField.png"); font = TTF_OpenFont("assets/dayrom.TTF", 12); /*** Show **/ displayAccueil(win, ren); SDLS_affiche_image("assets/pl.png", ren, 0, 0); awaitLoadingTexte("attente de session ", PHASE_SESSION); focusCoup = preFocusCoup = FALSE; focusUser = preFocusUser = FALSE; userSelected = robotSelected = -1; direction = NONE; lenCoups = 0; memset(message, 0, sizeof(message)); memset(moves, 0, sizeof(moves)); memset(move, 0, sizeof(move)); memset(coups, 0, sizeof(coups)); if (!quit) { awaitLoadingTexte("attente d'enigme ", PHASE_REFLEX); // display labelCoup tmp_Tx = txt2Texture(ren, font, &colorBlack, labelCoup); SDL_QueryTexture(tmp_Tx, NULL, NULL, &rectLabelCoup.w, &rectLabelCoup.h); SDL_RenderCopy(ren, tmp_Tx, NULL, &rectLabelCoup); SDL_RenderPresent(ren); TTF_CloseFont(font); font = TTF_OpenFont("assets/dayrom.TTF", 20); } SDL_StartTextInput(); int k, save_yUser; while (!quit) { SDL_WaitEvent(&event); switch (event.type) { case SDL_MOUSEBUTTONDOWN: // handle send moves or coups numbers of moves if (estContenu(&rectSendMoves, &event.motion)) { if (currentPhase == PHASE_REFLEX && strlen(coups) > 0) { send_request(sc, 3, SOLUTION, myName, coups); } else if (currentPhase == PHASE_ENCHERE && strlen(coups) > 0) { valideCoups = (valideCoups == -1) ? atoi(coups) : valideCoups; send_request(sc, 3, ENCHERE, myName, coups); } else if (currentPhase == PHASE_RESO && strlen(moves) > 0 && moiJoue) { send_request(sc, 3, SOLUTION, myName, moves); } else { if (!moiJoue && currentPhase == PHASE_RESO) { displayMsg("Ce n'est pas votre tour", FALSE); } else { displayMsg("coup ou deplacement est vide ", FALSE); } } } // handle btn reset /*|| estContenu(&rectCoup, &event.motion)*/ if (estContenu(&rectReset, &event.motion) || estContenu(&rectCoup, &event.motion)) { if (strlen(moves) > 0 || strlen(coups) > 0) { onclickReset(initPl, &initEnigme, coups, moves); } } // handle btn arret simulation if (estContenu(&rectArret, &event.motion)) { if (modeVisualisation) { arreterVisualisation(); displayMsg("arret de visualisation", FALSE); } } // handle btn voir simulation if (estContenu(&rectVoir, &event.motion)) { if (userSelected >= 0) { displayMsg("visalisation", FALSE); demarrerVisualisation(userSelected); } } // handle btn suivant (movement suivant de la simulation if (estContenu(&rectSuivant, &event.motion)) { if (modeVisualisation) { pasVisualisation(); displayMsg("pas suivant", FALSE); } } // handle focus coups focusCoup = FALSE; if (estContenu(&rectCoup, &event.motion)) { SDLS_affiche_image("assets/focusCoups.png", ren, rectCoup.x, rectCoup.y + CASE); memset(coups, 0, sizeof(coups)); lenCoups = 0; preFocusCoup = focusCoup = TRUE; } // handle select user save_yUser = rectUser.y; focusUser = FALSE; for (k = 0; k < bilan.list_users.nb; k++) { if (estContenu(&rectUser, &event.motion)) { if (userSelected > -1) { int y = rectUser.y; rectUser.y = save_yUser + CASE * userSelected; SDLS_affiche_image("assets/unfocusUser.png", ren, rectUser.x, rectUser.y); rectUser.y = y; } SDLS_affiche_image("assets/focusUser.png", ren, rectUser.x, rectUser.y); preFocusUser = focusUser = TRUE; userSelected = k; } rectUser.y = rectUser.y + CASE; } rectUser.y = save_yUser; //handle move robot if (!modeVisualisation) { x = event.motion.x / CASE; y = event.motion.y / CASE; for (i = 0; i < NB_ROBOT; ++i) { if (enigme.robots[i].x == x && enigme.robots[i].y == y) robotSelected = i; } if (robotSelected > -1) { direction = estDirection(&enigme, &event.motion, robotSelected, -1, 0) == TRUE ? Gauche : direction; direction = estDirection(&enigme, &event.motion, robotSelected, 1, 0) == TRUE ? Droit : direction; direction = estDirection(&enigme, &event.motion, robotSelected, 0, -1) == TRUE ? Haut : direction; direction = estDirection(&enigme, &event.motion, robotSelected, 0, 1) == TRUE ? Bas : direction; } if (direction != NONE) { update_pos_robot(pl, &enigme.robots[robotSelected], direction); /* update dans moves le nouveau deplacement de robot et le coups*/ move[0] = enigme.robots[robotSelected].c; move[1] = direction; strcat(moves, move); sprintf(coups, "%d", ((int) (strlen(moves) / 2))); //update view updateView(&rectCoup, &rectEmpty); robotSelected = -1; direction = NONE; } // handle unfocus if (preFocusCoup && !focusCoup) { SDLS_affiche_image("assets/unfocusCoups.png", ren, rectCoup.x, rectCoup.y + CASE); preFocusCoup = focusCoup; } if (preFocusUser && !focusUser) { rectUser.y = save_yUser + CASE * userSelected; SDLS_affiche_image("assets/unfocusUser.png", ren, rectUser.x, rectUser.y); rectUser.y = save_yUser; userSelected = -1; preFocusUser = focusUser; } } break; // handle entrer en dur le nb coups case SDL_TEXTINPUT: if (focusCoup && ((currentPhase & PHASE_REFLEX) || (currentPhase & PHASE_ENCHERE))) { int nb = estEntier(event.text.text); if (0 <= nb && nb <= 9) { if (lenCoups < 4) { coups[lenCoups++] = event.text.text[0]; tmp_Tx = txt2Texture(ren, font, &colorBlack, coups); displayCoup(tmp_Tx, rectCoup, &rectEmpty); SDL_RenderPresent(ren); } } } break; case SDL_QUIT: quit = TRUE; break; } // UPDATE Time memset(timeChaine, 0, 32); formatTime(SDL_GetTicks() - timeStart, timeChaine); SDLS_affiche_image("assets/emptyTT.png", ren, rectTime.x, rectTime.y); tmp_Tx = txt2Texture(ren, font, &colorBlack, timeChaine); SDL_QueryTexture(tmp_Tx, NULL, NULL, &rectTime.w, &rectTime.h); SDL_RenderCopy(ren, tmp_Tx, &rectEmpty, &rectTime); SDL_RenderPresent(ren); } TTF_CloseFont(font); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); send_request(sc, 2, SORT, myName); pthread_cancel(thread_com); pthread_cancel(thread_chat); SDL_Quit(); return 0; }
SDL_Texture *load_texture(const char *file, SDL_Renderer *ren){ SDL_Texture *texture = IMG_LoadTexture(ren, file); if(!texture) err_msg("LoadTexture"); return texture; }
// Initializes a texture, including size and position void Texture::LoadTexture( SDL_Renderer *renderer, const std::string &str ) { texture = IMG_LoadTexture( renderer, str.c_str() ); CalculateSize( ); }
void displayAccueil() { bool_t quitAccueil = FALSE; SDL_Event event; SDL_Color color = { 0, 0, 0, 0 }; if (TTF_Init() == -1) { fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError()); } TTF_Font *font = TTF_OpenFont("assets/dayrom.TTF", 20); SDL_Texture *inputField_Tx; SDL_Texture *emptyInput_Tx = IMG_LoadTexture(ren, "assets/inputField.png"); SDL_Rect rectInputField = { 8 * CASE, 8 * CASE, 0, 0 }; SDL_Rect rectEmptyField = { 8 * CASE, 8 * CASE, 9 * CASE, 64 }; SDL_Rect rectSend = { 17 * CASE, 8 * CASE, 64, 64 }; memset(myName, 0, 256); int len = 0; bool_t shift, updateInput; shift = updateInput = FALSE; SDLS_affiche_image(ACC, ren, 0, 0); while (!quitAccueil && !quit) { SDL_WaitEvent(&event); switch (event.type) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_DELETE: len = (len == 0) ? len : len - 1; myName[len] = 0; updateInput = TRUE; break; case SDLK_BACKSPACE: len = (len == 0) ? len : len - 1; myName[len] = 0; updateInput = TRUE; break; case SDLK_KP_ENTER: break; case SDLK_LSHIFT: case SDLK_RSHIFT: shift = TRUE; break; default: if (event.key.keysym.sym >= 'a' && event.key.keysym.sym <= 'z') { myName[len++] = event.key.keysym.sym - ((shift == TRUE) ? 32 : 0); updateInput = TRUE; } break; } break; case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_LSHIFT: case SDLK_RSHIFT: shift = FALSE; break; } break; case SDL_MOUSEBUTTONDOWN: if (estContenu(&rectSend, &event.motion)) { if (len <= 0) { displayMsg("nom vide", FALSE); } else { send_request(sc, 2, CONNEXION, myName); awaitLoading(); quitAccueil = TRUE; } } break; case SDL_MOUSEBUTTONUP: break; case SDL_QUIT: quit = TRUE; quitAccueil = TRUE; break; } if (updateInput) { updateInput = FALSE; inputField_Tx = txt2Texture(ren, font, &color, myName); SDL_QueryTexture(inputField_Tx, NULL, NULL, &rectInputField.w, &rectInputField.h); SDL_RenderCopy(ren, emptyInput_Tx, NULL, &rectEmptyField); SDL_RenderCopy(ren, inputField_Tx, NULL, &rectInputField); SDL_RenderPresent(ren); } } TTF_CloseFont(font); }
int main(int, char**){ Conway Cellular(N); Cellular.FieldFillRand(); /* for (int i = 0; i < N; ++i) { if (i%2) printf("\n"); else printf("\n "); for (int j = 0; j < N; ++j) { Field[i][j]= rand() % 2; printf("%u ",Field[i][j]); } } */ SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); const std::string resPath = getResourcePath("Lesson5"); SDL_Texture *tex = IMG_LoadTexture(renderer, "hex_102_88_g.png"); SDL_Texture *texI = IMG_LoadTexture(renderer, "hex_102_88_black.png"); double ratio = ((double)SCREEN_WIDTH / N) / CLIP_W; SDL_Rect dst,clip; clip.x = 0; clip.y = 0; clip.w = CLIP_W; clip.h = CLIP_H; dst.x = 400; dst.y = 400; //dst.w = CLIP_W/2; dst.w = CLIP_W * ratio; dst.h = CLIP_H * ratio; printf("dst.w = %d, dst.h = %d, ratio = %lf\n",dst.w,dst.h,ratio); //SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h); SDL_QueryTexture(texI, NULL, NULL, &clip.w, &clip.h); SDL_QueryTexture(tex, NULL, NULL, &clip.w, &clip.h); int alive; SDL_Event e; bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT){ quit = true; } //Use number input to select which clip should be drawn if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_ESCAPE: quit = true; break; case SDLK_1: Cellular.addGlider(rand() % (N-3),rand() % (N-3)); ; break; default: break; } } } alive = Cellular.Step(); printf("Alive = %d\n", alive); SDL_RenderClear(renderer); for (int i = 0; i < N; ++i) { dst.y = (dst.h*0.7)*i; for (int j = 0; j < N; ++j) { if (i%2) dst.x = j*dst.w; else dst.x = dst.w/2 + j*dst.w; if (Cellular.Cell(i,j)) SDL_RenderCopy(renderer, tex, &clip, &dst); //else SDL_RenderCopy(renderer, texI, &clip, &dst); } } /* SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); SDL_Rect rectangle; rectangle.x = 100; rectangle.y = 100; rectangle.w = 250; rectangle.h = 450; SDL_RenderFillRect(renderer, &rectangle); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);*/ //Update the screen SDL_RenderPresent(renderer); SDL_Delay(500); } //Clean up cleanup(tex, renderer, window); cleanup(texI, renderer, window); IMG_Quit(); SDL_Quit(); return 0; }
int8_t rockpush_menu(Rock_Screen *screen_data) { SDL_Event event; SDL_Surface *menu; SDL_Surface *sprite_textures; SDL_Texture *font_surface; Rock_Sprite *rocco; Rock_Scroll_Map map; Mix_Music *music; TTF_Font *menu_font; bool done = false; Uint32 init_ms; char font_path[128]; int16_t offset; int8_t orientation, total_options, option; Sint32 event_option; SDL_Joystick *joystick = NULL; Sint16 joy_event = 0, joyy = 0; if (SDL_NumJoysticks() >= 1) { joystick = SDL_JoystickOpen(0); SDL_JoystickEventState(SDL_ENABLE); } if ((menu_font = TTF_OpenFont(MENU_TTF, 34)) == NULL) { printf("Error %s\n", TTF_GetError()); exit(EXIT_FAILURE); } gfx_check_gpu(screen_data->screen); if (gfx_get_low_gpu()) sprintf(font_path, "%s", TINY_FONT_PATH); else sprintf(font_path, "%s", FONT_PATH); if ((font_surface = IMG_LoadTexture(screen_data->screen, font_path)) == NULL) { printf("La fuente bitmap no encontrada %s\n", SDL_GetError()); exit(EXIT_FAILURE); } menu = screen_make_surface(SCREEN_WIDTH, SCREEN_HEIGHT); sprite_textures = screen_make_surface(screen_data->sprites_surface->w, screen_data->sprites_surface->h); map.view_height = MINI_HEIGHT * TILE_SIZE; map.view_width = MINI_WIDTH * TILE_SIZE; map.scroll_shift = SCROLL_SHIFT / 2; map.diamonds = 0; map.level = (rand() % 15); map.points = 0; map.lives = INIT_ROCCO_LIVE; map.update_score = false; map.refresh_rocco = false; rocco = set_level_rocco(&map); rocco->active = false; map.objects_map[rocco->x_map][rocco->y_map] = EMPTY; map.rockmap[rocco->x_map][rocco->y_map] = GRASS; sprites_set_tiles_textures(); //Se hace una copia de las texturas cargadas para convertirlas a B/N SDL_BlitSurface(screen_data->sprites_surface, NULL, sprite_textures, NULL); screen_greyscale(screen_data->sprites_surface); orientation = (rand() % 4) + 2; option = offset = 0; total_options = menu_options(option, map.view_width, menu, menu_font); gfx_init(); screen_data->blit_surface = true; SDL_SetRenderDrawColor(screen_data->screen, 0, 0, 0, 255); SDL_RenderClear(screen_data->screen); if (sfx_get_active()) { music = Mix_LoadMUS(MENU_MUSIC); Mix_PlayMusic(music, -1); } while (!done) { init_ms = SDL_GetTicks(); map_show(screen_data, &map, false); map_move(&map, orientation); SDL_BlitSurface(menu, NULL, screen_data->buffer_surface, NULL); //sprites_update(&map); screen_dump_buffer(screen_data, map.view_width, map.view_height); offset ++; if (offset > 240) { orientation = (rand() % 4) + 2; offset = 0; } /* Desplazamiento de texto */ gfx_text_move(screen_data->screen, font_surface); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { option = 0; done = true; } if (SDL_JoystickGetAttached(joystick)) joy_event = SDL_JoystickGetAxis(joystick, 0) | SDL_JoystickGetAxis(joystick, 1); if (event.type == SDL_KEYDOWN || event.type == SDL_JOYBUTTONDOWN || joy_event) { event_option = event.key.keysym.sym; if (SDL_JoystickGetAttached(joystick)) { joyy = SDL_JoystickGetAxis(joystick, 1); joy_event = SDL_JoystickGetAxis(joystick, 0) | joyy; if (SDL_JoystickGetButton(joystick, 0)) event_option = SDLK_ESCAPE; if (SDL_JoystickGetButton(joystick, 1)) event_option = SDLK_RETURN; if (joyy < -10) event_option = SDLK_UP; if (joyy > 10) event_option = SDLK_DOWN; } switch (event_option) { case SDLK_UP: if (option > 0) option --; break; case SDLK_DOWN: if (option < total_options) option ++; break; case SDLK_ESCAPE: option = -1; case SDLK_RETURN: done = true; option ++; break; } menu_options(option, map.view_width, menu, menu_font); } } while ((SDL_GetTicks() - init_ms) < TICK_RATE); } //Restauramos la copia SDL_BlitSurface(sprite_textures, NULL, screen_data->sprites_surface, NULL); SDL_SetRenderDrawColor(screen_data->screen, 0, 0, 0, 255); SDL_RenderClear(screen_data->screen); screen_data->blit_surface = false; SDL_FreeSurface(sprite_textures); SDL_DestroyTexture(font_surface); SDL_FreeSurface(menu); TTF_CloseFont(menu_font); if (SDL_JoystickGetAttached(joystick)) SDL_JoystickClose(joystick); if (sfx_get_active()) { Mix_FadeOutMusic(SFX_FADE_OUT); while (Mix_PlayingMusic()) ; Mix_FreeMusic(music); } return option; }
Turret::Turret(SDL_Renderer *renderer, string filePath, string audioPath, float x, float y) { //activate active = true; e1K = false; tHealth = 10; powderDropped = false; fire = Mix_LoadWAV((audioPath + "fire.wav").c_str()); hitP = Mix_LoadWAV((audioPath + "hit.wav").c_str()); string basePath = filePath + "tBase.png"; tBase = IMG_LoadTexture(renderer, basePath.c_str()); string barrelPath = filePath + "tHead.png"; tBarrel = IMG_LoadTexture(renderer, barrelPath.c_str()); string powderPath = filePath + "Bag.png"; powder = IMG_LoadTexture(renderer, powderPath.c_str()); powderRect.x = x; powderRect.y = y; int w, h; SDL_QueryTexture(powder, NULL, NULL, &w, &h); powderRect.w = w; powderRect.h = h; baseRect.x = x; baseRect.y = y; SDL_QueryTexture(tBase, NULL, NULL, &w, &h); baseRect.w = w; baseRect.h = h; barrelRect.x = x +46; barrelRect.y = y +46; SDL_QueryTexture(tBarrel, NULL, NULL, &w, &h); barrelRect.w = w; barrelRect.h = h; center.x = 12; center.y = 12; string bulletPath = filePath + "tbullet.png"; for (int i = 0; i < 10; i++) { TurretBullet tmpBullet(renderer, bulletPath, 1500, 1500); bulletList.push_back(tmpBullet); } srand(time(NULL)); //update the float posB_X = baseRect.x; posB_Y = baseRect.y; posT_X = baseRect.x; posT_Y = baseRect.x; }
std::shared_ptr<Texture> Generic::Load(std::vector<std::vector<int>> map, std::shared_ptr<Entity> ent, std::string path, unsigned width, unsigned height, float starting_point_x, float starting_point_y, int frame_width, int frame_height) { if (!path.size()) { Output_Handler::Error << "ERR Generic::Load : No path supplied\n"; return nullptr; } if (!map.size() || !map[0].size()) { Output_Handler::Error << "ERR Generic::Change : Given map has width/height equal to 0\n"; return nullptr; } SDL_Texture* gt = nullptr; for (auto& ttr : Texture::__Textures) if (path == ttr->__Path && dynamic_cast<Generic*>(ttr.get())) { gt = dynamic_cast<Generic*>(ttr.get())->__Generic_Texture; break; } if (!gt) gt = IMG_LoadTexture(Screen::Renderer, path.c_str()); if (!gt) { Output_Handler::Error << "ERR Texture::Load : No valid texture file supplied\n"; return nullptr; } auto texture = SDL_CreateTexture ( Screen::Renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, frame_width * map[0].size(), frame_height * map.size() ); if (!texture) { Output_Handler::Error << "ERR Texture::Load : Couldn't create SDL_Texture (probably size is too big)\n"; SDL_DestroyTexture(gt); return nullptr; } Texture::__Textures.emplace_back(std::make_shared<Generic>()); Texture::__Load(ent, Texture::__Textures.back(), frame_width * map[0].size(), frame_height * map.size(), starting_point_x, starting_point_y); std::shared_ptr<Generic> ts = std::static_pointer_cast<Generic>(Texture::__Textures.back()); ts->__Generic_Texture = gt; ts->__Generic_Width = width; ts->__Generic_Height = height; ts->__Width = frame_width * map[0].size(); ts->__Height = frame_height * map.size(); ts->__SDL_Texture = texture; ts->__Tilemap = map; ts->__Path = path; if (frame_width == 0) ts->Frame_Width = width; else if (frame_width < 0) ts->Frame_Width = width / -frame_width; else ts->Frame_Width = frame_width; if (frame_height == 0) ts->Frame_Height = height; else if (frame_height < 0) ts->Frame_Height = height / -frame_height; else ts->Frame_Height = frame_height; if (ent) ent->texture = Texture::__Textures.back(); SDL_SetTextureBlendMode(ts->__SDL_Texture, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(Screen::Renderer, ts->__SDL_Texture); SDL_Rect src = { 0,0, (int)frame_width, (int)frame_height }; SDL_Rect dst = { 0,0, (int)frame_width, (int)frame_height }; auto get_frame_pos = [&ts](int frame)->std::pair<int, int> { if (frame < 0) return std::pair<int, int>( frame, frame ); std::pair<int, int> p; p.second = 0; p.first = frame * (int)ts->Frame_Width; while (p.first >= (int)ts->__Generic_Width) { p.first -= ts->__Generic_Width; p.second += ts->Frame_Height; } return p; }; SDL_RenderClear(Screen::Renderer); for (unsigned i = 0; i < map.size(); i++) { for (unsigned j = 0; j < map[i].size(); j++) { if (map[i][j] < (int)ts->Tiles_Count()) { auto frame_pos = get_frame_pos(map[i][j]); src.x = frame_pos.first; src.y = frame_pos.second; } else { Output_Handler::Output << "MSG Generic::Change : Tile " << map[i][j] << " doesn't exist (max " << ts->Tiles_Count() - 1 << "); no tile is drawn\n"; src.x = 0; src.y = 0; } if(src.x >= 0 && src.y >= 0) SDL_RenderCopy(Screen::Renderer, ts->__Generic_Texture, &src, &dst); dst.x += frame_width; } dst.y += frame_height; dst.x = 0; } //ent->__Type = ET_Generic; SDL_SetRenderTarget(Screen::Renderer, NULL); return Texture::__Textures.back(); }
void startscreen(SDL_Window *screen,uint *state,uint *grapset,uint *fullscreen) { /* Renderer (with VSync, nice !) */ SDL_Renderer *renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_PRESENTVSYNC|SDL_RENDERER_ACCELERATED); SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "0"); SDL_RenderSetLogicalSize(renderer, 256, 192); uint exit = 0; uint musicplay = 0; SDL_Rect srcintro = {0,0,256,192}; SDL_Rect desintro = {0,0,256,192}; SDL_Event keyp; /* Loading PNG */ SDL_Texture *intro = IMG_LoadTexture(renderer, DATADIR "/graphics/intro.png"); SDL_Texture *intromd = IMG_LoadTexture(renderer, DATADIR "/graphics/intromd.png"); /* Load audio */ Mix_Music *music = Mix_LoadMUS(DATADIR "/sounds/MainTitleN.ogg"); while (exit != 1) { /* Cleaning the renderer */ SDL_RenderClear(renderer); /* Put image on renderer */ if (*grapset == 0) SDL_RenderCopy(renderer, intro, &srcintro, &desintro); else SDL_RenderCopy(renderer, intromd, &srcintro, &desintro); /* Flip ! */ SDL_RenderPresent(renderer); /* Play music if required */ if (musicplay == 0) { musicplay = 1; Mix_PlayMusic(music, 0); } /* Check keyboard */ if ( SDL_PollEvent(&keyp) ) { if (keyp.type == SDL_KEYDOWN) { /* Key pressed */ if (keyp.key.keysym.sym == SDLK_c) { /* Change graphic set */ if (*grapset == 0) *grapset = 1; else *grapset = 0; } if (keyp.key.keysym.sym == SDLK_i) { /* Show instructions */ if (srcintro.y == 0) srcintro.y = 192; else { srcintro.y = 0; musicplay = 0; } } if (keyp.key.keysym.sym == SDLK_f) { /* Switch fullscreen/windowed */ if (*fullscreen == 0) { SDL_SetWindowFullscreen(screen,SDL_WINDOW_FULLSCREEN_DESKTOP); *fullscreen = 1; } else { SDL_SetWindowFullscreen(screen,0); *fullscreen = 0; } } if (keyp.key.keysym.sym == SDLK_SPACE) { /* Start game */ *state = 1; exit = 1; } if (keyp.key.keysym.sym == SDLK_ESCAPE) { /* Exit game */ exit = 1; *state = 6; } } } } /* Cleaning */ SDL_DestroyTexture(intro); SDL_DestroyTexture(intromd); SDL_DestroyRenderer(renderer); }
int main() { // Init SDL printf("Initializing SDL\n"); Init(); //SDL_RenderClear(Renderer); // SDL_CreateTextureFromSurface(Renderer, crateS); SDL_Texture* yellow_crate = IMG_LoadTexture(Renderer, "gfx/yellow_crate.png"); SDL_Texture* blue_crate = IMG_LoadTexture(Renderer, "gfx/blue_crate.png"); SDL_Texture* craneT = IMG_LoadTexture(Renderer, "gfx/crane.png"); if(yellow_crate == NULL || blue_crate == NULL || craneT == NULL) { printf("ERROR: %s", SDL_GetError()); } int sceneHeigth = 8; int sceneWidth = 3; // Scene and crane stuff Scene scene; std::vector<Box> start; std::vector<Box> result; std::vector< std::vector<int> > functions; functions.resize(4); functions[0].push_back(FUNC2); functions[0].push_back(FUNC3); functions[0].push_back(FUNC1); functions[1].push_back(GRAB); functions[1].push_back(RIGHT); functions[1].push_back(FUNC4); functions[2].push_back(FUNC4); functions[2].push_back(GRAB); functions[2].push_back(RIGHT); functions[3].push_back(GRAB); functions[3].push_back(LEFT); start.push_back(Box(1,1, YELLOW)); start.push_back(Box(2,1, BLUE)); start.push_back(Box(3,1, YELLOW)); start.push_back(Box(4,1, BLUE)); start.push_back(Box(5,1, YELLOW)); start.push_back(Box(6,1, BLUE)); result.push_back(Box(4, 0, BLUE)); result.push_back(Box(5, 0, BLUE)); result.push_back(Box(6, 0, BLUE)); result.push_back(Box(4, 2, YELLOW)); result.push_back(Box(5, 2, YELLOW)); result.push_back(Box(6, 2, YELLOW)); scene.Init(sceneHeigth, sceneWidth, start, result, functions); scene.crane.pos.y = 1; int res = NOT_DONE; int function, task; bool quit = false; SDL_Event e; SDL_Rect cratePos; cratePos.w = CRATE_SIZE; cratePos.h = CRATE_SIZE; SDL_Rect crateBasePos; crateBasePos.x = 30; crateBasePos.y = 20; crateBasePos.w = CRATE_SIZE; crateBasePos.h = CRATE_SIZE; SDL_Rect cranePos; cranePos.x = 30; cranePos.y = 200; cranePos.w = 80; cranePos.h = 76; SDL_Rect rect; rect.x = 20; rect.y = crateBasePos.y+CRATE_SIZE*(sceneHeigth-1); rect.w = 80; rect.h = 40; printf("Rect y: %d\n", rect.y); SDL_Rect basePos = rect; printf("Main Loop!\n"); while(!quit) { if(res == NOT_DONE) { res = scene.Tick( &function, &task); } else if(res == SUCCES) { printf("YOU WON\n"); res = DONE; } else if(res == FAILURE) { printf("YOU LOST!\n"); res = DONE; } //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } //User presses a key else if( e.type == SDL_KEYDOWN ) { //Select surfaces based on key press switch( e.key.keysym.sym ) { case SDLK_UP: printf("UP pressed!\n"); break; } } } // Render box's in grid for (int i = 0; i < (int)scene.box.size(); ++i) { if(scene.box[i].pos.x == 0) // Box is in crane, so use that pos cratePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.crane.pos.y); else cratePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.box[i].pos.y); cratePos.y = crateBasePos.y-CRATE_SIZE*(-scene.box[i].pos.x); switch(scene.box[i].color) { case YELLOW: SDL_RenderCopy( Renderer, yellow_crate, NULL, &cratePos ); break; case BLUE: SDL_RenderCopy( Renderer, blue_crate, NULL, &cratePos ); break; }; } for(int i = 0; i < sceneWidth; i++) { basePos.x = rect.x+(CRATE_SIZE+40)*i; Draw::FilledRectangleRoundEdge(Renderer, basePos, 10); } cranePos.x = crateBasePos.x+(CRATE_SIZE+40)*(scene.crane.pos.y)-10; cranePos.y = crateBasePos.y-CRATE_SIZE*(-scene.crane.pos.x)-20; SDL_RenderCopy(Renderer, craneT, NULL, &cranePos ); //Apply the image //SDL_RenderCopy( Renderer, crateT, NULL, &cratePos ); //SDL_RenderCopy( Renderer, crateT, NULL, &cratePos2); SDL_RenderPresent(Renderer); SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 0); SDL_RenderClear(Renderer); SDL_SetRenderDrawColor(Renderer, 100, 0, 0, 0); SDL_Delay(750); } SDL_DestroyRenderer( Renderer ); SDL_DestroyWindow( Window ); SDL_Quit(); return 0; }
SDLTexture Window::LoadImage(const std::string& file){ SDLTexture texture(IMG_LoadTexture(mRenderer.get(), file.c_str())); if (texture.get() == nullptr) throw std::runtime_error("Failed to load image: " + file + IMG_GetError()); return texture; }
void Csprites::setImage(std::string FilePath) { filePath = FilePath; image = IMG_LoadTexture(renderer, filePath.c_str()); }
int main(){ TempSettings gamesettings; gamesettings.mapw = 10; gamesettings.maph = 6; gamesettings.mapx = 0; gamesettings.mapy = 0; gamesettings.mapmidx = gamesettings.mapw/2.0; gamesettings.mapmidy = gamesettings.maph/2.0; gamesettings.window_width = 1300; gamesettings.window_height = 800; // initialize window, renderer, textures if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return 1; } if (TTF_Init() != 0){ std::cerr << "TTF_Init error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Window* window = SDL_CreateWindow("deathblade_floating", 0, 0, gamesettings.window_width, gamesettings.window_height, SDL_WINDOW_SHOWN); if (window == nullptr){ std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == nullptr){ std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl; SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string resource_path = getResourcePath(""); std::string charfile = resource_path + "initialcharacter.png"; std::string bgfile = resource_path + "initialbackgroundtile.png"; std::string starfile = resource_path + "star.png"; std::string wallfile = resource_path + "wall.png"; SDL_Texture* character_texture = IMG_LoadTexture(renderer, charfile.c_str()); SDL_Texture* bgtile_texture = IMG_LoadTexture(renderer, bgfile.c_str()); SDL_Texture* star_texture = IMG_LoadTexture(renderer, starfile.c_str()); SDL_Texture* wall_texture = IMG_LoadTexture(renderer,wallfile.c_str()); if (character_texture == nullptr || bgtile_texture == nullptr || star_texture == nullptr || wall_texture == nullptr){ std::cerr << "IMG_LoadTexture error: " << SDL_GetError() << std::endl; SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 1; } std::string fontfile = resource_path + "sample.ttf"; TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 15); if (font == NULL){ std::cerr << "TTF_OpenFont error: " << SDL_GetError() << std::endl; } CameraControl camera(&gamesettings); ObjectController objects; DeveloperConsoleClass console(&gamesettings); console.add_controller(&console); console.add_controller(&camera); const double tilew = 0.5; const double tileh = 0.5; double mousex = gamesettings.mapmidx; double mousey = gamesettings.mapmidy; int mousepx = gamesettings.window_width/2; int mousepy = gamesettings.window_height/2; double wallthickness = 0.1; TextureWall bottomwall, topwall, leftwall, rightwall; bottomwall.x = gamesettings.mapw/2; bottomwall.y = gamesettings.maph+wallthickness/2; bottomwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&bottomwall); topwall.x = gamesettings.mapw/2; topwall.y = -wallthickness/2; topwall.setTexture(wall_texture,gamesettings.mapw,wallthickness); objects.add_object(&topwall); leftwall.x = -wallthickness/2; leftwall.y = gamesettings.maph/2; leftwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&leftwall); rightwall.x = gamesettings.mapw + wallthickness/2; rightwall.y = gamesettings.maph/2; rightwall.setTexture(wall_texture,wallthickness,gamesettings.maph); objects.add_object(&rightwall); Player human; human.x = 5; human.y = 5; human.dx = -0.025; human.dy = -0.03; human.setTexture(character_texture, 0.05, 0.05); objects.add_object(&human); // map x [0, 10] // map y [0, 6] // star width 0.256 std::vector<vec2d> star_positions = { vec2d(6,4), vec2d(3,4.1), vec2d(9,0.2), vec2d(1,0.4), vec2d(2,2.5), vec2d(3,2.5), vec2d(9,4.9), vec2d(0.2,5.1), vec2d(4.1,4.1) }; std::vector<double> star_thetas = { 0, 45, 15, 60, 85, 4, 50, 66, 31 }; std::vector<Star*> star_field; for(unsigned int i = 0; i < star_positions.size(); ++i){ Star* newstar = new Star(); newstar->x = star_positions[i].x; newstar->y = star_positions[i].y; newstar->setTexture(star_texture, 0.256, 0.256); if(i < star_thetas.size()) newstar->rotate(star_thetas[i]*3.14159265359/180.0); star_field.push_back(newstar); objects.add_object(star_field[i]); } bool rightmouse_down = false; SDL_Event event; bool quitnow = false; Uint32 fps_lastframe = SDL_GetTicks(); while(!quitnow){ int zoomdirection = 0; while(SDL_PollEvent(&event)){ if (console.is_active()){ if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_BACKSPACE: console.backspace(); break; case SDLK_RETURN: case SDLK_RETURN2: console.enter(); break; case SDLK_UP: console.goback_inhistory(); break; case SDLK_DOWN: console.goforward_inhistory(); break; default: break; } console.render_current_command(renderer); } else if (event.type == SDL_TEXTINPUT && event.text.text[0] != '`'){ console.addinput(event.text.text); console.render_current_command(renderer); } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ if(!console.mouse_grab(true, event.button.x, event.button.y)) camera.mousecontrol_on(); } //if (event.button.button == SDL_BUTTON_RIGHT) } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ console.mouse_grab(false, -1,-1); camera.mousecontrol_off(); } } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; console.handle_mouse(event.motion.xrel, event.motion.yrel); if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); } } else if (event.type == SDL_MOUSEWHEEL){ if(!console.scroll(event.wheel.y, mousepx, mousepy)) zoomdirection += event.wheel.y; } else if (event.type == SDL_QUIT){ quitnow = true; } continue; } // if console is not up if (event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_ESCAPE: quitnow = true; break; case SDLK_BACKQUOTE: console.toggle(); break; case SDLK_t: if (!camera.is_tracking()) camera.track_object(&(human.x), &(human.y)); else camera.stop_tracking(); break; case SDLK_w: case SDLK_UP: camera.pan_updown(-1); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(-1); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(1); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(1); break; default: break; } } else if (event.type == SDL_KEYUP){ switch(event.key.keysym.sym){ case SDLK_w: case SDLK_UP: camera.pan_updown(0); break; case SDLK_a: case SDLK_LEFT: camera.pan_leftright(0); break; case SDLK_s: case SDLK_DOWN: camera.pan_updown(0); break; case SDLK_d: case SDLK_RIGHT: camera.pan_leftright(0); break; default: break; } } else if (event.type == SDL_MOUSEBUTTONDOWN){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_on(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = true; human.bound.xclick = camera.xfrompixel(event.button.x,event.button.y,db::Player); human.bound.yclick = camera.yfrompixel(event.button.x,event.button.y,db::Player); human.bound.xdrag = 0; human.bound.ydrag = 0; human.bound.enabled = true; } } else if (event.type == SDL_MOUSEBUTTONUP){ if (event.button.button == SDL_BUTTON_LEFT){ camera.mousecontrol_off(); } else if (event.button.button == SDL_BUTTON_RIGHT){ rightmouse_down = false; } } else if (event.type == SDL_MOUSEWHEEL){ zoomdirection += event.wheel.y; } else if (event.type == SDL_MOUSEMOTION){ mousepx = event.motion.x; mousepy = event.motion.y; if (camera.mouse_controlling()){ camera.mousecontrol_move(mousepx, mousepy, event.motion.xrel, event.motion.yrel,SDL_GetModState()==KMOD_LCTRL); } else{ mousex = camera.xfrompixel(event.motion.x, event.motion.y, db::Player); mousey = camera.yfrompixel(event.motion.x, event.motion.y, db::Player); if(mousepx <= 1) camera.pan_leftright(-1); else if (mousepx >= (int)gamesettings.window_width-1) camera.pan_leftright(1); else if (mousepx - event.motion.xrel <= 1) camera.pan_leftright(0); else if (mousepx - event.motion.xrel >= (int)gamesettings.window_width-1) camera.pan_leftright(0); if(mousepy <= 1) camera.pan_updown(-1); else if (mousepy >= (int)gamesettings.window_height-1) camera.pan_updown(1); else if (mousepy - event.motion.yrel <= 1) camera.pan_updown(0); else if (mousepy - event.motion.yrel >= (int)gamesettings.window_height-1) camera.pan_updown(0); if(rightmouse_down){ human.bound.xdrag += event.motion.xrel; human.bound.ydrag += event.motion.yrel; } } } else if (event.type == SDL_QUIT){ quitnow = true; } } objects.step_time(); SDL_SetRenderDrawColor(renderer, 0,0,0,255); SDL_RenderClear(renderer); camera.adjust_zoom(zoomdirection, mousex, mousey); for (double x = gamesettings.mapx+tilew/2; x < gamesettings.mapx+gamesettings.mapw+tilew/2; x += tilew){ for (double y = gamesettings.mapy+tileh/2; y < gamesettings.mapy+gamesettings.maph+tileh/2; y += tileh){ SDL_Rect dst = camera.calculate_display_destination(x,y,tilew,tileh,db::Floor); SDL_RenderCopyEx(renderer, bgtile_texture, NULL, &dst, -camera.camyaw*180.0/3.14156033, NULL, SDL_FLIP_NONE); } } objects.drawon(renderer, &camera); if(console.is_active()) console.drawon(renderer); human.bound.drawon(renderer, &camera); Uint32 fps_newframe = SDL_GetTicks(); if((fps_newframe-fps_lastframe) < SCREEN_TICKS_PER_FRAME){ SDL_Delay(SCREEN_TICKS_PER_FRAME - (fps_newframe-fps_lastframe)); } draw_fps(renderer, font, 1.0/(fps_newframe/1000.0 - fps_lastframe/1000.0)); fps_lastframe = fps_newframe; SDL_RenderPresent(renderer); } SDL_DestroyTexture(character_texture); SDL_DestroyTexture(bgtile_texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); for(unsigned int i = 0; i < star_field.size(); ++i) delete star_field[i]; return 0; }
DrawConfig *create_DrawConfig(){ DrawConfig* config = malloc(sizeof(DrawConfig)); config->bird_tick_length = 100; config->last_bird_change = 0; config->bird_index = 0; config->window_width = 500; config->window_height = 500; /* * Initialize SDL and related libraries. */ if(SDL_Init(SDL_INIT_EVERYTHING) < 0){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"SDL_Init failed: %s\n",SDL_GetError()); } if(IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"IMG_Init for IMG_INIT_PNG failed %s\n",IMG_GetError()); } if(TTF_Init() == -1){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"TTF_Init faled %s\n",TTF_GetError()); } /* * create and initialize SDL resources. */ if(SDL_CreateWindowAndRenderer(config->window_width,config->window_height,0,&(config->window),&(config->renderer))){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create window and renderer: %s\n",SDL_GetError()); } /* * Set the windows title */ SDL_SetWindowTitle(config->window,"Flappy Bird"); /* * Load image files using SDL_image. */ char* bird_sheet_path = "resources/images/bird_sheet.png"; config->bird_sprite_sheet = IMG_LoadTexture(config->renderer,bird_sheet_path); if(config->bird_sprite_sheet == NULL){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Image at \"%s\" failed to load: %s\n",bird_sheet_path,IMG_GetError()); } for(int i = 0; i < BIRD_SPRITE_NUM; i++){ /*32 is a magic number. Woops!*/ config->bird_texture_array[i].x = 32 * i; config->bird_texture_array[i].y = 0; config->bird_texture_array[i].w = 32; config->bird_texture_array[i].h = 32; } char* background_path = "resources/images/background.png"; config->background_texture = IMG_LoadTexture(config->renderer,background_path); if(config->background_texture == NULL){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Image at \"%s\" failed to load: %s\n",background_path,IMG_GetError()); } char* pipe_path = "resources/images/pipe.png"; config->pipe_texture = IMG_LoadTexture(config->renderer,pipe_path); if(config->pipe_texture == NULL){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Image at \"%s\" failed to load: %s\n",pipe_path,IMG_GetError()); } char* pipetop_path = "resources/images/pipe-top.png"; config->pipe_top_texture = IMG_LoadTexture(config->renderer,pipetop_path); if(config->pipe_top_texture == NULL){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Image at \"%s\" failed to load: %s\n",pipetop_path,IMG_GetError()); } /* * Load font using TTF_Font */ char* font_path = "resources/fonts/VeraMono.ttf"; config->game_font = TTF_OpenFont(font_path,24); if(config->game_font == NULL){ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Font at \"%s\" failed to load: %s\n",font_path,TTF_GetError()); } return config; }
GusanoSprite::GusanoSprite(SDL_Renderer* renderer, SDL_Rect recDestino, string path, int col, int fil, int anchoTex, int altoTex, string nombre,int maximosCLientes): DibujableTextura(){ this->armaTipo = NINGUNA; this->numCuadros = col*fil; this->velocidadRefresco = timeGusanoQuieto; this->contador = 0; this->congelado = 0; this->crosshair = IMG_LoadTexture(renderer, rutaCrosshair); this->mostrarCrosshair = false; this->frameCrosshair = 0; this->posFigura = new SDL_Point(); int tamanioCuadroX = anchoTex / col; int tamanioCuadroY = altoTex / fil; this->frame = 0; this->rect = recDestino; this->rectApuntando = new SDL_Rect[32]; for(int i=0; i< 32; i++){ rectApuntando[i].h = 60; rectApuntando[i].w = 60; rectApuntando[i].x = 0; rectApuntando[i].y = i* 60; } this->recCuadro = new SDL_Rect[numCuadros]; for(int i=0; i< numCuadros; i++){ recCuadro[i].h = tamanioCuadroY; recCuadro[i].w = tamanioCuadroX; } for(int i=0; i<fil; i++){ for(int j=0; j<col; j++){ recCuadro[j + i*col].x = j* tamanioCuadroX; recCuadro[j + i*col].y = i* tamanioCuadroY; } } this->recPotencia = new SDL_Rect[17]; for(int i=0; i<17; i++){ this->recPotencia[i].h = 28; this->recPotencia[i].w = 244; this->recPotencia[i].x = 0; this->recPotencia[i].y = i*28; } this->rectTnt = new SDL_Rect[60]; for (int i= 0; i<60; i++){ rectTnt[i].h = 60; rectTnt[i].w = 60; rectTnt[i].x = 0; rectTnt[i].y = i*60; } this->rectGrave = new SDL_Rect[20]; for (int i= 0; i<20; i++){ rectGrave[i].h = 46; rectGrave[i].w = 60; rectGrave[i].x = 0; rectGrave[i].y = i*60; } this->rectSuicida = new SDL_Rect[20]; for (int i= 0; i<20; i++){ rectSuicida[i].h = 60; rectSuicida[i].w = 60; rectSuicida[i].x = 0; rectSuicida[i].y = i*60; } this->enUso = recCuadro; this->imagen = IMG_LoadTexture(renderer, path.c_str()); this->cambiarImgDer = false; this->cambiarImgIzq = false; this->muertePorDisparo = false; this->terminoIteracion = false; this->contIzq = 0; this->contDer = 0; this->contFrent = 0; this->contMuerte = 0; this->contArma = 0; this->contMuerteVida = 0; this->estado = IZQ; this->nombre = nombre; SDL_Rect rectCart = this->rect; rectCart.h = rect.h / 4; rectCart.x = this->rect.x + this->rect.w/2; this->maximosCLientes = maximosCLientes; //this->cartel = NULL; this->cartel = new CartelDibujable(renderer, rectCart, rutaCartel, rutaCartelDEF, this->nombre); rectCart.w = this->rect.w/2; rectCart.h = this->rect.h * 2/3; this->flecha = new DibujableTextura(renderer,rectCart, rutaFlecha,rutaFlecha); //this->mostrarCartel = false; for(int i=0; i < this->maximosCLientes; i++){ this->mostrarCartel.push_back(false); } this->cliente = 0; SDL_Rect rectVida = this->rect; rectVida.h = 5; rectVida.w = pxPorVida * vidaGusano; this->vida = new DibujableTextura(renderer,rectVida,rutaVida,rutaVida); int rgb[3]; rgb[0] = 0; rgb[1] = 255; rgb[2] = 0; this->vida->setColor(rgb); this->activo = false; this->ahogado = false; }
Draw::Draw() { window = NULL; backgroundImage = NULL; renderTarget = NULL; SDL_Init(SDL_INIT_VIDEO); int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) cout << "Error " << IMG_GetError() << endl; window = SDL_CreateWindow("GameWindow", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN); renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); backgroundImage = IMG_LoadTexture(renderTarget, "Textures/pureBackground.png"); texture = IMG_LoadTexture(renderTarget, "Textures/borderPattern.png"); snakeBody = IMG_LoadTexture(renderTarget, "Textures/body.png"); snakeHeadDown = IMG_LoadTexture(renderTarget, "Textures/headdown.png"); snakeHeadUp = IMG_LoadTexture(renderTarget, "Textures/headup.png"); snakeHeadLeft = IMG_LoadTexture(renderTarget, "Textures/headleft.png"); snakeHeadRight = IMG_LoadTexture(renderTarget, "Textures/headright.png"); snakeTail = IMG_LoadTexture(renderTarget, "Textures/tail.png"); apple = IMG_LoadTexture(renderTarget, "Textures/apple.png"); banana = IMG_LoadTexture(renderTarget, "Textures/banana.png"); bomb = IMG_LoadTexture(renderTarget, "Textures/bomb.png"); }
BouncyBallMain::BouncyBallMain(unsigned id, sbe::MainLoop const& main_loop) : Entity(id) , main_loop_(main_loop) , background_(IMG_LoadTexture(main_loop_.Renderer(), BACKGROUND_PATH.c_str())) , title_screen_(main_loop_.Renderer(), main_loop_.world()) , losing_screen_(main_loop_.Renderer(), main_loop_.world()) , pause_menu_(main_loop_.Renderer(), main_loop_.world()) , game_layer_(std::make_shared<sbe::EntityLayer>()) , game_started_(false) , losing_(false) { key_up.connect(sigc::mem_fun(this, &BouncyBallMain::OnKeyUp)); main_loop_.world()->SetGameData((void*)&bouncy_data_); bouncy_data_.left_scored.connect([this] { left_->Increment(); CheckIfWinning(); }); bouncy_data_.right_scored.connect([this] { right_->Increment(); CheckIfWinning(); }); title_screen_.start_clicked.connect([this] { StartGame(); }); title_screen_.two_player_clicked.connect([this] { right_paddle_->EnablePlayer(); right_paddle_->EnableEvents(); }); title_screen_.easy_clicked.connect([this] { right_paddle_->SetEasy(); }); title_screen_.medium_clicked.connect([this] { right_paddle_->SetMedium(); }); title_screen_.hard_clicked.connect([this] { right_paddle_->SetHard(); }); title_screen_.exit_clicked.connect([this] { // FIXME exit better then this... exit(0); }); losing_screen_.play_again.connect([this] { losing_screen_.Hide(); StartGame(); losing_ = false; }); losing_screen_.main_menu.connect([this] { losing_screen_.Hide(); ResetGame(); losing_ = false; }); pause_menu_.resume_clicked.connect([this] { pause_menu_.Hide(); game_layer_->UnPause(); }); pause_menu_.main_menu_clicked.connect([this] { pause_menu_.Hide(); game_layer_->UnPause(); ResetGame(); }); pause_menu_.restart_clicked.connect([this] { pause_menu_.Hide(); game_layer_->UnPause(); StartGame(); }); pause_menu_.exit_clicked.connect([this] { // FIXME exit better then this... exit(0); }); sbe::Rect const& bound = main_loop_.world()->Boundary(); sbe::Rect new_bound = {0, 10, bound.width(), bound.height() - 10}; main_loop_.world()->SetBoundary(new_bound); SetupGame(); title_screen_.SetMedium(); game_layer_->Hide(); losing_screen_.Hide(); pause_menu_.Hide(); main_loop_.world()->AddEntityLayer(game_layer_); }
SFApp::SFApp(std::shared_ptr<SFWindow> window) : fire(0), is_running(true), sf_window(window) { int canvas_w, canvas_h; SDL_GetRendererOutputSize(sf_window->getRenderer(), &canvas_w, &canvas_h); app_box = make_shared<SFBoundingBox>(Vector2(canvas_w, canvas_h), canvas_w, canvas_h); player = make_shared<SFAsset>(SFASSET_PLAYER, sf_window); auto player_pos = Point2(canvas_w/2, canvas_h/2); player->SetPosition(player_pos); back.x = 0; back.y = 0; back.w = 640; back.h = 800; back2.x = 0; back2.y = 0 - 800; back2.w = 640; back2.h = 800; healthpos.x = canvas_w - 40; healthpos.y = 15; healthpos.w = 32; healthpos.h = 450; healthgreenpos.h = 444; healthgreenpos.w = 26; healthgreenpos.x = healthpos.x + 3; healthgreenpos.y = healthpos.y + 3; gameoverpos.h = 400; gameoverpos.w = 560; gameoverpos.x = canvas_w / 2 - gameoverpos.w / 2; gameoverpos.y = canvas_h / 2 - gameoverpos.h / 2; d1 = IMG_LoadTexture(sf_window->getRenderer(), "assets/1.png"); d2 = IMG_LoadTexture(sf_window->getRenderer(), "assets/2.png"); d3 = IMG_LoadTexture(sf_window->getRenderer(), "assets/3.png"); d4 = IMG_LoadTexture(sf_window->getRenderer(), "assets/4.png"); d5 = IMG_LoadTexture(sf_window->getRenderer(), "assets/5.png"); d6 = IMG_LoadTexture(sf_window->getRenderer(), "assets/6.png"); d7 = IMG_LoadTexture(sf_window->getRenderer(), "assets/7.png"); d8 = IMG_LoadTexture(sf_window->getRenderer(), "assets/8.png"); d9 = IMG_LoadTexture(sf_window->getRenderer(), "assets/9.png"); d0 = IMG_LoadTexture(sf_window->getRenderer(), "assets/0.png"); scorepos.w = 16; scorepos.h = 16; scorepos.x = 10; scorepos.y = 10; gameoverimage = IMG_LoadTexture(sf_window->getRenderer(), "assets/gameover.png"); background = IMG_LoadTexture(sf_window->getRenderer(), "assets/background.png"); healthbar = IMG_LoadTexture(sf_window->getRenderer(), "assets/emptyhealth.png"); healthgreen = IMG_LoadTexture(sf_window->getRenderer(), "assets/healthbar.png"); }
SDL_Texture* Engine::makeTexture(const char* img_path) { SDL_Texture* texture = IMG_LoadTexture(renderer, img_path); return texture; }
PersonajeJugador::PersonajeJugador(int x, int y,SDL_Renderer* renderer,list<Personaje*>*personajes) { this->rectangulo.x=x; this->rectangulo.y=y; this->personajes=personajes; SDL_Texture *textura = IMG_LoadTexture(renderer, "assets/personajes/down1.png"); SDL_QueryTexture(textura, NULL, NULL, &this->rectangulo.w, &this->rectangulo.h); texturas_down.push_back(textura); texturas_down.push_back(IMG_LoadTexture(renderer, "assets/personajes/down2.png")); texturas_up.push_back(IMG_LoadTexture(renderer, "assets/personajes/up1.png")); texturas_up.push_back(IMG_LoadTexture(renderer, "assets/personajes/up2.png")); texturas_left.push_back(IMG_LoadTexture(renderer, "assets/personajes/izquierda1.png")); texturas_left.push_back(IMG_LoadTexture(renderer, "assets/personajes/izquierda2.png")); texturas_right.push_back(IMG_LoadTexture(renderer, "assets/personajes/derecha1.png")); texturas_right.push_back(IMG_LoadTexture(renderer, "assets/personajes/derecha2.png")); ataque_abajo.push_back(IMG_LoadTexture(renderer, "assets/personajes/ataque1.png")); ataque_derecha.push_back(IMG_LoadTexture(renderer, "assets/personajes/ataque2.png")); ataque_arriba.push_back(IMG_LoadTexture(renderer, "assets/personajes/ataque3.png")); ataque_izquierda.push_back(IMG_LoadTexture(renderer, "assets/personajes/ataque4.png")); orientacion="down"; rayo_orientacion = orientacion; rayo2_orientacion = orientacion; estado = "pasivo"; player = true; vivo = true; vida=50; rayo_texture = IMG_LoadTexture(renderer, "assets/ataques/rayo.png"); rayo2_texture = IMG_LoadTexture(renderer, "assets/ataques/rayo2.png"); SDL_QueryTexture(rayo_texture,NULL,NULL, &this->rayo_rect.w, &this->rayo_rect.h); SDL_QueryTexture(rayo2_texture,NULL,NULL, &this->rayo2_rect.w, &this->rayo2_rect.h); rayo_rect.x = 0; rayo_rect.y = 0; rayo2_rect.x = 0; rayo2_rect.y = 0; rayo_activado=false; rayo2_activado=false; rayo_cooldown = 100; rayo_frame_actual = 0; textura_actual = texturas_down.begin(); }
void m_LoadCharacter(const char *file) { m_character = IMG_LoadTexture(renderer, file); }