예제 #1
0
QSharedPointer<QEnginioOperationShared> QEnginioObjectShared::save(QSharedPointer<QEnginioObjectShared> aSelf)
{
    if (!isModified()) {
        return QSharedPointer<QEnginioOperationShared>();
    }

    QJsonObject update;
    QJsonObject::iterator i;

    for (i = iJsonObject.begin(); i != iJsonObject.end(); ++i) {
        if (i.key() == QtCloudServicesConstants::id ||
                i.key() == QtCloudServicesConstants::objectType) {
            update.insert(i.key(), i.value());
            continue;
        }

        if (iPersistentJsonObject.contains(i.key()) &&
                iPersistentJsonObject[i.key()] == i.value()) {
            continue;
        }

        update.insert(i.key(), i.value());
    }

    return iEnginioCollection->update(iEnginioCollection,
                                      objectId(), update,
                                      SaveCompletedFunctor(aSelf));
}
예제 #2
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QTreeWidgetItem* FilterLibraryTreeWidget::UnwrapTreeItem(QJsonObject object)
{
    FilterLibraryTreeWidget::ItemType type = FilterLibraryTreeWidget::ItemType(object["Type"].toInt());
    QTreeWidgetItem* item = new QTreeWidgetItem(type);

    QString name = object["Name"].toString();
    item->setText(0, name);
    item->setData(0, Qt::UserRole, name);

    if (type == FilterLibraryTreeWidget::Node_Item_Type)
    {
        item->setIcon(0, QIcon(":/folder_blue.png"));
        item->setFlags(item->flags() | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled);
        item->setData(2, Qt::UserRole, object["Expanded"].toBool());
        for (QJsonObject::iterator iter = object.begin(); iter != object.end(); ++iter)
        {
            if (iter.value().isObject())
            {
                QJsonObject childObj = iter.value().toObject();
                QTreeWidgetItem* child = FilterLibraryTreeWidget::UnwrapTreeItem(childObj);
                item->insertChild(0, child);
            }
        }
    }
    else
    {
        item->setIcon(0, QIcon(":/text.png"));
        item->setFlags(item->flags() | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled);
        item->setText(1, object["Path"].toString());
        item->setData(1, Qt::UserRole, object["Path"].toString());
    }

    return item;
}
QList<QString> SingleWeatherParamWidget::getDataFromJson(QString jsonStr){
    QList<QString> valueList;
    QJsonParseError jsonErr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &jsonErr);
    if(jsonErr.error == QJsonParseError::NoError){
        if(!jsonDoc.isEmpty()){
            if(jsonDoc.isObject()){
                QJsonObject jobj = jsonDoc.object();
                QJsonObject::iterator it = jobj.begin();
                while(it != jobj.end()){
                    if(QJsonValue::Array == it.value().type()){
                        QJsonArray array = it.value().toArray();
                        int subArrayCount = array.count();
                        for(int i = 0;i < subArrayCount;i++){
                            QJsonArray subArray = array.at(i).toArray();
                            valueList.append(subArray.at(0).toString());
                            valueList.append(subArray.at(1).toString());
                        }
                    }
                    it++;
                }
            }
        }
    }
    return valueList;
}
예제 #4
0
void Config::load(QString filename)
{
    QFile f(filename);

    if (!f.open(QFile::ReadOnly)) {
        return;
    }

    QByteArray data = f.readAll();
    document = QJsonDocument::fromJson(data);

    if (!document.isObject()) {
        return;
    }

    if (!document.object()["name"].isString() || !document.object()["sounds"].isObject()) {
        return;
    }

    QJsonObject soundsConf = document.object()["sounds"].toObject();
    QFileInfo info(filename);
    QDir baseDir = info.absoluteDir();

    valid = true;

    for (QJsonObject::iterator i = soundsConf.begin(); i != soundsConf.end(); i++) {
        if (!i.value().isString()) {
            continue;
        }

        sounds[i.key()] = baseDir.filePath(i.value().toString());
    }
}
예제 #5
0
void wtss::tl::server_manager::changeStatusCoverage(const QString &server_uri,
                                                    const QString &cv_name)
{
  QJsonDocument j_doc = loadSettings();
  QJsonObject j_object = j_doc.object();

  QJsonObject j_servers = j_object.find("servers").value().toObject();

  if(!j_servers.contains(server_uri))
  {
    boost::format err_msg("Could not find the server: %1%");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_server = j_servers.find(server_uri).value().toObject();

  if(!j_server.contains("coverages"))
  {
    boost::format err_msg("The server %1% has no coverages");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_coverages = j_server.find("coverages").value().toObject();
  QJsonObject j_coverage = j_coverages.find(cv_name).value().toObject();
  bool active = j_coverage.find("active").value().toBool();
  j_coverage["active"] = !active;
  if(!active)
  {
    for(QJsonObject::iterator it = j_coverages.begin(); it != j_coverages.end();
        ++it)
    {
      if(it.key() != cv_name)
      {
        QJsonObject j_cv = it.value().toObject();
        j_cv["active"] = QJsonValue(false);
        j_coverages[it.key()] = j_cv;
      }
    }
  }
  if(!j_coverages.contains(cv_name))
  {
    boost::format err_msg("The server %1% has no coverage named: %2%");
    throw out_of_range_exception() << error_description(
        (err_msg % server_uri.toUtf8().data() % cv_name.toUtf8().data()).str());
  }

  j_coverages[cv_name] = j_coverage;
  j_server["coverages"] = j_coverages;
  j_servers[server_uri] = j_server;

  j_object["servers"] = j_servers;
  j_doc.setObject(j_object);

  saveSettings(j_doc);
}
예제 #6
0
void mibot::StandardLoggerBuilder::BuildLogger(QJsonObject &json)
{
    QJsonObject::iterator iter = json.begin();

    QString defaultChannelName;
    do
    {
        QString key = iter.key();

        if(key == "Sinks")
        {
            if(!iter.value().isArray())
            {
                LogProcess(LOG_TYPE::ERROR,"LoggerSink property is a non-array element.");
                continue;
            }

            QJsonArray array = iter.value().toArray();
            for(int i=0; i< array.count(); i++)
            {
                if(!array[i].isObject())
                {
                    LogProcess(LOG_TYPE::ERROR,"LoggerSink array element is a non-object type.");
                    continue;
                }

                QJsonObject obj = array[i].toObject();
                BuildSink(obj);
            }
        }
        else
            LogProcess(LOG_TYPE::ERROR, QString("Unsuported param '%1'.").arg(key));

        iter++;
    }
    while(iter != json.end());

    LogProcess(LOG_TYPE::OK, "Json reading done.");
}
예제 #7
0
bool TestPlugin::ValidateParameters(QJsonObject *params) const {
    // First level type check over given parameters
    for(QJsonObject::iterator itr = params->begin(); itr != params->end(); ++itr){
        // Get reference type
        auto ref = GetParameterJson().value(itr.key());

        if(ref.type() != itr.value().type()) {
            return false;
        }
    }

    return mAlgorithm->ValidateParameters(params);
}
예제 #8
0
void configFactory::Parse(){
  QFile json("../config.json");
  if (json.open(QIODevice::ReadOnly))
  {
    QJsonParseError  parseError;
    QJsonObject jsonDoc = QJsonDocument::fromJson(json.readAll(), &parseError).object();
    for (QJsonObject::iterator it = jsonDoc.begin(); it != jsonDoc.end(); it++)
    {
      MapOfConfigs[it.key()] = DetermineConfigObject(it.value().toObject());
    }
  }
  else
  {
  std::cout<<"Config json not found\n";
  }
}
예제 #9
0
//TODO: should use qt's json process lib here
int PkgHandle::loadConfig() { // default "" means use default conf inside, initialize all vars remember
    if (_confpath == QString("")) {
		pr_info("config file emtpy, error");
		return -1; //can not find conf file
    }   

    QByteArray val;
    QFile file(_confpath);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text) == false) {
        pr_info("can not open conf file \n");
        return -1;
    }
    val = file.readAll();
    file.close();
    QJsonDocument doc = QJsonDocument::fromJson(val);
    QJsonObject docobj = doc.object();

    for (QJsonObject::iterator it = docobj.begin(); it != docobj.end(); ++it) {
        if (it.key() == "localpkgdir") {
            _localpkgdir = it.value().toString();
        } else if (it.key() == "prefixdir") {
            _prefixdir = it.value().toString();
        } else if (it.key() == "remoteaddr") {
            _remoteaddr = it.value().toString();
        } else if (it.key() == "remoteuser") {
            _remoteuser = it.value().toString();
        } else if (it.key() == "remotepass") {
            _remotepass = it.value().toString();
        } else if (it.key() == "remotepkgdir") {
            _remotepkgdir = it.value().toString();
        } else if (it.key() == "remotemeta") {
            _remotemetafile = it.value().toString();
        } else if (it.key() == "localmeta") {
            _localmetafile = it.value().toString();
        } else {
            pr_info("unknown json object: %s\n", it.key().toStdString().c_str());
   //         return -1;
        }
    }

    return 0;
}
예제 #10
0
InstanceList::InstListError InstanceList::loadList()
{
	QDir dir(m_instDir);
	QDirIterator iter(dir);
	
	QString groupFileName = m_instDir + "/instgroups.json";
	// temporary map from instance ID to group name
	QMap<QString, QString> groupMap;
	
	// HACK: this is really an if. breaks after one iteration.
	while (QFileInfo(groupFileName).exists())
	{
		QFile groupFile(groupFileName);
		
		if (!groupFile.open(QIODevice::ReadOnly))
		{
			// An error occurred. Ignore it.
			qDebug("Failed to read instance group file.");
			break;
		}
		
		QTextStream in(&groupFile);
		QString jsonStr = in.readAll();
		groupFile.close();
		
		QJsonParseError error;
		QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);
		
		if (error.error != QJsonParseError::NoError)
		{
			qWarning(QString("Failed to parse instance group file: %1 at offset %2").
					 arg(error.errorString(), QString::number(error.offset)).toUtf8());
			break;
		}
		
		if (!jsonDoc.isObject())
		{
			qWarning("Invalid group file. Root entry should be an object.");
			break;
		}
		
		QJsonObject rootObj = jsonDoc.object();
		
		// Make sure the format version matches.
		if (rootObj.value("formatVersion").toVariant().toInt() == GROUP_FILE_FORMAT_VERSION)
		{
			// Get the group list.
			if (!rootObj.value("groups").isObject())
			{
				qWarning("Invalid group list JSON: 'groups' should be an object.");
				break;
			}
			
			// Iterate through the list.
			QJsonObject groupList = rootObj.value("groups").toObject();
			
			for (QJsonObject::iterator iter = groupList.begin(); 
				 iter != groupList.end(); iter++)
			{
				QString groupName = iter.key();
				
				// If not an object, complain and skip to the next one.
				if (!iter.value().isObject())
				{
					qWarning(QString("Group '%1' in the group list should "
									 "be an object.").arg(groupName).toUtf8());
					continue;
				}
				
				QJsonObject groupObj = iter.value().toObject();
				/*
				// Create the group object.
				InstanceGroup *group = new InstanceGroup(groupName, this);
				groups.push_back(group);
				
				// If 'hidden' isn't a bool value, just assume it's false.
				if (groupObj.value("hidden").isBool() && groupObj.value("hidden").toBool())
				{
					group->setHidden(groupObj.value("hidden").toBool());
				}
				*/
				
				if (!groupObj.value("instances").isArray())
				{
					qWarning(QString("Group '%1' in the group list is invalid. "
									 "It should contain an array "
									 "called 'instances'.").arg(groupName).toUtf8());
					continue;
				}
				
				// Iterate through the list of instances in the group.
				QJsonArray instancesArray = groupObj.value("instances").toArray();
				
				for (QJsonArray::iterator iter2 = instancesArray.begin(); 
					 iter2 != instancesArray.end(); iter2++)
				{
					groupMap[(*iter2).toString()] = groupName;
				}
			}
		}
		break;
	}
	m_instances.clear();
	while (iter.hasNext())
	{
		QString subDir = iter.next();
		if (QFileInfo(PathCombine(subDir, "instance.cfg")).exists())
		{
			Instance *instPtr = NULL;
			
			InstanceLoader::InstLoaderError error = InstanceLoader::get().
					loadInstance(instPtr, subDir);
			
			if (error != InstanceLoader::NoError &&
				error != InstanceLoader::NotAnInstance)
			{
				QString errorMsg = QString("Failed to load instance %1: ").
						arg(QFileInfo(subDir).baseName()).toUtf8();
				
				switch (error)
				{
				default:
					errorMsg += QString("Unknown instance loader error %1").
							arg(error);
					break;
				}
				qDebug(errorMsg.toUtf8());
			}
			else if (!instPtr)
			{
				qDebug(QString("Error loading instance %1. Instance loader returned null.").
					   arg(QFileInfo(subDir).baseName()).toUtf8());
			}
			else
			{
				QSharedPointer<Instance> inst(instPtr);
				auto iter = groupMap.find(inst->id());
				if(iter != groupMap.end())
				{
					inst->setGroup((*iter));
				}
				qDebug(QString("Loaded instance %1").arg(inst->name()).toUtf8());
				inst->setParent(this);
				m_instances.append(inst);
				connect(instPtr, SIGNAL(propertiesChanged(Instance*)),this, SLOT(propertiesChanged(Instance*)));
			}
		}
	}
예제 #11
0
void InstanceList::loadGroupList(QMap<QString, QString> & groupMap)
{
	QString groupFileName = m_instDir + "/instgroups.json";
	
	// if there's no group file, fail
	if(!QFileInfo(groupFileName).exists())
		return;
	
	QFile groupFile(groupFileName);
	
	// if you can't open the file, fail
	if (!groupFile.open(QIODevice::ReadOnly))
	{
		// An error occurred. Ignore it.
		qDebug("Failed to read instance group file.");
		return;
	}
	
	QTextStream in(&groupFile);
	QString jsonStr = in.readAll();
	groupFile.close();
	
	QJsonParseError error;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);
	
	// if the json was bad, fail
	if (error.error != QJsonParseError::NoError)
	{
		qWarning(QString("Failed to parse instance group file: %1 at offset %2").
					arg(error.errorString(), QString::number(error.offset)).toUtf8());
		return;
	}
	
	// if the root of the json wasn't an object, fail
	if (!jsonDoc.isObject())
	{
		qWarning("Invalid group file. Root entry should be an object.");
		return;
	}
	
	QJsonObject rootObj = jsonDoc.object();
	
	// Make sure the format version matches, otherwise fail.
	if (rootObj.value("formatVersion").toVariant().toInt() != GROUP_FILE_FORMAT_VERSION)
		return;
	
	// Get the groups. if it's not an object, fail
	if (!rootObj.value("groups").isObject())
	{
		qWarning("Invalid group list JSON: 'groups' should be an object.");
		return;
	}
		
	// Iterate through all the groups.
	QJsonObject groupMapping = rootObj.value("groups").toObject();
	for (QJsonObject::iterator iter = groupMapping.begin(); iter != groupMapping.end(); iter++)
	{
		QString groupName = iter.key();
		
		// If not an object, complain and skip to the next one.
		if (!iter.value().isObject())
		{
			qWarning(QString("Group '%1' in the group list should "
								"be an object.").arg(groupName).toUtf8());
			continue;
		}
		
		QJsonObject groupObj = iter.value().toObject();
		if (!groupObj.value("instances").isArray())
		{
			qWarning(QString("Group '%1' in the group list is invalid. "
								"It should contain an array "
								"called 'instances'.").arg(groupName).toUtf8());
			continue;
		}
		
		// Iterate through the list of instances in the group.
		QJsonArray instancesArray = groupObj.value("instances").toArray();
		
		for (QJsonArray::iterator iter2 = instancesArray.begin(); 
				iter2 != instancesArray.end(); iter2++)
		{
			groupMap[(*iter2).toString()] = groupName;
		}
	}
}
예제 #12
0
파일: npc.cpp 프로젝트: kvonosan/Vibra
bool Npc::fireToNpc(int pos)
{
    if (!_loader->_db.isOpen())
    {
        if (!_loader->_db.open())
        {
            qDebug() << "Ошибка соединения к базе данных:" << _loader->_db.lastError();
            exit(-1);
        }
    }
    QChar fireToClass = ' ';
    QSqlQuery q1;
    q1.prepare("SELECT data FROM map WHERE map_id=:map_id");
    q1.bindValue(":map_id", _player->_map);
    q1.exec();
    QString data = "";
    if (q1.next())
    {
        data = q1.value(0).toString();
    }
    if (data == "")
    {
        return false;
    }
    fireToClass = data[pos];
    QSqlQuery q12;
    q12.prepare("SELECT count(map) FROM ship_point WHERE map=:map AND pos=:pos");
    q12.bindValue(":map", _player->_map);
    q12.bindValue(":pos", pos);
    q12.exec();
    _found = false;
    if (q12.next())
    {
        if (q12.value(0).toInt() == 1)
        {
            _found = true;
        }
    }
    if (!_found)
    {
        QSqlQuery q2;
        q2.prepare("SELECT life FROM ship_body WHERE class=:fireclass");
        q2.bindValue(":fireclass", fireToClass);
        q2.exec();
        int life = 0;
        if (q2.next())
        {
            life = q2.value(0).toInt();
        }
        if (life == 0)
        {
            return false;
        }
        life = (life - 100) + rand()%100;
        QSqlQuery q6;
        q6.prepare("INSERT INTO ship_point(ship_id, life, energy, armor, fuel, life_gen, "
                   "energy_gen, armor_gen, net_speed, cartograph_link, grab_points, "
                   "radar_ships, scaner_predm, fire, fire_speed, fire_link, map, pos) VALUES("
                   ":ship_id, :life, 0, 0, :fuel, 0, 0,0,0,0,0,0,0,0,0,0,:map,:pos)");
        q6.bindValue(":ship_id", 0);
        q6.bindValue(":life", life);
        q6.bindValue(":fuel", 25);
        q6.bindValue(":map", _player->_map);
        q6.bindValue(":pos", pos);
        q6.exec();
    }
    QSqlQuery q3;
    q3.prepare("SELECT ship_id FROM ship WHERE player_id=:player_id");
    q3.bindValue(":player_id", _player->_player_id);
    q3.exec();
    int ship_id = 0;
    if (q3.next())
    {
        ship_id = q3.value(0).toInt();
    }
    if (ship_id == 0)
    {
        return false;
    }
    QSqlQuery q4;
    q4.prepare("SELECT fire FROM ship_point WHERE ship_id=:ship_id");
    q4.bindValue(":ship_id", ship_id);
    q4.exec();
    int fire = 0;
    if (q4.next())
    {
        fire = q4.value(0).toInt();
    }
    if (fire == 0)
    {
        return false;
    }
    QSqlQuery q7;
    q7.prepare("SELECT life FROM ship_point WHERE map=:map AND pos=:pos");
    q7.bindValue(":map", _player->_map);
    q7.bindValue(":pos", pos);
    q7.exec();
    int npc_life = 0;
    if (q7.next())
    {
        npc_life = q7.value(0).toInt();
    }
    if (npc_life == 0)
    {
        return false;
    }
    npc_life -= fire;
    int opit = 0, kills = 0;
    if (npc_life <= 0)
    {
        QSqlQuery q9;
        q9.prepare("DELETE FROM ship_point WHERE map=:map AND pos=:pos");
        q9.bindValue(":map", _player->_map);
        q9.bindValue(":pos", pos);
        q9.exec();
        opit = 20;
        kills = 1;
        _killed = true;
        qDebug() << "[" << _player->_player_id << "]" << "огонь по " << fireToClass << " убит.";
        QSqlQuery q13;
        q13.prepare("SELECT data FROM map WHERE map_id=:id");
        q13.bindValue(":id", _player->_map);
        q13.exec();
        QString data;
        if (q13.next())
        {
            data = q13.value(0).toString();
        }
        data[pos] = ' ';
        QSqlQuery q16;
        q16.prepare("UPDATE map SET data=:data WHERE map_id=:id");
        q16.bindValue(":id", _player->_map);
        q16.bindValue(":data", data);
        q16.exec();
        QSqlQuery q17;
        int mission_id = 0;
        q17.prepare("SELECT params_json, id FROM mission WHERE player_id=:id");
        q17.bindValue(":id", _player->_player_id);
        q17.exec();
        while (q17.next())
        {
            QString json = q17.value(0).toString();
            mission_id = q17.value(1).toInt();
            QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
            QJsonObject obj = doc.object();
            QJsonObject::iterator it = obj.begin();
            QJsonObject obj1;
            while (it!= obj.end())
            {
                QString str = QString::fromUtf8(it.key().toStdString().c_str());
                if (str.contains("kill") && fireToClass == it.value().toString().at(0))
                {
                    //nothing to do..
                } else
                {
                    obj1.insert(it.key(), it.value());
                }
                it++;
            }
            if (obj1.count() == 1)
            {
                QString priz = obj1.value("priz").toString();
                QSqlQuery q21;
                q21.prepare("SELECT ship_id FROM ship WHERE player_id=:id");
                q21.bindValue(":id", _player->_player_id);
                q21.exec();
                int ship_bonus_id=0;
                if (q21.next())
                {
                    ship_bonus_id = q21.value(0).toInt();
                }
                if (priz == "cartograph")
                {
                    QSqlQuery q20;
                    q20.prepare("UPDATE ship SET cartograph=1 WHERE player_id=:id");
                    q20.bindValue(":id", _player->_player_id);
                    q20.exec();
                    int link = rand()%10;
                    QSqlQuery q22;
                    q22.prepare("UPDATE ship_point SET cartograph_link=:link WHERE ship_id=:id");
                    q22.bindValue(":link", link);
                    q22.bindValue(":id", ship_bonus_id);
                    q22.exec();
                    qDebug() << "[" << _player->_player_id << "] " << "Выигран бонус картограф!";
                    _player->_bonus = 1;
                } else if (priz == "droid")
                {
                    QSqlQuery q23;
                    int time = rand()%10;
                    int points = rand()%10;
                    q23.prepare("INSERT INTO droid(player_id, class, time, points) VALUES(:id, :class, :time, :points)");
                    q23.bindValue(":id", _player->_player_id);
                    q23.bindValue(":class", "A");
                    q23.bindValue(":time", QDateTime::currentDateTime().addDays(time));
                    q23.bindValue(":points", points);
                    q23.exec();
                    qDebug() << "[" << _player->_player_id << "] " << "Выигран бонус дроид!";
                    _player->_bonus = 2;
                }
                QSqlQuery q24;
                q24.prepare("DELETE FROM mission WHERE id=:id");
                q24.bindValue(":id", mission_id);
                q24.exec();
            }
            QJsonDocument doc1(obj1);
            QSqlQuery q25;
            QString str = QString::fromUtf8(doc1.toJson(QJsonDocument::Compact).toStdString().c_str());
            q25.prepare("UPDATE mission SET params_json=:str WHERE id=:id");
            q25.bindValue(":id", mission_id);
            q25.bindValue(":str", str);
            q25.exec();
        }
    } else
    {
        QSqlQuery q8;
        q8.prepare("UPDATE ship_point SET life=:life WHERE map=:map AND pos=:pos");
        q8.bindValue(":map", _player->_map);
        q8.bindValue(":pos", pos);
        q8.bindValue(":life", npc_life);
        q8.exec();
        opit = 10;
        qDebug() << "[" << _player->_player_id << "]" << "огонь по " << fireToClass << " урон = " << fire;
    }
    QSqlQuery q10;
    q10.prepare("SELECT exp, kills FROM rating WHERE player_id=:player_id");
    q10.bindValue(":player_id", _player->_player_id);
    q10.exec();
    int exp = 0, kills_base = 0;
    if (q10.next())
    {
        exp = q10.value(0).toInt();
        kills_base = q10.value(1).toInt();
    }
    exp+=opit;
    kills_base+=kills;
    QSqlQuery q11;
    q11.prepare("UPDATE rating SET exp=:exp, kills=:kills WHERE player_id=:player_id");
    q11.bindValue(":exp", exp);
    q11.bindValue(":kills", kills_base);
    q11.bindValue(":player_id", _player->_player_id);
    q11.exec();
    QSqlQuery q13;
    q13.prepare("SELECT level FROM player WHERE player_id=:id");
    q13.bindValue(":id", _player->_player_id);
    q13.exec();
    int level = 0;
    if (q13.next())
    {
        level = q13.value(0).toInt();
    }
    if (level == 0)
    {
        qDebug() << "Ошибка level поврежден.";
        exit(-1);
    }
    _levelup = false;
    if (level >= 1 && level <=10)
    {
        if (exp >=1300000)
        {
            _levelup = true;
        }
    }
    if (level >= 11 && level <=20)
    {
        if (exp >=2100000)
        {
            _levelup = true;
        }
    }
    if (level >= 21 && level <=30)
    {
        if (exp >=3300000)
        {
            _levelup = true;
        }
    }
    if (level >= 31 && level <=40)
    {
        if (exp >=4400000)
        {
            _levelup = true;
        }
    }
    if (level >= 41 && level <=50)
    {
        if (exp >=5500000)
        {
            _levelup = true;
        }
    }
    if (level >= 51 && level <=60)
    {
        if (exp >=7700000)
        {
            _levelup = true;
        }
    }
    if (_levelup)
    {
        level++;
        qDebug() << "Игрок с id = " << QString::number(_player->_player_id) << " Повышение уровня. "
                 << level;
        QSqlQuery q14;
        q14.prepare("UPDATE rating SET exp=:exp WHERE player_id=:player_id");
        q14.bindValue(":player_id", _player->_player_id);
        q14.bindValue(":exp", 0);
        q14.exec();
        QSqlQuery q15;
        q15.prepare("UPDATE player SET level=:level WHERE player_id=:player_id");
        q15.bindValue(":player_id", _player->_player_id);
        q15.bindValue(":level", level);
        q15.exec();
        _player->_level = level;
    }
    return true;
}
예제 #13
0
void DatabaseManager::createDatabaseSchema()
{
    if (openDB()) {
        QSqlQuery createTableQuery;

        //first thing, we'll set yoga_point table on database
        if (!createTableQuery.prepare("CREATE TABLE IF NOT EXISTS yoga_point (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) UNIQUE, point INT, is_serie TINYINT)")) {
            throw runtime_error(createTableQuery.lastError().text().toStdString());
        }
        if (!createTableQuery.exec()) {
            throw runtime_error(createTableQuery.lastError().text().toStdString());
        }
        //and series table
        if (!createTableQuery.prepare("CREATE TABLE IF NOT EXISTS series (id INT, yoga_point_id INT)")) {
            throw runtime_error(createTableQuery.lastError().text().toStdString());
        }
        if (!createTableQuery.exec()) {
            throw runtime_error(createTableQuery.lastError().text().toStdString());
        }

        vector<shared_ptr<YogaPoint>> yogaPoints;

        //we read position from JSON file and copy them in Database if positions is empty
        QSqlQuery selectCountYogaPoint("SELECT COUNT(*) FROM yoga_point");
        selectCountYogaPoint.next();
        int yogaPointCount = selectCountYogaPoint.value(0).toInt();

        if (yogaPointCount == 0)
        {
            QFile positionJsonFile(":/positions.json");
            if (positionJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QString jsonString = positionJsonFile.readAll();
                positionJsonFile.close();
                QJsonDocument positionJson = QJsonDocument::fromJson(jsonString.toUtf8());
                QJsonObject positions = positionJson.object();
                for (QJsonObject::iterator it = positions.begin(); it != positions.end(); it++) {
                    string positionName = it.key().toStdString();
                    int positionPoint = it.value().toInt();
                    shared_ptr<YogaPoint> position = make_shared<Position>(Position(positionName, positionPoint));
                    yogaPoints.push_back(position);
                    position->save();
                }
            } else {
                throw runtime_error("Error while reading JSON position file");
            }
            QFile serieJsonFile(":/series.json");
            if (serieJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QString jsonString = serieJsonFile.readAll();
                serieJsonFile.close();
                QJsonDocument serieJson = QJsonDocument::fromJson(jsonString.toUtf8());
                QJsonObject series = serieJson.object();
                map<string, vector<string>> serieStringMap;
                map<string, shared_ptr<YogaPoint>> serieMap;
                for (QJsonObject::iterator it = series.begin(); it != series.end(); it++) {
                    string serieName = it.key().toStdString();
                    shared_ptr<YogaPoint> serie = make_shared<Serie>(Serie(serieName));
                    serieMap[serieName] = serie;
                    yogaPoints.push_back(serie);
                    QJsonArray serieYogaPointNames = it.value().toArray();
                    vector<string> serieYogaPoints;
                    for (QJsonArray::iterator iit = serieYogaPointNames.begin(); iit != serieYogaPointNames.end(); iit++) {
                        //find Yoga Point matching the name
                        string yogaPointName = (*iit).toString().toStdString();
                        serieYogaPoints.push_back(yogaPointName);
                    }
                    serieStringMap[serieName] = serieYogaPoints;
                }
                for (pair<const string, vector<string>> element : serieStringMap) {
                    shared_ptr<YogaPoint> serie = serieMap[element.first];
                    for (string yogaPointName : element.second) {
                        auto yogaPointIt = find_if(yogaPoints.begin(), yogaPoints.end(), [&yogaPointName](shared_ptr<YogaPoint> yogaPoint) { return yogaPointName == yogaPoint->name(); });
                        if (yogaPointIt != yogaPoints.end()) {
                            dynamic_pointer_cast<Serie>(serie)->addYogaPoint(*yogaPointIt);
                        }
                    }
                    serie->save();
                }
            }
        }

        //now we create a table recording daily positions
        QSqlQuery CreateTableDailyPositionsQuery;
        if (!CreateTableDailyPositionsQuery.prepare("CREATE TABLE IF NOT EXISTS daily_positions (days DATE, position_id INT, times TINYINT, is_serie BOOLEAN DEFAULT 0 NOT NULL)")) {
            throw runtime_error(CreateTableDailyPositionsQuery.lastError().text().toStdString());
        }
        if (!CreateTableDailyPositionsQuery.exec()) {
            throw runtime_error(CreateTableDailyPositionsQuery.lastError().text().toStdString());
        }
    } else {
        throw runtime_error("Problem occured with database connection");
    }
}
예제 #14
0
파일: getTable.cpp 프로젝트: ilnuribat/tmob
//Чисто парсим JSon файл. Раскидываем по полочкам
void getTable::parser()
{
    QJsonDocument d = QJsonDocument::fromJson(httpResponse.toUtf8());//
    QJsonObject jsonObj = d.object();

    for(QJsonObject::iterator it = jsonObj.begin(); it != jsonObj.end(); it++)
    {
        QJsonValueRef tmp = (it.value());
        QJsonObject CJson = tmp.toObject();
        QJsonObject::iterator cell = CJson.begin();

        if(it == jsonObj.begin()){
            ui->car_00->setNum(cell.value().toDouble());
            cell++;
            ui->human_00->setNum(cell.value().toDouble());
            cell++;
            ui->success_00->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 1){
            ui->car_03->setNum(cell.value().toDouble());
            cell++;
            ui->human_03->setNum(cell.value().toDouble());
            cell++;
            ui->success_03->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 2){
            ui->car_06->setNum(cell.value().toDouble());
            cell++;
            ui->human_06->setNum(cell.value().toDouble());
            cell++;
            ui->success_06->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 3){
            ui->car_09->setNum(cell.value().toDouble());
            cell++;
            ui->human_09->setNum(cell.value().toDouble());
            cell++;
            ui->success_09->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 4){
            ui->car_12->setNum(cell.value().toDouble());
            cell++;
            ui->human_12->setNum(cell.value().toDouble());
            cell++;
            ui->success_12->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 5){
            ui->car_15->setNum(cell.value().toDouble());
            cell++;
            ui->human_15->setNum(cell.value().toDouble());
            cell++;
            ui->success_15->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 6){
            ui->car_18->setNum(cell.value().toDouble());
            cell++;
            ui->human_18->setNum(cell.value().toDouble());
            cell++;
            ui->success_18->setNum(cell.value().toDouble());
        }
        if(it == jsonObj.begin() + 7){
            ui->car_21->setNum(cell.value().toDouble());
            cell++;
            ui->human_21->setNum(cell.value().toDouble());
            cell++;
            ui->success_21->setNum(cell.value().toDouble());
        }
    }
}