diff --git a/Konquest.cc b/Konquest.cc index 3cd4981..792e978 100644 --- a/Konquest.cc +++ b/Konquest.cc @@ -1,78 +1,78 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 #include #include -#include +#include +#include #include + +#include #include -#include -#include #include "mainwin.h" static const char description[] = I18N_NOOP("Galactic Strategy KDE Game"); #define KONQUEST_VERSION "2.3" int main(int argc, char **argv) { QApplication app(argc, argv); Kdelibs4ConfigMigrator migrate(QStringLiteral("konquest")); migrate.setConfigFiles(QStringList() << QStringLiteral("konquestrc")); migrate.setUiFiles(QStringList() << QStringLiteral("konquestui.rc")); migrate.migrate(); KLocalizedString::setApplicationDomain("konquest"); KAboutData aboutData( "konquest", i18n("Konquest"), KONQUEST_VERSION, i18n(description), KAboutLicense::GPL, i18n("Copyright (c) 1999-2013, Developers"), "http://games.kde.org/konquest" ); aboutData.addAuthor(i18n("Russ Steffen"), QString(), "rsteffen@bayarea.net"); aboutData.addCredit(i18n("Stephan Zehetner"), i18n("Computer/AI Player"), "s.zehetner@nevox.org"); aboutData.addCredit(i18n("Dmitry Suzdalev"), i18n("Port to KDE4"), "dimsuz@gmail.com"); aboutData.addCredit(i18n("Inge Wallin"), i18n("Cleaning and bugfixing"), "inge@lysator.liu.se"); aboutData.addCredit(i18n("Pierre Ducroquet"), i18n("Cleaning and bugfixing, maintenance"), "pinaraf@gmail.com"); aboutData.addCredit(i18n("Sean D'Epagnier"), i18n("Gameplay Enhancements"), "geckosenator@gmail.com"); aboutData.setOrganizationDomain(QByteArray("kde.org")); QCommandLineParser parser; KAboutData::setApplicationData(aboutData); KCrash::initialize(); parser.addVersionOption(); parser.addHelpOption(); aboutData.setupCommandLine(&parser); parser.process(app); aboutData.processCommandLine(&parser); KDBusService service; if (app.isSessionRestored()) RESTORE(MainWindow) else { MainWindow *w = new MainWindow; w->show(); } app.setWindowIcon(QIcon::fromTheme(QStringLiteral("konquest"))); return app.exec(); } diff --git a/dialogs/fleetdlg.cc b/dialogs/fleetdlg.cc index 0b3db1b..dc0a0c7 100644 --- a/dialogs/fleetdlg.cc +++ b/dialogs/fleetdlg.cc @@ -1,227 +1,226 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 "fleetdlg.h" -#include -#include - -#include #include + #include +#include #include +#include #include #include "planet.h" #include "../players/player.h" FleetDlg::FleetDlg( QWidget *parent, const AttackFleetList &fleets, const AttackFleetList &newFleets, const AttackFleetList &standingOrders) : QDialog(parent), m_newFleetList(newFleets), m_standingOrders(standingOrders), m_fleetList(fleets) { setObjectName( QLatin1String( "FleetDlg" ) ); setModal( true ); setWindowTitle( i18n("Fleet Overview") ); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); QWidget *mainWidget = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); mainLayout->addWidget(mainWidget); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, &QDialogButtonBox::accepted, this, &FleetDlg::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &FleetDlg::reject); setupTable(); update(); mainLayout->addWidget(m_fleetTable); mainLayout->addWidget(buttonBox); } QSize FleetDlg::sizeHint() const { int w = m_fleetTable->verticalHeader()->width(); int h = m_fleetTable->horizontalHeader()->height(); for (int col = 0; col < m_fleetTable->columnCount(); ++col) { w += m_fleetTable->columnWidth(col); } for (int row = 0; row < m_fleetTable->rowCount(); ++row) { h += m_fleetTable->rowHeight(row); } /** * @todo The created dialogue should not be larger than the screen, and * ideally, it should not be larger than the main application window. * As the vertical main application window size is not (yet) known here, * simply use a hard-coded limit right now. */ if (h > 480) { // As the height of the widget is reduced, a vertical scrollbar is // shown. Add the width of that scrollbar to the width of the widget to // prevent a horizontal scrollbar from appearing. h = 480; w += m_fleetTable->style()->pixelMetric(QStyle::PM_ScrollBarExtent); } /** * @todo The size calculated here does not yet prevent scrollbars to be * shown for the table. Figure out the offsets needed to be added and remove * the hard-coded numbers below! One reason here is that this size hint is * for the whole dialogue and not just for the table. */ return QSize(w, h) + QSize(40, 80); } void FleetDlg::setupTable() { m_fleetTable = new QTableWidget(this); m_fleetTable->setColumnCount(7); m_fleetTable->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); m_fleetTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); m_fleetTable->setSelectionMode(QAbstractItemView::NoSelection); QStringList headerLabels; headerLabels << QString() << i18n("Fleet No.") << i18n("Source") << i18n("Destination") << i18n("Ships") << i18n("Kill Percentage") << i18n("Arrival Turn"); m_fleetTable->setHorizontalHeaderLabels(headerLabels); m_fleetTable->verticalHeader()->hide(); } void FleetDlg::update() { AttackFleetList fleets = m_standingOrders + m_newFleetList + m_fleetList; const int standingOrders = m_standingOrders.count(); const int newFleets = standingOrders + m_newFleetList.count(); m_fleetTable->setRowCount( fleets.count() ); int row = 0; QTableWidgetItem *item; foreach (AttackFleet *curFleet, fleets) { item = new QTableWidgetItem(); if( row < newFleets) { item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); item->setCheckState(Qt::Checked); if( row < standingOrders ) item->setText(i18n("Standing order")); } else { item->setFlags(Qt::ItemIsEnabled); } m_fleetTable->setItem(row, 0, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, row + 1); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 1, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curFleet->source->name()); item->setData(Qt::DecorationRole, curFleet->source->player()->color()); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 2, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curFleet->destination->name()); item->setData(Qt::DecorationRole, curFleet->destination->player()->color()); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 3, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curFleet->shipCount()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 4, item); // The number is formatted and added as a string. Sorting by this // column sorts by string comparison rather than by floating point // number comparison. But as all values have the same amount of // characters/digits, sorting by string actually works. item = new QTableWidgetItem(QStringLiteral("%1").arg(curFleet->source->killPercentage(), 3, 'f', 3)); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 5, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curFleet->arrivalTurn); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_fleetTable->setItem(row, 6, item); ++row; } m_fleetTable->setSortingEnabled(true); m_fleetTable->resizeColumnsToContents(); } AttackFleetList* FleetDlg::uncheckedFleets() { AttackFleetList *fleets = new AttackFleetList(); QTableWidgetItem *item; int count = m_fleetTable->rowCount(); for( int f = 0; f < count; ++f) { item = m_fleetTable->item(f,0); if( (item->flags() & Qt::ItemIsUserCheckable) && (item->checkState() == Qt::Unchecked) ) { const int pos = m_fleetTable->item(f,1)->text().toInt() - 1; if (pos >= 0) { if(pos < m_standingOrders.count()) fleets->append( m_standingOrders.at(pos) ); else fleets->append( m_newFleetList.at(pos - m_standingOrders.count()) ); } } } return fleets; } diff --git a/dialogs/newgamedlg.cc b/dialogs/newgamedlg.cc index a65121e..1b81997 100644 --- a/dialogs/newgamedlg.cc +++ b/dialogs/newgamedlg.cc @@ -1,692 +1,690 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet Copyright 2011 Jeffrey Kelling 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 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 "newgamedlg.h" #include "../players/ai/becai/becai_gui.h" #include "../players/ai/becai/becai.h" #include "../players/ai/default/weak_gui.h" #include "../players/ai/default/normal_gui.h" #include "../players/ai/default/hard_gui.h" #ifdef KONQUEST_EXAMPLE_PLAYER #include "../players/ai/example/example_gui.h" #endif #include "../players/computerplayer.h" #include "../players/player_gui.h" #include "../players/localplayer.h" #include "../players/localplayer_gui.h" #include "../players/spectatorplayer.h" #include "../players/spectatorplayer_gui.h" #include "../game.h" -#include -#include -#include +#include #include +#include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include /************************************************************************* New Game Dialog Members ************************************************************************/ static const QColor PlayerColors[MAX_PLAYERS] = { QColor( 130, 130, 255 ), Qt::yellow, Qt::red, Qt::green, Qt::white, Qt::cyan, Qt::magenta, QColor( 235, 153, 46 ), QColor( 106, 157, 104 ), QColor( 131, 153, 128) }; class playersListModel : public QAbstractTableModel { typedef QPair PlayerId; QLinkedList m_availablePlayerId; NewGameDlg *m_newGameDlg; public: playersListModel(NewGameDlg *newGameDlg, Game *game, const QList &selectablePlayer) : QAbstractTableModel(newGameDlg), m_newGameDlg(newGameDlg), m_game(game), m_selectablePlayer(selectablePlayer) { for(int a = 0; a < MAX_PLAYERS; ++a) { m_availablePlayerId.push_back(PlayerId( PlayerColors[a], QString( i18nc("Default player name is \"player \" + player number", "Player %1", a) ))); } } int rowCount(const QModelIndex &index = QModelIndex()) const { Q_UNUSED(index); return m_players.count(); } int columnCount(const QModelIndex&) const { return 2; } QVariant data(const QModelIndex &index, int role) const { if (index.isValid()) { int row = index.row(); int column = index.column(); Player *player = m_players.at(row); if (role == Qt::DecorationRole && column == 0) { return player->color(); } else if (role == Qt::DisplayRole) { if (column == 0) { return player->name(); } else if (column == 1) { return player->guiName(); } } } return QVariant(); } QVariant headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { if (section == 0) return i18nc("The player name", "Name"); else if (section == 1) return i18n("Type"); } return QVariant(); } bool setData(const QModelIndex &index, const QVariant &value, int) { bool result = false; if (index.isValid()) { int row = index.row(); int column = index.column(); Player *player = m_players.at(row); if (column == 0) { // The player name changed. player->setName(value.toString()); result = true; } else if (column == 1) { // The player controller changed. QString playerGuiName = value.toString(); foreach (PlayerGui *playerGui, m_selectablePlayer) { if (playerGui->guiName() == playerGuiName) { Player *newPlayer = getNewPlayerByGui(playerGui, player->name(), player->color()); if (newPlayer) { m_players[row] = newPlayer; m_game->map()->turnOverPlayerPlanets(player, newPlayer); player->deleteLater(); result = true; } } } } } if (result) { m_game->setPlayers(m_players); m_newGameDlg->updateButtonOk(); emit dataChanged(index, index); } return result; } Player *addPlayer(PlayerGui* selectedPlayer = 0) { Player *player = NULL; int players = m_players.count(); if ((!m_availablePlayerId.empty()) && (!m_selectablePlayer.empty())) { beginInsertRows(QModelIndex(), players, players); // Use the given player controller. If none is given, use the very // first registered player controller as default. if (!selectedPlayer) { selectedPlayer = m_selectablePlayer.front(); } player = getNewPlayerByGui(selectedPlayer, m_availablePlayerId.front().second, m_availablePlayerId.front().first); if (player) { m_availablePlayerId.pop_front(); m_players.append(player); m_game->setPlayers(m_players); m_newGameDlg->updateButtonOk(); } endInsertRows(); } return player; } Qt::ItemFlags flags(const QModelIndex &) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; } Player *removePlayer(int row) { Player *player = NULL; if (row >= 0 && row < m_players.count()) { beginRemoveRows(QModelIndex(), row, row); player = m_players.at(row); m_availablePlayerId.push_back(PlayerId(player->color(), player->name())); m_players.removeAt(row); m_game->setPlayers(m_players); m_newGameDlg->updateButtonOk(); endRemoveRows(); } return player; } private: /** * Search the list of registered player controllers and return either a new * instance of that controller or NULL if it cannot be found. * * @note The GUI name of the player instance gets set. */ Player *getNewPlayerByGui(PlayerGui *playerGui, const QString &playerName, const QColor &color) const { Player *newPlayer = 0; if (playerGui) { newPlayer = playerGui->createInstance(m_game, playerName, color); newPlayer->setGuiName(playerGui->guiName()); } return newPlayer; } private: Game *m_game; QList m_players; QList m_selectablePlayer; }; /** * This class handles the list of selectable player controllers. * This includes the local player and all enabled AI players. */ class playersListDelegate : public QItemDelegate { public: playersListDelegate(QObject *parent, const QList &selectablePlayer) : QItemDelegate(parent), m_selectablePlayer(selectablePlayer) { } QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { if (index.column() == 0) return new QLineEdit(parent); else return new QComboBox(parent); } void setEditorData(QWidget *editor, const QModelIndex &index) const { if (index.column() != 0) { QComboBox *cbox = static_cast(editor); foreach (PlayerGui* playerGui, m_selectablePlayer) { cbox->addItem(playerGui->guiName()); } cbox->setCurrentIndex( cbox->findText(index.data( Qt::DisplayRole).toString()) ); } else { QLineEdit *lineEdit = static_cast(editor); lineEdit->setText(index.data(Qt::DisplayRole).toString()); } } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (index.column() != 0) { QComboBox *cbox = static_cast(editor); model->setData(index, cbox->currentText(), Qt::EditRole); } else { QLineEdit *lineEdit = static_cast(editor); model->setData(index, lineEdit->text(), Qt::EditRole); } } private: QList m_selectablePlayer; }; NewGameDlg::NewGameDlg( QWidget *parent, Game *game) : QDialog( parent), m_game(game) { m_neutral = m_game->neutral(); setWindowTitle(i18n("Start New Game")); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); QWidget *mainWidget = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); mainLayout->addWidget(mainWidget); okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, &QDialogButtonBox::accepted, this, &NewGameDlg::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &NewGameDlg::reject); m_selectablePlayer.push_back(new LocalPlayerGui()); m_selectablePlayer.push_back(new SpectatorPlayerGui()); m_selectablePlayer.push_back(new AiDefaultWeakGui()); m_selectablePlayer.push_back(new AiDefaultNormalGui()); m_selectablePlayer.push_back(new AiDefaultHardGui()); #ifdef KONQUEST_EXAMPLE_PLAYER m_selectablePlayer.push_back(new AiExampleGui()); #endif m_selectablePlayer.push_back(new AiBecaiGui()); m_playerTypeChooser = new QMenu(this); QSignalMapper *menuMapper = new QSignalMapper(this); for (int i = 0 ; i < m_selectablePlayer.size() ; i++) { PlayerGui *selectablePlayer = m_selectablePlayer[i]; QAction *action = m_playerTypeChooser->addAction(selectablePlayer->guiName()); menuMapper->setMapping(action, i); connect(action, SIGNAL(triggered(bool)), menuMapper, SLOT(map())); } connect(menuMapper, static_cast(&QSignalMapper::mapped), this, &NewGameDlg::slotAddPlayer); m_w = new NewGameDlgUI(this); m_w->map->setMap(m_game->map()); connect(m_w->map, &MiniMapView::sectorSelected, this, &NewGameDlg::slotUpdateSelection); playersListModel *model = new playersListModel(this, m_game, m_selectablePlayer); m_w->playerList->setModel(model); m_w->playerList->setItemDelegate(new playersListDelegate(this, m_selectablePlayer)); m_w->playerList->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_w->addPlayerButton->setMenu(m_playerTypeChooser); connect(m_w->neutralPlanetsSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotUpdateNeutrals); connect(m_w->widthSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotNewMap); connect(m_w->heightSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotNewMap); connect(m_w->randomizeMap, &QPushButton::clicked, this, &NewGameDlg::slotNewMap); connect(m_w->removePlayerButton, &QPushButton::clicked, this, &NewGameDlg::slotRemovePlayer); connect(m_w->OwnerCB, static_cast(&QComboBox::currentIndexChanged), this, &NewGameDlg::slotNewOwner); connect(m_w->KillPercentageSB, static_cast(&QDoubleSpinBox::valueChanged), this, &NewGameDlg::slotNewKillPercentage); connect(m_w->ProductionSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotNewProduction); init(); mainLayout->addWidget(m_w); mainLayout->addWidget(buttonBox); okButton->setDefault(true); slotNewMap(); updateButtonOk(); } NewGameDlg::~NewGameDlg() { qDeleteAll(m_selectablePlayer); } void NewGameDlg::updateOwnerCB() { m_w->OwnerCB->clear(); m_w->OwnerCB->addItem(i18n("vacant")); foreach(Player *player, m_game->players()) m_w->OwnerCB->addItem(player->name()); m_w->OwnerCB->addItem(i18n("neutral")); } void NewGameDlg::init() { KConfigGroup config = KSharedConfig::openConfig()->group("Game"); int nrOfPlayers = config.readEntry("NrOfPlayers",0); if (nrOfPlayers < 2) nrOfPlayers = 2; if (nrOfPlayers > MAX_PLAYERS) nrOfPlayers = MAX_PLAYERS; int nrOfPlanets = config.readEntry("NrOfPlanets", 3); int sizeWid = config.readEntry("SizeWidth", 10); int sizeHeight = config.readEntry("SizeHeight", 10); m_w->neutralPlanetsSB->setValue(nrOfPlanets); m_w->widthSB->setValue(sizeWid); m_w->heightSB->setValue(sizeHeight); m_w->BlindMapCB->setCheckState( config.readEntry("BlindMap", false) ? Qt::Checked : Qt::Unchecked); m_w->CumulativeProductionCB->setCheckState( config.readEntry("CumulativeProduction", false) ? Qt::Checked : Qt::Unchecked); m_w->ProductionAfterConquereCB->setCheckState( config.readEntry("ProductionAfterConquere", true) ? Qt::Checked : Qt::Unchecked); m_w->NeutralsShowShipsCB->setCheckState( config.readEntry("NeutralsShowShips", false) ? Qt::Checked : Qt::Unchecked); m_w->NeutralsShowStatsCB->setCheckState( config.readEntry("NeutralsShowStats", false) ? Qt::Checked : Qt::Unchecked); m_w->NeutralsProductionSB->setValue(config.readEntry("NeutralsProduction", 1)); // Restore player names playersListModel *model = static_cast(m_w->playerList->model()); for(int i = 0; i < nrOfPlayers; ++i) { QString keyName = QString("Player_%1").arg(i); QString keyType = QString("PlayerType_%1").arg(i); QString playerName = config.readEntry(keyName,QString()); QString playerType = config.readEntry(keyType,QString()); model->addPlayer(); if (!playerName.isEmpty()) { model->setData(model->index(i, 0), playerName, Qt::EditRole); } model->setData(model->index(i, 1), playerType, Qt::EditRole); } updateOwnerCB(); } void NewGameDlg::slotAddPlayer(int selectedPlayerType) { PlayerGui *selectablePlayer = m_selectablePlayer[selectedPlayerType]; playersListModel *model = static_cast(m_w->playerList->model()); Player *player = model->addPlayer(selectablePlayer); if (player) { m_game->map()->addPlayerPlanetSomewhere(player); } updateButtonOk(); updateOwnerCB(); } void NewGameDlg::slotRemovePlayer() { playersListModel *model = static_cast(m_w->playerList->model()); Player *player = model->removePlayer(m_w->playerList->currentIndex().row()); if(player) { m_game->map()->removePlayerPlanets(player); delete player; } updateButtonOk(); updateOwnerCB(); } void NewGameDlg::slotUpdateSelection(const Coordinate &coord) { Sector *sector = m_game->map()->sector(coord); if (!sector) { m_w->OwnerCB->setEnabled(false); m_w->KillPercentageSB->setEnabled(false); m_w->ProductionSB->setEnabled(false); return; } bool hasPlanet = sector->hasPlanet(); m_w->OwnerCB->setEnabled(hasPlanet); m_w->KillPercentageSB->setEnabled(hasPlanet); m_w->ProductionSB->setEnabled(hasPlanet); disconnect(m_w->OwnerCB, static_cast(&QComboBox::currentIndexChanged), this, &NewGameDlg::slotNewOwner); if (hasPlanet) { Planet *planet = sector->planet(); int f = m_w->OwnerCB->findText(planet->player()->name()); if (f >= 0) { m_w->OwnerCB->setCurrentIndex(f); } else { m_w->OwnerCB->setCurrentIndex(m_w->OwnerCB->count()-1); } m_w->KillPercentageSB->setValue(planet->killPercentage()); m_w->ProductionSB->setValue(planet->production()); } else { m_w->OwnerCB->setCurrentIndex(0); } connect(m_w->OwnerCB, static_cast(&QComboBox::currentIndexChanged), this, &NewGameDlg::slotNewOwner); } void NewGameDlg::slotNewOwner(int index) { if (!m_w->map->hasSelection()) return; Sector *sector = m_game->map()->sector(m_w->map->selection()); if (sector->hasPlanet()) { delete sector->planet(); } if (index > 0) { m_game->map()->addPlanet(sector, index - 1 < m_game->players().count() ? m_game->players()[index-1] : m_neutral, m_w->ProductionSB->value(), m_w->KillPercentageSB->value()); } m_w->KillPercentageSB->setEnabled(index); m_w->ProductionSB->setEnabled(index); updateButtonOk(); } void NewGameDlg::slotNewKillPercentage(double value) { Sector *selected = m_game->map()->sector(m_w->map->selection()); if(selected->hasPlanet()) selected->planet()->setKillPercentage(value); } void NewGameDlg::slotNewProduction(int value) { Sector *selected = m_game->map()->sector(m_w->map->selection()); if(selected->hasPlanet()) selected->planet()->setProduction(value); } void NewGameDlg::save() { KConfigGroup config = KSharedConfig::openConfig()->group("Game"); config.writeEntry("NrOfPlanets", m_w->neutralPlanetsSB->value()); config.writeEntry("SizeWidth", m_w->widthSB->value()); config.writeEntry("SizeHeight", m_w->heightSB->value()); #define CONFIG_WRITE_ENTRY_CB(NAME) \ config.writeEntry(#NAME, m_game->options().NAME \ = m_w->NAME##CB->checkState() == Qt::Checked); CONFIG_WRITE_ENTRY_CB(BlindMap); CONFIG_WRITE_ENTRY_CB(CumulativeProduction); CONFIG_WRITE_ENTRY_CB(ProductionAfterConquere); CONFIG_WRITE_ENTRY_CB(NeutralsShowShips); CONFIG_WRITE_ENTRY_CB(NeutralsShowStats); config.writeEntry("NeutralsProduction", m_game->options().NeutralsProduction = m_w->NeutralsProductionSB->value()); playersListModel *model = static_cast(m_w->playerList->model()); config.writeEntry("NrOfPlayers", model->rowCount()); for (int i = 0; i < model->rowCount(); ++i) { QString keyName = QString("Player_%1").arg(i); QString playerName = model->data(model->index(i, 0), Qt::DisplayRole).toString(); QString keyType = QString("PlayerType_%1").arg(i); QString playerType = model->data(model->index(i, 1), Qt::DisplayRole).toString(); config.writeEntry(keyName, playerName); config.writeEntry(keyType, playerType); } config.sync(); } void NewGameDlg::slotNewMap() { // Clear map, player and planet lists m_game->map()->clearMap(); m_game->map()->resizeMap(m_w->heightSB->value(), m_w->widthSB->value()); // make sure we have space for neutrals int maxneutrals = m_w->heightSB->value()*m_w->widthSB->value() - m_game->players().count(); if(m_w->neutralPlanetsSB->value() > maxneutrals) { disconnect(m_w->neutralPlanetsSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotNewMap); m_w->neutralPlanetsSB->setValue(maxneutrals); connect(m_w->neutralPlanetsSB, static_cast(&QSpinBox::valueChanged), this, &NewGameDlg::slotNewMap); } // make the planets m_game->map()->populateMap(m_game->players(), m_neutral, m_w->neutralPlanetsSB->value()); slotUpdateSelection(m_w->map->selection()); updateButtonOk(); } void NewGameDlg::slotUpdateNeutrals(int count) { while(m_game->map()->playerPlanetCount(m_neutral) < count && m_game->map()->addNeutralPlanetSomewhere(m_neutral)) ; while(m_game->map()->playerPlanetCount(m_neutral) > count && m_game->map()->removePlayerPlanet(m_neutral)) ; if(m_w->map->hasSelection()) slotUpdateSelection(m_w->map->selection()); } /** * Enable the "ok" button if the game settings are sane. */ void NewGameDlg::updateButtonOk() { int nonSpectatorCount = 0; bool isSaneConfiguration = true; foreach (Player *player, m_game->players()) { if (player->isSpectator()) { // Spectator player controllers can be completely ignored here as // they do not count as active players and thus there is no need for // them to own at least one planet. continue; } ++nonSpectatorCount; bool foundPlanet = false; foreach (Planet *planet, m_game->planets()) { if (planet->player() == player) { foundPlanet = true; break; } } if (!foundPlanet) { isSaneConfiguration = false; break; } } okButton->setEnabled( (nonSpectatorCount >= 2) && isSaneConfiguration ); } diff --git a/dialogs/scoredlg.cc b/dialogs/scoredlg.cc index ed23ebb..02c24a5 100644 --- a/dialogs/scoredlg.cc +++ b/dialogs/scoredlg.cc @@ -1,58 +1,54 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 "scoredlg.h" -#include -#include - -#include #include #include #include ScoreDlg::ScoreDlg( QWidget *parent, const QString& title, QList players ) : QDialog(parent) { setObjectName( QLatin1String( "ScoreDlg" ) ); setModal( true ); setWindowTitle(title); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); QWidget *mainWidget = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); mainLayout->addWidget(mainWidget); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, &QDialogButtonBox::accepted, this, &ScoreDlg::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &ScoreDlg::reject); m_standingsWidget = new StandingsWidget(this, players); mainLayout->addWidget(m_standingsWidget ); mainLayout->addWidget(buttonBox); } ScoreDlg::~ScoreDlg() { } diff --git a/dialogs/scoredlg.h b/dialogs/scoredlg.h index aafb758..39369fb 100644 --- a/dialogs/scoredlg.h +++ b/dialogs/scoredlg.h @@ -1,46 +1,45 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 KONQUEST_SCOREDLG_H #define KONQUEST_SCOREDLG_H -#include #include #include "../players/player.h" #include "../view/standingswidget.h" class ScoreDlg : public QDialog { public: ScoreDlg( QWidget *parent, const QString& title, QList players ); ~ScoreDlg(); private: StandingsWidget *m_standingsWidget; }; #endif // KONQUEST_SCOREDLG_H diff --git a/mainwin.cc b/mainwin.cc index 6cf1703..8ab6511 100644 --- a/mainwin.cc +++ b/mainwin.cc @@ -1,245 +1,242 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 "mainwin.h" +#include #include -#include +#include #include -#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include "game.h" #include "localgame.h" #include "gameview.h" // KonquestMainWindow MainWindow::MainWindow() { setWindowTitle( i18n("Galactic Conquest") ); setupActions(); setupGameView(); setupGUI(); // The status bar. m_statusBarText = new QLabel(i18n("Galactic Conquest")); statusBar()->addWidget(m_statusBarText); } MainWindow::~MainWindow() { } QSize MainWindow::sizeHint() const { return KXmlGuiWindow::sizeHint().expandedTo(QSize(600, 650)); } void MainWindow::setupActions() { KStandardGameAction::gameNew( this, SLOT( startNewGame() ), actionCollection() ); KStandardGameAction::quit( this, SLOT( close() ), actionCollection() ); m_endTurnAction = KStandardGameAction::endTurn(this, NULL, actionCollection()); m_endTurnAction->setShortcut(Qt::CTRL + Qt::Key_E); m_endTurnAction->setEnabled(false); m_endGameAction = KStandardGameAction::end( this, NULL, actionCollection() ); m_endGameAction->setEnabled(false); //AB: there is no icon for disabled - KToolBar::insertButton shows the //different state - QAction not :-( m_measureAction = actionCollection()->addAction( QLatin1String( "game_measure" ) ); m_measureAction->setIcon( QIcon::fromTheme( QLatin1String( "go-jump" )) ); m_measureAction->setText( i18n("&Measure Distance") ); m_measureAction->setEnabled(false); // Show fleet overview m_fleetAction = actionCollection()->addAction( QLatin1String( "game_fleets" ) ); m_fleetAction->setIcon( QIcon::fromTheme( QLatin1String( "fork" )) ); m_fleetAction->setText( i18n("&Fleet Overview") ); m_fleetAction->setEnabled(false); // Toolbar addToolBar ( Qt::LeftToolBarArea, toolBar() ); toolBar()->setMovable(false); // docking area - messages m_messagesDock = new QDockWidget(i18n("Messages"), this); m_messagesDock->setObjectName("dock-messages"); addDockWidget(Qt::BottomDockWidgetArea, m_messagesDock); m_messagesAction = actionCollection()->addAction(QLatin1String("view_messages")); m_messagesAction->setText(i18n("Show &Messages")); m_messagesAction->setCheckable(true); m_messagesAction->setChecked(m_messagesDock->isVisible()); // The action signal "toggled" is fired even in case the state is changed // via code using setChecked(). "triggered" however is only fired if the // user actually triggered the change. // The dock signal "visibilityChanged" is fired if the dock is shown or // hidden. But this includes hidden in a tab as well. The action should not // represent the visibility state, but if the dock is present somewhere in // the GUI, regardless of currently visible in an active tab or invisible // in a not currently active tab. connect(m_messagesAction, &QAction::triggered, m_messagesDock, &QDockWidget::setVisible); connect(m_messagesDock, &QDockWidget::visibilityChanged, this, &MainWindow::updateMessagesActionSlot); // docking area - standings m_standingsDock = new QDockWidget(i18n("Standings"), this); m_standingsDock->setObjectName("dock-standings"); tabifyDockWidget(m_messagesDock, m_standingsDock); m_standingsAction = actionCollection()->addAction(QLatin1String("view_standings")); m_standingsAction->setIcon(QIcon::fromTheme(QLatin1String("help-contents"))); m_standingsAction->setText(i18n("Show &Standings")); m_standingsAction->setCheckable(true); m_standingsAction->setChecked(m_standingsDock->isVisible()); connect(m_standingsAction, &QAction::triggered, m_standingsDock, &QDockWidget::setVisible); connect(m_standingsDock, &QDockWidget::visibilityChanged, this, &MainWindow::updateStandingsActionSlot); } void MainWindow::setupGameView() { m_game = new LocalGame( this ); m_gameView = new GameView(this, m_game, m_messagesDock, m_standingsDock); setCentralWidget( m_gameView ); connect(m_game, &Game::gameMsg, m_gameView, &GameView::gameMsg); connect(m_gameView, &GameView::newGUIState, this, &MainWindow::guiStateChange); connect(m_measureAction, &QAction::triggered, m_gameView, &GameView::measureDistance); connect(m_fleetAction, &QAction::triggered, m_gameView, &GameView::showFleets); connect(m_endTurnAction, &QAction::triggered, m_gameView, &GameView::nextPlayer); connect(m_endGameAction, &QAction::triggered, m_gameView, &GameView::shutdownGame); } void MainWindow::setupGUI() { KXmlGuiWindow::setupGUI(); /** * @todo The docks should not be visible on the main screen, and neither * should it be possible to open the docks. During the game and later on, * this is handled by GameView::changeGameView() and by * MainWindow::guiStateChange(). Just the initial setup does not work that * way. - Rework the GUI setup sequence so that the following hack is not * required. */ m_messagesAction->setEnabled(false); m_standingsAction->setEnabled(false); m_messagesDock->toggleViewAction()->setEnabled(false); m_standingsDock->toggleViewAction()->setEnabled(false); m_messagesDock->hide(); m_standingsDock->hide(); } void MainWindow::startNewGame() { if (m_gameView->confirmNewGame()) { m_gameView->deleteLater(); m_game->deleteLater(); setupGameView(); m_gameView->startNewGame(); } } void MainWindow::guiStateChange( GUIState newState ) { if (newState == NONE) { m_gameView->deleteLater(); m_game->deleteLater(); this->setupGameView(); } // An alternative to disabling the "end turn" action during "send fleet // command sequence" is to simply abort this sequence if the user decides // to "end turn" before completion. /** * @todo The game view handles the state of the actions, so the game view * should be able to update the enabled state of the actions as well. This * should be implemented via signals, instead of copying the conditions here * again. */ m_endTurnAction ->setEnabled( m_game->isRunning() && (newState == SOURCE_PLANET) ); m_endGameAction ->setEnabled( m_game->isRunning() ); m_measureAction ->setEnabled( newState == SOURCE_PLANET ); m_fleetAction ->setEnabled( newState == SOURCE_PLANET ); m_messagesAction->setEnabled(m_game->isRunning()); m_standingsAction->setEnabled(m_game->isRunning()); m_messagesDock->toggleViewAction()->setEnabled(m_game->isRunning()); m_standingsDock->toggleViewAction()->setEnabled(m_game->isRunning()); m_statusBarText->setText(i18n("Turn # %1", m_game->turnCounter())); } void MainWindow::updateMessagesActionSlot() { m_messagesAction->setChecked(m_messagesDock->toggleViewAction()->isChecked()); } void MainWindow::updateStandingsActionSlot() { m_standingsAction->setChecked(m_standingsDock->toggleViewAction()->isChecked()); } diff --git a/map/map.h b/map/map.h index c27b67e..0f1bd7e 100644 --- a/map/map.h +++ b/map/map.h @@ -1,89 +1,89 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 KONQUEST_MAP_H #define KONQUEST_MAP_H -#include #include +#include #include "sector.h" #include "../players/player.h" class Map : public QObject { Q_OBJECT public: Map(int rows, int cols); virtual ~Map(); int rows() { return m_rows; } int columns() { return m_columns; } void addPlanet(Sector *sector, Player *player, int production, double killpercentage); Planet* addPlayerPlanetSomewhere(Player *player); Planet* addNeutralPlanetSomewhere(Player *neutral); bool removePlayerPlanet(Player *player); void removePlayerPlanets(Player *player); int playerPlanetCount(Player *player); void turnOverPlayerPlanets(Player* owner, Player* newOwner); void clearMap(); void resizeMap(int rows, int cols); void populateMap( const QList &players, Player *neutral, int numNeutralPlanets); double distance( Planet *p1, Planet *p2 ); Sector *sector(Coordinate coord) { if (coord.y() >= 0 && coord.y() < m_grid.size()) { if (coord.x() >= 0 && coord.x() < m_grid[coord.y()].size()) { return &m_grid[coord.y()][coord.x()]; } } return NULL; } QList planets(); protected slots: void childSectorUpdate(); signals: void update(); private: Sector* findRandomFreeSector(); QString UniquePlanetName(void); protected: // A map is a 2-D array of Sectors. QList > m_grid; int m_rows; // size of grid in sectors int m_columns; }; #endif // KONQUEST_MAP_H diff --git a/map/mapitems.cc b/map/mapitems.cc index 966a746..e11279e 100644 --- a/map/mapitems.cc +++ b/map/mapitems.cc @@ -1,277 +1,276 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2008-2009 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet Copyright 2011 Jeffrey Kelling 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 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 "mapitems.h" +#include #include #include -#include #include #include -#include -#include +#include #include "mapscene.h" #include "map.h" #include "../planet.h" /******************************** PlanetItem *******************************/ PlanetItem::PlanetItem (MapScene *scene, Sector *sector, Game *game) : QGraphicsObject(), m_scene(scene), m_sector(sector), m_game(game), m_hovered(false), m_selected(false), m_blinkState(false) { if (m_sector->planet() != NULL) { m_lookName = QString("planet_%1").arg(m_sector->planet()->planetLook() + 1); } setAcceptHoverEvents(true); m_blinkTimer = new QTimer(this); connect(m_blinkTimer, &QTimer::timeout, this, &PlanetItem::blinkPlanet); connect(m_sector, &Sector::update, this, &PlanetItem::updatePlanet); } void PlanetItem::updatePlanet() { Planet *planet = m_sector->planet(); if (planet != NULL) { m_lookName = QString("planet_%1").arg(planet->planetLook() + 1); update(); } } QRectF PlanetItem::boundingRect() const { qreal size = m_scene->getSectorSize(); return QRectF(m_sector->coord().y() * size + m_scene->itemsHorizontalOffset(), m_sector->coord().x() * size + m_scene->itemsVerticalOffset(), size, size); } void PlanetItem::paint(QPainter *p, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { if(!m_sector->planet()) return; // Display a frame around the planet if (!m_sector->planet()->player()->isNeutral()) { QBrush backBrush = p->brush(); backBrush.setColor(m_sector->planet()->player()->color()); backBrush.setStyle(Qt::SolidPattern); p->setOpacity(0.5); p->fillRect(boundingRect(), backBrush ); p->setOpacity(1); } // Display the planet qreal sectorSize = m_scene->getSectorSize(); QPointF sectorTopLeft(m_sector->coord().y() * sectorSize + m_scene->itemsHorizontalOffset(), m_sector->coord().x() * sectorSize + m_scene->itemsVerticalOffset()); QPixmap planetPix = renderPixmap(m_lookName, sectorSize, sectorSize); p->drawPixmap(sectorTopLeft, planetPix); if ( m_hovered || (m_selected && m_blinkState) ) { QBrush backBrush = p->brush(); backBrush.setColor(KColorScheme(QPalette::Active).background().color()); backBrush.setStyle(Qt::SolidPattern); p->setOpacity(0.3); p->fillRect(boundingRect(), backBrush ); p->setOpacity(1); } // Show the name of the planet (on top of bkgnd) QRectF TextRect(sectorTopLeft.x(), sectorTopLeft.y(), sectorSize, sectorSize); QPixmap nameBackgroundPix = renderPixmap("planet_name_background", sectorSize, sectorSize); p->drawPixmap(TextRect.topLeft(), nameBackgroundPix); p->setFont(QFont("Times", 16)); p->drawText(TextRect, m_sector->planet()->name()); // Show the number of ships on the planet. if((m_game->options().NeutralsShowShips || !m_sector->planet()->player()->isNeutral()) && ((!m_game->options().BlindMap || m_game->currentPlayer() == m_sector->planet()->player()) || (m_game->options().NeutralsShowShips && m_sector->planet()->player()->isNeutral()))) { QString shipCount = QString::number(m_sector->planet()->ships()); QPixmap shipsBackgroundPix = renderPixmap("planet_ship_count_background", sectorSize, sectorSize); p->drawPixmap(TextRect.topLeft(), shipsBackgroundPix); p->setFont(QFont("Times", 16)); p->drawText(TextRect, Qt::AlignRight | Qt::AlignBottom, shipCount); } } QPixmap PlanetItem::renderPixmap( const QString& svgId, int width, int height ) const { QPixmap pix; QString cacheKey = QString("%1%2x%3").arg(svgId).arg(width).arg(height); if (!m_scene->imageCache()->findPixmap(cacheKey, &pix)) { pix = QPixmap(width, height); pix.fill(Qt::transparent); QPainter pixPainter(&pix); m_scene->renderer()->render(&pixPainter, svgId, QRect(0, 0, width, height)); m_scene->imageCache()->insertPixmap(cacheKey, pix); } return pix; } void PlanetItem::hoverEnterEvent( QGraphicsSceneHoverEvent * /*event*/ ) { m_hovered = true; Planet *planet = m_sector->planet(); m_scene->displayPlanetInfo(planet); update(); } void PlanetItem::hoverLeaveEvent( QGraphicsSceneHoverEvent * /*event*/ ) { m_hovered = false; m_scene->displayPlanetInfo(NULL); update(); } void PlanetItem::mousePressEvent( QGraphicsSceneMouseEvent * /*event*/ ) { m_selected = true; m_blinkTimer->start(500); update(); emit planetItemSelected(this); } void PlanetItem::select( ) { m_selected = true; m_blinkTimer->start(500); update(); } void PlanetItem::unselect() { m_blinkTimer->stop(); m_blinkState = false; m_selected = false; update(); } void PlanetItem::blinkPlanet() { m_blinkState = !m_blinkState; update(); } /******************************** PlanetInfoItem *******************************/ PlanetInfoItem::PlanetInfoItem (Game *game) : QGraphicsItem(), m_game(game), m_textDoc(), m_planet(NULL) { } void PlanetInfoItem::setPlanet (Planet *planet) { m_planet = planet; QString text = i18n("Planet name: %1", planet->name()); if((m_game->options().NeutralsShowStats || !planet->player()->isNeutral()) && ((!m_game->options().BlindMap || m_game->currentPlayer() == planet->player()) || (m_game->options().NeutralsShowStats && planet->player()->isNeutral()))) { text += QString("
" + i18n("Owner: %1", planet->player()->coloredName()) + (m_game->options().NeutralsShowShips || !planet->player()->isNeutral() ? QString("
" + i18n("Ships: %1", planet->ships() )) : QString())); if( m_game->currentPlayer() == planet->player() ) { int shipsNeeded = 0; // determine how many ships will be needed by standing orders foreach(AttackFleet* fleet, planet->player()->standingOrders()) { if(fleet->source == planet) shipsNeeded += fleet->shipCount(); } if(shipsNeeded) text += QString("
" + i18nc("regarding standing orders", "Ships due: %1", shipsNeeded)); } text += QString("
" + i18n("Production: %1", planet->production() ) + "
" + i18n("Kill percent: %1", planet->killPercentage() )); } m_textDoc.setHtml(text); } QRectF PlanetInfoItem::boundingRect() const { return QRectF(0, 0, m_textDoc.idealWidth(), m_textDoc.size().height()); } void PlanetInfoItem::paint(QPainter *p, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { QBrush brush = p->brush(); brush.setColor(KColorScheme(QPalette::Active).background().color()); brush.setStyle(Qt::SolidPattern); p->setOpacity(0.7); p->fillRect(QRectF(0, 0, m_textDoc.idealWidth() + 1, m_textDoc.size().height() + 1), brush); p->setOpacity(1.0); m_textDoc.drawContents(p); } diff --git a/map/mapitems.h b/map/mapitems.h index fbfaaaf..a3985ee 100644 --- a/map/mapitems.h +++ b/map/mapitems.h @@ -1,94 +1,93 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 KONQUEST_MAPITEMS_H #define KONQUEST_MAPITEMS_H #include #include -#include #include "sector.h" class Game; class MapScene; class PlanetItem : public QGraphicsObject { Q_OBJECT public: explicit PlanetItem(MapScene *scene, Sector *sector, Game *game); ~PlanetItem() {} QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void hoverEnterEvent ( QGraphicsSceneHoverEvent *event ); void hoverLeaveEvent ( QGraphicsSceneHoverEvent *event ); void mousePressEvent ( QGraphicsSceneMouseEvent *event ); void unselect (); void select (); Sector *sector () { return m_sector; } signals: void planetItemSelected (PlanetItem *); private slots: void updatePlanet (); void blinkPlanet (); private: QPixmap renderPixmap( const QString& svgId, int width, int height ) const; MapScene *m_scene; Sector *m_sector; Game *m_game; bool m_hovered; bool m_selected; bool m_blinkState; QTimer *m_blinkTimer; QString m_lookName; }; class PlanetInfoItem : public QGraphicsItem { public: explicit PlanetInfoItem(Game*); ~PlanetInfoItem() {} QRectF boundingRect() const; void setPlanet (Planet *planet); Planet *planet () { return m_planet; } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); private: Game *m_game; QTextDocument m_textDoc; Planet *m_planet; }; #endif // KONQUEST_MAPITEMS_H diff --git a/map/mapscene.cc b/map/mapscene.cc index 8c1fcae..2158be4 100644 --- a/map/mapscene.cc +++ b/map/mapscene.cc @@ -1,255 +1,254 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 "mapscene.h" #include #include -#include #include "map.h" #include "mapitems.h" #include "../sector.h" #include "../images.h" #include "../game.h" #include "../planet.h" MapScene::MapScene (Game *game) : QGraphicsScene(), m_game(game), m_selectedPlanetItem(NULL), m_planetInfoItem(NULL), m_width(width()), m_height(height()) { m_renderer = new QSvgRenderer(IMAGES_SVG); m_imageCache = new KImageCache("konquest-pixmaps", 100000); } MapScene::~MapScene () { delete m_imageCache; delete m_renderer; } void MapScene::resizeScene(const QRectF& rect) { m_width = rect.width(); m_height = rect.height(); setSceneRect(rect); } void MapScene::selectPlanet(Planet *planet) { unselectPlanet(); foreach (PlanetItem *item, m_planetItems) { if (item->sector() == planet->sector()) { item->select(); m_selectedPlanetItem = item; break; } } } void MapScene::clearMap() { QGraphicsItem *item; while (items().count() > 0) { item = items()[0]; removeItem(item); delete item; } m_planetItems.clear(); m_planetInfoItem = NULL; m_selectedPlanetItem = NULL; } void MapScene::mapUpdate() { Sector *sector; clearMap(); if(m_game->isRunning()) { for (int i = 0 ; i < map()->rows() ; i++) { for (int j = 0 ; j < map()->columns() ; j++) { sector = map()->sector(Coordinate(j, i)); if (sector->hasPlanet()) { PlanetItem *item = new PlanetItem(this, sector, m_game); connect(item, &PlanetItem::planetItemSelected, this, &MapScene::planetItemSelected); item->setZValue(1.0); addItem(item); m_planetItems.append(item); } } } } } void MapScene::unselectPlanet() { if (m_selectedPlanetItem) { m_selectedPlanetItem->unselect(); m_selectedPlanetItem = NULL; } } void MapScene::planetItemSelected (PlanetItem *item) { if (m_selectedPlanetItem) unselectPlanet(); m_selectedPlanetItem = item; emit planetSelected(item->sector()->planet()); } void MapScene::drawBackground ( QPainter * painter, const QRectF & /*rect*/ ) { qreal sectorSize = getSectorSize(); qreal horizontalOffset = itemsHorizontalOffset(); qreal verticalOffset = itemsVerticalOffset(); qreal mapWidth = map()->columns()*sectorSize; qreal mapHeight = map()->rows()*sectorSize; QPen pen = painter->pen(); pen.setColor(Qt::black); pen.setWidth(1); pen.setStyle(Qt::SolidLine); painter->setPen(pen); painter->fillRect(0, 0, m_width, m_height, Qt::black); m_renderer->render(painter, "background", QRectF(0, 0, m_width, m_height)); m_renderer->render(painter, "screen", QRectF(horizontalOffset, verticalOffset, mapWidth, mapHeight)); painter->setOpacity(0.5); qreal lastLine = mapWidth + horizontalOffset; for (qreal i = horizontalOffset ; i <= lastLine ; i += sectorSize) { painter->drawLine(QPointF(i, verticalOffset), QPointF(i, mapHeight + verticalOffset)); } lastLine = mapHeight + verticalOffset; for (qreal j = verticalOffset ; j <= lastLine ; j += sectorSize) { painter->drawLine(QPointF(horizontalOffset, j), QPointF(mapWidth + horizontalOffset, j)); } } void MapScene::displayPlanetInfo(Planet *planet) { if (!planet) { if (m_planetInfoItem) { m_planetInfoItem->hide(); } return; } /** * @todo Figure out why coord.y and coord.x seem to be used the other way * around. */ QPointF pos( planet->sector()->coord().y() * getSectorSize() + itemsHorizontalOffset(), planet->sector()->coord().x() * getSectorSize() + itemsVerticalOffset() ); displayPlanetInfo(planet, pos); } void MapScene::displayPlanetInfo (Planet *planet, const QPointF &pos) { if (!planet) { if (m_planetInfoItem) { m_planetInfoItem->hide(); } return; } if (!m_planetInfoItem) { m_planetInfoItem = new PlanetInfoItem(m_game); addItem(m_planetInfoItem); } m_planetInfoItem->show(); m_planetInfoItem->setPlanet(planet); m_planetInfoItem->setZValue(1.5); m_planetInfoItem->moveBy( pos.x() - m_planetInfoItem->x(), pos.y() - m_planetInfoItem->y() ); // Move to stay in the game field. if (pos.x() > m_width / 2) { m_planetInfoItem->moveBy(-m_planetInfoItem->boundingRect().width(), 0); } if (pos.y() > m_height / 2) { m_planetInfoItem->moveBy(0, -m_planetInfoItem->boundingRect().height()); } update(); } qreal MapScene::getSectorSize() { qreal s_w = m_width / map()->columns(); qreal s_h = m_height / map()->rows(); return qMin(s_w, s_h); } qreal MapScene::itemsHorizontalOffset() { return (m_width - map()->columns() * getSectorSize()) / 2; } qreal MapScene::itemsVerticalOffset() { return (m_height - map()->rows() * getSectorSize()) / 2; } diff --git a/map/mapscene.h b/map/mapscene.h index 9bb438f..e585584 100644 --- a/map/mapscene.h +++ b/map/mapscene.h @@ -1,132 +1,134 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 KONQUEST_MAPSCENE_H #define KONQUEST_MAPSCENE_H -#include #include +#include + #include + #include "mapitems.h" #include "../game.h" class Planet; class PlanetItem; class PlanetInfoItem; class Map; class MapScene: public QGraphicsScene { Q_OBJECT public: explicit MapScene(Game *game); ~MapScene(); QSvgRenderer *renderer() const { return m_renderer; } KImageCache *imageCache() const { return m_imageCache; } Map *map() const { return m_game->map(); } void selectPlanet(Planet *planet); void unselectPlanet(); /** * Show planet information box. * * @param planet * planet for which to show planet information or NULL to hide possibly * shown planet information */ void displayPlanetInfo(Planet *planet); void drawBackground( QPainter * painter, const QRectF & rect ); /** * Get size of a sector in pixel. * * A sector is rendered as a square, so width and height are the same. The * size depends on the number of sectors per direction (horizontal and * vertical) as well as the dimensions of the board canvas. */ qreal getSectorSize(); /** * Get the horizontal offset. * * In case the board is tall, it is horizontally centered on the board * canvas. */ qreal itemsHorizontalOffset(); /** * Get the vertical offset. * * In case the board is wide, it is vertically centered on the board canvas. */ qreal itemsVerticalOffset(); void resizeScene(const QRectF& rect); void clearMap(); void mapUpdate(); signals: void planetSelected( Planet * ); private slots: void planetItemSelected (PlanetItem *); private: /** * Show planet information box. * * @param planet * planet for which to show planet information or NULL to hide possibly * shown planet information * * @param pos * position relative to upper left edge of the board */ void displayPlanetInfo(Planet *planet, const QPointF &pos); Game *m_game; QSvgRenderer *m_renderer; KImageCache *m_imageCache; PlanetItem *m_selectedPlanetItem; PlanetInfoItem *m_planetInfoItem; QVector m_planetItems; qreal m_width; qreal m_height; }; #endif // KONQUEST_MAPSCENE_H diff --git a/minimapview.cc b/minimapview.cc index 84139c7..2e64914 100644 --- a/minimapview.cc +++ b/minimapview.cc @@ -1,136 +1,135 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet Copyright Sean D'Epagnier 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 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 "minimapview.h" #include #include -#include #include "planet.h" #include "players/player.h" MiniMapView::MiniMapView(QWidget *parent) : QWidget(parent), m_map(0), m_selection(-1, -1) { QPalette pal = palette(); pal.setColor(backgroundRole(), Qt::black); setPalette(pal); setMinimumSize(100, 100); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } MiniMapView::~MiniMapView() { } void MiniMapView::setMap(Map *map) { m_map = map; connect(m_map, &Map::update, this, static_cast(&QWidget::update)); } void MiniMapView::CalculateOffsets(float §orSize, float &woffset, float &hoffset) { sectorSize = ((float)width())/m_map->columns(); if (height()/m_map->rows() < sectorSize) sectorSize = ((float)height())/m_map->rows(); woffset = ((float)width() - m_map->columns()*sectorSize)/2; hoffset = ((float)height() - m_map->rows()*sectorSize)/2; } void MiniMapView::mousePressEvent(QMouseEvent *event) { float sectorSize, woffset, hoffset; CalculateOffsets(sectorSize, woffset, hoffset); m_selection = Coordinate((event->x() - woffset) / sectorSize, (event->y() - hoffset) / sectorSize); const Sector *sector = m_map->sector(m_selection); if (sector && !sector->hasPlanet()) m_selection = Coordinate(-1, -1); emit sectorSelected(m_selection); } void MiniMapView::paintEvent(QPaintEvent * /*event*/) { QPainter painter(this); float sectorSize, woffset, hoffset; CalculateOffsets(sectorSize, woffset, hoffset); // Draw the black background painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::black); painter.setBrush(Qt::black); painter.drawRect(QRectF(woffset, hoffset, m_map->columns() * sectorSize, m_map->rows() * sectorSize)); // Draw selection if (hasSelection()) { painter.setBrush(Qt::cyan); painter.drawRect(QRectF( woffset + m_selection.x() * sectorSize, hoffset + m_selection.y() * sectorSize, sectorSize, sectorSize )); } // Now draw the planets... for (int col = 0 ; col < m_map->columns() ; col++) { for (int row = 0 ; row < m_map->rows() ; row++) { QPoint pt(col, row); Planet *planet = m_map->sector(pt)->planet(); if (planet) { Player *player = planet->player(); if (player) { painter.setBrush(player->color()); // Draw a circle in the planets color to show the planet. painter.drawEllipse(QRectF( woffset + col * sectorSize, hoffset + row * sectorSize, sectorSize, sectorSize )); } } } } } diff --git a/players/computerplayer.cpp b/players/computerplayer.cpp index 73032e0..0b64666 100644 --- a/players/computerplayer.cpp +++ b/players/computerplayer.cpp @@ -1,41 +1,40 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet 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 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 "computerplayer.h" #include "../game.h" -#include #include #include ComputerPlayer::ComputerPlayer(Game *game, const QString &newName, const QColor &color) : Player(game, newName, color) { } bool ComputerPlayer::isAiPlayer() { return true; } diff --git a/players/neutralplayer.cpp b/players/neutralplayer.cpp index cdef5e2..cf8d511 100644 --- a/players/neutralplayer.cpp +++ b/players/neutralplayer.cpp @@ -1,74 +1,72 @@ /* Copyright 2006 Pierre Ducroquet 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 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 "neutralplayer.h" #include "../game.h" #include "../planet.h" -#include #include -#include NeutralPlayer::NeutralPlayer(Game *game) : Player(game, QString(), Qt::gray) { } bool NeutralPlayer::isNeutral() { return true; } bool NeutralPlayer::isDead() { return false; } void NeutralPlayer::play() { //qDebug() << "NeutralPlayer::play"; // Go on each attack... foreach (Player *player, m_game->players()) { player->resetTurnStats(); foreach (AttackFleet *fleet, player->attackList()) { if (m_game->doFleetArrival(fleet)) { player->attackDone(fleet); fleet->deleteLater(); } else { // Only add the number of ships of the fleet to the player's // total fleet size if the fleet does not arrive this turn. player->statShipCount(fleet->shipCount()); } } } // Go over each planet, adding its ships foreach (Planet *planet, m_game->map()->planets()) { //qDebug() << "Turn for planet " << planet->name(); planet->turn(m_game->options()); } m_game->findWinner(); // After all that mess... It's done emit(donePlaying()); } diff --git a/players/player.h b/players/player.h index acf92ff..c476f25 100644 --- a/players/player.h +++ b/players/player.h @@ -1,133 +1,133 @@ /* Copyright 2006 Pierre Ducroquet 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 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 PLAYER_H #define PLAYER_H -#include #include +#include #include "../fleet.h" class Game; class Planet; class Player : public QState { Q_OBJECT public: explicit Player(Game *game, const QString &newName, const QColor &color); virtual bool isDead(); virtual bool isNeutral(); virtual bool isAiPlayer(); virtual bool isSpectator(); // Getters and Setters for some fundamental properties. QString name() const { return m_name; } void setName(QString name) { m_name = name; } QString coloredName() const; QColor& color() { return m_color; } Game *game() const { return m_game; } // Statistics collection void statShipsBuilt( int x ) { m_turnProduction += x; m_shipsBuilt += x; } void statPlanetsConquered( int x ) { m_planetsConquered += x; } void statFleetsLaunched( int x ) { m_fleetsLaunched += x; } void statEnemyFleetsDestroyed( int x ) { m_enemyFleetsDestroyed += x; } void statEnemyShipsDestroyed( int x ) { m_enemyShipsDestroyed += x; } int shipsBuilt() const { return m_shipsBuilt; } int planetsConquered() const { return m_planetsConquered; } int fleetsLaunched() const { return m_fleetsLaunched; } int enemyFleetsDestroyed() const { return m_enemyFleetsDestroyed; } int enemyShipsDestroyed() const { return m_enemyShipsDestroyed; } void resetTurnStats(); void statShipCount(int x) { m_turnShips += x; } int turnProduction() const { return m_turnProduction; } int turnShips() const { return m_turnShips; } AttackFleetList attackList() { return m_attackList; } AttackFleetList newAttacks() { return m_newAttacks; } AttackFleetList standingOrders() { return m_standingOrders; } void attackDone(AttackFleet *fleet); void addAttackFleet(AttackFleet *fleet); void addStandingOrder(AttackFleet *fleet); void cancelNewAttack(AttackFleet *fleet); void deleteStandingOrders(Planet *planet); protected: virtual void play() = 0; virtual void onEntry (QEvent *event); virtual void onExit (QEvent *event); Game *m_game; signals: void donePlaying(); public slots: private slots: private: // Attack fleets sent by this player that are still moving AttackFleetList m_attackList; // Fleets to send at the end of this turn AttackFleetList m_newAttacks; AttackFleetList m_standingOrders; // Some fundamental properties. QString m_name; QColor m_color; // statistics counters int m_shipsBuilt; int m_planetsConquered; int m_fleetsLaunched; int m_enemyFleetsDestroyed; int m_enemyShipsDestroyed; int m_turnProduction; ///< number of ships produced in this turn int m_turnShips; ///< number of all available player ships in this turn /** * @todo This is a bad GUI hack. The game selection grid is handled by just * a list of player instances. This property stores the GUI name of the class * used to create this player. For example a player of "AiDefaultWeak" class * will be created via "AiDefaultWeakGui" with the GUI name of "Default Weak". * That GUI name is stored here. */ QString m_guiName; public: void setGuiName(const QString &guiName) { m_guiName = guiName; } QString guiName() const { return m_guiName; } }; #endif // PLAYER_H diff --git a/view/standingswidget.cpp b/view/standingswidget.cpp index 2c9f717..190c146 100644 --- a/view/standingswidget.cpp +++ b/view/standingswidget.cpp @@ -1,179 +1,178 @@ /* Copyright 2003 Russell Steffen Copyright 2003 Stephan Zehetner Copyright 2006 Dmitry Suzdalev Copyright 2006 Inge Wallin Copyright 2006 Pierre Ducroquet Copyright 2013 Alexander Schuch 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 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 "standingswidget.h" #include #include #include +#include #include -#include -#include StandingsWidget::StandingsWidget(QWidget *parent) : QWidget(parent) { setupTable(); } /** * @note Use "delegating constructor" once C++11 is required by KDE. */ StandingsWidget::StandingsWidget(QWidget *parent, const QList players) : // StandingsWidget(parent) QWidget(parent) { setupTable(); update(players); } StandingsWidget::~StandingsWidget() { } QSize StandingsWidget::sizeHint() const { int w = m_standingsTable->verticalHeader()->width(); int h = m_standingsTable->horizontalHeader()->height(); for (int col = 0; col < m_standingsTable->columnCount(); ++col) { w += m_standingsTable->columnWidth(col); } for (int row = 0; row < m_standingsTable->rowCount(); ++row) { h += m_standingsTable->rowHeight(row); } /** * @todo The size calculated here does not yet prevent scrollbars to be * shown for the table. Figure out the offsets needed to be added and remove * the hard-coded numbers below! */ return QSize(w, h) + QSize(m_standingsTable->columnCount() - 1, 40); } void StandingsWidget::update(const QList players ) { m_standingsTable->setRowCount(players.count()); m_standingsTable->clearContents(); m_standingsTable->setSortingEnabled(false); int row = 0; QTableWidgetItem *item; foreach (Player *curPlayer, players) { item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->name()); item->setData(Qt::DecorationRole, curPlayer->color()); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 0, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->shipsBuilt()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 1, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->planetsConquered()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 2, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->fleetsLaunched()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 3, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->enemyFleetsDestroyed()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 4, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->enemyShipsDestroyed()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 5, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->turnProduction()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 6, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, curPlayer->turnShips()); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setFlags(Qt::ItemIsEnabled); m_standingsTable->setItem(row, 7, item); ++row; } m_standingsTable->setSortingEnabled(true); m_standingsTable->resizeColumnsToContents(); } void StandingsWidget::setupTable() { setObjectName(QLatin1String("widget-standings")); QVBoxLayout *main = new QVBoxLayout(this); m_standingsTable = new QTableWidget(); m_standingsTable->setColumnCount(8); m_standingsTable->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); m_standingsTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); m_standingsTable->setSelectionMode(QAbstractItemView::NoSelection); QStringList headerLabels; headerLabels << i18nc("The player name", "Player") << i18n("Ships\nBuilt") << i18n("Planets\nConquered") << i18n("Fleets\nLaunched") << i18n("Fleets\nDestroyed") << i18n("Ships\nDestroyed") << i18n("Current\nProduction") << i18n("Current\nFleet Size"); m_standingsTable->setHorizontalHeaderLabels(headerLabels); m_standingsTable->verticalHeader()->hide(); main->addWidget(m_standingsTable); }