//////////////////////////////////////////////////////////////////// // Использую потом (не ВКЛЮЧЕНА) void MainPerson::computeAngle(RenderWindow &window) { Vector2i pixelPos = Mouse::getPosition(window);//забираем коорд курсора Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна) float dX = pos.x - spriteEntity->getPosition().x - width / 2;//вектор , колинеарный прямой, которая пересекает спрайт и курсор float dY = pos.y - spriteEntity->getPosition().y - height / 2;//он же, координата y rotation = (atan2(dY, dX)) * 180 / PI;//получаем угол в радианах и переводим его в градусы }
void Entity::computeAngle(RenderWindow &window) { Vector2i pixelPos = Mouse::getPosition(window); Vector2f pos = window.mapPixelToCoords(pixelPos); sizeSprite &size = type->featuresSprite.size; float dX = pos.x - spriteEntity->getPosition().x - size.width / 2; float dY = pos.y - spriteEntity->getPosition().y - size.height / 2; rotation = (atan2(dX , dY)) * 180 / PI - 180; if (rotation < 0) { rotation += 360; } }
//map<color, Color> colors = { // { Black, Color::Black }, // { White, Color::White }, // { Red, Color::Red }, // { Green, Color::Green }, // { Blue, Color::Blue }, // { Yellow, Color::Yellow }, // { Magenta, Color::Magenta }, // { Cyan, Color::Cyan }, // { Transparent, Color::Transparent }, // { Orange, Color(255, 128, 0) } //}; ////////////////////////// this returns a lambda ////////////////////////// function<void()> ////////////////////////// TYPE APP NAME ON LINE BELOW ////////////////////////// mine_solver (RenderWindow&window, ui &UI) { return [&window, &UI]() { #ifndef COMMON_INITS //void smoothmouse(RenderWindow&window, ui &UI){ // tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary function<void()> draw, loop, init, update; function<void(Vec2 pos)> mousemoved; function<void(sf::Mouse::Button button)> mouseclick, mouserelease; function<void(Event&e)> treatotherevent; function<void(Keyboard::Key k)> treatkeyevent; // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway. Texture cursor_tx; Sprite cursor; configfile cfg; cfg.init("bedlab.cfg"); Color background = cfg.getvar<Color>("background"); if (!cursor_tx.loadFromFile(cfg.getstr("cursor"))) cout << "did not load cursor" << endl; cursor.setTexture(cursor_tx); cursor.setOrigin(3, 3); window.setMouseCursorVisible(false); Vec2 mpos; bool leftclicked = false, rightclicked = false; // view and zoom View view, ui_view; ui_view = view = window.getDefaultView(); float zoomlevel = 1; Vec2 mpos_abs; #endif // COMMON_INITS // ************************ CODE BEGIN ************************ barstack bst(FONT, FONTSIZE); slider_finder sl; randgenfloat cell_rnd(0, 16); //grd. vector<string> mines_str = { " ", " 21114X411 ", " 3X22XX212 ", " X3--4433X ", " 23--4XX3X ", " 1X4---433 ", " 12X4--4X2 ", " 123X3XX3X ", " 2X2122221 ", " " }; int w = mines_str[0].length(); int h = mines_str.size(); vector<int> mine_states(h*w); grid grd; grd.screen_init(Vec2u(window.getSize()), Vec2u( w,h ), true); /* 1-8: surrounding mines 0 no mine, "clear" -1: unknown -2 mine */ map<char, int> lookup = { { '-',-1 }, { 'X',-2 }, { ' ',0 } }; int i = 0; logfile lg("minelog.txt"); lg.logw(to_str("i", "j", "index", "value")); for (auto&a : mines_str) { int j = 0; for (auto&b : a) { int value = -10; //value = // lookup.count(b) ? // lookup[b] // : (b > '0' || b <= '9') ? // int(b - '0') // : value; //msg(value); if (lookup.count(b)) value = lookup[b]; else if (b > '0' || b <= '9')value = int(b - '0'); int index = getat(j, i, w); mine_states[index] = value; //msgm(i,j,index, value); lg.logw(to_str(i,j,index, value)); ++j; } ++i; } map<int, Color> mine_colors = { { -2,Color::Red }, { -1,Color::Cyan }, { 0,Color::Black } }; msg(mine_states); i = 0; for (auto&a : mine_states) { if(a > 0) grd.texts[i].setString(to_str(a)); else grd.cells[i].setFillColor(mine_colors[a]); //grd.texts2[i].setString(to_str(i)); //grd.texts3[i].setString(to_str(getat(i,w))); ++i; } auto analyse = [&mine_states, w, h, &grd]() { vector<Vec2i> offsets = { { -1,-1 }, { 1,-1 }, { -1,1 }, { 1,1 }, { 0,-1 }, { -1,0 }, { 0,1 }, { 1,0 } }; int i = 0; for (auto&a : mine_states) { auto pos = getat(i, w); int unknown = 0, is_mine = 0; for (auto&off : offsets) { auto cell = pos + off; int cell_index = getat(cell,w); if (cell_index < 0 || cell_index >= mine_states.size() || cell.x < 0 || cell.x > w) continue; switch (mine_states[cell_index]) { case -1: ++is_mine; break; //unknown case -2: ++unknown; break; //mine } } int mine_left = a - is_mine; float prob = mine_left / unknown; ++i; } }; auto nearest_pt = mkcircle({ 0, 0 }, Color::Transparent, 10); nearest_pt.setOutlineThickness(2); // ************************ INITS END ********************** //then we actually define the functions, note how all function captures the local context by reference #ifndef LOOP_LAMBDAS draw = [&]() { window.setView(view); // object draw, AFTER normal view //////////////// obj draw START //////////////// for (auto&a : glob_pts)window.draw(a); for (auto&a : glob_rects)window.draw(a); for (auto&a : glob_vert)window.draw(a); for (auto&a : glob_texts)window.draw(a); window.draw(nearest_pt); grd.draw(window); //////////////// obj draw END //////////////// // UI draw, AFTER ui view and BEFORE other draw window.setView(ui_view); bst.draw(window); // nothing after here please UI.draw(window); window.draw(cursor); }; update = [&]() { }; treatkeyevent = [&](Keyboard::Key k) { switch (k) { case Keyboard::BackSpace: glob_pts.clear(); glob_texts.clear(); glob_rects.clear(); glob_vert.clear(); break; case Keyboard::Space: break; case Keyboard::Q: break; } }; mousemoved = [&](Vec2 pos) { cursor.setPosition(pos); if (leftclicked) sl.mouse_callback(pos); }; mouseclick = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = true; if (button == Mouse::Button::Right) rightclicked = true; }; mouserelease = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = false; if (button == Mouse::Button::Right) rightclicked = false; sl.release(); }; loop = [&]() { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window.close(); treatkeyevent(event.key.code); break; case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mouseclick(event.mouseButton.button); break; case sf::Event::MouseButtonReleased: mouserelease(event.mouseButton.button); break; case sf::Event::MouseMoved: mpos = Vec2(event.mouseMove.x, event.mouseMove.y); mousemoved(mpos); break; default: treatotherevent(event); break; } } window.clear(background); update(); draw(); window.display(); } }; treatotherevent = [&](Event&e) { if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta) { mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); //view = window.getView(); if (e.mouseWheel.delta < 0) { zoomlevel *= 2.f; view.setSize(view.getSize()*2.f); view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); } if (e.mouseWheel.delta > 0) { zoomlevel *= 0.5; view.setSize(view.getSize()*.5f); view.setCenter(.5f*(view.getCenter() + mpos_abs)); //view.setCenter(.5f*(view.getCenter() + mpos_abs)); } window.setView(view); } }; loop(); #endif // LOOP_LAMBDAS }; }
bool StartGame(RenderWindow & window, Game & game) { Level lvl; lvl.LoadFromFile(GetLevelNumb(game)); Image image; Texture texture; if (!image.loadFromFile("images/lvl1.png")) cout << "Error loading image from file " << endl; image.createMaskFromColor(Color(0, 128, 0)); if (!texture.loadFromImage(image)) cout << "Error loading texture from image " << endl; Sprite heartSprite; heartSprite.setTexture(texture); heartSprite.setTextureRect(IntRect(395, 151, 54, 46)); heartSprite.setScale(0.3f, 0.3f); Sprite lifeSprite; lifeSprite.setTexture(texture); lifeSprite.setTextureRect(IntRect(457, 149, 29, 29)); lifeSprite.setScale(0.8f, 0.8f); Font font; font.loadFromFile("fonts/pixel.ttf"); Text text("", font, 25); game.graphic.statistic.heart = heartSprite; game.graphic.statistic.life = lifeSprite; game.graphic.text = text; game.isPause = true; game.restart = false; vector <Enemy*> enemies; std::vector<Object> e = lvl.GetObjects("easyEnemy"); for (Object i : e) enemies.push_back(new Enemy(texture, "easyEnemy", i.rect.left, i.rect.top, 53, 28)); e = lvl.GetObjects("flyEnemy"); for (Object i : e) enemies.push_back(new Enemy(texture, "flyEnemy", i.rect.left, i.rect.top, 38, 36)); if (lvl.IsExist("trap")) { e = lvl.GetObjects("trap"); for (Object i : e) enemies.push_back(new Enemy(texture, "trap", i.rect.left, i.rect.top, 32, 18)); } vector <Portal*> portals; vector <Bullet*> bullets; vector <Object> objects = lvl.GetAllObjects(); Clock clock; SoundBuffer shootBuffer; shootBuffer.loadFromFile("sound/shoot.wav"); Sound shoot(shootBuffer); SoundBuffer portalBuffer; portalBuffer.loadFromFile("sound/portal.wav"); Sound portal(portalBuffer); SoundBuffer teleportBuffer; teleportBuffer.loadFromFile("sound/teleport.wav"); Sound teleport(teleportBuffer); SoundBuffer damageBuffer; damageBuffer.loadFromFile("sound/damage.wav"); Sound damage(damageBuffer); SoundBuffer deathBuffer; deathBuffer.loadFromFile("sound/damage.wav"); Sound gameOver(deathBuffer); Music music; music.openFromFile("sound/musicGame.ogg"); music.play(); Object playerObject = lvl.GetObject("player"); Player player(texture, "Player1", playerObject.rect.left, playerObject.rect.top, 32, 32); player.health = game.health; player.heart = game.hearts; while (window.isOpen() && (!game.restart)) { float time = float(clock.getElapsedTime().asMicroseconds()); clock.restart(); time = time / 800; Event event; Vector2i pixelPos = Mouse::getPosition(window); Vector2f pos = window.mapPixelToCoords(pixelPos); while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || (Keyboard::isKeyPressed(Keyboard::Escape) && game.isPause)) { window.close(); game.restart = false; } if (event.type == Event::MouseButtonPressed) { pos.y = float(player.teleportY); if ((event.key.code == Mouse::Left) && (player.doesOpenPortal)) { CreatePortal(portals, game, "blue", pos, texture); portal.play(); } else if (event.key.code == Mouse::Right && (player.doesOpenPortal)) { CreatePortal(portals, game, "yellow", pos, texture); portal.play(); } } if (player.isTeleporting) { TeleportPlayer(player, portals); teleport.play(); } if (Keyboard::isKeyPressed(Keyboard::Return)) { game.isPause = false; } if (Keyboard::isKeyPressed(Keyboard::P)) { game.isPause = true; } if (Keyboard::isKeyPressed(Keyboard::Tab) && game.isPause) { game.restart = true; } } if (player.isExit) { if (game.isEndLevel) { game.isPause = true; } else { game.level++; game.restart = true; game.health = player.health; game.hearts = player.heart; } } for (auto *e : enemies) { if ((*e).name == "flyEnemy" && (*e).isShoot) { CreateBullet(bullets, (*e).GetRect(), player, texture); shoot.play(); } } EntitiesIntersection(player, enemies, portals, bullets, damage); if (player.alive) { setPlayerCoordinateForView(game.camera, player.GetPos().x, player.GetPos().y); } if (!game.isPause) { UpdateEnemies(objects, enemies, time, player); UpdatePortals(portals, time); UpdateBullets(objects, bullets, time); player.Update(objects, time, pos, game.portalH); } window.setView(game.camera); window.clear(); lvl.Draw(window); DrawEnemies(window, enemies); DrawPortals(window, portals); DrawBullets(window, bullets); DrawStatistic(window, &game, player, game.camera); window.draw(player.sprite); DrawAllMessages(player, game, window); music.setLoop(true); window.display(); } return game.restart; }
function<void()> ////////////////////////// TYPE APP NAME ON LINE BELOW ////////////////////////// delaun_distr (RenderWindow&window, ui &UI) { return [&window, &UI]() { #ifndef COMMON_INITS //void smoothmouse(RenderWindow&window, ui &UI){ // tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary function<void()> draw, loop, init, update; function<void(Vec2 pos)> mousemoved; function<void(sf::Mouse::Button button)> mouseclick, mouserelease; function<void(Event&e)> treatotherevent; function<void(Keyboard::Key k)> treatkeyevent; // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway. Texture cursor_tx; Sprite cursor; configfile cfg; cfg.init("bedlab.cfg"); Color background = cfg.getvar<Color>("background"); if (!cursor_tx.loadFromFile(cfg.getstr("cursor"))) cout << "did not load cursor" << endl; cursor.setTexture(cursor_tx); cursor.setOrigin(3, 3); window.setMouseCursorVisible(false); Vec2 mpos; bool leftclicked = false, rightclicked = false; // view and zoom View view, ui_view; ui_view = view = window.getDefaultView(); float zoomlevel = 1; Vec2 mpos_abs; #endif // COMMON_INITS // ************************ CODE BEGIN ************************ auto random_graph = [](int pick_count, float distrib_radius) { vector<pair<int,Vec2>> points; vector<pair<int, int>> graph; //float distrib_radius;// = cfg.getvar<float>("distrib_radius"); paused_distr paus_distr(distrib_radius, 5, 321); //int winheight = cfg.getvar<Vec2i>("windowsize").y; //scaler scl(winheight*0.9f, { 0,0 }); DelaunayTriangulation dela(1, 1); //int pick_count = cfg.getvar<int>("pick_count"); for (int i = 0; i < pick_count; ++i) { Vec2 cand; int retcode = -1; do { retcode = paus_distr.pick5(cand); } while (retcode == 2); if (retcode != -1 && retcode != 0) { dela.AddPoint(Point(cand.x, cand.y)); //glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f)); //glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f)); points.push_back({ points.size(),cand }); } } //msg(glob_pts.size()); for (auto&triangle : dela.triangles) { int a = triangle.get()->v[0], b = triangle.get()->v[1], c = triangle.get()->v[2]; Point A = dela.points[a], B = dela.points[b], C = dela.points[c]; if ( A.x == 0 || A.x == 1 || A.y == 0 || A.y == 1 || B.x == 0 || B.x == 1 || B.y == 0 || B.y == 1 || C.x == 0 || C.x == 1 || C.y == 0 || C.y == 1 ) { continue; } graph.push_back({a,b}); graph.push_back({b,c}); graph.push_back({a,c}); // those are the ones! //segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y))); //segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y))); //segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y))); //segment(Vec2(A.x, A.y), Vec2(B.x, B.y)); //segment(Vec2(C.x, C.y), Vec2(B.x, B.y)); //segment(Vec2(A.x, A.y), Vec2(C.x, C.y)); //segment(pts[a], pts[b]); //segment(pts[a], pts[c]); //segment(pts[c], pts[b]); } return make_pair(points, graph); }; float distrib_radius = cfg.getvar<float>("distrib_radius"); paused_distr paus_distr(distrib_radius, 5, 321); int winheight = cfg.getvar<Vec2i>("windowsize").y; scaler scl(winheight*0.9f, { 0,0 }); DelaunayTriangulation dela(1, 1); int pick_count = cfg.getvar<int>("pick_count"); for(int i = 0; i < pick_count; ++i) { Vec2 cand; int retcode = -1; do { retcode = paus_distr.pick5(cand); } while (retcode == 2); if (retcode != -1 && retcode != 0) { dela.AddPoint(Point(cand.x, cand.y)); //glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f)); glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f)); } } msg(glob_pts.size()); for (auto&triangle : dela.triangles) { int a = triangle.get()->v[0], b = triangle.get()->v[1], c = triangle.get()->v[2]; Point A = dela.points[a], B = dela.points[b], C = dela.points[c]; if ( A.x == 0 || A.x == 1 || A.y == 0 || A.y == 1 || B.x == 0 || B.x == 1 || B.y == 0 || B.y == 1 || C.x == 0 || C.x == 1 || C.y == 0 || C.y == 1 ) { continue; } segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y))); segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y))); segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y))); //segment(Vec2(A.x, A.y), Vec2(B.x, B.y)); //segment(Vec2(C.x, C.y), Vec2(B.x, B.y)); //segment(Vec2(A.x, A.y), Vec2(C.x, C.y)); //segment(pts[a], pts[b]); //segment(pts[a], pts[c]); //segment(pts[c], pts[b]); } barstack bst(FONT, FONTSIZE); slider_finder sl; size_t edit_mode = 1; // ************************ INITS END ************************ //then we actually define the functions, note how all function captures the local context by reference #ifndef LOOP_LAMBDAS draw = [&]() { window.setView(view); // object draw, AFTER normal view //Vec2 cand; //int retcode = -1; //do //{ // retcode = paus_distr.pick4(cand); //} while (retcode == 2); //if (retcode != -1 && retcode != 0) //{ // //glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f)); // glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f)); //} //////////////// obj draw START //////////////// for (auto&a : glob_pts)window.draw(a); for (auto&a : glob_rects)window.draw(a); for (auto&a : glob_vert)window.draw(a); for (auto&a : glob_texts)window.draw(a); //window.draw(nearest_pt); //////////////// obj draw END //////////////// // UI draw, AFTER ui view and BEFORE other draw window.setView(ui_view); bst.draw(window); // nothing after here please UI.draw(window); window.draw(cursor); }; update = [&]() { }; treatkeyevent = [&](Keyboard::Key k) { switch (k) { case Keyboard::BackSpace: glob_pts.clear(); glob_texts.clear(); glob_rects.clear(); glob_vert.clear(); break; case Keyboard::Space: break; case Keyboard::Q: break; } }; mousemoved = [&](Vec2 pos) { cursor.setPosition(pos); if (leftclicked) sl.mouse_callback(pos); }; mouseclick = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = true; if (button == Mouse::Button::Right) rightclicked = true; }; mouserelease = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = false; if (button == Mouse::Button::Right) rightclicked = false; sl.release(); }; loop = [&]() { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window.close(); treatkeyevent(event.key.code); break; case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mouseclick(event.mouseButton.button); break; case sf::Event::MouseButtonReleased: mouserelease(event.mouseButton.button); break; case sf::Event::MouseMoved: mpos = Vec2(event.mouseMove.x, event.mouseMove.y); mousemoved(mpos); break; default: treatotherevent(event); break; } } window.clear(background); update(); draw(); window.display(); } }; treatotherevent = [&](Event&e) { if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta) { mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); //view = window.getView(); if (e.mouseWheel.delta < 0) { zoomlevel *= 2.f; view.setSize(view.getSize()*2.f); view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); } if (e.mouseWheel.delta > 0) { zoomlevel *= 0.5; view.setSize(view.getSize()*.5f); view.setCenter(.5f*(view.getCenter() + mpos_abs)); //view.setCenter(.5f*(view.getCenter() + mpos_abs)); } window.setView(view); } }; loop(); #endif // LOOP_LAMBDAS }; }
Vector2f GetMousePos(RenderWindow &window) { Vector2i pixelPos = Mouse::getPosition(window); return window.mapPixelToCoords(pixelPos); }