Advertisement
Guest User

Untitled

a guest
May 5th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.94 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <iostream>
  3. #include <sstream>
  4. #include "iostream"
  5. #include "view.h"
  6. #include "level.h"
  7. #include <vector>
  8. #include <list>
  9.  
  10. using namespace sf;
  11.  
  12. ///////////////////////////////////
  13. class Entity {
  14. public:
  15.     std::vector<Object> obj; //вектор объектов карты
  16.     float dx, dy, x, y, speed, moveTimer;
  17.     int w, h, health;
  18.     bool life, onGround;
  19.     Texture texture;
  20.     Sprite sprite;
  21.     String name; // тк типов врагов будет несколько, то дадим каждому типу имя
  22.     Entity(Image &image, String Name, float X, float Y, int W, int H) {
  23.         x = X; y = Y; w = W; h = H; name = Name; moveTimer = 0;
  24.         speed = 0; health = 100; dx = 0; dy = 0;
  25.         life = true; onGround = false;
  26.         texture.loadFromImage(image);
  27.         sprite.setTexture(texture);
  28.         sprite.setOrigin(w / 2, h / 2);
  29.     }
  30.  
  31.     FloatRect getRect() { //получение коорд прямоугольника
  32.         return FloatRect(x, y, w, h); // используется для проверки столкновений
  33.     }
  34. };
  35.  
  36. ////////////////////КЛАСС ИГРОКА//////////////////
  37. class Player :public Entity {
  38. public:
  39.     int playerScore;//очки набранные игроком
  40.     enum stateObject{left, right, up, down, jump, stay} state; //состояния объекта
  41.    
  42.     Player (Image &image, String Name, Level &lev, float X, float Y, float W, float H) :Entity(image, Name, X, Y, W, H) {
  43.         playerScore = 0; state = stay; obj = lev.GetAllObjects();
  44.         if (name == "Player1") {
  45.             sprite.setTextureRect(IntRect(0, 0, w, h));
  46.         }
  47.     }
  48.  
  49.     void control() {
  50.             if (Keyboard::isKeyPressed(Keyboard::Left)) {
  51.                 state = left; speed = 0.1;
  52.                 //CurrentFrame += 0.005*time;
  53.                 //if (CurrentFrame > 7) CurrentFrame -= 6;
  54.                 //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, -39, 53));
  55.             }
  56.  
  57.             if (Keyboard::isKeyPressed(Keyboard::Right)) {
  58.                 state = right; speed = 0.1;
  59.                 //CurrentFrame += 0.005*time;
  60.                 //if (CurrentFrame > 6) CurrentFrame -= 6;
  61.                 //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, 39, 53));
  62.             }
  63.  
  64.             if ((Keyboard::isKeyPressed(Keyboard::Up)) && (onGround)) {
  65.                 state = jump; dy = -0.6; onGround = false;
  66.                 //CurrentFrame += 0.005*time;
  67.                 //if (CurrentFrame > 3) CurrentFrame -= 3;
  68.                 //p.sprite.setTextureRect(IntRect(47 * int(CurrentFrame), 216, 47, 80));
  69.             }
  70.  
  71.             if (Keyboard::isKeyPressed(Keyboard::Down)) {
  72.                 state = down; speed = 0.1;
  73.                 //CurrentFrame += 0.005*time;
  74.                 //if (CurrentFrame > 6) CurrentFrame -= 6;
  75.                 //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, 39, 53));
  76.             }
  77.         }
  78.  
  79.     void checkCollisionWithMap(float Dx, float Dy) {
  80.         for (int i = 0; i<obj.size(); i++)//проходимся по объектам
  81.             if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом
  82.             {
  83.                 if (obj[i].name == "solid")//если встретили препятствие
  84.                 {
  85.                     if (Dy>0) { y = obj[i].rect.top - h;  dy = 0; onGround = true; }
  86.                     if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height;   dy = 0; }
  87.                     if (Dx>0) { x = obj[i].rect.left - w; }
  88.                     if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; }
  89.                 }
  90.             }
  91.     }
  92.  
  93.     void update(float time) {
  94.         control();//управление персонажем
  95.         switch (state) {
  96.         case right: dx = speed; break;
  97.         case left: dx = -speed; break;
  98.         case up: break;
  99.         case down: dx = 0;  break;
  100.         case jump: break;
  101.         case stay: break;
  102.         }
  103.         x += dx*time;
  104.         checkCollisionWithMap(dx, 0);//обработка столкновения по X
  105.         y += dy*time;
  106.         checkCollisionWithMap(0, dy);//по Y
  107.        
  108.         speed = 0;
  109.         sprite.setPosition(x+w/2, y+h/2);
  110.         if (health <= 0) { life = false; speed = 0; } // если хп меньше 0, то умираем
  111.         if (life) { setPlayerCoordinateForView(x, y); }
  112.         dy = dy + 0.0015*time; //притяжение к земле, если не на земле
  113.     }
  114.    
  115.     float setPlayerCoordinateX() {
  116.         return x;
  117.     }
  118.  
  119.     float setPlayerCoordinateY() {
  120.         return y;
  121.     }
  122.  
  123. };
  124.  
  125. class Enemy :public Entity {
  126. public:
  127.     Enemy(Image &image, String Name, Level &lvl, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H){
  128.         obj = lvl.GetObjects("solid");//инициализируем.получаем нужные объекты для взаимодействия врага с картой
  129.         if (name == "EasyEnemy") {
  130.             sprite.setTextureRect(IntRect(0, 0, w, h));
  131.             dx = 0.1;//скорость движения объекта
  132.         }
  133.     }
  134.  
  135.     void checkCollisionWithMap(float Dx, float Dy){
  136.         for (int i = 0; i<obj.size(); i++)//проходимся по объектам
  137.             if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом
  138.             {
  139.                 //if (obj[i].name == "solid"){//если встретили препятствие (объект с именем solid)
  140.                 if (Dy>0) { y = obj[i].rect.top - h;  dy = 0; onGround = true; }
  141.                 if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height;   dy = 0; }
  142.                 if (Dx>0) { x = obj[i].rect.left - w;  dx = -0.1; sprite.scale(-1, 1); }
  143.                 if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; dx = 0.1; sprite.scale(-1, 1); }
  144.                 //}
  145.             }
  146.     }
  147.  
  148.     void update(float time) {
  149.         if (name == "EasyEnemy") {//для персонажа с таким именем логика будет такой
  150.  
  151.             //moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }//меняет направление примерно каждые 3 сек
  152.             checkCollisionWithMap(dx, 0);//обрабатываем столкновение по Х
  153.             x += dx*time;
  154.             sprite.setPosition(x + w / 2, y + h / 2); //задаем позицию спрайта в место его центра
  155.             if (health <= 0) { life = false; }
  156.         }
  157.     }
  158. };
  159.  
  160. int main()
  161. {
  162.     RenderWindow window(VideoMode(640, 480), "gaaaaameeeee");
  163.     view.reset(FloatRect(0, 0, 640, 480));//размер "вида" камеры при создании объекта вида камеры. (потом можем менять как хотим) Что то типа инициализации.
  164.  
  165.     Level lvl;
  166.     lvl.LoadFromFile("map.tmx");
  167.  
  168.     Font font;
  169.     font.loadFromFile("CyrilicOld.TTF");
  170.     Text text("", font, 20);
  171.     text.setColor(Color::White);
  172.     text.setStyle(Text::Bold);
  173.  
  174.     Image heroImage;
  175.     heroImage.loadFromFile("images/n_walk.png");
  176.     heroImage.createMaskFromColor(Color(255, 255, 255));
  177.  
  178.     Image easyEnemyImage;
  179.     easyEnemyImage.loadFromFile("images/enemy.png");
  180.  
  181.     Object player = lvl.GetObject("palyer");//задаем координаты игрока на карте
  182.     Object easyEnemyObject = lvl.GetObject("easyEnemy");//координаты врага на карте
  183.  
  184.     Player p(heroImage, "Player1", lvl, player.rect.left, player.rect.top, 39, 53);
  185.     Enemy easyEnemy(easyEnemyImage, "EasyEnemy", lvl, easyEnemyObject.rect.left, easyEnemyObject.rect.top, 45, 64);
  186.  
  187.     float CurrentFrame = 0;
  188.     Clock clock;
  189.     Clock gameTimeClock;
  190.     int gameTime = 0;
  191.  
  192.     while (window.isOpen()) {
  193.  
  194.         float time = clock.getElapsedTime().asMicroseconds();
  195.  
  196.         if (p.life) gameTime = gameTimeClock.getElapsedTime().asSeconds();
  197.             else { p.sprite.setColor(Color::Red);  
  198.             window.draw(text);  }
  199.  
  200.         clock.restart();
  201.         time = time / 500;
  202.  
  203.         Event event;
  204.         while (window.pollEvent(event))
  205.         {
  206.             if (event.type == Event::Closed)
  207.                 window.close();
  208.         }      
  209.  
  210.         p.update(time);
  211.         easyEnemy.update(time);
  212.         window.setView(view);
  213.         window.clear();
  214.         lvl.Draw(window);
  215.  
  216.         window.draw(easyEnemy.sprite);//рисовка врага
  217.         window.draw(p.sprite);//рисовка игрока
  218.        
  219.         std::ostringstream playerHealthString, gameTimeString;
  220.         playerHealthString << p.health; gameTimeString << gameTime;
  221.         text.setString("Здоровье: "+playerHealthString.str() + "\nВремя игры: " + gameTimeString.str());
  222.         text.setPosition(view.getCenter().x-300, view.getCenter().y-240);
  223.  
  224.         window.draw(text);
  225.         window.display();
  226.     }
  227.  
  228.     return 0;
  229. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement