I have to do an online game but i'm experimenting some trouble with my chain of responsibility. The point is that the "int level" a every step of my chain is changing. I mount up the chain in a TcpClient class contructor, every thing work fine when I test in the same constructor but outside the level is totally different. I brought you some code :
- Parser.cpp
Parser *Parser::setNext(Parser *next)
{
this->next = next;
return (this->next);
}
void Parser::message(QString msg, int id)
{
qDebug() << Q_FUNC_INFO;
qDebug() << "message lvl " << level << "id : " << id;
qDebug() << "message lvl " << level << "msg : " << msg;
if (id <= this->level)
this->writeMessage(msg);
else if (this->next != nullptr)
this->next->message(msg, id);
}
//LaucherParser
LaunchParser::LaunchParser(int lvl)
{
this->level = lvl;
this->next = nullptr;
}
void LaunchParser::writeMessage(QString msg)
{
qDebug() << "msg launch parser:" << msg;
emit launchGame();
}
- TcpClient.cpp
TcpClient::TcpClient(QObject *parent) : QObject(parent),
parsers()
{
ErrorParser parser(0);
EmailParser parser2(1);
LaunchParser parser3(2);
parser.setNext(&parser2);
parser2.setNext(&parser3);
parsers["error"] = &parser;
parsers["email"] = &parser2;
parsers["launch"] = &parser3;
connect(parsers["launch"], SIGNAL(launchGame()), this, SLOT(startGame()));
parsers["error"]->message("Game Starting now", 2); // Traverse toute la chaine de commande
}
void TcpClient::readyRead()
{
qDebug() << "Reading...";
QByteArray data = socket->readAll();
qDebug() << data;
Command command = analyse(data);
qDebug() << "command msg : " << command.msg;
qDebug() << "command id : " << command.id;
parsers["error"]->message(command.msg, command.id);
}
void TcpClient::startGame()
{ // ceci est un SLOT
qDebug() << "Le signal est ok";
}
Command TcpClient::analyse(QByteArray data)
{
QTextCodec *codec = QTextCodec::codecForName("KOI8-R");
QString string = codec->toUnicode(data);
QString codeString = string;
QString msg = string;
codeString.truncate(2);
int id = codeString.toInt();
msg.remove(0, 3);
Command result = {id,msg};
return result;
}
And My server send :
void ServerLounge::sendGame(QTcpSocket *client )
{
qDebug() << "Game starting for :" << client->socketDescriptor();
client->write( "02 launch");
client->waitForBytesWritten(3000);
}
Here is what i get, you can see the level changing. client debug on the left, server on the right