diff --git a/common/.directory b/common/.directory new file mode 100644 index 00000000..44c54669 --- /dev/null +++ b/common/.directory @@ -0,0 +1,3 @@ +[Dolphin] +Timestamp=2009,10,26,13,45,44 +ViewMode=1 diff --git a/common/common.pro b/common/common.pro deleted file mode 100644 index 6419dcc3..00000000 --- a/common/common.pro +++ /dev/null @@ -1,16 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) So. Okt 25 12:02:12 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . -MOC_DIR = build -OBJECTS_DIR = build - -# Input -HEADERS += protocol.h widget.h protocol_items.h -SOURCES += main.cpp protocol.cpp widget.cpp protocol_items.cpp - -CONFIG += qt debug diff --git a/common/main.cpp b/common/main.cpp deleted file mode 100644 index 866537ff..00000000 --- a/common/main.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include -#include -#include "widget.h" - -int main(int argc, char *argv[]) -{ -// qInstallMsgHandler(myMessageOutput); - QApplication app(argc, argv); - QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); - - Widget *widget = new Widget; - widget->show(); - - return app.exec(); -} - - diff --git a/common/protocol.cpp b/common/protocol.cpp index 40208051..c0375ffc 100644 --- a/common/protocol.cpp +++ b/common/protocol.cpp @@ -63,6 +63,9 @@ ProtocolItem *ProtocolItem::getNewItem(const QString &name) void ProtocolItem::initializeHash() { + if (!itemNameHash.isEmpty()) + return; + initializeHashAuto(); itemNameHash.insert("resp", ProtocolResponse::newItem); ProtocolResponse::initializeHash(); diff --git a/common/protocol.h b/common/protocol.h index 24b6e865..1a27d500 100644 --- a/common/protocol.h +++ b/common/protocol.h @@ -28,6 +28,7 @@ protected: private: static void initializeHashAuto(); public: + static const int protocolVersion = 4; ProtocolItem(const QString &_itemName); static void initializeHash(); static ProtocolItem *getNewItem(const QString &name); @@ -36,6 +37,7 @@ public: }; class Command : public ProtocolItem { + Q_OBJECT private: int cmdId; static int lastCmdId; diff --git a/common/rng_abstract.cpp b/common/rng_abstract.cpp new file mode 100644 index 00000000..eb2e38ac --- /dev/null +++ b/common/rng_abstract.cpp @@ -0,0 +1,4 @@ +#include "rng_abstract.h" +#include "rng_qt.h" + +RNG_Abstract *rng = new RNG_Qt; diff --git a/common/rng_abstract.h b/common/rng_abstract.h new file mode 100644 index 00000000..739efeb3 --- /dev/null +++ b/common/rng_abstract.h @@ -0,0 +1,15 @@ +#ifndef RNG_ABSTRACT_H +#define RNG_ABSTRACT_H + +#include + +class RNG_Abstract : public QObject { + Q_OBJECT +public: + RNG_Abstract(QObject *parent = 0) : QObject(parent) { } + virtual unsigned int getNumber(unsigned int min, unsigned int max) = 0; +}; + +extern RNG_Abstract *rng; + +#endif diff --git a/servatrice/src/rng_qt.cpp b/common/rng_qt.cpp similarity index 94% rename from servatrice/src/rng_qt.cpp rename to common/rng_qt.cpp index 97440800..30cb8b34 100644 --- a/servatrice/src/rng_qt.cpp +++ b/common/rng_qt.cpp @@ -3,7 +3,7 @@ #include RNG_Qt::RNG_Qt(QObject *parent) - : AbstractRNG(parent) + : RNG_Abstract(parent) { int seed = QDateTime::currentDateTime().toTime_t(); qDebug(QString("qsrand(%1)").arg(seed).toLatin1()); diff --git a/servatrice/src/rng_qt.h b/common/rng_qt.h similarity index 71% rename from servatrice/src/rng_qt.h rename to common/rng_qt.h index 3b2434ad..e30719ef 100644 --- a/servatrice/src/rng_qt.h +++ b/common/rng_qt.h @@ -1,9 +1,9 @@ #ifndef RNG_QT_H #define RNG_QT_H -#include "abstractrng.h" +#include "rng_abstract.h" -class RNG_Qt : public AbstractRNG { +class RNG_Qt : public RNG_Abstract { Q_OBJECT public: RNG_Qt(QObject *parent = 0); diff --git a/common/server.cpp b/common/server.cpp new file mode 100644 index 00000000..bcd5ebb3 --- /dev/null +++ b/common/server.cpp @@ -0,0 +1,89 @@ +/*************************************************************************** + * Copyright (C) 2008 by Max-Wilhelm Bruker * + * brukie@laptop * + * * + * 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., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include "server.h" +#include "server_game.h" +#include "server_counter.h" +#include "server_chatchannel.h" + +Server::Server(QObject *parent) + : QObject(parent), nextGameId(0) +{ +} + +Server::~Server() +{ +} + +Server_Game *Server::createGame(const QString &description, const QString &password, int maxPlayers, bool spectatorsAllowed, const QString &creator) +{ + Server_Game *newGame = new Server_Game(creator, nextGameId++, description, password, maxPlayers, spectatorsAllowed, this); + games.insert(newGame->getGameId(), newGame); + connect(newGame, SIGNAL(gameClosing()), this, SLOT(gameClosing())); + + broadcastGameListUpdate(newGame); + + return newGame; +} + +void Server::addClient(Server_ProtocolHandler *client) +{ + clients << client; +} + +void Server::removeClient(Server_ProtocolHandler *client) +{ + clients.removeAt(clients.indexOf(client)); + qDebug(QString("Server::removeClient: %1 clients left").arg(clients.size()).toLatin1()); +} + +Server_Game *Server::getGame(int gameId) const +{ + return games.value(gameId); +} + +void Server::broadcastGameListUpdate(Server_Game *game) +{ +/* QString line = game->getGameListLine(); + for (int i = 0; i < clients.size(); i++) + if (clients[i]->getAcceptsGameListChanges()) + clients[i]->msg(line); +*/} + +void Server::broadcastChannelUpdate() +{ +/* QString line = qobject_cast(sender())->getChannelListLine(); + for (int i = 0; i < players.size(); ++i) + if (players[i]->getAcceptsChatChannelListChanges()) + players[i]->msg(line); +*/} + +void Server::gameClosing() +{ + qDebug("Server::gameClosing"); + Server_Game *game = static_cast(sender()); + broadcastGameListUpdate(game); + games.remove(games.key(game)); +} + +void Server::addChatChannel(Server_ChatChannel *newChannel) +{ + chatChannels.insert(newChannel->getName(), newChannel); + connect(newChannel, SIGNAL(channelInfoChanged()), this, SLOT(broadcastChannelUpdate())); +} diff --git a/common/server.h b/common/server.h new file mode 100644 index 00000000..1a99f853 --- /dev/null +++ b/common/server.h @@ -0,0 +1,42 @@ +#ifndef SERVER_H +#define SERVER_H + +#include +#include +#include + +class Server_Game; +class Server_ChatChannel; +class Server_ProtocolHandler; + +enum AuthenticationResult { PasswordWrong = 0, PasswordRight = 1, UnknownUser = 2 }; + +class Server : public QObject +{ + Q_OBJECT +private slots: + void gameClosing(); + void broadcastChannelUpdate(); +public: + Server(QObject *parent = 0); + ~Server(); + virtual AuthenticationResult checkUserPassword(const QString &user, const QString &password) = 0; + QList getGames() const { return games.values(); } + Server_Game *getGame(int gameId) const; + const QMap &getChatChannels() { return chatChannels; } + void broadcastGameListUpdate(Server_Game *game); + + void addClient(Server_ProtocolHandler *player); + void removeClient(Server_ProtocolHandler *player); + virtual QStringList getLoginMessage() const = 0; + Server_Game *createGame(const QString &description, const QString &password, int maxPlayers, bool spectatorsAllowed, const QString &playerName); +private: + QMap games; + QList clients; + QMap chatChannels; +protected: + int nextGameId; + void addChatChannel(Server_ChatChannel *newChannel); +}; + +#endif diff --git a/common/server_arrow.h b/common/server_arrow.h new file mode 100644 index 00000000..216d6246 --- /dev/null +++ b/common/server_arrow.h @@ -0,0 +1,20 @@ +#ifndef SERVER_ARROW_H +#define SERVER_ARROW_H + +class Server_Card; + +class Server_Arrow { +private: + int id; + Server_Card *startCard, *targetCard; + int color; +public: + Server_Arrow(int _id, Server_Card *_startCard, Server_Card *_targetCard, int _color) + : id(_id), startCard(_startCard), targetCard(_targetCard), color(_color) { } + int getId() const { return id; } + Server_Card *getStartCard() const { return startCard; } + Server_Card *getTargetCard() const { return targetCard; } + int getColor() const { return color; } +}; + +#endif \ No newline at end of file diff --git a/servatrice/src/card.cpp b/common/server_card.cpp similarity index 90% rename from servatrice/src/card.cpp rename to common/server_card.cpp index f3e8e58d..505c70d4 100644 --- a/servatrice/src/card.cpp +++ b/common/server_card.cpp @@ -17,19 +17,19 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include "card.h" +#include "server_card.h" -Card::Card(QString _name, int _id, int _coord_x, int _coord_y) +Server_Card::Server_Card(QString _name, int _id, int _coord_x, int _coord_y) : id(_id), coord_x(_coord_x), coord_y(_coord_y), name(_name), counters(0), tapped(false), attacking(false), facedown(false), annotation(QString()), doesntUntap(false) { } -Card::~Card() +Server_Card::~Server_Card() { } -void Card::resetState() +void Server_Card::resetState() { setCoords(0, 0); setCounters(0); @@ -40,7 +40,7 @@ void Card::resetState() setDoesntUntap(false); } -bool Card::setAttribute(const QString &aname, const QString &avalue, bool allCards) +bool Server_Card::setAttribute(const QString &aname, const QString &avalue, bool allCards) { if (aname == "counters") { bool ok; diff --git a/servatrice/src/card.h b/common/server_card.h similarity index 89% rename from servatrice/src/card.h rename to common/server_card.h index 6ee3c88f..f8090701 100644 --- a/servatrice/src/card.h +++ b/common/server_card.h @@ -17,16 +17,16 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#ifndef CARD_H -#define CARD_H +#ifndef SERVER_CARD_H +#define SERVER_CARD_H #include -class PlayerZone; +class Server_CardZone; -class Card { +class Server_Card { private: - PlayerZone *zone; + Server_CardZone *zone; int id; int coord_x, coord_y; QString name; @@ -37,11 +37,11 @@ private: QString annotation; bool doesntUntap; public: - Card(QString _name, int _id, int _coord_x, int _coord_y); - ~Card(); + Server_Card(QString _name, int _id, int _coord_x, int _coord_y); + ~Server_Card(); - PlayerZone *getZone() const { return zone; } - void setZone(PlayerZone *_zone) { zone = _zone; } + Server_CardZone *getZone() const { return zone; } + void setZone(Server_CardZone *_zone) { zone = _zone; } int getId() const { return id; } int getX() const { return coord_x; } diff --git a/servatrice/src/playerzone.cpp b/common/server_cardzone.cpp similarity index 77% rename from servatrice/src/playerzone.cpp rename to common/server_cardzone.cpp index 1192cf8d..2913256e 100644 --- a/servatrice/src/playerzone.cpp +++ b/common/server_cardzone.cpp @@ -17,36 +17,36 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include "playerzone.h" -#include "abstractrng.h" -#include "card.h" +#include "server_cardzone.h" +#include "server_card.h" +#include "rng_abstract.h" -PlayerZone::PlayerZone(Player *_player, const QString &_name, bool _has_coords, ZoneType _type) +Server_CardZone::Server_CardZone(Server_Player *_player, const QString &_name, bool _has_coords, ZoneType _type) : player(_player), name(_name), has_coords(_has_coords), type(_type), cardsBeingLookedAt(0) { } -PlayerZone::~PlayerZone() +Server_CardZone::~Server_CardZone() { - qDebug(QString("PlayerZone destructor: %1").arg(name).toLatin1()); + qDebug(QString("Server_CardZone destructor: %1").arg(name).toLatin1()); clear(); } -void PlayerZone::shuffle() +void Server_CardZone::shuffle() { - QList temp; + QList temp; for (int i = cards.size(); i; i--) temp.append(cards.takeAt(rng->getNumber(0, i - 1))); cards = temp; } -Card *PlayerZone::getCard(int id, bool remove, int *position) +Server_Card *Server_CardZone::getCard(int id, bool remove, int *position) { if (type != HiddenZone) { - QListIterator CardIterator(cards); + QListIterator CardIterator(cards); int i = 0; while (CardIterator.hasNext()) { - Card *tmp = CardIterator.next(); + Server_Card *tmp = CardIterator.next(); if (tmp->getId() == id) { if (remove) { cards.removeAt(i); @@ -62,7 +62,7 @@ Card *PlayerZone::getCard(int id, bool remove, int *position) } else { if ((id >= cards.size()) || (id < 0)) return NULL; - Card *tmp = cards[id]; + Server_Card *tmp = cards[id]; if (remove) { cards.removeAt(id); tmp->setZone(0); @@ -73,7 +73,7 @@ Card *PlayerZone::getCard(int id, bool remove, int *position) } } -void PlayerZone::insertCard(Card *card, int x, int y) +void Server_CardZone::insertCard(Server_Card *card, int x, int y) { if (hasCoords()) { card->setCoords(x, y); @@ -85,7 +85,7 @@ void PlayerZone::insertCard(Card *card, int x, int y) card->setZone(this); } -void PlayerZone::clear() +void Server_CardZone::clear() { for (int i = 0; i < cards.size(); i++) delete cards.at(i); diff --git a/servatrice/src/playerzone.h b/common/server_cardzone.h similarity index 83% rename from servatrice/src/playerzone.h rename to common/server_cardzone.h index 3814af36..03d97b24 100644 --- a/servatrice/src/playerzone.h +++ b/common/server_cardzone.h @@ -17,17 +17,16 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#ifndef PLAYERZONE_H -#define PLAYERZONE_H +#ifndef SERVER_CARDZONE_H +#define SERVER_CARDZONE_H #include #include -class Card; -class ServerSocket; -class Player; +class Server_Card; +class Server_Player; -class PlayerZone { +class Server_CardZone { public: // PrivateZone: Contents of the zone are always visible to the owner, // but not to anyone else. @@ -39,26 +38,26 @@ public: // list index, whereas cards in any other zone are referenced by their ids. enum ZoneType { PrivateZone, PublicZone, HiddenZone }; private: - Player *player; + Server_Player *player; QString name; bool has_coords; ZoneType type; int cardsBeingLookedAt; public: - PlayerZone(Player *_player, const QString &_name, bool _has_coords, ZoneType _type); - ~PlayerZone(); + Server_CardZone(Server_Player *_player, const QString &_name, bool _has_coords, ZoneType _type); + ~Server_CardZone(); - Card *getCard(int id, bool remove, int *position = NULL); + Server_Card *getCard(int id, bool remove, int *position = NULL); int getCardsBeingLookedAt() const { return cardsBeingLookedAt; } void setCardsBeingLookedAt(int _cardsBeingLookedAt) { cardsBeingLookedAt = _cardsBeingLookedAt; } bool hasCoords() const { return has_coords; } ZoneType getType() const { return type; } QString getName() const { return name; } - Player *getPlayer() const { return player; } + Server_Player *getPlayer() const { return player; } - QList cards; - void insertCard(Card *card, int x, int y); + QList cards; + void insertCard(Server_Card *card, int x, int y); void shuffle(); void clear(); }; diff --git a/common/server_chatchannel.cpp b/common/server_chatchannel.cpp new file mode 100644 index 00000000..a1559ba4 --- /dev/null +++ b/common/server_chatchannel.cpp @@ -0,0 +1,46 @@ +#include "server_chatchannel.h" +#include "server_protocolhandler.h" + +Server_ChatChannel::Server_ChatChannel(const QString &_name, const QString &_description, bool _autoJoin, const QStringList &_joinMessage) + : name(_name), description(_description), autoJoin(_autoJoin), joinMessage(_joinMessage) +{ +} + +void Server_ChatChannel::addClient(Server_ProtocolHandler *client) +{ +/* QString str = QString("chat|join_channel|%1|%2").arg(name).arg(player->getPlayerName()); + for (int i = 0; i < size(); ++i) + at(i)->msg(str); + + append(player); + + for (int i = 0; i < size(); ++i) + player->msg(QString("chat|list_players|%1|%2").arg(name).arg(at(i)->getPlayerName())); + for (int i = 0; i < joinMessage.size(); ++i) + player->msg(QString("chat|server_message|%1|%2").arg(name).arg(joinMessage[i])); + + emit channelInfoChanged(); +*/} + +void Server_ChatChannel::removeClient(Server_ProtocolHandler *client) +{ +/* QString str = QString("chat|leave_channel|%1|%2").arg(name).arg(player->getPlayerName()); + + removeAt(indexOf(player)); + for (int i = 0; i < size(); ++i) + at(i)->msg(str); + + emit channelInfoChanged(); +*/} + +void Server_ChatChannel::say(Server_ProtocolHandler *client, const QString &s) +{ +/* QString str = QString("chat|say|%1|%2|%3").arg(name).arg(player->getPlayerName()).arg(s); + for (int i = 0; i < size(); ++i) + at(i)->msg(str); +*/} + +QString Server_ChatChannel::getChannelListLine() const +{ +// return QString("chat|list_channels|%1|%2|%3|%4").arg(name).arg(description).arg(size()).arg(autoJoin ? 1 : 0); +} diff --git a/servatrice/src/chatchannel.h b/common/server_chatchannel.h similarity index 52% rename from servatrice/src/chatchannel.h rename to common/server_chatchannel.h index c7ca5b76..05afd99f 100644 --- a/servatrice/src/chatchannel.h +++ b/common/server_chatchannel.h @@ -5,9 +5,9 @@ #include #include -class ServerSocket; +class Server_ProtocolHandler; -class ChatChannel : public QObject, public QList { +class Server_ChatChannel : public QObject, public QList { Q_OBJECT signals: void channelInfoChanged(); @@ -17,13 +17,13 @@ private: bool autoJoin; QStringList joinMessage; public: - ChatChannel(const QString &_name, const QString &_description, bool _autoJoin, const QStringList &_joinMessage); + Server_ChatChannel(const QString &_name, const QString &_description, bool _autoJoin, const QStringList &_joinMessage); QString getName() const { return name; } QString getDescription() const { return description; } bool getAutoJoin() const { return autoJoin; } - void addPlayer(ServerSocket *player); - void removePlayer(ServerSocket *player); - void say(ServerSocket *player, const QString &s); + void addClient(Server_ProtocolHandler *client); + void removeClient(Server_ProtocolHandler *client); + void say(Server_ProtocolHandler *client, const QString &s); QString getChannelListLine() const; }; diff --git a/servatrice/src/counter.h b/common/server_counter.h similarity index 87% rename from servatrice/src/counter.h rename to common/server_counter.h index c9d96028..30568ada 100644 --- a/servatrice/src/counter.h +++ b/common/server_counter.h @@ -17,12 +17,12 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#ifndef COUNTER_H -#define COUNTER_H +#ifndef SERVER_COUNTER_H +#define SERVER_COUNTER_H #include -class Counter { +class Server_Counter { protected: int id; QString name; @@ -30,8 +30,8 @@ protected: int radius; int count; public: - Counter(int _id, const QString &_name, int _color, int _radius, int _count = 0) : id(_id), name(_name), color(_color), radius(_radius), count(_count) { } - ~Counter() { } + Server_Counter(int _id, const QString &_name, int _color, int _radius, int _count = 0) : id(_id), name(_name), color(_color), radius(_radius), count(_count) { } + ~Server_Counter() { } int getId() const { return id; } QString getName() const { return name; } int getColor() const { return color; } diff --git a/servatrice/src/servergame.cpp b/common/server_game.cpp similarity index 75% rename from servatrice/src/servergame.cpp rename to common/server_game.cpp index b65f176a..7d2f8d97 100644 --- a/servatrice/src/servergame.cpp +++ b/common/server_game.cpp @@ -18,22 +18,22 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "server.h" -#include "servergame.h" -#include "serversocket.h" -#include "arrow.h" +#include "server_game.h" +#include "server_protocolhandler.h" +#include "server_arrow.h" #include -ServerGame::ServerGame(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent) +Server_Game::Server_Game(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent) : QObject(parent), gameStarted(false), gameId(_gameId), description(_description), password(_password), maxPlayers(_maxPlayers), spectatorsAllowed(_spectatorsAllowed) { creator = addPlayer(_creator, false); } -ServerGame::~ServerGame() +Server_Game::~Server_Game() { broadcastEvent("game_closed", 0); - QMapIterator playerIterator(players); + QMapIterator playerIterator(players); while (playerIterator.hasNext()) delete playerIterator.next().value(); players.clear(); @@ -42,10 +42,10 @@ ServerGame::~ServerGame() spectators.clear(); emit gameClosing(); - qDebug("ServerGame destructor"); + qDebug("Server_Game destructor"); } -QString ServerGame::getGameListLine() const +QString Server_Game::getGameListLine() const { if (players.isEmpty()) return QString("list_games|%1|||0|%2||0|0").arg(gameId).arg(maxPlayers); @@ -62,32 +62,32 @@ QString ServerGame::getGameListLine() const } } -void ServerGame::broadcastEvent(const QString &eventStr, Player *player) +void Server_Game::broadcastEvent(const QString &eventStr, Server_Player *player) { - QList allClients = QList() << players.values() << spectators; + QList allClients = QList() << players.values() << spectators; for (int i = 0; i < allClients.size(); ++i) allClients[i]->publicEvent(eventStr, player); } -void ServerGame::startGameIfReady() +void Server_Game::startGameIfReady() { if (players.size() < maxPlayers) return; - QMapIterator playerIterator(players); + QMapIterator playerIterator(players); while (playerIterator.hasNext()) if (playerIterator.next().value()->getStatus() != StatusReadyStart) return; - QSqlQuery query; +/* QSqlQuery query; query.prepare("insert into games (id, descr, password, time_started) values(:id, :descr, :password, now())"); query.bindValue(":id", gameId); query.bindValue(":descr", description); query.bindValue(":password", !password.isEmpty()); query.exec(); - QMapIterator playerIterator2(players); + QMapIterator playerIterator2(players); while (playerIterator2.hasNext()) { - Player *player = playerIterator2.next().value(); + Server_Player *player = playerIterator2.next().value(); query.prepare("insert into games_players (id_game, player) values(:id, :player)"); query.bindValue(":id", gameId); query.bindValue(":player", player->getPlayerName()); @@ -95,13 +95,13 @@ void ServerGame::startGameIfReady() player->setupZones(); } - +*/ gameStarted = true; broadcastEvent("game_start", NULL); setActivePlayer(0); } -ReturnMessage::ReturnCode ServerGame::checkJoin(const QString &_password, bool spectator) +ReturnMessage::ReturnCode Server_Game::checkJoin(const QString &_password, bool spectator) { if (_password != password) return ReturnMessage::ReturnPasswordWrong; @@ -114,12 +114,12 @@ ReturnMessage::ReturnCode ServerGame::checkJoin(const QString &_password, bool s return ReturnMessage::ReturnOk; } -Player *ServerGame::addPlayer(const QString &playerName, bool spectator) +Server_Player *Server_Game::addPlayer(const QString &playerName, bool spectator) { int playerId; if (!spectator) { int max = -1; - QMapIterator i(players); + QMapIterator i(players); while (i.hasNext()) { int tmp = i.next().value()->getPlayerId(); if (tmp > max) @@ -129,7 +129,7 @@ Player *ServerGame::addPlayer(const QString &playerName, bool spectator) } else playerId = -1; - Player *newPlayer = new Player(this, playerId, playerName, spectator); + Server_Player *newPlayer = new Server_Player(this, playerId, playerName, spectator); broadcastEvent(QString("join|%1").arg(spectator ? 1 : 0), newPlayer); if (spectator) @@ -142,7 +142,7 @@ Player *ServerGame::addPlayer(const QString &playerName, bool spectator) return newPlayer; } -void ServerGame::removePlayer(Player *player) +void Server_Game::removePlayer(Server_Player *player) { if (player->getSpectator()) spectators.removeAt(spectators.indexOf(player)); @@ -156,21 +156,21 @@ void ServerGame::removePlayer(Player *player) qobject_cast(parent())->broadcastGameListUpdate(this); } -void ServerGame::setActivePlayer(int _activePlayer) +void Server_Game::setActivePlayer(int _activePlayer) { activePlayer = _activePlayer; broadcastEvent(QString("set_active_player|%1").arg(_activePlayer), NULL); setActivePhase(0); } -void ServerGame::setActivePhase(int _activePhase) +void Server_Game::setActivePhase(int _activePhase) { - QMapIterator playerIterator(players); + QMapIterator playerIterator(players); while (playerIterator.hasNext()) { - Player *player = playerIterator.next().value(); - QList toDelete = player->getArrows().values(); + Server_Player *player = playerIterator.next().value(); + QList toDelete = player->getArrows().values(); for (int i = 0; i < toDelete.size(); ++i) { - Arrow *a = toDelete[i]; + Server_Arrow *a = toDelete[i]; broadcastEvent(QString("delete_arrow|%1").arg(a->getId()), player); player->deleteArrow(a->getId()); } diff --git a/servatrice/src/servergame.h b/common/server_game.h similarity index 75% rename from servatrice/src/servergame.h rename to common/server_game.h index 04f8e1f5..9b552dc0 100644 --- a/servatrice/src/servergame.h +++ b/common/server_game.h @@ -22,16 +22,16 @@ #include #include -#include "player.h" +#include +#include "server_player.h" #include "returnmessage.h" -#include "serversocket.h" -class ServerGame : public QObject { +class Server_Game : public QObject { Q_OBJECT private: - QPointer creator; - QMap players; - QList spectators; + QPointer creator; + QMap players; + QList spectators; bool gameStarted; int gameId; QString description; @@ -42,13 +42,13 @@ private: signals: void gameClosing(); public: - ServerGame(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent = 0); - ~ServerGame(); - Player *getCreator() const { return creator; } + Server_Game(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent = 0); + ~Server_Game(); + Server_Player *getCreator() const { return creator; } bool getGameStarted() const { return gameStarted; } int getPlayerCount() const { return players.size(); } - QList getPlayers() const { return players.values(); } - Player *getPlayer(int playerId) const { return players.value(playerId, 0); } + QList getPlayers() const { return players.values(); } + Server_Player *getPlayer(int playerId) const { return players.value(playerId, 0); } int getGameId() const { return gameId; } QString getDescription() const { return description; } QString getPassword() const { return password; } @@ -56,15 +56,15 @@ public: bool getSpectatorsAllowed() const { return spectatorsAllowed; } QString getGameListLine() const; ReturnMessage::ReturnCode checkJoin(const QString &_password, bool spectator); - Player *addPlayer(const QString &playerName, bool spectator); - void removePlayer(Player *player); + Server_Player *addPlayer(const QString &playerName, bool spectator); + void removePlayer(Server_Player *player); void startGameIfReady(); int getActivePlayer() const { return activePlayer; } int getActivePhase() const { return activePhase; } void setActivePlayer(int _activePlayer); void setActivePhase(int _activePhase); - void broadcastEvent(const QString &eventStr, Player *player); + void broadcastEvent(const QString &eventStr, Server_Player *player); }; #endif diff --git a/servatrice/src/player.cpp b/common/server_player.cpp similarity index 50% rename from servatrice/src/player.cpp rename to common/server_player.cpp index c735a7f0..46418573 100644 --- a/servatrice/src/player.cpp +++ b/common/server_player.cpp @@ -1,46 +1,45 @@ -#include "player.h" -#include "card.h" -#include "counter.h" -#include "arrow.h" -#include "playerzone.h" -#include "serversocket.h" -#include "servergame.h" +#include "server_player.h" +#include "server_card.h" +#include "server_counter.h" +#include "server_arrow.h" +#include "server_cardzone.h" +#include "server_game.h" -Player::Player(ServerGame *_game, int _playerId, const QString &_playerName, bool _spectator) +Server_Player::Server_Player(Server_Game *_game, int _playerId, const QString &_playerName, bool _spectator) : game(_game), socket(0), playerId(_playerId), playerName(_playerName), spectator(_spectator), nextCardId(0), PlayerStatus(StatusNormal) { } -int Player::newCardId() +int Server_Player::newCardId() { return nextCardId++; } -int Player::newCounterId() const +int Server_Player::newCounterId() const { int id = 0; - QMapIterator i(counters); + QMapIterator i(counters); while (i.hasNext()) { - Counter *c = i.next().value(); + Server_Counter *c = i.next().value(); if (c->getId() > id) id = c->getId(); } return id + 1; } -int Player::newArrowId() const +int Server_Player::newArrowId() const { int id = 0; - QMapIterator i(arrows); + QMapIterator i(arrows); while (i.hasNext()) { - Arrow *a = i.next().value(); + Server_Arrow *a = i.next().value(); if (a->getId() > id) id = a->getId(); } return id + 1; } -void Player::setupZones() +void Server_Player::setupZones() { // Delete existing zones and counters clearZones(); @@ -49,14 +48,14 @@ void Player::setupZones() // ------------------------------------------------------------------ // Create zones - PlayerZone *deck = new PlayerZone(this, "deck", false, PlayerZone::HiddenZone); + Server_CardZone *deck = new Server_CardZone(this, "deck", false, Server_CardZone::HiddenZone); addZone(deck); - PlayerZone *sb = new PlayerZone(this, "sb", false, PlayerZone::HiddenZone); + Server_CardZone *sb = new Server_CardZone(this, "sb", false, Server_CardZone::HiddenZone); addZone(sb); - addZone(new PlayerZone(this, "table", true, PlayerZone::PublicZone)); - addZone(new PlayerZone(this, "hand", false, PlayerZone::PrivateZone)); - addZone(new PlayerZone(this, "grave", false, PlayerZone::PublicZone)); - addZone(new PlayerZone(this, "rfg", false, PlayerZone::PublicZone)); + addZone(new Server_CardZone(this, "table", true, Server_CardZone::PublicZone)); + addZone(new Server_CardZone(this, "hand", false, Server_CardZone::PrivateZone)); + addZone(new Server_CardZone(this, "grave", false, Server_CardZone::PublicZone)); + addZone(new Server_CardZone(this, "rfg", false, Server_CardZone::PublicZone)); // ------------------------------------------------------------------ @@ -64,12 +63,12 @@ void Player::setupZones() QListIterator DeckIterator(DeckList); int i = 0; while (DeckIterator.hasNext()) - deck->cards.append(new Card(DeckIterator.next(), i++, 0, 0)); + deck->cards.append(new Server_Card(DeckIterator.next(), i++, 0, 0)); deck->shuffle(); QListIterator SBIterator(SideboardList); while (SBIterator.hasNext()) - sb->cards.append(new Card(SBIterator.next(), i++, 0, 0)); + sb->cards.append(new Server_Card(SBIterator.next(), i++, 0, 0)); nextCardId = i; @@ -78,37 +77,37 @@ void Player::setupZones() .arg(sb->cards.size()), this); } -void Player::clearZones() +void Server_Player::clearZones() { - QMapIterator zoneIterator(zones); + QMapIterator zoneIterator(zones); while (zoneIterator.hasNext()) delete zoneIterator.next().value(); zones.clear(); - QMapIterator counterIterator(counters); + QMapIterator counterIterator(counters); while (counterIterator.hasNext()) delete counterIterator.next().value(); counters.clear(); - QMapIterator arrowIterator(arrows); + QMapIterator arrowIterator(arrows); while (arrowIterator.hasNext()) delete arrowIterator.next().value(); arrows.clear(); } -void Player::addZone(PlayerZone *zone) +void Server_Player::addZone(Server_CardZone *zone) { zones.insert(zone->getName(), zone); } -void Player::addArrow(Arrow *arrow) +void Server_Player::addArrow(Server_Arrow *arrow) { arrows.insert(arrow->getId(), arrow); } -bool Player::deleteArrow(int arrowId) +bool Server_Player::deleteArrow(int arrowId) { - Arrow *arrow = arrows.value(arrowId, 0); + Server_Arrow *arrow = arrows.value(arrowId, 0); if (!arrow) return false; arrows.remove(arrowId); @@ -116,14 +115,14 @@ bool Player::deleteArrow(int arrowId) return true; } -void Player::addCounter(Counter *counter) +void Server_Player::addCounter(Server_Counter *counter) { counters.insert(counter->getId(), counter); } -bool Player::deleteCounter(int counterId) +bool Server_Player::deleteCounter(int counterId) { - Counter *counter = counters.value(counterId, 0); + Server_Counter *counter = counters.value(counterId, 0); if (!counter) return false; counters.remove(counterId); @@ -131,19 +130,19 @@ bool Player::deleteCounter(int counterId) return true; } -void Player::privateEvent(const QString &line) +void Server_Player::privateEvent(const QString &line) { - if (!socket) +/* if (!socket) return; socket->msg(QString("private|%1|%2|%3").arg(playerId).arg(playerName).arg(line)); -} +*/} -void Player::publicEvent(const QString &line, Player *player) +void Server_Player::publicEvent(const QString &line, Server_Player *player) { - if (!socket) +/* if (!socket) return; if (player) socket->msg(QString("public|%1|%2|%3").arg(player->getPlayerId()).arg(player->getPlayerName()).arg(line)); else socket->msg(QString("public|||%1").arg(line)); -} +*/} diff --git a/servatrice/src/player.h b/common/server_player.h similarity index 58% rename from servatrice/src/player.h rename to common/server_player.h index ebdd88bc..a7df9dc2 100644 --- a/servatrice/src/player.h +++ b/common/server_player.h @@ -7,21 +7,21 @@ #include class ServerSocket; -class ServerGame; -class PlayerZone; -class Counter; -class Arrow; +class Server_Game; +class Server_CardZone; +class Server_Counter; +class Server_Arrow; enum PlayerStatusEnum { StatusNormal, StatusSubmitDeck, StatusReadyStart, StatusPlaying }; -class Player : public QObject { +class Server_Player : public QObject { Q_OBJECT private: - ServerGame *game; + Server_Game *game; ServerSocket *socket; - QMap zones; - QMap counters; - QMap arrows; + QMap zones; + QMap counters; + QMap arrows; int playerId; QString playerName; bool spectator; @@ -34,7 +34,7 @@ public: QList SideboardList; // Pfusch Ende - Player(ServerGame *_game, int _playerId, const QString &_playerName, bool _spectator); + Server_Player(Server_Game *_game, int _playerId, const QString &_playerName, bool _spectator); void setSocket(ServerSocket *_socket) { socket = _socket; } void setStatus(PlayerStatusEnum _status) { PlayerStatus = _status; } @@ -43,24 +43,24 @@ public: int getPlayerId() const { return playerId; } bool getSpectator() const { return spectator; } QString getPlayerName() const { return playerName; } - const QMap &getZones() const { return zones; } - const QMap &getCounters() const { return counters; } - const QMap &getArrows() const { return arrows; } + const QMap &getZones() const { return zones; } + const QMap &getCounters() const { return counters; } + const QMap &getArrows() const { return arrows; } int newCardId(); int newCounterId() const; int newArrowId() const; - void addZone(PlayerZone *zone); - void addArrow(Arrow *arrow); + void addZone(Server_CardZone *zone); + void addArrow(Server_Arrow *arrow); bool deleteArrow(int arrowId); - void addCounter(Counter *counter); + void addCounter(Server_Counter *counter); bool deleteCounter(int counterId); void setupZones(); void privateEvent(const QString &line); - void publicEvent(const QString &line, Player *player = 0); + void publicEvent(const QString &line, Server_Player *player = 0); }; #endif diff --git a/common/server_protocolhandler.cpp b/common/server_protocolhandler.cpp new file mode 100644 index 00000000..9f53d393 --- /dev/null +++ b/common/server_protocolhandler.cpp @@ -0,0 +1,33 @@ +#include +#include "server_protocolhandler.h" +#include "protocol.h" +#include "protocol_items.h" + +Server_ProtocolHandler::Server_ProtocolHandler(Server *_server, QObject *parent) + : QObject(parent), server(_server), authState(PasswordWrong), acceptsGameListChanges(false) +{ +} + +Server_ProtocolHandler::~Server_ProtocolHandler() +{ +} + +void Server_ProtocolHandler::processCommand(Command *command) +{ + ChatCommand *chatCommand = qobject_cast(command); + GameCommand *gameCommand = qobject_cast(command); + if (chatCommand) { + qDebug() << "received ChatCommand: channel =" << chatCommand->getChannel(); + } else if (gameCommand) { + qDebug() << "received GameCommand: game =" << gameCommand->getGameId(); + } else { + qDebug() << "received generic Command"; + } +} + +QPair Server_ProtocolHandler::getGame(int gameId) const +{ + if (games.contains(gameId)) + return games.value(gameId); + return QPair(0, 0); +} diff --git a/common/server_protocolhandler.h b/common/server_protocolhandler.h new file mode 100644 index 00000000..ee340461 --- /dev/null +++ b/common/server_protocolhandler.h @@ -0,0 +1,36 @@ +#ifndef SERVER_PROTOCOLHANDLER_H +#define SERVER_PROTOCOLHANDLER_H + +#include +#include +#include "server.h" + +class Server_Player; +class Command; + +class Server_ProtocolHandler : public QObject { + Q_OBJECT +private: + Server *server; + QMap > games; + QMap chatChannels; + QString playerName; + + Server *getServer() const { return server; } + QPair getGame(int gameId) const; + + AuthenticationResult authState; + bool acceptsGameListChanges; + bool acceptsChatChannelListChanges; +public: + Server_ProtocolHandler(Server *_server, QObject *parent = 0); + ~Server_ProtocolHandler(); + + bool getAcceptsGameListChanges() const { return acceptsGameListChanges; } + bool getAcceptsChatChannelListChanges() const { return acceptsChatChannelListChanges; } + const QString &getPlayerName() const { return playerName; } + + void processCommand(Command *command); +}; + +#endif diff --git a/common/widget.cpp b/common/widget.cpp deleted file mode 100644 index 1f50e451..00000000 --- a/common/widget.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include -#include -#include "widget.h" -#include "protocol.h" -#include "protocol_items.h" - -Widget::Widget() - : QMainWindow() -{ - edit1 = new QTextEdit; - start = new QPushButton; - connect(start, SIGNAL(clicked()), this, SLOT(startClicked())); - - buffer = new QBuffer; - buffer->open(QIODevice::ReadWrite); - connect(buffer, SIGNAL(readyRead()), this, SLOT(updateEdit())); - - xmlWriter.setDevice(buffer); - xmlWriter.setAutoFormatting(true); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(edit1); - vbox->addWidget(start); - - QWidget *central = new QWidget; - central->setLayout(vbox); - setCentralWidget(central); - - resize(400, 500); - - Command::initializeHash(); -} - -void Widget::startClicked() -{ - currentItem = 0; - xmlWriter.writeStartDocument(); - xmlWriter.writeStartElement("cockatrice_communication"); - xmlWriter.writeAttribute("version", "4"); - - Command *test = new Command_Ping; - test->write(xmlWriter); - - Command *test2 = new Command_ChatLeaveChannel("foobar"); - test2->write(xmlWriter); - - Command *test3 = new Command_ChatSay("foobar", "Hallo, dies ist ein Test"); - test3->write(xmlWriter); - - ProtocolResponse *test4 = new ProtocolResponse(123, ProtocolResponse::RespContextError); - test4->write(xmlWriter); - - GameEvent *test5 = new Event_RollDie(1234, 1, 20, 13); - test5->write(xmlWriter); -} - -bool Widget::readCurrentCommand() -{ - if (!currentItem) - return false; - if (currentItem->read(xmlReader)) { - qDebug() << "setting to 0"; - currentItem = 0; - } - return true; -} - -void Widget::parseXml() -{ - if (readCurrentCommand()) - return; - - while (!xmlReader.atEnd()) { - xmlReader.readNext(); - if (xmlReader.isStartElement()) { - QString itemType = xmlReader.name().toString(); - QString itemName = xmlReader.attributes().value("name").toString(); - qDebug() << "parseXml: startElement: " << "type =" << itemType << ", name =" << itemName; - currentItem = ProtocolItem::getNewItem(itemType + itemName); - if (!currentItem) - qDebug() << "unrecognized item"; - readCurrentCommand(); - } - } -} - -void Widget::parseBuffer() -{ - xmlReader.clear(); - buffer->seek(0); - while (!buffer->atEnd()) { - QByteArray oneByte = buffer->read(1); - xmlReader.addData(oneByte); - parseXml(); - } -} - -void Widget::updateEdit() -{ - buffer->seek(0); - edit1->setText(buffer->readAll()); - - parseBuffer(); -} diff --git a/common/widget.h b/common/widget.h deleted file mode 100644 index f43d9c88..00000000 --- a/common/widget.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include -#include - -class QTextEdit; -class QPushButton; -class QBuffer; -class ProtocolItem; - -class Widget : public QMainWindow { - Q_OBJECT -private: - QTextEdit *edit1; - QPushButton *start; - QBuffer *buffer; - QXmlStreamReader xmlReader; - QXmlStreamWriter xmlWriter; - - ProtocolItem *currentItem; - bool readCurrentCommand(); - void parseBuffer(); - void parseXml(); -private slots: - void startClicked(); - void updateEdit(); -public: - Widget(); -}; - -#endif diff --git a/servatrice/servatrice.pro b/servatrice/servatrice.pro index f82fc240..9c0ff7c0 100755 --- a/servatrice/servatrice.pro +++ b/servatrice/servatrice.pro @@ -4,8 +4,8 @@ TEMPLATE = app TARGET = -DEPENDPATH += . src -INCLUDEPATH += . src +DEPENDPATH += . src ../common/src +INCLUDEPATH += . src ../common/src MOC_DIR = build OBJECTS_DIR = build @@ -13,26 +13,34 @@ CONFIG += qt debug QT += network sql QT -= gui -# Input -HEADERS += src/server.h src/servergame.h src/serversocket.h \ - src/playerzone.h \ - src/card.h \ - src/arrow.h \ - src/version.h \ - src/counter.h \ - src/abstractrng.h \ - src/rng_qt.h \ - src/returnmessage.h \ - src/chatchannel.h \ - src/player.h +HEADERS += src/servatrice.h \ + src/serversocketinterface.h \ + src/version.h \ + ../common/src/protocol.h \ + ../common/src/protocol_items.h \ + ../common/src/rng_abstract.h \ + ../common/src/rng_qt.h \ + ../common/src/server.h \ + ../common/src/server_arrow.h \ + ../common/src/server_card.h \ + ../common/src/server_cardzone.h \ + ../common/src/server_chatchannel.h \ + ../common/src/server_counter.h \ + ../common/src/server_game.h \ + ../common/src/server_player.h \ + ../common/src/server_protocolhandler.h + SOURCES += src/main.cpp \ - src/server.cpp \ - src/servergame.cpp \ - src/serversocket.cpp \ - src/playerzone.cpp \ - src/card.cpp \ - src/counter.cpp \ - src/rng_qt.cpp \ - src/returnmessage.cpp \ - src/chatchannel.cpp \ - src/player.cpp + src/servatrice.cpp \ + src/serversocketinterface.cpp \ + ../common/src/protocol.cpp \ + ../common/src/protocol_items.cpp \ + ../common/src/rng_abstract.cpp \ + ../common/src/rng_qt.cpp \ + ../common/src/server.cpp \ + ../common/src/server_card.cpp \ + ../common/src/server_cardzone.cpp \ + ../common/src/server_chatchannel.cpp \ + ../common/src/server_game.cpp \ + ../common/src/server_player.cpp \ + ../common/src/server_protocolhandler.cpp diff --git a/servatrice/src/abstractrng.h b/servatrice/src/abstractrng.h deleted file mode 100644 index d4350da0..00000000 --- a/servatrice/src/abstractrng.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef ABSTRACTRNG_H -#define ABSTRACTRNG_H - -#include - -class AbstractRNG : public QObject { - Q_OBJECT -public: - AbstractRNG(QObject *parent = 0) : QObject(parent) { } - virtual unsigned int getNumber(unsigned int min, unsigned int max) = 0; -}; - -extern AbstractRNG *rng; - -#endif diff --git a/servatrice/src/arrow.h b/servatrice/src/arrow.h deleted file mode 100644 index 65d34b40..00000000 --- a/servatrice/src/arrow.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef ARROW_H -#define ARROW_H - -class Card; - -class Arrow { -private: - int id; - Card *startCard, *targetCard; - int color; -public: - Arrow(int _id, Card *_startCard, Card *_targetCard, int _color) - : id(_id), startCard(_startCard), targetCard(_targetCard), color(_color) { } - int getId() const { return id; } - Card *getStartCard() const { return startCard; } - Card *getTargetCard() const { return targetCard; } - int getColor() const { return color; } -}; - -#endif \ No newline at end of file diff --git a/servatrice/src/chatchannel.cpp b/servatrice/src/chatchannel.cpp deleted file mode 100644 index 75d8dad6..00000000 --- a/servatrice/src/chatchannel.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "chatchannel.h" -#include "serversocket.h" - -ChatChannel::ChatChannel(const QString &_name, const QString &_description, bool _autoJoin, const QStringList &_joinMessage) - : name(_name), description(_description), autoJoin(_autoJoin), joinMessage(_joinMessage) -{ -} - -void ChatChannel::addPlayer(ServerSocket *player) -{ - QString str = QString("chat|join_channel|%1|%2").arg(name).arg(player->getPlayerName()); - for (int i = 0; i < size(); ++i) - at(i)->msg(str); - - append(player); - - for (int i = 0; i < size(); ++i) - player->msg(QString("chat|list_players|%1|%2").arg(name).arg(at(i)->getPlayerName())); - for (int i = 0; i < joinMessage.size(); ++i) - player->msg(QString("chat|server_message|%1|%2").arg(name).arg(joinMessage[i])); - - emit channelInfoChanged(); -} - -void ChatChannel::removePlayer(ServerSocket *player) -{ - QString str = QString("chat|leave_channel|%1|%2").arg(name).arg(player->getPlayerName()); - - removeAt(indexOf(player)); - for (int i = 0; i < size(); ++i) - at(i)->msg(str); - - emit channelInfoChanged(); -} - -void ChatChannel::say(ServerSocket *player, const QString &s) -{ - QString str = QString("chat|say|%1|%2|%3").arg(name).arg(player->getPlayerName()).arg(s); - for (int i = 0; i < size(); ++i) - at(i)->msg(str); -} - -QString ChatChannel::getChannelListLine() const -{ - return QString("chat|list_channels|%1|%2|%3|%4").arg(name).arg(description).arg(size()).arg(autoJoin ? 1 : 0); -} diff --git a/servatrice/src/main.cpp b/servatrice/src/main.cpp index 84a81c8a..072290be 100644 --- a/servatrice/src/main.cpp +++ b/servatrice/src/main.cpp @@ -20,10 +20,7 @@ #include #include -#include "server.h" -#include "rng_qt.h" - -AbstractRNG *rng; +#include "servatrice.h" int main(int argc, char *argv[]) { @@ -33,10 +30,7 @@ int main(int argc, char *argv[]) QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); - rng = new RNG_Qt; - - Server server; - server.listen(QHostAddress::Any, 4747); + Servatrice server; return app.exec(); } diff --git a/servatrice/src/server.cpp b/servatrice/src/servatrice.cpp similarity index 56% rename from servatrice/src/server.cpp rename to servatrice/src/servatrice.cpp index 2491835b..65cee166 100644 --- a/servatrice/src/server.cpp +++ b/servatrice/src/servatrice.cpp @@ -17,17 +17,19 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include "server.h" -#include "servergame.h" -#include "serversocket.h" -#include "counter.h" -#include "chatchannel.h" #include #include +#include "servatrice.h" +#include "server_chatchannel.h" +#include "serversocketinterface.h" -Server::Server(QObject *parent) - : QTcpServer(parent), nextGameId(0) +Servatrice::Servatrice(QObject *parent) + : Server(parent) { + tcpServer = new QTcpServer(this); + connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection())); + tcpServer->listen(QHostAddress::Any, 4747); // XXX make customizable + settings = new QSettings("servatrice.ini", QSettings::IniFormat, this); QString dbType = settings->value("database/type").toString(); @@ -37,23 +39,24 @@ Server::Server(QObject *parent) int size = settings->beginReadArray("chatchannels"); for (int i = 0; i < size; ++i) { settings->setArrayIndex(i); - ChatChannel *newChannel = new ChatChannel(settings->value("name").toString(), - settings->value("description").toString(), - settings->value("autojoin").toBool(), - settings->value("joinmessage").toStringList()); - chatChannels.insert(newChannel->getName(), newChannel); - connect(newChannel, SIGNAL(channelInfoChanged()), this, SLOT(broadcastChannelUpdate())); + Server_ChatChannel *newChannel = new Server_ChatChannel( + settings->value("name").toString(), + settings->value("description").toString(), + settings->value("autojoin").toBool(), + settings->value("joinmessage").toStringList() + ); + addChatChannel(newChannel); } settings->endArray(); loginMessage = settings->value("messages/login").toStringList(); } -Server::~Server() +Servatrice::~Servatrice() { } -bool Server::openDatabase() +bool Servatrice::openDatabase() { if (!QSqlDatabase::connectionNames().isEmpty()) QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionNames().at(0)); @@ -81,27 +84,14 @@ bool Server::openDatabase() return true; } -ServerGame *Server::createGame(const QString &description, const QString &password, int maxPlayers, bool spectatorsAllowed, const QString &creator) +void Servatrice::newConnection() { - ServerGame *newGame = new ServerGame(creator, nextGameId++, description, password, maxPlayers, spectatorsAllowed, this); - games.insert(newGame->getGameId(), newGame); - connect(newGame, SIGNAL(gameClosing()), this, SLOT(gameClosing())); - - broadcastGameListUpdate(newGame); - - return newGame; + QTcpSocket *socket = tcpServer->nextPendingConnection(); + ServerSocketInterface *ssi = new ServerSocketInterface(this, socket); + addClient(ssi); } -void Server::incomingConnection(int socketId) -{ - ServerSocket *socket = new ServerSocket(this); - socket->setSocketDescriptor(socketId); - connect(socket, SIGNAL(createGame(const QString, const QString, int, bool, ServerSocket *)), this, SLOT(addGame(const QString, const QString, int, bool, ServerSocket *))); - socket->initConnection(); - players << socket; -} - -AuthenticationResult Server::checkUserPassword(const QString &user, const QString &password) +AuthenticationResult Servatrice::checkUserPassword(const QString &user, const QString &password) { const QString method = settings->value("authentication/method").toString(); if (method == "none") @@ -127,39 +117,3 @@ AuthenticationResult Server::checkUserPassword(const QString &user, const QStrin } else return UnknownUser; } - -ServerGame *Server::getGame(int gameId) const -{ - return games.value(gameId); -} - -void Server::broadcastGameListUpdate(ServerGame *game) -{ - qDebug(QString("broadcastGameListUpdate() to %1 players").arg(players.size()).toLatin1()); - QString line = game->getGameListLine(); - for (int i = 0; i < players.size(); i++) - if (players[i]->getAcceptsGameListChanges()) - players[i]->msg(line); -} - -void Server::broadcastChannelUpdate() -{ - QString line = qobject_cast(sender())->getChannelListLine(); - for (int i = 0; i < players.size(); ++i) - if (players[i]->getAcceptsChatChannelListChanges()) - players[i]->msg(line); -} - -void Server::gameClosing() -{ - qDebug("Server::gameClosing"); - ServerGame *game = static_cast(sender()); - broadcastGameListUpdate(game); - games.remove(games.key(game)); -} - -void Server::removePlayer(ServerSocket *player) -{ - players.removeAt(players.indexOf(player)); - qDebug(QString("Server::removePlayer: %1 players left").arg(players.size()).toLatin1()); -} diff --git a/servatrice/src/counter.cpp b/servatrice/src/servatrice.h similarity index 72% rename from servatrice/src/counter.cpp rename to servatrice/src/servatrice.h index ba1c1c43..14653ecc 100644 --- a/servatrice/src/counter.cpp +++ b/servatrice/src/servatrice.h @@ -17,5 +17,30 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include "counter.h" +#ifndef SERVATRICE_H +#define SERVATRICE_H +#include +#include "server.h" + +class QSqlDatabase; +class QSettings; + +class Servatrice : public Server +{ + Q_OBJECT +private slots: + void newConnection(); +public: + Servatrice(QObject *parent = 0); + ~Servatrice(); + bool openDatabase(); + AuthenticationResult checkUserPassword(const QString &user, const QString &password); + QStringList getLoginMessage() const { return loginMessage; } +private: + QTcpServer *tcpServer; + QStringList loginMessage; + QSettings *settings; +}; + +#endif diff --git a/servatrice/src/serversocket.cpp b/servatrice/src/serversocket.cpp deleted file mode 100644 index 04a92d70..00000000 --- a/servatrice/src/serversocket.cpp +++ /dev/null @@ -1,948 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Max-Wilhelm Bruker * - * brukie@laptop * - * * - * 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., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * - ***************************************************************************/ - -#include -#include "server.h" -#include "serversocket.h" -#include "servergame.h" -#include "version.h" -#include "returnmessage.h" -#include "playerzone.h" -#include "counter.h" -#include "card.h" -#include "arrow.h" -#include "chatchannel.h" -#include "player.h" -#include "abstractrng.h" - -QHash ServerSocket::commandHash; - -ServerSocket::ServerSocket(Server *_server, QObject *parent) - : QTcpSocket(parent), server(_server), authState(PasswordWrong), acceptsGameListChanges(false) -{ - if (commandHash.isEmpty()) { - commandHash.insert("ping", new GenericCommandProperties(false, QList(), &ServerSocket::cmdPing)); - commandHash.insert("login", new GenericCommandProperties(false, QList() - << QVariant::String - << QVariant::String, &ServerSocket::cmdLogin)); - commandHash.insert("chat_list_channels", new GenericCommandProperties(true, QList(), &ServerSocket::cmdChatListChannels)); - commandHash.insert("chat_join_channel", new GenericCommandProperties(true, QList() - << QVariant::String, &ServerSocket::cmdChatJoinChannel)); - commandHash.insert("list_games", new GenericCommandProperties(true, QList(), &ServerSocket::cmdListGames)); - commandHash.insert("create_game", new GenericCommandProperties(true, QList() - << QVariant::String - << QVariant::String - << QVariant::Int - << QVariant::Bool, &ServerSocket::cmdCreateGame)); - commandHash.insert("join_game", new GenericCommandProperties(true, QList() - << QVariant::Int - << QVariant::String - << QVariant::Bool, &ServerSocket::cmdJoinGame)); - - commandHash.insert("chat_leave_channel", new ChatCommandProperties(QList(), &ServerSocket::cmdChatLeaveChannel)); - commandHash.insert("chat_say", new ChatCommandProperties(QList() - << QVariant::String, &ServerSocket::cmdChatSay)); - - commandHash.insert("leave_game", new GameCommandProperties(false, true, QList(), &ServerSocket::cmdLeaveGame)); - commandHash.insert("list_players", new GameCommandProperties(false, true, QList(), &ServerSocket::cmdListPlayers)); - commandHash.insert("say", new GameCommandProperties(false, false, QList() - << QVariant::String, &ServerSocket::cmdSay)); - commandHash.insert("submit_deck", new GameCommandProperties(false, false, QList(), &ServerSocket::cmdSubmitDeck)); - commandHash.insert("ready_start", new GameCommandProperties(false, false, QList(), &ServerSocket::cmdReadyStart)); - commandHash.insert("shuffle", new GameCommandProperties(true, false, QList(), &ServerSocket::cmdShuffle)); - commandHash.insert("draw_cards", new GameCommandProperties(true, false, QList() - << QVariant::Int, &ServerSocket::cmdDrawCards)); - commandHash.insert("reveal_card", new GameCommandProperties(true, false, QList() - << QVariant::Int - << QVariant::String, &ServerSocket::cmdRevealCard)); - commandHash.insert("move_card", new GameCommandProperties(true, false, QList() - << QVariant::Int - << QVariant::String - << QVariant::String - << QVariant::Int - << QVariant::Int - << QVariant::Bool, &ServerSocket::cmdMoveCard)); - commandHash.insert("create_token", new GameCommandProperties(true, false, QList() - << QVariant::String - << QVariant::String - << QVariant::String - << QVariant::Int - << QVariant::Int, &ServerSocket::cmdCreateToken)); - commandHash.insert("create_arrow", new GameCommandProperties(true, false, QList() - << QVariant::Int - << QVariant::String - << QVariant::Int - << QVariant::Int - << QVariant::String - << QVariant::Int - << QVariant::Int, &ServerSocket::cmdCreateArrow)); - commandHash.insert("delete_arrow", new GameCommandProperties(true, false, QList() - << QVariant::Int, &ServerSocket::cmdDeleteArrow)); - commandHash.insert("set_card_attr", new GameCommandProperties(true, false, QList() - << QVariant::String - << QVariant::Int - << QVariant::String - << QVariant::String, &ServerSocket::cmdSetCardAttr)); - commandHash.insert("inc_counter", new GameCommandProperties(true, false, QList() - << QVariant::String - << QVariant::Int, &ServerSocket::cmdIncCounter)); - commandHash.insert("add_counter", new GameCommandProperties(true, false, QList() - << QVariant::String - << QVariant::Int - << QVariant::Int - << QVariant::Int, &ServerSocket::cmdAddCounter)); - commandHash.insert("set_counter", new GameCommandProperties(true, false, QList() - << QVariant::Int - << QVariant::Int, &ServerSocket::cmdSetCounter)); - commandHash.insert("del_counter", new GameCommandProperties(true, false, QList() - << QVariant::Int, &ServerSocket::cmdDelCounter)); - commandHash.insert("list_counters", new GameCommandProperties(true, true, QList() - << QVariant::Int, &ServerSocket::cmdListCounters)); - commandHash.insert("list_zones", new GameCommandProperties(true, true, QList() - << QVariant::Int, &ServerSocket::cmdListZones)); - commandHash.insert("dump_zone", new GameCommandProperties(true, true, QList() - << QVariant::Int - << QVariant::String - << QVariant::Int, &ServerSocket::cmdDumpZone)); - commandHash.insert("stop_dump_zone", new GameCommandProperties(true, true, QList() - << QVariant::Int - << QVariant::String, &ServerSocket::cmdStopDumpZone)); - commandHash.insert("roll_die", new GameCommandProperties(true, false, QList() - << QVariant::Int, &ServerSocket::cmdRollDie)); - commandHash.insert("next_turn", new GameCommandProperties(true, false, QList(), &ServerSocket::cmdNextTurn)); - commandHash.insert("set_active_phase", new GameCommandProperties(true, false, QList() - << QVariant::Int, &ServerSocket::cmdSetActivePhase)); - commandHash.insert("dump_all", new GameCommandProperties(false, true, QList(), &ServerSocket::cmdDumpAll)); - } - - remsg = new ReturnMessage(this); - connect(this, SIGNAL(readyRead()), this, SLOT(readClient())); - connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater())); - connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); - setTextModeEnabled(true); -} - -ServerSocket::~ServerSocket() -{ - qDebug("ServerSocket destructor"); -/* clearZones(); - // The socket has to be removed from the server's list before it is removed from the game's list - // so it will not receive the game update event. - server->removePlayer(this); - if (game) - game->removePlayer(this); - for (int i = 0; i < chatChannels.size(); ++i) - chatChannels[i]->removePlayer(this); -*/} - -void ServerSocket::readClient() -{ - while (canReadLine()) { - QString line = QString(readLine()).trimmed(); - if (line.isNull()) - break; - - qDebug(QString("<<< %1").arg(line).toLatin1()); -/* switch (PlayerStatus) { - case StatusNormal: - case StatusReadyStart: - case StatusPlaying: - parseCommand(line); - break; - case StatusSubmitDeck: - QString card = line; - if (card == ".") { - PlayerStatus = StatusNormal; - remsg->send(ReturnMessage::ReturnOk); - } else if (card.startsWith("SB:")) - SideboardList << card.mid(3); - else - DeckList << card; - } -*/ } -} - -ReturnMessage::ReturnCode ServerSocket::cmdPing(const QList &/*params*/) -{ - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdLogin(const QList ¶ms) -{ - authState = server->checkUserPassword(params[0].toString(), params[1].toString()); - if (authState == PasswordWrong) - return ReturnMessage::ReturnPasswordWrong; - playerName = params[0].toString(); - - remsg->send(ReturnMessage::ReturnOk); - - QStringList loginMessage = server->getLoginMessage(); - for (int i = 0; i < loginMessage.size(); ++i) - msg("chat|server_message||" + loginMessage[i]); - - return ReturnMessage::ReturnNothing; -} - -ReturnMessage::ReturnCode ServerSocket::cmdChatListChannels(const QList &/*params*/) -{ - QMapIterator channelIterator(server->getChatChannels()); - while (channelIterator.hasNext()) { - ChatChannel *c = channelIterator.next().value(); - msg(c->getChannelListLine()); - } - - acceptsChatChannelListChanges = true; - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdChatJoinChannel(const QList ¶ms) -{ - QString channelName = params[0].toString(); - if (chatChannels.contains(channelName)) - return ReturnMessage::ReturnContextError; - - QMap allChannels = server->getChatChannels(); - ChatChannel *c = allChannels.value(channelName, 0); - if (!c) - return ReturnMessage::ReturnNameNotFound; - - remsg->send(ReturnMessage::ReturnOk); - c->addPlayer(this); - chatChannels.insert(channelName, c); - return ReturnMessage::ReturnNothing; -} - -ReturnMessage::ReturnCode ServerSocket::cmdChatLeaveChannel(ChatChannel *channel, const QList & /*params*/) -{ - chatChannels.remove(channel->getName()); - channel->removePlayer(this); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdChatSay(ChatChannel *channel, const QList ¶ms) -{ - channel->say(this, params[0].toString()); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdListGames(const QList &/*params*/) -{ - const QList &gameList = server->getGames(); - for (int i = 0; i < gameList.size(); ++i) - msg(gameList[i]->getGameListLine()); - - acceptsGameListChanges = true; - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdCreateGame(const QList ¶ms) -{ - QString description = params[0].toString(); - QString password = params[1].toString(); - int maxPlayers = params[2].toInt(); - bool spectatorsAllowed = params[3].toBool(); - - ServerGame *game = server->createGame(description, password, maxPlayers, spectatorsAllowed, playerName); - games.insert(game->getGameId(), QPair(game, game->getCreator())); - - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdJoinGame(const QList ¶ms) -{ - int gameId = params[0].toInt(); - QString password = params[1].toString(); - bool spectator = params[2].toBool(); - - ServerGame *g = server->getGame(gameId); - if (!g) - return ReturnMessage::ReturnNameNotFound; - - ReturnMessage::ReturnCode result = g->checkJoin(password, spectator); - if (result == ReturnMessage::ReturnOk) { - Player *player = g->addPlayer(playerName, spectator); - games.insert(gameId, QPair(g, player)); - } - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdLeaveGame(ServerGame *game, Player *player, const QList &/*params*/) -{ - game->removePlayer(player); - return ReturnMessage::ReturnOk; -} - -QStringList ServerSocket::listPlayersHelper(ServerGame *game, Player *player) -{ - QStringList result; - const QList &players = game->getPlayers(); - for (int i = 0; i < players.size(); ++i) - result << QString("%1|%2|%3").arg(players[i]->getPlayerId()).arg(players[i]->getPlayerName()).arg(players[i] == player ? 1 : 0); - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdListPlayers(ServerGame *game, Player *player, const QList &/*params*/) -{ - remsg->sendList(listPlayersHelper(game, player)); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdSay(ServerGame *game, Player *player, const QList ¶ms) -{ - game->broadcastEvent(QString("say|%1").arg(params[0].toString()), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdSubmitDeck(ServerGame * /*game*/, Player *player, const QList &/*params*/) -{ - player->setStatus(StatusSubmitDeck); - player->DeckList.clear(); - player->SideboardList.clear(); - return ReturnMessage::ReturnNothing; -} - -ReturnMessage::ReturnCode ServerSocket::cmdReadyStart(ServerGame *game, Player *player, const QList &/*params*/) -{ - player->setStatus(StatusReadyStart); - game->broadcastEvent(QString("ready_start"), player); - game->startGameIfReady(); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdShuffle(ServerGame *game, Player *player, const QList &/*params*/) -{ - player->getZones().value("deck")->shuffle(); - game->broadcastEvent("shuffle", player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdDrawCards(ServerGame *game, Player *player, const QList ¶ms) -{ - int number = params[0].toInt(); - PlayerZone *deck = player->getZones().value("deck"); - PlayerZone *hand = player->getZones().value("hand"); - if (deck->cards.size() < number) - return ReturnMessage::ReturnContextError; - - for (int i = 0; i < number; ++i) { - Card *card = deck->cards.first(); - deck->cards.removeFirst(); - hand->cards.append(card); - player->privateEvent(QString("draw|%1|%2").arg(card->getId()).arg(card->getName())); - } - - game->broadcastEvent(QString("draw|%1").arg(number), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdRevealCard(ServerGame *game, Player *player, const QList ¶ms) -{ -/* int cardid = params[0].toInt(); - PlayerZone *zone = getZone(params[1].toString()); - if (!zone) - return ReturnMessage::ReturnContextError; - int position = -1; - Card *card = zone->getCard(cardid, false, &position); - if (!card) - return ReturnMessage::ReturnContextError; - emit broadcastEvent(QString("reveal_card|%1|%2|%3").arg(cardid).arg(zone->getName()).arg(card->getName()), this); -*/ return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdMoveCard(ServerGame *game, Player *player, const QList ¶ms) -{ - // ID Karte, Startzone, Zielzone, Koordinaten X, Y, Facedown - int cardid = params[0].toInt(); - PlayerZone *startzone = player->getZones().value(params[1].toString()); - PlayerZone *targetzone = player->getZones().value(params[2].toString()); - if ((!startzone) || (!targetzone)) - return ReturnMessage::ReturnContextError; - - int position = -1; - Card *card = startzone->getCard(cardid, true, &position); - if (!card) - return ReturnMessage::ReturnContextError; - int x = params[3].toInt(); - if (x == -1) - x = targetzone->cards.size(); - int y = 0; - if (targetzone->hasCoords()) - y = params[4].toInt(); - bool facedown = params[5].toBool(); - - targetzone->insertCard(card, x, y); - - bool targetBeingLookedAt = (targetzone->getType() != PlayerZone::HiddenZone) || (targetzone->getCardsBeingLookedAt() > x) || (targetzone->getCardsBeingLookedAt() == -1); - bool sourceBeingLookedAt = (startzone->getType() != PlayerZone::HiddenZone) || (startzone->getCardsBeingLookedAt() > position) || (startzone->getCardsBeingLookedAt() == -1); - - bool targetHiddenToPlayer = facedown || !targetBeingLookedAt; - bool targetHiddenToOthers = facedown || (targetzone->getType() != PlayerZone::PublicZone); - bool sourceHiddenToPlayer = card->getFaceDown() || !sourceBeingLookedAt; - bool sourceHiddenToOthers = card->getFaceDown() || (startzone->getType() != PlayerZone::PublicZone); - - QString privateCardName, publicCardName; - if (!(sourceHiddenToPlayer && targetHiddenToPlayer)) - privateCardName = card->getName(); - if (!(sourceHiddenToOthers && targetHiddenToOthers)) - publicCardName = card->getName(); - - if (facedown) - card->setId(player->newCardId()); - card->setFaceDown(facedown); - - // The player does not get to see which card he moved if it moves between two parts of hidden zones which - // are not being looked at. - QString privateCardId = QString::number(card->getId()); - if (!targetBeingLookedAt && !sourceBeingLookedAt) { - privateCardId = QString(); - privateCardName = QString(); - } - player->privateEvent(QString("move_card|%1|%2|%3|%4|%5|%6|%7|%8").arg(privateCardId) - .arg(privateCardName) - .arg(startzone->getName()) - .arg(position) - .arg(targetzone->getName()) - .arg(x) - .arg(y) - .arg(facedown ? 1 : 0)); - - // Other players do not get to see the start and/or target position of the card if the respective - // part of the zone is being looked at. The information is not needed anyway because in hidden zones, - // all cards are equal. - if ((startzone->getType() == PlayerZone::HiddenZone) && ((startzone->getCardsBeingLookedAt() > position) || (startzone->getCardsBeingLookedAt() == -1))) - position = -1; - if ((targetzone->getType() == PlayerZone::HiddenZone) && ((targetzone->getCardsBeingLookedAt() > x) || (targetzone->getCardsBeingLookedAt() == -1))) - x = -1; - - if ((startzone->getType() == PlayerZone::PublicZone) || (targetzone->getType() == PlayerZone::PublicZone)) - game->broadcastEvent(QString("move_card|%1|%2|%3|%4|%5|%6|%7|%8").arg(card->getId()) - .arg(publicCardName) - .arg(startzone->getName()) - .arg(position) - .arg(targetzone->getName()) - .arg(x) - .arg(y) - .arg(facedown ? 1 : 0), player); - else - game->broadcastEvent(QString("move_card|||%1|%2|%3|%4|%5|0").arg(startzone->getName()) - .arg(position) - .arg(targetzone->getName()) - .arg(x) - .arg(y), player); - - // If the card was moved to another zone, delete all arrows from and to the card - if (startzone != targetzone) { - const QList &players = game->getPlayers(); - for (int i = 0; i < players.size(); ++i) { - QList arrowsToDelete; - QMapIterator arrowIterator(players[i]->getArrows()); - while (arrowIterator.hasNext()) { - Arrow *arrow = arrowIterator.next().value(); - if ((arrow->getStartCard() == card) || (arrow->getTargetCard() == card)) - arrowsToDelete.append(arrow->getId()); - } - for (int j = 0; j < arrowsToDelete.size(); ++j) - players[i]->deleteArrow(arrowsToDelete[j]); - } - } - - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdCreateToken(ServerGame *game, Player *player, const QList ¶ms) -{ - // zone, cardname, powtough, x, y - // powtough wird erst mal ignoriert - PlayerZone *zone = player->getZones().value(params[0].toString()); - if (!zone) - return ReturnMessage::ReturnContextError; - QString cardname = params[1].toString(); - QString powtough = params[2].toString(); - int x = params[3].toInt(); - int y = params[4].toInt(); - int cardid = player->newCardId(); - - Card *card = new Card(cardname, cardid, x, y); - zone->insertCard(card, x, y); - game->broadcastEvent(QString("create_token|%1|%2|%3|%4|%5|%6").arg(zone->getName()) - .arg(cardid) - .arg(cardname) - .arg(powtough) - .arg(x) - .arg(y), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdCreateArrow(ServerGame *game, Player *player, const QList ¶ms) -{ - Player *startPlayer = game->getPlayer(params[0].toInt()); - Player *targetPlayer = game->getPlayer(params[3].toInt()); - if (!startPlayer || !targetPlayer) - return ReturnMessage::ReturnContextError; - PlayerZone *startZone = startPlayer->getZones().value(params[1].toString()); - PlayerZone *targetZone = targetPlayer->getZones().value(params[4].toString()); - if (!startZone || !targetZone) - return ReturnMessage::ReturnContextError; - Card *startCard = startZone->getCard(params[2].toInt(), false); - Card *targetCard = targetZone->getCard(params[5].toInt(), false); - if (!startCard || !targetCard || (startCard == targetCard)) - return ReturnMessage::ReturnContextError; - QMapIterator arrowIterator(player->getArrows()); - while (arrowIterator.hasNext()) { - Arrow *temp = arrowIterator.next().value(); - if ((temp->getStartCard() == startCard) && (temp->getTargetCard() == targetCard)) - return ReturnMessage::ReturnContextError; - } - int color = params[6].toInt(); - - Arrow *arrow = new Arrow(player->newArrowId(), startCard, targetCard, color); - player->addArrow(arrow); - game->broadcastEvent(QString("create_arrow|%1|%2|%3|%4|%5|%6|%7|%8") - .arg(arrow->getId()) - .arg(startPlayer->getPlayerId()) - .arg(startZone->getName()) - .arg(startCard->getId()) - .arg(targetPlayer->getPlayerId()) - .arg(targetZone->getName()) - .arg(targetCard->getId()) - .arg(color), player - ); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdDeleteArrow(ServerGame *game, Player *player, const QList ¶ms) -{ - int arrowId = params[0].toInt(); - if (!player->deleteArrow(arrowId)) - return ReturnMessage::ReturnContextError; - - game->broadcastEvent(QString("delete_arrow|%1").arg(arrowId), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdSetCardAttr(ServerGame *game, Player *player, const QList ¶ms) -{ - // zone, card id, attr name, attr value - // card id = -1 => affects all cards in the specified zone - PlayerZone *zone = player->getZones().value(params[0].toString()); - if (!zone) - return ReturnMessage::ReturnContextError; - int cardid = params[1].toInt(); - QString aname = params[2].toString(); - QString avalue = params[3].toString(); - - if (cardid == -1) { - QListIterator CardIterator(zone->cards); - while (CardIterator.hasNext()) - if (!CardIterator.next()->setAttribute(aname, avalue, true)) - return ReturnMessage::ReturnSyntaxError; - } else { - Card *card = zone->getCard(cardid, false); - if (!card) - return ReturnMessage::ReturnContextError; - if (!card->setAttribute(aname, avalue, false)) - return ReturnMessage::ReturnSyntaxError; - } - game->broadcastEvent(QString("set_card_attr|%1|%2|%3|%4").arg(zone->getName()).arg(cardid).arg(aname).arg(avalue), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdIncCounter(ServerGame *game, Player *player, const QList ¶ms) -{ - const QMap counters = player->getCounters(); - Counter *c = counters.value(params[0].toInt(), 0); - if (!c) - return ReturnMessage::ReturnContextError; - int delta = params[1].toInt(); - - c->setCount(c->getCount() + delta); - game->broadcastEvent(QString("set_counter|%1|%2").arg(c->getId()).arg(c->getCount()), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdAddCounter(ServerGame *game, Player *player, const QList ¶ms) -{ - QString name = params[0].toString(); - int color = params[1].toInt(); - int radius = params[2].toInt(); - int count = params[3].toInt(); - - Counter *c = new Counter(player->newCounterId(), name, color, radius, count); - player->addCounter(c); - game->broadcastEvent(QString("add_counter|%1|%2|%3|%4|%5").arg(c->getId()).arg(c->getName()).arg(color).arg(radius).arg(count), player); - - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdSetCounter(ServerGame *game, Player *player, const QList ¶ms) -{ - const QMap counters = player->getCounters(); - Counter *c = counters.value(params[0].toInt(), 0); - if (!c) - return ReturnMessage::ReturnContextError; - int count = params[1].toInt(); - - c->setCount(count); - game->broadcastEvent(QString("set_counter|%1|%2").arg(c->getId()).arg(count), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdDelCounter(ServerGame *game, Player *player, const QList ¶ms) -{ - int counterId = params[0].toInt(); - if (!player->deleteCounter(counterId)) - return ReturnMessage::ReturnContextError; - game->broadcastEvent(QString("del_counter|%1").arg(counterId), player); - return ReturnMessage::ReturnOk; -} - -QStringList ServerSocket::listCountersHelper(Player *player) -{ - QStringList result; - QMapIterator i(player->getCounters()); - while (i.hasNext()) { - Counter *c = i.next().value(); - result << QString("%1|%2|%3|%4|%5|%6").arg(player->getPlayerId()).arg(c->getId()).arg(c->getName()).arg(c->getColor()).arg(c->getRadius()).arg(c->getCount()); - } - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdListCounters(ServerGame *game, Player * /*player*/, const QList ¶ms) -{ - int player_id = params[0].toInt(); - Player *player = game->getPlayer(player_id); - if (!player) - return ReturnMessage::ReturnContextError; - - remsg->sendList(listCountersHelper(player)); - return ReturnMessage::ReturnOk; -} - -QStringList ServerSocket::listZonesHelper(Player *player) -{ - QStringList result; - QMapIterator zoneIterator(player->getZones()); - while (zoneIterator.hasNext()) { - PlayerZone *zone = zoneIterator.next().value(); - QString typeStr; - switch (zone->getType()) { - case PlayerZone::PublicZone: typeStr = "public"; break; - case PlayerZone::PrivateZone: typeStr = "private"; break; - case PlayerZone::HiddenZone: typeStr = "hidden"; break; - default: ; - } - result << QString("%1|%2|%3|%4|%5").arg(player->getPlayerId()).arg(zone->getName()).arg(typeStr).arg(zone->hasCoords()).arg(zone->cards.size()); - } - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdListZones(ServerGame *game, Player * /*player*/, const QList ¶ms) -{ - int player_id = params[0].toInt(); - Player *player = game->getPlayer(player_id); - if (!player) - return ReturnMessage::ReturnContextError; - - remsg->sendList(listZonesHelper(player)); - return ReturnMessage::ReturnOk; -} - -QStringList ServerSocket::dumpZoneHelper(Player *player, PlayerZone *zone, int number_cards) -{ - QStringList result; - for (int i = 0; (i < zone->cards.size()) && (i < number_cards || number_cards == -1); i++) { - Card *tmp = zone->cards[i]; - QString displayedName = tmp->getFaceDown() ? QString() : tmp->getName(); - - if (zone->getType() != PlayerZone::HiddenZone) - result << QString("%1|%2|%3|%4|%5|%6|%7|%8|%9|%10").arg(player->getPlayerId()) - .arg(zone->getName()) - .arg(tmp->getId()) - .arg(displayedName) - .arg(tmp->getX()) - .arg(tmp->getY()) - .arg(tmp->getCounters()) - .arg(tmp->getTapped()) - .arg(tmp->getAttacking()) - .arg(tmp->getAnnotation()); - else { - zone->setCardsBeingLookedAt(number_cards); - result << QString("%1|%2|%3|%4||||||").arg(player->getPlayerId()).arg(zone->getName()).arg(i).arg(displayedName); - } - } - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdDumpZone(ServerGame *game, Player *player, const QList ¶ms) -{ - int player_id = params[0].toInt(); - int number_cards = params[2].toInt(); - Player *otherPlayer = game->getPlayer(player_id); - if (!otherPlayer) - return ReturnMessage::ReturnContextError; - PlayerZone *zone = otherPlayer->getZones().value(params[1].toString()); - if (!zone) - return ReturnMessage::ReturnContextError; - if (!((zone->getType() == PlayerZone::PublicZone) || (player == otherPlayer))) - return ReturnMessage::ReturnContextError; - - if (zone->getType() == PlayerZone::HiddenZone) - game->broadcastEvent(QString("dump_zone|%1|%2|%3").arg(player_id).arg(zone->getName()).arg(number_cards), player); - - remsg->sendList(dumpZoneHelper(otherPlayer, zone, number_cards)); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdStopDumpZone(ServerGame *game, Player *player, const QList ¶ms) -{ - Player *otherPlayer = game->getPlayer(params[0].toInt()); - if (!otherPlayer) - return ReturnMessage::ReturnContextError; - PlayerZone *zone = otherPlayer->getZones().value(params[1].toString()); - if (!zone) - return ReturnMessage::ReturnContextError; - - if (zone->getType() == PlayerZone::HiddenZone) { - zone->setCardsBeingLookedAt(0); - game->broadcastEvent(QString("stop_dump_zone|%1|%2").arg(otherPlayer->getPlayerId()).arg(zone->getName()), player); - } - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdRollDie(ServerGame *game, Player *player, const QList ¶ms) -{ - int sides = params[0].toInt(); - game->broadcastEvent(QString("roll_die|%1|%2").arg(sides).arg(rng->getNumber(1, sides)), player); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdNextTurn(ServerGame *game, Player * /*player*/, const QList &/*params*/) -{ - int activePlayer = game->getActivePlayer(); - if (++activePlayer == game->getPlayerCount()) - activePlayer = 0; - game->setActivePlayer(activePlayer); - return ReturnMessage::ReturnOk; -} - -ReturnMessage::ReturnCode ServerSocket::cmdSetActivePhase(ServerGame *game, Player *player, const QList ¶ms) -{ - int active_phase = params[0].toInt(); - // XXX Überprüfung, ob die Phase existiert... - if (game->getActivePlayer() != player->getPlayerId()) - return ReturnMessage::ReturnContextError; - game->setActivePhase(active_phase); - return ReturnMessage::ReturnOk; -} - -QStringList ServerSocket::listArrowsHelper(Player *player) -{ - QStringList result; - QMapIterator arrowIterator(player->getArrows()); - while (arrowIterator.hasNext()) { - Arrow *arrow = arrowIterator.next().value(); - - Card *startCard = arrow->getStartCard(); - Card *targetCard = arrow->getTargetCard(); - PlayerZone *startZone = startCard->getZone(); - PlayerZone *targetZone = targetCard->getZone(); - Player *startPlayer = startZone->getPlayer(); - Player *targetPlayer = targetZone->getPlayer(); - - result << QString("%1|%2|%3|%4|%5|%6|%7|%8|%9").arg(player->getPlayerId()).arg(arrow->getId()).arg(startPlayer->getPlayerId()).arg(startZone->getName()).arg(startCard->getId()).arg(targetPlayer->getPlayerId()).arg(targetZone->getName()).arg(targetCard->getId()).arg(arrow->getColor()); - } - return result; -} - -ReturnMessage::ReturnCode ServerSocket::cmdDumpAll(ServerGame *game, Player *player, const QList &/*params*/) -{ - remsg->sendList(listPlayersHelper(game, player), "list_players"); - - if (game->getGameStarted()) { - const QList &players = game->getPlayers(); - for (int i = 0; i < players.size(); ++i) { - remsg->sendList(listZonesHelper(players[i]), "list_zones"); - - QMapIterator zoneIterator(players[i]->getZones()); - while (zoneIterator.hasNext()) { - PlayerZone *zone = zoneIterator.next().value(); - if ((zone->getType() == PlayerZone::PublicZone) || ((zone->getType() == PlayerZone::PrivateZone) && (player == players[i]))) - remsg->sendList(dumpZoneHelper(players[i], zone, -1), "dump_zone"); - } - - remsg->sendList(listCountersHelper(players[i]), "list_counters"); - remsg->sendList(listArrowsHelper(players[i]), "list_arrows"); - } - } - remsg->send(ReturnMessage::ReturnOk); - if (game->getGameStarted()) { - player->publicEvent(QString("set_active_player|%1").arg(game->getActivePlayer())); - player->publicEvent(QString("set_active_phase|%1").arg(game->getActivePhase())); - } - - return ReturnMessage::ReturnNothing; -} - -QList ServerSocket::CommandProperties::getParamList(const QStringList ¶ms) const -{ - QList paramList; - if (paramList.size() != params.size()) - throw ReturnMessage::ReturnSyntaxError; - for (int j = 0; j < paramTypes.size(); j++) - switch (paramTypes[j]) { - case QVariant::String: { - paramList << QVariant(params[j]); - break; - } - case QVariant::Int: { - bool ok; - int temp = params[j].toInt(&ok); - if (!ok) - throw ReturnMessage::ReturnSyntaxError; - paramList << QVariant(temp); - break; - } - case QVariant::Bool: { - if (params[j] == "1") - paramList << QVariant(true); - else if (params[j] == "0") - paramList << QVariant(false); - else - throw ReturnMessage::ReturnSyntaxError; - break; - } - default: - paramList << QVariant(params[j]); - } - return paramList; -} - -ReturnMessage::ReturnCode ServerSocket::GenericCommandProperties::exec(ServerSocket *s, QStringList ¶ms) -{ - QList paramList; - try { paramList = getParamList(params); } - catch (ReturnMessage::ReturnCode rc) { return rc; } - - return (s->*handler)(paramList); -} - -ReturnMessage::ReturnCode ServerSocket::ChatCommandProperties::exec(ServerSocket *s, QStringList ¶ms) -{ - if (params.isEmpty()) - return ReturnMessage::ReturnSyntaxError; - QString channelName = params.takeFirst(); - ChatChannel *channel = s->getServer()->getChatChannels().value(channelName, 0); - if (!channel) - return ReturnMessage::ReturnNameNotFound; - - QList paramList; - try { paramList = getParamList(params); } - catch (ReturnMessage::ReturnCode rc) { return rc; } - - return (s->*handler)(channel, paramList); -} - -ReturnMessage::ReturnCode ServerSocket::GameCommandProperties::exec(ServerSocket *s, QStringList ¶ms) -{ - if (params.isEmpty()) - return ReturnMessage::ReturnSyntaxError; - bool ok; - int gameId = params.takeFirst().toInt(&ok); - if (!ok) - return ReturnMessage::ReturnSyntaxError; - QPair pair = s->getGame(gameId); - ServerGame *game = pair.first; - Player *player = pair.second; - if (!game) - return ReturnMessage::ReturnNameNotFound; - - if (!allowedToSpectator && player->getSpectator()) - return ReturnMessage::ReturnContextError; - if (needsStartedGame && !game->getGameStarted()) - return ReturnMessage::ReturnContextError; - - QList paramList; - try { paramList = getParamList(params); } - catch (ReturnMessage::ReturnCode rc) { return rc; } - - return (s->*handler)(game, player, paramList); -} - -bool ServerSocket::parseCommand(const QString &line) -{ - QStringList params = line.split("|"); - - // Extract message id - bool conv_ok; - int msgId = params.takeFirst().toInt(&conv_ok); - if (!conv_ok) { - remsg->setMsgId(0); - return remsg->send(ReturnMessage::ReturnSyntaxError); - } - remsg->setMsgId(msgId); - - if (params.empty()) { - remsg->setMsgId(0); - return remsg->send(ReturnMessage::ReturnSyntaxError); - } - - // Extract command - QString cmd = params.takeFirst(); - CommandProperties *cp = commandHash.value(cmd, 0); - if (!cp) - return remsg->send(ReturnMessage::ReturnSyntaxError); - remsg->setCmd(cmd); - - // Check login - if (cp->getNeedsLogin() && (authState == PasswordWrong)) - return remsg->send(ReturnMessage::ReturnLoginNeeded); - - // Validate parameters and call handler function - return remsg->send(cp->exec(this, params)); -} - -void ServerSocket::msg(const QString &s) -{ - qDebug(QString("OUT >>> %3").arg(s).toLatin1()); - QTextStream stream(this); - stream.setCodec("UTF-8"); - stream << s << endl; - stream.flush(); - flush(); -} - -void ServerSocket::initConnection() -{ - msg(QString("welcome|%1|%2").arg(PROTOCOL_VERSION).arg(VERSION_STRING)); -} - -void ServerSocket::catchSocketError(QAbstractSocket::SocketError socketError) -{ - qDebug(QString("socket error: %1").arg(socketError).toLatin1()); - - deleteLater(); -} - -QPair ServerSocket::getGame(int gameId) const -{ - if (games.contains(gameId)) - return games.value(gameId); - return QPair(0, 0); -} diff --git a/servatrice/src/serversocket.h b/servatrice/src/serversocket.h deleted file mode 100644 index 6526bbcc..00000000 --- a/servatrice/src/serversocket.h +++ /dev/null @@ -1,163 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Max-Wilhelm Bruker * - * brukie@laptop * - * * - * 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., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * - ***************************************************************************/ -#ifndef SERVERSOCKET_H -#define SERVERSOCKET_H - -#include -#include -#include -#include "server.h" -#include "returnmessage.h" - -class Server; -class ServerGame; -class Player; -class PlayerZone; -class Counter; -class Arrow; - -class ServerSocket : public QTcpSocket -{ - Q_OBJECT -private slots: - void readClient(); - void catchSocketError(QAbstractSocket::SocketError socketError); -signals: - void commandReceived(QString cmd, ServerSocket *player); - void startGameIfReady(); -private: - typedef ReturnMessage::ReturnCode (ServerSocket::*GameCommandHandler)(ServerGame *game, Player *player, const QList &); - typedef ReturnMessage::ReturnCode (ServerSocket::*ChatCommandHandler)(ChatChannel *channel, const QList &); - typedef ReturnMessage::ReturnCode (ServerSocket::*GenericCommandHandler)(const QList &); - - class CommandProperties { - public: - enum CommandType { ChatCommand, GameCommand, GenericCommand }; - private: - CommandType type; - bool needsLogin; - QList paramTypes; - protected: - QList getParamList(const QStringList ¶ms) const; - public: - CommandProperties(CommandType _type, bool _needsLogin, const QList &_paramTypes) - : type(_type), needsLogin(_needsLogin), paramTypes(_paramTypes) { } - bool getNeedsLogin() const { return needsLogin; } - CommandType getType() const { return type; } - const QList &getParamTypes() const { return paramTypes; } - virtual ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList ¶ms) = 0; - }; - class ChatCommandProperties : public CommandProperties { - private: - ChatCommandHandler handler; - public: - ChatCommandProperties(const QList &_paramTypes, ChatCommandHandler _handler) - : CommandProperties(ChatCommand, true, _paramTypes), handler(_handler) { } - ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList ¶ms); - }; - class GameCommandProperties : public CommandProperties { - private: - bool needsStartedGame; - bool allowedToSpectator; - GameCommandHandler handler; - public: - GameCommandProperties(bool _needsStartedGame, bool _allowedToSpectator, const QList &_paramTypes, GameCommandHandler _handler) - : CommandProperties(GameCommand, true, _paramTypes), needsStartedGame(_needsStartedGame), allowedToSpectator(_allowedToSpectator), handler(_handler) { } - bool getNeedsStartedGame() const { return needsStartedGame; } - bool getAllowedToSpectator() const { return allowedToSpectator; } - ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList ¶ms); - }; - class GenericCommandProperties : public CommandProperties { - private: - GenericCommandHandler handler; - public: - GenericCommandProperties(bool _needsLogin, const QList &_paramTypes, GenericCommandHandler _handler) - : CommandProperties(GenericCommand, _needsLogin, _paramTypes), handler(_handler) { } - ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList ¶ms); - }; - static QHash commandHash; - - QStringList listPlayersHelper(ServerGame *game, Player *player); - QStringList listZonesHelper(Player *player); - QStringList dumpZoneHelper(Player *player, PlayerZone *zone, int numberCards); - QStringList listCountersHelper(Player *player); - QStringList listArrowsHelper(Player *player); - - ReturnMessage::ReturnCode cmdPing(const QList ¶ms); - ReturnMessage::ReturnCode cmdLogin(const QList ¶ms); - ReturnMessage::ReturnCode cmdChatListChannels(const QList ¶ms); - ReturnMessage::ReturnCode cmdChatJoinChannel(const QList ¶ms); - ReturnMessage::ReturnCode cmdListGames(const QList ¶ms); - ReturnMessage::ReturnCode cmdCreateGame(const QList ¶ms); - ReturnMessage::ReturnCode cmdJoinGame(const QList ¶ms); - - ReturnMessage::ReturnCode cmdChatLeaveChannel(ChatChannel *channel, const QList ¶ms); - ReturnMessage::ReturnCode cmdChatSay(ChatChannel *channel, const QList ¶ms); - - ReturnMessage::ReturnCode cmdLeaveGame(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdListPlayers(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdSay(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdSubmitDeck(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdReadyStart(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdShuffle(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdDrawCards(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdRevealCard(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdMoveCard(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdCreateToken(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdCreateArrow(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdDeleteArrow(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdSetCardAttr(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdIncCounter(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdAddCounter(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdSetCounter(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdDelCounter(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdListCounters(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdListZones(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdDumpZone(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdStopDumpZone(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdRollDie(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdNextTurn(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdSetActivePhase(ServerGame *game, Player *player, const QList ¶ms); - ReturnMessage::ReturnCode cmdDumpAll(ServerGame *game, Player *player, const QList ¶ms); - - Server *server; - QMap > games; - QMap chatChannels; - QString playerName; - - Server *getServer() const { return server; } - QPair getGame(int gameId) const; - - bool parseCommand(const QString &line); - ReturnMessage *remsg; - AuthenticationResult authState; - bool acceptsGameListChanges; - bool acceptsChatChannelListChanges; -public: - ServerSocket(Server *_server, QObject *parent = 0); - ~ServerSocket(); - void msg(const QString &s); - void initConnection(); - bool getAcceptsGameListChanges() const { return acceptsGameListChanges; } - bool getAcceptsChatChannelListChanges() const { return acceptsChatChannelListChanges; } - const QString &getPlayerName() const { return playerName; } -}; - -#endif diff --git a/servatrice/src/serversocketinterface.cpp b/servatrice/src/serversocketinterface.cpp new file mode 100644 index 00000000..fc7d26eb --- /dev/null +++ b/servatrice/src/serversocketinterface.cpp @@ -0,0 +1,93 @@ +/*************************************************************************** + * Copyright (C) 2008 by Max-Wilhelm Bruker * + * brukie@laptop * + * * + * 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., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include +#include +#include "serversocketinterface.h" +#include "protocol.h" + +ServerSocketInterface::ServerSocketInterface(Server *_server, QTcpSocket *_socket, QObject *parent) + : Server_ProtocolHandler(_server, parent), socket(_socket) +{ + xmlWriter = new QXmlStreamWriter; + xmlWriter->setDevice(socket); + + xmlReader = new QXmlStreamReader; + + connect(socket, SIGNAL(readyRead()), this, SLOT(readClient())); + connect(socket, SIGNAL(disconnected()), this, SLOT(deleteLater())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(catchSocketError(QAbstractSocket::SocketError))); + + xmlWriter->writeStartDocument(); + xmlWriter->writeStartElement("cockatrice_communication"); + xmlWriter->writeAttribute("version", QString::number(ProtocolItem::protocolVersion)); +} + +ServerSocketInterface::~ServerSocketInterface() +{ + qDebug("ServerSocketInterface destructor"); + + delete xmlWriter; + delete xmlReader; + delete socket; +/* clearZones(); + // The socket has to be removed from the server's list before it is removed from the game's list + // so it will not receive the game update event. + server->removePlayer(this); + if (game) + game->removePlayer(this); + for (int i = 0; i < chatChannels.size(); ++i) + chatChannels[i]->removePlayer(this); +*/} + +void ServerSocketInterface::readClient() +{ +/* while (canReadLine()) { + QString line = QString(readLine()).trimmed(); + if (line.isNull()) + break; + + qDebug(QString("<<< %1").arg(line).toLatin1()); +/* switch (PlayerStatus) { + case StatusNormal: + case StatusReadyStart: + case StatusPlaying: + parseCommand(line); + break; + case StatusSubmitDeck: + QString card = line; + if (card == ".") { + PlayerStatus = StatusNormal; + remsg->send(ReturnMessage::ReturnOk); + } else if (card.startsWith("SB:")) + SideboardList << card.mid(3); + else + DeckList << card; + } + } +*/} + +void ServerSocketInterface::catchSocketError(QAbstractSocket::SocketError socketError) +{ + qDebug(QString("socket error: %1").arg(socketError).toLatin1()); + + deleteLater(); +} + diff --git a/servatrice/src/server.h b/servatrice/src/serversocketinterface.h similarity index 54% rename from servatrice/src/server.h rename to servatrice/src/serversocketinterface.h index 01a0d770..0eadf64e 100644 --- a/servatrice/src/server.h +++ b/servatrice/src/serversocketinterface.h @@ -17,46 +17,30 @@ * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#ifndef SERVER_H -#define SERVER_H +#ifndef SERVERSOCKETINTERFACE_H +#define SERVERSOCKETINTERFACE_H -#include -#include +#include +#include -class ServerGame; -class ServerSocket; -class QSqlDatabase; -class QSettings; -class ChatChannel; +class QTcpSocket; +class Server; +class QXmlStreamReader; +class QXmlStreamWriter; -enum AuthenticationResult { PasswordWrong = 0, PasswordRight = 1, UnknownUser = 2 }; - -class Server : public QTcpServer +class ServerSocketInterface : public Server_ProtocolHandler { Q_OBJECT private slots: - void gameClosing(); - void broadcastChannelUpdate(); -public: - Server(QObject *parent = 0); - ~Server(); - QSettings *settings; - bool openDatabase(); - AuthenticationResult checkUserPassword(const QString &user, const QString &password); - QList getGames() const { return games.values(); } - ServerGame *getGame(int gameId) const; - const QMap &getChatChannels() { return chatChannels; } - void broadcastGameListUpdate(ServerGame *game); - void removePlayer(ServerSocket *player); - const QStringList &getLoginMessage() const { return loginMessage; } - ServerGame *createGame(const QString &description, const QString &password, int maxPlayers, bool spectatorsAllowed, const QString &playerName); + void readClient(); + void catchSocketError(QAbstractSocket::SocketError socketError); private: - void incomingConnection(int SocketId); - QMap games; - QList players; - QMap chatChannels; - int nextGameId; - QStringList loginMessage; + QTcpSocket *socket; + QXmlStreamWriter *xmlWriter; + QXmlStreamReader *xmlReader; +public: + ServerSocketInterface(Server *_server, QTcpSocket *_socket, QObject *parent = 0); + ~ServerSocketInterface(); }; #endif