This commit is contained in:
Max-Wilhelm Bruker 2009-10-29 17:13:37 +01:00
parent d329376e93
commit 1c2aa15b22
38 changed files with 638 additions and 1651 deletions

3
common/.directory Normal file
View file

@ -0,0 +1,3 @@
[Dolphin]
Timestamp=2009,10,26,13,45,44
ViewMode=1

View file

@ -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

View file

@ -1,17 +0,0 @@
#include <QApplication>
#include <QTextCodec>
#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();
}

View file

@ -63,6 +63,9 @@ ProtocolItem *ProtocolItem::getNewItem(const QString &name)
void ProtocolItem::initializeHash() void ProtocolItem::initializeHash()
{ {
if (!itemNameHash.isEmpty())
return;
initializeHashAuto(); initializeHashAuto();
itemNameHash.insert("resp", ProtocolResponse::newItem); itemNameHash.insert("resp", ProtocolResponse::newItem);
ProtocolResponse::initializeHash(); ProtocolResponse::initializeHash();

View file

@ -28,6 +28,7 @@ protected:
private: private:
static void initializeHashAuto(); static void initializeHashAuto();
public: public:
static const int protocolVersion = 4;
ProtocolItem(const QString &_itemName); ProtocolItem(const QString &_itemName);
static void initializeHash(); static void initializeHash();
static ProtocolItem *getNewItem(const QString &name); static ProtocolItem *getNewItem(const QString &name);
@ -36,6 +37,7 @@ public:
}; };
class Command : public ProtocolItem { class Command : public ProtocolItem {
Q_OBJECT
private: private:
int cmdId; int cmdId;
static int lastCmdId; static int lastCmdId;

4
common/rng_abstract.cpp Normal file
View file

@ -0,0 +1,4 @@
#include "rng_abstract.h"
#include "rng_qt.h"
RNG_Abstract *rng = new RNG_Qt;

15
common/rng_abstract.h Normal file
View file

@ -0,0 +1,15 @@
#ifndef RNG_ABSTRACT_H
#define RNG_ABSTRACT_H
#include <QObject>
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

View file

@ -3,7 +3,7 @@
#include <stdlib.h> #include <stdlib.h>
RNG_Qt::RNG_Qt(QObject *parent) RNG_Qt::RNG_Qt(QObject *parent)
: AbstractRNG(parent) : RNG_Abstract(parent)
{ {
int seed = QDateTime::currentDateTime().toTime_t(); int seed = QDateTime::currentDateTime().toTime_t();
qDebug(QString("qsrand(%1)").arg(seed).toLatin1()); qDebug(QString("qsrand(%1)").arg(seed).toLatin1());

View file

@ -1,9 +1,9 @@
#ifndef RNG_QT_H #ifndef RNG_QT_H
#define 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 Q_OBJECT
public: public:
RNG_Qt(QObject *parent = 0); RNG_Qt(QObject *parent = 0);

89
common/server.cpp Normal file
View file

@ -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<Server_ChatChannel *>(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<Server_Game *>(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()));
}

42
common/server.h Normal file
View file

@ -0,0 +1,42 @@
#ifndef SERVER_H
#define SERVER_H
#include <QObject>
#include <QStringList>
#include <QMap>
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<Server_Game *> getGames() const { return games.values(); }
Server_Game *getGame(int gameId) const;
const QMap<QString, Server_ChatChannel *> &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<int, Server_Game *> games;
QList<Server_ProtocolHandler *> clients;
QMap<QString, Server_ChatChannel *> chatChannels;
protected:
int nextGameId;
void addChatChannel(Server_ChatChannel *newChannel);
};
#endif

20
common/server_arrow.h Normal file
View file

@ -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

View file

@ -17,19 +17,19 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 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) : 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); setCoords(0, 0);
setCounters(0); setCounters(0);
@ -40,7 +40,7 @@ void Card::resetState()
setDoesntUntap(false); 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") { if (aname == "counters") {
bool ok; bool ok;

View file

