Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <iostream>
- #include <sstream>
- #include "iostream"
- #include "view.h"
- #include "level.h"
- #include <vector>
- #include <list>
- using namespace sf;
- ///////////////////////////////////
- class Entity {
- public:
- std::vector<Object> obj; //вектор объектов карты
- float dx, dy, x, y, speed, moveTimer;
- int w, h, health;
- bool life, onGround;
- Texture texture;
- Sprite sprite;
- String name; // тк типов врагов будет несколько, то дадим каждому типу имя
- Entity(Image &image, String Name, float X, float Y, int W, int H) {
- x = X; y = Y; w = W; h = H; name = Name; moveTimer = 0;
- speed = 0; health = 100; dx = 0; dy = 0;
- life = true; onGround = false;
- texture.loadFromImage(image);
- sprite.setTexture(texture);
- sprite.setOrigin(w / 2, h / 2);
- }
- FloatRect getRect() { //получение коорд прямоугольника
- return FloatRect(x, y, w, h); // используется для проверки столкновений
- }
- };
- ////////////////////КЛАСС ИГРОКА//////////////////
- class Player :public Entity {
- public:
- int playerScore;//очки набранные игроком
- enum stateObject{left, right, up, down, jump, stay} state; //состояния объекта
- Player (Image &image, String Name, Level &lev, float X, float Y, float W, float H) :Entity(image, Name, X, Y, W, H) {
- playerScore = 0; state = stay; obj = lev.GetAllObjects();
- if (name == "Player1") {
- sprite.setTextureRect(IntRect(0, 0, w, h));
- }
- }
- void control() {
- if (Keyboard::isKeyPressed(Keyboard::Left)) {
- state = left; speed = 0.1;
- //CurrentFrame += 0.005*time;
- //if (CurrentFrame > 7) CurrentFrame -= 6;
- //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, -39, 53));
- }
- if (Keyboard::isKeyPressed(Keyboard::Right)) {
- state = right; speed = 0.1;
- //CurrentFrame += 0.005*time;
- //if (CurrentFrame > 6) CurrentFrame -= 6;
- //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, 39, 53));
- }
- if ((Keyboard::isKeyPressed(Keyboard::Up)) && (onGround)) {
- state = jump; dy = -0.6; onGround = false;
- //CurrentFrame += 0.005*time;
- //if (CurrentFrame > 3) CurrentFrame -= 3;
- //p.sprite.setTextureRect(IntRect(47 * int(CurrentFrame), 216, 47, 80));
- }
- if (Keyboard::isKeyPressed(Keyboard::Down)) {
- state = down; speed = 0.1;
- //CurrentFrame += 0.005*time;
- //if (CurrentFrame > 6) CurrentFrame -= 6;
- //p.sprite.setTextureRect(IntRect(39 * int(CurrentFrame), 0, 39, 53));
- }
- }
- void checkCollisionWithMap(float Dx, float Dy) {
- for (int i = 0; i<obj.size(); i++)//проходимся по объектам
- if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом
- {
- if (obj[i].name == "solid")//если встретили препятствие
- {
- if (Dy>0) { y = obj[i].rect.top - h; dy = 0; onGround = true; }
- if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height; dy = 0; }
- if (Dx>0) { x = obj[i].rect.left - w; }
- if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; }
- }
- }
- }
- void update(float time) {
- control();//управление персонажем
- switch (state) {
- case right: dx = speed; break;
- case left: dx = -speed; break;
- case up: break;
- case down: dx = 0; break;
- case jump: break;
- case stay: break;
- }
- x += dx*time;
- checkCollisionWithMap(dx, 0);//обработка столкновения по X
- y += dy*time;
- checkCollisionWithMap(0, dy);//по Y
- speed = 0;
- sprite.setPosition(x+w/2, y+h/2);
- if (health <= 0) { life = false; speed = 0; } // если хп меньше 0, то умираем
- if (life) { setPlayerCoordinateForView(x, y); }
- dy = dy + 0.0015*time; //притяжение к земле, если не на земле
- }
- float setPlayerCoordinateX() {
- return x;
- }
- float setPlayerCoordinateY() {
- return y;
- }
- };
- class Enemy :public Entity {
- public:
- Enemy(Image &image, String Name, Level &lvl, float X, float Y, int W, int H) :Entity(image, Name, X, Y, W, H){
- obj = lvl.GetObjects("solid");//инициализируем.получаем нужные объекты для взаимодействия врага с картой
- if (name == "EasyEnemy") {
- sprite.setTextureRect(IntRect(0, 0, w, h));
- dx = 0.1;//скорость движения объекта
- }
- }
- void checkCollisionWithMap(float Dx, float Dy){
- for (int i = 0; i<obj.size(); i++)//проходимся по объектам
- if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом
- {
- //if (obj[i].name == "solid"){//если встретили препятствие (объект с именем solid)
- if (Dy>0) { y = obj[i].rect.top - h; dy = 0; onGround = true; }
- if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height; dy = 0; }
- if (Dx>0) { x = obj[i].rect.left - w; dx = -0.1; sprite.scale(-1, 1); }
- if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; dx = 0.1; sprite.scale(-1, 1); }
- //}
- }
- }
- void update(float time) {
- if (name == "EasyEnemy") {//для персонажа с таким именем логика будет такой
- //moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }//меняет направление примерно каждые 3 сек
- checkCollisionWithMap(dx, 0);//обрабатываем столкновение по Х
- x += dx*time;
- sprite.setPosition(x + w / 2, y + h / 2); //задаем позицию спрайта в место его центра
- if (health <= 0) { life = false; }
- }
- }
- };
- int main()
- {
- RenderWindow window(VideoMode(640, 480), "gaaaaameeeee");
- view.reset(FloatRect(0, 0, 640, 480));//размер "вида" камеры при создании объекта вида камеры. (потом можем менять как хотим) Что то типа инициализации.
- Level lvl;
- lvl.LoadFromFile("map.tmx");
- Font font;
- font.loadFromFile("CyrilicOld.TTF");
- Text text("", font, 20);
- text.setColor(Color::White);
- text.setStyle(Text::Bold);
- Image heroImage;
- heroImage.loadFromFile("images/n_walk.png");
- heroImage.createMaskFromColor(Color(255, 255, 255));
- Image easyEnemyImage;
- easyEnemyImage.loadFromFile("images/enemy.png");
- Object player = lvl.GetObject("palyer");//задаем координаты игрока на карте
- Object easyEnemyObject = lvl.GetObject("easyEnemy");//координаты врага на карте
- Player p(heroImage, "Player1", lvl, player.rect.left, player.rect.top, 39, 53);
- Enemy easyEnemy(easyEnemyImage, "EasyEnemy", lvl, easyEnemyObject.rect.left, easyEnemyObject.rect.top, 45, 64);
- float CurrentFrame = 0;
- Clock clock;
- Clock gameTimeClock;
- int gameTime = 0;
- while (window.isOpen()) {
- float time = clock.getElapsedTime().asMicroseconds();
- if (p.life) gameTime = gameTimeClock.getElapsedTime().asSeconds();
- else { p.sprite.setColor(Color::Red);
- window.draw(text); }
- clock.restart();
- time = time / 500;
- Event event;
- while (window.pollEvent(event))
- {
- if (event.type == Event::Closed)
- window.close();
- }
- p.update(time);
- easyEnemy.update(time);
- window.setView(view);
- window.clear();
- lvl.Draw(window);
- window.draw(easyEnemy.sprite);//рисовка врага
- window.draw(p.sprite);//рисовка игрока
- std::ostringstream playerHealthString, gameTimeString;
- playerHealthString << p.health; gameTimeString << gameTime;
- text.setString("Здоровье: "+playerHealthString.str() + "\nВремя игры: " + gameTimeString.str());
- text.setPosition(view.getCenter().x-300, view.getCenter().y-240);
- window.draw(text);
- window.display();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement