diff --git a/CMakeLists.txt b/CMakeLists.txt index 869d2fc..7890c13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,73 +1,73 @@ cmake_minimum_required (VERSION 3.5 FATAL_ERROR) # KDE Application Version, managed by release script set(KDE_APPLICATIONS_VERSION_MAJOR "20") set(KDE_APPLICATIONS_VERSION_MINOR "03") set(KDE_APPLICATIONS_VERSION_MICRO "70") set(KDE_APPLICATIONS_VERSION "${KDE_APPLICATIONS_VERSION_MAJOR}.${KDE_APPLICATIONS_VERSION_MINOR}.${KDE_APPLICATIONS_VERSION_MICRO}") project(ksirk VERSION ${KDE_APPLICATIONS_VERSION}) -set (QT_MIN_VERSION "5.7.0") +set (QT_MIN_VERSION "5.8.0") set (KF5_MIN_VERSION "5.30.0") find_package(ECM ${KF5_MIN_VERSION} REQUIRED CONFIG) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR}) find_package(Qt5 ${QT_MIN_VERSION} REQUIRED NO_MODULE COMPONENTS Widgets Svg Test) find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS Completion Config ConfigWidgets CoreAddons Crash DocTools I18n IconThemes KIO NewStuff Wallet WidgetsAddons XmlGui ) find_package(KF5KDEGames 4.9.0 REQUIRED) find_package(Phonon4Qt5 REQUIRED) include(FeatureSummary) include(ECMAddAppIcon) include(ECMInstallIcons) include(ECMSetupVersion) include(KDEInstallDirs) include(KDECompilerSettings NO_POLICY_SCOPE) include(KDECMakeSettings) include(ECMQtDeclareLoggingCategory) add_definitions(-DQT_USE_FAST_CONCATENATION -DQT_USE_FAST_OPERATOR_PLUS) add_definitions(-DQT_NO_URL_CAST_FROM_STRING) find_package(Phonon4Qt5 CONFIG REQUIRED) find_package(Qca-qt5 2.1.0) set_package_properties(Qca-qt5 PROPERTIES DESCRIPTION "Support for encryption" URL "https://download.kde.org/stable/qca-qt5" TYPE REQUIRED) kde_enable_exceptions() remove_definitions(-DQT_NO_STL) ecm_setup_version(${KDE_APPLICATIONS_VERSION} VARIABLE_PREFIX KSIRK VERSION_HEADER ksirk_version.h) if (EXISTS "${CMAKE_SOURCE_DIR}/.git") add_definitions(-DQT_DISABLE_DEPRECATED_BEFORE=0x060000) add_definitions(-DKF_DISABLE_DEPRECATED_BEFORE_AND_AT=0x060000) endif() add_subdirectory(ksirk) add_subdirectory(ksirkskineditor) add_subdirectory(doc) if (${ECM_VERSION} STRGREATER "5.58.0") install(FILES ksirk.categories DESTINATION ${KDE_INSTALL_LOGGINGCATEGORIESDIR}) else() install(FILES ksirk.categories DESTINATION ${KDE_INSTALL_CONFDIR}) endif() feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/ksirk/GameLogic/gameautomaton.cpp b/ksirk/GameLogic/gameautomaton.cpp index 85f24d1..93cb3a0 100644 --- a/ksirk/GameLogic/gameautomaton.cpp +++ b/ksirk/GameLogic/gameautomaton.cpp @@ -1,2690 +1,2691 @@ /* This file is part of KsirK. Copyright (C) 2004-2007 Gael de Chalendar KsirK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "gameautomaton.h" #include "ksirksettings.h" #include "kgamewin.h" #include "aiplayer.h" #include "aiColsonPlayer.h" #include "aiplayerio.h" #include "onu.h" #include "dice.h" #include "goal.h" #include "country.h" #include "KMessageParts.h" #include "newgamesetup.h" #include "krightdialog.h" #include "Dialogs/joingame.h" #include "Jabber/kmessagejabber.h" #include "newplayerdata.h" #include #include #include #include #include #include #include #include #include #include #define USE_UNSTABLE_LIBKDEGAMESPRIVATE_API #include #include #include #include #include #include #include namespace Ksirk{ namespace GameLogic { const char* GameAutomaton::GameStateNames[] = { "INIT", "INTERLUDE", "NEWARMIES", "WAIT", "WAIT1", "WAIT_RECYCLING", "ATTACK", "ATTACK2", "INVADE", "SHIFT1", "SHIFT2", "FIGHT_BRING", "FIGHT_ANIMATE", "FIGHT_BRINGBACK", "WAITDEFENSE", "EXPLOSION_ANIMATE", "WAIT_PLAYERS", "GAME_OVER", "INVALID", "STARTING_GAME" }; const char* GameAutomaton::KsirkMessagesIdsNames[] = { "CountryOwner", // 257 "PlayerPutsArmy", // 258 "StateChange", // 259 "PlayerChange", // 260 "RegisterCountry", // 261 "PlayerAvailArmies", // 262 "ResetPlayersDistributionData", // 263 "ChangeItem", // 264 "DisplayRecyclingButtons", // 265 "ClearHighlighting", // 266 "ActionRecycling", // 267 "ClearGameActionsToolbar", // 268 "DisplayDefenseButtons", // 269 "ActionDefense", // 270 "FirstCountry", // 271 "SecondCountry", // 272 "InitCombatMovement", // 273 "AnimCombat", // 274 // 275 "TerminateAttackSequence", // 276 "DecrNbArmies", // 277 "StartLocalCurrentAI", // 278 "Invade", // 279 "Retreat", // 280 "NextPlayerNormal", // 281 "NextPlayerRecycling", // 282 "ShowArmiesToPlace", // 283 "PlayerPutsInitialArmy", // 284 "PlayerRemovesArmy", //285 "VoteRecyclingFinished", // 286 "CancelShiftSource", // 287 "ChangePlayerNation", // 288 "ChangePlayerName", // 289 "StartGame", // 290 "SetNation", // 291 "SetBarFlagButton", // 292 "FinishMoves", // 293 "AnimExplosion", // 294 "SetupOnePlayer", // 295 "SetupWaitedPlayer", // 296 "ValidateWaitedPlayerPassword", // 297 "ValidPassword", // 298 "InvalidPassword", // 299 "SetupCountries", // 300 "AddMsgIdPair", // 301 "CheckGoal", // 302 "SetGoalFor", // 303 "GoalForIs", // 304 "Winner", // 305 "NbPlayers", // 306 "FinalizePlayers", // 307 "Acknowledge", // 308 "DisplayGoals", // 309 "DisplayFightResult", // 310 "MoveSlide", // 311 "InvasionFinished", // 312 "AttackAuto", // 313 "DisplayRecycleDetails", // 314 "CurrentPlayerPlayed", // 315 "NewGameSetupMsg", // 316 }; #define KSIRK_DEFAULT_PORT 20000 GameAutomaton::GameAutomaton() : KGame(), m_aicannotrunhack(true), m_state(INIT), m_game(0), m_networkPlayersNumber(0), m_currentPlayer(""), m_currentPlayerPlayed(false), m_savedState(INVALID), m_goals(), m_useGoals(true), m_attackAuto(false), m_defenseAuto(false), m_port(KSIRK_DEFAULT_PORT), m_startingGame(false) { m_skin = "skins/default"; // qCDebug(KSIRK_LOG) << endl; // m_stateId = m_state.registerData(dataHandler(),KGamePropertyBase::PolicyDirty,QString("m_state")); m_skinId = m_skin.registerData(dataHandler(),KGamePropertyBase::PolicyDirty,QString("m_skin")); // m_currentPlayerId = m_currentPlayer.registerData(dataHandler(),KGamePropertyBase::PolicyDirty,QString("m_currentPlayer")); // m_events.registerData(dataHandler(),KGamePropertyBase::PolicyDirty,QString("m_events")); // Connect the most important slot which tells us which properties are // changed connect(this,&KGame::signalPropertyChanged, this,&GameAutomaton::slotPropertyChanged); connect(this,&KGame::signalPlayerJoinedGame, this,&GameAutomaton::slotPlayerJoinedGame); connect(this,&KGame::signalNetworkData, this,&GameAutomaton::slotNetworkData); connect(this,&KGame::signalClientJoinedGame, this,&GameAutomaton::slotClientJoinedGame); connect(messageClient(),&KMessageClient::connectionBroken, this,&GameAutomaton::slotConnectionToServerBroken); connect(messageServer(),&KMessageServer::connectionLost, this,&GameAutomaton::slotConnectionToClientBroken); setPolicy(KGame::PolicyDirty,true); // qCDebug(KSIRK_LOG) << "finished" << endl; } GameAutomaton::~GameAutomaton() { qCDebug(KSIRK_LOG); qDeleteAll(m_goals); } void GameAutomaton::init(KGameWindow* gw) { m_game = gw; } GameAutomaton::GameState GameAutomaton::state() const { return m_state; } void GameAutomaton::state(GameAutomaton::GameState state) { qCDebug(KSIRK_LOG) << "new state (id=" << state << ") is " << GameStateNames[state] << endl; m_state = state; m_game->setSaveGameActionEnabled(m_state == WAIT); m_game->setContextualHelpActionEnabled(m_state, currentPlayer() && currentPlayer()->isAI()); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << state; sendMessage(buffer,StateChange); } Player* GameAutomaton::getAnyLocalPlayer() { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( !((Player*)(*it))->isVirtual() ) { return (Player*)(*it); } } return 0; } GameAutomaton::GameState GameAutomaton::run() { // qCDebug(KSIRK_LOG) << "(KGame running=" << (gameStatus()==KGame::Run) << ")"; if (m_game == 0 || gameStatus() == KGame::Pause) { QTimer::singleShot(200, this, &GameAutomaton::run); return m_state; } activateNeededAIPlayers(); QString event = ""; QPointF point; if (!m_events.empty()) { QPair< QString, QPointF > pair = m_events.front(); event = pair.first; point = pair.second; m_events.pop_front(); } // qCDebug(KSIRK_LOG) << "Handling " << stateName() << " ; " << event << " ; " << point; // if (currentPlayer()) // { // qCDebug(KSIRK_LOG) << "current player=" << currentPlayer()->name() << " is active=" << currentPlayer()->isActive(); // } if (event == "requestForAck") { qCDebug(KSIRK_LOG) << "requestForAck" << endl; } if((event == "actionRButtonDown" || event == "actionLButtonDown") && (m_state != INIT && m_state != NEWARMIES && m_state != INTERLUDE && m_state != WAIT_RECYCLING)) { if (m_game->getRightDialog()->isOpen()) { m_game->getRightDialog()->close(); } } if (event == "actionNewGame") { if (m_game->actionNewGame(GameAutomaton::None)) { state(INIT); QTimer::singleShot(200, this, &GameAutomaton::run); return INIT; } else { QTimer::singleShot(200, this, &GameAutomaton::run); return m_state; } } if (event == "actionOpenGame") { if (m_game->actionOpenGame()) { qCDebug(KSIRK_LOG) << "opened" << endl; bool ok; m_port = QInputDialog::getInt(m_game, i18n("KsirK - Network configuration"), i18n("Please type in the port number on which to offer connections:"), m_port, 0, 32000, 1, &ok); offerConnections(m_port); state(WAIT_PLAYERS); QTimer::singleShot(200, this, &GameAutomaton::run); return WAIT_PLAYERS; } else { qCDebug(KSIRK_LOG) << "opened" << endl; QTimer::singleShot(200, this, &GameAutomaton::run); return m_state; } } if (event == "actionJoinNetworkGame") { joinNetworkGame(); QTimer::singleShot(200, this, &GameAutomaton::run); return m_state; } switch (m_state) { case INIT: if (currentPlayer() != 0 && isAdmin()) { if ( (event == "actionLButtonDown") && (m_game->playerPutsInitialArmy(point)) ) { m_choosedToRecycleNumber = 0; m_game->initRecycling(); state(WAIT_RECYCLING); } } break; case ATTACK: state(ATTACK2); break; case ATTACK2: qCDebug(KSIRK_LOG) << "Handling ATTACK2"; if (isAdmin()) { QByteArray buffer; switch ( m_game->attacked(point) ) { case 0: qCDebug(KSIRK_LOG) << "handling attacked value; 0" << endl; state(WAIT); break; case 1: qCDebug(KSIRK_LOG) << "handling attacked value; 1" << endl; sendMessage(buffer,CurrentPlayerPlayed); state(WAITDEFENSE); break; case 2: qCDebug(KSIRK_LOG) << "handling attacked value; 2" << endl; sendMessage(buffer,CurrentPlayerPlayed); qCDebug(KSIRK_LOG) << "calling defense(1)" << endl; m_game-> defense(1); qCDebug(KSIRK_LOG) << "setting state to FIGHT_BRING" << endl; state(FIGHT_BRING); break; case 3: qCDebug(KSIRK_LOG) << "handling attacked value; 3" << endl; // AI action: nothing to do. break; default: qCCritical(KSIRK_LOG) << "Unknown return value from attacked" << endl; exit(1); } } qCDebug(KSIRK_LOG) << "handling of ATTACK2 finished !" << endl; break; case EXPLOSION_ANIMATE: break; case FIGHT_ANIMATE: break; case FIGHT_BRING: break; case FIGHT_BRINGBACK: // no more moving fighter returning home // qCDebug(KSIRK_LOG) << "$$$$$$$STATE FIGHT_BRINGBACK $$$$$$$$$$$" << m_game->haveAnimFighters() << endl; if (!m_game->haveAnimFighters() && isAdmin()) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,TerminateAttackSequence); } break; case INTERLUDE: if (event == "playersLooped") { m_choosedToRecycleNumber = 0; m_game->initRecycling(); state(WAIT_RECYCLING); } else if (event == "actionLButtonDown" ) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << point; // qCDebug(KSIRK_LOG) << "Sending message PlayerPutsArmy " << point << endl; sendMessage(buffer,PlayerPutsInitialArmy); } else if (event == "actionRButtonDown") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << point; sendMessage(buffer,PlayerRemovesArmy); } else if (event == "actionNextPlayer") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << -1; sendMessage(buffer,NextPlayerRecycling); } else if (event == "actionRecycling") { QByteArray buffer; sendMessage(buffer,ActionRecycling); } else if (event == "actionRecyclingFinished") { qCDebug(KSIRK_LOG) << "actionRecyclingFinished"; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); // stream << currentPlayer()->name(); PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); quint32 nbLocal = 0; for (; it != it_end; it++) { if ( !((Player*)(*it))->isVirtual() ) { qCDebug(KSIRK_LOG) << "Local:" << ((Player*)(*it))->name(); nbLocal++; } } qCDebug(KSIRK_LOG) << "Nb Local:" << nbLocal; stream << nbLocal; for (it = playerList()->begin(); it != it_end; it++) { if ( !((Player*)(*it))->isVirtual() ) { stream << ((Player*)(*it))->id(); } } sendMessage(buffer,VoteRecyclingFinished); } else { // if (!event.isEmpty()) // qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName() << endl; } break; case INVADE: // qCDebug(KSIRK_LOG) << "$$$$$$$STATE INVADE$$$$$$$$$$$" << endl; if (event == "actionInvade1") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,Invade); } else if (event == "actionInvade5") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(5); sendMessage(buffer,Invade); } else if (event == "actionInvade10") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(10); sendMessage(buffer,Invade); } else if (event == "actionRetreat1") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,Retreat); } else if (event == "actionRetreat5") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(5); sendMessage(buffer,Retreat); } else if (event == "actionRetreat10") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(10); sendMessage(buffer,Retreat); } else if (event == "actionInvasionFinished") { state(WAIT); m_game-> invasionFinished(); } else { // if (!event.isEmpty()) // qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName() << endl; } break; case NEWARMIES: if (event == "actionLButtonDown") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << point << quint32(true); sendMessage(buffer,PlayerPutsArmy); } else if (event == "actionRButtonDown") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << point; sendMessage(buffer,PlayerRemovesArmy); } else if (event == "actionNextPlayer") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(WAIT); sendMessage(buffer,NextPlayerRecycling); } // else // { // if (!event.isEmpty()) // qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName() << endl; // } break; case SHIFT1: if (event == "actionCancel") { m_game-> cancelAction(); state(WAIT); } else if (event == "actionLButtonDown") { m_game->firstCountryAt(point); } else if (event == "actionLButtonUp") { m_game->secondCountryAt(point); if (m_game->isMoveValid(point)) { m_game->startLocalCurrentAI(); QByteArray buffer; sendMessage(buffer,CurrentPlayerPlayed); state(SHIFT2); } else { // state(WAIT); } } else { // if (!event.isEmpty()) // qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName(); } break; case SHIFT2: // qCDebug(KSIRK_LOG) << "$$$$$$$STATE SHIFT2$$$$$$$$$$$" << endl; if (event == "actionInvade1") { // qCDebug(KSIRK_LOG) << "actionInvade1" << endl; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,Invade); } else if (event == "actionInvade5") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(5); sendMessage(buffer,Invade); } else if (event == "actionInvade10") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(10); sendMessage(buffer,Invade); } else if (event == "actionRetreat1") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,Retreat); } else if (event == "actionRetreat5") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(5); sendMessage(buffer,Retreat); } else if (event == "actionRetreat10") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(10); sendMessage(buffer,Retreat); } else if (event == "actionInvasionFinished") { m_game-> shiftFinished(); state(WAIT); } else if (event == "actionCancel") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,CancelShiftSource); } else { //qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName(); } break; case WAIT_RECYCLING: if (event == "actionRecycling") { QByteArray buffer; sendMessage(buffer,ActionRecycling); } else if (event == "actionRecyclingFinished") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); // stream << currentPlayer()->name(); PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); quint32 nbLocal = 0; for (; it != it_end; it++) { if ( !((Player*)(*it))->isVirtual() ) { nbLocal++; } } stream << nbLocal; it = playerList()->begin(); it_end = playerList()->end(); for (; it != it_end; it++) { if ( !((Player*)(*it))->isVirtual() ) { stream << (*it)->id(); } } sendMessage(buffer,VoteRecyclingFinished); } else { if (!event.isEmpty()) qCDebug(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName() << endl; else { if (allLocalPlayersComputer()) { m_game->getRightDialog()->updateRecycleDetails(NULL,true,0); m_game->displayRecyclingButtons(); } } } break; case WAITDEFENSE: if (event == "actionDefense1") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,ActionDefense); } else if (event == "actionDefense2") { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(2); sendMessage(buffer,ActionDefense); } else if ( m_game->secondCountry() != 0 && !m_game->secondCountry()->owner()->isVirtual() && isDefenseAuto() && (m_game->secondCountry()->owner()->getNbDefense() == 0) ) { quint32 nbDefense = 1; if (m_game->secondCountry()->nbArmies() > 1) { nbDefense = 2; } m_game->secondCountry()->owner()->setNbDefense(nbDefense); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << nbDefense; sendMessage(buffer,ActionDefense); } else { // if (!event.isEmpty()) qCDebug(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName(); } break; case WAIT: if (event == "actionNextPlayer") { actionNextPlayer(); } else if (event == "actionLButtonDown") { if (m_game->firstCountryAt(point)) state(WAIT1); } else { // if (!event.isEmpty()) // qCCritical(KSIRK_LOG) << "Unhandled event " << event << " during handling of " << stateName(); } // other case : state doesn't change break; case WAIT1: if (event == "actionNextPlayer") { actionNextPlayer(); } else if (event == "actionAttack1") { m_game->attack(1); state(ATTACK); } else if (event == "actionAttack2") { m_game->attack(2); state(ATTACK); } else if (event == "actionAttack3") { m_game->attack(3); state(ATTACK); } else if (event == "actionInvade1") { // qCDebug(KSIRK_LOG) << "actionInvade1" << endl; QByteArray buffer2; sendMessage(buffer2,CurrentPlayerPlayed); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(1); sendMessage(buffer,Invade); // state(WAIT); } else if (event == "actionInvade5") { QByteArray buffer2; sendMessage(buffer2,CurrentPlayerPlayed); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(5); sendMessage(buffer,Invade); // state(WAIT); } else if (event == "actionInvade10") { QByteArray buffer2; sendMessage(buffer2,CurrentPlayerPlayed); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(10); sendMessage(buffer,Invade); // state(WAIT); } else if (event == "actionInvasionFinished") { m_game-> shiftFinished(); state(WAIT); } else if (event == "actionLButtonUp") { qCDebug(KSIRK_LOG) << "actionLButtonUp in WAIT1"; if (!currentPlayer()-> isAI()) { if (m_game->isMoveValid(point) && m_game->firstCountry()->nbArmies() !=1) { m_game->secondCountryAt(point); state(WAIT); qCDebug(KSIRK_LOG) << "Sending MoveSlide"; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,MoveSlide); } else if (m_game->isFightValid(point) && m_game->firstCountry()->nbArmies() != 1) { m_game->secondCountryAt(point); if (m_game->firstCountry()->nbArmies() > 3) { m_game->frame()->getAttack1Action()->setVisible(true); m_game->frame()->getAttack2Action()->setVisible(true); m_game->frame()->getAttack3Action()->setVisible(true); } else if (m_game->firstCountry()->nbArmies() > 2) { m_game->frame()->getAttack1Action()->setVisible(true); m_game->frame()->getAttack2Action()->setVisible(true); m_game->frame()->getAttack3Action()->setVisible(false); } else if (m_game->firstCountry()->nbArmies() > 1) { m_game->frame()->getAttack1Action()->setVisible(true); m_game->frame()->getAttack2Action()->setVisible(false); m_game->frame()->getAttack3Action()->setVisible(false); } m_game->frame()->setMenuPoint(QCursor::pos()); m_game->frame()->getAttackContextMenu()->exec(QCursor::pos()); } else { m_game-> cancelAction(); state(WAIT); } } else { m_game->secondCountryAt(point); } } else if (event == "actionLButtonDown") { m_game-> cancelAction(); if (m_game->firstCountryAt(point)) { state(WAIT1); } state(WAIT); } break; /*case WAIT_INPUT: break;*/ case WAIT_PLAYERS: break; case GAME_OVER: break; case STARTING_GAME: break; default: qCCritical(KSIRK_LOG) << "Unhandled state: " << stateName() << ". Event was: " << event << endl; exit(1); // @todo handle this error } QTimer::singleShot(200, this, &GameAutomaton::run); // m_game->initTimer(); return m_state; } void GameAutomaton::activateNeededAIPlayers() { // qCDebug(KSIRK_LOG); if ( currentPlayer() && (currentPlayer()-> isAI() ) && (!currentPlayer()->isVirtual()) && (!(dynamic_cast< AIPlayer* >(currentPlayer())-> isRunning())) ) { dynamic_cast< AIPlayer* >(currentPlayer())-> start(); } if ( ( m_state == WAITDEFENSE ) && ( m_game->secondCountry()) && ( m_game->secondCountry()->owner()) && ( m_game->secondCountry()->owner()->isAI() ) && ( !m_game->secondCountry()->owner()->isVirtual()) && ( !(dynamic_cast< AIPlayer* >(m_game->secondCountry()->owner())-> isRunning())) ) { dynamic_cast< AIPlayer* >(m_game->secondCountry()->owner())-> start(); } } void GameAutomaton::gameEvent(const QString& event, const QPointF& point) { m_events.push_back(qMakePair(event, point)); } /** returns the name of the current state */ QString GameAutomaton::stateName() const { if (m_state >= (int) sizeof(GameStateNames)) { QString string; QTextStream oss(&string); oss << "Invalid stored state id: " << m_state; qCCritical(KSIRK_LOG) << string << endl; return string; } else { return QString::fromUtf8(GameStateNames[m_state]); } } void GameAutomaton::saveXml(QTextStream& xmlStream) { xmlStream << "" << endl; } const QString& GameAutomaton::skin() const { return m_skin.value(); } void GameAutomaton::skin(const QString& newSkin) { m_skin = newSkin; } // Called when a player input (e.g. a mouse event) is received from the KGame // object // This is obviously the central function in the game as all player moves, // whether network or local, end up here. So do something sensible here. bool GameAutomaton::playerInput(QDataStream &msg, KPlayer* player) { qCDebug(KSIRK_LOG); // if (player->isVirtual()) if (!isAdmin()) { // qCDebug(KSIRK_LOG) << "Network player: nothing to do" << endl; return false; } // Convert the player to the right class Player* p = dynamic_cast(player); QString action; QPointF point; msg >> action >> point; qCDebug(KSIRK_LOG) << " ======================================================="<name() << " id=" << player->id() << " uid=" << player->userId() << " : " << action << " at " << point << "current is" << currentPlayer()->name(); if (p->name() == currentPlayer()->name() || (m_state == WAITDEFENSE) ) { if (action == "actionLButtonDown") m_game->slotLeftButtonDown( point ); else if (action == "actionLButtonUp") m_game->slotLeftButtonUp( point ); else if (action == "actionRButtonDown") m_game->slotRightButtonDown( point ); else if (action == "actionRButtonUp") m_game->slotRightButtonUp( point ); else if (action == "zoomInAction") m_game->slotZoomIn(); else if (action == "zoomOutAction") m_game->slotZoomOut(); else if (action == "actionAttack1") m_game->slotAttack1(); else if (action == "actionAttack2") m_game->slotAttack2(); else if (action == "actionAttack3") m_game->slotAttack3(); else if (action == "actionMove") m_game->slotMove(); else if (action == "slotRecyclingFinished") m_game->slotRecyclingFinished(); else if (action == "actionInvade10") m_game->slotInvade10(); else if (action == "actionInvade5") m_game->slotInvade5(); else if (action == "actionInvade1") m_game->slotInvade1(); else if (action == "actionInvasionFinished") m_game->slotInvasionFinished(); else if (action == "slotDefense1") m_game->slotDefense1(); else if (action == "slotDefense2") m_game->slotDefense2(); else if (action == "actionNextPlayer") m_game->slotNextPlayer(); } if (action == "requestForAck") { QString ack; msg >> ack; qCDebug(KSIRK_LOG) << "acknowledging " << ack; if (p->isVirtual()) { qCDebug(KSIRK_LOG) << p->name() << "is virtual; sending message"; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << p->id() << ack; sendMessage(buffer,Acknowledge); } else { qCDebug(KSIRK_LOG) << p->name() << "is local; acknowledging"; p->acknowledge(ack); } } return false; } // Create an IO device for the player. We could create any // device here, e.g. mouse, keyboard, computer player. In the // demo game here we have only the mouse player available. void GameAutomaton::createIO(KPlayer *player,KGameIO::IOMode io) { // Error check if (!player) return; qCDebug(KSIRK_LOG) << "createIO for " << player->name() << endl; if (io&KGameIO::MouseIO) { // Create new game mouse input KGameMouseIO *input; // We want the player to work over mouse // in our canvas view input=new KGameMouseIO(m_game->frame()->scene()); // Connect mouse input to a function to process the actual input connect( input, &KGameMouseIO::signalMouseEvent, m_game->frame(), &DecoratedGameFrame::slotMouseInput); // Add the device to the player player->addGameIO(input); } else if (io&AIPLAYERIO) { if (dynamic_cast(player) != 0) { /*AIPlayerIO* input =*/ new AIPlayerIO(dynamic_cast(player)); } else { qCCritical(KSIRK_LOG) << "Can create an AIPlayerIO only for AI players: " << io << endl; } } else { qCCritical(KSIRK_LOG) << "Cannot create the requested IO device " << io << endl; } qCDebug(KSIRK_LOG) << "Done createIO for " << player->name() << endl; } // Find out who will be the next player // Note: The default behaviour as we have it here is done automatically // by the lib, too. So if all players player one after the other // this functions is NOT needed at all. KPlayer * GameAutomaton::nextPlayer(KPlayer */*last*/,bool /*exclusive*/) { // qCDebug(KSIRK_LOG) << last->name() << endl; // m_game->setCurrentPlayerToNext(); // If a last player is given switch the player // Should be enough if the admin sets the turn (unclear) if (isAdmin()) { currentPlayer()->setTurn(true,true); // last->setTurn(true,true); // qCDebug(KSIRK_LOG) << "nextPlayer::Setting turn to " << last->name() << ", " << last->id() << "("<userId()<<")"<userId().value(),next,this); // Return the next player return dynamic_cast(currentPlayer()); } QDataStream& operator>>(QDataStream& s, GameAutomaton::GameState& state) { int istate; s >> istate; state = GameAutomaton::GameState(istate); return s; } bool GameAutomaton::setupPlayersNumberAndSkin(NetworkGameType netGameType) { qCDebug(KSIRK_LOG) << netGameType << endl; m_netGameType = netGameType; m_game->newGameDialog(m_skin.value(), m_netGameType); // m_networkPlayersNumber = ???; return false; } bool GameAutomaton::finishSetupPlayersNumberAndSkin() { qCDebug(KSIRK_LOG); setUseGoals(m_game->newGameSetup()->useGoals()); state(GameLogic::GameAutomaton::INIT); savedState(GameLogic::GameAutomaton::INVALID); setNetworkPlayersNumber(m_game->newGameSetup()->nbNetworkPlayers()); m_startingGame = true; state(INIT); setMinPlayers(m_game->newGameSetup()->nbPlayers()); setMaxPlayers(m_game->newGameSetup()->nbPlayers()); m_nbPlayers = m_game->newGameSetup()->nbPlayers(); return true; } void GameAutomaton::setGoalFor(Player* player) { qCDebug(KSIRK_LOG) << player->name() << endl; unsigned int max = m_goals.size(); unsigned int goalId = Dice::roll(max); QList< Goal* >::iterator it = m_goals.begin(); for (unsigned int i = 1 ; i < goalId; it++,i++) {} Goal* goal = (*it); qCDebug(KSIRK_LOG) << "Goal for " << player->name() << " is of type " << goal->type() << endl; if (goal->type() == Goal::GoalPlayer) { Player* target = 0; while (target==0 || target->id() == player->id()) { unsigned int max = playerList()->count(); unsigned int playerNum = Dice::roll(max); // qCDebug(KSIRK_LOG) << "Choice player num " << playerNum << " on " << max << endl; PlayersArray::iterator itp = playerList()->begin(); unsigned int j = 1; for (; j < playerNum; j++,itp++) {} target = dynamic_cast< Player* >(*itp); } if (target != 0) { // qCDebug(KSIRK_LOG) << "Target choice for " << player->name() << ": " << target->name() << endl; goal->players().push_back(target->name()); } else { // qCDebug(KSIRK_LOG) << "No target chosen for " << player->name() << endl; } } /// @note hack to avoid too easy countries goal when there is only two players else if (goal->type() == Goal::Countries && playerList()->count() == 2) { goal->nbCountries(int(goal->nbCountries()*1.5)); } QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << player->id(); stream << (*goal); qCDebug(KSIRK_LOG) << "Sending message GoalForIs ("<name() << endl; sendMessage(buffer,GoalForIs); // delete goal; m_goals.erase(it); } Country * GameAutomaton::getDefCountry () { return this->defCountry; } bool GameAutomaton::joinNetworkGame() { qCDebug(KSIRK_LOG); if (stateName() == "INIT" || (KMessageBox::warningContinueCancel(m_game,i18n("Do you really want to end your current game and join another?"),i18n( "New game confirmation" ),KStandardGuiItem::yes()) == KMessageBox::Continue)) { m_game->joinNetworkGame(); } return false; } bool GameAutomaton::connectToServ() { qCDebug(KSIRK_LOG); if (messageServer() != 0) { QObject::disconnect(messageServer(),&KMessageServer::connectionLost, this,&GameAutomaton::slotConnectionToClientBroken); } qCDebug(KSIRK_LOG) << "Before connectToServer" << endl; QString host = m_game->newGameSetup()->host(); int port = m_game->newGameSetup()->tcpPort(); bool status = connectToServer(host, port); qCDebug(KSIRK_LOG) << "After connectToServer" << status; if (messageServer()) connect(messageServer(),&KMessageServer::connectionLost, this,&GameAutomaton::slotConnectionToClientBroken); return status; } bool GameAutomaton::joinJabberGame(const QString& nick) { if (stateName() == "INIT" || (KMessageBox::warningContinueCancel(m_game,i18n("Do you really want to end your current game and join another?"),i18n( "New game confirmation" ),KStandardGuiItem::yes()) == KMessageBox::Continue)) { // stop game setGameStatus(KGame::End); state(INIT); savedState(INVALID); if (messageServer() != 0) { QObject::disconnect(messageServer(),&KMessageServer::connectionLost, this,&GameAutomaton::slotConnectionToClientBroken); } qCDebug(KSIRK_LOG) << "Before connectToServer" << endl; m_game->setServerJid(nick); KMessageJabber* messageIO = new KMessageJabber(m_game->serverJid().full(), m_game->jabberClient(), this); bool status = connectToServer(messageIO); // bool status = connectToServer(host, port); qCDebug(KSIRK_LOG) << "After connectToServer" << status; if (status) { QByteArray msg("connect"); XMPP::Message message(m_game->serverJid().full()); message.setType("ksirkgame"); message.setId(QUuid::createUuid().toString().remove("{").remove("}").remove("-")); message.setBody(msg); m_game->jabberClient()->sendMessage(message); } // connect(messageServer(),SIGNAL(connectionLost(KMessageIO*)), // this,SLOT(slotConnectionToClientBroken(KMessageIO*))); return status; } return false; } KPlayer * GameAutomaton::createPlayer(int rtti, int /*io*/, bool isVirtual) { qCDebug(KSIRK_LOG) << "(" << rtti << ", " << isVirtual << ")" << endl; if (rtti == 1) { Player* p = new Player(this, "", 0, 0); p->setVirtual(isVirtual); if (!isVirtual) { qCDebug(KSIRK_LOG) << "Calling player createIO" << endl; createIO(p,KGameIO::IOMode(KGameIO::MouseIO)); } return (KPlayer*) p; } else if (rtti == 2) { AIPlayer* aip = new AIColsonPlayer("", 0, 0, *playerList(), m_game->theWorld(), this); aip->stop(); aip->setVirtual(isVirtual); if (!isVirtual) { qCDebug(KSIRK_LOG) << "Calling player createIO" << endl; createIO(aip, KGameIO::IOMode(AIPLAYERIO)); } return (KPlayer*) aip; } else { qCCritical(KSIRK_LOG) << "No rtti given... creating a Player" << endl; Player* p = new Player(this, "", 0, 0); p->setVirtual(isVirtual); if (!isVirtual) { qCDebug(KSIRK_LOG) << "Calling player createIO" << endl; createIO(p,KGameIO::IOMode(KGameIO::MouseIO)); } return (KPlayer*) p; } } /** * @return A pointer to the given's named player ; 0 if there is no such player */ Player* GameAutomaton::playerNamed(const QString& playerName) { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( (*it)-> name() == playerName) { return dynamic_cast(*it); } } qCCritical(KSIRK_LOG) << "GameAutomaton::playerNamed: there is no player named " << playerName << endl; return 0; } Player* GameAutomaton::currentPlayer() { if (m_game && !m_currentPlayer.isEmpty()) { return playerNamed(m_currentPlayer); } else return 0; } void GameAutomaton::currentPlayer(Player* player) { qCDebug(KSIRK_LOG) << endl; if (player) { qCDebug(KSIRK_LOG) << " name = " << player->name() << endl; m_currentPlayer = player->name(); m_currentPlayerPlayed = false; if (isAdmin()) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << m_currentPlayer; sendMessage(buffer,PlayerChange); player->setTurn(true,true); } QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << player->name(); sendMessage(buffer,SetBarFlagButton); if (!player->isVirtual()) { m_game->chatWidget()->setFromPlayer(player); } } else m_currentPlayer = ""; } void GameAutomaton::slotPlayerJoinedGame(KPlayer* player) { qCDebug(KSIRK_LOG) << "currently " << playerList()->count() << " / " << maxPlayers() << endl; Player* p = dynamic_cast(player); Q_ASSERT(p); if (isAdmin()) { unsigned int nbWithNation = 0; unsigned int nbWithName = 0; PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if (p->getNation()->name() == ((Player*)(*it))->getNation()->name()) { nbWithNation++; } if (p->name() == ((Player*)(*it))->name()) { nbWithName++; } } if (nbWithName != 1) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << quint32(player->id()); qCDebug(KSIRK_LOG) << "Sending ChangePlayerName for player id " << player->id() << endl; sendMessage(buffer,ChangePlayerName); return; } else if (nbWithNation != 1) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << player->id(); qCDebug(KSIRK_LOG) << "Sending ChangePlayerNation for player id " << player->id() << endl; sendMessage(buffer,ChangePlayerNation); return; } KMessageParts messageParts; messageParts << I18N_NOOP("%1 (%2) joined game ; waiting for %3 players to connect") << p-> name() << p->getNation()->name() << QString::number(maxPlayers() - int(playerList()->count())); m_game->broadcastChangeItem(messageParts, ID_STATUS_MSG2); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); qCDebug(KSIRK_LOG) << "Sending StartGame" << endl; sendMessage(buffer,StartGame); } else { if (!player->isVirtual()) { m_game->showNewGameSummary(); } m_game->newGameSetup()->setNbPlayers(maxPlayers()); } NewPlayerData* pd = new NewPlayerData(p->name(),p->getNation()->name(),"",p->isAI(),true); if (!m_game->newGameSetup()->addPlayer(pd)) { delete pd; } m_game->updateNewGameSummary(); } bool GameAutomaton::startGame() { qCDebug(KSIRK_LOG) << stateName() << "nb players = " << playerList()->count() << " / " << maxPlayers() << endl; m_aicannotrunhack = true; // qCDebug(KSIRK_LOG) << " state is " << GameStateNames[m_state] << endl; // qCDebug(KSIRK_LOG) << " saved state is " << GameStateNames[m_savedState] << endl; if (isAdmin() && int(playerList()->count()) == maxPlayers() && gameStatus()!=KGame::Run) { // m_game->haltTimer(); if (m_state == INIT && m_savedState == INVALID) { firstCountriesDistribution(); if (useGoals()) { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << (*it)->id(); sendMessage(buffer,SetGoalFor); } } } else if (m_state == WAIT_PLAYERS) { sendCountries(); qCDebug(KSIRK_LOG) << "at " << __FILE__ << ", line " << __LINE__ << ", setting state to " << m_savedState << endl; state(m_savedState); currentPlayer(playerNamed(m_savedPlayer)); m_game->displayButtonsForState(m_savedState); m_savedPlayer = ""; m_savedState = INVALID; } qCDebug(KSIRK_LOG) << "Sending message FinalizePlayers" << endl; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,FinalizePlayers); qCDebug(KSIRK_LOG) << "Setting game status to Run" << endl; setGameStatus(KGame::Run); // m_game->initTimer(); // qCDebug(KSIRK_LOG) << " true" << endl; return true; } else { // qCDebug(KSIRK_LOG) << " false" << endl; return false; } } void GameAutomaton::changePlayerName(Player* player) { // qCDebug(KSIRK_LOG); QMap< QString, QString > nations = m_game->nationsList(); PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { QMap::iterator nationsIt; nationsIt = nations.find(((Player*)(*it))-> getNation()->name()); if (nationsIt != nations.end()) { nations.erase(nationsIt); } } // Players names QString mes = ""; QString nationName; QString nomEntre = player->name(); bool found = true; KMessageBox::information(m_game, i18n("Please choose another name"), i18n("KsirK - Name already used!")); while(found) { bool emptyName = true; while (emptyName) { mes = i18n("Player number %1, what's your name?", 1); QString password; if (nomEntre.isEmpty()) { mes = i18n("Error - Player %1, you have to choose a name.", 1); KMessageBox::sorry(m_game, mes, i18n("Error")); nomEntre = i18nc("@info Forged player name", "Player%1", 1); } else { emptyName = false; } } found = false; PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( (*it)-> name() == nomEntre) { found = true; it = it_end; } } if (!found) { // qCDebug(KSIRK_LOG) << "Creating player " << nomEntre << "(computer: " << computer << "): " << nationName << endl; player->setName(nomEntre); } } QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,StartGame); } void GameAutomaton::changePlayerNation(Player* player) { // qCDebug(KSIRK_LOG) << endl; QMap< QString, QString > nations = m_game->nationsList(); PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { QMap::iterator nationsIt; nationsIt = nations.find(((Player*)(*it))-> getNation()->name()); if (nationsIt != nations.end()) { nations.erase(nationsIt); } } // Players names QString mes = ""; QString nationName; QString nomEntre = player->name(); KMessageBox::information(m_game, i18n("Please choose another nation"), i18n("KsirK - Nation already used!")); QString password; QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << player->name() << nationName; sendMessage(buffer,SetNation); QByteArray buffer2; QDataStream stream2(&buffer2, QIODevice::WriteOnly); sendMessage(buffer2,StartGame); } quint32 GameAutomaton::idForMsg(const QString& msg) { QMap::iterator it = m_msgs2ids.find(msg); if (it != m_msgs2ids.end()) { return (*it); } else { quint32 id = m_msgs2ids.size(); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << msg << id; sendMessage(buffer,AddMsgIdPair); return id; } } QString& GameAutomaton::msgForId(quint32 id) { return m_ids2msgs[id]; } void GameAutomaton::slotPropertyChanged(KGamePropertyBase *prop,KGame *) { qCDebug(KSIRK_LOG) << prop->id() << " (skin is " << m_skinId << ")" << endl; if (prop->id() == m_skinId) { qCDebug(KSIRK_LOG) << "skin changed to: " << m_skin << endl; m_game->newSkin(); if (m_game->theWorld()!=0) { m_game->theWorld()->reset(); } } qCDebug(KSIRK_LOG) << "END GameAutomaton::slotPropertyChanged " << prop->id() << " (skin is " << m_skinId << ")" << endl; } void GameAutomaton::slotClientJoinedGame(quint32 clientid, KGame* /*me*/) { qCDebug(KSIRK_LOG) << clientid; if (isAdmin() && clientid!=gameId()) { QByteArray buffernbp; QDataStream streamnbp(&buffernbp, QIODevice::WriteOnly); streamnbp << m_nbPlayers; sendMessage(buffernbp,NbPlayers,clientid); QByteArray bufferngs; QDataStream streamngs(&bufferngs, QIODevice::WriteOnly); streamngs << *m_game->newGameSetup(); sendMessage(bufferngs,NewGameSetupMsg,clientid); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); if (m_game->waitedPlayers().empty()) { sendMessage(buffer,SetupOnePlayer,clientid); } else { stream << quint32(m_game->waitedPlayers().size()); QList::iterator it, it_end; it = m_game->waitedPlayers().begin(); it_end = m_game->waitedPlayers().end(); for (; it != it_end; it++) { stream << (*it); } sendMessage(buffer,SetupWaitedPlayer,clientid); } } } void GameAutomaton::slotConnectionToServerBroken() { qCDebug(KSIRK_LOG); // m_game->haltTimer(); if (m_state != GAME_OVER) { int answer = KMessageBox::questionYesNoCancel(m_game, i18n("KsirK - Lost connection to server!\nWhat do you want to do?"), i18n("Starting a new game or exit."), KGuiItem(i18n("New Game")), KGuiItem(i18n("Exit")), KGuiItem(i18n("Do nothing"))); if (answer == KMessageBox::Yes) { m_game->showMainMenu(); } else if (answer == KMessageBox::No) { exit(0); } else { } } } void GameAutomaton::slotConnectionToClientBroken(KMessageIO *) { qCDebug(KSIRK_LOG) << endl; // m_game->haltTimer(); if (m_state != GAME_OVER) { KMessageBox::information(m_game, i18n("Lost connection to a client.\nFor the moment, you can only save the game and start a new one or quit.\nThis will be improved in a future version."), i18n("KsirK - Lost connection to client!")); switch ( KMessageBox::warningYesNo( m_game, i18n("Do want to save your game?")) ) { case KMessageBox::Yes : m_game->slotSaveGame(); break; case KMessageBox::No :; default: ; } if (!m_game->actionNewGame(GameAutomaton::None)) exit(1); } // else // { // m_game->haltTimer(); // } } void GameAutomaton::finalizePlayers() { qCDebug(KSIRK_LOG); PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { dynamic_cast(*it)-> finalize(); } QByteArray buffer; if (isAdmin()) { sendMessage(buffer,DisplayGoals); } m_game->showMap(); m_startingGame = false; } /** @return true if all players are played by computer ; false otherwise */ bool GameAutomaton::allComputerPlayers() { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( ! dynamic_cast(*it)-> isAI() ) { return false; } } return true; } bool GameAutomaton::allLocalPlayersComputer() { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( ( ! dynamic_cast(*it)-> isVirtual() ) && ( ! dynamic_cast(*it)-> isAI() ) ) { return false; } } return true; } void GameAutomaton::firstCountriesDistribution() { qCDebug(KSIRK_LOG) << endl; if (isAdmin()) { PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { ((Player*)(*it))->setNbAvailArmies((unsigned int)(m_game->theWorld()->getNbCountries() * 2.5 / nbPlayers() ), true); } m_game->setCurrentPlayerToFirst(); qCDebug(KSIRK_LOG) << "Setup players: distributing countries" << endl; countriesDistribution(); // qCDebug(KSIRK_LOG) << " KGameWindow::setupPlayers: before initTimer" << endl; // m_game->initTimer(); m_game->setCurrentPlayerToFirst(); if ( currentPlayer()-> isAI() && (!currentPlayer()->isVirtual()) ) if ( ! ( dynamic_cast(currentPlayer())-> isRunning()) ) dynamic_cast(currentPlayer())-> start(); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << currentPlayer()->name(); // stream << (quint32)m_game->availArmies(); stream << (quint32)currentPlayer()->getNbAvailArmies(); qCDebug(KSIRK_LOG) << "sending DisplayRecycleDetails " << currentPlayer()->name() << (quint32)currentPlayer()->getNbAvailArmies() << " at " << __FILE__ << ", line " << __LINE__; // qCDebug(KSIRK_LOG) << "sending DisplayRecycleDetails " << currentPlayer()->name() << m_game->availArmies() // << " at " << __FILE__ << ", line " << __LINE__; sendMessage(buffer,DisplayRecycleDetails); // qCDebug(KSIRK_LOG) << "OUT KGameWindow::setupPlayers" << endl; } } void GameAutomaton::countriesDistribution() { qCDebug(KSIRK_LOG); unsigned int initialNbArmies; QList< int > vect; QMap distributedCountriesNumberMap; PlayersArray::iterator it = playerList()->begin(); initialNbArmies = ((Player*)(*playerList()->begin()))->getNbAvailArmies(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { distributedCountriesNumberMap[(*it)-> name()] = 0; } // creates a vector containing the numbers of the countries for (unsigned int i = 0; i < m_game->theWorld()->getNbCountries() ; i++) vect.push_back(i); // do while the vector not empty (will distribute one country each turn and // remove its number from the vector) while (vect.size()) { // chooses randomly a position in the remaining countries vector int h = Dice::roll(vect.size()) - 1; // moves an iterator up to the position chosen QList< int >::iterator it = vect.begin(); for (int itPos = 0; itPos < h-1; itPos++) it++; // affect the country that have the number at this position QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << (m_game->theWorld()->getCountries().at(*it)->name()) << currentPlayer()-> name(); qCDebug(KSIRK_LOG) << (m_game->theWorld()->getCountries().at(*it)->name()) << currentPlayer()-> name(); distributedCountriesNumberMap[currentPlayer()-> name()] = distributedCountriesNumberMap[currentPlayer()-> name()]+1; sendMessage(buffer,CountryOwner); //m_game->theWorld()->getCountries().at(*it)-> owner(currentPlayer()); m_game->setCurrentPlayerToNext(false); // removes the chosen country number from the vector, thus reducing its size vect.erase(it); } it = playerList()->begin(); it_end = playerList()->end(); for (; it != it_end; it++) { ((GameLogic::Player*)(*it))->setNbAvailArmies(((GameLogic::Player*)(*it))->getNbAvailArmies() - distributedCountriesNumberMap[(*it)-> name()], true); ((GameLogic::Player*)(*it))->incrNbCountries(distributedCountriesNumberMap[(*it)-> name()]); } // qCDebug(KSIRK_LOG) << "All countries are now distributed." << endl; m_game->setCurrentPlayerToFirst(); QString nextPlayerName = currentPlayer()->name(); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << (quint32)((GameLogic::Player*)(currentPlayer()))->getNbAvailArmies(); // qCDebug(KSIRK_LOG) << " Setting status " << nextPlayerName << " / " << m_game->availArmies() << endl; QPixmap pm = playerNamed(nextPlayerName)->getFlag()->image(0); KMessageParts messageParts; messageParts << pm << I18N_NOOP("%1: %2 armies to place") << nextPlayerName << QString::number( initialNbArmies - distributedCountriesNumberMap[nextPlayerName]); qCDebug(KSIRK_LOG) << "Message parts size= " << messageParts.size() << endl; m_game->broadcastChangeItem(messageParts, ID_STATUS_MSG2); m_game->showMessage(i18n("Now, place your armies in your countries
by clicking in the target countries.")); state(INTERLUDE); m_game->setNextPlayerActionEnabled(false); } void GameAutomaton::sendCountries() { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); m_game->theWorld()->sendCountries(stream); sendMessage(buffer,SetupCountries); } void GameAutomaton::movingFigthersArrived() { qCDebug(KSIRK_LOG) << endl; state(FIGHT_ANIMATE); QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); sendMessage(buffer,AnimCombat); } void GameAutomaton::movingArmiesArrived() { qCDebug(KSIRK_LOG) << endl; // m_game->terminateAttackSequence(); } void GameAutomaton::movingArmyArrived(Country* country, unsigned int number) { qCDebug(KSIRK_LOG) << number << endl; country->incrNbArmies(number); country->createArmiesSprites(); checkGoal(country->owner()); } void GameAutomaton::firingFinished() { qCDebug(KSIRK_LOG) << endl; if (isAdmin()) { m_game->resolveAttack(); state(EXPLOSION_ANIMATE); } } void GameAutomaton::explosionFinished() { qCDebug(KSIRK_LOG) << endl; if (isAdmin()) { switch (gameStatus()) { case KGame::Pause: m_game->setStateBeforeNewGame(FIGHT_BRINGBACK); break; case KGame::Run:; default: state(FIGHT_BRINGBACK); } } } void GameAutomaton::displayGoals() { qCDebug(KSIRK_LOG) << endl; PlayersArray::iterator it = playerList()->begin(); PlayersArray::iterator it_end = playerList()->end(); for (; it != it_end; it++) { if ( (dynamic_cast(*it) != 0) && ( ! dynamic_cast(*it)-> isVirtual() ) && ( ! dynamic_cast(*it)-> isAI() ) ) { KMessageBox::information( game(), i18n("%1, your goal will be displayed. Please
" "make sure that no other player can see it!",(*it)->name()), i18n("KsirK - Displaying Goal")); dynamic_cast(*it)->goal().show(); } } m_aicannotrunhack = false; } void GameAutomaton::moveSlide() { qCDebug(KSIRK_LOG); if (!currentPlayer()->isVirtual()) m_game->slideInvade(m_game->firstCountry(), m_game->secondCountry(),InvasionSlider::Moving); } /** * Change the automatic attack state. * @param activated new state */ void GameAutomaton::setAttackAuto(bool activated) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << (quint32)activated; sendMessage(buffer,AttackAuto); } void GameAutomaton::slotNetworkData(int msgid, const QByteArray &buffer, quint32 receiver, quint32 sender) { qCDebug(KSIRK_LOG) << "msg " << msgid << " ; rec="<(&buffer), QIODevice::ReadOnly); QString countryName, playerName, nationName; QPointF point; quint32 removable; quint32 theState; quint32 nbArmies; quint32 newState; quint32 statusBarId, messagePartsNb, messagePartsCounter, logStatus; quint32 propId, prop2Id; quint32 playerId; quint32 nbVotes = 0; quint32 explosing; KMessageParts messageParts; QString messagePart; Player* player; PlayerMatrix waitedPlayerDef(this); quint32 nbWaitedPlayers; quint32 waitedPlayerId; QString waitedPlayerPassword; quint32 nbCountries; Country* country; quint32 msgId; QString ack; QString msg; Goal goal(this); QString playersNames; QPixmap pm; quint32 A1, A2, A3, D1, D2, NKA, NKD; quint32 win; quint32 attackAutoValue; quint32 availArmies; quint32 elemType; quint32 nb; if (currentPlayer() != 0 && currentPlayer()->getFlag() != 0) { pm = currentPlayer()->getFlag()->image(0); } QByteArray sendBuffer; QDataStream sendStream(&sendBuffer, QIODevice::WriteOnly); switch (msgid) { case CountryOwner: stream >> countryName >> playerName; qCDebug(KSIRK_LOG) << "CountryOwner for " << (void*)m_game->theWorld()->countryNamed(countryName) << " " << countryName << " and " << (void*)playerNamed(playerName) << playerName << endl; m_game->theWorld()->countryNamed(countryName)-> owner(playerNamed(playerName)); break; case PlayerPutsInitialArmy: stream >> point; if (m_game->playerPutsInitialArmy(point)) { if (isAdmin()) gameEvent("playersLooped", point); } break; case PlayerPutsArmy: stream >> point >> removable; if (m_game->playerPutsArmy(point, removable) && isAdmin()) { gameEvent("playersLooped", point); } break; case StateChange: stream >> theState; qCDebug(KSIRK_LOG) << "Got new state id: " << theState << " ("<> playerName; if (!isAdmin()) { m_currentPlayer = playerName; m_currentPlayerPlayed = false; } break; case RegisterCountry: stream >> countryName >> propId >> prop2Id; m_nbArmiesIdsNamesCountriesMap.insert(int(propId),countryName); m_namesNbArmiesIdsCountriesMap.insert(countryName,int(propId));; // m_nbAddedArmiesIdsNamesCountriesMap.insert(int(prop2Id),countryName); // m_namesNbAddedArmiesIdsCountriesMap.insert(countryName,int(prop2Id)); break; case PlayerAvailArmies: if (sender == gameId()) break; stream >> playerName >> nbArmies; if (playerNamed(playerName) != 0) playerNamed(playerName)->setNbAvailArmies((unsigned int)nbArmies, false); break; /* case KGameWinAvailArmies: if (sender == gameId()) break; stream >> nbArmies; m_game->availArmies(nbArmies);*/ break; case ChangeItem: if (sender == gameId()) break; stream >> statusBarId >> logStatus >> messagePartsNb; qCDebug(KSIRK_LOG) << "Got ChangeItem on " << statusBarId << " ; nb= " << messagePartsNb << endl; for (messagePartsCounter = 0; messagePartsCounter < messagePartsNb; messagePartsCounter++) { stream >> elemType; if (elemType == KMessageParts::Text) { stream >> messagePart; messageParts << messagePart; qCDebug(KSIRK_LOG) << " message part: " << messagePart << endl; } else if (elemType == KMessageParts::StringId) { stream >> msgId; messageParts << msgForId(msgId); qCDebug(KSIRK_LOG) << " message part for id "<> pm; messageParts << pm; } } m_game->changeItem(messageParts,statusBarId, logStatus); break; case DisplayRecyclingButtons: m_game->getRightDialog()->updateRecycleDetails(0,true,0); m_game->displayRecyclingButtons(); break; case ClearHighlighting: m_game->clearHighlighting(); break; case ActionRecycling: if (isAdmin()) { m_game->actionRecycling(); state(NEWARMIES); } break; case ClearGameActionsToolbar: break; case DisplayDefenseButtons: stream >> playerName; if ( (!playerNamed(playerName)->isVirtual()) && (!playerNamed(playerName)->isAI()) && (!isDefenseAuto())) { defCountry = this->game()->secondCountry(); m_game->displayDefenseWindow(); } messageParts << I18N_NOOP("%1 chooses its defense") << playerName; m_game->broadcastChangeItem(messageParts, ID_STATUS_MSG2); break; case ActionDefense: stream >> nbArmies; if (isAdmin()) m_game->defense((unsigned int)nbArmies); break; case FirstCountry: stream >> countryName; qCDebug(KSIRK_LOG) << "FirstCountry " << countryName << endl; m_game->firstCountry(m_game->theWorld()->countryNamed(countryName)); break; case SecondCountry: stream >> countryName; qCDebug(KSIRK_LOG) << "SecondCountry " << countryName << endl; m_game->secondCountry(m_game->theWorld()->countryNamed(countryName)); break; case InitCombatMovement: m_game->initCombatMovement(); break; case AnimCombat: m_game->animCombat(); break; case TerminateAttackSequence: { // update country display if (m_game->terminateAttackSequence()) { // Re-display the world view m_game->showMap(); setAttackAuto(false); // setDefenseAuto(false); if(!currentPlayer()->isAI() && !currentPlayer()->isVirtual()) { m_game->slideInvade(m_game->firstCountry(), m_game->secondCountry()); } if (isAdmin()) { state(INVADE); } } else if (isAdmin()) { // if there is more than 1 army on my country and automatic // attack is activated if (m_game->firstCountry()->nbArmies() > 1 && m_attackAuto) { // continue automatically attacking by making the same attack state(WAIT1); if (m_game->firstCountry()->nbArmies() > 3) { gameEvent("actionAttack3", m_game->secondCountry()->centralPoint()); } else if (m_game->firstCountry()->nbArmies() > 2) { gameEvent("actionAttack2", m_game->secondCountry()->centralPoint()); } else { gameEvent("actionAttack1", m_game->secondCountry()->centralPoint()); } // else wait user choice } else { // Re-display the world view m_game->showMap(); setAttackAuto(false); // setDefenseAuto(false); state(WAIT); } } m_game->firstCountry()-> createArmiesSprites(); m_game->secondCountry()-> createArmiesSprites(); } break; case DecrNbArmies: stream >> countryName >> nbArmies; m_game->theWorld()->countryNamed(countryName)->decrNbArmies(nbArmies); + Q_FALLTHROUGH(); case StartLocalCurrentAI: m_game->startLocalCurrentAI(); break; case Invade: stream >> nbArmies; nb = nbArmies; while (nb >= 10) { if (m_game-> invade(10)) m_game-> incrNbMovedArmies(10); nb -= 10; } while (nb >= 5) { if (m_game-> invade(5)) m_game-> incrNbMovedArmies(5); nb -= 5; } while (nb > 0) { if (m_game-> invade(1)) m_game-> incrNbMovedArmies(1); nb--; } break; case Retreat: stream >> nbArmies; if (m_game-> retreat(nbArmies)) m_game-> decrNbMovedArmies(nbArmies); break; case NextPlayerNormal: if (isAdmin()) { stream >> playerName; stream >> newState; if (playerName == currentPlayer()->name() && m_game->nextPlayerNormal()) { if (newState > 0) { qCDebug(KSIRK_LOG) << "at " << __FILE__ << ", line " << __LINE__ << ", setting state to " << newState << endl; state(GameState(newState)); } } } break; case NextPlayerRecycling: if (isAdmin()) { stream >> newState; if (m_game->nextPlayerRecycling()) { m_choosedToRecycleNumber = 0; if (newState > 0) { qCDebug(KSIRK_LOG) << "at " << __FILE__ << ", line " << __LINE__ << ", setting state to " << newState << endl; state(GameState(newState)); m_game->slotContextualHelp(); } } } break; case ShowArmiesToPlace: messageParts << pm << I18N_NOOP("%1: %2 armies to place") << (currentPlayer()-> name()) << QString::number(currentPlayer()-> getNbAvailArmies()); m_game->broadcastChangeItem(messageParts, ID_STATUS_MSG2); m_game->showMessage(i18n("Now, place your armies in your countries
by clicking in the target countries.")); break; case PlayerRemovesArmy: stream >> point; m_game->playerRemovesArmy(point); break; case VoteRecyclingFinished: if (isAdmin()) { // stream >> playerName; messageParts << I18N_NOOP("%1 choose to end recycling; there are now %2 players who want so"); stream >> nbVotes; stream >> playerId; playersNames = ((Player*)(findPlayer(playerId)))->name(); if (!m_choosedToRecycle.contains(playerId)) { m_choosedToRecycle.push_back(playerId); } else { nbVotes--; } for (quint32 i = 1 ; i < nbVotes; i++) { stream >> playerId; playersNames += QString(", ") + ((Player*)(findPlayer(playerId)))->name(); if (!m_choosedToRecycle.contains(playerId)) { m_choosedToRecycle.push_back(playerId); } else { nbVotes--; } } qCDebug(KSIRK_LOG) << "VoteRecyclingFinished nb before: " << m_choosedToRecycleNumber << endl; m_choosedToRecycleNumber+=nbVotes; qCDebug(KSIRK_LOG) << "VoteRecyclingFinished nb after : " << m_choosedToRecycleNumber << endl; messageParts << playersNames << QString::number(m_choosedToRecycleNumber); m_game->broadcastChangeItem(messageParts, ID_NO_STATUS_MSG); if (m_choosedToRecycleNumber == (unsigned int)(playerList()->count())) { m_game->actionRecyclingFinished(); m_choosedToRecycle.clear(); } } break; case CancelShiftSource: m_game-> cancelShiftSource(); if (isAdmin()) { state(SHIFT1); } break; case ChangePlayerNation: stream >> playerId; // qCDebug(KSIRK_LOG) << "Got ChangePlayerNation for player id " << playerId << endl; player = (Player*)(findPlayer(playerId)); // qCDebug(KSIRK_LOG) << "Found player id " << player; if (player && !player->isVirtual()) { changePlayerNation(player); } break; case ChangePlayerName: stream >> playerId; player = (Player*)(findPlayer(playerId)); if (player && !player->isVirtual()) { changePlayerName(player); } break; case StartGame: if (isAdmin()) startGame(); break; case SetNation: stream >> playerName >> nationName; playerNamed(playerName)->setNation(nationName); break; case SetBarFlagButton: stream >> playerName; qCDebug(KSIRK_LOG) << "Calling setBarFlagButton for player " << playerNamed(playerName) << " named " << playerName << endl; m_game->setBarFlagButton(playerNamed(playerName)); break; case FinishMoves: m_game->finishMoves(); break; case AnimExplosion: stream >> explosing; qCDebug(KSIRK_LOG) << "AnimExplosion" << explosing; if (m_game->backGnd()->bgIsArena()) { m_game->animExplosionForArena(); } else { if (explosing != 0 && explosing != 1 && explosing != 2) { KMessageBox::information(m_game, i18n("Problem : no one destroyed"), i18n("Ksirk - Error!")); } else { m_game->animExplosion(explosing); } } break; case SetupOnePlayer: if (receiver == gameId()) { m_game->setupOnePlayer(); } break; case SetupWaitedPlayer: stream >> nbWaitedPlayers; for (quint32 i = 0; i < nbWaitedPlayers; i++) { stream >> waitedPlayerDef; m_game->waitedPlayers().push_back(waitedPlayerDef); } m_game->setupOneWaitedPlayer(); break; case ValidateWaitedPlayerPassword: if (isAdmin()) { stream >> waitedPlayerId >> waitedPlayerPassword; // qCDebug(KSIRK_LOG) << "Validating password for waited player " << waitedPlayerId << " : " << m_game->waitedPlayers()[waitedPlayerId].password << " / " << waitedPlayerPassword << endl; if (m_game->waitedPlayers()[waitedPlayerId].password == waitedPlayerPassword) { sendStream << waitedPlayerId; sendMessage(sendBuffer,ValidPassword, sender); } else { sendMessage(sendBuffer,InvalidPassword, sender); } } break; case ValidPassword: if (receiver == gameId()) { stream >> waitedPlayerId; m_game->createWaitedPlayer(waitedPlayerId); } break; case InvalidPassword: if (receiver == gameId()) { KMessageBox::information(m_game, i18n("You entered an invalid password.\nPlease try again."), i18n("KsirK - Invalid password!")); m_game->setupOneWaitedPlayer(); } break; case SetupCountries: stream >> nbCountries; for (unsigned int i = 0; i < nbCountries; i++) { stream >> countryName; country = m_game->theWorld()->countryNamed(countryName); qCDebug(KSIRK_LOG) << "Setting up country n°" << i << " on " << nbCountries << ", " << (void*)country << " named " << countryName << endl; if (country) { stream >> country; } } break; case AddMsgIdPair: stream >> msg >> msgId; m_msgs2ids.insert(msg,msgId); m_ids2msgs.insert(msgId,msg); break; case CheckGoal: if (isAdmin()) { qCDebug(KSIRK_LOG) << "CheckGoal: " << endl; stream >> playerId; player = dynamic_cast< Player* >(findPlayer(playerId)); if (player) { if (player->checkGoal()) { qCDebug(KSIRK_LOG) << " goal reached for " << player->name() << endl; qCDebug(KSIRK_LOG) << " setting state to " << GameStateNames[GAME_OVER] << endl; // m_game->haltTimer(); setGameStatus(KGame::End); state(GAME_OVER); sendStream << player->id(); qCDebug(KSIRK_LOG) << " sending Winner" << endl; sendMessage(sendBuffer,Winner); } } } break; case SetGoalFor: if (isAdmin()) { stream >> playerId; setGoalFor(dynamic_cast(findPlayer(playerId))); } break; case GoalForIs: qCDebug(KSIRK_LOG) << "GoalForIs: " << endl; stream >> playerId; qCDebug(KSIRK_LOG) << " player id: " << playerId << endl; stream >> goal; player = dynamic_cast(findPlayer(playerId)); if (player != 0) { player->goal(goal); } break; case FinalizePlayers: qCDebug(KSIRK_LOG) << "Got message FinalizePlayers" << endl; finalizePlayers(); break; case Winner: QObject::disconnect(messageServer(),&KMessageServer::connectionLost, this,&GameAutomaton::slotConnectionToClientBroken); stream >> playerId; m_game->winner(dynamic_cast(findPlayer(playerId))); break; case NbPlayers: stream >> m_nbPlayers; break; case Acknowledge: stream >> playerId; stream >> ack; if (!isAdmin() && !dynamic_cast(findPlayer(playerId))->isVirtual()) { qCDebug(KSIRK_LOG) << "Got message Acknowledge" << playerId << ack; dynamic_cast(findPlayer(playerId))->acknowledge(ack); } break; case DisplayGoals: qCDebug(KSIRK_LOG) << "Got message DisplayGoals" << endl; QTimer::singleShot(0,this,&GameAutomaton::displayGoals); break; case DisplayFightResult: qCDebug(KSIRK_LOG) << "Got message DisplayFightResult" << endl; stream >> A1 >> A2 >> A3 >> D1 >> D2 >> NKA >> NKD >> win; m_game->getRightDialog()->displayFightResult(A1,A2,A3,D1,D2,NKA,NKD,win); break; case MoveSlide: qCDebug(KSIRK_LOG) << "Got message MoveSlide"; moveSlide(); break; case InvasionFinished: qCDebug(KSIRK_LOG) << "Got message InvasionFinished"; if (isAdmin()) { gameEvent("actionInvasionFinished", point); } break; case AttackAuto: qCDebug(KSIRK_LOG) << "Got message AttackAuto"; stream >> attackAutoValue; m_attackAuto = attackAutoValue; break; case DisplayRecycleDetails: stream >> playerName; stream >> availArmies; qCDebug(KSIRK_LOG) << "Got message DisplayRecycleDetails " << playerName << availArmies; m_game->getRightDialog()->displayRecycleDetails(playerNamed(playerName),availArmies); // bool value; // if (playerNamed(playerName)->isAI() || playerNamed(playerName)->isVirtual()) // { // value = false; // } // else // { // value = true; // } m_game->setNextPlayerActionEnabled(false); break; case CurrentPlayerPlayed: m_currentPlayerPlayed = true; break; case ResetPlayersDistributionData: resetPlayersDistributionData(); break; case NewGameSetupMsg: qCDebug(KSIRK_LOG) << "Got message NewGameSetupMsg"; stream >> *m_game->newGameSetup(); break; default: ; } } void GameAutomaton::askForJabberGames() { m_game->askForJabberGames(); } QSvgRenderer& GameAutomaton::rendererFor(const QString& skinName) { if (!m_renderers.contains(skinName)) { m_renderers.insert(skinName,new QSvgRenderer(this)); } return *m_renderers[skinName]; } KGameSvgDocument& GameAutomaton::svgDomFor(const QString& skinName) { if (!m_svgDoms.contains(skinName)) { m_svgDoms.insert(skinName,KGameSvgDocument()); } return m_svgDoms[skinName]; } bool GameAutomaton::startingGame() const { qCDebug(KSIRK_LOG) << m_startingGame; return m_startingGame; } bool GameAutomaton::isDefenseAuto() { return m_defenseAuto.isDefenseAuto(m_game->firstCountry(),m_game->secondCountry()); } void GameAutomaton::setDefenseAuto(bool activated) { m_defenseAuto.value = activated; if (activated) { m_defenseAuto.firstCountry = m_game->firstCountry(); m_defenseAuto.secondCountry= m_game->secondCountry(); } else { m_defenseAuto.firstCountry = 0; m_defenseAuto.secondCountry= 0; } } void GameAutomaton::resetPlayersDistributionData() { foreach (KPlayer* p, *playerList()) { if ( !p->isVirtual() ) { ((GameLogic::Player*)p)->reset(); } } } void GameAutomaton::actionNextPlayer() { if ( currentPlayer()->isVirtual() || currentPlayer()->isAI() || m_currentPlayerPlayed || (KMessageBox::questionYesNo (m_game, i18n("%1, you have not played anything this turn.\nDo you really want to lose your turn?",m_currentPlayer), i18n("Really Next Player?")) == KMessageBox::Yes) ) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); stream << currentPlayer()->name(); stream << (quint32)NEWARMIES; qCDebug(KSIRK_LOG) << "(state " << stateName() << ") sending NextPlayerNormal" << currentPlayer()->name() << NEWARMIES; sendMessage(buffer,NextPlayerNormal); m_game-> cancelAction(); } } void GameAutomaton::removeAllPlayers() { qCDebug(KSIRK_LOG); m_currentPlayer = ""; /* Bug 304362. KPlayer destructor removes * player from the list and makes iterators invalid. * qDeleteAll crashes in that case. */ while (!playerList()->isEmpty()) { delete playerList()->takeFirst(); } // qDeleteAll(*playerList()); // playerList()->clear(); } // Bug 308527. void GameAutomaton::removeAllGoals() { qCDebug(KSIRK_LOG); while (!goals().isEmpty()) delete goals().takeFirst(); } void GameAutomaton::newGameNext() { qCDebug(KSIRK_LOG); m_startingGame = true; state(INIT); qCDebug(KSIRK_LOG) << "Changing skin"; m_skin = m_game->newGameSetup()->skin(); if (m_game->newGameSetup()->networkGameType() == Socket) { offerConnections(m_game->newGameSetup()->tcpPort()); } m_game->finishSetupPlayers(); } void GameAutomaton::checkGoal(Player* player) { QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); if (player == 0) stream << currentPlayer()->id(); else stream << player->id(); qCDebug(KSIRK_LOG) << "sending CheckGoal"; sendMessage(buffer,CheckGoal); } } // closing namespace GameLogic } // closing namespace Ksirk diff --git a/ksirk/GameLogic/goal.h b/ksirk/GameLogic/goal.h index 50d1935..f5e6cbc 100644 --- a/ksirk/GameLogic/goal.h +++ b/ksirk/GameLogic/goal.h @@ -1,184 +1,184 @@ /* This file is part of KsirK. Copyright (C) 2005-2007 Gael de Chalendar KsirK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef KSIRK_GAMELOGICGOAL_H #define KSIRK_GAMELOGICGOAL_H // #include #include #include namespace Ksirk { namespace GameLogic { class GameAutomaton; class Player; /** * This is a representation of a goal to be reached by a player. * * A goal can be a combination of a number of countries to conquier, some * continents to conquier entirely or some players to eliminate. * @author Gael de Chalendar */ class Goal { public: /** * The different kind of goals */ enum GoalType { NoGoal, /**< The goal is to conquer all the world. */ GoalPlayer, /**< The goal is to eliminate one player. */ Countries, /**< The goal is to conquier a given number of countries. */ Continents /**< The goal is to conquier a few continents. */ }; /** * The different kind of goal displaying */ enum DisplayType { GoalDesc = 1, /**< The description of the goal is displayed. */ GoalAdvance = 2 /**< The advance step. */ }; Goal(GameAutomaton* automaton); /** Copy constructor */ Goal(const Goal& goal); /** Default destructor */ ~Goal(); - + //@{ /** Accessors for the goal type */ inline GoalType type() const {return m_type;} inline GoalType type() {return m_type;} inline void type(GoalType type) {m_type = type;} //@} //@{ /** Accessors for the goal description */ inline const QString& description() const {return m_description;} inline QString& description() {return m_description;} inline void description(const QString& desc) {m_description = desc;} //@} //@{ /** Accessors for the number of countries to conquier to reach this goal */ inline unsigned int nbCountries() const {return m_nbCountries;} inline unsigned int nbCountries() {return m_nbCountries;} inline void nbCountries(unsigned int nb) {m_nbCountries = nb;} //@} //@{ /** Accessors for the minimal number of armies to put on each country to * reach this goal */ inline unsigned int nbArmiesByCountry() const {return m_nbArmiesByCountry;} inline unsigned int nbArmiesByCountry() {return m_nbArmiesByCountry;} inline void nbArmiesByCountry(unsigned int nb) {m_nbArmiesByCountry = nb;} //@} //@{ /** Accessors for the list of continents to conquier to reach this goal */ inline QList& continents() {return m_continents;} inline const QList& continents() const {return m_continents;} //@} //@{ /** Accessors for the list of players to eliminate to reach this goal */ inline QList& players() {return m_players;} inline const QList& players() const {return m_players;} //@} //@{ /** Accessors for the player concerned by this goal */ inline const Player* player() const {return m_player;} inline Player* player() {return m_player;} inline void player(Player* p) {m_player = p;} //@} /** * Test if this goal is reached for the given player * @param player The player to test this goal for * @return true if this goal is reached for the given player ; false otherwise. */ bool checkFor(const Player* player) const; /** * Test if countries conditions of this goal are reached for the given player * @param player The player to test this goal countries conditions for * @return true if the countries conditions of this goal are reached for the * given player ; false otherwise. */ bool checkCountriesFor(const Player* player) const; /** * Test if continents conditions of this goal are reached for the given player * @param player The player to test this goal continents conditions for * @return true if the continents conditions of this goal are reached for the * given player ; false otherwise. */ bool checkContinentsFor(const Player* player) const; /** * Displays this goal in a message dialog * @param displayType the manner to display this goal: final goal or advance. */ void show(int displayType = GoalDesc); /** * Saves a XML representation of the goal for game saving purpose * @param xmlStream The stream to write on */ void saveXml(QTextStream& xmlStream) const; /** * Builds this goal's description. * @param displayType the manner to display this goal: final goal (default) or advance. * @return a string containing this goal's description. */ QString message(int displayType = GoalDesc) const; GameAutomaton* m_automaton; private: /** Default constructor */ Goal(); GoalType m_type; QString m_description; unsigned int m_nbCountries; unsigned int m_nbArmiesByCountry; QList m_continents; QList m_players; Player* m_player; }; QDataStream& operator<<(QDataStream& stream, const Goal& goal); QDataStream& operator>>(QDataStream& stream, Goal& goal); } } #endif diff --git a/ksirk/GameLogic/onu.cpp b/ksirk/GameLogic/onu.cpp index bd254db..9fb2809 100644 --- a/ksirk/GameLogic/onu.cpp +++ b/ksirk/GameLogic/onu.cpp @@ -1,751 +1,751 @@ /*************************************************************************** onu.cpp - description ------------------- begin : Wed Jul 18 2001 copyright : (C) 2001-2006 by Gael de Chalendar (aka Kleag) email : kleag@free.fr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either either version 2 of the License, or (at your option) any later version.of the License, or * * (at your option) any later version. * * * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA ***************************************************************************/ #include "onu.h" #include "Sprites/skinSpritesData.h" #include "goal.h" #include "gameautomaton.h" #include "kgamewin.h" #define KDE_NO_COMPAT #include #include #include #include #include #include #include #include #include "ksirk_debug.h" #include #include #include namespace Ksirk { namespace GameLogic { ONU::ONU(GameAutomaton* automaton, const QString& configFileName): QObject(automaton), m_automaton(automaton), m_configFileName(configFileName), countries(), nationalities(), m_continents(), m_skin(), m_zoom(1.0), m_zoomArena(1.0), m_nbZooms(0), m_zoomFactorFinal(1) { qCDebug(KSIRK_LOG) << "ONU constructor: " << m_configFileName; QFileInfo qfi(m_configFileName); qCDebug(KSIRK_LOG) << "skin written at :" << qfi.lastModified().toSecsSinceEpoch(); //qCDebug(KSIRK_LOG) << "cache created at:" << m_automaton->pixmapCache().timestamp(); #pragma message("port to qt5") #if 0 if (m_automaton->pixmapCache().timestamp() < qfi.lastModified().toSecsSinceEpoch()) { m_automaton->pixmapCache().discard(); } #endif m_font.family = "URW Chancery L"; - m_font.size = (uint)(13*m_zoom); + m_font.size = (int)(13*m_zoom); m_font.weight = QFont::Bold; m_font.italic = true; m_font.foregroundColor = "black"; m_font.backgroundColor = "white"; m_timerFast=new QTimer(this); //instanciation of the timer QObject::connect(m_timerFast,&QTimer::timeout, this, &ONU::changingZoom); //connect the timer to the good slot Sprites::SkinSpritesData::changeable().init(); // unsigned int nationalityId = 0; // unsigned int continentId = 0; KConfig config(configFileName); KConfigGroup onugroup = config.group("onu"); qCDebug(KSIRK_LOG) << "ONU XML format version: " << onugroup.readEntry("format-version"); QString formatVersion = onugroup.readEntry("format-version"); if (formatVersion != ONU_FILE_FORMAT_VERSION) { qCCritical(KSIRK_LOG) << "Error - Invalid skin definition file format. Expected "<" + m_configFileName, // i18n("Fatal Error")); return; } m_name = onugroup.readEntry("name"); m_skin = onugroup.readEntry("skinpath"); qCDebug(KSIRK_LOG) << "skin snapshot file: " << QStandardPaths::locate(QStandardPaths::AppDataLocation, m_skin + "/Images/snapshot.jpg"); if (!QPixmapCache::find(m_skin+"snapshot", &m_snapshot)) { // Pixmap isn't in the cache, create it and insert to cache m_snapshot = QPixmap(QStandardPaths::locate(QStandardPaths::AppDataLocation, m_skin + "/Images/snapshot.jpg")); if (m_snapshot.isNull()) { qCCritical(KSIRK_LOG) << "Was not able to load the snapshot image: " << QStandardPaths::locate(QStandardPaths::AppDataLocation, m_skin + "/Images/snapshot.jpg") << endl; } QPixmapCache::insert(m_skin+"snapshot", m_snapshot); } m_width = onugroup.readEntry("width",0); m_height = onugroup.readEntry("height",0); m_description = onugroup.readEntry("desc"); // countries.resize(onugroup.readEntry("nb-countries",0)); // nationalities.resize(onugroup.readEntry("nb-nationalities",0)); // m_continents.resize(onugroup.readEntry("nb-continents",0)); // root.attribute("map"); QString poolString = onugroup.readEntry("pool"); qCDebug(KSIRK_LOG) << "Pool path: " << poolString; qCDebug(KSIRK_LOG) << "Searching resource: " << (m_skin + '/' + poolString); QString poolFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, m_skin + '/' + poolString); qCDebug(KSIRK_LOG) << "Pool file name: " << poolFileName; if (poolFileName.isEmpty()) { KMessageBox::error(0, i18n("Pool filename not found\nProgram cannot continue"), i18n("Error!")); exit(2); } m_map = QPixmap(); qCDebug(KSIRK_LOG) << m_skin << "before pool loading"; if (!m_automaton->rendererFor(m_skin).isValid()) m_automaton->rendererFor(m_skin).load(poolFileName); if (m_automaton->svgDomFor(m_skin).svgFilename().isNull()) m_automaton->svgDomFor(m_skin).load(poolFileName); qCDebug(KSIRK_LOG) << m_skin << "after pool loading"; QString mapMaskFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, m_skin + '/' + onugroup.readEntry("map-mask")); qCDebug(KSIRK_LOG) << "Map mask file name: " << mapMaskFileName; if (mapMaskFileName.isNull()) { KMessageBox::error(0, i18n("Map mask image not found\nProgram cannot continue"), i18n("Error!")); exit(2); } qCDebug(KSIRK_LOG) << "Loading map mask file: " << mapMaskFileName; QPixmap countriesMaskPix; if (!QPixmapCache::find(m_skin+"mapmask", &countriesMaskPix)) { // Pixmap isn't in the cache, create it and insert to cache countriesMaskPix = QPixmap(mapMaskFileName); if (countriesMaskPix.isNull()) { qCCritical(KSIRK_LOG) << "Was not able to load the map mask image: " << mapMaskFileName << endl; } QPixmapCache::insert(m_skin+"mapmask", countriesMaskPix); } // countriesMask = QImage(mapMaskFileName); countriesMask = countriesMaskPix.toImage(); Sprites::SkinSpritesData::changeable().intData("width-between-flag-and-fighter", onugroup.readEntry("width-between-flag-and-fighter",0)); Sprites::SkinSpritesData::changeable().intData("flag-width", config.group("flag").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("flag-height", config.group("flag").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("flag-frames", config.group("flag").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("flag-versions", config.group("flag").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("infantry-id", config.group("infantry").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("infantry-width", config.group("infantry").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("infantry-height", config.group("infantry").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("infantry-frames", config.group("infantry").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("infantry-versions", config.group("infantry").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("infantry1-id", config.group("infantry1").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("infantry1-width", config.group("infantry1").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("infantry1-height", config.group("infantry1").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("infantry1-frames", config.group("infantry1").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("infantry1-versions", config.group("infantry1").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("infantry2-id", config.group("infantry2").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("infantry2-width", config.group("infantry2").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("infantry2-height", config.group("infantry2").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("infantry2-frames", config.group("infantry2").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("infantry2-versions", config.group("infantry2").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("infantry3-id", config.group("infantry3").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("infantry3-width", config.group("infantry3").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("infantry3-height", config.group("infantry3").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("infantry3-frames", config.group("infantry3").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("infantry3-versions", config.group("infantry3").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("cavalry-id", config.group("cavalry").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("cavalry-width", config.group("cavalry").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("cavalry-height", config.group("cavalry").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("cavalry-frames", config.group("cavalry").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("cavalry-versions", config.group("cavalry").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("cannon-id", config.group("cannon").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("cannon-width", config.group("cannon").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("cannon-height", config.group("cannon").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("cannon-frames", config.group("cannon").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("cannon-versions", config.group("cannon").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("firing-id", config.group("firing").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("firing-width", config.group("firing").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("firing-height", config.group("firing").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("firing-frames", config.group("firing").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("firing-versions", config.group("firing").readEntry("versions",0)); // Sprites::SkinSpritesData::changeable().strData("exploding-id", config.group("exploding").readEntry("id")); Sprites::SkinSpritesData::changeable().intData("exploding-width", config.group("exploding").readEntry("width",0)); Sprites::SkinSpritesData::changeable().intData("exploding-height", config.group("cannon").readEntry("height",0)); Sprites::SkinSpritesData::changeable().intData("exploding-frames", config.group("exploding").readEntry("frames",0)); Sprites::SkinSpritesData::changeable().intData("exploding-versions", config.group("exploding").readEntry("versions",0)); KConfigGroup fontgroup = config.group("font"); m_font.family = fontgroup.readEntry("family","URW Chancery L"); - m_font.size = fontgroup.readEntry("size",(uint)(13*m_zoom)); + m_font.size = fontgroup.readEntry("size",(int)(13*m_zoom)); QString w = fontgroup.readEntry("weight", "bold");; if (w == "normal") { m_font.weight = QFont::Normal; } else if (w == "light") { m_font.weight = QFont::Light; } else if (w == "demibold") { m_font.weight = QFont::DemiBold; } else if (w == "bold") { m_font.weight = QFont::Bold; } else if (w == "black") { m_font.weight = QFont::Black; } m_font.italic = fontgroup.readEntry("italic", true); m_font.foregroundColor = fontgroup.readEntry("foreground-color", "black"); m_font.backgroundColor = fontgroup.readEntry("background-color", "white"); QStringList countriesList = onugroup.readEntry("countries", QStringList()); foreach (const QString &country, countriesList) { KConfigGroup countryGroup = config.group(country); // unsigned int id = countryGroup.readEntry("id",0); QString name = country; QPointF anchorPoint = countryGroup.readEntry("anchor-point",QPointF())*m_zoom; QPointF centralPoint = countryGroup.readEntry("central-point",QPointF())*m_zoom; QPointF flagPoint = countryGroup.readEntry("flag-point",QPointF())*m_zoom; QPointF cannonPoint = countryGroup.readEntry("cannon-point",QPointF())*m_zoom; QPointF cavalryPoint = countryGroup.readEntry("cavalry-point",QPointF())*m_zoom; QPointF infantryPoint = countryGroup.readEntry("infantry-point",QPointF())*m_zoom; // qCDebug(KSIRK_LOG) << "Creating country " << name; // qCDebug(KSIRK_LOG) << "\tflag point: " << flagPoint; // qCDebug(KSIRK_LOG) << "\tcentral point: " << centralPoint; // qCDebug(KSIRK_LOG) << "\tcannon point: " << cannonPoint; // qCDebug(KSIRK_LOG) << "\tcavalry point: " << cavalryPoint; // qCDebug(KSIRK_LOG) << "\tinfantry point: " << infantryPoint; countries.push_back(new Country(automaton, name, anchorPoint, centralPoint, flagPoint, cannonPoint, cavalryPoint, infantryPoint)); } QStringList nationalitiesList = onugroup.readEntry("nationalities", QStringList()); foreach (const QString &nationality, nationalitiesList) { // qCDebug(KSIRK_LOG) << "Creating nationality " << nationality; KConfigGroup nationalityGroup = config.group(nationality); QString leader = nationalityGroup.readEntry("leader",""); QString flag = nationalityGroup.readEntry("flag",""); // qCDebug(KSIRK_LOG) << "Creating nationality " << name << " ; flag: " << flag; nationalities.push_back(new Nationality(nationality, flag, leader)); // nationalityId++; } QStringList continentsList = onugroup.readEntry("continents", QStringList()); foreach (const QString &continent, continentsList) { KConfigGroup continentGroup = config.group(continent); // unsigned int id = continentGroup.readEntry("id",0); unsigned int bonus = continentGroup.readEntry("bonus",0); QList countryIdList = continentGroup.readEntry("continent-countries",QList()); // int countryId; QList continentList; foreach(const QString& countryId, countryIdList) { // qCDebug(KSIRK_LOG) << "Adding" << countryId << "to" << continent << "list"; Country *c = countryNamed(countryId); if (c) { continentList.push_back(c); } } // qCDebug(KSIRK_LOG) << "Creating continent " << name; m_continents.push_back(new Continent(continent, continentList, bonus)); } QStringList goalsList = onugroup.readEntry("goals", QStringList()); foreach (const QString &_goal, goalsList) { // qCDebug(KSIRK_LOG) << "init goal " << _goal; KConfigGroup goalGroup = config.group(_goal); Goal* goal = new Goal(automaton); goal->description(goalGroup.readEntry("desc","")); QString goalType = goalGroup.readEntry("type",""); if (goalType == "countries") { goal->type(Goal::Countries); goal->nbCountries(goalGroup.readEntry("nbCountries",0)); goal->nbArmiesByCountry(goalGroup.readEntry("nbArmiesByCountry",0)); // qCDebug(KSIRK_LOG) << " nb countries: **********************************" << goal->nbCountries(); // qCDebug(KSIRK_LOG) << " nbarmies countries: **********************************" << goal->nbArmiesByCountry(); } else if (goalType == "continents" ) { goal->type(Goal::Continents); QList contList = goalGroup.readEntry("continents",QList()); foreach(const QString& continentId, contList) { // Bug 308527. Use only known continents. if (continentsList.contains(continentId)) goal->continents().push_back(continentId); else { qCDebug(KSIRK_LOG) << "Unknown continent " << continentId << " in skin " << m_skin << endl; } } } else if (goalType == "player" ) { goal->type(Goal::GoalPlayer); unsigned int nb = goalGroup.readEntry("nbCountriesFallback",0); goal->nbCountries(nb); } automaton->goals().push_back(goal); } foreach (const QString &countryName, countriesList) { Country *country = countryNamed(countryName); if (!country) { continue; } // qCDebug(KSIRK_LOG) << "building neighbours list of " << countryName; QList< Country* > theNeighbours; KConfigGroup countryGroup = config.group(countryName); QList theNeighboursIds = countryGroup.readEntry("neighbours",QList()); // int neighbourId; foreach(const QString& neighbourId, theNeighboursIds) { Country *c = countryNamed(neighbourId); if (c) { theNeighbours.push_back(c); } } country-> neighbours(theNeighbours); } buildMap(); qCDebug(KSIRK_LOG) << "OUT"; } ONU::~ONU() { delete m_timerFast; QList::iterator countriesIt, countriesIt_end; countriesIt = countries.begin(); countriesIt_end = countries.end(); for (; countriesIt != countriesIt_end; countriesIt++) { delete *countriesIt; } QList::iterator nationalitiesIt, nationalitiesIt_end; nationalitiesIt = nationalities.begin(); nationalitiesIt_end = nationalities.end(); for (; nationalitiesIt != nationalitiesIt_end; nationalitiesIt++) { delete *nationalitiesIt; } QList::iterator continentsIt, continentsIt_end; continentsIt = m_continents.begin(); continentsIt_end = m_continents.end(); for (; continentsIt != continentsIt_end; continentsIt++) { delete *continentsIt; } } /** This method returns a pointer to the country that contains the point (x,y). If there is no country at (x,y), the functions returns 0. */ Country* ONU::countryAt(const QPointF& point) { // qCDebug(KSIRK_LOG) << "ONU::countryAt x y " << x << " " << y; QPointF norm = point; norm /= m_zoom; if ( norm.x() < 0 || norm.x() >= countriesMask.width() || norm.y() < 0 || norm.y() >= countriesMask.height() ) return 0; int index = qBlue(countriesMask.pixel(norm.toPoint())); // qCDebug(KSIRK_LOG) << "OUT ONU::countryAt: " << index; if (index >= countries.size()) return 0; return countries.at(index); } void ONU::reset() { qCDebug(KSIRK_LOG); foreach (Country* country, countries) { country-> reset(); } } QList& ONU::getCountries() { return countries; } QList& ONU::getNationalities() { return nationalities; } /** Read property of QList continents. */ const QList& ONU::getContinents() const { return m_continents; } QList& ONU::getContinents() { return m_continents; } /** * Returns the list of countries neighbours of this country that does not * belongs to the argument player. */ QList ONU::neighboursBelongingTo(const Country& country, const Player* player) { QList list; foreach (Country *c, country.neighbours()) { if ((country.communicateWith(c)) && (c-> owner() == player)) {list.push_back(c);} } return list; } /** * Returns the list of countries neighbours of this country that does not * belongs to the argument player. */ QList ONU::neighboursNotBelongingTo(const Country& country, const Player* player) { QList list; foreach (Country *c, country.neighbours()) { if ((country.communicateWith(c)) && (c-> owner() != player)) {list.push_back(c);} } return list; } /** * Returns the country named "name" ; 0 in case there is no such country */ Country* ONU::countryNamed(const QString& name) { if (name.isEmpty()) { // qCDebug(KSIRK_LOG) << "request for country with empty name"; return 0; } foreach (Country *c, countries) { if (c-> name() == name) return c; } // qCDebug(KSIRK_LOG) << "request for country" << name << "which doesn't seem to exist."; return 0; } /** @return the number of countries in the world */ unsigned int ONU::getNbCountries() const { return(countries.size()); } void ONU::saveXml(QTextStream& xmlStream) { xmlStream << "" << endl; xmlStream << "" << endl; foreach (Country *c, countries) { c->saveXml(xmlStream); } xmlStream << "" << endl; xmlStream << "" << endl; } unsigned int ONU::width() const { return m_width; } unsigned int ONU::height() const { return m_height; } /** Returns the nation named "name" ; 0 in case there is no such nation */ Nationality* ONU::nationNamed(const QString& name) { foreach (Nationality *n, nationalities) { if (n->name() == name) { return n; } } return 0; } void ONU::sendCountries(QDataStream& stream) { stream << quint32(countries.size()); foreach (Country* country, countries) { // qCDebug(KSIRK_LOG) << "Sending country " << country->name(); country->send(stream); } } /*const Continent* ONU::continentWithId(const unsigned int id) const { for (unsigned int i = 0; i < m_continents.size(); i++) { if ( m_continents.at(i)->id() == id) { return m_continents.at(i); } } return 0; } */ Continent* ONU::continentNamed(const QString& name) { foreach (Continent *c, m_continents) { if (c-> name() == name) return c; } return 0; } void ONU::buildMap() { qCDebug(KSIRK_LOG) << "with zoom="<< m_zoom; //QSize size((int)(m_automaton->rendererFor(m_skin).defaultSize().width()*m_zoom),(int)(m_automaton->rendererFor(m_skin).defaultSize().height()*m_zoom)); if (!QPixmapCache::find(m_skin+"map"+QString::number(m_width)+QString::number(m_height), &m_map)) { // Pixmap isn't in the cache, create it and insert to cache QSize size((int)(m_width),(int)(m_height)); QImage image(size, QImage::Format_ARGB32_Premultiplied); image.fill(0); QPainter p(&image); m_automaton->rendererFor(m_skin).render(&p, "map"); m_map = QPixmap::fromImage(image); QPainter painter(&m_map); QFont foregroundFont(m_font.family, m_font.size, m_font.weight, m_font.italic); QFont backgroundFont(m_font.family, m_font.size, QFont::Normal, m_font.italic); painter.drawPixmap(0,0,m_map); foreach (Country* country, countries) { const QString& countryName = i18n(country->name().toUtf8().data()); if (m_font.backgroundColor != "none") { painter.setPen(m_font.backgroundColor); painter.setFont(backgroundFont); QRect countryNameRect = painter.fontMetrics().boundingRect(countryName); painter.drawText( int( (country->centralPoint().x()*m_zoom) - (countryNameRect.width()/2) + 1 ), // HACK HACK see the same below int( (country->centralPoint().y()*m_zoom) + 4/*(countryNameRect.height()/2)*/ + 1 ), countryName); } painter.setPen(m_font.foregroundColor); painter.setFont(foregroundFont); QRect countryNameRect = painter.fontMetrics().boundingRect(countryName); // qCDebug(KSIRK_LOG) << countryName << "countryNameRect=" << countryNameRect; // qCDebug(KSIRK_LOG) << "draw at" << int( (country->centralPoint().x()*m_zoom) - (countryNameRect.width()/2) ) << // int( (country->centralPoint().y()*m_zoom) - (countryNameRect.height()/2) ); painter.drawText( int( (country->centralPoint().x()*m_zoom) - (countryNameRect.width()/2) ), // HACK HACK why is this 4 necessary below instead of the commented correction ??? int( (country->centralPoint().y()*m_zoom) + 4/*- (countryNameRect.height()/2)*/ ), countryName); } QPixmapCache::insert(m_skin+"map"+QString::number(m_width)+QString::number(m_height), m_map); } } void ONU::applyZoomFactor(qreal zoomFactor) { /** Zoom 1: First method (take a long time to zoom) : */ // qCDebug(KSIRK_LOG) << "zoomFactor=" << zoomFactor << "old zoom=" << m_zoom; // qCDebug(KSIRK_LOG) << "new zoom=" << m_zoom; m_zoom *= zoomFactor; - //m_font.size = (unsigned int)(m_font.size*m_zoom); + //m_font.size = (int)(m_font.size*m_zoom); //m_width = (unsigned int)(m_width *m_zoom); //m_height = (unsigned int)(m_height *m_zoom); buildMap(); foreach (Country* country, countries) { country->createArmiesSprites(); } } void ONU::applyZoomFactorFast(qreal zoomFactor) //benj { /** Zoom 2 : Second method , Very performent. Carefull ! Can cause the game to lag. To try this, comment all the first method and uncomment these lines */ qCDebug(KSIRK_LOG) << "zoomFactor FASTTTTTTT"< 1 && m_nbZooms < nbLimitZooms) { - m_font.size = (unsigned int)(m_font.size*zoomFactor); + m_font.size = (int)(m_font.size*zoomFactor); m_width = (unsigned int)(m_width *zoomFactor); m_height = (unsigned int)(m_height *zoomFactor); m_nbZooms++; // zoom forward m_automaton->game()->frame()->scale(zoomFactor, zoomFactor); m_zoomFactorFinal *= zoomFactor; //starting timer /*if (m_timerFast->isActive()) { m_timerFast->stop(); } m_timerFast->start(4000); m_timerFast->setSingleShot(true);*/ } else if (zoomFactor < 1 && m_nbZooms > -nbLimitZooms) { - m_font.size = (unsigned int)(m_font.size*zoomFactor); + m_font.size = (int)(m_font.size*zoomFactor); m_width = (unsigned int)(m_width *zoomFactor); m_height = (unsigned int)(m_height *zoomFactor); m_nbZooms--; // zoom backward m_automaton->game()->frame()->scale(zoomFactor, zoomFactor); m_zoomFactorFinal *= zoomFactor; //starting timer /*if (m_timerFast->isActive()) { m_timerFast->stop(); } m_timerFast->start(4000); m_timerFast->setSingleShot(true);*/ } } double ONU::zoom() const { if (m_automaton->game()->currentWidgetType() == KGameWindow::Map) { return m_zoom; } return m_zoomArena; } QSvgRenderer* ONU::renderer() { return &m_automaton->rendererFor(m_skin); } KGameSvgDocument* ONU::svgDom() { return &m_automaton->svgDomFor(m_skin); } unsigned int ONU::indexOfCountry(Country* c) const { return countries.indexOf(c); } /** the SLOTS METHODS FOR THE ONU CLASS*/ void ONU::changingZoom() { /* m_automaton->game()->frame()->resetTransform(); qreal m_zo=m_zoomFactorFinal; m_zoomFactorFinal=1; applyZoomFactor(m_zo);*/ // m_automaton->game()->frame()->scale(1/m_zoomFactorFinal, 1/m_zoomFactorFinal); m_automaton->game()->frame()->resetTransform(); applyZoomFactor(m_zoomFactorFinal); m_zoomFactorFinal=1.0; } /**END OF SLOTS METHODS FOR THE ONU*/ } // closing namespace GameLogic } // closing namespace Ksirk diff --git a/ksirk/GameLogic/onu.h b/ksirk/GameLogic/onu.h index 0f96ab3..b5206d8 100644 --- a/ksirk/GameLogic/onu.h +++ b/ksirk/GameLogic/onu.h @@ -1,334 +1,334 @@ /*************************************************************************** onu.h - description ------------------- begin : Wed Jul 18 2001 copyright : (C) 2001 by Gael de Chalendar email : Gael.de.Chalendar@free.fr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either either version 2 of the License, or (at your option) any later version.of the License, or * * (at your option) any later version. * * * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA ***************************************************************************/ #define KDE_NO_COMPAT #ifndef ONU_H #define ONU_H #define USE_UNSTABLE_LIBKDEGAMESPRIVATE_API #include #include #include #include #include #include #include #include "country.h" #include "continent.h" #include "nationality.h" #include "kgamewin.h" #include "gameautomaton.h" #include namespace Ksirk { namespace GameLogic { class Country; /** * Class ONU (Organisation des Nations Unies = UNO : United Nations * Organization) is simply the list of the countries. The data definining * each country is loaded from an XML configuration file located in the * current skin data directory */ class ONU: public QObject { Q_OBJECT public: /** * Constructor * @param configFileName The name of the XML file defining this world. Built * from the current skin dir and a default file name. */ ONU(GameAutomaton* automaton, const QString& configFileName); /** Default destructor */ ~ONU() override; /** Zoom methods: */ void applyZoomFactor(qreal zoomFactor); void applyZoomFactorFast(qreal zoomFactor); //benj //{@ /** * Accessors */ const QString& skin() const {return m_skin;} const QString& name() const {return m_name;} const QString& description() const {return m_description;} const QString& mapFileName() const; const QString& getConfigFileName() const {return m_configFileName;} const QPixmap& map() const {return m_map;} const QPixmap& snapshot() const {return m_snapshot;} unsigned int width() const; unsigned int height() const; //@} /** * This method returns a pointer to the country that contains the given * point. If there is no country there, the functions returns 0. * @param point The point where to search for a country in the map mask * @return The country at the given point or 0 if there is no country there. */ Country* countryAt(const QPointF& point); /** * Calls its reset method for each country */ void reset(); /** * Return the countries list */ QList& getCountries(); /** * Returns the nationalities list */ QList& getNationalities(); //@{ /** Read property of QList continents. */ QList& getContinents(); const QList& getContinents() const; //@} /** * Retrieves the continent with the given id * @param id The id of the continent to retrieve * @return A pointer to the retrieved continent or 0 if there is no * continent with the given id. */ // const Continent* continentWithId(const unsigned int id) const; /** * Returns the list of countries neighbours of the parameter country that * belongs to the argument player. * @param country The country whose neighbours have to be tested * @param player The countries that belong to this player will be retrieved * @return A vector of pointers on countries neighbour to the given country * and belonging to the given player. */ QList neighboursBelongingTo(const Country& country, const Player* player); /** Returns the list of countries neighbours of the parameter country that * does not belong to the argument player. * @param country The country whose neighbours have to be tested * @param player The countries that do not belong to this player will be * retrieved * @return A vector of pointers on countries neighbour to the given country * and not belonging to the given player. */ QList neighboursNotBelongingTo(const Country& country, const Player* player); /** * Returns the country named "name" ; 0 in case there is no such country. * @param name The name of the country to retrieve. * @return The country named name or 0 if there is no such country. */ Country* countryNamed(const QString& name); /** * Gets the number of countries in the world * @return The number of countries in the world */ unsigned int getNbCountries() const; unsigned int indexOfCountry(Country*) const; /** * Saves a XML representation of the world for game saving purpose * @param xmlStream The stream to write on */ void saveXml(QTextStream& xmlStream); /** * Returns the nation named "name" ; 0 in case there is no such nation * @param name The name of the nation to retrieve. * @return The nation named name or 0 if there is no such nation. */ Nationality* nationNamed(const QString& name); /** * Transmit countries data to all network clients of the game. Called once * during finalization of network game start. * @param stream The stream to write countries data on */ void sendCountries(QDataStream& stream); /** * Returns the continent named "name" ; 0 in case there is no such continent * @param name The name of the continent to retrieve. * @return The continent named name or 0 if there is no such continent. */ Continent* continentNamed(const QString& name); double zoom() const; QSvgRenderer* renderer(); KGameSvgDocument* svgDom(); inline const QImage& mask() const {return countriesMask;} inline void setZoomArena(double newZoom) {m_zoomArena = newZoom;} inline GameAutomaton* automaton() {return m_automaton;} private: /** * All data that have to be stored about the font to display countries names * in this world's skin */ struct FontDesc { QString family; - uint size; + int size; QFont::Weight weight; bool italic; QString foregroundColor; QString backgroundColor; }; GameAutomaton* m_automaton; /** * The name of the XML file containing the world's definition */ QString m_configFileName; /** * The displayable name of the skin */ QString m_name; /** * The displayable long description of the skin */ QString m_description; /** * The map used by this skin, built at the proper size from its SVG source * and decorated with countries names */ QPixmap m_map; /** * A snaphsot of a running game with this skin. Used at skin choice time. */ QPixmap m_snapshot; //@{ /** * The width and height of the map file (will be used as canvas size). These * measures do not take into account the zoom factor. */ unsigned int m_width; unsigned int m_height; //@} /** * The list of countries */ QList countries; /** * The list of nationalities */ QList nationalities; /** * The continents of the world */ QList m_continents; /** * This image stores the mask that defines the countries of the world. * The blue RGB component value of each pixel gives the index of the * country in the countries list. */ QImage countriesMask; /** * The path to the skin ; relative to the ksirk data dir ; loaded from the * XML file */ QString m_skin; /** * The description of the font used to draw countries names onto the map. */ FontDesc m_font; /** * Zoom factor */ double m_zoom; /** * Zoom arena factor */ double m_zoomArena; /** * Counter to know how many zooms have been asked by user */ int m_nbZooms; /** * Zoom used to change size of map */ qreal m_zoomFactorFinal; /** * Timer for the ZoomfactorFast */ QTimer * m_timerFast; /** * This SVG renderer stores the SVG file of the map, renders it at the * desired zoom factor and the result is used to build the map image. */ // QSvgRenderer m_renderer; // KGameSvgDocument m_svgDom; /** * Build the map from it's stored image and the countries names */ void buildMap(); /** SLOTS */ public Q_SLOTS: void changingZoom(); }; } } #endif // ONU_H diff --git a/ksirk/krightdialog.cpp b/ksirk/krightdialog.cpp index f7b7aed..68a3b60 100644 --- a/ksirk/krightdialog.cpp +++ b/ksirk/krightdialog.cpp @@ -1,627 +1,627 @@ /* This file is part of KsirK. Copyright (C) 2008 Gael Clouet KsirK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /* begin : Thu JAN 22 2008 */ #include "krightdialog.h" #include "GameLogic/country.h" #include "GameLogic/player.h" #include "Sprites/animsprite.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Ksirk { using namespace GameLogic; KRightDialog::KRightDialog(QDockWidget * parent, ONU * world,KGameWindow* m_game) : QWidget(parent), mainLayout(new QGridLayout(this)), m_parentWidget(parent), world(world), rightContents(), flag1(0), flag2(0), milieu(0), milieu2(0), btRecycleWidget(0), btValidWidget(0), game(m_game), buttonStopAttack(0), buttonStopDefense(0) { setLayout(mainLayout); // setBaseSize(220,360); // load the armie image KConfig config(world->getConfigFileName()); KConfigGroup onugroup = config.group("onu"); QString skin = onugroup.readEntry("skinpath"); InfantrySprite *sprite = new InfantrySprite(1.0, m_game->backGnd()); sprite-> setDestination(0); // Sprite immobile soldat = sprite->image(0).scaled(24,24,Qt::KeepAspectRatioByExpanding); delete sprite; // load the stopAttackAuto image QString imageFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, skin + "/Images/stopAttackAuto.png"); stopAttackAuto.load(imageFileName); // load the recycle image imageFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, skin + '/' +CM_RECYCLING); recycleContinue.load(imageFileName); // load the finish recycle image imageFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, skin + '/' + CM_RECYCLINGFINISHED); recycleDone.load(imageFileName); // load the next player image imageFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, skin + '/' + CM_NEXTPLAYER); recycleNextPlayer.load(imageFileName); show(); } KRightDialog::~KRightDialog() { delete mainLayout; } void KRightDialog::displayCountryDetails(const QPointF& countryPoint) { qCDebug(KSIRK_LOG); Country* country = world->countryAt(countryPoint); if (country == 0) { return; } clearLayout(); QHBoxLayout * unit = new QHBoxLayout(); QHBoxLayout * drap = new QHBoxLayout(); flag1 = new QLabel(); flag2 = new QLabel(); initListLabel(7); QPixmap picture; picture = country->owner()->getFlag()->image(0); QString continent = i18n(country->continent()->name().toUtf8().data()); QString pays = i18n(country->name().toUtf8().data()); QString units = QString::number(country->nbArmies()); QString owner = country->owner()->name(); rightContents.at(0)->setText(i18n("Nationality:")); rightContents.at(1)->setText(i18n("Continent: %1", continent)); rightContents.at(2)->setText(i18n("Country: %1", pays)); rightContents.at(3)->setPixmap(soldat); rightContents.at(6)->setText(units); rightContents.at(4)->setText(i18n("Owner: %1", owner)); rightContents.at(5)->setText(i18n("Country details")); flag1->setPixmap(QPixmap()); flag2->setPixmap(QPixmap()); flag1->setPixmap(picture); drap->addWidget(rightContents.at(0)); drap->addWidget(flag1); mainLayout->addWidget(rightContents.at(5),0,0,Qt::AlignLeft); mainLayout->addWidget(rightContents.at(1),2,0,Qt::AlignLeft); mainLayout->addWidget(rightContents.at(2),3,0,Qt::AlignLeft); mainLayout->addWidget(rightContents.at(4),5,0,Qt::AlignLeft); unit->addWidget(rightContents.at(3)); unit->addWidget(rightContents.at(6)); mainLayout->addLayout(unit,4,0,Qt::AlignLeft); mainLayout->addLayout(drap,1,0,Qt::AlignLeft); m_parentWidget->show(); repaint(); } void KRightDialog::displayFightDetails(Country * attaker, Country * defender,int nb_A, int nb_D) { qCDebug(KSIRK_LOG); clearLayout(); initListLabel(10); haut = new QWidget(); bas = new QWidget(); QGridLayout * hautGrid = new QGridLayout(this); QGridLayout * basGrid = new QGridLayout(this); flag1 = new QLabel(); flag2 = new QLabel(); QHBoxLayout * box1 = new QHBoxLayout(); QHBoxLayout * box2 = new QHBoxLayout(); QHBoxLayout * box3 = new QHBoxLayout(); QHBoxLayout * box4 = new QHBoxLayout(); QGridLayout * tp = new QGridLayout(); infoProcess = new QLabel(); infoProcess->setWordWrap(true); infoProcess->setText(i18n("Fighting in progress...")); loadingLabel = new QLabel(); QLabel *l3 = new QLabel(); QLabel *l4 = new QLabel(); KConfig config(world->getConfigFileName()); KConfigGroup onugroup = config.group("onu"); QString skin = onugroup.readEntry("skinpath"); QString imageFileName = QStandardPaths::locate(QStandardPaths::AppDataLocation, skin + "/Images/loader.gif"); QMovie * loading = new QMovie(imageFileName); loadingLabel->setMovie(loading); loading->start(); tp->addWidget(l3,0,0); tp->addWidget(infoProcess,1,0,Qt::AlignCenter); tp->addWidget(loadingLabel,2,0,Qt::AlignCenter); tp->addWidget(l4,3,0); milieu2 = new QWidget(this); milieu2->setAutoFillBackground(true); QPalette tempP(milieu2->palette()); tempP.setColor(QPalette::Window,QColor(190,190,190)); milieu2->setPalette(tempP); milieu2->setLayout(tp); haut->setLayout(hautGrid); bas->setLayout(basGrid); //ATTACKER QString owner_A = attaker->owner()->name(); QString nb_units_A = QString::number(attaker->nbArmies()); QString pays_A = attaker->name(); QString owner_D = defender->owner()->name(); QString nb_units_D = QString::number(defender->nbArmies()); QString pays_D = defender->name(); QPixmap picture1; QPixmap picture2; picture1 = attaker->owner()->getFlag()->image(0); picture2 = defender->owner()->getFlag()->image(0); rightContents.at(0)->setText(""+i18n(pays_A.toUtf8().data())+""); flag1->setPixmap(picture1); rightContents.at(1)->setText("("+owner_A+") "); if (!soldat.isNull()) rightContents.at(2)->setPixmap(soldat); rightContents.at(3)->setText(""+nb_units_A+""); rightContents.at(4)->setText(i18np("Attack with 1 army.
","Attack with %1 armies.
", nb_A)); rightContents.at(5)->setText(""+i18n(pays_D.toUtf8().data())+" "); flag2->setPixmap(picture2); rightContents.at(6)->setText("("+owner_D+") "); if (!soldat.isNull()) rightContents.at(7)->setPixmap(soldat); rightContents.at(8)->setText(""+nb_units_D+" "); rightContents.at(9)->setText(i18np("Defend with 1 army.
","Defend with %1 armies.
", nb_D)); box1->addWidget(rightContents.at(0)); box1->addWidget(flag1); box2->addWidget(rightContents.at(2)); box2->addWidget(rightContents.at(3)); box3->addWidget(rightContents.at(5)); box3->addWidget(flag2); box4->addWidget(rightContents.at(7)); box4->addWidget(rightContents.at(8)); hautGrid->addLayout(box1,0,0,Qt::AlignCenter); hautGrid->addWidget(rightContents.at(1),1,0,Qt::AlignCenter); hautGrid->addLayout(box2,2,0,Qt::AlignLeft); hautGrid->addWidget(rightContents.at(4),3,0,Qt::AlignLeft); basGrid->addLayout(box3,0,0,Qt::AlignCenter); basGrid->addWidget(rightContents.at(6),1,0,Qt::AlignCenter); basGrid->addLayout(box4,2,0,Qt::AlignLeft); basGrid->addWidget(rightContents.at(9),3,0,Qt::AlignLeft); mainLayout->addWidget(haut,0,0); mainLayout->addWidget(milieu2,1,0); mainLayout->addWidget(bas,2,0); if (game->automaton()->isAttackAuto() && !game->automaton()->currentPlayer()->isAI() && !game->automaton()->currentPlayer()->isVirtual()) { buttonStopAttack = new QPushButton(stopAttackAuto,i18n("Stop Auto-Attack")); mainLayout->addWidget(buttonStopAttack,3,0); connect(buttonStopAttack, &QAbstractButton::clicked, this, &KRightDialog::slotStopAttackAuto); } if (game->automaton()->isDefenseAuto() && !game->automaton()->currentPlayer()->isAI() && !game->automaton()->currentPlayer()->isVirtual()) { buttonStopDefense = new QPushButton(stopAttackAuto,i18n("Stop Auto-Defense")); mainLayout->addWidget(buttonStopDefense,4,0); connect(buttonStopDefense, &QAbstractButton::clicked, this, &KRightDialog::slotStopDefenseAuto); } mainLayout->update(); m_parentWidget->show(); repaint(); } void KRightDialog::displayRecycleDetails(GameLogic::Player * player, int nbAvailArmies) { qCDebug(KSIRK_LOG) << player->name() << nbAvailArmies; this->show(); clearLayout(); initListLabel(4); flag1 = new QLabel(); flag2 = new QLabel(); QGridLayout* recycleLayout = new QGridLayout(); QGridLayout* btRecycleLayout = new QGridLayout(); QGridLayout* btValidLayout = new QGridLayout(); QPushButton* buttonValid = new QPushButton(recycleNextPlayer, i18n("Valid"), this); QPushButton* buttonRecycle = new QPushButton(recycleContinue, i18n("Recycle"), this); QPushButton* buttonRecycleDone = new QPushButton(recycleDone, i18n("Done"), this); connect(buttonValid, &QAbstractButton::clicked, game, &KGameWindow::slotNextPlayer); connect(buttonRecycle, &QAbstractButton::clicked, game, &KGameWindow::slotRecycling); connect(buttonRecycleDone, &QAbstractButton::clicked, game, &KGameWindow::slotRecyclingFinished); QHBoxLayout* title = new QHBoxLayout(); haut = new QWidget(); // Widgets which contains buttons btRecycleWidget = new QWidget(); btValidWidget = new QWidget(); btRecycleLayout->addWidget(buttonRecycle,0,0,Qt::AlignCenter); btRecycleLayout->addWidget(buttonRecycleDone,0,1,Qt::AlignCenter); btValidLayout->addWidget(buttonValid,0,0,Qt::AlignCenter); btRecycleWidget->setLayout(btRecycleLayout); btValidWidget->setLayout(btValidLayout); rightContents.at(0)->setText(""+player->name()+" "); flag1->setPixmap(player->getFlag()->image(0)); rightContents.at(1)->setText(i18np("%1 army to place", "%1 armies to place", nbAvailArmies)); title->addWidget(rightContents.at(0)); title->addWidget(flag1); recycleLayout->addLayout(title,0,0,Qt::AlignCenter); recycleLayout->addWidget(rightContents.at(1),1,0,Qt::AlignCenter); recycleLayout->addWidget(rightContents.at(2),2,0,Qt::AlignCenter); recycleLayout->addWidget(rightContents.at(3),3,0,Qt::AlignCenter); recycleLayout->addWidget(btRecycleWidget,4,0,Qt::AlignCenter); recycleLayout->addWidget(btValidWidget,5,0,Qt::AlignCenter); haut->setLayout(recycleLayout); mainLayout->addWidget(haut,0,0); // hide buttons initialy btRecycleWidget->hide(); if (nbAvailArmies > 0 || game->getState() == GameLogic::GameAutomaton::INTERLUDE || player->isVirtual() || player->isAI()) { btValidWidget->hide(); } else { btValidWidget->show(); } mainLayout->update(); m_parentWidget->show(); repaint(); } void KRightDialog::updateRecycleDetails(GameLogic::Country* country, bool recyclePhase, int nbAvailArmies) { qCDebug(KSIRK_LOG) << (void*)country << recyclePhase << nbAvailArmies; this->show(); if (btValidWidget == 0) { if (country == 0) { return; } displayRecycleDetails(country->owner(),nbAvailArmies); } if (recyclePhase) { rightContents.at(0)->setText(i18n("Change some
placements?
")); flag1->hide(); rightContents.at(1)->setText(QString()); rightContents.at(2)->setText(QString()); rightContents.at(3)->setText(QString()); // show "redistribute" and "end redistribute" buttons if (!game->automaton()->allLocalPlayersComputer()) { btRecycleWidget->show(); } btValidWidget->hide(); } else { rightContents.at(1)->setText(i18np("1 army to place", "%1 armies to place", nbAvailArmies)); rightContents.at(2)->setText(""+i18n(country->name().toUtf8().data())+""); rightContents.at(3)->setText(i18n("Armies: %1", country->nbArmies())); if (nbAvailArmies > 0) { btValidWidget->hide(); } else { if (!game->currentPlayer()->isVirtual() && !game->currentPlayer()->isAI()) { btValidWidget->show(); } } } qCDebug(KSIRK_LOG) << "before update and repaint"; mainLayout->update(); repaint(); } void KRightDialog::displayFightResult(int A1=0, int A2=0, int A3=0, int D1=0, int D2=0,int nbA=0,int nbD=0, bool win=false) { qCDebug(KSIRK_LOG); // Bug 309863. Should not happen anymore because Country details and Fight results shouldn't be mixed. // If, by any chance, occurs again, do not crash and log the incident. In that case label just won't be refreshed. if (loadingLabel != 0) { QMovie* movie = loadingLabel->movie(); delete movie; loadingLabel->clear(); } else qCDebug(KSIRK_LOG) << "Item (loadingLabel) has already been cleared!"; if (infoProcess != 0) infoProcess->clear(); else qCDebug(KSIRK_LOG) << "Item (infoProcess) has already been cleared!"; milieu = new QWidget(this); milieu->setAutoFillBackground(true); QPalette tempP(milieu->palette()); tempP.setColor(QPalette::Window,QColor(190,190,190)); milieu->setPalette(tempP); QGridLayout * milieuGrid = new QGridLayout(); QHBoxLayout * deAtt = new QHBoxLayout(); QHBoxLayout * deDef = new QHBoxLayout(); - if(A1!=0 || A1!=-1) + if(A1!=0 && A1!=-1) { QLabel * de1 = new QLabel(); de1->setPixmap(game->getDice(KGameWindow::Red,A1)); rightContents.insert(0,de1);deAtt->addWidget(de1); } - if(A2!=0 || A2!=-1) + if(A2!=0 && A2!=-1) { QLabel * de2= new QLabel(); de2->setPixmap(game->getDice(KGameWindow::Red,A2)); rightContents.insert(0,de2);deAtt->addWidget(de2); } - if(A3!=0 || A3!=-1) + if(A3!=0 && A3!=-1) { QLabel * de3= new QLabel(); de3->setPixmap(game->getDice(KGameWindow::Red,A3)); rightContents.insert(0,de3);deAtt->addWidget(de3); } - if(D1!=0 || D1!=-1) + if(D1!=0 && D1!=-1) { QLabel * de4= new QLabel(); de4->setPixmap(game->getDice(KGameWindow::Blue,D1)); rightContents.insert(0,de4);deDef->addWidget(de4); } - if(D2!=0 || D2!=-1) + if(D2!=0 && D2!=-1) { QLabel * de5= new QLabel(); de5->setPixmap(game->getDice(KGameWindow::Blue,D2)); rightContents.insert(0,de5);deDef->addWidget(de5); } QLabel * rLabelR = new QLabel(i18n("lost armies: %1", nbA)); rLabelR->setWordWrap(true); rightContents.insert(0,rLabelR); QLabel * rLabelB = new QLabel(i18n("lost armies: %1", nbD)); rLabelB->setWordWrap(true); rightContents.insert(0,rLabelB); milieuGrid->addWidget(rightContents.at(1),0,0,Qt::AlignCenter); milieuGrid->addLayout(deAtt,1,0,Qt::AlignCenter); milieuGrid->addLayout(deDef,2,0,Qt::AlignCenter); milieuGrid->addWidget(rightContents.at(0),4,0,Qt::AlignCenter); milieu->setLayout(milieuGrid); mainLayout->addWidget(milieu,1,0); if (buttonStopAttack != 0 && win) { buttonStopAttack->setEnabled(false); } repaint(); } void KRightDialog::initListLabel(int nb) { qCDebug(KSIRK_LOG); removeListLabel(); for (int i=0;isetWordWrap ( true ); rightContents.push_back(label); } clearLabel(); } void KRightDialog::removeListLabel() { qCDebug(KSIRK_LOG); while (rightContents.size() > 0) { QLabel* label = rightContents.first(); rightContents.removeFirst(); delete label; } } void KRightDialog::clearLabel() { qCDebug(KSIRK_LOG); for (int i=0;isetText(""); rightContents.at(i)->setPixmap(QPixmap()); } } void KRightDialog::clearLayout() { qCDebug(KSIRK_LOG); while (rightContents.size() > 0) { QLabel* obj = rightContents.first(); rightContents.removeFirst(); mainLayout->removeWidget(obj); delete obj; } if (flag1 != 0) { mainLayout->removeWidget(flag1); delete flag1; flag1 = 0; } if (flag2 != 0) { mainLayout->removeWidget(flag2); delete flag2; flag2 = 0; } if (btRecycleWidget != 0) { delete btRecycleWidget; btRecycleWidget = 0; } if (btValidWidget != 0) { delete btValidWidget; btValidWidget = 0; } if (buttonStopAttack != 0) { mainLayout->removeWidget(buttonStopAttack); delete buttonStopAttack; buttonStopAttack = 0; } if (buttonStopDefense != 0) { mainLayout->removeWidget(buttonStopDefense); delete buttonStopDefense; buttonStopDefense = 0; } if(bas != 0 && mainLayout->indexOf(bas)!=-1) { mainLayout->removeWidget(bas); delete bas; } if(milieu != 0) { mainLayout->removeWidget(milieu); delete milieu; milieu = 0; } if (milieu2 != 0) { mainLayout->removeWidget(milieu2); QMovie* movie = loadingLabel->movie(); loadingLabel->clear(); delete movie; delete loadingLabel; loadingLabel = 0; delete infoProcess; infoProcess = 0; delete milieu2; milieu2 = 0; } if(mainLayout->indexOf(haut)!=-1) { mainLayout->removeWidget(haut); delete haut; } } void KRightDialog::slotStopAttackAuto() { qCDebug(KSIRK_LOG); this->game->automaton()->setAttackAuto(false); this->buttonStopAttack->setEnabled(false); } void KRightDialog::slotStopDefenseAuto() { qCDebug(KSIRK_LOG); this->game->automaton()->setDefenseAuto(false); this->buttonStopDefense->setEnabled(false); } } diff --git a/ksirkskineditor/onu.cpp b/ksirkskineditor/onu.cpp index 47f1b4a..9fb6096 100644 --- a/ksirkskineditor/onu.cpp +++ b/ksirkskineditor/onu.cpp @@ -1,1018 +1,1018 @@ /*************************************************************************** onu.cpp - description ------------------- begin : Wed Jul 18 2001 copyright : (C) 2001-2006 by Gael de Chalendar (aka Kleag) email : kleag@free.fr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either either version 2 of the License, or (at your option) any later version.of the License, or * * (at your option) any later version. * * * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA ***************************************************************************/ #include "onu.h" #include "skinSpritesData.h" #include "goal.h" #include "../ksirk/KsirkGlobalDefinitions.h" #define KDE_NO_COMPAT #include // #include #include #include #include #include #include #include #include "ksirkskineditor_debug.h" #include #include #include namespace KsirkSkinEditor { ONU::ONU(const QString& configDir, QObject *parent) : QObject(parent), m_configDir(configDir), m_configFileName(configDir + "/Data/world.desktop"), m_countries(), m_nationalities(), m_continents(), m_renderer(), m_itemsMap(), m_dirty(false) { qCDebug(KSIRKSKINEDITOR_LOG) << "ONU constructor: " << m_configFileName; m_font.family = QStringLiteral("URW Chancery L"); - m_font.size = (uint)(13); + m_font.size = 13; m_font.weight = QFont::Bold; m_font.italic = true; m_font.foregroundColor = QStringLiteral("black"); m_font.backgroundColor = QStringLiteral("white"); SkinSpritesData::changeable().init(); // unsigned int nationalityId = 0; // unsigned int continentId = 0; KConfig config(m_configFileName); KConfigGroup onugroup = config.group("onu"); qCDebug(KSIRKSKINEDITOR_LOG) << "ONU XML format version: " << onugroup.readEntry("format-version"); QString formatVersion = onugroup.readEntry("format-version"); if (!formatVersion.isEmpty() && formatVersion != ONU_FILE_FORMAT_VERSION) { KMessageBox::error(0, i18n("Error - Invalid skin definition file format. Expected %1 and got %2",QStringLiteral(ONU_FILE_FORMAT_VERSION),formatVersion) + "
" + m_configFileName, i18n("Error")); // exit(1); } m_name = onugroup.readEntry("name"); m_skin = onugroup.readEntry("skinpath"); qCDebug(KSIRKSKINEDITOR_LOG) << "skin snapshot file: " << m_configDir + "/Images/snapshot.jpg"; m_snapshot = QString(m_configDir + "/Images/snapshot.jpg"); if (m_snapshot.isNull()) { qCCritical(KSIRKSKINEDITOR_LOG) << "Was not able to load the snapshot image: " << m_configDir + "/Images/snapshot.jpg"; } m_width = onugroup.readEntry("width",1024); m_height = onugroup.readEntry("height",768); m_description = onugroup.readEntry("desc"); // countries.resize(onugroup.readEntry("nb-countries",0)); // nationalities.resize(onugroup.readEntry("nb-nationalities",0)); // m_continents.resize(onugroup.readEntry("nb-continents",0)); // root.attribute("map"); m_poolString = onugroup.readEntry("pool"); if (m_poolString.isEmpty()) { m_poolString = QStringLiteral("Images/pool.svg"); } qCDebug(KSIRKSKINEDITOR_LOG) << "Pool path: " << m_poolString; qCDebug(KSIRKSKINEDITOR_LOG) << "Searching resource: " << (m_configDir + '/' + m_poolString); QString poolFileName = m_configDir + '/' + m_poolString; qCDebug(KSIRKSKINEDITOR_LOG) << "Pool file name: " << poolFileName; if (poolFileName.isEmpty()) { KMessageBox::error(0, i18n("Pool filename not found\nProgram cannot continue"), i18n("Error")); exit(2); } m_map = QPixmap(); m_renderer.load(poolFileName); m_svgDom.load(poolFileName); loadPoolIds(poolFileName); QString mapMaskFileName = m_configDir + '/' + onugroup.readEntry("map-mask"); qCDebug(KSIRKSKINEDITOR_LOG) << "Map mask file name init: " << mapMaskFileName; if (mapMaskFileName == (m_configDir + '/')) { mapMaskFileName = m_configDir + '/' + "Images/map-mask.png"; } qCDebug(KSIRKSKINEDITOR_LOG) << "Map mask file name: " << mapMaskFileName; if (mapMaskFileName.isNull()) { KMessageBox::error(0, i18n("Map mask image not found\nProgram cannot continue"), i18n("Error")); exit(2); } qCDebug(KSIRKSKINEDITOR_LOG) << "Loading map mask file: " << mapMaskFileName; m_countriesMask = QImage(mapMaskFileName); SkinSpritesData::changeable().intData(QStringLiteral("width-between-flag-and-fighter"), onugroup.readEntry("width-between-flag-and-fighter",0)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading flag data"; SkinSpritesData::changeable().intData(QStringLiteral("flag-width"), config.group("flag").readEntry("width",20)); SkinSpritesData::changeable().intData(QStringLiteral("flag-height"), config.group("flag").readEntry("height",20)); SkinSpritesData::changeable().intData(QStringLiteral("flag-frames"), config.group("flag").readEntry("frames",4)); SkinSpritesData::changeable().intData(QStringLiteral("flag-versions"), config.group("flag").readEntry("versions",1)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading infantry data"; // SkinSpritesData::changeable().strData("infantry-id", config.group("infantry").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("infantry-width"), config.group("infantry").readEntry("width",23)); SkinSpritesData::changeable().intData(QStringLiteral("infantry-height"), config.group("infantry").readEntry("height",32)); SkinSpritesData::changeable().intData(QStringLiteral("infantry-frames"), config.group("infantry").readEntry("frames",1)); SkinSpritesData::changeable().intData(QStringLiteral("infantry-versions"), config.group("infantry").readEntry("versions",3)); // SkinSpritesData::changeable().strData("infantry1-id", config.group("infantry1").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("infantry1-width"), config.group("infantry1").readEntry("width",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry1-height"), config.group("infantry1").readEntry("height",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry1-frames"), config.group("infantry1").readEntry("frames",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry1-versions"), config.group("infantry1").readEntry("versions",0)); // SkinSpritesData::changeable().strData("infantry2-id", config.group("infantry2").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("infantry2-width"), config.group("infantry2").readEntry("width",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry2-height"), config.group("infantry2").readEntry("height",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry2-frames"), config.group("infantry2").readEntry("frames",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry2-versions"), config.group("infantry2").readEntry("versions",0)); // SkinSpritesData::changeable().strData("infantry3-id", config.group("infantry3").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("infantry3-width"), config.group("infantry3").readEntry("width",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry3-height"), config.group("infantry3").readEntry("height",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry3-frames"), config.group("infantry3").readEntry("frames",0)); SkinSpritesData::changeable().intData(QStringLiteral("infantry3-versions"), config.group("infantry3").readEntry("versions",0)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading cavalry data"; // SkinSpritesData::changeable().strData("cavalry-id", config.group("cavalry").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("cavalry-width"), config.group("cavalry").readEntry("width",32)); SkinSpritesData::changeable().intData(QStringLiteral("cavalry-height"), config.group("cavalry").readEntry("height",32)); SkinSpritesData::changeable().intData(QStringLiteral("cavalry-frames"), config.group("cavalry").readEntry("frames",1)); SkinSpritesData::changeable().intData(QStringLiteral("cavalry-versions"), config.group("cavalry").readEntry("versions",3)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading cannon data"; // SkinSpritesData::changeable().strData("cannon-id", config.group("cannon").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("cannon-width"), config.group("cannon").readEntry("width",32)); SkinSpritesData::changeable().intData(QStringLiteral("cannon-height"), config.group("cannon").readEntry("height",32)); SkinSpritesData::changeable().intData(QStringLiteral("cannon-frames"), config.group("cannon").readEntry("frames",2)); SkinSpritesData::changeable().intData(QStringLiteral("cannon-versions"), config.group("cannon").readEntry("versions",3)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading firing data"; // SkinSpritesData::changeable().strData("firing-id", config.group("firing").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("firing-width"), config.group("firing").readEntry("width",64)); SkinSpritesData::changeable().intData(QStringLiteral("firing-height"), config.group("firing").readEntry("height",32)); SkinSpritesData::changeable().intData(QStringLiteral("firing-frames"), config.group("firing").readEntry("frames",4)); SkinSpritesData::changeable().intData(QStringLiteral("firing-versions"), config.group("firing").readEntry("versions",3)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading exploding data"; // SkinSpritesData::changeable().strData("exploding-id", config.group("exploding").readEntry("id")); SkinSpritesData::changeable().intData(QStringLiteral("exploding-width"), config.group("exploding").readEntry("width",32)); SkinSpritesData::changeable().intData(QStringLiteral("exploding-height"), config.group("cannon").readEntry("height",32)); SkinSpritesData::changeable().intData(QStringLiteral("exploding-frames"), config.group("exploding").readEntry("frames",4)); SkinSpritesData::changeable().intData(QStringLiteral("exploding-versions"), config.group("exploding").readEntry("versions",3)); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading font data"; KConfigGroup fontgroup = config.group("font"); m_font.family = fontgroup.readEntry("family","URW Chancery L"); - m_font.size = fontgroup.readEntry("size",(uint)(13)); + m_font.size = fontgroup.readEntry("size", 13); QString w = fontgroup.readEntry("weight", "bold");; if (w == QLatin1String("normal")) { m_font.weight = QFont::Normal; } else if (w == QLatin1String("light")) { m_font.weight = QFont::Light; } else if (w == QLatin1String("demibold")) { m_font.weight = QFont::DemiBold; } else if (w == QLatin1String("bold")) { m_font.weight = QFont::Bold; } else if (w == QLatin1String("black")) { m_font.weight = QFont::Black; } m_font.italic = fontgroup.readEntry("italic", true); m_font.foregroundColor = fontgroup.readEntry("foreground-color", "black"); m_font.backgroundColor = fontgroup.readEntry("background-color", "white"); qCDebug(KSIRKSKINEDITOR_LOG) << "Loading countries data"; QStringList countriesList = onugroup.readEntry("countries", QStringList()); /* while (m_countries.size() < countriesList.size()) { m_countries.push_back(0); }*/ foreach (const QString &country, countriesList) { qCDebug(KSIRKSKINEDITOR_LOG) << "Loading"< countryIdList = continentGroup.readEntry("continent-countries",QList()); // int countryId; QList continentList; foreach(const QString& countryId, countryIdList) { continentList.push_back(countryNamed(countryId)); } // qCDebug(KSIRKSKINEDITOR_LOG) << "Creating continent " << name; m_continents.push_back(new Continent(continent, continentList, bonus)); } qCDebug(KSIRKSKINEDITOR_LOG) << "Loading goals data"; QStringList goalsList = onugroup.readEntry("goals", QStringList()); foreach (const QString &_goal, goalsList) { qCDebug(KSIRKSKINEDITOR_LOG) << "init goal " << _goal; KConfigGroup goalGroup = config.group(_goal); Goal* goal = new Goal(); goal->setDescription(goalGroup.readEntry("desc","")); QString goalType = goalGroup.readEntry("type",""); if (goalType == QLatin1String("countries")) { goal->setType(Goal::Countries); goal->setNbCountries(goalGroup.readEntry("nbCountries",0)); goal->setNbArmiesByCountry(goalGroup.readEntry("nbArmiesByCountry",0)); qCDebug(KSIRKSKINEDITOR_LOG) << " nb countries: **********************************" << goal->nbCountries(); qCDebug(KSIRKSKINEDITOR_LOG) << " nbarmies countries: **********************************" << goal->nbArmiesByCountry(); } else if (goalType == QLatin1String("continents") ) { goal->setType(Goal::Continents); QList continentsList = goalGroup.readEntry("continents",QList()); foreach(const QString& continentId, continentsList) goal->continents().push_back(continentId); } else if (goalType == QLatin1String("player") ) { goal->setType(Goal::GoalPlayer); unsigned int nb = goalGroup.readEntry("nbCountriesFallback",0); goal->setNbCountries(nb); } m_goals.push_back(goal); } foreach (const QString &country, countriesList) { qCDebug(KSIRKSKINEDITOR_LOG) << "building neighbours list of " << country; QList< Country* > theNeighbours; KConfigGroup countryGroup = config.group(country); QList theNeighboursIds = countryGroup.readEntry("neighbours",QList()); // int neighbourId; foreach(const QString& neighbourId, theNeighboursIds) { theNeighbours.push_back(countryNamed(neighbourId)); } countryNamed(country)-> neighbours(theNeighbours); } qCDebug(KSIRKSKINEDITOR_LOG) << "Building map"; buildMap(); qCDebug(KSIRKSKINEDITOR_LOG) << "Map built"; qCDebug(KSIRKSKINEDITOR_LOG) << "Building flag icon"; int flagWidth = SkinSpritesData::changeable().intData(QStringLiteral("flag-width")); int flagHeight = SkinSpritesData::changeable().intData(QStringLiteral("flag-height")); int flagFrames = SkinSpritesData::changeable().intData(QStringLiteral("flag-frames")); int flagVersions = SkinSpritesData::changeable().intData(QStringLiteral("flag-versions")); if (m_nationalities.empty()) { m_flagIcon = QPixmap(flagWidth,flagHeight); } else { m_flagIcon = QPixmap(pixmapForId(m_nationalities[0]->name().toLower(),flagWidth*flagFrames,flagHeight*flagVersions).copy(0,0,flagWidth,flagHeight)); } qCDebug(KSIRKSKINEDITOR_LOG) << "Building infantry icon"; int infantryWidth = SkinSpritesData::changeable().intData(QStringLiteral("infantry-width")); int infantryHeight = SkinSpritesData::changeable().intData(QStringLiteral("infantry-height")); int infantryFrames = SkinSpritesData::changeable().intData(QStringLiteral("infantry-frames")); int infantryVersions = SkinSpritesData::changeable().intData(QStringLiteral("infantry-versions")); m_infantryIcon = QPixmap( pixmapForId(QStringLiteral("infantry"),infantryWidth*infantryFrames,infantryHeight*infantryVersions).copy(0,0,infantryWidth,infantryHeight)); qCDebug(KSIRKSKINEDITOR_LOG) << "Building cavalry icon"; int cavalryWidth = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-width")); int cavalryHeight = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-height")); int cavalryFrames = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-frames")); int cavalryVersions = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-versions")); m_cavalryIcon = QPixmap( pixmapForId(QStringLiteral("cavalry"),cavalryWidth*cavalryFrames,cavalryHeight*cavalryVersions).copy(0,0,cavalryWidth,cavalryHeight)); qCDebug(KSIRKSKINEDITOR_LOG) << "Building cannon icon"; int cannonWidth = SkinSpritesData::changeable().intData(QStringLiteral("cannon-width")); int cannonHeight = SkinSpritesData::changeable().intData(QStringLiteral("cannon-height")); int cannonFrames = SkinSpritesData::changeable().intData(QStringLiteral("cannon-frames")); int cannonVersions = SkinSpritesData::changeable().intData(QStringLiteral("cannon-versions")); m_cannonIcon = QPixmap( pixmapForId(QStringLiteral("cannon"),cannonWidth*cannonFrames,cannonHeight*cannonVersions).copy(0,0,cannonWidth,cannonHeight)); qCDebug(KSIRKSKINEDITOR_LOG) << "OUT"; } ONU::~ONU() { qDeleteAll(m_countries); qDeleteAll(m_nationalities); qDeleteAll(m_continents); qDeleteAll(m_goals); } void ONU::saveConfig(const QString& configFileName) { if (!configFileName.isNull()) { m_configFileName = configFileName; } qCDebug(KSIRKSKINEDITOR_LOG) << m_configFileName; KConfig config(m_configFileName); KConfigGroup onugroup = config.group("onu"); qCDebug(KSIRKSKINEDITOR_LOG) << "ONU XML format version: "; onugroup.writeEntry("format-version",ONU_FILE_FORMAT_VERSION); onugroup.writeEntry("name",m_name); onugroup.writeEntry("skinpath",m_skin); onugroup.writeEntry("width",m_width); onugroup.writeEntry("height",m_height); onugroup.writeEntry("desc",m_description); onugroup.writeEntry("pool",m_poolString); onugroup.writeEntry("width-between-flag-and-fighter",SkinSpritesData::changeable().intData(QStringLiteral("width-between-flag-and-fighter"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving flag data"; config.group("flag").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("flag-width"))); config.group("flag").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("flag-height"))); config.group("flag").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("flag-frames"))); config.group("flag").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("flag-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving infantry data"; // config.group("infantry").writeEntry("id",SkinSpritesData::changeable().strData("infantry-id")); config.group("infantry").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("infantry-width"))); config.group("infantry").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("infantry-height"))); config.group("infantry").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("infantry-frames"))); config.group("infantry").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("infantry-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving cavalry data"; // config.group("cavalry").writeEntry("id",SkinSpritesData::changeable().strData("cavalry-id")); config.group("cavalry").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("cavalry-width"))); config.group("cavalry").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("cavalry-height"))); config.group("cavalry").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("cavalry-frames"))); config.group("cavalry").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("cavalry-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving cannon data"; // config.group("cannon").writeEntry("id",SkinSpritesData::changeable().strData("cannon-id")); config.group("cannon").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("cannon-width"))); config.group("cannon").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("cannon-height"))); config.group("cannon").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("cannon-frames"))); config.group("cannon").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("cannon-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving firing data"; // config.group("firing").writeEntry("id",SkinSpritesData::changeable().strData("firing-id")); config.group("firing").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("firing-width"))); config.group("firing").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("firing-height"))); config.group("firing").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("firing-frames"))); config.group("firing").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("firing-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving exploding data"; // config.group("exploding").writeEntry("id",SkinSpritesData::changeable().strData("exploding-id")); config.group("exploding").writeEntry("width",SkinSpritesData::changeable().intData(QStringLiteral("exploding-width"))); config.group("cannon").writeEntry("height",SkinSpritesData::changeable().intData(QStringLiteral("exploding-height"))); config.group("exploding").writeEntry("frames",SkinSpritesData::changeable().intData(QStringLiteral("exploding-frames"))); config.group("exploding").writeEntry("versions",SkinSpritesData::changeable().intData(QStringLiteral("exploding-versions"))); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving font data"; KConfigGroup fontgroup = config.group("font"); fontgroup.writeEntry("family",m_font.family); fontgroup.writeEntry("size",m_font.size); switch (m_font.weight) { case QFont::Normal: fontgroup.writeEntry("weight", "normal"); break; case QFont::Light: fontgroup.writeEntry("weight", "light"); break; case QFont::DemiBold: fontgroup.writeEntry("weight", "demibold"); break; case QFont::Bold: fontgroup.writeEntry("weight", "bold"); break; case QFont::Black: fontgroup.writeEntry("weight", "black"); break; default: fontgroup.writeEntry("weight", "normal"); } fontgroup.writeEntry("italic", m_font.italic); fontgroup.writeEntry("foreground-color", m_font.foregroundColor); fontgroup.writeEntry("background-color", m_font.backgroundColor); qCDebug(KSIRKSKINEDITOR_LOG) << "Saving countries data"; QStringList countriesList; foreach (Country* country, m_countries) { countriesList.push_back(country->name()); } onugroup.writeEntry("countries", countriesList); unsigned int countryNum = 0; foreach (Country* country, m_countries) { qCDebug(KSIRKSKINEDITOR_LOG) << "Saving"<name()<<"data" << countryNum; KConfigGroup countryGroup = config.group(country->name()); // countryGroup.writeEntry("id",countryNum); countryNum++; countryGroup.writeEntry("anchor-point",country->anchorPoint()); countryGroup.writeEntry("central-point",country->centralPoint()); countryGroup.writeEntry("flag-point",country->pointFlag()); countryGroup.writeEntry("cannon-point",country->pointCannon()); countryGroup.writeEntry("cavalry-point",country->pointCavalry()); countryGroup.writeEntry("infantry-point",country->pointInfantry()); } qCDebug(KSIRKSKINEDITOR_LOG) << "Saving nationalities data"; QStringList nationalitiesList; foreach (Nationality* nationality, m_nationalities) { nationalitiesList.push_back(nationality->name()); } onugroup.writeEntry("nationalities", nationalitiesList); foreach (Nationality* nationality, m_nationalities) { qCDebug(KSIRKSKINEDITOR_LOG) << "Saving nationality " << nationality->name(); KConfigGroup nationalityGroup = config.group(nationality->name()); nationalityGroup.writeEntry("leader",nationality->leaderName()); nationalityGroup.writeEntry("flag",nationality->flagFileName()); } qCDebug(KSIRKSKINEDITOR_LOG) << "Saving continents data"; QStringList continentsList; foreach (Continent* continent, m_continents) { continentsList.push_back(continent->name()); } onugroup.writeEntry("continents", continentsList); // unsigned int continentNum = 0; foreach (Continent* continent, m_continents) { qCDebug(KSIRKSKINEDITOR_LOG) << "Saving"<name()<<"data"; KConfigGroup continentGroup = config.group(continent->name()); // continentGroup.writeEntry("id",++continentNum); continentGroup.writeEntry("bonus",continent->bonus()); QList countryIdList; foreach(Country* country, continent->members()) { countryIdList.push_back(country->name()); } continentGroup.writeEntry("continent-countries",countryIdList); } qCDebug(KSIRKSKINEDITOR_LOG) << "Saving goals data"; QStringList goalsList; int goalNum = 0; foreach (Goal* goal, m_goals) { QString name = QStringLiteral("goal") + QString::number(++goalNum); KConfigGroup goalGroup = config.group(name); goalGroup.writeEntry("desc",goal->description()); QList continentsList; switch(goal->type()) { case Goal::Countries: goalGroup.writeEntry("type","countries"); goalGroup.writeEntry("nbCountries",goal->nbCountries()); goalGroup.writeEntry("nbArmiesByCountry",goal->nbArmiesByCountry()); break; case Goal::Continents: goalGroup.writeEntry("type","continents"); foreach(const QString& continent, goal->continents()) { continentsList.push_back(continent); } goalGroup.writeEntry("continents",continentsList); break; case Goal::GoalPlayer: goalGroup.writeEntry("type","player"); goalGroup.writeEntry("nbCountriesFallback",goal->nbCountries()); break; default: goalGroup.writeEntry("type",""); } goalsList.push_back(name); } onugroup.writeEntry("goals", goalsList); foreach (Country* country, m_countries) { QList theNeighboursIds; KConfigGroup countryGroup = config.group(country->name()); foreach(Country* theNeighbour, country->neighbours()) { theNeighboursIds.push_back(theNeighbour->name()); } countryGroup.writeEntry("neighbours",theNeighboursIds); } m_dirty = false; qCDebug(KSIRKSKINEDITOR_LOG) << "OUT"; } /** This method returns a pointer to the country that contains the point (x,y). If there is no country at (x,y), the functions returns 0. */ Country* ONU::countryAt(const QPointF& point) { // qCDebug(KSIRKSKINEDITOR_LOG) << "ONU::countryAt x y " << x << " " << y; QPointF norm = point; if ( norm.x() < 0 || norm.x() >= m_countriesMask.width() || norm.y() < 0 || norm.y() >= m_countriesMask.height() ) return 0; int index = qBlue(m_countriesMask.pixel(norm.toPoint())); // qCDebug(KSIRKSKINEDITOR_LOG) << "OUT ONU::countryAt: " << index; if (index >= m_countries.size()) return 0; return m_countries.at(index); } void ONU::reset() { qCDebug(KSIRKSKINEDITOR_LOG); foreach (Country* country, m_countries) { country->reset(); } } /** * Returns the country named "name" ; 0 in case there is no such country */ Country* ONU::countryNamed(const QString& name) { if (name.isEmpty()) { return 0; } foreach (Country *c, m_countries) { if (c-> name() == name) return c; } return 0; } /** @return the number of countries in the world */ unsigned int ONU::getNbCountries() const { return(m_countries.size()); } /** Returns the nation named "name" ; 0 in case there is no such nation */ Nationality* ONU::nationNamed(const QString& name) { foreach (Nationality *n, m_nationalities) { if (n->name() == name) { return n; } } return 0; } // const Continent* ONU::continentWithId(const unsigned int id) const // { // foreach (const Continent* c, m_continents) // { // if (c->id() == id) // { // return c; // } // } // return 0; // } Continent* ONU::continentNamed(const QString& name) { foreach (Continent *c, m_continents) { if (c-> name() == name) return c; } return 0; } void ONU::buildMap() { qCDebug(KSIRKSKINEDITOR_LOG); //QSize size((int)(m_renderer.defaultSize().width()),(int)(m_renderer.defaultSize().height())); QSize size((int)(m_width),(int)(m_height)); QImage image(size, QImage::Format_ARGB32_Premultiplied); image.fill(0); QPainter p(&image); m_renderer.render(&p, QStringLiteral("map")); QPixmap mapPixmap = QPixmap::fromImage(image); m_map = mapPixmap; QPainter painter(&m_map); QFont foregroundFont(m_font.family, m_font.size, m_font.weight, m_font.italic); QFont backgroundFont(m_font.family, m_font.size, QFont::Normal, m_font.italic); painter.drawPixmap(0,0,mapPixmap); for (int i = 0; i < m_countries.size(); i++) { Country* country = m_countries[i]; const QString& countryName = i18n(country->name().toUtf8().data()); if (m_font.backgroundColor != QLatin1String("none")) { painter.setPen(m_font.backgroundColor); painter.setFont(backgroundFont); QRect countryNameRect = painter.fontMetrics().boundingRect(countryName); painter.drawText( int((country->centralPoint().x()-countryNameRect.width()/2+1)), int((country->centralPoint().y()+countryNameRect.height()/2 + 1)), countryName); } painter.setPen(m_font.foregroundColor); painter.setFont(foregroundFont); QRect countryNameRect = painter.fontMetrics().boundingRect(countryName); painter.drawText( int((country->centralPoint().x()-countryNameRect.width()/2)), int((country->centralPoint().y()+countryNameRect.height()/2)), countryName); } } QPixmap ONU::pixmapForId(const QString& id, int width, int height) { qCDebug(KSIRKSKINEDITOR_LOG) << id << width << height; //QSize size((int)(m_renderer.defaultSize().width()),(int)(m_renderer.defaultSize().height())); QSize size(width,height); QImage image(size, QImage::Format_ARGB32_Premultiplied); image.fill(0); QPainter p(&image); m_renderer.render(&p, id); QPixmap pixmap = QPixmap::fromImage(image); return pixmap; } QSvgRenderer* ONU::renderer() { return &m_renderer; } KGameSvgDocument* ONU::svgDom() { return &m_svgDom; } QGraphicsItem* ONU::itemFor(const Country* country, SpriteType spriteType) { if (country==0 || spriteType == None) return 0; foreach (QGraphicsItem* item, m_itemsMap.keys()) { if (m_itemsMap[item].first == country && m_itemsMap[item].second == spriteType) { // qCDebug(KSIRKSKINEDITOR_LOG) << item << (void*)country << spriteType; return item; } } qCDebug(KSIRKSKINEDITOR_LOG) << 0; return 0; } QFont ONU::foregroundFont() { QFont foregroundFont(m_font.family, m_font.size, m_font.weight, m_font.italic); return foregroundFont; } QFont ONU::backgroundFont() { QFont backgroundFont(m_font.family, m_font.size, QFont::Normal, m_font.italic); return backgroundFont; } void ONU::setFont(const QFont& font) { if (m_font.family == font.family() && m_font.size == font.pointSize() && m_font.weight == (QFont::Weight)font.weight() && m_font.italic == font.italic()) return; m_font.family = font.family(); m_font.size = font.pointSize(); m_font.weight = (QFont::Weight)font.weight(); m_font.italic = font.italic(); m_dirty = true; } void ONU::setFontFgColor(const QColor& color) { if (m_font.foregroundColor == color.name()) return; m_font.foregroundColor = color.name(); m_dirty = true; } void ONU::setFontBgColor(const QColor& color) { if (m_font.backgroundColor == color.name()) return; m_font.backgroundColor = color.name(); m_dirty = true; } void ONU::createCountry(const QString& newCountryName) { qCDebug(KSIRKSKINEDITOR_LOG); Country* newCountry = new Country(newCountryName, QPointF(), QPointF(), QPointF(), QPointF(), QPointF(), QPointF()/*, m_countries.size()*/); m_countries.push_back(newCountry); m_dirty = true; } void ONU::deleteCountry(Country* country) { qCDebug(KSIRKSKINEDITOR_LOG) << country->name(); QList itemsToRemove; foreach (QGraphicsItem* item, m_itemsMap.keys()) { if (m_itemsMap[item].first == country) { itemsToRemove.push_back(item); } } foreach (QGraphicsItem* item, itemsToRemove) { qCDebug(KSIRKSKINEDITOR_LOG) << "remove an item"; item->hide(); item->scene()->removeItem(item); m_itemsMap.remove(item); delete item; } qCDebug(KSIRKSKINEDITOR_LOG) << "remove and delete the country"; KConfig config(m_configFileName); config.deleteGroup(country->name()); m_countries.removeAll(country); delete country; m_dirty = true; } void ONU::createContinent(const QString& newContinentName) { qCDebug(KSIRKSKINEDITOR_LOG); Continent* newContinent = new Continent(newContinentName, QList(), 0); m_continents.push_back(newContinent); m_dirty = true; } void ONU::deleteContinent(Continent* continent) { qCDebug(KSIRKSKINEDITOR_LOG) << continent->name(); qCDebug(KSIRKSKINEDITOR_LOG) << "remove and delete the continent"; KConfig config(m_configFileName); config.deleteGroup(continent->name()); m_continents.removeAll(continent); delete continent; m_dirty = true; } void ONU::updateIcon(SpriteType type) { qCDebug(KSIRKSKINEDITOR_LOG) << type; int flagWidth; int flagHeight; int flagFrames; int flagVersions; int infantryWidth; int infantryHeight; int infantryFrames; int infantryVersions; int cavalryWidth; int cavalryHeight; int cavalryFrames; int cavalryVersions; int cannonWidth; int cannonHeight; int cannonFrames; int cannonVersions; switch (type) { case Flag: flagWidth = SkinSpritesData::changeable().intData(QStringLiteral("flag-width")); flagHeight = SkinSpritesData::changeable().intData(QStringLiteral("flag-height")); flagFrames = SkinSpritesData::changeable().intData(QStringLiteral("flag-frames")); flagVersions = SkinSpritesData::changeable().intData(QStringLiteral("flag-versions")); if (m_nationalities.empty()) { m_flagIcon = QPixmap(flagWidth,flagHeight); } else { m_flagIcon = QPixmap(pixmapForId(nationalities()[0]->name().toLower(),flagWidth*flagFrames,flagHeight*flagVersions).copy(0,0,flagWidth,flagHeight)); } break; case Infantry: infantryWidth = SkinSpritesData::changeable().intData(QStringLiteral("infantry-width")); infantryHeight = SkinSpritesData::changeable().intData(QStringLiteral("infantry-height")); infantryFrames = SkinSpritesData::changeable().intData(QStringLiteral("infantry-frames")); infantryVersions = SkinSpritesData::changeable().intData(QStringLiteral("infantry-versions")); m_infantryIcon = QPixmap( pixmapForId(QStringLiteral("infantry"),infantryWidth*infantryFrames,infantryHeight*infantryVersions).copy(0,0,infantryWidth,infantryHeight)); break; case Cavalry: cavalryWidth = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-width")); cavalryHeight = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-height")); cavalryFrames = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-frames")); cavalryVersions = SkinSpritesData::changeable().intData(QStringLiteral("cavalry-versions")); m_cavalryIcon = QPixmap( pixmapForId(QStringLiteral("cavalry"),cavalryWidth*cavalryFrames,cavalryHeight*cavalryVersions).copy(0,0,cavalryWidth,cavalryHeight)); break; case Cannon: cannonWidth = SkinSpritesData::changeable().intData(QStringLiteral("cannon-width")); cannonHeight = SkinSpritesData::changeable().intData(QStringLiteral("cannon-height")); cannonFrames = SkinSpritesData::changeable().intData(QStringLiteral("cannon-frames")); cannonVersions = SkinSpritesData::changeable().intData(QStringLiteral("cannon-versions")); m_cannonIcon = QPixmap( pixmapForId(QStringLiteral("cannon"),cannonWidth*cannonFrames,cannonHeight*cannonVersions).copy(0,0,cannonWidth,cannonHeight)); break; default:; } } void ONU::createGoal() { Goal* goal = new Goal(); m_goals.push_back(goal); m_dirty = true; } void ONU::deleteGoal(int g) { qCDebug(KSIRKSKINEDITOR_LOG) << m_goals.size() << g; KConfig config(m_configFileName); QString groupName = QStringLiteral("goal")+QString::number(g+1); qCDebug(KSIRKSKINEDITOR_LOG) << "delete group" << groupName; config.deleteGroup(groupName); Goal* goal = m_goals.takeAt(g); delete goal; m_dirty = true; } Nationality* ONU::nationalityNamed(const QString& name) { foreach (Nationality* nationality, m_nationalities) { if (nationality->name() == name) { return nationality; } } return 0; } void ONU::createNationality(const QString& newNationalityName) { Nationality* nationality = new Nationality(newNationalityName, QLatin1String(""), QLatin1String("")); m_nationalities.push_back(nationality); m_dirty = true; } void ONU::deleteNationality(Nationality* nationality) { qCDebug(KSIRKSKINEDITOR_LOG); KConfig config(m_configFileName); config.deleteGroup(nationality->name()); m_nationalities.removeAll(nationality); delete nationality; m_dirty = true; } void ONU::loadPoolIds(const QString& fileName) { qCDebug(KSIRKSKINEDITOR_LOG) << fileName; QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { KMessageBox::sorry(0, i18n("Cannot read file %1:\n%2.",fileName,file.errorString()), i18n("PoolLoader")); return; } QXmlStreamReader xml(&file); QRegExp reg("\\D+\\d+"); while (!xml.atEnd()) { QXmlStreamReader::TokenType type = xml.readNext(); if (type == QXmlStreamReader::StartElement) { qCDebug(KSIRKSKINEDITOR_LOG) << xml.text().toString(); QXmlStreamAttributes attributes = xml.attributes (); QStringRef id = attributes.value(QLatin1String(""), QStringLiteral("id") ); if (!id.isEmpty() && !reg.exactMatch(id.toString())) { m_poolIds.push_back(id.toString()); } } } if (xml.hasError()) { qCCritical(KSIRKSKINEDITOR_LOG) << "Error: " << xml.errorString(); // do error handling } m_poolIds.sort(); } } diff --git a/ksirkskineditor/onu.h b/ksirkskineditor/onu.h index ed243b1..5fcc2af 100644 --- a/ksirkskineditor/onu.h +++ b/ksirkskineditor/onu.h @@ -1,326 +1,326 @@ /*************************************************************************** onu.h - description ------------------- begin : Wed Jul 18 2001 copyright : (C) 2001 by Gael de Chalendar email : Gael.de.Chalendar@free.fr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either either version 2 of the License, or (at your option) any later version.of the License, or * * (at your option) any later version. * * * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA ***************************************************************************/ #define KDE_NO_COMPAT #ifndef KSIRKSKINEDITORONU_H #define KSIRKSKINEDITORONU_H #include "country.h" #include "continent.h" #include "nationality.h" #include "spritetype.h" #include #include #include #include #include #define USE_UNSTABLE_LIBKDEGAMESPRIVATE_API #include class QGraphicsItem; namespace KsirkSkinEditor { class Country; class Goal; /** * Class ONU (Organisation des Nations Unies = UNO : United Nations * Organization) is simply the list of the countries. The data definining * each country is loaded from an XML configuration file located in the * current skin data directory */ class ONU: public QObject { Q_OBJECT public: /** * Constructor * @param configFileName The name of the XML file defining this world. Built * from the current skin dir and a default file name. */ explicit ONU(const QString& configFileName, QObject *parent); /** Default destructor */ ~ONU() override; //{@ /** * Accessors */ inline const QString& skin() const {return m_skin;} inline const QString& name() const {return m_name;} inline void setName(const QString& n) { if (m_name != n) {m_name = n; m_dirty = true;} } inline const QString& description() const {return m_description;} inline void setDescription(const QString& d) { if (m_description != d) {m_description = d; m_dirty=true;} } inline const QString& configFileName() const {return m_configFileName;} inline const QPixmap& map() const {return m_map;} inline const QPixmap& snapshot() const {return m_snapshot;} inline unsigned int width() const {return m_width;} inline void setWidth(unsigned int w) { if (m_width != w) {m_width = w; m_dirty = true;} } inline unsigned int height() const {return m_height;} inline void setHeight(unsigned int h) { if (m_height != h) {m_height = h; m_dirty = true;} } inline const QStringList& poolIds() const {return m_poolIds;} inline bool dirty() const {return m_dirty;} inline void setDirty() {m_dirty = true;} //@} /** * This method returns a pointer to the country that contains the given * point. If there is no country there, the functions returns 0. * @param point The point where to search for a country in the map mask * @return The country at the given point or 0 if there is no country there. */ Country* countryAt(const QPointF& point); /** * Calls its reset method for each country */ void reset(); /** * Return the countries list */ inline QList& countries() {return m_countries;} /** * Returns the nationalities list */ inline QList& nationalities() {return m_nationalities;} //@{ /** Read property of QList continents. */ inline QList& continents() {return m_continents;} inline const QList& continents() const {return m_continents;} //@} inline QList& goals() {return m_goals;} /** * Retrieves the continent with the given id * @param id The id of the continent to retrieve * @return A pointer to the retrieved continent or 0 if there is no * continent with the given id. */ const Continent* continentWithId(const unsigned int id) const; /** * Returns the country named "name" ; 0 in case there is no such country. * @param name The name of the country to retrieve. * @return The country named name or 0 if there is no such country. */ Country* countryNamed(const QString& name); /** * Gets the number of countries in the world * @return The number of countries in the world */ unsigned int getNbCountries() const; /** * Saves a XML representation of the world for game saving purpose * @param xmlStream The stream to write on */ void saveXml(std::ostream& xmlStream); /** * Returns the nation named "name" ; 0 in case there is no such nation * @param name The name of the nation to retrieve. * @return The nation named name or 0 if there is no such nation. */ Nationality* nationNamed(const QString& name); /** * Returns the continent named "name" ; 0 in case there is no such continent * @param name The name of the continent to retrieve. * @return The continent named name or 0 if there is no such continent. */ Continent* continentNamed(const QString& name); Nationality* nationalityNamed(const QString& name); QSvgRenderer* renderer(); inline const QImage& mask() const {return m_countriesMask;} KGameSvgDocument* svgDom(); inline QMap >& itemsMap() {return m_itemsMap;} QGraphicsItem* itemFor(const Country* country, SpriteType spriteType); QPixmap pixmapForId(const QString& id, int width, int height); inline const QPixmap& flagIcon() const {return m_flagIcon;} inline const QPixmap& infantryIcon() const {return m_infantryIcon;} inline const QPixmap& cavalryIcon() const {return m_cavalryIcon;} inline const QPixmap& cannonIcon() const {return m_cannonIcon;} void saveConfig(const QString& configFileName = QString()); QFont foregroundFont(); QFont backgroundFont(); QColor foregroundColor() {return QColor(m_font.foregroundColor);} QColor backgroundColor() {return QColor(m_font.backgroundColor);} void setFont(const QFont& font); void setFontFgColor(const QColor& color); void setFontBgColor(const QColor& color); void createCountry(const QString& newCountryName); void deleteCountry(Country* country); void createContinent(const QString& newCountryName); void deleteContinent(Continent* country); void updateIcon(SpriteType type); void createGoal(); void deleteGoal(int g); void createNationality(const QString& newNationalityName); void deleteNationality(Nationality* nationality); private: /** * All data that have to be stored about the font to display countries names * in this world's skin */ struct FontDesc { QString family; - uint size; + int size; QFont::Weight weight; bool italic; QString foregroundColor; QString backgroundColor; }; /** * Build the map from it's stored image and the countries names */ void buildMap(); void loadPoolIds(const QString& fileName); QString m_configDir; /** * The name of the .desktop file containing the world's definition */ QString m_configFileName; /** * The displayable name of the skin */ QString m_name; /** * The displayable long description of the skin */ QString m_description; /** * The map used by this skin, built at the proper size from its SVG source * and decorated with countries names */ QPixmap m_map; /** * A snaphsot of a running game with this skin. Used at skin choice time. */ QPixmap m_snapshot; //@{ /** * The width and height of the map file (will be used as canvas size). These * measures do not take into account the zoom factor. */ unsigned int m_width; unsigned int m_height; //@} /** * The list of countries */ QList m_countries; /** * The list of nationalities */ QList m_nationalities; /** * The continents of the world */ QList m_continents; /** * This image stores the mask that defines the countries of the world. * The blue RGB component value of each pixel gives the index of the * country in the countries list. */ QImage m_countriesMask; /** * The path to the skin ; relative to the ksirk data dir ; loaded from the * XML file */ QString m_skin; /** * The description of the font used to draw countries names onto the map. */ FontDesc m_font; /** * This SVG renderer stores the SVG file of the map, renders it at the * desired zoom factor and the result is used to build the map image. */ QSvgRenderer m_renderer; KGameSvgDocument m_svgDom; QMap > m_itemsMap; QPixmap m_flagIcon; QPixmap m_infantryIcon; QPixmap m_cavalryIcon; QPixmap m_cannonIcon; QString m_poolString; QList m_goals; QStringList m_poolIds; bool m_dirty; }; } #endif // ONU_H