Snake/back-end/world.cpp

123 lines
2.3 KiB
C++
Raw Normal View History

2018-09-27 00:10:42 +03:00
#include "world.h"
2018-10-11 00:04:52 +03:00
#include <QMap>
#include "guiobject.h"
#include "guiobjectfactory.h"
2018-10-11 18:09:35 +03:00
#include <QDateTime>
2018-10-11 00:04:52 +03:00
#include <QDebug>
2018-09-27 00:10:42 +03:00
2018-10-11 00:04:52 +03:00
World::World() {
currentLong = 0;
endLong = 0;
background = "";
2018-09-27 00:10:42 +03:00
}
2018-10-11 00:04:52 +03:00
void World::clearItems() {
2018-09-27 00:10:42 +03:00
for (auto i : items) {
delete i;
}
items.clear();
}
2018-10-11 18:09:35 +03:00
void World::changeCountObjects(const QString &name, int count) {
2018-10-11 18:09:35 +03:00
if (count > 0) {
for ( int i = 0; i < count; ++i ) {
auto obj = GuiObjectFactory::generate(name);
if (!obj) {
qWarning() <<"object not created line:" << Q_FUNC_INFO;
break;
}
items.push_back(obj);
}
} else {
for ( int i = count; i < 0; ++i ) {
auto obj = items.first();
items.removeFirst();
delete obj;
}
}
}
2018-10-11 00:04:52 +03:00
QMap<int, GuiObject *> World::init(const WorldRules &rules) {
QMap<int, GuiObject*> res;
2018-11-16 20:01:47 +03:00
auto snakeItems = snake.init(10, 15);
for (auto i = snakeItems.begin(); i != snakeItems.end(); ++i) {
res.insert(i.key(), i.value());
}
2018-10-11 00:04:52 +03:00
currentLong = -1;
for (auto i = rules.begin(); i != rules.end(); ++i) {
if (i.key() == "Long") {
endLong = rules["Long"];
currentLong = 0;
}
2018-10-11 18:09:35 +03:00
else if (i.key() == "Spead") {
spead = rules["Spead"];
}
2018-10-11 00:04:52 +03:00
else {
changeCountObjects(i.key(), i.value() - oldRules.value(i.key()));
2018-10-11 00:04:52 +03:00
}
}
2018-10-11 18:09:35 +03:00
for (auto i : items) {
res[i->guiId()] = i;
}
2018-10-11 18:09:35 +03:00
oldRules = rules;
2018-10-11 00:04:52 +03:00
return res;
}
World::~World() {
clearItems();
}
void World::render() {
2018-10-11 18:09:35 +03:00
qint64 tempTime = QDateTime::currentMSecsSinceEpoch() - time;
time = QDateTime::currentMSecsSinceEpoch();
auto dx = speed / 1000 * tempTime;
2018-10-11 00:04:52 +03:00
snake.render();
2018-10-11 18:09:35 +03:00
const QRectF &rig = snake.getRiger();
2018-10-11 00:04:52 +03:00
2018-11-14 23:15:36 +03:00
for (int i = items.length() - 1; i >= 0; --i) {
2018-10-11 18:09:35 +03:00
defiat |= items[i]->move(rig, dx);
2018-09-27 14:59:10 +03:00
items[i]->render();
2018-09-27 00:10:42 +03:00
}
2018-10-11 18:09:35 +03:00
currentLong += dx;
2018-09-27 00:10:42 +03:00
}
2018-10-11 18:09:35 +03:00
bool World::move() {
2018-10-11 00:04:52 +03:00
return isEnd();
}
bool World::isEnd() {
return currentLong >= endLong;
}
bool World::isDefiat() const {
return defiat;
}
WorldRules World::currentRules() const {
return oldRules;
}
2018-11-16 02:08:35 +03:00
void World::reversClick() {
snake.reverse();
}
2018-09-27 00:10:42 +03:00
const QVector<ItemWorld *> &World::getItems() const {
return items;
}