@ -17,16 +17,16 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef CARD_H #ifndef SERVER_CARD_H
#define CARD_H #define SERVER_CARD_H
#include <QString> #include <QString>
class PlayerZone; class Server_CardZone;
class Card { class Server_Card {
private: private:
PlayerZone *zone; Server_CardZone *zone;
int id; int id;
int coord_x, coord_y; int coord_x, coord_y;
QString name; QString name;
@ -37,11 +37,11 @@ private:
QString annotation; QString annotation;
bool doesntUntap; bool doesntUntap;
public: public:
Card(QString _name, int _id, int _coord_x, int _coord_y); Server_Card(QString _name, int _id, int _coord_x, int _coord_y);
~Card(); ~Server_Card();
PlayerZone *getZone() const { return zone; } Server_CardZone *getZone() const { return zone; }
void setZone(PlayerZone *_zone) { zone = _zone; } void setZone(Server_CardZone *_zone) { zone = _zone; }
int getId() const { return id; } int getId() const { return id; }
int getX() const { return coord_x; } int getX() const { return coord_x; }

View file

@ -17,36 +17,36 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#include "playerzone.h" #include "server_cardzone.h"
#include "abstractrng.h" #include "server_card.h"
#include "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) : 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(); clear();
} }
void PlayerZone::shuffle() void Server_CardZone::shuffle()
{ {
QList<Card *> temp; QList<Server_Card *> temp;
for (int i = cards.size(); i; i--) for (int i = cards.size(); i; i--)
temp.append(cards.takeAt(rng->getNumber(0, i - 1))); temp.append(cards.takeAt(rng->getNumber(0, i - 1)));
cards = temp; 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) { if (type != HiddenZone) {
QListIterator<Card *> CardIterator(cards); QListIterator<Server_Card *> CardIterator(cards);
int i = 0; int i = 0;
while (CardIterator.hasNext()) { while (CardIterator.hasNext()) {
Card *tmp = CardIterator.next(); Server_Card *tmp = CardIterator.next();
if (tmp->getId() == id) { if (tmp->getId() == id) {
if (remove) { if (remove) {
cards.removeAt(i); cards.removeAt(i);
@ -62,7 +62,7 @@ Card *PlayerZone::getCard(int id, bool remove, int *position)
} else { } else {
if ((id >= cards.size()) || (id < 0)) if ((id >= cards.size()) || (id < 0))
return NULL; return NULL;
Card *tmp = cards[id]; Server_Card *tmp = cards[id];
if (remove) { if (remove) {
cards.removeAt(id); cards.removeAt(id);
tmp->setZone(0); 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()) { if (hasCoords()) {
card->setCoords(x, y); card->setCoords(x, y);
@ -85,7 +85,7 @@ void PlayerZone::insertCard(Card *card, int x, int y)
card->setZone(this); card->setZone(this);
} }
void PlayerZone::clear() void Server_CardZone::clear()
{ {
for (int i = 0; i < cards.size(); i++) for (int i = 0; i < cards.size(); i++)
delete cards.at(i); delete cards.at(i);

View file

@ -17,17 +17,16 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef PLAYERZONE_H #ifndef SERVER_CARDZONE_H
#define PLAYERZONE_H #define SERVER_CARDZONE_H
#include <QList> #include <QList>
#include <QString> #include <QString>
class Card; class Server_Card;
class ServerSocket; class Server_Player;
class Player;
class PlayerZone { class Server_CardZone {
public: public:
// PrivateZone: Contents of the zone are always visible to the owner, // PrivateZone: Contents of the zone are always visible to the owner,
// but not to anyone else. // but not to anyone else.
@ -39,26 +38,26 @@ public:
// list index, whereas cards in any other zone are referenced by their ids. // list index, whereas cards in any other zone are referenced by their ids.
enum ZoneType { PrivateZone, PublicZone, HiddenZone }; enum ZoneType { PrivateZone, PublicZone, HiddenZone };
private: private:
Player *player; Server_Player *player;
QString name; QString name;
bool has_coords; bool has_coords;
ZoneType type; ZoneType type;
int cardsBeingLookedAt; int cardsBeingLookedAt;
public: public:
PlayerZone(Player *_player, const QString &_name, bool _has_coords, ZoneType _type); Server_CardZone(Server_Player *_player, const QString &_name, bool _has_coords, ZoneType _type);
~PlayerZone(); ~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; } int getCardsBeingLookedAt() const { return cardsBeingLookedAt; }
void setCardsBeingLookedAt(int _cardsBeingLookedAt) { cardsBeingLookedAt = _cardsBeingLookedAt; } void setCardsBeingLookedAt(int _cardsBeingLookedAt) { cardsBeingLookedAt = _cardsBeingLookedAt; }
bool hasCoords() const { return has_coords; } bool hasCoords() const { return has_coords; }
ZoneType getType() const { return type; } ZoneType getType() const { return type; }
QString getName() const { return name; } QString getName() const { return name; }
Player *getPlayer() const { return player; } Server_Player *getPlayer() const { return player; }
QList<Card *> cards; QList<Server_Card *> cards;
void insertCard(Card *card, int x, int y); void insertCard(Server_Card *card, int x, int y);
void shuffle(); void shuffle();
void clear(); void clear();
}; };

View file

@ -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);
}

View file

@ -5,9 +5,9 @@
#include <QObject> #include <QObject>
#include <QStringList> #include <QStringList>
class ServerSocket; class Server_ProtocolHandler;
class ChatChannel : public QObject, public QList<ServerSocket *> { class Server_ChatChannel : public QObject, public QList<Server_ProtocolHandler *> {
Q_OBJECT Q_OBJECT
signals: signals:
void channelInfoChanged(); void channelInfoChanged();
@ -17,13 +17,13 @@ private:
bool autoJoin; bool autoJoin;
QStringList joinMessage; QStringList joinMessage;
public: 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 getName() const { return name; }
QString getDescription() const { return description; } QString getDescription() const { return description; }
bool getAutoJoin() const { return autoJoin; } bool getAutoJoin() const { return autoJoin; }
void addPlayer(ServerSocket *player); void addClient(Server_ProtocolHandler *client);
void removePlayer(ServerSocket *player); void removeClient(Server_ProtocolHandler *client);
void say(ServerSocket *player, const QString &s); void say(Server_ProtocolHandler *client, const QString &s);
QString getChannelListLine() const; QString getChannelListLine() const;
}; };

View file

@ -17,12 +17,12 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef COUNTER_H #ifndef SERVER_COUNTER_H
#define COUNTER_H #define SERVER_COUNTER_H
#include <QString> #include <QString>
class Counter { class Server_Counter {
protected: protected:
int id; int id;
QString name; QString name;
@ -30,8 +30,8 @@ protected:
int radius; int radius;
int count; int count;
public: public:
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 _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 getId() const { return id; } int getId() const { return id; }
QString getName() const { return name; } QString getName() const { return name; }
int getColor() const { return color; } int getColor() const { return color; }

View file

@ -18,22 +18,22 @@
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#include "server.h" #include "server.h"
#include "servergame.h" #include "server_game.h"
#include "serversocket.h" #include "server_protocolhandler.h"
#include "arrow.h" #include "server_arrow.h"
#include <QSqlQuery> #include <QSqlQuery>
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) : QObject(parent), gameStarted(false), gameId(_gameId), description(_description), password(_password), maxPlayers(_maxPlayers), spectatorsAllowed(_spectatorsAllowed)
{ {
creator = addPlayer(_creator, false); creator = addPlayer(_creator, false);
} }
ServerGame::~ServerGame() Server_Game::~Server_Game()
{ {
broadcastEvent("game_closed", 0); broadcastEvent("game_closed", 0);
QMapIterator<int, Player *> playerIterator(players); QMapIterator<int, Server_Player *> playerIterator(players);
while (playerIterator.hasNext()) while (playerIterator.hasNext())
delete playerIterator.next().value(); delete playerIterator.next().value();
players.clear(); players.clear();
@ -42,10 +42,10 @@ ServerGame::~ServerGame()
spectators.clear(); spectators.clear();
emit gameClosing(); emit gameClosing();
qDebug("ServerGame destructor"); qDebug("Server_Game destructor");
} }
QString ServerGame::getGameListLine() const QString Server_Game::getGameListLine() const
{ {
if (players.isEmpty()) if (players.isEmpty())
return QString("list_games|%1|||0|%2||0|0").arg(gameId).arg(maxPlayers); 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<Player *> allClients = QList<Player *>() << players.values() << spectators; QList<Server_Player *> allClients = QList<Server_Player *>() << players.values() << spectators;
for (int i = 0; i < allClients.size(); ++i) for (int i = 0; i < allClients.size(); ++i)
allClients[i]->publicEvent(eventStr, player); allClients[i]->publicEvent(eventStr, player);
} }
void ServerGame::startGameIfReady() void Server_Game::startGameIfReady()
{ {
if (players.size() < maxPlayers) if (players.size() < maxPlayers)
return; return;
QMapIterator<int, Player *> playerIterator(players); QMapIterator<int, Server_Player *> playerIterator(players);
while (playerIterator.hasNext()) while (playerIterator.hasNext())
if (playerIterator.next().value()->getStatus() != StatusReadyStart) if (playerIterator.next().value()->getStatus() != StatusReadyStart)
return; return;
QSqlQuery query; /* QSqlQuery query;
query.prepare("insert into games (id, descr, password, time_started) values(:id, :descr, :password, now())"); query.prepare("insert into games (id, descr, password, time_started) values(:id, :descr, :password, now())");
query.bindValue(":id", gameId); query.bindValue(":id", gameId);
query.bindValue(":descr", description); query.bindValue(":descr", description);
query.bindValue(":password", !password.isEmpty()); query.bindValue(":password", !password.isEmpty());
query.exec(); query.exec();
QMapIterator<int, Player *> playerIterator2(players); QMapIterator<int, Server_Player *> playerIterator2(players);
while (playerIterator2.hasNext()) { 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.prepare("insert into games_players (id_game, player) values(:id, :player)");
query.bindValue(":id", gameId); query.bindValue(":id", gameId);
query.bindValue(":player", player->getPlayerName()); query.bindValue(":player", player->getPlayerName());
@ -95,13 +95,13 @@ void ServerGame::startGameIfReady()
player->setupZones(); player->setupZones();
} }
*/
gameStarted = true; gameStarted = true;
broadcastEvent("game_start", NULL); broadcastEvent("game_start", NULL);
setActivePlayer(0); setActivePlayer(0);
} }
ReturnMessage::ReturnCode ServerGame::checkJoin(const QString &_password, bool spectator) ReturnMessage::ReturnCode Server_Game::checkJoin(const QString &_password, bool spectator)
{ {
if (_password != password) if (_password != password)
return ReturnMessage::ReturnPasswordWrong; return ReturnMessage::ReturnPasswordWrong;
@ -114,12 +114,12 @@ ReturnMessage::ReturnCode ServerGame::checkJoin(const QString &_password, bool s
return ReturnMessage::ReturnOk; return ReturnMessage::ReturnOk;
} }
Player *ServerGame::addPlayer(const QString &playerName, bool spectator) Server_Player *Server_Game::addPlayer(const QString &playerName, bool spectator)
{ {
int playerId; int playerId;
if (!spectator) { if (!spectator) {
int max = -1; int max = -1;
QMapIterator<int, Player *> i(players); QMapIterator<int, Server_Player *> i(players);
while (i.hasNext()) { while (i.hasNext()) {
int tmp = i.next().value()->getPlayerId(); int tmp = i.next().value()->getPlayerId();
if (tmp > max) if (tmp > max)
@ -129,7 +129,7 @@ Player *ServerGame::addPlayer(const QString &playerName, bool spectator)
} else } else
playerId = -1; 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); broadcastEvent(QString("join|%1").arg(spectator ? 1 : 0), newPlayer);
if (spectator) if (spectator)
@ -142,7 +142,7 @@ Player *ServerGame::addPlayer(const QString &playerName, bool spectator)
return newPlayer; return newPlayer;
} }
void ServerGame::removePlayer(Player *player) void Server_Game::removePlayer(Server_Player *player)
{ {
if (player->getSpectator()) if (player->getSpectator())
spectators.removeAt(spectators.indexOf(player)); spectators.removeAt(spectators.indexOf(player));
@ -156,21 +156,21 @@ void ServerGame::removePlayer(Player *player)
qobject_cast<Server *>(parent())->broadcastGameListUpdate(this); qobject_cast<Server *>(parent())->broadcastGameListUpdate(this);
} }
void ServerGame::setActivePlayer(int _activePlayer) void Server_Game::setActivePlayer(int _activePlayer)
{ {
activePlayer = _activePlayer; activePlayer = _activePlayer;
broadcastEvent(QString("set_active_player|%1").arg(_activePlayer), NULL); broadcastEvent(QString("set_active_player|%1").arg(_activePlayer), NULL);
setActivePhase(0); setActivePhase(0);
} }
void ServerGame::setActivePhase(int _activePhase) void Server_Game::setActivePhase(int _activePhase)
{ {
QMapIterator<int, Player *> playerIterator(players); QMapIterator<int, Server_Player *> playerIterator(players);
while (playerIterator.hasNext()) { while (playerIterator.hasNext()) {
Player *player = playerIterator.next().value(); Server_Player *player = playerIterator.next().value();
QList<Arrow *> toDelete = player->getArrows().values(); QList<Server_Arrow *> toDelete = player->getArrows().values();
for (int i = 0; i < toDelete.size(); ++i) { 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); broadcastEvent(QString("delete_arrow|%1").arg(a->getId()), player);
player->deleteArrow(a->getId()); player->deleteArrow(a->getId());
} }

View file

@ -22,16 +22,16 @@
#include <QStringList> #include <QStringList>
#include <QPointer> #include <QPointer>
#include "player.h" #include <QObject>
#include "server_player.h"
#include "returnmessage.h" #include "returnmessage.h"
#include "serversocket.h"
class ServerGame : public QObject { class Server_Game : public QObject {
Q_OBJECT Q_OBJECT
private: private:
QPointer<Player> creator; QPointer<Server_Player> creator;
QMap<int, Player *> players; QMap<int, Server_Player *> players;
QList<Player *> spectators; QList<Server_Player *> spectators;
bool gameStarted; bool gameStarted;
int gameId; int gameId;
QString description; QString description;
@ -42,13 +42,13 @@ private:
signals: signals:
void gameClosing(); void gameClosing();
public: public:
ServerGame(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent = 0); Server_Game(const QString &_creator, int _gameId, const QString &_description, const QString &_password, int _maxPlayers, bool _spectatorsAllowed, QObject *parent = 0);
~ServerGame(); ~Server_Game();
Player *getCreator() const { return creator; } Server_Player *getCreator() const { return creator; }
bool getGameStarted() const { return gameStarted; } bool getGameStarted() const { return gameStarted; }
int getPlayerCount() const { return players.size(); } int getPlayerCount() const { return players.size(); }
QList<Player *> getPlayers() const { return players.values(); } QList<Server_Player *> getPlayers() const { return players.values(); }
Player *getPlayer(int playerId) const { return players.value(playerId, 0); } Server_Player *getPlayer(int playerId) const { return players.value(playerId, 0); }
int getGameId() const { return gameId; } int getGameId() const { return gameId; }
QString getDescription() const { return description; } QString getDescription() const { return description; }
QString getPassword() const { return password; } QString getPassword() const { return password; }
@ -56,15 +56,15 @@ public:
bool getSpectatorsAllowed() const { return spectatorsAllowed; } bool getSpectatorsAllowed() const { return spectatorsAllowed; }
QString getGameListLine() const; QString getGameListLine() const;
ReturnMessage::ReturnCode checkJoin(const QString &_password, bool spectator); ReturnMessage::ReturnCode checkJoin(const QString &_password, bool spectator);
Player *addPlayer(const QString &playerName, bool spectator); Server_Player *addPlayer(const QString &playerName, bool spectator);
void removePlayer(Player *player); void removePlayer(Server_Player *player);
void startGameIfReady(); void startGameIfReady();
int getActivePlayer() const { return activePlayer; } int getActivePlayer() const { return activePlayer; }
int getActivePhase() const { return activePhase; } int getActivePhase() const { return activePhase; }
void setActivePlayer(int _activePlayer); void setActivePlayer(int _activePlayer);
void setActivePhase(int _activePhase); void setActivePhase(int _activePhase);
void broadcastEvent(const QString &eventStr, Player *player); void broadcastEvent(const QString &eventStr, Server_Player *player);
}; };
#endif #endif

View file

@ -1,46 +1,45 @@
#include "player.h" #include "server_player.h"
#include "card.h" #include "server_card.h"
#include "counter.h" #include "server_counter.h"
#include "arrow.h" #include "server_arrow.h"
#include "playerzone.h" #include "server_cardzone.h"
#include "serversocket.h" #include "server_game.h"
#include "servergame.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) : game(_game), socket(0), playerId(_playerId), playerName(_playerName), spectator(_spectator), nextCardId(0), PlayerStatus(StatusNormal)
{ {
} }
int Player::newCardId() int Server_Player::newCardId()
{ {
return nextCardId++; return nextCardId++;
} }
int Player::newCounterId() const int Server_Player::newCounterId() const
{ {
int id = 0; int id = 0;
QMapIterator<int, Counter *> i(counters); QMapIterator<int, Server_Counter *> i(counters);
while (i.hasNext()) { while (i.hasNext()) {
Counter *c = i.next().value(); Server_Counter *c = i.next().value();
if (c->getId() > id) if (c->getId() > id)
id = c->getId(); id = c->getId();
} }
return id + 1; return id + 1;
} }
int Player::newArrowId() const int Server_Player::newArrowId() const
{ {
int id = 0; int id = 0;
QMapIterator<int, Arrow *> i(arrows); QMapIterator<int, Server_Arrow *> i(arrows);
while (i.hasNext()) { while (i.hasNext()) {
Arrow *a = i.next().value(); Server_Arrow *a = i.next().value();
if (a->getId() > id) if (a->getId() > id)
id = a->getId(); id = a->getId();
} }
return id + 1; return id + 1;
} }
void Player::setupZones() void Server_Player::setupZones()
{ {
// Delete existing zones and counters // Delete existing zones and counters
clearZones(); clearZones();
@ -49,14 +48,14 @@ void Player::setupZones()
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Create zones // 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); 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(sb);
addZone(new PlayerZone(this, "table", true, PlayerZone::PublicZone)); addZone(new Server_CardZone(this, "table", true, Server_CardZone::PublicZone));
addZone(new PlayerZone(this, "hand", false, PlayerZone::PrivateZone)); addZone(new Server_CardZone(this, "hand", false, Server_CardZone::PrivateZone));
addZone(new PlayerZone(this, "grave", false, PlayerZone::PublicZone)); addZone(new Server_CardZone(this, "grave", false, Server_CardZone::PublicZone));
addZone(new PlayerZone(this, "rfg", false, PlayerZone::PublicZone)); addZone(new Server_CardZone(this, "rfg", false, Server_CardZone::PublicZone));
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@ -64,12 +63,12 @@ void Player::setupZones()
QListIterator<QString> DeckIterator(DeckList); QListIterator<QString> DeckIterator(DeckList);
int i = 0; int i = 0;
while (DeckIterator.hasNext()) 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(); deck->shuffle();
QListIterator<QString> SBIterator(SideboardList); QListIterator<QString> SBIterator(SideboardList);
while (SBIterator.hasNext()) 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; nextCardId = i;
@ -78,37 +77,37 @@ void Player::setupZones()
.arg(sb->cards.size()), this); .arg(sb->cards.size()), this);
} }
void Player::clearZones() void Server_Player::clearZones()
{ {
QMapIterator<QString, PlayerZone *> zoneIterator(zones); QMapIterator<QString, Server_CardZone *> zoneIterator(zones);
while (zoneIterator.hasNext()) while (zoneIterator.hasNext())
delete zoneIterator.next().value(); delete zoneIterator.next().value();
zones.clear(); zones.clear();
QMapIterator<int, Counter *> counterIterator(counters); QMapIterator<int, Server_Counter *> counterIterator(counters);
while (counterIterator.hasNext()) while (counterIterator.hasNext())
delete counterIterator.next().value(); delete counterIterator.next().value();
counters.clear(); counters.clear();
QMapIterator<int, Arrow *> arrowIterator(arrows); QMapIterator<int, Server_Arrow *> arrowIterator(arrows);
while (arrowIterator.hasNext()) while (arrowIterator.hasNext())
delete arrowIterator.next().value(); delete arrowIterator.next().value();
arrows.clear(); arrows.clear();
} }
void Player::addZone(PlayerZone *zone) void Server_Player::addZone(Server_CardZone *zone)
{ {
zones.insert(zone->getName(), zone); zones.insert(zone->getName(), zone);
} }
void Player::addArrow(Arrow *arrow) void Server_Player::addArrow(Server_Arrow *arrow)
{ {
arrows.insert(arrow->getId(), 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) if (!arrow)
return false; return false;
arrows.remove(arrowId); arrows.remove(arrowId);
@ -116,14 +115,14 @@ bool Player::deleteArrow(int arrowId)
return true; return true;
} }
void Player::addCounter(Counter *counter) void Server_Player::addCounter(Server_Counter *counter)
{ {
counters.insert(counter->getId(), 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) if (!counter)
return false; return false;
counters.remove(counterId); counters.remove(counterId);
@ -131,19 +130,19 @@ bool Player::deleteCounter(int counterId)
return true; return true;
} }
void Player::privateEvent(const QString &line) void Server_Player::privateEvent(const QString &line)
{ {
if (!socket) /* if (!socket)
return; return;
socket->msg(QString("private|%1|%2|%3").arg(playerId).arg(playerName).arg(line)); 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; return;
if (player) if (player)
socket->msg(QString("public|%1|%2|%3").arg(player->getPlayerId()).arg(player->getPlayerName()).arg(line)); socket->msg(QString("public|%1|%2|%3").arg(player->getPlayerId()).arg(player->getPlayerName()).arg(line));
else else
socket->msg(QString("public|||%1").arg(line)); socket->msg(QString("public|||%1").arg(line));
} */}

View file

@ -7,21 +7,21 @@
#include <QMap> #include <QMap>
class ServerSocket; class ServerSocket;
class ServerGame; class Server_Game;
class PlayerZone; class Server_CardZone;
class Counter; class Server_Counter;
class Arrow; class Server_Arrow;
enum PlayerStatusEnum { StatusNormal, StatusSubmitDeck, StatusReadyStart, StatusPlaying }; enum PlayerStatusEnum { StatusNormal, StatusSubmitDeck, StatusReadyStart, StatusPlaying };
class Player : public QObject { class Server_Player : public QObject {
Q_OBJECT Q_OBJECT
private: private:
ServerGame *game; Server_Game *game;
ServerSocket *socket; ServerSocket *socket;
QMap<QString, PlayerZone *> zones; QMap<QString, Server_CardZone *> zones;
QMap<int, Counter *> counters; QMap<int, Server_Counter *> counters;
QMap<int, Arrow *> arrows; QMap<int, Server_Arrow *> arrows;
int playerId; int playerId;
QString playerName; QString playerName;
bool spectator; bool spectator;
@ -34,7 +34,7 @@ public:
QList<QString> SideboardList; QList<QString> SideboardList;
// Pfusch Ende // 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 setSocket(ServerSocket *_socket) { socket = _socket; }
void setStatus(PlayerStatusEnum _status) { PlayerStatus = _status; } void setStatus(PlayerStatusEnum _status) { PlayerStatus = _status; }
@ -43,24 +43,24 @@ public:
int getPlayerId() const { return playerId; } int getPlayerId() const { return playerId; }
bool getSpectator() const { return spectator; } bool getSpectator() const { return spectator; }
QString getPlayerName() const { return playerName; } QString getPlayerName() const { return playerName; }
const QMap<QString, PlayerZone *> &getZones() const { return zones; } const QMap<QString, Server_CardZone *> &getZones() const { return zones; }
const QMap<int, Counter *> &getCounters() const { return counters; } const QMap<int, Server_Counter *> &getCounters() const { return counters; }
const QMap<int, Arrow *> &getArrows() const { return arrows; } const QMap<int, Server_Arrow *> &getArrows() const { return arrows; }
int newCardId(); int newCardId();
int newCounterId() const; int newCounterId() const;
int newArrowId() const; int newArrowId() const;
void addZone(PlayerZone *zone); void addZone(Server_CardZone *zone);
void addArrow(Arrow *arrow); void addArrow(Server_Arrow *arrow);
bool deleteArrow(int arrowId); bool deleteArrow(int arrowId);
void addCounter(Counter *counter); void addCounter(Server_Counter *counter);
bool deleteCounter(int counterId); bool deleteCounter(int counterId);
void setupZones(); void setupZones();
void privateEvent(const QString &line); void privateEvent(const QString &line);
void publicEvent(const QString &line, Player *player = 0); void publicEvent(const QString &line, Server_Player *player = 0);
}; };
#endif #endif

View file

@ -0,0 +1,33 @@
#include <QDebug>
#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<ChatCommand *>(command);
GameCommand *gameCommand = qobject_cast<GameCommand *>(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_Game *, Server_Player *> Server_ProtocolHandler::getGame(int gameId) const
{
if (games.contains(gameId))
return games.value(gameId);
return QPair<Server_Game *, Server_Player *>(0, 0);
}

View file

@ -0,0 +1,36 @@
#ifndef SERVER_PROTOCOLHANDLER_H
#define SERVER_PROTOCOLHANDLER_H
#include <QObject>
#include <QPair>
#include "server.h"
class Server_Player;
class Command;
class Server_ProtocolHandler : public QObject {
Q_OBJECT
private:
Server *server;
QMap<int, QPair<Server_Game *, Server_Player *> > games;
QMap<QString, Server_ChatChannel *> chatChannels;
QString playerName;
Server *getServer() const { return server; }
QPair<Server_Game *, Server_Player *> 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

View file

@ -1,104 +0,0 @@
#include <QtGui>
#include <QDebug>
#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();
}

View file

@ -1,33 +0,0 @@
#ifndef WIDGET_H
#define WIDGET_H
#include <QMainWindow>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
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

View file

@ -4,8 +4,8 @@
TEMPLATE = app TEMPLATE = app
TARGET = TARGET =
DEPENDPATH += . src DEPENDPATH += . src ../common/src
INCLUDEPATH += . src INCLUDEPATH += . src ../common/src
MOC_DIR = build MOC_DIR = build
OBJECTS_DIR = build OBJECTS_DIR = build
@ -13,26 +13,34 @@ CONFIG += qt debug
QT += network sql QT += network sql
QT -= gui QT -= gui
# Input HEADERS += src/servatrice.h \
HEADERS += src/server.h src/servergame.h src/serversocket.h \ src/serversocketinterface.h \
src/playerzone.h \ src/version.h \
src/card.h \ ../common/src/protocol.h \
src/arrow.h \ ../common/src/protocol_items.h \
src/version.h \ ../common/src/rng_abstract.h \
src/counter.h \ ../common/src/rng_qt.h \
src/abstractrng.h \ ../common/src/server.h \
src/rng_qt.h \ ../common/src/server_arrow.h \
src/returnmessage.h \ ../common/src/server_card.h \
src/chatchannel.h \ ../common/src/server_cardzone.h \
src/player.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 \ SOURCES += src/main.cpp \
src/server.cpp \ src/servatrice.cpp \
src/servergame.cpp \ src/serversocketinterface.cpp \
src/serversocket.cpp \ ../common/src/protocol.cpp \
src/playerzone.cpp \ ../common/src/protocol_items.cpp \
src/card.cpp \ ../common/src/rng_abstract.cpp \
src/counter.cpp \ ../common/src/rng_qt.cpp \
src/rng_qt.cpp \ ../common/src/server.cpp \
src/returnmessage.cpp \ ../common/src/server_card.cpp \
src/chatchannel.cpp \ ../common/src/server_cardzone.cpp \
src/player.cpp ../common/src/server_chatchannel.cpp \
../common/src/server_game.cpp \
../common/src/server_player.cpp \
../common/src/server_protocolhandler.cpp

View file

@ -1,15 +0,0 @@
#ifndef ABSTRACTRNG_H
#define ABSTRACTRNG_H
#include <QObject>
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

View file

@ -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

View file

@ -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);
}

View file

@ -20,10 +20,7 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QTextCodec> #include <QTextCodec>
#include "server.h" #include "servatrice.h"
#include "rng_qt.h"
AbstractRNG *rng;
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
@ -33,10 +30,7 @@ int main(int argc, char *argv[])
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
rng = new RNG_Qt; Servatrice server;
Server server;
server.listen(QHostAddress::Any, 4747);
return app.exec(); return app.exec();
} }

View file

@ -17,17 +17,19 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 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 <QtSql> #include <QtSql>
#include <QSettings> #include <QSettings>
#include "servatrice.h"
#include "server_chatchannel.h"
#include "serversocketinterface.h"
Server::Server(QObject *parent) Servatrice::Servatrice(QObject *parent)
: QTcpServer(parent), nextGameId(0) : 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); settings = new QSettings("servatrice.ini", QSettings::IniFormat, this);
QString dbType = settings->value("database/type").toString(); QString dbType = settings->value("database/type").toString();
@ -37,23 +39,24 @@ Server::Server(QObject *parent)
int size = settings->beginReadArray("chatchannels"); int size = settings->beginReadArray("chatchannels");
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i); settings->setArrayIndex(i);
ChatChannel *newChannel = new ChatChannel(settings->value("name").toString(), Server_ChatChannel *newChannel = new Server_ChatChannel(
settings->value("description").toString(), settings->value("name").toString(),
settings->value("autojoin").toBool(), settings->value("description").toString(),
settings->value("joinmessage").toStringList()); settings->value("autojoin").toBool(),
chatChannels.insert(newChannel->getName(), newChannel); settings->value("joinmessage").toStringList()
connect(newChannel, SIGNAL(channelInfoChanged()), this, SLOT(broadcastChannelUpdate())); );
addChatChannel(newChannel);
} }
settings->endArray(); settings->endArray();
loginMessage = settings->value("messages/login").toStringList(); loginMessage = settings->value("messages/login").toStringList();
} }
Server::~Server() Servatrice::~Servatrice()
{ {
} }
bool Server::openDatabase() bool Servatrice::openDatabase()
{ {
if (!QSqlDatabase::connectionNames().isEmpty()) if (!QSqlDatabase::connectionNames().isEmpty())
QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionNames().at(0)); QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionNames().at(0));
@ -81,27 +84,14 @@ bool Server::openDatabase()
return true; 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); QTcpSocket *socket = tcpServer->nextPendingConnection();
games.insert(newGame->getGameId(), newGame); ServerSocketInterface *ssi = new ServerSocketInterface(this, socket);
connect(newGame, SIGNAL(gameClosing()), this, SLOT(gameClosing())); addClient(ssi);
broadcastGameListUpdate(newGame);
return newGame;
} }
void Server::incomingConnection(int socketId) AuthenticationResult Servatrice::checkUserPassword(const QString &user, const QString &password)
{
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)
{ {
const QString method = settings->value("authentication/method").toString(); const QString method = settings->value("authentication/method").toString();
if (method == "none") if (method == "none")
@ -127,39 +117,3 @@ AuthenticationResult Server::checkUserPassword(const QString &user, const QStrin
} else } else
return UnknownUser; 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<ChatChannel *>(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<ServerGame *>(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());
}

View file

@ -17,5 +17,30 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#include "counter.h" #ifndef SERVATRICE_H
#define SERVATRICE_H
#include <QTcpServer>
#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

View file

@ -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 <QStringList>
#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<QString, ServerSocket::CommandProperties *> 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<QVariant::Type>(), &ServerSocket::cmdPing));
commandHash.insert("login", new GenericCommandProperties(false, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::String, &ServerSocket::cmdLogin));
commandHash.insert("chat_list_channels", new GenericCommandProperties(true, QList<QVariant::Type>(), &ServerSocket::cmdChatListChannels));
commandHash.insert("chat_join_channel", new GenericCommandProperties(true, QList<QVariant::Type>()
<< QVariant::String, &ServerSocket::cmdChatJoinChannel));
commandHash.insert("list_games", new GenericCommandProperties(true, QList<QVariant::Type>(), &ServerSocket::cmdListGames));
commandHash.insert("create_game", new GenericCommandProperties(true, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::String
<< QVariant::Int
<< QVariant::Bool, &ServerSocket::cmdCreateGame));
commandHash.insert("join_game", new GenericCommandProperties(true, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::String
<< QVariant::Bool, &ServerSocket::cmdJoinGame));
commandHash.insert("chat_leave_channel", new ChatCommandProperties(QList<QVariant::Type>(), &ServerSocket::cmdChatLeaveChannel));
commandHash.insert("chat_say", new ChatCommandProperties(QList<QVariant::Type>()
<< QVariant::String, &ServerSocket::cmdChatSay));
commandHash.insert("leave_game", new GameCommandProperties(false, true, QList<QVariant::Type>(), &ServerSocket::cmdLeaveGame));
commandHash.insert("list_players", new GameCommandProperties(false, true, QList<QVariant::Type>(), &ServerSocket::cmdListPlayers));
commandHash.insert("say", new GameCommandProperties(false, false, QList<QVariant::Type>()
<< QVariant::String, &ServerSocket::cmdSay));
commandHash.insert("submit_deck", new GameCommandProperties(false, false, QList<QVariant::Type>(), &ServerSocket::cmdSubmitDeck));
commandHash.insert("ready_start", new GameCommandProperties(false, false, QList<QVariant::Type>(), &ServerSocket::cmdReadyStart));
commandHash.insert("shuffle", new GameCommandProperties(true, false, QList<QVariant::Type>(), &ServerSocket::cmdShuffle));
commandHash.insert("draw_cards", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdDrawCards));
commandHash.insert("reveal_card", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::String, &ServerSocket::cmdRevealCard));
commandHash.insert("move_card", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::String
<< QVariant::String
<< QVariant::Int
<< QVariant::Int
<< QVariant::Bool, &ServerSocket::cmdMoveCard));
commandHash.insert("create_token", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::String
<< QVariant::String
<< QVariant::Int
<< QVariant::Int, &ServerSocket::cmdCreateToken));
commandHash.insert("create_arrow", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< 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::Type>()
<< QVariant::Int, &ServerSocket::cmdDeleteArrow));
commandHash.insert("set_card_attr", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::Int
<< QVariant::String
<< QVariant::String, &ServerSocket::cmdSetCardAttr));
commandHash.insert("inc_counter", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::Int, &ServerSocket::cmdIncCounter));
commandHash.insert("add_counter", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::String
<< QVariant::Int
<< QVariant::Int
<< QVariant::Int, &ServerSocket::cmdAddCounter));
commandHash.insert("set_counter", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::Int, &ServerSocket::cmdSetCounter));
commandHash.insert("del_counter", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdDelCounter));
commandHash.insert("list_counters", new GameCommandProperties(true, true, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdListCounters));
commandHash.insert("list_zones", new GameCommandProperties(true, true, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdListZones));
commandHash.insert("dump_zone", new GameCommandProperties(true, true, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::String
<< QVariant::Int, &ServerSocket::cmdDumpZone));
commandHash.insert("stop_dump_zone", new GameCommandProperties(true, true, QList<QVariant::Type>()
<< QVariant::Int
<< QVariant::String, &ServerSocket::cmdStopDumpZone));
commandHash.insert("roll_die", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdRollDie));
commandHash.insert("next_turn", new GameCommandProperties(true, false, QList<QVariant::Type>(), &ServerSocket::cmdNextTurn));
commandHash.insert("set_active_phase", new GameCommandProperties(true, false, QList<QVariant::Type>()
<< QVariant::Int, &ServerSocket::cmdSetActivePhase));
commandHash.insert("dump_all", new GameCommandProperties(false, true, QList<QVariant::Type>(), &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<QVariant> &/*params*/)
{
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdLogin(const QList<QVariant> &params)
{
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<QVariant> &/*params*/)
{
QMapIterator<QString, ChatChannel *> 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<QVariant> &params)
{
QString channelName = params[0].toString();
if (chatChannels.contains(channelName))
return ReturnMessage::ReturnContextError;
QMap<QString, ChatChannel *> 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<QVariant> & /*params*/)
{
chatChannels.remove(channel->getName());
channel->removePlayer(this);
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdChatSay(ChatChannel *channel, const QList<QVariant> &params)
{
channel->say(this, params[0].toString());
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdListGames(const QList<QVariant> &/*params*/)
{
const QList<ServerGame *> &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<QVariant> &params)
{
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<ServerGame *, Player *>(game, game->getCreator()));
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdJoinGame(const QList<QVariant> &params)
{
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<ServerGame *, Player *>(g, player));
}
return result;
}
ReturnMessage::ReturnCode ServerSocket::cmdLeaveGame(ServerGame *game, Player *player, const QList<QVariant> &/*params*/)
{
game->removePlayer(player);
return ReturnMessage::ReturnOk;
}
QStringList ServerSocket::listPlayersHelper(ServerGame *game, Player *player)
{
QStringList result;
const QList<Player *> &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<QVariant> &/*params*/)
{
remsg->sendList(listPlayersHelper(game, player));
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdSay(ServerGame *game, Player *player, const QList<QVariant> &params)
{
game->broadcastEvent(QString("say|%1").arg(params[0].toString()), player);
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdSubmitDeck(ServerGame * /*game*/, Player *player, const QList<QVariant> &/*params*/)
{
player->setStatus(StatusSubmitDeck);
player->DeckList.clear();
player->SideboardList.clear();
return ReturnMessage::ReturnNothing;
}
ReturnMessage::ReturnCode ServerSocket::cmdReadyStart(ServerGame *game, Player *player, const QList<QVariant> &/*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<QVariant> &/*params*/)
{
player->getZones().value("deck")->shuffle();
game->broadcastEvent("shuffle", player);
return ReturnMessage::ReturnOk;
}
ReturnMessage::ReturnCode ServerSocket::cmdDrawCards(ServerGame *game, Player *player, const QList<QVariant> &params)
{
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<QVariant> &params)
{
/* 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<QVariant> &params)
{
// 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<Player *> &players = game->getPlayers();
for (int i = 0; i < players.size(); ++i) {
QList<int> arrowsToDelete;
QMapIterator<int, Arrow *> 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<QVariant> &params)
{
// 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<QVariant> &params)
{
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<int, Arrow *> 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<QVariant> &params)
{
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<QVariant> &params)
{
// 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<Card *> 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<QVariant> &params)
{
const QMap<int, Counter *> 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<QVariant> &params)
{
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<QVariant> &params)
{
const QMap<int, Counter *> 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<QVariant> &params)
{
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<int, Counter *> 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<QVariant> &params)
{
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<QString, PlayerZone *> 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<QVariant> &params)
{
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<QVariant> &params)
{
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<QVariant> &params)
{
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<QVariant> &params)
{
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<QVariant> &/*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<QVariant> &params)
{
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<int, Arrow *> 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<QVariant> &/*params*/)
{
remsg->sendList(listPlayersHelper(game, player), "list_players");
if (game->getGameStarted()) {
const QList<Player *> &players = game->getPlayers();
for (int i = 0; i < players.size(); ++i) {
remsg->sendList(listZonesHelper(players[i]), "list_zones");
QMapIterator<QString, PlayerZone *> 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<QVariant> ServerSocket::CommandProperties::getParamList(const QStringList &params) const
{
QList<QVariant> 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 &params)
{
QList<QVariant> paramList;
try { paramList = getParamList(params); }
catch (ReturnMessage::ReturnCode rc) { return rc; }
return (s->*handler)(paramList);
}
ReturnMessage::ReturnCode ServerSocket::ChatCommandProperties::exec(ServerSocket *s, QStringList &params)
{
if (params.isEmpty())
return ReturnMessage::ReturnSyntaxError;
QString channelName = params.takeFirst();
ChatChannel *channel = s->getServer()->getChatChannels().value(channelName, 0);
if (!channel)
return ReturnMessage::ReturnNameNotFound;
QList<QVariant> paramList;
try { paramList = getParamList(params); }
catch (ReturnMessage::ReturnCode rc) { return rc; }
return (s->*handler)(channel, paramList);
}
ReturnMessage::ReturnCode ServerSocket::GameCommandProperties::exec(ServerSocket *s, QStringList &params)
{
if (params.isEmpty())
return ReturnMessage::ReturnSyntaxError;
bool ok;
int gameId = params.takeFirst().toInt(&ok);
if (!ok)
return ReturnMessage::ReturnSyntaxError;
QPair<ServerGame *, Player *> 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<QVariant> 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<ServerGame *, Player *> ServerSocket::getGame(int gameId) const
{
if (games.contains(gameId))
return games.value(gameId);
return QPair<ServerGame *, Player *>(0, 0);
}

View file

@ -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 <QTcpSocket>
#include <QList>
#include <QVariant>
#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<QVariant> &);
typedef ReturnMessage::ReturnCode (ServerSocket::*ChatCommandHandler)(ChatChannel *channel, const QList<QVariant> &);
typedef ReturnMessage::ReturnCode (ServerSocket::*GenericCommandHandler)(const QList<QVariant> &);
class CommandProperties {
public:
enum CommandType { ChatCommand, GameCommand, GenericCommand };
private:
CommandType type;
bool needsLogin;
QList<QVariant::Type> paramTypes;
protected:
QList<QVariant> getParamList(const QStringList &params) const;
public:
CommandProperties(CommandType _type, bool _needsLogin, const QList<QVariant::Type> &_paramTypes)
: type(_type), needsLogin(_needsLogin), paramTypes(_paramTypes) { }
bool getNeedsLogin() const { return needsLogin; }
CommandType getType() const { return type; }
const QList<QVariant::Type> &getParamTypes() const { return paramTypes; }
virtual ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList &params) = 0;
};
class ChatCommandProperties : public CommandProperties {
private:
ChatCommandHandler handler;
public:
ChatCommandProperties(const QList<QVariant::Type> &_paramTypes, ChatCommandHandler _handler)
: CommandProperties(ChatCommand, true, _paramTypes), handler(_handler) { }
ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList &params);
};
class GameCommandProperties : public CommandProperties {
private:
bool needsStartedGame;
bool allowedToSpectator;
GameCommandHandler handler;
public:
GameCommandProperties(bool _needsStartedGame, bool _allowedToSpectator, const QList<QVariant::Type> &_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 &params);
};
class GenericCommandProperties : public CommandProperties {
private:
GenericCommandHandler handler;
public:
GenericCommandProperties(bool _needsLogin, const QList<QVariant::Type> &_paramTypes, GenericCommandHandler _handler)
: CommandProperties(GenericCommand, _needsLogin, _paramTypes), handler(_handler) { }
ReturnMessage::ReturnCode exec(ServerSocket *s, QStringList &params);
};
static QHash<QString, CommandProperties *> 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<QVariant> &params);
ReturnMessage::ReturnCode cmdLogin(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdChatListChannels(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdChatJoinChannel(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdListGames(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdCreateGame(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdJoinGame(const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdChatLeaveChannel(ChatChannel *channel, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdChatSay(ChatChannel *channel, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdLeaveGame(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdListPlayers(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdSay(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdSubmitDeck(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdReadyStart(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdShuffle(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdDrawCards(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdRevealCard(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdMoveCard(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdCreateToken(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdCreateArrow(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdDeleteArrow(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdSetCardAttr(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdIncCounter(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdAddCounter(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdSetCounter(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdDelCounter(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdListCounters(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdListZones(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdDumpZone(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdStopDumpZone(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdRollDie(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdNextTurn(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdSetActivePhase(ServerGame *game, Player *player, const QList<QVariant> &params);
ReturnMessage::ReturnCode cmdDumpAll(ServerGame *game, Player *player, const QList<QVariant> &params);
Server *server;
QMap<int, QPair<ServerGame *, Player *> > games;
QMap<QString, ChatChannel *> chatChannels;
QString playerName;
Server *getServer() const { return server; }
QPair<ServerGame *, Player *> 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

View file

@ -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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#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();
}

View file

@ -17,46 +17,30 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef SERVER_H #ifndef SERVERSOCKETINTERFACE_H
#define SERVER_H #define SERVERSOCKETINTERFACE_H
#include <QTcpServer> #include <QTcpSocket>
#include <QStringList> #include <server_protocolhandler.h>
class ServerGame; class QTcpSocket;
class ServerSocket; class Server;
class QSqlDatabase; class QXmlStreamReader;
class QSettings; class QXmlStreamWriter;
class ChatChannel;
enum AuthenticationResult { PasswordWrong = 0, PasswordRight = 1, UnknownUser = 2 }; class ServerSocketInterface : public Server_ProtocolHandler
class Server : public QTcpServer
{ {
Q_OBJECT Q_OBJECT
private slots: private slots:
void gameClosing(); void readClient();
void broadcastChannelUpdate(); void catchSocketError(QAbstractSocket::SocketError socketError);
public:
Server(QObject *parent = 0);
~Server();
QSettings *settings;
bool openDatabase();
AuthenticationResult checkUserPassword(const QString &user, const QString &password);
QList<ServerGame *> getGames() const { return games.values(); }
ServerGame *getGame(int gameId) const;
const QMap<QString, ChatChannel *> &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);
private: private:
void incomingConnection(int SocketId); QTcpSocket *socket;
QMap<int, ServerGame *> games; QXmlStreamWriter *xmlWriter;
QList<ServerSocket *> players; QXmlStreamReader *xmlReader;
QMap<QString, ChatChannel *> chatChannels; public:
int nextGameId; ServerSocketInterface(Server *_server, QTcpSocket *_socket, QObject *parent = 0);
QStringList loginMessage; ~ServerSocketInterface();
}; };
#endif #endif