Reformatting code using Kernighan & Ritchie style, tabs, tab width=4.

Command line: astyle --style=kr --indent=force-tab=4 --lineend=linux -n -r <file names>
This commit is contained in:
lotodore committed 2011-02-11 20:02:08 +00:00
1 parent 29dca1846e
commit 02518c67b2
226 files changed
+21869 -20170

No files matched your search

+7 -4
View File
@@ -3,12 +3,15 @@
#include <QtCore> #include <QtCore>
class BadWordCheck: public QObject { class BadWordCheck: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
BadWordCheck(); BadWordCheck();
void setBadWords(QStringList bw) { badWords = bw; } void setBadWords(QStringList bw) {
badWords = bw;
}
bool run(QString); bool run(QString);
+2 -3
View File
@@ -3,7 +3,7 @@
#include <QtCore> #include <QtCore>
CapsFloodCheck::CapsFloodCheck() CapsFloodCheck::CapsFloodCheck()
: capsNumberToTrigger(0) : capsNumberToTrigger(0)
{ {
} }
@@ -16,8 +16,7 @@ bool CapsFloodCheck::run(QString msg)
e.indexIn(msg); e.indexIn(msg);
if(e.matchedLength() != -1 ) return true; if(e.matchedLength() != -1 ) return true;
else return false; else return false;
} } else {
else {
// qDebug() << "The current Caps Flood RegExp is invalid" << endl; // qDebug() << "The current Caps Flood RegExp is invalid" << endl;
return false; return false;
} }
+7 -4
View File
@@ -3,12 +3,15 @@
#include <QtCore> #include <QtCore>
class CapsFloodCheck: public QObject { class CapsFloodCheck: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
CapsFloodCheck(); CapsFloodCheck();
void setCapsNumberToTrigger(int n) { capsNumberToTrigger = n; } void setCapsNumberToTrigger(int n) {
capsNumberToTrigger = n;
}
bool run(QString); bool run(QString);
private: private:
+7 -7
View File
@@ -2,21 +2,21 @@
#include "cleanerserver.h" #include "cleanerserver.h"
#ifdef _WIN32 #ifdef _WIN32
#include <process.h> #include <process.h>
#else #else
#include <unistd.h> #include <unistd.h>
#ifndef daemon #ifndef daemon
int daemon(int, int); int daemon(int, int);
#endif #endif
#endif #endif
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
CleanerServer server; CleanerServer server;
#ifndef _WIN32 #ifndef _WIN32
if (daemon(0, 0) != 0) if (daemon(0, 0) != 0)
return -1; return -1;
#endif #endif
return a.exec(); return a.exec();
} }
+39 -29
View File
@@ -43,15 +43,14 @@ using namespace std;
CleanerConfig::CleanerConfig() CleanerConfig::CleanerConfig()
{ {
// !!!! Revisionsnummer der Configdefaults !!!!! // !!!! Revisionsnummer der Configdefaults !!!!!
configRev = 8; configRev = 8;
// Pfad und Dateinamen setzen // Pfad und Dateinamen setzen
#ifdef _WIN32 #ifdef _WIN32
const char *appDataPath = getenv("AppData"); const char *appDataPath = getenv("AppData");
if (appDataPath && appDataPath[0] != 0) { if (appDataPath && appDataPath[0] != 0) {
configFileName = appDataPath; configFileName = appDataPath;
} } else {
else {
const int MaxPathSize = 1024; const int MaxPathSize = 1024;
char curDir[MaxPathSize + 1]; char curDir[MaxPathSize + 1];
curDir[0] = 0; curDir[0] = 0;
@@ -67,8 +66,7 @@ CleanerConfig::CleanerConfig()
// Datei wieder loeschen. // Datei wieder loeschen.
tmpFile.close(); tmpFile.close();
remove((configFileName + "\\" + tmpFileName).c_str()); remove((configFileName + "\\" + tmpFileName).c_str());
} } else {
else {
// Fehlgeschlagen, Verzeichnis nicht beschreibbar // Fehlgeschlagen, Verzeichnis nicht beschreibbar
curDir[0] = 0; curDir[0] = 0;
GetTempPathA(MaxPathSize, curDir); GetTempPathA(MaxPathSize, curDir);
@@ -122,8 +120,8 @@ CleanerConfig::CleanerConfig()
configList.push_back(ConfigInfo("CapsFloodCapsNumberToTrigger", CONFIG_TYPE_INT, "10")); configList.push_back(ConfigInfo("CapsFloodCapsNumberToTrigger", CONFIG_TYPE_INT, "10"));
configList.push_back(ConfigInfo("LetterRepeatingNumberToTrigger", CONFIG_TYPE_INT, "10")); configList.push_back(ConfigInfo("LetterRepeatingNumberToTrigger", CONFIG_TYPE_INT, "10"));
configList.push_back(ConfigInfo("KickNumberToBan", CONFIG_TYPE_INT, "2")); configList.push_back(ConfigInfo("KickNumberToBan", CONFIG_TYPE_INT, "2"));
configList.push_back(ConfigInfo("SecondsToForgetAboutKick", CONFIG_TYPE_INT, "1800")); configList.push_back(ConfigInfo("SecondsToForgetAboutKick", CONFIG_TYPE_INT, "1800"));
list<string> badWordsList; list<string> badWordsList;
badWordsList.push_back("arsch"); badWordsList.push_back("arsch");
@@ -183,17 +181,18 @@ CleanerConfig::CleanerConfig()
//Prüfen ob Configfile existiert --> sonst anlegen //Prüfen ob Configfile existiert --> sonst anlegen
TiXmlDocument doc(configFileName); TiXmlDocument doc(configFileName);
if(!doc.LoadFile()){ if(!doc.LoadFile()) {
myConfigState = NONEXISTING; myConfigState = NONEXISTING;
updateConfig(myConfigState); updateConfig(myConfigState);
} } else {
else { //Check if config revision is ok. Otherwise --> update()
//Check if config revision is ok. Otherwise --> update()
int tempRevision = 0; int tempRevision = 0;
TiXmlHandle docHandle( &doc ); TiXmlHandle docHandle( &doc );
TiXmlElement* confRevision = docHandle.FirstChild( "PokerTHCleaner" ).FirstChild( "Configuration" ).FirstChild( "ConfigRevision" ).ToElement(); TiXmlElement* confRevision = docHandle.FirstChild( "PokerTHCleaner" ).FirstChild( "Configuration" ).FirstChild( "ConfigRevision" ).ToElement();
if ( confRevision ) { confRevision->QueryIntAttribute("value", &tempRevision ); } if ( confRevision ) {
confRevision->QueryIntAttribute("value", &tempRevision );
}
if (tempRevision < configRev ) { /*löschen()*/ if (tempRevision < configRev ) { /*löschen()*/
myConfigState = OLD; myConfigState = OLD;
@@ -211,7 +210,8 @@ CleanerConfig::~CleanerConfig()
} }
void CleanerConfig::fillBuffer() { void CleanerConfig::fillBuffer()
{
string tempString1(""); string tempString1("");
string tempString2(""); string tempString2("");
@@ -219,7 +219,7 @@ void CleanerConfig::fillBuffer() {
TiXmlDocument doc(configFileName); TiXmlDocument doc(configFileName);
if(doc.LoadFile()) { if(doc.LoadFile()) {
TiXmlHandle docHandle( &doc ); TiXmlHandle docHandle( &doc );
for (size_t i=0; i<configBufferList.size(); i++) { for (size_t i=0; i<configBufferList.size(); i++) {
@@ -247,13 +247,15 @@ void CleanerConfig::fillBuffer() {
configBufferList[i].defaultListValue = tempStringList2; configBufferList[i].defaultListValue = tempStringList2;
} }
} }
} else {
qDebug("Could not find the root element in the config file!");
} }
else { qDebug("Could not find the root element in the config file!"); }
} }
} }
} }
void CleanerConfig::writeBuffer() const { void CleanerConfig::writeBuffer() const
{
TiXmlDocument doc; TiXmlDocument doc;
TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", ""); TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "");
@@ -291,7 +293,8 @@ void CleanerConfig::writeBuffer() const {
} }
void CleanerConfig::updateConfig(ConfigState myConfigState) { void CleanerConfig::updateConfig(ConfigState myConfigState)
{
size_t i; size_t i;
@@ -368,10 +371,10 @@ void CleanerConfig::updateConfig(ConfigState myConfigState) {
TiXmlElement* oldConf = oldDocHandle.FirstChild( "PokerTHCleaner" ).FirstChild( "Configuration" ).FirstChild( configList[i].name ).ToElement(); TiXmlElement* oldConf = oldDocHandle.FirstChild( "PokerTHCleaner" ).FirstChild( "Configuration" ).FirstChild( configList[i].name ).ToElement();
if ( oldConf ) { if ( oldConf ) {
// if element is already there --> take over the saved values // if element is already there --> take over the saved values
if(configList[i].name != "ConfigRevision") { if(configList[i].name != "ConfigRevision") {
// dont update ConfigRevision because it was already set ^ // dont update ConfigRevision because it was already set ^
TiXmlElement *tmpElement = new TiXmlElement(configList[i].name); TiXmlElement *tmpElement = new TiXmlElement(configList[i].name);
config->LinkEndChild( tmpElement ); config->LinkEndChild( tmpElement );
@@ -392,7 +395,7 @@ void CleanerConfig::updateConfig(ConfigState myConfigState) {
for( ; oldConfList; oldConfList=oldConfList->NextSiblingElement()) { for( ; oldConfList; oldConfList=oldConfList->NextSiblingElement()) {
tempStringList2.push_back(oldConfList->Attribute("value")); tempStringList2.push_back(oldConfList->Attribute("value"));
} }
tmpElement->SetAttribute("type", "list"); tmpElement->SetAttribute("type", "list");
list<string> tempList = tempStringList2; list<string> tempList = tempStringList2;
@@ -406,8 +409,7 @@ void CleanerConfig::updateConfig(ConfigState myConfigState) {
} }
} }
} }
} } else {
else {
// if element is not there --> set it with defaultValue // if element is not there --> set it with defaultValue
TiXmlElement *tmpElement = new TiXmlElement(configList[i].name); TiXmlElement *tmpElement = new TiXmlElement(configList[i].name);
config->LinkEndChild( tmpElement ); config->LinkEndChild( tmpElement );
@@ -428,8 +430,9 @@ void CleanerConfig::updateConfig(ConfigState myConfigState) {
} }
} }
newDoc.SaveFile( configFileName ); newDoc.SaveFile( configFileName );
} else {
qDebug("Cannot update config file: Unable to load configuration.");
} }
else { qDebug("Cannot update config file: Unable to load configuration."); }
} }
@@ -449,7 +452,7 @@ string CleanerConfig::readConfigString(string varName) const
} }
return tempString; return tempString;
} }
int CleanerConfig::readConfigInt(string varName) const int CleanerConfig::readConfigInt(string varName) const
{ {
@@ -486,7 +489,7 @@ list<string> CleanerConfig::readConfigStringList(string varName) const
} }
return tempStringList; return tempStringList;
} }
list<int> CleanerConfig::readConfigIntList(string varName) const list<int> CleanerConfig::readConfigIntList(string varName) const
@@ -582,11 +585,14 @@ void CleanerConfig::writeConfigString(string varName, string varCont)
size_t i; size_t i;
for (i=0; i<configBufferList.size(); i++) { for (i=0; i<configBufferList.size(); i++) {
if (configBufferList[i].name == varName) { configBufferList[i].defaultValue = varCont; } if (configBufferList[i].name == varName) {
configBufferList[i].defaultValue = varCont;
}
} }
} }
std::string CleanerConfig::stringToUtf8(const std::string &myString) { std::string CleanerConfig::stringToUtf8(const std::string &myString)
{
QString tmpString = QString::fromStdString(myString); QString tmpString = QString::fromStdString(myString);
std::string myUtf8String = tmpString.toUtf8().constData(); std::string myUtf8String = tmpString.toUtf8().constData();
@@ -594,10 +600,14 @@ std::string CleanerConfig::stringToUtf8(const std::string &myString) {
return myUtf8String; return myUtf8String;
} }
std::string CleanerConfig::stringFromUtf8(const std::string &myString) { std::string CleanerConfig::stringFromUtf8(const std::string &myString)
{
QString tmpString = QString::fromUtf8(myString.c_str()); QString tmpString = QString::fromUtf8(myString.c_str());
return tmpString.toStdString(); return tmpString.toStdString();
} }
std::string CleanerConfig::getDefaultLanguage() { return QLocale::system().name().toStdString(); } std::string CleanerConfig::getDefaultLanguage()
{
return QLocale::system().name().toStdString();
}
+6 -4
View File
@@ -28,13 +28,16 @@ enum ConfigState { NONEXISTING, OLD };
enum ConfigType { CONFIG_TYPE_INT, CONFIG_TYPE_STRING, CONFIG_TYPE_INT_LIST, CONFIG_TYPE_STRING_LIST }; enum ConfigType { CONFIG_TYPE_INT, CONFIG_TYPE_STRING, CONFIG_TYPE_INT_LIST, CONFIG_TYPE_STRING_LIST };
class CleanerConfig{ class CleanerConfig
{
public: public:
CleanerConfig(); CleanerConfig();
~CleanerConfig(); ~CleanerConfig();
std::string getConfigFileName() const { return configFileName; } std::string getConfigFileName() const {
return configFileName;
}
void fillBuffer(); void fillBuffer();
void writeBuffer() const; void writeBuffer() const;
@@ -57,8 +60,7 @@ public:
private: private:
struct ConfigInfo struct ConfigInfo {
{
ConfigInfo(const std::string &n, ConfigType t, const std::string &d, const std::list<std::string> &l =std::list<std::string>()) : name(n), type(t), defaultValue(d), defaultListValue(l) {} ConfigInfo(const std::string &n, ConfigType t, const std::string &d, const std::list<std::string> &l =std::list<std::string>()) : name(n), type(t), defaultValue(d), defaultListValue(l) {}
std::string name; std::string name;
ConfigType type; ConfigType type;
+27 -40
View File
@@ -59,24 +59,19 @@ void CleanerServer::onRead()
{ {
qint64 bytesRead = tcpSocket->read((char *)m_recvBuf + m_recvBufUsed, sizeof(m_recvBuf) - m_recvBufUsed); qint64 bytesRead = tcpSocket->read((char *)m_recvBuf + m_recvBufUsed, sizeof(m_recvBuf) - m_recvBufUsed);
bool error = bytesRead < 1; bool error = bytesRead < 1;
if (!error) if (!error) {
{
m_recvBufUsed += bytesRead; m_recvBufUsed += bytesRead;
asn_dec_rval_t retVal; asn_dec_rval_t retVal;
do do {
{
// Try to decode the packets. // Try to decode the packets.
InternalChatCleanerPacket recvMsg; InternalChatCleanerPacket recvMsg;
retVal = ber_decode(0, &asn_DEF_ChatCleanerMessage, (void **)recvMsg.GetMsgPtr(), m_recvBuf, m_recvBufUsed); retVal = ber_decode(0, &asn_DEF_ChatCleanerMessage, (void **)recvMsg.GetMsgPtr(), m_recvBuf, m_recvBufUsed);
if(retVal.code == RC_OK) if(retVal.code == RC_OK) {
{ if (retVal.consumed < m_recvBufUsed) {
if (retVal.consumed < m_recvBufUsed)
{
m_recvBufUsed -= retVal.consumed; m_recvBufUsed -= retVal.consumed;
memmove(m_recvBuf, m_recvBuf + retVal.consumed, m_recvBufUsed); memmove(m_recvBuf, m_recvBuf + retVal.consumed, m_recvBufUsed);
} } else
else
m_recvBufUsed = 0; m_recvBufUsed = 0;
// Handle the packets. // Handle the packets.
@@ -85,8 +80,7 @@ void CleanerServer::onRead()
} while (!error && retVal.code == RC_OK); } while (!error && retVal.code == RC_OK);
} }
if (error) if (error) {
{
qDebug() << "Error handling packets from client."; qDebug() << "Error handling packets from client.";
tcpSocket->close(); tcpSocket->close();
} }
@@ -104,16 +98,14 @@ void CleanerServer::onRead()
tcpSocket->write(checkMessage.toAscii().data(), checkMessage.length());*/ tcpSocket->write(checkMessage.toAscii().data(), checkMessage.length());*/
} }
bool CleanerServer::handleMessage(InternalChatCleanerPacket &msg) { bool CleanerServer::handleMessage(InternalChatCleanerPacket &msg)
{
bool error = true; bool error = true;
if (msg.GetMsg()->present == ChatCleanerMessage_PR_cleanerInitMessage) if (msg.GetMsg()->present == ChatCleanerMessage_PR_cleanerInitMessage) {
{
CleanerInitMessage_t *netInit = &msg.GetMsg()->choice.cleanerInitMessage; CleanerInitMessage_t *netInit = &msg.GetMsg()->choice.cleanerInitMessage;
if (netInit->requestedVersion == CLEANER_PROTOCOL_VERSION) if (netInit->requestedVersion == CLEANER_PROTOCOL_VERSION) {
{
string tmpClientSecret((const char *)netInit->clientSecret.buf, netInit->clientSecret.size); string tmpClientSecret((const char *)netInit->clientSecret.buf, netInit->clientSecret.size);
if (clientSecret == QString::fromStdString(tmpClientSecret)) if (clientSecret == QString::fromStdString(tmpClientSecret)) {
{
error = false; error = false;
InternalChatCleanerPacket tmpAck; InternalChatCleanerPacket tmpAck;
@@ -125,28 +117,23 @@ bool CleanerServer::handleMessage(InternalChatCleanerPacket &msg) {
tmpServerSecret.c_str(), tmpServerSecret.c_str(),
tmpServerSecret.length()); tmpServerSecret.length());
sendMessageToClient(tmpAck); sendMessageToClient(tmpAck);
} } else
else
qDebug() << "Invalid client secret."; qDebug() << "Invalid client secret.";
} } else
else
qDebug() << "Invalid client version: " << netInit->requestedVersion; qDebug() << "Invalid client version: " << netInit->requestedVersion;
} } else if (msg.GetMsg()->present == ChatCleanerMessage_PR_cleanerChatRequestMessage) {
else if (msg.GetMsg()->present == ChatCleanerMessage_PR_cleanerChatRequestMessage)
{
error = false; error = false;
CleanerChatRequestMessage_t *netRequest = &msg.GetMsg()->choice.cleanerChatRequestMessage; CleanerChatRequestMessage_t *netRequest = &msg.GetMsg()->choice.cleanerChatRequestMessage;
unsigned playerId = netRequest->playerId; unsigned playerId = netRequest->playerId;
QString nick(QString::fromUtf8( QString nick(QString::fromUtf8(
string((const char *)netRequest->playerName.buf, netRequest->playerName.size).c_str())); string((const char *)netRequest->playerName.buf, netRequest->playerName.size).c_str()));
QString message(QString::fromUtf8( QString message(QString::fromUtf8(
string((const char *)netRequest->chatMessage.buf, netRequest->chatMessage.size).c_str())); string((const char *)netRequest->chatMessage.buf, netRequest->chatMessage.size).c_str()));
QStringList checkreturn = myMessageFilter->check(playerId, nick, message); QStringList checkreturn = myMessageFilter->check(playerId, nick, message);
QString checkAction = checkreturn.at(0); QString checkAction = checkreturn.at(0);
QString checkMessage = checkreturn.at(1); QString checkMessage = checkreturn.at(1);
if (!checkAction.isEmpty()) if (!checkAction.isEmpty()) {
{
InternalChatCleanerPacket tmpReply; InternalChatCleanerPacket tmpReply;
tmpReply.GetMsg()->present = ChatCleanerMessage_PR_cleanerChatReplyMessage; tmpReply.GetMsg()->present = ChatCleanerMessage_PR_cleanerChatReplyMessage;
CleanerChatReplyMessage_t *netReply = &tmpReply.GetMsg()->choice.cleanerChatReplyMessage; CleanerChatReplyMessage_t *netReply = &tmpReply.GetMsg()->choice.cleanerChatReplyMessage;
@@ -156,33 +143,33 @@ bool CleanerServer::handleMessage(InternalChatCleanerPacket &msg) {
if(checkAction == "warn") { if(checkAction == "warn") {
netReply->cleanerActionType = cleanerActionType_cleanerActionWarning; netReply->cleanerActionType = cleanerActionType_cleanerActionWarning;
} } else if(checkAction == "kick") {
else if(checkAction == "kick") {
netReply->cleanerActionType = cleanerActionType_cleanerActionKick; netReply->cleanerActionType = cleanerActionType_cleanerActionKick;
} } else if(checkAction == "kickban") {
else if(checkAction == "kickban") {
netReply->cleanerActionType = cleanerActionType_cleanerActionBan; netReply->cleanerActionType = cleanerActionType_cleanerActionBan;
} }
string tmpCheck(checkMessage.toUtf8()); string tmpCheck(checkMessage.toUtf8());
netReply->cleanerText = netReply->cleanerText =
OCTET_STRING_new_fromBuf( OCTET_STRING_new_fromBuf(
&asn_DEF_OCTET_STRING, &asn_DEF_OCTET_STRING,
(const char *)tmpCheck.c_str(), (const char *)tmpCheck.c_str(),
tmpCheck.length()); tmpCheck.length());
sendMessageToClient(tmpReply); sendMessageToClient(tmpReply);
} }
} }
return error; return error;
} }
void CleanerServer::socketStateChanged(QAbstractSocket::SocketState state) { void CleanerServer::socketStateChanged(QAbstractSocket::SocketState state)
{
qDebug() << "Socket state changed to: " << QAbstractSocket::UnconnectedState; qDebug() << "Socket state changed to: " << QAbstractSocket::UnconnectedState;
if(state == QAbstractSocket::UnconnectedState) blockConnection = false; if(state == QAbstractSocket::UnconnectedState) blockConnection = false;
} }
void CleanerServer::refreshConfig() { void CleanerServer::refreshConfig()
{
QFileInfo configFileInfo(QString::fromUtf8(config->getConfigFileName().c_str())); QFileInfo configFileInfo(QString::fromUtf8(config->getConfigFileName().c_str()));
+21 -20
View File
@@ -8,36 +8,37 @@
class MessageFilter; class MessageFilter;
class CleanerConfig; class CleanerConfig;
class CleanerServer: public QObject { class CleanerServer: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
CleanerServer(); CleanerServer();
~CleanerServer(); ~CleanerServer();
private slots: private slots:
void newCon(); void newCon();
void onRead(); void onRead();
bool handleMessage(InternalChatCleanerPacket &msg); bool handleMessage(InternalChatCleanerPacket &msg);
void socketStateChanged(QAbstractSocket::SocketState); void socketStateChanged(QAbstractSocket::SocketState);
void refreshConfig(); void refreshConfig();
void sendMessageToClient(InternalChatCleanerPacket &msg); void sendMessageToClient(InternalChatCleanerPacket &msg);
private: private:
QTcpServer *tcpServer; QTcpServer *tcpServer;
QTcpSocket *tcpSocket; QTcpSocket *tcpSocket;
QTimer *configRefreshTimer; QTimer *configRefreshTimer;
MessageFilter *myMessageFilter; MessageFilter *myMessageFilter;
CleanerConfig *config; CleanerConfig *config;
bool blockConnection; bool blockConnection;
QString clientSecret; QString clientSecret;
QString serverSecret; QString serverSecret;
unsigned char m_recvBuf[2*MAX_CLEANER_PACKET_SIZE]; unsigned char m_recvBuf[2*MAX_CLEANER_PACKET_SIZE];
unsigned m_recvBufUsed; unsigned m_recvBufUsed;
int secondsSinceLastConfigChange; int secondsSinceLastConfigChange;
}; };
#endif // CLEANERSERVER_H #endif // CLEANERSERVER_H
+3 -5
View File
@@ -3,7 +3,7 @@
#include <QtCore> #include <QtCore>
LetterRepeatingCheck::LetterRepeatingCheck() LetterRepeatingCheck::LetterRepeatingCheck()
: letterNumberToTrigger(0) : letterNumberToTrigger(0)
{ {
} }
@@ -14,12 +14,10 @@ bool LetterRepeatingCheck::run(QString msg)
if(e.isValid()) { if(e.isValid()) {
if(e.exactMatch(msg)) { if(e.exactMatch(msg)) {
return true; return true;
} } else {
else {
return false; return false;
} }
} } else {
else {
// qDebug() << "The current Letter Repeating RegExp is invalid" << endl; // qDebug() << "The current Letter Repeating RegExp is invalid" << endl;
return false; return false;
} }
+7 -4
View File
@@ -3,12 +3,15 @@
#include <QtCore> #include <QtCore>
class LetterRepeatingCheck: public QObject { class LetterRepeatingCheck: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
LetterRepeatingCheck(); LetterRepeatingCheck();
void setLetterNumberToTrigger(int n) { letterNumberToTrigger = n; } void setLetterNumberToTrigger(int n) {
letterNumberToTrigger = n;
}
bool run(QString); bool run(QString);
private: private:
+154 -158
View File
@@ -10,203 +10,199 @@
#include "urlcheck.h" #include "urlcheck.h"
enum ActionType { enum ActionType {
NOTHING, NOTHING,
WARN, WARN,
KICK, KICK,
KICKBAN KICKBAN
}; };
enum OffenceType { enum OffenceType {
NONE, NONE,
BAD_WORD, BAD_WORD,
TEXT_FLOOD_LINES, TEXT_FLOOD_LINES,
CAPS_FLOOD, CAPS_FLOOD,
LETTER_REPEATING, LETTER_REPEATING,
URL URL
}; };
MessageFilter::MessageFilter(CleanerConfig *c): config(c) MessageFilter::MessageFilter(CleanerConfig *c): config(c)
{ {
myBadWordCheck = new BadWordCheck; myBadWordCheck = new BadWordCheck;
myTextFloodCheck = new TextFloodCheck; myTextFloodCheck = new TextFloodCheck;
myCapsFloodCheck = new CapsFloodCheck; myCapsFloodCheck = new CapsFloodCheck;
myLetterRepeatingCheck = new LetterRepeatingCheck; myLetterRepeatingCheck = new LetterRepeatingCheck;
myUrlCheck = new UrlCheck; myUrlCheck = new UrlCheck;
cleanTimer = new QTimer(); cleanTimer = new QTimer();
connect(cleanTimer, SIGNAL(timeout()), this, SLOT(cleanKickCounterList())); connect(cleanTimer, SIGNAL(timeout()), this, SLOT(cleanKickCounterList()));
cleanTimer->start(30000); cleanTimer->start(30000);
} }
MessageFilter::~MessageFilter() { MessageFilter::~MessageFilter()
{
delete myBadWordCheck; delete myBadWordCheck;
delete myTextFloodCheck; delete myTextFloodCheck;
delete myCapsFloodCheck; delete myCapsFloodCheck;
delete myLetterRepeatingCheck; delete myLetterRepeatingCheck;
delete myUrlCheck; delete myUrlCheck;
delete cleanTimer; delete cleanTimer;
} }
QStringList MessageFilter::check(unsigned playerId, QString nick, QString msg) QStringList MessageFilter::check(unsigned playerId, QString nick, QString msg)
{ {
QStringList returnList; QStringList returnList;
QString returnMessage; QString returnMessage;
QString returnAction; QString returnAction;
OffenceType offence = NONE; OffenceType offence = NONE;
if(myBadWordCheck->run(msg)) offence = BAD_WORD; if(myBadWordCheck->run(msg)) offence = BAD_WORD;
if(myCapsFloodCheck->run(msg)) offence = CAPS_FLOOD; if(myCapsFloodCheck->run(msg)) offence = CAPS_FLOOD;
if(myLetterRepeatingCheck->run(msg)) offence = LETTER_REPEATING; if(myLetterRepeatingCheck->run(msg)) offence = LETTER_REPEATING;
if(myUrlCheck->run(msg)) offence = URL; if(myUrlCheck->run(msg)) offence = URL;
if(myTextFloodCheck->run(playerId)) offence = TEXT_FLOOD_LINES; if(myTextFloodCheck->run(playerId)) offence = TEXT_FLOOD_LINES;
if(offence){ if(offence) {
ActionType action = NOTHING; ActionType action = NOTHING;
QMap<unsigned, ClientWarnInfos>::const_iterator i = myClientWarnLevelList.find(playerId); QMap<unsigned, ClientWarnInfos>::const_iterator i = myClientWarnLevelList.find(playerId);
if(i == myClientWarnLevelList.end()) { if(i == myClientWarnLevelList.end()) {
ClientWarnInfos tmpInfos; ClientWarnInfos tmpInfos;
tmpInfos.warnLevel = 1; tmpInfos.warnLevel = 1;
tmpInfos.lastWarnType = offence; tmpInfos.lastWarnType = offence;
tmpInfos.nick = nick; tmpInfos.nick = nick;
myClientWarnLevelList.insert(playerId, tmpInfos); myClientWarnLevelList.insert(playerId, tmpInfos);
action = WARN; action = WARN;
} } else {
else { if(i.value().warnLevel == warnLevelToKick || i.value().lastWarnType == offence) {
if(i.value().warnLevel == warnLevelToKick || i.value().lastWarnType == offence) { // Kick Command
// Kick Command action = KICK;
action = KICK; //remove playerId from all lists and as LAST from myClientWarnLevelList
//remove playerId from all lists and as LAST from myClientWarnLevelList myTextFloodCheck->removeNickFromList(i.key());
myTextFloodCheck->removeNickFromList(i.key()); myClientWarnLevelList.remove(i.key());
myClientWarnLevelList.remove(i.key()); //check if player is already on kickCounterList
//check if player is already on kickCounterList QMap<QString, ClientKickInfos>::const_iterator j = myClientKickCounterList.find(nick);
QMap<QString, ClientKickInfos>::const_iterator j = myClientKickCounterList.find(nick); if(j == myClientKickCounterList.end()) {
if(j == myClientKickCounterList.end()) { //if player is NOT on this list put the playerId on it to ban after multiple offence
//if player is NOT on this list put the playerId on it to ban after multiple offence ClientKickInfos tmpInfos;
ClientKickInfos tmpInfos; tmpInfos.kickNumber = 1;
tmpInfos.kickNumber = 1; tmpInfos.lastKickTimestamp = timer.elapsed().total_seconds();
tmpInfos.lastKickTimestamp = timer.elapsed().total_seconds(); myClientKickCounterList.insert(nick, tmpInfos);
myClientKickCounterList.insert(nick, tmpInfos); } else {
} //pleayer is already on the list: either raise kickNumber or kickban when kickNumerToBan is reached
else { if(j.value().kickNumber == kickNumberToBan) {
//pleayer is already on the list: either raise kickNumber or kickban when kickNumerToBan is reached action = KICKBAN;
if(j.value().kickNumber == kickNumberToBan) { //remove player from kickCounterList
action = KICKBAN; myClientKickCounterList.remove(j.key());
//remove player from kickCounterList } else {
myClientKickCounterList.remove(j.key()); ClientKickInfos tmpInfos;
} tmpInfos.kickNumber = j.value().kickNumber+1;
else { tmpInfos.lastKickTimestamp = timer.elapsed().total_seconds();
ClientKickInfos tmpInfos; myClientKickCounterList.insert(nick, tmpInfos);
tmpInfos.kickNumber = j.value().kickNumber+1; }
tmpInfos.lastKickTimestamp = timer.elapsed().total_seconds(); }
myClientKickCounterList.insert(nick, tmpInfos); } else {
} ClientWarnInfos tmpInfos;
} tmpInfos.warnLevel = i.value().warnLevel+1;
} tmpInfos.lastWarnType = offence;
else { tmpInfos.nick = nick;
ClientWarnInfos tmpInfos; myClientWarnLevelList.insert(playerId, tmpInfos);
tmpInfos.warnLevel = i.value().warnLevel+1; action = WARN;
tmpInfos.lastWarnType = offence; }
tmpInfos.nick = nick; }
myClientWarnLevelList.insert(playerId, tmpInfos);
action = WARN;
}
}
if(action == WARN) { if(action == WARN) {
switch(offence) { switch(offence) {
case BAD_WORD: { case BAD_WORD: {
returnMessage = QString ("%1: Warning! No racial, religious, or sexually inflammatory language!\n").arg(nick); returnMessage = QString ("%1: Warning! No racial, religious, or sexually inflammatory language!\n").arg(nick);
} }
break; break;
case TEXT_FLOOD_LINES: { case TEXT_FLOOD_LINES: {
returnMessage = QString ("%1: Warning! You've triggered text flood (lines) protection, slow down your typing!\n").arg(nick); returnMessage = QString ("%1: Warning! You've triggered text flood (lines) protection, slow down your typing!\n").arg(nick);
} }
break; break;
case CAPS_FLOOD: { case CAPS_FLOOD: {
returnMessage = QString ("%1: Warning: You've triggered caps flood protection, release your caps!\n").arg(nick); returnMessage = QString ("%1: Warning: You've triggered caps flood protection, release your caps!\n").arg(nick);
} }
break; break;
case LETTER_REPEATING: { case LETTER_REPEATING: {
returnMessage = QString ("%1: Warning: You've triggered letter repeating protection, stop repeating!\n").arg(nick); returnMessage = QString ("%1: Warning: You've triggered letter repeating protection, stop repeating!\n").arg(nick);
} }
break; break;
case URL: { case URL: {
returnMessage = QString ("%1: Warning: You've triggered url spam protection, stop posting urls!\n").arg(nick); returnMessage = QString ("%1: Warning: You've triggered url spam protection, stop posting urls!\n").arg(nick);
} }
break; break;
default:; default:
} ;
returnAction = QString("warn"); }
} returnAction = QString("warn");
else if(action == KICK) { } else if(action == KICK) {
returnMessage = QString("%1 kicked! Please respect: http://chatrules.pokerth.net\n").arg(nick); returnMessage = QString("%1 kicked! Please respect: http://chatrules.pokerth.net\n").arg(nick);
returnAction = QString("kick"); returnAction = QString("kick");
} } else if(action == KICKBAN) {
else if(action == KICKBAN) { returnMessage = QString("%1 kicked and banned! Please respect: http://chatrules.pokerth.net\n").arg(nick);
returnMessage = QString("%1 kicked and banned! Please respect: http://chatrules.pokerth.net\n").arg(nick); returnAction = QString("kickban");
returnAction = QString("kickban"); }
} } else {
} returnAction = QString("");
else { returnMessage = QString("");
returnAction = QString(""); }
returnMessage = QString("");
}
returnList << returnAction << returnMessage; returnList << returnAction << returnMessage;
return returnList; return returnList;
} }
void MessageFilter::refreshConfig() { void MessageFilter::refreshConfig()
{
// global settings // global settings
warnLevelToKick = config->readConfigInt("WarnLevelToKick"); warnLevelToKick = config->readConfigInt("WarnLevelToKick");
kickNumberToBan = config->readConfigInt("KickNumberToBan"); kickNumberToBan = config->readConfigInt("KickNumberToBan");
// special check settings // special check settings
//Bad Words //Bad Words
std::list<std::string> badWordsList = config->readConfigStringList("BadWordsList"); std::list<std::string> badWordsList = config->readConfigStringList("BadWordsList");
std::list<std::string>::iterator it1; std::list<std::string>::iterator it1;
QStringList bwList; QStringList bwList;
for(it1= badWordsList.begin(); it1 != badWordsList.end(); ++it1) { for(it1= badWordsList.begin(); it1 != badWordsList.end(); ++it1) {
bwList << QString::fromUtf8(it1->c_str()); bwList << QString::fromUtf8(it1->c_str());
} }
myBadWordCheck->setBadWords(bwList); myBadWordCheck->setBadWords(bwList);
std::list<std::string> urlStringsList = config->readConfigStringList("UrlStringsList"); std::list<std::string> urlStringsList = config->readConfigStringList("UrlStringsList");
std::list<std::string>::iterator it2; std::list<std::string>::iterator it2;
QStringList urlList; QStringList urlList;
for(it2= urlStringsList.begin(); it2 != urlStringsList.end(); ++it2) { for(it2= urlStringsList.begin(); it2 != urlStringsList.end(); ++it2) {
urlList << QString::fromUtf8(it2->c_str()); urlList << QString::fromUtf8(it2->c_str());
} }
myUrlCheck->setUrlStrings(urlList); myUrlCheck->setUrlStrings(urlList);
std::list<std::string> urlExceptionStringsList = config->readConfigStringList("UrlExceptionStringsList"); std::list<std::string> urlExceptionStringsList = config->readConfigStringList("UrlExceptionStringsList");
std::list<std::string>::iterator it3; std::list<std::string>::iterator it3;
QStringList urlExceptionList; QStringList urlExceptionList;
for(it3= urlExceptionStringsList.begin(); it3 != urlExceptionStringsList.end(); ++it3) { for(it3= urlExceptionStringsList.begin(); it3 != urlExceptionStringsList.end(); ++it3) {
urlExceptionList << QString::fromUtf8(it3->c_str()); urlExceptionList << QString::fromUtf8(it3->c_str());
} }
myUrlCheck->setUrlExceptionStrings(urlExceptionList); myUrlCheck->setUrlExceptionStrings(urlExceptionList);
myTextFloodCheck->setTextFloodLevelToTrigger(config->readConfigInt("TextFloodLevelToTrigger")); myTextFloodCheck->setTextFloodLevelToTrigger(config->readConfigInt("TextFloodLevelToTrigger"));
myCapsFloodCheck->setCapsNumberToTrigger(config->readConfigInt("CapsFloodCapsNumberToTrigger")); myCapsFloodCheck->setCapsNumberToTrigger(config->readConfigInt("CapsFloodCapsNumberToTrigger"));
myLetterRepeatingCheck->setLetterNumberToTrigger(config->readConfigInt("LetterRepeatingNumberToTrigger")); myLetterRepeatingCheck->setLetterNumberToTrigger(config->readConfigInt("LetterRepeatingNumberToTrigger"));
} }
void MessageFilter::cleanKickCounterList() void MessageFilter::cleanKickCounterList()
{ {
QMapIterator<QString, ClientKickInfos> it(myClientKickCounterList); QMapIterator<QString, ClientKickInfos> it(myClientKickCounterList);
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
if(timer.elapsed().total_seconds()-it.value().lastKickTimestamp > static_cast<unsigned>(config->readConfigInt("SecondsToForgetAboutKick"))) { if(timer.elapsed().total_seconds()-it.value().lastKickTimestamp > static_cast<unsigned>(config->readConfigInt("SecondsToForgetAboutKick"))) {
// qDebug() << it.key() << "removed from kick counter list" << endl; // qDebug() << it.key() << "removed from kick counter list" << endl;
myClientKickCounterList.remove(it.key()); myClientKickCounterList.remove(it.key());
} }
} }
} }
+29 -28
View File
@@ -12,46 +12,47 @@ class CapsFloodCheck;
class LetterRepeatingCheck; class LetterRepeatingCheck;
class UrlCheck; class UrlCheck;
class MessageFilter: public QObject { class MessageFilter: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
MessageFilter(CleanerConfig*); MessageFilter(CleanerConfig*);
~MessageFilter(); ~MessageFilter();
QStringList check(unsigned, QString, QString); QStringList check(unsigned, QString, QString);
void refreshConfig(); void refreshConfig();
public slots: public slots:
void cleanKickCounterList(); void cleanKickCounterList();
private: private:
BadWordCheck *myBadWordCheck; BadWordCheck *myBadWordCheck;
TextFloodCheck *myTextFloodCheck; TextFloodCheck *myTextFloodCheck;
CapsFloodCheck *myCapsFloodCheck; CapsFloodCheck *myCapsFloodCheck;
LetterRepeatingCheck *myLetterRepeatingCheck; LetterRepeatingCheck *myLetterRepeatingCheck;
UrlCheck *myUrlCheck; UrlCheck *myUrlCheck;
struct ClientWarnInfos { struct ClientWarnInfos {
QString nick; QString nick;
int lastWarnType; int lastWarnType;
int warnLevel; int warnLevel;
}; };
struct ClientKickInfos { struct ClientKickInfos {
size_t lastKickTimestamp; size_t lastKickTimestamp;
int kickNumber; int kickNumber;
}; };
QMap<unsigned, ClientWarnInfos> myClientWarnLevelList; QMap<unsigned, ClientWarnInfos> myClientWarnLevelList;
QMap<QString, ClientKickInfos> myClientKickCounterList; QMap<QString, ClientKickInfos> myClientKickCounterList;
int warnLevelToKick; int warnLevelToKick;
int kickNumberToBan; int kickNumberToBan;
CleanerConfig *config; CleanerConfig *config;
boost::timers::portable::second_timer timer; boost::timers::portable::second_timer timer;
QTimer *cleanTimer; QTimer *cleanTimer;
}; };
#endif // MESSAGEFILTER_H #endif // MESSAGEFILTER_H
+13 -14
View File
@@ -19,11 +19,12 @@ TextFloodCheck::~TextFloodCheck()
delete cleanTimer; delete cleanTimer;
} }
bool TextFloodCheck::run(unsigned playerId) { bool TextFloodCheck::run(unsigned playerId)
{
QMapIterator<unsigned, TextFloodInfos> it(msgTimesList); QMapIterator<unsigned, TextFloodInfos> it(msgTimesList);
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
// qDebug() << "counter: " << msgTimesList.count() << " playerid: " << it.key() << " floodlevel: " << it.value().floodLevel << " timestamp: " << it.value().timeStamp; // qDebug() << "counter: " << msgTimesList.count() << " playerid: " << it.key() << " floodlevel: " << it.value().floodLevel << " timestamp: " << it.value().timeStamp;
} }
@@ -35,8 +36,7 @@ bool TextFloodCheck::run(unsigned playerId) {
tmpInfos1.timeStamp = timer.elapsed().total_seconds(); tmpInfos1.timeStamp = timer.elapsed().total_seconds();
msgTimesList.insert(playerId, tmpInfos1); msgTimesList.insert(playerId, tmpInfos1);
qDebug () << "Add Player: set player floodlevel to " << tmpInfos1.floodLevel; qDebug () << "Add Player: set player floodlevel to " << tmpInfos1.floodLevel;
} } else {
else {
TextFloodInfos tmpInfos2; TextFloodInfos tmpInfos2;
if(timer.elapsed().total_seconds()-i.value().timeStamp <= 1) { if(timer.elapsed().total_seconds()-i.value().timeStamp <= 1) {
if(i.value().floodLevel == textFloodLevelToTrigger) { if(i.value().floodLevel == textFloodLevelToTrigger) {
@@ -46,13 +46,11 @@ bool TextFloodCheck::run(unsigned playerId) {
qDebug () << "Trigger: set player floodlevel to " << tmpInfos3.floodLevel; qDebug () << "Trigger: set player floodlevel to " << tmpInfos3.floodLevel;
msgTimesList.insert(playerId, tmpInfos3); msgTimesList.insert(playerId, tmpInfos3);
return true; return true;
} } else {
else {
tmpInfos2.floodLevel = i.value().floodLevel+1; tmpInfos2.floodLevel = i.value().floodLevel+1;
qDebug () << "Raise: set player floodlevel to " << tmpInfos2.floodLevel << " from " << i.value().floodLevel; qDebug () << "Raise: set player floodlevel to " << tmpInfos2.floodLevel << " from " << i.value().floodLevel;
} }
} } else {
else {
tmpInfos2.floodLevel = i.value().floodLevel; tmpInfos2.floodLevel = i.value().floodLevel;
qDebug () << "Keep: player floodlevel is " << tmpInfos2.floodLevel << " from " << i.value().floodLevel; qDebug () << "Keep: player floodlevel is " << tmpInfos2.floodLevel << " from " << i.value().floodLevel;
} }
@@ -63,18 +61,18 @@ bool TextFloodCheck::run(unsigned playerId) {
return false; return false;
} }
void TextFloodCheck::cleanMsgTimesList() { void TextFloodCheck::cleanMsgTimesList()
{
QMapIterator<unsigned, TextFloodInfos> it(msgTimesList); QMapIterator<unsigned, TextFloodInfos> it(msgTimesList);
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
if(timer.elapsed().total_seconds()-it.value().timeStamp > 3) { if(timer.elapsed().total_seconds()-it.value().timeStamp > 3) {
if(it.value().floodLevel == 0) { if(it.value().floodLevel == 0) {
msgTimesList.remove(it.key()); msgTimesList.remove(it.key());
qDebug () << "Refresh: player removed from List"; qDebug () << "Refresh: player removed from List";
} } else {
else {
TextFloodInfos tmpInfos; TextFloodInfos tmpInfos;
tmpInfos.floodLevel = it.value().floodLevel-1; tmpInfos.floodLevel = it.value().floodLevel-1;
tmpInfos.timeStamp = it.value().timeStamp; tmpInfos.timeStamp = it.value().timeStamp;
@@ -86,7 +84,8 @@ void TextFloodCheck::cleanMsgTimesList() {
} }
} }
void TextFloodCheck::removeNickFromList(unsigned playerId) { void TextFloodCheck::removeNickFromList(unsigned playerId)
{
// qDebug() << "id " << playerId << "removed from textfloodcheck list" << endl; // qDebug() << "id " << playerId << "removed from textfloodcheck list" << endl;
msgTimesList.remove(playerId); msgTimesList.remove(playerId);
+4 -2
View File
@@ -10,10 +10,12 @@ class TextFloodCheck: public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
TextFloodCheck(); TextFloodCheck();
~TextFloodCheck(); ~TextFloodCheck();
void setTextFloodLevelToTrigger(int level) { textFloodLevelToTrigger = level; } void setTextFloodLevelToTrigger(int level) {
textFloodLevelToTrigger = level;
}
bool run(unsigned); bool run(unsigned);
+3 -1
View File
@@ -22,7 +22,9 @@ bool UrlCheck::run(QString msg)
break; break;
} }
} }
if(!exception) { return true; } if(!exception) {
return true;
}
} }
} }
return false; return false;
+10 -5
View File
@@ -3,13 +3,18 @@
#include <QtCore> #include <QtCore>
class UrlCheck: public QObject { class UrlCheck: public QObject
Q_OBJECT {
Q_OBJECT
public: public:
UrlCheck(); UrlCheck();
void setUrlStrings(QStringList us) { urlStrings = us; } void setUrlStrings(QStringList us) {
void setUrlExceptionStrings(QStringList ues) { urlExceptionStrings = ues; } urlStrings = us;
}
void setUrlExceptionStrings(QStringList ues) {
urlExceptionStrings = ues;
}
bool run(QString); bool run(QString);
private: private:
+514 -507
View File
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -30,7 +30,8 @@ enum ConfigType { CONFIG_TYPE_INT, CONFIG_TYPE_STRING, CONFIG_TYPE_INT_LIST, CON
class QtToolsInterface; class QtToolsInterface;
class ConfigFile{ class ConfigFile
{
public: public:
ConfigFile(char *argv0, bool readonly); ConfigFile(char *argv0, bool readonly);
@@ -40,7 +41,9 @@ public:
void writeBuffer() const; void writeBuffer() const;
void updateConfig(ConfigState); void updateConfig(ConfigState);
ConfigState getConfigState() const { return myConfigState; } ConfigState getConfigState() const {
return myConfigState;
}
std::string readConfigString(std::string varName) const; std::string readConfigString(std::string varName) const;
std::list<std::string> readConfigStringList(std::string varName) const; std::list<std::string> readConfigStringList(std::string varName) const;
@@ -56,8 +59,7 @@ private:
mutable boost::recursive_mutex m_configMutex; mutable boost::recursive_mutex m_configMutex;
struct ConfigInfo struct ConfigInfo {
{
ConfigInfo(const std::string &n, ConfigType t, const std::string &d, const std::list<std::string> &l =std::list<std::string>()) : name(n), type(t), defaultValue(d), defaultListValue(l) {} ConfigInfo(const std::string &n, ConfigType t, const std::string &d, const std::list<std::string> &l =std::list<std::string>()) : name(n), type(t), defaultValue(d), defaultListValue(l) {}
std::string name; std::string name;
ConfigType type; ConfigType type;
+49 -95
View File
@@ -56,23 +56,16 @@ PokerTHMessage_t *
receiveMessage(tcp::socket &socket) receiveMessage(tcp::socket &socket)
{ {
PokerTHMessage_t *msg = NULL; PokerTHMessage_t *msg = NULL;
do do {
{
asn_dec_rval_t retVal = ber_decode(0, &asn_DEF_PokerTHMessage, (void **)&msg, recBuf.data(), recBufPos); asn_dec_rval_t retVal = ber_decode(0, &asn_DEF_PokerTHMessage, (void **)&msg, recBuf.data(), recBufPos);
if(retVal.code == RC_OK && msg != NULL) if(retVal.code == RC_OK && msg != NULL) {
{ if (retVal.consumed < recBufPos) {
if (retVal.consumed < recBufPos)
{
recBufPos -= retVal.consumed; recBufPos -= retVal.consumed;
memmove(recBuf.c_array(), recBuf.c_array() + retVal.consumed, recBufPos); memmove(recBuf.c_array(), recBuf.c_array() + retVal.consumed, recBufPos);
} } else {
else
{
recBufPos = 0; recBufPos = 0;
} }
} } else {
else
{
// Free the partially decoded message (if applicable). // Free the partially decoded message (if applicable).
ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg); ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg);
msg = NULL; msg = NULL;
@@ -86,11 +79,9 @@ bool
sendMessage(tcp::socket &socket, PokerTHMessage_t *msg) sendMessage(tcp::socket &socket, PokerTHMessage_t *msg)
{ {
bool retVal = false; bool retVal = false;
if (msg) if (msg) {
{
asn_enc_rval_t e = der_encode_to_buffer(&asn_DEF_PokerTHMessage, msg, sendBuf.data(), BUF_SIZE); asn_enc_rval_t e = der_encode_to_buffer(&asn_DEF_PokerTHMessage, msg, sendBuf.data(), BUF_SIZE);
if (e.encoded != -1) if (e.encoded != -1) {
{
socket.send(boost::asio::buffer(sendBuf.data(), e.encoded)); socket.send(boost::asio::buffer(sendBuf.data(), e.encoded));
retVal = true; retVal = true;
} }
@@ -102,30 +93,27 @@ sendMessage(tcp::socket &socket, PokerTHMessage_t *msg)
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
try try {
{
// Check command line options. // Check command line options.
po::options_description desc("Allowed options"); po::options_description desc("Allowed options");
desc.add_options() desc.add_options()
("help,h", "produce help message") ("help,h", "produce help message")
("server,s", po::value<string>(), "PokerTH server name") ("server,s", po::value<string>(), "PokerTH server name")
("port,P", po::value<string>(), "PokerTH server port") ("port,P", po::value<string>(), "PokerTH server port")
("mode,m", po::value<int>(), "set mode (0=connection test, 1=lag test)") ("mode,m", po::value<int>(), "set mode (0=connection test, 1=lag test)")
("username,u", po::value<string>(), "user name used for test") ("username,u", po::value<string>(), "user name used for test")
("password,p", po::value<string>(), "password used for test") ("password,p", po::value<string>(), "password used for test")
; ;
po::variables_map vm; po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm); po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm); po::notify(vm);
if (vm.count("help")) if (vm.count("help")) {
{
cout << desc << endl; cout << desc << endl;
return 1; return 1;
} }
if (!vm.count("server") || !vm.count("port") || !vm.count("mode") || !vm.count("username")) if (!vm.count("server") || !vm.count("port") || !vm.count("mode") || !vm.count("username")) {
{
cout << "Missing option!" << endl << desc << endl; cout << "Missing option!" << endl << desc << endl;
return 1; return 1;
} }
@@ -135,22 +123,19 @@ main(int argc, char *argv[])
int mode = vm["mode"].as<int>(); int mode = vm["mode"].as<int>();
string username(vm["username"].as<string>()); string username(vm["username"].as<string>());
string password; string password;
if (vm.count("password")) if (vm.count("password")) {
{
password = vm["password"].as<string>(); password = vm["password"].as<string>();
} }
// Initialise gsasl. // Initialise gsasl.
Gsasl *authContext; Gsasl *authContext;
Gsasl_session *authSession; Gsasl_session *authSession;
int res = gsasl_init(&authContext); int res = gsasl_init(&authContext);
if (res != GSASL_OK) if (res != GSASL_OK) {
{
cout << "gsasl init failed" << endl; cout << "gsasl init failed" << endl;
return 1; return 1;
} }
if (!gsasl_client_support_p(authContext, "SCRAM-SHA-1")) if (!gsasl_client_support_p(authContext, "SCRAM-SHA-1")) {
{
gsasl_done(authContext); gsasl_done(authContext);
cout << "This version of gsasl does not support SCRAM-SHA-1" << endl; cout << "This version of gsasl does not support SCRAM-SHA-1" << endl;
return 1; return 1;
@@ -165,26 +150,22 @@ main(int argc, char *argv[])
tcp::resolver::iterator end; tcp::resolver::iterator end;
tcp::socket socket(io_service); tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found; boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end) while (error && endpoint_iterator != end) {
{
socket.close(); socket.close();
socket.connect(*endpoint_iterator++, error); socket.connect(*endpoint_iterator++, error);
} }
if (error) if (error) {
{
cout << "Connect failed" << endl; cout << "Connect failed" << endl;
return 1; return 1;
} }
if (mode == 1) if (mode == 1) {
{
cout << "Connect.value " << perfTimer.elapsed().total_milliseconds() << endl; cout << "Connect.value " << perfTimer.elapsed().total_milliseconds() << endl;
} }
perfTimer.restart(); perfTimer.restart();
// Receive server information // Receive server information
PokerTHMessage_t *msg = receiveMessage(socket); PokerTHMessage_t *msg = receiveMessage(socket);
if (!msg || msg->present != PokerTHMessage_PR_announceMessage) if (!msg || msg->present != PokerTHMessage_PR_announceMessage) {
{
cout << "Announce failed" << endl; cout << "Announce failed" << endl;
return 1; return 1;
} }
@@ -196,24 +177,19 @@ main(int argc, char *argv[])
InitMessage_t *netInit = &msg->choice.initMessage; InitMessage_t *netInit = &msg->choice.initMessage;
netInit->requestedVersion.major = 1; netInit->requestedVersion.major = 1;
netInit->requestedVersion.minor = 0; netInit->requestedVersion.minor = 0;
if (password.empty()) if (password.empty()) {
{
netInit->login.present = login_PR_guestLogin; netInit->login.present = login_PR_guestLogin;
GuestLogin_t *guestLogin = &netInit->login.choice.guestLogin; GuestLogin_t *guestLogin = &netInit->login.choice.guestLogin;
OCTET_STRING_fromBuf(&guestLogin->nickName, OCTET_STRING_fromBuf(&guestLogin->nickName,
username.c_str(), username.c_str(),
username.length()); username.length());
if (!sendMessage(socket, msg)) if (!sendMessage(socket, msg)) {
{
cout << "Init guest failed" << endl; cout << "Init guest failed" << endl;
return 1; return 1;
} }
} } else {
else
{
int errorCode = gsasl_client_start(authContext, "SCRAM-SHA-1", &authSession); int errorCode = gsasl_client_start(authContext, "SCRAM-SHA-1", &authSession);
if (errorCode == GSASL_OK) if (errorCode == GSASL_OK) {
{
gsasl_property_set(authSession, GSASL_AUTHID, username.c_str()); gsasl_property_set(authSession, GSASL_AUTHID, username.c_str());
gsasl_property_set(authSession, GSASL_PASSWORD, password.c_str()); gsasl_property_set(authSession, GSASL_PASSWORD, password.c_str());
@@ -224,12 +200,9 @@ main(int argc, char *argv[])
size_t tmpOutSize; size_t tmpOutSize;
string nextGsaslMsg; string nextGsaslMsg;
errorCode = gsasl_step(authSession, NULL, 0, &tmpOut, &tmpOutSize); errorCode = gsasl_step(authSession, NULL, 0, &tmpOut, &tmpOutSize);
if (errorCode == GSASL_NEEDS_MORE) if (errorCode == GSASL_NEEDS_MORE) {
{
nextGsaslMsg = string(tmpOut, tmpOutSize); nextGsaslMsg = string(tmpOut, tmpOutSize);
} } else {
else
{
cout << "gsasl step 1 failed" << endl; cout << "gsasl step 1 failed" << endl;
return 1; return 1;
} }
@@ -238,15 +211,13 @@ main(int argc, char *argv[])
OCTET_STRING_fromBuf(&authLogin->clientUserData, OCTET_STRING_fromBuf(&authLogin->clientUserData,
nextGsaslMsg.c_str(), nextGsaslMsg.c_str(),
nextGsaslMsg.length()); nextGsaslMsg.length());
if (!sendMessage(socket, msg)) if (!sendMessage(socket, msg)) {
{
cout << "Init auth request failed" << endl; cout << "Init auth request failed" << endl;
return 1; return 1;
} }
msg = receiveMessage(socket); msg = receiveMessage(socket);
if (!msg || msg->present != PokerTHMessage_PR_authMessage) if (!msg || msg->present != PokerTHMessage_PR_authMessage) {
{
cout << "Auth request failed" << endl; cout << "Auth request failed" << endl;
return 1; return 1;
} }
@@ -255,12 +226,9 @@ main(int argc, char *argv[])
AuthServerChallenge_t *netChallenge = &netAuth->choice.authServerChallenge; AuthServerChallenge_t *netChallenge = &netAuth->choice.authServerChallenge;
string challengeStr = STL_STRING_FROM_OCTET_STRING(netChallenge->serverChallenge); string challengeStr = STL_STRING_FROM_OCTET_STRING(netChallenge->serverChallenge);
errorCode = gsasl_step(authSession, challengeStr.c_str(), challengeStr.size(), &tmpOut, &tmpOutSize); errorCode = gsasl_step(authSession, challengeStr.c_str(), challengeStr.size(), &tmpOut, &tmpOutSize);
if (errorCode == GSASL_NEEDS_MORE) if (errorCode == GSASL_NEEDS_MORE) {
{
nextGsaslMsg = string(tmpOut, tmpOutSize); nextGsaslMsg = string(tmpOut, tmpOutSize);
} } else {
else
{
cout << "gsasl step 2 failed" << endl; cout << "gsasl step 2 failed" << endl;
return 1; return 1;
} }
@@ -275,14 +243,12 @@ main(int argc, char *argv[])
OCTET_STRING_fromBuf(&outResponse->clientResponse, OCTET_STRING_fromBuf(&outResponse->clientResponse,
nextGsaslMsg.c_str(), nextGsaslMsg.c_str(),
nextGsaslMsg.length()); nextGsaslMsg.length());
if (!sendMessage(socket, msg)) if (!sendMessage(socket, msg)) {
{
cout << "Init auth response failed" << endl; cout << "Init auth response failed" << endl;
return 1; return 1;
} }
msg = receiveMessage(socket); msg = receiveMessage(socket);
if (!msg || msg->present != PokerTHMessage_PR_authMessage) if (!msg || msg->present != PokerTHMessage_PR_authMessage) {
{
cout << "Auth response failed" << endl; cout << "Auth response failed" << endl;
return 1; return 1;
} }
@@ -291,15 +257,13 @@ main(int argc, char *argv[])
// Receive init ack // Receive init ack
msg = receiveMessage(socket); msg = receiveMessage(socket);
if (!msg || msg->present != PokerTHMessage_PR_initAckMessage) if (!msg || msg->present != PokerTHMessage_PR_initAckMessage) {
{
cout << "Init ack failed" << endl; cout << "Init ack failed" << endl;
return 1; return 1;
} }
ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg); ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg);
if (mode == 1) if (mode == 1) {
{
cout << "Init.value " << perfTimer.elapsed().total_milliseconds() << endl; cout << "Init.value " << perfTimer.elapsed().total_milliseconds() << endl;
} }
perfTimer.restart(); perfTimer.restart();
@@ -310,9 +274,9 @@ main(int argc, char *argv[])
JoinGameRequestMessage_t *netJoinGame = &msg->choice.joinGameRequestMessage; JoinGameRequestMessage_t *netJoinGame = &msg->choice.joinGameRequestMessage;
string tmpGamePassword("blah123"); string tmpGamePassword("blah123");
netJoinGame->password = OCTET_STRING_new_fromBuf( netJoinGame->password = OCTET_STRING_new_fromBuf(
&asn_DEF_UTF8String, &asn_DEF_UTF8String,
tmpGamePassword.c_str(), tmpGamePassword.c_str(),
tmpGamePassword.length()); tmpGamePassword.length());
netJoinGame->joinGameAction.present = joinGameAction_PR_joinNewGame; netJoinGame->joinGameAction.present = joinGameAction_PR_joinNewGame;
JoinNewGame_t *joinNew = &netJoinGame->joinGameAction.choice.joinNewGame; JoinNewGame_t *joinNew = &netJoinGame->joinGameAction.choice.joinNewGame;
string tmpGameName("_perftest_do_not_join_" + username); string tmpGameName("_perftest_do_not_join_" + username);
@@ -330,48 +294,38 @@ main(int argc, char *argv[])
OCTET_STRING_fromBuf(&joinNew->gameInfo.gameName, OCTET_STRING_fromBuf(&joinNew->gameInfo.gameName,
tmpGameName.c_str(), tmpGameName.c_str(),
tmpGameName.length()); tmpGameName.length());
if (!sendMessage(socket, msg)) if (!sendMessage(socket, msg)) {
{
cout << "Create game failed" << endl; cout << "Create game failed" << endl;
return 1; return 1;
} }
msg = NULL; msg = NULL;
// Receive join game ack // Receive join game ack
do do {
{
ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg); ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg);
msg = receiveMessage(socket); msg = receiveMessage(socket);
if (!msg) if (!msg) {
{
cout << "Receive in lobby failed" << endl; cout << "Receive in lobby failed" << endl;
return 1; return 1;
} }
if (msg->present == PokerTHMessage_PR_errorMessage) if (msg->present == PokerTHMessage_PR_errorMessage) {
{
cout << "Received error" << endl; cout << "Received error" << endl;
return 1; return 1;
} }
} while (msg->present != PokerTHMessage_PR_joinGameReplyMessage); } while (msg->present != PokerTHMessage_PR_joinGameReplyMessage);
if (msg->choice.joinGameReplyMessage.joinGameResult.present != joinGameResult_PR_joinGameAck) if (msg->choice.joinGameReplyMessage.joinGameResult.present != joinGameResult_PR_joinGameAck) {
{
cout << "Join game ack failed" << endl; cout << "Join game ack failed" << endl;
return 1; return 1;
} }
ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg); ASN_STRUCT_FREE(asn_DEF_PokerTHMessage, msg);
if (mode == 1) if (mode == 1) {
{
cout << "CreateGame.value " << perfTimer.elapsed().total_milliseconds() << endl; cout << "CreateGame.value " << perfTimer.elapsed().total_milliseconds() << endl;
} } else {
else
{
cout << "Success" << endl; cout << "Success" << endl;
} }
perfTimer.restart(); perfTimer.restart();
gsasl_done(authContext); gsasl_done(authContext);
} } catch (...) {
catch (...)
{
cout << "Exception caught" << endl; cout << "Exception caught" << endl;
return 1; return 1;
} }
+1 -1
View File
@@ -42,7 +42,7 @@ class AvatarManager
public: public:
AvatarManager(bool useExternalServer = false, const std::string &externalServerAddress = "", AvatarManager(bool useExternalServer = false, const std::string &externalServerAddress = "",
const std::string &externalServerUser = "", const std::string &externalServerPassword = ""); const std::string &externalServerUser = "", const std::string &externalServerPassword = "");
~AvatarManager(); ~AvatarManager();
bool Init(const std::string &dataDir, const std::string &cacheDir); bool Init(const std::string &dataDir, const std::string &cacheDir);
+88 -146
View File
@@ -48,15 +48,14 @@
using namespace std; using namespace std;
using namespace boost::filesystem; using namespace boost::filesystem;
struct AvatarFileState struct AvatarFileState {
{
ifstream inputStream; ifstream inputStream;
}; };
AvatarManager::AvatarManager(bool useExternalServer, const std::string &externalServerAddress, AvatarManager::AvatarManager(bool useExternalServer, const std::string &externalServerAddress,
const string &externalServerUser, const string &externalServerPassword) const string &externalServerUser, const string &externalServerPassword)
: m_useExternalServer(useExternalServer), m_externalServerAddress(externalServerAddress), : m_useExternalServer(useExternalServer), m_externalServerAddress(externalServerAddress),
m_externalServerUser(externalServerUser), m_externalServerPassword(externalServerPassword) m_externalServerUser(externalServerUser), m_externalServerPassword(externalServerPassword)
{ {
m_uploader.reset(new UploaderThread()); m_uploader.reset(new UploaderThread());
} }
@@ -87,8 +86,7 @@ AvatarManager::Init(const string &dataDir, const string &cacheDir)
} }
if (cacheDir.empty() || tmpCachePath.empty()) if (cacheDir.empty() || tmpCachePath.empty())
LOG_ERROR("Cache directory was not set!"); LOG_ERROR("Cache directory was not set!");
else else {
{
boost::mutex::scoped_lock lock(m_cachedAvatarsMutex); boost::mutex::scoped_lock lock(m_cachedAvatarsMutex);
tmpRet = InternalReadDirectory(tmpCachePath.directory_string(), m_cachedAvatars); tmpRet = InternalReadDirectory(tmpCachePath.directory_string(), m_cachedAvatars);
retVal = retVal && tmpRet; retVal = retVal && tmpRet;
@@ -105,20 +103,17 @@ AvatarManager::AddSingleAvatar(const std::string &fileName)
path filePath(fileName); path filePath(fileName);
string tmpFileName(filePath.file_string()); string tmpFileName(filePath.file_string());
if (!fileName.empty() && !tmpFileName.empty()) if (!fileName.empty() && !tmpFileName.empty()) {
{
unsigned outFileSize = 0; unsigned outFileSize = 0;
AvatarFileType outFileType; AvatarFileType outFileType;
boost::shared_ptr<AvatarFileState> tmpFileState = OpenAvatarFileForChunkRead(tmpFileName, outFileSize, outFileType); boost::shared_ptr<AvatarFileState> tmpFileState = OpenAvatarFileForChunkRead(tmpFileName, outFileSize, outFileType);
// Check whether the avatar file is valid. // Check whether the avatar file is valid.
if (tmpFileState.get()) if (tmpFileState.get()) {
{
tmpFileState.reset(); tmpFileState.reset();
MD5Buf md5buf; MD5Buf md5buf;
if (CryptHelper::MD5Sum(tmpFileName, md5buf)) if (CryptHelper::MD5Sum(tmpFileName, md5buf)) {
{
boost::mutex::scoped_lock lock(m_avatarsMutex); boost::mutex::scoped_lock lock(m_avatarsMutex);
m_avatars.insert(AvatarMap::value_type(md5buf, tmpFileName)); m_avatars.insert(AvatarMap::value_type(md5buf, tmpFileName));
retVal = true; retVal = true;
@@ -133,13 +128,11 @@ AvatarManager::OpenAvatarFileForChunkRead(const std::string &fileName, unsigned
{ {
outFileSize = 0; outFileSize = 0;
boost::shared_ptr<AvatarFileState> retVal; boost::shared_ptr<AvatarFileState> retVal;
try try {
{
outFileType = GetAvatarFileType(fileName); outFileType = GetAvatarFileType(fileName);
boost::shared_ptr<AvatarFileState> fileState(new AvatarFileState); boost::shared_ptr<AvatarFileState> fileState(new AvatarFileState);
fileState->inputStream.open(fileName.c_str(), ios_base::in | ios_base::binary); fileState->inputStream.open(fileName.c_str(), ios_base::in | ios_base::binary);
if (!fileState->inputStream.fail()) if (!fileState->inputStream.fail()) {
{
// Find out file size. // Find out file size.
// Not fully portable, but works on win/linux/mac. // Not fully portable, but works on win/linux/mac.
fileState->inputStream.seekg(0, ios_base::beg); fileState->inputStream.seekg(0, ios_base::beg);
@@ -149,8 +142,7 @@ AvatarManager::OpenAvatarFileForChunkRead(const std::string &fileName, unsigned
fileState->inputStream.seekg(0, ios_base::beg); fileState->inputStream.seekg(0, ios_base::beg);
std::streamoff posDiff(endPos - startPos); std::streamoff posDiff(endPos - startPos);
outFileSize = (unsigned)posDiff; outFileSize = (unsigned)posDiff;
if (outFileSize >= MIN_AVATAR_FILE_SIZE && outFileSize <= MAX_AVATAR_FILE_SIZE) if (outFileSize >= MIN_AVATAR_FILE_SIZE && outFileSize <= MAX_AVATAR_FILE_SIZE) {
{
// Validate type of file by verifying image header. // Validate type of file by verifying image header.
unsigned char fileHeader[MAX_HEADER_SIZE]; unsigned char fileHeader[MAX_HEADER_SIZE];
fileState->inputStream.read((char *)fileHeader, sizeof(fileHeader)); fileState->inputStream.read((char *)fileHeader, sizeof(fileHeader));
@@ -160,8 +152,7 @@ AvatarManager::OpenAvatarFileForChunkRead(const std::string &fileName, unsigned
retVal = fileState; retVal = fileState;
} }
} }
} catch (...) } catch (...) {
{
LOG_ERROR("Exception caught when trying to open avatar."); LOG_ERROR("Exception caught when trying to open avatar.");
} }
return retVal; return retVal;
@@ -171,17 +162,13 @@ unsigned
AvatarManager::ChunkReadAvatarFile(boost::shared_ptr<AvatarFileState> fileState, unsigned char *data, unsigned chunkSize) AvatarManager::ChunkReadAvatarFile(boost::shared_ptr<AvatarFileState> fileState, unsigned char *data, unsigned chunkSize)
{ {
unsigned retVal = 0; unsigned retVal = 0;
if (fileState.get()) if (fileState.get()) {
{ try {
try if (!fileState->inputStream.fail() && !fileState->inputStream.eof()) {
{
if (!fileState->inputStream.fail() && !fileState->inputStream.eof())
{
fileState->inputStream.read((char *)data, chunkSize); fileState->inputStream.read((char *)data, chunkSize);
retVal = fileState->inputStream.gcount(); retVal = fileState->inputStream.gcount();
} }
} catch (...) } catch (...) {
{
LOG_ERROR("Exception caught when trying to read avatar."); LOG_ERROR("Exception caught when trying to read avatar.");
} }
} }
@@ -195,8 +182,7 @@ AvatarManager::AvatarFileToNetPackets(const string &fileName, unsigned requestId
unsigned fileSize = 0; unsigned fileSize = 0;
AvatarFileType fileType; AvatarFileType fileType;
boost::shared_ptr<AvatarFileState> tmpState = OpenAvatarFileForChunkRead(fileName, fileSize, fileType); boost::shared_ptr<AvatarFileState> tmpState = OpenAvatarFileForChunkRead(fileName, fileSize, fileType);
if (tmpState.get() && fileSize && fileType != AVATAR_FILE_TYPE_UNKNOWN) if (tmpState.get() && fileSize && fileType != AVATAR_FILE_TYPE_UNKNOWN) {
{
boost::shared_ptr<NetPacket> avatarHeader(new NetPacket(NetPacket::Alloc)); boost::shared_ptr<NetPacket> avatarHeader(new NetPacket(NetPacket::Alloc));
avatarHeader->GetMsg()->present = PokerTHMessage_PR_avatarReplyMessage; avatarHeader->GetMsg()->present = PokerTHMessage_PR_avatarReplyMessage;
AvatarReplyMessage_t *netHeader = &avatarHeader->GetMsg()->choice.avatarReplyMessage; AvatarReplyMessage_t *netHeader = &avatarHeader->GetMsg()->choice.avatarReplyMessage;
@@ -209,11 +195,9 @@ AvatarManager::AvatarFileToNetPackets(const string &fileName, unsigned requestId
unsigned numBytes = 0; unsigned numBytes = 0;
unsigned totalBytesRead = 0; unsigned totalBytesRead = 0;
vector<unsigned char> tmpData(MAX_FILE_DATA_SIZE); vector<unsigned char> tmpData(MAX_FILE_DATA_SIZE);
do do {
{
numBytes = ChunkReadAvatarFile(tmpState, &tmpData[0], MAX_FILE_DATA_SIZE); numBytes = ChunkReadAvatarFile(tmpState, &tmpData[0], MAX_FILE_DATA_SIZE);
if (numBytes) if (numBytes) {
{
totalBytesRead += numBytes; totalBytesRead += numBytes;
boost::shared_ptr<NetPacket> avatarFile(new NetPacket(NetPacket::Alloc)); boost::shared_ptr<NetPacket> avatarFile(new NetPacket(NetPacket::Alloc));
@@ -231,8 +215,7 @@ AvatarManager::AvatarFileToNetPackets(const string &fileName, unsigned requestId
if (fileSize != totalBytesRead) if (fileSize != totalBytesRead)
retVal = ERR_NET_WRONG_AVATAR_SIZE; retVal = ERR_NET_WRONG_AVATAR_SIZE;
else else {
{
boost::shared_ptr<NetPacket> avatarEnd(new NetPacket(NetPacket::Alloc)); boost::shared_ptr<NetPacket> avatarEnd(new NetPacket(NetPacket::Alloc));
avatarEnd->GetMsg()->present = PokerTHMessage_PR_avatarReplyMessage; avatarEnd->GetMsg()->present = PokerTHMessage_PR_avatarReplyMessage;
AvatarReplyMessage_t *netEnd = &avatarEnd->GetMsg()->choice.avatarReplyMessage; AvatarReplyMessage_t *netEnd = &avatarEnd->GetMsg()->choice.avatarReplyMessage;
@@ -268,19 +251,18 @@ string
AvatarManager::GetAvatarFileExtension(AvatarFileType fileType) AvatarManager::GetAvatarFileExtension(AvatarFileType fileType)
{ {
string ext; string ext;
switch (fileType) switch (fileType) {
{ case AVATAR_FILE_TYPE_PNG:
case AVATAR_FILE_TYPE_PNG: ext = ".png";
ext = ".png"; break;
break; case AVATAR_FILE_TYPE_JPG:
case AVATAR_FILE_TYPE_JPG: ext = ".jpg";
ext = ".jpg"; break;
break; case AVATAR_FILE_TYPE_GIF:
case AVATAR_FILE_TYPE_GIF: ext = ".gif";
ext = ".gif"; break;
break; case AVATAR_FILE_TYPE_UNKNOWN:
case AVATAR_FILE_TYPE_UNKNOWN: break;
break;
} }
return ext; return ext;
} }
@@ -289,17 +271,14 @@ bool
AvatarManager::GetHashForAvatar(const std::string &fileName, MD5Buf &md5buf) const AvatarManager::GetHashForAvatar(const std::string &fileName, MD5Buf &md5buf) const
{ {
bool found = false; bool found = false;
if (exists(fileName)) if (exists(fileName)) {
{
// Scan default avatars first. // Scan default avatars first.
{ {
boost::mutex::scoped_lock lock(m_avatarsMutex); boost::mutex::scoped_lock lock(m_avatarsMutex);
AvatarMap::const_iterator i = m_avatars.begin(); AvatarMap::const_iterator i = m_avatars.begin();
AvatarMap::const_iterator end = m_avatars.end(); AvatarMap::const_iterator end = m_avatars.end();
while (i != end) while (i != end) {
{ if (i->second == fileName) {
if (i->second == fileName)
{
md5buf = i->first; md5buf = i->first;
found = true; found = true;
break; break;
@@ -308,15 +287,12 @@ AvatarManager::GetHashForAvatar(const std::string &fileName, MD5Buf &md5buf) con
} }
} }
// Check cached avatars next. // Check cached avatars next.
if (!found) if (!found) {
{
boost::mutex::scoped_lock lock(m_cachedAvatarsMutex); boost::mutex::scoped_lock lock(m_cachedAvatarsMutex);
AvatarMap::const_iterator i = m_cachedAvatars.begin(); AvatarMap::const_iterator i = m_cachedAvatars.begin();
AvatarMap::const_iterator end = m_cachedAvatars.end(); AvatarMap::const_iterator end = m_cachedAvatars.end();
while (i != end) while (i != end) {
{ if (i->second == fileName) {
if (i->second == fileName)
{
md5buf = i->first; md5buf = i->first;
found = true; found = true;
break; break;
@@ -326,8 +302,7 @@ AvatarManager::GetHashForAvatar(const std::string &fileName, MD5Buf &md5buf) con
} }
// Calculate md5 sum if not found. // Calculate md5 sum if not found.
if (!found) if (!found) {
{
if (CryptHelper::MD5Sum(fileName, md5buf)) if (CryptHelper::MD5Sum(fileName, md5buf))
found = true; found = true;
} }
@@ -342,18 +317,15 @@ AvatarManager::GetAvatarFileName(const MD5Buf &md5buf, std::string &fileName) co
{ {
boost::mutex::scoped_lock lock(m_avatarsMutex); boost::mutex::scoped_lock lock(m_avatarsMutex);
AvatarMap::const_iterator pos = m_avatars.find(md5buf); AvatarMap::const_iterator pos = m_avatars.find(md5buf);
if (pos != m_avatars.end()) if (pos != m_avatars.end()) {
{
fileName = pos->second; fileName = pos->second;
retVal = true; retVal = true;
} }
} }
if (!retVal) if (!retVal) {
{
boost::mutex::scoped_lock lock(m_cachedAvatarsMutex); boost::mutex::scoped_lock lock(m_cachedAvatarsMutex);
AvatarMap::const_iterator pos = m_cachedAvatars.find(md5buf); AvatarMap::const_iterator pos = m_cachedAvatars.find(md5buf);
if (pos != m_cachedAvatars.end()) if (pos != m_cachedAvatars.end()) {
{
fileName = pos->second; fileName = pos->second;
retVal = true; retVal = true;
} }
@@ -377,24 +349,19 @@ AvatarManager::StoreAvatarInCache(const MD5Buf &md5buf, AvatarFileType avatarFil
boost::mutex::scoped_lock lock(m_cacheDirMutex); boost::mutex::scoped_lock lock(m_cacheDirMutex);
cacheDir = m_cacheDir; cacheDir = m_cacheDir;
} }
try try {
{
string ext(GetAvatarFileExtension(avatarFileType)); string ext(GetAvatarFileExtension(avatarFileType));
if (!ext.empty() && !cacheDir.empty()) if (!ext.empty() && !cacheDir.empty()) {
{
// Check header before storing file. // Check header before storing file.
if (IsValidAvatarFileType(avatarFileType, data, size)) if (IsValidAvatarFileType(avatarFileType, data, size)) {
{
path tmpPath(cacheDir); path tmpPath(cacheDir);
tmpPath /= (md5buf.ToString() + ext); tmpPath /= (md5buf.ToString() + ext);
string fileName(tmpPath.file_string()); string fileName(tmpPath.file_string());
ofstream o(fileName.c_str(), ios_base::out | ios_base::binary | ios_base::trunc); ofstream o(fileName.c_str(), ios_base::out | ios_base::binary | ios_base::trunc);
if (!o.fail()) if (!o.fail()) {
{
o.write((const char *)data, size); o.write((const char *)data, size);
o.close(); o.close();
if (upload && m_useExternalServer) if (upload && m_useExternalServer) {
{
m_uploader->QueueUpload(m_externalServerAddress, m_externalServerUser, m_externalServerPassword, fileName, size); m_uploader->QueueUpload(m_externalServerAddress, m_externalServerUser, m_externalServerPassword, fileName, size);
} }
@@ -406,8 +373,7 @@ AvatarManager::StoreAvatarInCache(const MD5Buf &md5buf, AvatarFileType avatarFil
} }
} }
} }
} catch (...) } catch (...) {
{
LOG_ERROR("Exception caught when trying to store avatar."); LOG_ERROR("Exception caught when trying to store avatar.");
} }
return retVal; return retVal;
@@ -418,32 +384,28 @@ AvatarManager::IsValidAvatarFileType(AvatarFileType avatarFileType, const unsign
{ {
bool validType = false; bool validType = false;
switch (avatarFileType) switch (avatarFileType) {
{ case AVATAR_FILE_TYPE_PNG:
case AVATAR_FILE_TYPE_PNG: if (fileHeaderSize >= PNG_HEADER_SIZE
if (fileHeaderSize >= PNG_HEADER_SIZE && memcmp(fileHeader, PNG_HEADER, PNG_HEADER_SIZE) == 0) {
&& memcmp(fileHeader, PNG_HEADER, PNG_HEADER_SIZE) == 0) validType = true;
{ }
validType = true; break;
} case AVATAR_FILE_TYPE_JPG:
break; if (fileHeaderSize >= JPG_HEADER_SIZE
case AVATAR_FILE_TYPE_JPG: && memcmp(fileHeader, JPG_HEADER, JPG_HEADER_SIZE) == 0) {
if (fileHeaderSize >= JPG_HEADER_SIZE validType = true;
&& memcmp(fileHeader, JPG_HEADER, JPG_HEADER_SIZE) == 0) }
{ break;
validType = true; case AVATAR_FILE_TYPE_GIF:
} if (fileHeaderSize >= GIF_HEADER_SIZE
break;
case AVATAR_FILE_TYPE_GIF:
if (fileHeaderSize >= GIF_HEADER_SIZE
&& (memcmp(fileHeader, GIF_HEADER_1, GIF_HEADER_SIZE) == 0 && (memcmp(fileHeader, GIF_HEADER_1, GIF_HEADER_SIZE) == 0
|| memcmp(fileHeader, GIF_HEADER_2, GIF_HEADER_SIZE) == 0)) || memcmp(fileHeader, GIF_HEADER_2, GIF_HEADER_SIZE) == 0)) {
{ validType = true;
validType = true; }
} break;
break; case AVATAR_FILE_TYPE_UNKNOWN:
case AVATAR_FILE_TYPE_UNKNOWN: break;
break;
} }
return validType; return validType;
} }
@@ -456,13 +418,11 @@ AvatarManager::RemoveOldAvatarCacheEntries()
boost::mutex::scoped_lock lock(m_cacheDirMutex); boost::mutex::scoped_lock lock(m_cacheDirMutex);
cacheDir = m_cacheDir; cacheDir = m_cacheDir;
} }
try try {
{
path cachePath(cacheDir); path cachePath(cacheDir);
cacheDir = cachePath.directory_string(); cacheDir = cachePath.directory_string();
// Never delete anything if we do not have a special cache dir set. // Never delete anything if we do not have a special cache dir set.
if (!cacheDir.empty()) if (!cacheDir.empty()) {
{
boost::mutex::scoped_lock lock(m_cachedAvatarsMutex); boost::mutex::scoped_lock lock(m_cachedAvatarsMutex);
// First pass: Remove files which no longer exist. // First pass: Remove files which no longer exist.
@@ -473,18 +433,15 @@ AvatarManager::RemoveOldAvatarCacheEntries()
{ {
AvatarMap::const_iterator i = m_cachedAvatars.begin(); AvatarMap::const_iterator i = m_cachedAvatars.begin();
AvatarMap::const_iterator end = m_cachedAvatars.end(); AvatarMap::const_iterator end = m_cachedAvatars.end();
while (i != end) while (i != end) {
{
bool keepFile = false; bool keepFile = false;
path filePath(i->second); path filePath(i->second);
string fileString(filePath.file_string()); string fileString(filePath.file_string());
// Only consider files which are definitely in the cache dir. // Only consider files which are definitely in the cache dir.
if (fileString.size() > cacheDir.size() && fileString.substr(0, cacheDir.size()) == cacheDir) if (fileString.size() > cacheDir.size() && fileString.substr(0, cacheDir.size()) == cacheDir) {
{
// Only consider files with MD5 as file name. // Only consider files with MD5 as file name.
MD5Buf tmpBuf; MD5Buf tmpBuf;
if (exists(filePath) && tmpBuf.FromString(basename(filePath))) if (exists(filePath) && tmpBuf.FromString(basename(filePath))) {
{
++fileCount; ++fileCount;
timeMap.insert(TimeAvatarMap::value_type(last_write_time(filePath), i->first)); timeMap.insert(TimeAvatarMap::value_type(last_write_time(filePath), i->first));
keepFile = true; keepFile = true;
@@ -500,8 +457,7 @@ AvatarManager::RemoveOldAvatarCacheEntries()
{ {
AvatarList::const_iterator i = removeList.begin(); AvatarList::const_iterator i = removeList.begin();
AvatarList::const_iterator end = removeList.end(); AvatarList::const_iterator end = removeList.end();
while (i != end) while (i != end) {
{
m_cachedAvatars.erase(*i); m_cachedAvatars.erase(*i);
++i; ++i;
} }
@@ -514,14 +470,11 @@ AvatarManager::RemoveOldAvatarCacheEntries()
// - delete until only MAX_NUMBER_OF_FILES/2 are left. // - delete until only MAX_NUMBER_OF_FILES/2 are left.
// 2. Files are older than 30 days. // 2. Files are older than 30 days.
if (m_cachedAvatars.size() > MAX_NUMBER_OF_FILES) if (m_cachedAvatars.size() > MAX_NUMBER_OF_FILES) {
{ while (!timeMap.empty() && m_cachedAvatars.size() > MAX_NUMBER_OF_FILES / 2) {
while (!timeMap.empty() && m_cachedAvatars.size() > MAX_NUMBER_OF_FILES / 2)
{
TimeAvatarMap::iterator i = timeMap.begin(); TimeAvatarMap::iterator i = timeMap.begin();
AvatarMap::iterator pos = m_cachedAvatars.find(i->second); AvatarMap::iterator pos = m_cachedAvatars.find(i->second);
if (pos != m_cachedAvatars.end()) if (pos != m_cachedAvatars.end()) {
{
path tmpPath(pos->second); path tmpPath(pos->second);
remove(tmpPath); remove(tmpPath);
m_cachedAvatars.erase(pos); m_cachedAvatars.erase(pos);
@@ -532,14 +485,12 @@ AvatarManager::RemoveOldAvatarCacheEntries()
// Get reference time. // Get reference time.
time_t curTime = time(NULL); time_t curTime = time(NULL);
while (!timeMap.empty() && !m_cachedAvatars.empty()) while (!timeMap.empty() && !m_cachedAvatars.empty()) {
{
TimeAvatarMap::iterator i = timeMap.begin(); TimeAvatarMap::iterator i = timeMap.begin();
if (curTime - i->first < (int)MAX_AVATAR_CACHE_AGE) if (curTime - i->first < (int)MAX_AVATAR_CACHE_AGE)
break; break;
AvatarMap::iterator pos = m_cachedAvatars.find(i->second); AvatarMap::iterator pos = m_cachedAvatars.find(i->second);
if (pos != m_cachedAvatars.end()) if (pos != m_cachedAvatars.end()) {
{
path tmpPath(pos->second); path tmpPath(pos->second);
remove(tmpPath); remove(tmpPath);
m_cachedAvatars.erase(pos); m_cachedAvatars.erase(pos);
@@ -547,8 +498,7 @@ AvatarManager::RemoveOldAvatarCacheEntries()
timeMap.erase(i); timeMap.erase(i);
} }
} }
} catch (...) } catch (...) {
{
LOG_ERROR("Exception caught while cleaning up cache."); LOG_ERROR("Exception caught while cleaning up cache.");
} }
} }
@@ -559,37 +509,29 @@ AvatarManager::InternalReadDirectory(const std::string &dir, AvatarMap &avatars)
bool retVal = true; bool retVal = true;
path tmpPath(dir); path tmpPath(dir);
if (exists(tmpPath) && is_directory(tmpPath)) if (exists(tmpPath) && is_directory(tmpPath)) {
{ try {
try
{
// This method is not thread safe. Only call after locking the map. // This method is not thread safe. Only call after locking the map.
directory_iterator i(tmpPath); directory_iterator i(tmpPath);
directory_iterator end; directory_iterator end;
while (i != end) while (i != end) {
{ if (is_regular(i->status())) {
if (is_regular(i->status()))
{
string md5sum(basename(i->path())); string md5sum(basename(i->path()));
MD5Buf md5buf; MD5Buf md5buf;
string fileName(i->path().file_string()); string fileName(i->path().file_string());
if (md5buf.FromString(md5sum)) if (md5buf.FromString(md5sum)) {
{
// Only consider files with md5sum as name. // Only consider files with md5sum as name.
avatars.insert(AvatarMap::value_type(md5buf, fileName)); avatars.insert(AvatarMap::value_type(md5buf, fileName));
} }
} }
++i; ++i;
} }
} catch (...) } catch (...) {
{
LOG_ERROR("Exception caught when trying to scan avatar directory."); LOG_ERROR("Exception caught when trying to scan avatar directory.");
retVal = false; retVal = false;
} }
} } else {
else
{
LOG_ERROR("Avatar directory does not exist."); LOG_ERROR("Avatar directory does not exist.");
retVal = false; retVal = false;
} }
+20 -40
View File
@@ -53,8 +53,7 @@ HashBuf::ToString() const
char tmpBuf[2 + 1]; char tmpBuf[2 + 1];
tmpBuf[sizeof(tmpBuf) - 1] = 0; tmpBuf[sizeof(tmpBuf) - 1] = 0;
const unsigned char *tmpData = GetData(); const unsigned char *tmpData = GetData();
for (int i = 0; i < GetDataSize(); i++) for (int i = 0; i < GetDataSize(); i++) {
{
sprintf(tmpBuf, "%02x", tmpData[i]); sprintf(tmpBuf, "%02x", tmpData[i]);
retValue += tmpBuf; retValue += tmpBuf;
} }
@@ -67,8 +66,7 @@ HashBuf::FromString(const std::string &text)
// Convert hex-based string to MD5 data. // Convert hex-based string to MD5 data.
bool retVal = false; bool retVal = false;
int tmpSize = GetDataSize(); int tmpSize = GetDataSize();
if (text.size() == 2 * (unsigned)tmpSize) if (text.size() == 2 * (unsigned)tmpSize) {
{
unsigned char *tmpData = GetData(); unsigned char *tmpData = GetData();
const char *t = text.c_str(); const char *t = text.c_str();
int i = 0; int i = 0;
@@ -92,8 +90,7 @@ HashBuf::IsZero() const
int dataSize = GetDataSize(); int dataSize = GetDataSize();
const unsigned char *tmpData = GetData(); const unsigned char *tmpData = GetData();
int i; int i;
for (i = 0; i < dataSize; i++) for (i = 0; i < dataSize; i++) {
{
if (tmpData[i] != 0) if (tmpData[i] != 0)
break; break;
} }
@@ -166,8 +163,7 @@ CryptHelper::MD5Sum(const std::string &fileName, MD5Buf &buf)
bool retVal = false; bool retVal = false;
FILE *file = fopen(fileName.c_str(), "rb"); FILE *file = fopen(fileName.c_str(), "rb");
if (file) if (file) {
{
// Calculate MD5 sum of file. // Calculate MD5 sum of file.
unsigned char readBuf[8192]; unsigned char readBuf[8192];
MD5_CTX context; MD5_CTX context;
@@ -211,15 +207,12 @@ CryptHelper::HMACSha1(const unsigned char *keyData, unsigned keySize, const unsi
retVal = false; retVal = false;
gcry_md_hd_t hd; gcry_md_hd_t hd;
gcry_error_t err = gcry_md_open(&hd, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC); gcry_error_t err = gcry_md_open(&hd, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
if (!err) if (!err) {
{
err = gcry_md_setkey(hd, keyData, keySize); err = gcry_md_setkey(hd, keyData, keySize);
if (!err) if (!err) {
{
gcry_md_write(hd, plainData, plainSize); gcry_md_write(hd, plainData, plainSize);
unsigned char *hash = gcry_md_read(hd, 0); unsigned char *hash = gcry_md_read(hd, 0);
if (hash) if (hash) {
{
memcpy(buf.GetData(), hash, buf.GetDataSize()); memcpy(buf.GetData(), hash, buf.GetDataSize());
retVal = true; retVal = true;
} }
@@ -260,8 +253,7 @@ CryptHelper::AES128Encrypt(const unsigned char *keyData, unsigned keySize, const
{ {
bool retVal = false; bool retVal = false;
unsigned plainSize = static_cast<unsigned>(plainStr.size()); unsigned plainSize = static_cast<unsigned>(plainStr.size());
if (keySize && plainSize) if (keySize && plainSize) {
{
unsigned char key[AES_BLOCK_SIZE]; unsigned char key[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE]; unsigned char iv[AES_BLOCK_SIZE];
BytesToKey(keyData, keySize, key, iv); BytesToKey(keyData, keySize, key, iv);
@@ -281,24 +273,20 @@ CryptHelper::AES128Encrypt(const unsigned char *keyData, unsigned keySize, const
int success = EVP_EncryptInit(&encryptCtx, EVP_aes_128_cbc(), key, iv); int success = EVP_EncryptInit(&encryptCtx, EVP_aes_128_cbc(), key, iv);
EVP_CIPHER_CTX_set_padding(&encryptCtx, 0); EVP_CIPHER_CTX_set_padding(&encryptCtx, 0);
if (success) if (success) {
{
success = EVP_EncryptUpdate(&encryptCtx, &outCipher[0], &outCipherSize, paddedPlainStr, paddedPlainSize); success = EVP_EncryptUpdate(&encryptCtx, &outCipher[0], &outCipherSize, paddedPlainStr, paddedPlainSize);
if (success && outCipherSize) if (success && outCipherSize) {
{
// Since padding is off, this will not modify the cipher. However, parameters need to be set. // Since padding is off, this will not modify the cipher. However, parameters need to be set.
EVP_EncryptFinal(&encryptCtx, &outCipher[0], &outCipherSize); EVP_EncryptFinal(&encryptCtx, &outCipher[0], &outCipherSize);
retVal = true; retVal = true;
} }
} } else
else
outCipher.clear(); outCipher.clear();
#else #else
gcry_cipher_hd_t hd; gcry_cipher_hd_t hd;
gcry_error_t err = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); gcry_error_t err = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0);
if (!err) if (!err) {
{
gcry_cipher_setkey(hd, key, sizeof(key)); gcry_cipher_setkey(hd, key, sizeof(key));
gcry_cipher_setiv(hd, iv, sizeof(iv)); gcry_cipher_setiv(hd, iv, sizeof(iv));
err = gcry_cipher_encrypt(hd, &outCipher[0], cipherSize, paddedPlainStr, paddedPlainSize); err = gcry_cipher_encrypt(hd, &outCipher[0], cipherSize, paddedPlainStr, paddedPlainSize);
@@ -306,8 +294,7 @@ CryptHelper::AES128Encrypt(const unsigned char *keyData, unsigned keySize, const
retVal = true; retVal = true;
else else
outCipher.clear(); outCipher.clear();
} } else
else
outCipher.clear(); outCipher.clear();
gcry_cipher_close(hd); gcry_cipher_close(hd);
@@ -320,8 +307,7 @@ bool
CryptHelper::AES128Decrypt(const unsigned char *keyData, unsigned keySize, const unsigned char *cipher, unsigned cipherSize, string &outPlain) CryptHelper::AES128Decrypt(const unsigned char *keyData, unsigned keySize, const unsigned char *cipher, unsigned cipherSize, string &outPlain)
{ {
bool retVal = false; bool retVal = false;
if (keySize && cipherSize) if (keySize && cipherSize) {
{
unsigned char key[AES_BLOCK_SIZE]; unsigned char key[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE]; unsigned char iv[AES_BLOCK_SIZE];
BytesToKey(keyData, keySize, key, iv); BytesToKey(keyData, keySize, key, iv);
@@ -333,24 +319,20 @@ CryptHelper::AES128Decrypt(const unsigned char *keyData, unsigned keySize, const
int success = EVP_DecryptInit(&decryptCtx, EVP_aes_128_cbc(), key, iv); int success = EVP_DecryptInit(&decryptCtx, EVP_aes_128_cbc(), key, iv);
EVP_CIPHER_CTX_set_padding(&decryptCtx, 0); EVP_CIPHER_CTX_set_padding(&decryptCtx, 0);
if (success) if (success) {
{
success = EVP_DecryptUpdate(&decryptCtx, (unsigned char *)&outPlain[0], &outPlainSize, cipher, cipherSize); success = EVP_DecryptUpdate(&decryptCtx, (unsigned char *)&outPlain[0], &outPlainSize, cipher, cipherSize);
if (success && outPlainSize) if (success && outPlainSize) {
{
// Since padding is off, this will not modify the plain text. However, parameters need to be set. // Since padding is off, this will not modify the plain text. However, parameters need to be set.
EVP_DecryptFinal(&decryptCtx, (unsigned char *)outPlain.c_str(), &outPlainSize); EVP_DecryptFinal(&decryptCtx, (unsigned char *)outPlain.c_str(), &outPlainSize);
retVal = true; retVal = true;
} }
} } else
else
outPlain.clear(); outPlain.clear();
#else #else
gcry_cipher_hd_t hd; gcry_cipher_hd_t hd;
gcry_error_t err = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); gcry_error_t err = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0);
if (!err) if (!err) {
{
gcry_cipher_setkey(hd, key, sizeof(key)); gcry_cipher_setkey(hd, key, sizeof(key));
gcry_cipher_setiv(hd, iv, sizeof(iv)); gcry_cipher_setiv(hd, iv, sizeof(iv));
err = gcry_cipher_decrypt(hd, &outPlain[0], outPlain.size(), cipher, cipherSize); err = gcry_cipher_decrypt(hd, &outPlain[0], outPlain.size(), cipher, cipherSize);
@@ -358,15 +340,13 @@ CryptHelper::AES128Decrypt(const unsigned char *keyData, unsigned keySize, const
retVal = true; retVal = true;
else else
outPlain.clear(); outPlain.clear();
} } else
else
outPlain.clear(); outPlain.clear();
gcry_cipher_close(hd); gcry_cipher_close(hd);
#endif #endif
// Remove trailing zeroes (padding). // Remove trailing zeroes (padding).
if (!outPlain.empty()) if (!outPlain.empty()) {
{
size_t pos = outPlain.find_first_of('\0'); size_t pos = outPlain.find_first_of('\0');
if (pos != string::npos) if (pos != string::npos)
outPlain = outPlain.substr(0, pos); outPlain = outPlain.substr(0, pos);
+6 -12
View File
@@ -54,11 +54,9 @@ loghelper_init(const string &logDir, int logLevel)
void void
internal_log_err(const string &msg) internal_log_err(const string &msg)
{ {
if (!g_logFile.empty()) if (!g_logFile.empty()) {
{
ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app); ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app);
if (!o.fail()) if (!o.fail()) {
{
o << second_clock::local_time() << " ERR: " << msg; o << second_clock::local_time() << " ERR: " << msg;
o.flush(); o.flush();
} }
@@ -68,10 +66,8 @@ internal_log_err(const string &msg)
void void
internal_log_msg(const std::string &msg) internal_log_msg(const std::string &msg)
{ {
if (g_logLevel) if (g_logLevel) {
{ if (!g_logFile.empty()) {
if (!g_logFile.empty())
{
ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app); ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app);
if (!o.fail()) if (!o.fail())
o << second_clock::local_time() << " MSG: " << msg; o << second_clock::local_time() << " MSG: " << msg;
@@ -82,10 +78,8 @@ internal_log_msg(const std::string &msg)
void void
internal_log_level(const std::string &msg, int logLevel) internal_log_level(const std::string &msg, int logLevel)
{ {
if (g_logLevel >= logLevel) if (g_logLevel >= logLevel) {
{ if (!g_logFile.empty()) {
if (!g_logFile.empty())
{
ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app); ofstream o(g_logFile.c_str(), ios_base::out | ios_base::app);
if (!o.fail()) if (!o.fail())
o << second_clock::local_time() << " OUT: " << msg; o << second_clock::local_time() << " OUT: " << msg;
+1 -1
View File
@@ -23,7 +23,7 @@
using namespace std; using namespace std;
PokerTHException::PokerTHException(const char *sourcefile, int sourceline, int errorId, int osErrorCode) PokerTHException::PokerTHException(const char *sourcefile, int sourceline, int errorId, int osErrorCode)
: m_errorId(errorId), m_osErrorCode(osErrorCode) : m_errorId(errorId), m_osErrorCode(osErrorCode)
{ {
ostringstream msgStream; ostringstream msgStream;
msgStream << sourcefile << " (" << sourceline << "): Error " << errorId; msgStream << sourcefile << " (" << sourceline << "): Error " << errorId;
+7 -15
View File
@@ -26,8 +26,7 @@ inline void ADD_MSEC_TO_XTIME(boost::xtime &xt, unsigned msec)
{ {
xt.sec += msec / 1000; xt.sec += msec / 1000;
xt.nsec += (msec % 1000) * 1000000; xt.nsec += (msec % 1000) * 1000000;
if (xt.nsec > NANOSECONDS_PER_SECOND) if (xt.nsec > NANOSECONDS_PER_SECOND) {
{
xt.sec++; xt.sec++;
xt.nsec -= NANOSECONDS_PER_SECOND; xt.nsec -= NANOSECONDS_PER_SECOND;
} }
@@ -39,8 +38,7 @@ class ThreadStarter
{ {
public: public:
ThreadStarter(Thread &thread) : m_thread(thread) {} ThreadStarter(Thread &thread) : m_thread(thread) {}
void operator()() void operator()() {
{
m_thread.MainWrapper(); m_thread.MainWrapper();
} }
@@ -62,8 +60,7 @@ Thread::Run()
boost::mutex::scoped_lock threadLock(m_threadObjMutex); boost::mutex::scoped_lock threadLock(m_threadObjMutex);
// Create the boost thread object. // Create the boost thread object.
if (!m_threadObj.get()) if (!m_threadObj.get()) {
{
// Initialise data structures within the context of the thread // Initialise data structures within the context of the thread
// who runs/terminates this thread. // who runs/terminates this thread.
m_userReqTerminateLock.reset(new boost::timed_mutex::scoped_try_lock(m_shouldTerminateMutex)); m_userReqTerminateLock.reset(new boost::timed_mutex::scoped_try_lock(m_shouldTerminateMutex));
@@ -89,14 +86,11 @@ Thread::Join(unsigned msecTimeout)
return true; return true;
bool tmpIsTerminated; bool tmpIsTerminated;
if (msecTimeout == THREAD_WAIT_INFINITE) if (msecTimeout == THREAD_WAIT_INFINITE) {
{
// Wait infinitely. // Wait infinitely.
boost::timed_mutex::scoped_lock lock(m_isTerminatedMutex); boost::timed_mutex::scoped_lock lock(m_isTerminatedMutex);
tmpIsTerminated = true; tmpIsTerminated = true;
} } else {
else
{
// Wait for the termination of the application code. // Wait for the termination of the application code.
#if (BOOST_VERSION) >= 103500 #if (BOOST_VERSION) >= 103500
boost::defer_lock_t defer; boost::defer_lock_t defer;
@@ -113,12 +107,10 @@ Thread::Join(unsigned msecTimeout)
#endif #endif
} }
if (tmpIsTerminated) if (tmpIsTerminated) {
{
boost::mutex::scoped_lock lock(m_threadObjMutex); boost::mutex::scoped_lock lock(m_threadObjMutex);
// Wait for "real" termination of the thread. // Wait for "real" termination of the thread.
if (m_threadObj.get()) if (m_threadObj.get()) {
{
m_threadObj->join(); m_threadObj->join();
m_threadObj.reset(); m_threadObj.reset();
} }
+3 -5
View File
@@ -25,7 +25,7 @@
#endif #endif
#if defined(__FreeBSD__) || defined(__NetBSD__) #if defined(__FreeBSD__) || defined(__NetBSD__)
#define HAVE_ICONV_CONST #define HAVE_ICONV_CONST
#endif #endif
#include <string> #include <string>
@@ -57,8 +57,7 @@ ConvHelper::NativeToUtf8(const std::string &inStr)
if (conversion == (iconv_t)(-1)) if (conversion == (iconv_t)(-1))
LOG_ERROR("iconv_open() failed: " << strerror(errno)); LOG_ERROR("iconv_open() failed: " << strerror(errno));
else else {
{
size_t retval = iconv(conversion, &inbuf, &insize, &outbuf, &outsize); size_t retval = iconv(conversion, &inbuf, &insize, &outbuf, &outsize);
if (retval == (size_t)-1) if (retval == (size_t)-1)
@@ -91,8 +90,7 @@ ConvHelper::Utf8ToNative(const std::string &inStr)
if (conversion == (iconv_t)(-1)) if (conversion == (iconv_t)(-1))
LOG_ERROR("iconv_open() failed: " << strerror(errno)); LOG_ERROR("iconv_open() failed: " << strerror(errno));
else else {
{
size_t retval = iconv(conversion, &inbuf, &insize, &outbuf, &outsize); size_t retval = iconv(conversion, &inbuf, &insize, &outbuf, &outsize);
if (retval == (size_t)-1) if (retval == (size_t)-1)
+28 -28
View File
@@ -25,28 +25,28 @@
#define HAVE_SSIZE_T #define HAVE_SSIZE_T
#include <sys/types.h> #include <sys/types.h>
#ifdef _WIN64 // This is only for Windows. #ifdef _WIN64 // This is only for Windows.
#ifndef _SSIZE_T_ #ifndef _SSIZE_T_
typedef long long ssize_t; typedef long long ssize_t;
#define _SSIZE_T_ #define _SSIZE_T_
#endif #endif
#ifndef _PID_T_ #ifndef _PID_T_
typedef __int64 pid_t; typedef __int64 pid_t;
#define _PID_T_ #define _PID_T_
#endif #endif
#elif _WIN32 #elif _WIN32
#ifndef _SSIZE_T_ #ifndef _SSIZE_T_
typedef int ssize_t; typedef int ssize_t;
#define _SSIZE_T_ #define _SSIZE_T_
#endif #endif
#ifndef _PID_T_ #ifndef _PID_T_
typedef int pid_t; typedef int pid_t;
#define _PID_T_ #define _PID_T_
#endif #endif
#endif #endif
#endif #endif
#ifdef X509_NAME #ifdef X509_NAME
#undef X509_NAME // Again for Windows - conflict with WinCrypt.h. #undef X509_NAME // Again for Windows - conflict with WinCrypt.h.
#endif #endif
// For BSD-Systems, we assume that OpenSSL is part of the operating system. // For BSD-Systems, we assume that OpenSSL is part of the operating system.
@@ -56,21 +56,21 @@
// http://www.openssl.org/support/faq.html#LEGAL2 // http://www.openssl.org/support/faq.html#LEGAL2
// //
#if defined(_WIN64) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) #if defined(_WIN64) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
#define HAVE_OPENSSL #define HAVE_OPENSSL
#endif #endif
#ifdef HAVE_OPENSSL #ifdef HAVE_OPENSSL
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <openssl/md5.h> #include <openssl/md5.h>
#include <openssl/sha.h> #include <openssl/sha.h>
#include <openssl/hmac.h> #include <openssl/hmac.h>
#include <openssl/rand.h> #include <openssl/rand.h>
#include <openssl/evp.h> #include <openssl/evp.h>
#else #else
// For all other systems, we use GnuTLS. // For all other systems, we use GnuTLS.
#include <gnutls/openssl.h> #include <gnutls/openssl.h>
#include <gcrypt.h> #include <gcrypt.h>
#define PKTH_USE_GNUTLS #define PKTH_USE_GNUTLS
#endif #endif
#endif #endif
+6 -2
View File
@@ -31,8 +31,12 @@ public:
PokerTHException(const char *sourcefile, int sourceline, int errorId, int osErrorCode); PokerTHException(const char *sourcefile, int sourceline, int errorId, int osErrorCode);
virtual ~PokerTHException() throw(); virtual ~PokerTHException() throw();
int GetErrorId() const {return m_errorId;} int GetErrorId() const {
int GetOsErrorCode() const {return m_osErrorCode;} return m_errorId;
}
int GetOsErrorCode() const {
return m_osErrorCode;
}
virtual const char *what() const throw(); virtual const char *what() const throw();
+1 -1
View File
@@ -82,7 +82,7 @@ private:
mutable boost::shared_ptr<boost::barrier> m_threadStartBarrier; mutable boost::shared_ptr<boost::barrier> m_threadStartBarrier;
friend class ThreadStarter; friend class ThreadStarter;
}; };
#endif #endif
+4 -8
View File
@@ -33,22 +33,18 @@ Convert(const std::string &inStr, int fromCP, int toCP)
// convert str from current Windows source to target charset // convert str from current Windows source to target charset
string retStr(inStr); string retStr(inStr);
if (!inStr.empty()) if (!inStr.empty()) {
{
int len = (int)inStr.length() + 1; int len = (int)inStr.length() + 1;
int reqLen = ::MultiByteToWideChar(fromCP, 0, inStr.c_str(), len, NULL, 0); int reqLen = ::MultiByteToWideChar(fromCP, 0, inStr.c_str(), len, NULL, 0);
if (reqLen) if (reqLen) {
{
wchar_t *wstr = new wchar_t[reqLen]; wchar_t *wstr = new wchar_t[reqLen];
wstr[0] = L'\0'; wstr[0] = L'\0';
if (::MultiByteToWideChar(fromCP, 0, inStr.c_str(), len, wstr, reqLen) == (int)reqLen) if (::MultiByteToWideChar(fromCP, 0, inStr.c_str(), len, wstr, reqLen) == (int)reqLen) {
{
len = reqLen; len = reqLen;
reqLen = ::WideCharToMultiByte(toCP, 0, wstr, len, NULL, 0, NULL, NULL); reqLen = ::WideCharToMultiByte(toCP, 0, wstr, len, NULL, 0, NULL, NULL);
if (reqLen) if (reqLen) {
{
char *str = new char[reqLen]; char *str = new char[reqLen];
if (::WideCharToMultiByte(toCP, 0, wstr, len, str, reqLen, NULL, NULL) == (int)reqLen) if (::WideCharToMultiByte(toCP, 0, wstr, len, str, reqLen, NULL, NULL) == (int)reqLen)
retStr = str; retStr = str;
+2 -2
View File
@@ -24,7 +24,7 @@ using namespace std;
ServerDBGeneric::ServerDBGeneric(ServerDBCallback &cb, boost::shared_ptr<boost::asio::io_service> ioService) ServerDBGeneric::ServerDBGeneric(ServerDBCallback &cb, boost::shared_ptr<boost::asio::io_service> ioService)
: m_ioService(ioService), m_callback(cb) : m_ioService(ioService), m_callback(cb)
{ {
} }
@@ -87,7 +87,7 @@ ServerDBGeneric::EndGame(DB_id /*gameId*/)
} }
void void
ServerDBGeneric::AsyncReportAvatar(unsigned requestId, unsigned replyId, DB_id /*reportedPlayerId*/, const std::string &/*avatarHash*/, const std::string &/*avatarType*/, DB_id */*byPlayerId*/) ServerDBGeneric::AsyncReportAvatar(unsigned requestId, unsigned replyId, DB_id /*reportedPlayerId*/, const std::string &/*avatarHash*/, const std::string &/*avatarType*/, DB_id */*byPlayerId*/)
{ {
m_ioService->post(boost::bind(&ServerDBCallback::ReportAvatarFailed, &m_callback, requestId, replyId)); m_ioService->post(boost::bind(&ServerDBCallback::ReportAvatarFailed, &m_callback, requestId, replyId));
} }
+1 -2
View File
@@ -27,8 +27,7 @@
typedef unsigned DB_id; typedef unsigned DB_id;
#define DB_ID_INVALID 0 #define DB_ID_INVALID 0
struct DBPlayerData struct DBPlayerData {
{
DBPlayerData() : id(DB_ID_INVALID) {} DBPlayerData() : id(DB_ID_INVALID) {}
DB_id id; DB_id id;
std::string secret; std::string secret;
+1 -1
View File
@@ -27,7 +27,7 @@
class ServerDBNoAction : public ServerDBInterface class ServerDBNoAction : public ServerDBInterface
{ {
public: public:
ServerDBNoAction(); ServerDBNoAction();
virtual ~ServerDBNoAction(); virtual ~ServerDBNoAction();
virtual void Init(const std::string &/*host*/, const std::string &/*user*/, const std::string &/*pwd*/, virtual void Init(const std::string &/*host*/, const std::string &/*user*/, const std::string &/*pwd*/,
+2 -1
View File
@@ -23,7 +23,8 @@
#include <game_defs.h> #include <game_defs.h>
#include <engine_defs.h> #include <engine_defs.h>
class BeRoInterface{ class BeRoInterface
{
public: public:
virtual ~BeRoInterface(); virtual ~BeRoInterface();
+4 -3
View File
@@ -24,7 +24,8 @@
class HandInterface; class HandInterface;
class BoardInterface { class BoardInterface
{
public: public:
@@ -40,8 +41,8 @@ public:
virtual int getSets() const=0; virtual int getSets() const=0;
virtual void setSets(int theValue) =0; virtual void setSets(int theValue) =0;
virtual void setAllInCondition(bool theValue) =0; virtual void setAllInCondition(bool theValue) =0;
virtual void setLastActionPlayer(unsigned theValue) =0; virtual void setLastActionPlayer(unsigned theValue) =0;
// //
virtual void collectSets() =0; virtual void collectSets() =0;
virtual void collectPot() =0; virtual void collectPot() =0;
+2 -1
View File
@@ -26,7 +26,8 @@
#include "berointerface.h" #include "berointerface.h"
#include "log.h" #include "log.h"
class EngineFactory{ class EngineFactory
{
public: public:
virtual ~EngineFactory(); virtual ~EngineFactory();
+9 -8
View File
@@ -25,7 +25,8 @@
#include "playerinterface.h" #include "playerinterface.h"
#include "berointerface.h" #include "berointerface.h"
class HandInterface{ class HandInterface
{
public: public:
virtual ~HandInterface(); virtual ~HandInterface();
@@ -84,13 +85,13 @@ protected:
virtual PlayerListIterator getActivePlayerIt(unsigned) const =0; virtual PlayerListIterator getActivePlayerIt(unsigned) const =0;
virtual PlayerListIterator getRunningPlayerIt(unsigned) const =0; virtual PlayerListIterator getRunningPlayerIt(unsigned) const =0;
friend class Game; friend class Game;
friend class LocalBeRo; friend class LocalBeRo;
friend class LocalBeRoPreflop; friend class LocalBeRoPreflop;
friend class LocalBeRoFlop; friend class LocalBeRoFlop;
friend class LocalBeRoTurn; friend class LocalBeRoTurn;
friend class LocalBeRoRiver; friend class LocalBeRoRiver;
friend class LocalBeRoPostRiver; friend class LocalBeRoPostRiver;
}; };
#endif #endif
+14 -17
View File
@@ -22,14 +22,12 @@
using namespace std; using namespace std;
struct RoundData struct RoundData {
{
int hand; int hand;
double data[4]; double data[4];
}; };
static const RoundData PreflopValues[] = static const RoundData PreflopValues[] = {
{
{ 0, { 0.392398, 0.276545, 0.212940, 0.178564 } }, { 0, { 0.392398, 0.276545, 0.212940, 0.178564 } },
{ 10, { 0.341141, 0.213735, 0.153802, 0.121123 } }, { 10, { 0.341141, 0.213735, 0.153802, 0.121123 } },
{ 11, { 0.374930, 0.252093, 0.194671, 0.161691 } }, { 11, { 0.374930, 0.252093, 0.194671, 0.161691 } },
@@ -201,8 +199,7 @@ static const RoundData PreflopValues[] =
{ 12120, { 0.855608, 0.736617, 0.642366, 0.562044 } } { 12120, { 0.855608, 0.736617, 0.642366, 0.562044 } }
}; };
static const RoundData FlopValues[] = static const RoundData FlopValues[] = {
{
{ 106, { 0.160312, 0.078750, 0.048325, 0.033350 } }, { 106, { 0.160312, 0.078750, 0.048325, 0.033350 } },
{ 206, { 0.185012, 0.099666, 0.071425, 0.053450 } }, { 206, { 0.185012, 0.099666, 0.071425, 0.053450 } },
{ 306, { 0.199662, 0.115567, 0.081625, 0.067500 } }, { 306, { 0.199662, 0.115567, 0.081625, 0.067500 } },
@@ -839,14 +836,12 @@ static const RoundData FlopValues[] =
{ 71212, { 0.751687, 0.628100, 0.560100, 0.516900 } } { 71212, { 0.751687, 0.628100, 0.560100, 0.516900 } }
}; };
struct calcHandsData struct calcHandsData {
{
int hand; int hand;
int data[10][2]; int data[10][2];
}; };
static const calcHandsData handChancePreflop[] = static const calcHandsData handChancePreflop[] = {
{
{ 0, { { 0,0}, { 36,1}, { 40,1}, { 12,1}, { 1,1}, { 2,1}, { 9,1}, { 1,1}, { 0,1}, { 0,1} } }, { 0, { { 0,0}, { 36,1}, { 40,1}, { 12,1}, { 1,1}, { 2,1}, { 9,1}, { 1,1}, { 0,1}, { 0,1} } },
{ 10, { { 19,1}, { 45,1}, { 23,1}, { 4,1}, { 5,1}, { 2,1}, { 2,1}, { 0,1}, { 0,1}, { 0,1} } }, { 10, { { 19,1}, { 45,1}, { 23,1}, { 4,1}, { 5,1}, { 2,1}, { 2,1}, { 0,1}, { 0,1}, { 0,1} } },
{ 11, { { 18,1}, { 42,1}, { 22,1}, { 4,1}, { 5,1}, { 6,1}, { 2,1}, { 0,1}, { 0,1}, { 0,1} } }, { 11, { { 18,1}, { 42,1}, { 22,1}, { 4,1}, { 5,1}, { 6,1}, { 2,1}, { 0,1}, { 0,1}, { 0,1} } },
@@ -1030,15 +1025,16 @@ ArrayData::~ArrayData()
{ {
} }
void ArrayData::getHandChancePreflop(int handCode, int** values) { void ArrayData::getHandChancePreflop(int handCode, int** values)
{
int check = -1; int check = -1;
for (unsigned val = 0; val < NUM_HAND_CHANCE_PREFLOP; val++) { for (unsigned val = 0; val < NUM_HAND_CHANCE_PREFLOP; val++) {
if(handCode == handChancePreflop[val].hand) { if(handCode == handChancePreflop[val].hand) {
check = 1; check = 1;
for(int i=0;i<10;i++) { for(int i=0; i<10; i++) {
for(int j=0;j<2;j++) { for(int j=0; j<2; j++) {
values[i][j] = handChancePreflop[val].data[i][j]; values[i][j] = handChancePreflop[val].data[i][j];
} }
} }
@@ -1049,7 +1045,8 @@ void ArrayData::getHandChancePreflop(int handCode, int** values) {
} }
vector< vector<int> > ArrayData::getHandChancePreflop(int handCode) { vector< vector<int> > ArrayData::getHandChancePreflop(int handCode)
{
int check = -1; int check = -1;
@@ -1060,7 +1057,7 @@ vector< vector<int> > ArrayData::getHandChancePreflop(int handCode) {
chance[0].resize(10); chance[0].resize(10);
chance[1].resize(10); chance[1].resize(10);
for(i=0;i<10;i++) { for(i=0; i<10; i++) {
chance[0][i] = 0; chance[0][i] = 0;
chance[1][i] = 0; chance[1][i] = 0;
} }
@@ -1068,8 +1065,8 @@ vector< vector<int> > ArrayData::getHandChancePreflop(int handCode) {
for (unsigned val = 0; val < NUM_HAND_CHANCE_PREFLOP; val++) { for (unsigned val = 0; val < NUM_HAND_CHANCE_PREFLOP; val++) {
if(handCode == handChancePreflop[val].hand) { if(handCode == handChancePreflop[val].hand) {
check = 1; check = 1;
for(int i=0;i<10;i++) { for(int i=0; i<10; i++) {
for(int j=0;j<2;j++) { for(int j=0; j<2; j++) {
chance[j][i] = handChancePreflop[val].data[i][j]; chance[j][i] = handChancePreflop[val].data[i][j];
} }
} }
+4 -3
View File
@@ -24,11 +24,12 @@
#include<vector> #include<vector>
class ArrayData{ class ArrayData
{
public: public:
ArrayData(); ArrayData();
~ArrayData(); ~ArrayData();
void getHandChancePreflop(int, int**); void getHandChancePreflop(int, int**);
std::vector< std::vector<int> > getHandChancePreflop(int); std::vector< std::vector<int> > getHandChancePreflop(int);
+245 -190
View File
@@ -30,143 +30,192 @@ CardsValue::~CardsValue()
{ {
} }
int CardsValue::holeCardsClass(int one, int two) const { int CardsValue::holeCardsClass(int one, int two) const
{
if((one-1)%13<(two-1)%13) { if((one-1)%13<(two-1)%13) {
int temp = one; int temp = one;
one = two; one = two;
two = temp; two = temp;
} }
if((one-1)%13 == (two-1)%13) { if((one-1)%13 == (two-1)%13) {
if((one-1)%13+2 > 10) return 10; if((one-1)%13+2 > 10) return 10;
else { else {
switch((one-1)%13+2) { switch((one-1)%13+2) {
case 10: return 9; case 10:
case 9: return 8; return 9;
case 8: return 7; case 9:
case 7: return 6; return 8;
default: return 5; case 8:
} return 7;
} case 7:
} return 6;
switch((one-1)%13+2) { default:
//Ass return 5;
case 14: { }
if((one-1)/13 == (two-1)/13) { }
switch((one-1)%13-(two-1)%13) { }
case 1: return 10; switch((one-1)%13+2) {
case 2: return 9; //Ass
case 3: return 9; case 14: {
case 4: return 8; if((one-1)/13 == (two-1)/13) {
default: return 7; switch((one-1)%13-(two-1)%13) {
} case 1:
} return 10;
else { case 2:
switch((one-1)%13-(two-1)%13) { return 9;
case 1: return 9; case 3:
case 2: return 8; return 9;
case 3: return 7; case 4:
case 4: return 7; return 8;
default: return 4; default:
} return 7;
} }
} break; } else {
//K�ig switch((one-1)%13-(two-1)%13) {
case 13: { case 1:
if((one-1)/13 == (two-1)/13) { return 9;
switch((one-1)%13-(two-1)%13) { case 2:
case 1: return 9; return 8;
case 2: return 8; case 3:
case 3: return 8; return 7;
case 4: return 6; case 4:
default: return 5; return 7;
} default:
} return 4;
else { }
switch((one-1)%13-(two-1)%13) { }
case 1: return 7; }
case 2: return 6; break;
case 3: return 6; //K�ig
default: return 4; case 13: {
} if((one-1)/13 == (two-1)/13) {
} switch((one-1)%13-(two-1)%13) {
} break; case 1:
//Dame return 9;
case 12: { case 2:
if((one-1)/13 == (two-1)/13) { return 8;
switch((one-1)%13-(two-1)%13) { case 3:
case 1: return 8; return 8;
case 2: return 7; case 4:
case 3: return 6; return 6;
case 4: return 5; default:
default: return 4; return 5;
} }
} } else {
else { switch((one-1)%13-(two-1)%13) {
switch((one-1)%13-(two-1)%13) { case 1:
case 1: return 6; return 7;
case 2: return 6; case 2:
case 3: return 4; return 6;
default: return 3; case 3:
} return 6;
} default:
} break; return 4;
//Bube }
case 11: { }
if((one-1)/13 == (two-1)/13) { }
switch((one-1)%13-(two-1)%13) { break;
case 1: return 7; //Dame
case 2: return 6; case 12: {
case 3: return 5; if((one-1)/13 == (two-1)/13) {
case 4: return 4; switch((one-1)%13-(two-1)%13) {
default: return 3; case 1:
} return 8;
} case 2:
else { return 7;
switch((one-1)%13-(two-1)%13) { case 3:
case 1: return 6; return 6;
case 2: return 5; case 4:
case 3: return 4; return 5;
default: return 2; default:
} return 4;
} }
} break; } else {
//10 switch((one-1)%13-(two-1)%13) {
case 10: { case 1:
if((one-1)/13 == (two-1)/13) { return 6;
switch((one-1)%13-(two-1)%13) { case 2:
case 1: return 6; return 6;
case 2: return 5; case 3:
default: return 2; return 4;
} default:
} return 3;
else { }
switch((one-1)%13-(two-1)%13) { }
case 1: return 5; }
case 2: return 4; break;
default: return 1; //Bube
} case 11: {
} if((one-1)/13 == (two-1)/13) {
} break; switch((one-1)%13-(two-1)%13) {
//Rest case 1:
default: { return 7;
if((one-1)%13 - (two-1)%13 <= 2) { case 2:
if((one-1)/13 == (two-1)/13) return 5; return 6;
else return 3; case 3:
} return 5;
else { case 4:
if((one-1)%13 - (two-1)%13 == 3) return 2; return 4;
else return 1; default:
} return 3;
} }
} } else {
switch((one-1)%13-(two-1)%13) {
case 1:
return 6;
case 2:
return 5;
case 3:
return 4;
default:
return 2;
}
}
}
break;
//10
case 10: {
if((one-1)/13 == (two-1)/13) {
switch((one-1)%13-(two-1)%13) {
case 1:
return 6;
case 2:
return 5;
default:
return 2;
}
} else {
switch((one-1)%13-(two-1)%13) {
case 1:
return 5;
case 2:
return 4;
default:
return 1;
}
}
}
break;
//Rest
default: {
if((one-1)%13 - (two-1)%13 <= 2) {
if((one-1)/13 == (two-1)/13) return 5;
else return 3;
} else {
if((one-1)%13 - (two-1)%13 == 3) return 2;
else return 1;
}
}
}
} }
int CardsValue::holeCardsToIntCode(int* cards) const { int CardsValue::holeCardsToIntCode(int* cards) const
{
// Code der HoleCards ermitteln // Code der HoleCards ermitteln
if(cards[0]%13 == cards[1]%13) { if(cards[0]%13 == cards[1]%13) {
@@ -189,7 +238,8 @@ int CardsValue::holeCardsToIntCode(int* cards) const {
} }
int* CardsValue::intCodeToHoleCards(int code) const { int* CardsValue::intCodeToHoleCards(int code) const
{
// one possibility !!! // one possibility !!!
@@ -198,8 +248,9 @@ int* CardsValue::intCodeToHoleCards(int code) const {
cards[0] = code/1000; cards[0] = code/1000;
cards[1] = (code-cards[0]*1000)/10; cards[1] = (code-cards[0]*1000)/10;
if(cards[0]==cards[1]) { cards[1] +=13; } if(cards[0]==cards[1]) {
else { cards[1] +=13;
} else {
if(code%10 == 0) cards[1] +=13; if(code%10 == 0) cards[1] +=13;
} }
@@ -207,9 +258,10 @@ int* CardsValue::intCodeToHoleCards(int code) const {
} }
int CardsValue::cardsValue(int* cards, int* position) const { int CardsValue::cardsValue(int* cards, int* position) const
{
int array[7][3]; int array[7][3];
int j1, j2, j3, j4, j5, k1, k2, ktemp[3]; int j1, j2, j3, j4, j5, k1, k2, ktemp[3];
// Kartenwerte umwandeln (z.B. [ 11 (Karo K�ig) -> 0 11 ] oder [ 31 (Pik 7) -> 2 5 ] ) // Kartenwerte umwandeln (z.B. [ 11 (Karo K�ig) -> 0 11 ] oder [ 31 (Pik 7) -> 2 5 ] )
@@ -368,8 +420,7 @@ int array[7][3];
} }
} }
return 700000000+array[j1][1]*1000000+array[j1+4][1]*10000; return 700000000+array[j1][1]*1000000+array[j1+4][1]*10000;
} } else {
else {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
for(j2=0; j2<4; j2++) { for(j2=0; j2<4; j2++) {
@@ -414,8 +465,13 @@ int array[7][3];
position[4] = array[j5][2]; position[4] = array[j5][2];
} }
// Paar und Drilling des Full House ermitteln ermitteln // Paar und Drilling des Full House ermitteln ermitteln
if(array[j3][1]==array[j1][1]) { drei = array[j1][1]; zwei = array[j4][1]; } if(array[j3][1]==array[j1][1]) {
else { drei = array[j4][1]; zwei = array[j1][1]; } drei = array[j1][1];
zwei = array[j4][1];
} else {
drei = array[j4][1];
zwei = array[j1][1];
}
return 600000000+drei*1000000+zwei*10000; return 600000000+drei*1000000+zwei*10000;
} }
} }
@@ -454,26 +510,24 @@ int array[7][3];
if(j1==0) { if(j1==0) {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
for(j2=0; j2<5;j2++) { for(j2=0; j2<5; j2++) {
position[j2] = array[j2][2]; position[j2] = array[j2][2];
} }
} }
return 300000000+array[j1][1]*1000000+array[j1+3][1]*10000+array[j1+4][1]*100; return 300000000+array[j1][1]*1000000+array[j1+3][1]*10000+array[j1+4][1]*100;
} } else {
else {
if(j1==1) { if(j1==1) {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
for(j2=0; j2<5;j2++) { for(j2=0; j2<5; j2++) {
position[j2] = array[j2][2]; position[j2] = array[j2][2];
} }
} }
return 300000000+array[j1][1]*1000000+array[j1-1][1]*10000+array[j1+3][1]*100; return 300000000+array[j1][1]*1000000+array[j1-1][1]*10000+array[j1+3][1]*100;
} } else {
else {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
for(j2=0; j2<3;j2++) { for(j2=0; j2<3; j2++) {
position[j2] = array[j1+j2][2]; position[j2] = array[j1+j2][2];
} }
position[3] = array[0][2]; position[3] = array[0][2];
@@ -501,8 +555,7 @@ int array[7][3];
position[4] = array[j2+2][2]; position[4] = array[j2+2][2];
} }
return 200000000+array[j1][1]*1000000+array[j2][1]*10000+array[j2+2][1]*100; return 200000000+array[j1][1]*1000000+array[j2][1]*10000+array[j2+2][1]*100;
} } else {
else {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
position[0] = array[j1][2]; position[0] = array[j1][2];
@@ -513,8 +566,7 @@ int array[7][3];
} }
return 200000000+array[j1][1]*1000000+array[j2][1]*10000+array[j1+2][1]*100; return 200000000+array[j1][1]*1000000+array[j2][1]*10000+array[j1+2][1]*100;
} }
} } else {
else {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
position[0] = array[j1][2]; position[0] = array[j1][2];
@@ -559,8 +611,7 @@ int array[7][3];
} }
} }
return 100000000+array[j1][1]*1000000+array[j1-2][1]*10000+array[j1-1][1]*100+array[j1+2][1]; return 100000000+array[j1][1]*1000000+array[j1-2][1]*10000+array[j1-1][1]*100+array[j1+2][1];
} } else {
else {
if(position) { if(position) {
// Position-Array fuellen // Position-Array fuellen
for(j2=0; j2<2; j2++) { for(j2=0; j2<2; j2++) {
@@ -595,7 +646,7 @@ vector< vector<int> > CardsValue::calcCardsChance(GameState beRoID, int* playerC
chance[0].resize(10); chance[0].resize(10);
chance[1].resize(10); chance[1].resize(10);
for(i=0;i<10;i++) { for(i=0; i<10; i++) {
chance[0][i] = 0; chance[0][i] = 0;
chance[1][i] = 0; chance[1][i] = 0;
} }
@@ -605,22 +656,23 @@ vector< vector<int> > CardsValue::calcCardsChance(GameState beRoID, int* playerC
cards[0] = playerCards[0]; cards[0] = playerCards[0];
cards[1] = playerCards[1]; cards[1] = playerCards[1];
for(i=0;i<5;i++) cards[i+2] = boardCards[i]; for(i=0; i<5; i++) cards[i+2] = boardCards[i];
switch(beRoID) { switch(beRoID) {
case GAME_STATE_PREFLOP: { case GAME_STATE_PREFLOP: {
ArrayData* myArrayData = new ArrayData; ArrayData* myArrayData = new ArrayData;
chance = myArrayData->getHandChancePreflop(holeCardsToIntCode(playerCards)); chance = myArrayData->getHandChancePreflop(holeCardsToIntCode(playerCards));
delete myArrayData; delete myArrayData;
} break; }
case GAME_STATE_FLOP: { break;
case GAME_STATE_FLOP: {
for(i=0;i<51;i++) { for(i=0; i<51; i++) {
if(i!=cards[0] && i!=cards[1] && i!=cards[2] && i!=cards[3] && i!=cards[4]) { if(i!=cards[0] && i!=cards[1] && i!=cards[2] && i!=cards[3] && i!=cards[4]) {
for(j=i+1;j<52;j++) { for(j=i+1; j<52; j++) {
if(j!=cards[0] && j!=cards[1] && j!=cards[2] && j!=cards[3] && j!=cards[4]) { if(j!=cards[0] && j!=cards[1] && j!=cards[2] && j!=cards[3] && j!=cards[4]) {
cards[5] = i; cards[5] = i;
cards[6] = j; cards[6] = j;
@@ -628,35 +680,38 @@ vector< vector<int> > CardsValue::calcCardsChance(GameState beRoID, int* playerC
sum++; sum++;
} }
} }
}
} }
for(i=0;i<10;i++) {
if(chance[0][i] > 0) chance[1][i] = 1;
chance[0][i] = (int)(((double)chance[0][i]/(double)sum)*100.0+0.5);
}
} break;
case GAME_STATE_TURN: {
for(i=0;i<52;i++) {
if(i!=cards[0] && i!=cards[1] && i!=cards[2] && i!=cards[3] && i!=cards[4] && i!=cards[5]) {
cards[6] = i;
(chance[0][cardsValue(cards,0)/100000000])++;
sum++;
}
}
for(i=0;i<10;i++) {
if(chance[0][i] > 0) chance[1][i] = 1;
chance[0][i] = (int)(((double)chance[0][i]/(double)sum)*100.0+0.5);
}
} break;
case GAME_STATE_RIVER: {
chance[0][cardsValue(cards,0)/100000000] = 100;
chance[1][cardsValue(cards,0)/100000000] = 1;
} break;
default: {
} }
for(i=0; i<10; i++) {
if(chance[0][i] > 0) chance[1][i] = 1;
chance[0][i] = (int)(((double)chance[0][i]/(double)sum)*100.0+0.5);
}
}
break;
case GAME_STATE_TURN: {
for(i=0; i<52; i++) {
if(i!=cards[0] && i!=cards[1] && i!=cards[2] && i!=cards[3] && i!=cards[4] && i!=cards[5]) {
cards[6] = i;
(chance[0][cardsValue(cards,0)/100000000])++;
sum++;
}
}
for(i=0; i<10; i++) {
if(chance[0][i] > 0) chance[1][i] = 1;
chance[0][i] = (int)(((double)chance[0][i]/(double)sum)*100.0+0.5);
}
}
break;
case GAME_STATE_RIVER: {
chance[0][cardsValue(cards,0)/100000000] = 100;
chance[1][cardsValue(cards,0)/100000000] = 1;
}
break;
default: {
}
} }
return chance; return chance;
+10 -9
View File
@@ -28,20 +28,21 @@
class CardsValue{ class CardsValue
{
public: public:
CardsValue(); CardsValue();
~CardsValue(); ~CardsValue();
int holeCardsClass(int, int) const; int holeCardsClass(int, int) const;
int cardsValue(int*, int*) const; int cardsValue(int*, int*) const;
int holeCardsToIntCode(int*) const; int holeCardsToIntCode(int*) const;
int* intCodeToHoleCards(int) const; int* intCodeToHoleCards(int) const;
std::vector< std::vector<int> > calcCardsChance(GameState, int*, int*) const; std::vector< std::vector<int> > calcCardsChance(GameState, int*, int*) const;
//int** showdown(GameState, int**, int); //int** showdown(GameState, int**, int);
}; };
+20 -14
View File
@@ -26,7 +26,7 @@
using namespace std; using namespace std;
LocalBeRo::LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS) LocalBeRo::LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS)
: BeRoInterface(), myHand(hi), myBeRoID(gS), myID(id), dealerPosition(dP), smallBlindPosition(0), dealerPositionId(dP), smallBlindPositionId(0), bigBlindPositionId(0), smallBlind(sB), highestSet(0), minimumRaise(2*sB), fullBetRule(false), firstRun(true), firstRunGui(true), firstRound(true), firstHeadsUpRound(true), currentPlayersTurnId(0), firstRoundLastPlayersTurnId(0), logBoardCardsDone(false) : BeRoInterface(), myHand(hi), myBeRoID(gS), myID(id), dealerPosition(dP), smallBlindPosition(0), dealerPositionId(dP), smallBlindPositionId(0), bigBlindPositionId(0), smallBlind(sB), highestSet(0), minimumRaise(2*sB), fullBetRule(false), firstRun(true), firstRunGui(true), firstRound(true), firstHeadsUpRound(true), currentPlayersTurnId(0), firstRoundLastPlayersTurnId(0), logBoardCardsDone(false)
{ {
currentPlayersTurnIt = myHand->getRunningPlayerList()->begin(); currentPlayersTurnIt = myHand->getRunningPlayerList()->begin();
lastPlayersTurnIt = myHand->getRunningPlayerList()->begin(); lastPlayersTurnIt = myHand->getRunningPlayerList()->begin();
@@ -68,7 +68,8 @@ int LocalBeRo::getHighestCardsValue() const
return 0; return 0;
} }
void LocalBeRo::nextPlayer() { void LocalBeRo::nextPlayer()
{
PlayerListConstIterator currentPlayersTurnConstIt = myHand->getRunningPlayerIt(currentPlayersTurnId); PlayerListConstIterator currentPlayersTurnConstIt = myHand->getRunningPlayerIt(currentPlayersTurnId);
if(currentPlayersTurnConstIt == myHand->getRunningPlayerList()->end()) { if(currentPlayersTurnConstIt == myHand->getRunningPlayerList()->end()) {
@@ -79,14 +80,14 @@ void LocalBeRo::nextPlayer() {
} }
void LocalBeRo::run() { void LocalBeRo::run()
{
if(firstRunGui) { if(firstRunGui) {
firstRunGui = false; firstRunGui = false;
myHand->setLastPlayersTurn(-1); myHand->setLastPlayersTurn(-1);
myHand->getGuiInterface()->dealBeRoCards(myBeRoID); myHand->getGuiInterface()->dealBeRoCards(myBeRoID);
} } else {
else {
if(firstRun) { if(firstRun) {
@@ -138,13 +139,18 @@ void LocalBeRo::run() {
myHand->getBoard()->getMyCards(tempBoardCardsArray); myHand->getBoard()->getMyCards(tempBoardCardsArray);
switch(myBeRoID) { switch(myBeRoID) {
case GAME_STATE_FLOP: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2]); case GAME_STATE_FLOP:
myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2]);
break; break;
case GAME_STATE_TURN: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3]); case GAME_STATE_TURN:
myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3]);
break; break;
case GAME_STATE_RIVER: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3], tempBoardCardsArray[4]); case GAME_STATE_RIVER:
myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3], tempBoardCardsArray[4]);
break; break;
default: { LOG_ERROR(__FILE__ << " (" << __LINE__ << "): ERROR - wrong myBeRoID"); } default: {
LOG_ERROR(__FILE__ << " (" << __LINE__ << "): ERROR - wrong myBeRoID");
}
} }
logBoardCardsDone = true; logBoardCardsDone = true;
@@ -183,11 +189,12 @@ void LocalBeRo::run() {
myHand->getGuiInterface()->refreshSet(); myHand->getGuiInterface()->refreshSet();
myHand->getGuiInterface()->refreshCash(); myHand->getGuiInterface()->refreshCash();
for(int i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { myHand->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE); } for(int i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
myHand->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE);
}
myHand->switchRounds(); myHand->switchRounds();
} } else {
else {
// aktuelle bero ist wirklich dran // aktuelle bero ist wirklich dran
// Anzahl der effektiv gespielten Runden (des human player) erhöhen // Anzahl der effektiv gespielten Runden (des human player) erhöhen
@@ -229,8 +236,7 @@ void LocalBeRo::run() {
if( currentPlayersTurnId == 0) { if( currentPlayersTurnId == 0) {
// Wir sind dran // Wir sind dran
myHand->getGuiInterface()->meInAction(); myHand->getGuiInterface()->meInAction();
} } else {
else {
//Gegner sind dran //Gegner sind dran
myHand->getGuiInterface()->beRoAnimation2(myBeRoID); myHand->getGuiInterface()->beRoAnimation2(myBeRoID);
+102 -35
View File
@@ -26,23 +26,36 @@
#include "berointerface.h" #include "berointerface.h"
#include "handinterface.h" #include "handinterface.h"
class LocalBeRo : public BeRoInterface{ class LocalBeRo : public BeRoInterface
{
public: public:
LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS); LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS);
~LocalBeRo(); ~LocalBeRo();
GameState getMyBeRoID() const { return myBeRoID; } GameState getMyBeRoID() const {
return myBeRoID;
}
int getHighestCardsValue() const; int getHighestCardsValue() const;
void setHighestCardsValue(int /*theValue*/) { } void setHighestCardsValue(int /*theValue*/) { }
void setMinimumRaise ( int theValue ) { minimumRaise = theValue; } void setMinimumRaise ( int theValue ) {
int getMinimumRaise() const { return minimumRaise; } minimumRaise = theValue;
}
int getMinimumRaise() const {
return minimumRaise;
}
void setFullBetRule ( bool theValue ) { fullBetRule = theValue; } void setFullBetRule ( bool theValue ) {
bool getFullBetRule() const { return fullBetRule; } fullBetRule = theValue;
}
bool getFullBetRule() const {
return fullBetRule;
}
void skipFirstRunGui() { firstRunGui = false; } void skipFirstRunGui() {
firstRunGui = false;
}
void nextPlayer(); void nextPlayer();
void run(); void run();
@@ -52,48 +65,102 @@ public:
protected: protected:
HandInterface* getMyHand() const { return myHand; } HandInterface* getMyHand() const {
return myHand;
}
int getDealerPosition() const {return dealerPosition; } int getDealerPosition() const {
void setDealerPosition(int theValue) { dealerPosition = theValue; } return dealerPosition;
}
void setDealerPosition(int theValue) {
dealerPosition = theValue;
}
void setCurrentPlayersTurnId(unsigned theValue) { currentPlayersTurnId = theValue; } void setCurrentPlayersTurnId(unsigned theValue) {
unsigned getCurrentPlayersTurnId() const { return currentPlayersTurnId;} currentPlayersTurnId = theValue;
}
unsigned getCurrentPlayersTurnId() const {
return currentPlayersTurnId;
}
void setFirstRoundLastPlayersTurnId(unsigned theValue) { firstRoundLastPlayersTurnId = theValue; } void setFirstRoundLastPlayersTurnId(unsigned theValue) {
unsigned getFirstRoundLastPlayersTurnId() const { return firstRoundLastPlayersTurnId;} firstRoundLastPlayersTurnId = theValue;
}
unsigned getFirstRoundLastPlayersTurnId() const {
return firstRoundLastPlayersTurnId;
}
void setCurrentPlayersTurnIt(PlayerListIterator theValue) { currentPlayersTurnIt = theValue; } void setCurrentPlayersTurnIt(PlayerListIterator theValue) {
PlayerListIterator getCurrentPlayersTurnIt() const { return currentPlayersTurnIt; } currentPlayersTurnIt = theValue;
}
PlayerListIterator getCurrentPlayersTurnIt() const {
return currentPlayersTurnIt;
}
void setLastPlayersTurnIt(PlayerListIterator theValue) { lastPlayersTurnIt = theValue; } void setLastPlayersTurnIt(PlayerListIterator theValue) {
PlayerListIterator getLastPlayersTurnIt() const { return lastPlayersTurnIt; } lastPlayersTurnIt = theValue;
}
PlayerListIterator getLastPlayersTurnIt() const {
return lastPlayersTurnIt;
}
void setHighestSet(int theValue) { highestSet = theValue; } void setHighestSet(int theValue) {
int getHighestSet() const { return highestSet;} highestSet = theValue;
}
int getHighestSet() const {
return highestSet;
}
void setFirstRun(bool theValue) { firstRun = theValue;} void setFirstRun(bool theValue) {
bool getFirstRun() const { return firstRun;} firstRun = theValue;
}
bool getFirstRun() const {
return firstRun;
}
void setFirstRound(bool theValue) { firstRound = theValue;} void setFirstRound(bool theValue) {
bool getFirstRound() const { return firstRound;} firstRound = theValue;
}
bool getFirstRound() const {
return firstRound;
}
void setDealerPositionId(unsigned theValue) { dealerPositionId = theValue;} void setDealerPositionId(unsigned theValue) {
unsigned getDealerPositionId() const { return dealerPositionId; } dealerPositionId = theValue;
}
unsigned getDealerPositionId() const {
return dealerPositionId;
}
void setSmallBlindPositionId(unsigned theValue) { smallBlindPositionId = theValue;} void setSmallBlindPositionId(unsigned theValue) {
unsigned getSmallBlindPositionId() const { return smallBlindPositionId; } smallBlindPositionId = theValue;
}
unsigned getSmallBlindPositionId() const {
return smallBlindPositionId;
}
void setBigBlindPositionId(unsigned theValue) { bigBlindPositionId = theValue;} void setBigBlindPositionId(unsigned theValue) {
unsigned getBigBlindPositionId() const { return bigBlindPositionId; } bigBlindPositionId = theValue;
}
unsigned getBigBlindPositionId() const {
return bigBlindPositionId;
}
void setSmallBlindPosition(int theValue) { smallBlindPosition = theValue;} void setSmallBlindPosition(int theValue) {
int getSmallBlindPosition() const { return smallBlindPosition; } smallBlindPosition = theValue;
}
int getSmallBlindPosition() const {
return smallBlindPosition;
}
void setSmallBlind(int theValue) { smallBlind = theValue; } void setSmallBlind(int theValue) {
int getSmallBlind() const { return smallBlind; } smallBlind = theValue;
}
int getSmallBlind() const {
return smallBlind;
}
@@ -115,7 +182,7 @@ private:
int smallBlind; int smallBlind;
int highestSet; int highestSet;
int minimumRaise; int minimumRaise;
bool fullBetRule; bool fullBetRule;
bool firstRun; bool firstRun;
bool firstRunGui; // HACK bool firstRunGui; // HACK
+2 -1
View File
@@ -25,7 +25,8 @@
class HandInterface; class HandInterface;
class LocalBeRoFlop : public LocalBeRo{ class LocalBeRoFlop : public LocalBeRo
{
public: public:
LocalBeRoFlop(HandInterface*, int, unsigned, int); LocalBeRoFlop(HandInterface*, int, unsigned, int);
@@ -33,10 +33,12 @@ LocalBeRoPostRiver::~LocalBeRoPostRiver()
{ {
} }
void LocalBeRoPostRiver::run() { void LocalBeRoPostRiver::run()
{
} }
void LocalBeRoPostRiver::postRiverRun() { void LocalBeRoPostRiver::postRiverRun()
{
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
PlayerListIterator it; PlayerListIterator it;
+8 -3
View File
@@ -26,13 +26,18 @@
class HandInterface; class HandInterface;
class LocalBeRoPostRiver : public LocalBeRo{ class LocalBeRoPostRiver : public LocalBeRo
{
public: public:
LocalBeRoPostRiver(HandInterface*, int, int, int); LocalBeRoPostRiver(HandInterface*, int, int, int);
~LocalBeRoPostRiver(); ~LocalBeRoPostRiver();
void setHighestCardsValue(int theValue) { highestCardsValue = theValue;} void setHighestCardsValue(int theValue) {
int getHighestCardsValue() const { return highestCardsValue;} highestCardsValue = theValue;
}
int getHighestCardsValue() const {
return highestCardsValue;
}
void run(); void run();
+7 -6
View File
@@ -38,7 +38,8 @@ LocalBeRoPreflop::~LocalBeRoPreflop()
{ {
} }
void LocalBeRoPreflop::run() { void LocalBeRoPreflop::run()
{
if(getFirstRun()) { if(getFirstRun()) {
@@ -151,11 +152,12 @@ void LocalBeRoPreflop::run() {
getMyHand()->getGuiInterface()->refreshSet(); getMyHand()->getGuiInterface()->refreshSet();
getMyHand()->getGuiInterface()->refreshCash(); getMyHand()->getGuiInterface()->refreshCash();
for(int i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { getMyHand()->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE); } for(int i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
getMyHand()->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE);
}
getMyHand()->switchRounds(); getMyHand()->switchRounds();
} } else {
else {
// lastPlayersTurn -> PreflopFirstRound is over // lastPlayersTurn -> PreflopFirstRound is over
if( getCurrentPlayersTurnId() == getFirstRoundLastPlayersTurnId() ) { if( getCurrentPlayersTurnId() == getFirstRoundLastPlayersTurnId() ) {
setFirstRound(false); setFirstRound(false);
@@ -175,8 +177,7 @@ void LocalBeRoPreflop::run() {
if( getCurrentPlayersTurnId() == 0) { if( getCurrentPlayersTurnId() == 0) {
// Wir sind dran // Wir sind dran
getMyHand()->getGuiInterface()->meInAction(); getMyHand()->getGuiInterface()->meInAction();
} } else {
else {
//Gegner sind dran //Gegner sind dran
getMyHand()->getGuiInterface()->beRoAnimation2(getMyBeRoID()); getMyHand()->getGuiInterface()->beRoAnimation2(getMyBeRoID());
} }
+2 -1
View File
@@ -25,7 +25,8 @@
class HandInterface; class HandInterface;
class LocalBeRoPreflop : public LocalBeRo{ class LocalBeRoPreflop : public LocalBeRo
{
public: public:
LocalBeRoPreflop(HandInterface*, int, unsigned, int); LocalBeRoPreflop(HandInterface*, int, unsigned, int);
+2 -1
View File
@@ -26,7 +26,8 @@
class HandInterface; class HandInterface;
class LocalBeRoRiver : public LocalBeRo{ class LocalBeRoRiver : public LocalBeRo
{
public: public:
LocalBeRoRiver(HandInterface*, int, unsigned, int); LocalBeRoRiver(HandInterface*, int, unsigned, int);
~LocalBeRoRiver(); ~LocalBeRoRiver();
+2 -1
View File
@@ -25,7 +25,8 @@
class HandInterface; class HandInterface;
class LocalBeRoTurn : public LocalBeRo{ class LocalBeRoTurn : public LocalBeRo
{
public: public:
LocalBeRoTurn(HandInterface*, int, unsigned, int); LocalBeRoTurn(HandInterface*, int, unsigned, int);
~LocalBeRoTurn(); ~LocalBeRoTurn();
+151 -146
View File
@@ -36,13 +36,15 @@ LocalBoard::~LocalBoard()
{ {
} }
void LocalBoard::setPlayerLists(PlayerList sl, PlayerList apl, PlayerList rpl) { void LocalBoard::setPlayerLists(PlayerList sl, PlayerList apl, PlayerList rpl)
{
seatsList = sl; seatsList = sl;
activePlayerList = apl; activePlayerList = apl;
runningPlayerList = rpl; runningPlayerList = rpl;
} }
void LocalBoard::collectSets() { void LocalBoard::collectSets()
{
sets = 0; sets = 0;
@@ -53,7 +55,8 @@ void LocalBoard::collectSets() {
} }
void LocalBoard::collectPot() { void LocalBoard::collectPot()
{
pot += sets; pot += sets;
sets = 0; sets = 0;
@@ -65,7 +68,8 @@ void LocalBoard::collectPot() {
} }
void LocalBoard::distributePot() { void LocalBoard::distributePot()
{
winners.clear(); winners.clear();
@@ -139,12 +143,12 @@ void LocalBoard::distributePot() {
if(mod == 0) { if(mod == 0) {
for(j=2; j<potLevel.size(); j++) { for(j=2; j<potLevel.size(); j++) {
// find seat with potLevel[j]-ID // find seat with potLevel[j]-ID
for(it=seatsList->begin(); it!=seatsList->end(); ++it) { for(it=seatsList->begin(); it!=seatsList->end(); ++it) {
if((*it)->getMyUniqueID() == potLevel[j]) { if((*it)->getMyUniqueID() == potLevel[j]) {
break; break;
} }
} }
if(it == seatsList->end()) { if(it == seatsList->end()) {
throw LocalException(__FILE__, __LINE__, ERR_SEAT_NOT_FOUND); throw LocalException(__FILE__, __LINE__, ERR_SEAT_NOT_FOUND);
} }
@@ -162,13 +166,13 @@ void LocalBoard::distributePot() {
// winnerPointer = currentHand->getDealerPosition(); // winnerPointer = currentHand->getDealerPosition();
// find Seat with dealerPosition // find Seat with dealerPosition
for(it=seatsList->begin(); it!=seatsList->end(); ++it) { for(it=seatsList->begin(); it!=seatsList->end(); ++it) {
if((*it)->getMyUniqueID() == dealerPosition) { if((*it)->getMyUniqueID() == dealerPosition) {
break; break;
} }
} }
if(it == seatsList->end()) { if(it == seatsList->end()) {
throw LocalException(__FILE__, __LINE__, ERR_SEAT_NOT_FOUND); throw LocalException(__FILE__, __LINE__, ERR_SEAT_NOT_FOUND);
} }
@@ -176,7 +180,7 @@ void LocalBoard::distributePot() {
winnerHit = false; winnerHit = false;
for(k=0; k<MAX_NUMBER_OF_PLAYERS && !winnerHit; k++){ for(k=0; k<MAX_NUMBER_OF_PLAYERS && !winnerHit; k++) {
// winnerPointer = (winnerPointer+1)%(MAX_NUMBER_OF_PLAYERS); // winnerPointer = (winnerPointer+1)%(MAX_NUMBER_OF_PLAYERS);
@@ -247,195 +251,196 @@ void LocalBoard::distributePot() {
}*/ }*/
} }
void LocalBoard::determinePlayerNeedToShowCards() { void LocalBoard::determinePlayerNeedToShowCards()
{
playerNeedToShowCards.clear(); playerNeedToShowCards.clear();
// in All In Condition everybody have to show the cards // in All In Condition everybody have to show the cards
if(allInCondition) { if(allInCondition) {
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) { for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) {
if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) { if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) {
playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
} }
} }
} }
else { else {
// all winners have to show their cards // all winners have to show their cards
// playerNeedToShowCards = winners; // playerNeedToShowCards = winners;
// std::_List_const_iterator<unsigned> it_c; // std::_List_const_iterator<unsigned> it_c;
std::list<int*> level; std::list<int*> level;
// for(it_c=winners.begin(); it_c != winners.end(); it_c++) { // for(it_c=winners.begin(); it_c != winners.end(); it_c++) {
// cout << (*it_c) << endl; // cout << (*it_c) << endl;
// } // }
// //
// cout << "lastActionPlayer" << currentHand->getCurrentBeRo()->getLastActionPlayer() << endl; // cout << "lastActionPlayer" << currentHand->getCurrentBeRo()->getLastActionPlayer() << endl;
// //
// int lastActionPlayer = ; // int lastActionPlayer = ;
// //
// if(lastActionPlayer == -1) { // if(lastActionPlayer == -1) {
// lastActionPlayer = 0; // lastActionPlayer = 0;
// } // }
// //
// //
// //
PlayerListConstIterator lastActionPlayerIt; PlayerListConstIterator lastActionPlayerIt;
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
// cout << "lAP-Ende: " << currentHand->getLastActionPlayer() << endl; // cout << "lAP-Ende: " << currentHand->getLastActionPlayer() << endl;
// search lastActionPlayer // search lastActionPlayer
for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) { for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) {
if((*it_c)->getMyUniqueID() == lastActionPlayer && (*it_c)->getMyAction() != PLAYER_ACTION_FOLD) { if((*it_c)->getMyUniqueID() == lastActionPlayer && (*it_c)->getMyAction() != PLAYER_ACTION_FOLD) {
lastActionPlayerIt = it_c; lastActionPlayerIt = it_c;
// cout << (*it_c)->getMyUniqueID() << endl; // cout << (*it_c)->getMyUniqueID() << endl;
break; break;
} }
} }
if(it_c == activePlayerList->end()) { if(it_c == activePlayerList->end()) {
for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) { for(it_c = activePlayerList->begin(); it_c != activePlayerList->end(); ++it_c) {
if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) { if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) {
lastActionPlayerIt = it_c; lastActionPlayerIt = it_c;
break; break;
} }
} }
} }
// the player who has done the last action has to show his cards first // the player who has done the last action has to show his cards first
playerNeedToShowCards.push_back((*lastActionPlayerIt)->getMyUniqueID()); playerNeedToShowCards.push_back((*lastActionPlayerIt)->getMyUniqueID());
// cout << (*lastActionPlayerIt)->getMyUniqueID() << " - " << (*lastActionPlayerIt)->getMyName() << endl; // cout << (*lastActionPlayerIt)->getMyUniqueID() << " - " << (*lastActionPlayerIt)->getMyName() << endl;
int *level_tmp = new int[2]; int *level_tmp = new int[2];
// get position und cardsValue of the player who show his cards first // get position und cardsValue of the player who show his cards first
level_tmp[0] = (*lastActionPlayerIt)->getMyCardsValueInt(); level_tmp[0] = (*lastActionPlayerIt)->getMyCardsValueInt();
level_tmp[1] = (*lastActionPlayerIt)->getMyRoundStartCash()-(*lastActionPlayerIt)->getMyCash(); level_tmp[1] = (*lastActionPlayerIt)->getMyRoundStartCash()-(*lastActionPlayerIt)->getMyCash();
// level_tmp = {(*lastActionPlayerIt)->getMyCardsValueInt(),(*lastActionPlayerIt)->getMyRoundStartCash()-(*lastActionPlayerIt)->getMyCash()}; // level_tmp = {(*lastActionPlayerIt)->getMyCardsValueInt(),(*lastActionPlayerIt)->getMyRoundStartCash()-(*lastActionPlayerIt)->getMyCash()};
// cout << level_tmp[0] << "," << level_tmp[1] << endl; // cout << level_tmp[0] << "," << level_tmp[1] << endl;
level.push_back(level_tmp); level.push_back(level_tmp);
std::_List_iterator<int*> level_it; std::_List_iterator<int*> level_it;
std::_List_iterator<int*> level_it_tmp; std::_List_iterator<int*> level_it_tmp;
std::_List_iterator<int*> next_level_it; std::_List_iterator<int*> next_level_it;
// PlayerListConstIterator firstAfterLastActionPlayerIt = lastActionPlayerIt; // PlayerListConstIterator firstAfterLastActionPlayerIt = lastActionPlayerIt;
// firstAfterLastActionPlayerIt++; // firstAfterLastActionPlayerIt++;
it_c = lastActionPlayerIt; it_c = lastActionPlayerIt;
++it_c; ++it_c;
for(unsigned i = 0; i < activePlayerList->size(); i++) { for(unsigned i = 0; i < activePlayerList->size(); i++) {
if(it_c == activePlayerList->end()) it_c = activePlayerList->begin(); if(it_c == activePlayerList->end()) it_c = activePlayerList->begin();
if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) { if((*it_c)->getMyAction() != PLAYER_ACTION_FOLD) {
// for(it_c = firstAfterLastActionPlayerIt; it_c != lastActionPlayerIt; it_c++) { // for(it_c = firstAfterLastActionPlayerIt; it_c != lastActionPlayerIt; it_c++) {
// if(it_c == lastActionPlayerIt) { // if(it_c == lastActionPlayerIt) {
// break; // break;
// } // }
// } // }
for(level_it = level.begin(); level_it != level.end(); level_it++) { for(level_it = level.begin(); level_it != level.end(); level_it++) {
if((*it_c)->getMyCardsValueInt() > (*level_it)[0]) { if((*it_c)->getMyCardsValueInt() > (*level_it)[0]) {
next_level_it = level_it; next_level_it = level_it;
next_level_it++; next_level_it++;
if(next_level_it == level.end()) { if(next_level_it == level.end()) {
playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
level_tmp = new int[2]; level_tmp = new int[2];
level_tmp[0] = (*it_c)->getMyCardsValueInt(); level_tmp[0] = (*it_c)->getMyCardsValueInt();
level_tmp[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash(); level_tmp[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash();
level.push_back(level_tmp); level.push_back(level_tmp);
break; break;
} }
} else { } else {
if((*it_c)->getMyCardsValueInt() == (*level_it)[0]) { if((*it_c)->getMyCardsValueInt() == (*level_it)[0]) {
next_level_it = level_it; next_level_it = level_it;
next_level_it++; next_level_it++;
// //
// for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) { // for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) {
// cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl; // cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl;
// } // }
if(next_level_it == level.end() || (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*next_level_it)[1]) { if(next_level_it == level.end() || (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*next_level_it)[1]) {
playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
if((*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*level_it)[1]) { if((*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*level_it)[1]) {
(*level_it)[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash(); (*level_it)[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash();
} }
} }
break; break;
} else { } else {
if((*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*level_it)[1]) { if((*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash() > (*level_it)[1]) {
playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
level_tmp = new int(2); level_tmp = new int(2);
level_tmp[0] = (*it_c)->getMyCardsValueInt(); level_tmp[0] = (*it_c)->getMyCardsValueInt();
level_tmp[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash(); level_tmp[1] = (*it_c)->getMyRoundStartCash()-(*it_c)->getMyCash();
// //
// for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) { // for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) {
// cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl; // cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl;
// } // }
level.insert(level_it,level_tmp); level.insert(level_it,level_tmp);
// for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) { // for(level_it_tmp = level.begin(); level_it_tmp != level.end(); level_it_tmp++) {
// cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl; // cout << (*level_it_tmp)[0] << "," << (*level_it_tmp)[1] << endl;
// } // }
break; break;
} }
} }
} }
} }
} }
++it_c; ++it_c;
} }
// bool showCards; // bool showCards;
// search for more player who have to show their cards (perhaps not all situation are considered yet) // search for more player who have to show their cards (perhaps not all situation are considered yet)
// for(it_c = ++lastActionPlayerIt; it_c!=activePlayerList->end(); it_c++) { // for(it_c = ++lastActionPlayerIt; it_c!=activePlayerList->end(); it_c++) {
// //
// showCards = false; // showCards = false;
// //
//// if((*it_c)->getMyCardsValueInt() >= highestCardsValueInt) { //// if((*it_c)->getMyCardsValueInt() >= highestCardsValueInt) {
//// playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); //// playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
//// highestCardsValueInt = (*it_c)->getMyCardsValueInt(); //// highestCardsValueInt = (*it_c)->getMyCardsValueInt();
//// } //// }
// } // }
// //
// for(it_c = activePlayerList->begin(); it_c!=lastActionPlayerIt; it_c++) { // for(it_c = activePlayerList->begin(); it_c!=lastActionPlayerIt; it_c++) {
//// if((*it_c)->getMyCardsValueInt() >= highestCardsValueInt) { //// if((*it_c)->getMyCardsValueInt() >= highestCardsValueInt) {
//// playerNeedToShowCards.push_back((*it_c)->getMyUniqueID()); //// playerNeedToShowCards.push_back((*it_c)->getMyUniqueID());
//// highestCardsValueInt = (*it_c)->getMyCardsValueInt(); //// highestCardsValueInt = (*it_c)->getMyCardsValueInt();
//// } //// }
// } // }
} }
// sort and unique the list // sort and unique the list
playerNeedToShowCards.sort(); playerNeedToShowCards.sort();
playerNeedToShowCards.unique(); playerNeedToShowCards.unique();
// std::_List_iterator<unsigned> playerNeedToShowCardsIt; // std::_List_iterator<unsigned> playerNeedToShowCardsIt;
// //
+46 -19
View File
@@ -30,35 +30,62 @@ class PlayerInterface;
class HandInterface; class HandInterface;
class LocalBoard : public BoardInterface{ class LocalBoard : public BoardInterface
{
public: public:
LocalBoard(unsigned dealerPosition); LocalBoard(unsigned dealerPosition);
~LocalBoard(); ~LocalBoard();
void setPlayerLists(PlayerList, PlayerList, PlayerList); void setPlayerLists(PlayerList, PlayerList, PlayerList);
void setMyCards(int* theValue) { int i; for(i=0; i<5; i++) myCards[i] = theValue[i]; } void setMyCards(int* theValue) {
void getMyCards(int* theValue) { int i; for(i=0; i<5; i++) theValue[i] = myCards[i]; } int i;
for(i=0; i<5; i++) myCards[i] = theValue[i];
}
void getMyCards(int* theValue) {
int i;
for(i=0; i<5; i++) theValue[i] = myCards[i];
}
void setAllInCondition(bool theValue) { allInCondition = theValue; } void setAllInCondition(bool theValue) {
void setLastActionPlayer(unsigned theValue) { lastActionPlayer = theValue; } allInCondition = theValue;
}
void setLastActionPlayer(unsigned theValue) {
lastActionPlayer = theValue;
}
int getPot() const { return pot;} int getPot() const {
void setPot(int theValue) { pot = theValue;} return pot;
int getSets() const { return sets; } }
void setSets(int theValue) { sets = theValue; } void setPot(int theValue) {
pot = theValue;
}
int getSets() const {
return sets;
}
void setSets(int theValue) {
sets = theValue;
}
void collectSets() ; void collectSets() ;
void collectPot() ; void collectPot() ;
void distributePot(); void distributePot();
void determinePlayerNeedToShowCards(); void determinePlayerNeedToShowCards();
std::list<unsigned> getWinners() const { return winners; } std::list<unsigned> getWinners() const {
void setWinners(const std::list<unsigned> &w) { winners = w; } return winners;
}
void setWinners(const std::list<unsigned> &w) {
winners = w;
}
std::list<unsigned> getPlayerNeedToShowCards() const { return playerNeedToShowCards; } std::list<unsigned> getPlayerNeedToShowCards() const {
void setPlayerNeedToShowCards(const std::list<unsigned> &p) { playerNeedToShowCards = p; } return playerNeedToShowCards;
}
void setPlayerNeedToShowCards(const std::list<unsigned> &p) {
playerNeedToShowCards = p;
}
private: private:
@@ -67,14 +94,14 @@ private:
PlayerList runningPlayerList; PlayerList runningPlayerList;
std::list<unsigned> winners; std::list<unsigned> winners;
std::list<unsigned> playerNeedToShowCards; std::list<unsigned> playerNeedToShowCards;
int myCards[5]; int myCards[5];
int pot; int pot;
int sets; int sets;
unsigned dealerPosition; unsigned dealerPosition;
bool allInCondition; bool allInCondition;
unsigned lastActionPlayer; unsigned lastActionPlayer;
}; };
@@ -32,7 +32,7 @@
LocalEngineFactory::LocalEngineFactory(ConfigFile *c) LocalEngineFactory::LocalEngineFactory(ConfigFile *c)
: myConfig(c) : myConfig(c)
{ {
} }
+228 -213
View File
@@ -31,8 +31,8 @@
using namespace std; using namespace std;
LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost::shared_ptr<BoardInterface> b, Log *l, PlayerList sl, PlayerList apl, PlayerList rpl, int id, int sP, unsigned dP, int sB,int sC) LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost::shared_ptr<BoardInterface> b, Log *l, PlayerList sl, PlayerList apl, PlayerList rpl, int id, int sP, unsigned dP, int sB,int sC)
: myFactory(f), myGui(g), myBoard(b), myLog(l), seatsList(sl), activePlayerList(apl), runningPlayerList(rpl), myBeRo(0), myID(id), startQuantityPlayers(sP), dealerPosition(dP), smallBlindPosition(dP), bigBlindPosition(dP), currentRound(0), smallBlind(sB), startCash(sC), lastPlayersTurn(-1), lastActionPlayer(0), allInCondition(false), : myFactory(f), myGui(g), myBoard(b), myLog(l), seatsList(sl), activePlayerList(apl), runningPlayerList(rpl), myBeRo(0), myID(id), startQuantityPlayers(sP), dealerPosition(dP), smallBlindPosition(dP), bigBlindPosition(dP), currentRound(0), smallBlind(sB), startCash(sC), lastPlayersTurn(-1), lastActionPlayer(0), allInCondition(false),
cardsShown(false), bettingRoundsPlayed(0) cardsShown(false), bettingRoundsPlayed(0)
{ {
int i, j, k; int i, j, k;
@@ -94,19 +94,19 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEBUGGER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEBUGGER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //
if(DEBUG_MODE) { if(DEBUG_MODE) {
//QSqlDatabase *mySqliteLogDb; //QSqlDatabase *mySqliteLogDb;
// myGui->getMyW()->getSession(); // myGui->getMyW()->getSession();
//QSqlDatabase * test = myGui->getMyLog()->getMySqliteLogDb(); //QSqlDatabase * test = myGui->getMyLog()->getMySqliteLogDb();
// if(!mySqliteLogDb->open()) { // if(!mySqliteLogDb->open()) {
// QMessageBox::critical(0, tr("ERROR"),mySqliteLogDb->lastError().text().toUtf8().data(), QMessageBox::Cancel); // QMessageBox::critical(0, tr("ERROR"),mySqliteLogDb->lastError().text().toUtf8().data(), QMessageBox::Cancel);
// } // }
@@ -114,159 +114,160 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
switch(myID) { switch(myID) {
case 1: { case 1: {
tempBoardArray[0] = 4; tempBoardArray[0] = 4;
tempBoardArray[1] = 19; tempBoardArray[1] = 19;
tempBoardArray[2] = 20; tempBoardArray[2] = 20;
tempBoardArray[3] = 43; tempBoardArray[3] = 43;
tempBoardArray[4] = 49; tempBoardArray[4] = 49;
myBoard->setMyCards(tempBoardArray); myBoard->setMyCards(tempBoardArray);
tempPlayerAndBoardArray[2] = tempBoardArray[0]; tempPlayerAndBoardArray[2] = tempBoardArray[0];
tempPlayerAndBoardArray[3] = tempBoardArray[1]; tempPlayerAndBoardArray[3] = tempBoardArray[1];
tempPlayerAndBoardArray[4] = tempBoardArray[2]; tempPlayerAndBoardArray[4] = tempBoardArray[2];
tempPlayerAndBoardArray[5] = tempBoardArray[3]; tempPlayerAndBoardArray[5] = tempBoardArray[3];
tempPlayerAndBoardArray[6] = tempBoardArray[4]; tempPlayerAndBoardArray[6] = tempBoardArray[4];
// player0 // player0
it = seatsList->begin(); it = seatsList->begin();
tempPlayerArray[0] = 18; tempPlayerArray[0] = 18;
tempPlayerArray[1] = 17; tempPlayerArray[1] = 17;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player1 // player1
++it; ++it;
tempPlayerArray[0] = 31; tempPlayerArray[0] = 31;
tempPlayerArray[1] = 8; tempPlayerArray[1] = 8;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player2 // player2
++it; ++it;
tempPlayerArray[0] = 26; tempPlayerArray[0] = 26;
tempPlayerArray[1] = 27; tempPlayerArray[1] = 27;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player3 // player3
++it; ++it;
tempPlayerArray[0] = 31; tempPlayerArray[0] = 31;
tempPlayerArray[1] = 30; tempPlayerArray[1] = 30;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player4 // player4
++it; ++it;
tempPlayerArray[0] = 50; tempPlayerArray[0] = 50;
tempPlayerArray[1] = 51; tempPlayerArray[1] = 51;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player5 // player5
++it; ++it;
tempPlayerArray[0] = 25; tempPlayerArray[0] = 25;
tempPlayerArray[1] = 24; tempPlayerArray[1] = 24;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player6 // player6
++it; ++it;
tempPlayerArray[0] = 38; tempPlayerArray[0] = 38;
tempPlayerArray[1] = 37; tempPlayerArray[1] = 37;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player7 // player7
++it; ++it;
tempPlayerArray[0] = 32; tempPlayerArray[0] = 32;
tempPlayerArray[1] = 33; tempPlayerArray[1] = 33;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
// player8 // player8
++it; ++it;
tempPlayerArray[0] = 19; tempPlayerArray[0] = 19;
tempPlayerArray[1] = 20; tempPlayerArray[1] = 20;
tempPlayerAndBoardArray[0] = tempPlayerArray[0]; tempPlayerAndBoardArray[0] = tempPlayerArray[0];
tempPlayerAndBoardArray[1] = tempPlayerArray[1]; tempPlayerAndBoardArray[1] = tempPlayerArray[1];
(*it)->setMyCards(tempPlayerArray); (*it)->setMyCards(tempPlayerArray);
(*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array)); (*it)->setMyCardsValueInt(myCardsValue.cardsValue(tempPlayerAndBoardArray,temp5Array));
(*it)->setMyBestHandPosition(temp5Array); (*it)->setMyBestHandPosition(temp5Array);
} break; }
case 2: { break;
case 2: {
/* tempBoardArray[0] = 48; /* tempBoardArray[0] = 48;
tempBoardArray[1] = 21; tempBoardArray[1] = 21;
tempBoardArray[2] = 4; tempBoardArray[2] = 4;
tempBoardArray[3] = 9; tempBoardArray[3] = 9;
tempBoardArray[4] = 0; tempBoardArray[4] = 0;
myBoard->setMyCards(tempBoardArray); myBoard->setMyCards(tempBoardArray);
tempPlayerAndBoardArray[2] = tempBoardArray[0]; tempPlayerAndBoardArray[2] = tempBoardArray[0];
tempPlayerAndBoardArray[3] = tempBoardArray[1]; tempPlayerAndBoardArray[3] = tempBoardArray[1];
tempPlayerAndBoardArray[4] = tempBoardArray[2]; tempPlayerAndBoardArray[4] = tempBoardArray[2];
tempPlayerAndBoardArray[5] = tempBoardArray[3]; tempPlayerAndBoardArray[5] = tempBoardArray[3];
tempPlayerAndBoardArray[6] = tempBoardArray[4];*/ tempPlayerAndBoardArray[6] = tempBoardArray[4];*/
// player0 // player0
it = seatsList->begin(); it = seatsList->begin();
// tempPlayerArray[0] = 9; // tempPlayerArray[0] = 9;
// tempPlayerArray[1] = 5; // tempPlayerArray[1] = 5;
@@ -278,8 +279,8 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
// player1 // player1
++it; ++it;
// tempPlayerArray[0] = 47; // tempPlayerArray[0] = 47;
// tempPlayerArray[1] = 22; // tempPlayerArray[1] = 22;
@@ -291,8 +292,8 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
// player2 // player2
++it; ++it;
// tempPlayerArray[0] = 33; // tempPlayerArray[0] = 33;
// tempPlayerArray[1] = 27; // tempPlayerArray[1] = 27;
@@ -304,8 +305,8 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
// player3 // player3
++it; ++it;
// tempPlayerArray[0] = 38; // tempPlayerArray[0] = 38;
// tempPlayerArray[1] = 22; // tempPlayerArray[1] = 22;
@@ -317,8 +318,8 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
// player4 // player4
++it; ++it;
// tempPlayerArray[0] = 25; // tempPlayerArray[0] = 25;
// tempPlayerArray[1] = 16; // tempPlayerArray[1] = 16;
@@ -330,8 +331,8 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
// player5 // player5
++it; ++it;
// tempPlayerArray[0] = 27; // tempPlayerArray[0] = 27;
// tempPlayerArray[1] = 10; // tempPlayerArray[1] = 10;
@@ -343,8 +344,10 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// //
// (*it)->setMyBestHandPosition(temp5Array); // (*it)->setMyBestHandPosition(temp5Array);
} break; }
default: {} break;
default:
{}
} }
@@ -356,7 +359,7 @@ LocalHand::LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost:
// determine dealer, SB, BB // determine dealer, SB, BB
assignButtons(); assignButtons();
myLog->logNewHandMsg(myID, dealerPosition, smallBlind, smallBlindPosition, 2*smallBlind, bigBlindPosition, seatsList); myLog->logNewHandMsg(myID, dealerPosition, smallBlind, smallBlindPosition, 2*smallBlind, bigBlindPosition, seatsList);
myBeRo = myFactory->createBeRo(this, myID, dealerPosition, smallBlind); myBeRo = myFactory->createBeRo(this, myID, dealerPosition, smallBlind);
} }
@@ -367,16 +370,18 @@ LocalHand::~LocalHand()
{ {
} }
void LocalHand::start() { void LocalHand::start()
{
//Log blinds sets for new Hand //Log blinds sets for new Hand
PlayerListConstIterator it_sB, it_bB; PlayerListConstIterator it_sB, it_bB;
it_sB = getActivePlayerIt(getCurrentBeRo()->getSmallBlindPositionId()); it_sB = getActivePlayerIt(getCurrentBeRo()->getSmallBlindPositionId());
it_bB = getActivePlayerIt(getCurrentBeRo()->getBigBlindPositionId()); it_bB = getActivePlayerIt(getCurrentBeRo()->getBigBlindPositionId());
if(it_sB != getActivePlayerList()->end() && it_bB != getActivePlayerList()->end()) { if(it_sB != getActivePlayerList()->end() && it_bB != getActivePlayerList()->end()) {
myGui->logNewBlindsSetsMsg((*it_sB)->getMySet(), (*it_bB)->getMySet(), (*it_sB)->getMyName().c_str(), (*it_bB)->getMyName().c_str()); myGui->logNewBlindsSetsMsg((*it_sB)->getMySet(), (*it_bB)->getMySet(), (*it_sB)->getMyName().c_str(), (*it_bB)->getMyName().c_str());
} else {
LOG_ERROR(__FILE__ << " (" << __LINE__ << "): Log Error: cannot find sBID or bBID");
} }
else { LOG_ERROR(__FILE__ << " (" << __LINE__ << "): Log Error: cannot find sBID or bBID"); }
myGui->flushLogAtHand(); myGui->flushLogAtHand();
// deal cards // deal cards
@@ -389,7 +394,8 @@ void LocalHand::start() {
myGui->nextPlayerAnimation(); myGui->nextPlayerAnimation();
} }
void LocalHand::assignButtons() { void LocalHand::assignButtons()
{
size_t i; size_t i;
PlayerListIterator it; PlayerListIterator it;
@@ -424,33 +430,33 @@ void LocalHand::assignButtons() {
it = getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() ); it = getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() );
if(it != activePlayerList->end() ) { if(it != activePlayerList->end() ) {
nextActivePlayerFound = true; nextActivePlayerFound = true;
if(activePlayerList->size() > 2) { if(activePlayerList->size() > 2) {
//small blind normal //small blind normal
(*it)->setMyButton(2); (*it)->setMyButton(2);
smallBlindPosition = (*it)->getMyUniqueID(); smallBlindPosition = (*it)->getMyUniqueID();
} else { } else {
//big blind in heads up //big blind in heads up
(*it)->setMyButton(3); (*it)->setMyButton(3);
bigBlindPosition = (*it)->getMyUniqueID(); bigBlindPosition = (*it)->getMyUniqueID();
// lastPlayerAction for showing cards // lastPlayerAction for showing cards
} }
// first player after dealer have to show his cards first (in showdown) // first player after dealer have to show his cards first (in showdown)
lastActionPlayer = (*it)->getMyUniqueID(); lastActionPlayer = (*it)->getMyUniqueID();
myBoard->setLastActionPlayer(lastActionPlayer); myBoard->setLastActionPlayer(lastActionPlayer);
++it; ++it;
if(it == activePlayerList->end()) it = activePlayerList->begin(); if(it == activePlayerList->end()) it = activePlayerList->begin();
if(activePlayerList->size() > 2) { if(activePlayerList->size() > 2) {
//big blind normal //big blind normal
(*it)->setMyButton(3); (*it)->setMyButton(3);
bigBlindPosition = (*it)->getMyUniqueID(); bigBlindPosition = (*it)->getMyUniqueID();
} else { } else {
//small blind in heads up //small blind in heads up
(*it)->setMyButton(2); (*it)->setMyButton(2);
smallBlindPosition = (*it)->getMyUniqueID(); smallBlindPosition = (*it)->getMyUniqueID();
} }
break; break;
} }
@@ -475,8 +481,7 @@ void LocalHand::assignButtons() {
// 1 to do not log this // 1 to do not log this
(*it_c)->setMyAction(PLAYER_ACTION_ALLIN,1); (*it_c)->setMyAction(PLAYER_ACTION_ALLIN,1);
} } else {
else {
(*it_c)->setMySet(smallBlind); (*it_c)->setMySet(smallBlind);
} }
} }
@@ -491,8 +496,7 @@ void LocalHand::assignButtons() {
// 1 to do not log this // 1 to do not log this
(*it_c)->setMyAction(PLAYER_ACTION_ALLIN,1); (*it_c)->setMyAction(PLAYER_ACTION_ALLIN,1);
} } else {
else {
(*it_c)->setMySet(2*smallBlind); (*it_c)->setMySet(2*smallBlind);
} }
} }
@@ -500,7 +504,8 @@ void LocalHand::assignButtons() {
} }
void LocalHand::switchRounds() { void LocalHand::switchRounds()
{
PlayerListIterator it, it_1; PlayerListIterator it, it_1;
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
@@ -550,7 +555,7 @@ void LocalHand::switchRounds() {
// 1) all players all in // 1) all players all in
if(allInPlayersCounter == nonFoldPlayerCounter) { if(allInPlayersCounter == nonFoldPlayerCounter) {
allInCondition = true; allInCondition = true;
myBoard->setAllInCondition(true); myBoard->setAllInCondition(true);
} }
// 2) all players but one all in and he has highest set // 2) all players but one all in and he has highest set
@@ -559,38 +564,38 @@ void LocalHand::switchRounds() {
for(it_c=runningPlayerList->begin(); it_c!=runningPlayerList->end(); ++it_c) { for(it_c=runningPlayerList->begin(); it_c!=runningPlayerList->end(); ++it_c) {
if((*it_c)->getMySet() >= myBeRo[currentRound]->getHighestSet()) { if((*it_c)->getMySet() >= myBeRo[currentRound]->getHighestSet()) {
allInCondition = true; allInCondition = true;
myBoard->setAllInCondition(true); myBoard->setAllInCondition(true);
} }
} }
// exception // exception
// no.1: if in first Preflop Round next player is small blind and only all-in-big-blind with less than smallblind amount and other all-in players with less than small blind are nonfold too -> preflop is over // no.1: if in first Preflop Round next player is small blind and only all-in-big-blind with less than smallblind amount and other all-in players with less than small blind are nonfold too -> preflop is over
PlayerListConstIterator smallBlindIt_c = getRunningPlayerIt(myBeRo[currentRound]->getSmallBlindPositionId()); PlayerListConstIterator smallBlindIt_c = getRunningPlayerIt(myBeRo[currentRound]->getSmallBlindPositionId());
PlayerListConstIterator bigBlindIt_c = getActivePlayerIt(myBeRo[currentRound]->getBigBlindPositionId()); PlayerListConstIterator bigBlindIt_c = getActivePlayerIt(myBeRo[currentRound]->getBigBlindPositionId());
if(smallBlindIt_c!=runningPlayerList->end() && bigBlindIt_c!=activePlayerList->end() && currentRound == GAME_STATE_PREFLOP && myBeRo[currentRound]->getFirstRound()) { if(smallBlindIt_c!=runningPlayerList->end() && bigBlindIt_c!=activePlayerList->end() && currentRound == GAME_STATE_PREFLOP && myBeRo[currentRound]->getFirstRound()) {
// determine player who are all in with less than small blind amount // determine player who are all in with less than small blind amount
int tempCounter = 0; int tempCounter = 0;
for(it_c=activePlayerList->begin(); it_c!=activePlayerList->end(); ++it_c) {
if((*it_c)->getMyAction() == PLAYER_ACTION_ALLIN && (*it_c)->getMySet() <= smallBlind) {
tempCounter++;
}
}
if( (*bigBlindIt_c)->getMySet() <= smallBlind && tempCounter == allInPlayersCounter) {
allInCondition = true;
myBoard->setAllInCondition(true);
}
}
// no.2: heads up -> detect player who is all in and bb but could set less than sb
for(it_c=activePlayerList->begin(); it_c!=activePlayerList->end(); ++it_c) { for(it_c=activePlayerList->begin(); it_c!=activePlayerList->end(); ++it_c) {
if((*it_c)->getMyAction() == PLAYER_ACTION_ALLIN && (*it_c)->getMySet() <= smallBlind) {
if(activePlayerList->size()==2 && (*it_c)->getMyAction() == PLAYER_ACTION_ALLIN && (*it_c)->getMyButton()==BUTTON_BIG_BLIND && (*it_c)->getMySet()<=smallBlind && currentRound == GAME_STATE_PREFLOP) { tempCounter++;
allInCondition = true;
myBoard->setAllInCondition(true);
} }
} }
if( (*bigBlindIt_c)->getMySet() <= smallBlind && tempCounter == allInPlayersCounter) {
allInCondition = true;
myBoard->setAllInCondition(true);
}
}
// no.2: heads up -> detect player who is all in and bb but could set less than sb
for(it_c=activePlayerList->begin(); it_c!=activePlayerList->end(); ++it_c) {
if(activePlayerList->size()==2 && (*it_c)->getMyAction() == PLAYER_ACTION_ALLIN && (*it_c)->getMyButton()==BUTTON_BIG_BLIND && (*it_c)->getMySet()<=smallBlind && currentRound == GAME_STATE_PREFLOP) {
allInCondition = true;
myBoard->setAllInCondition(true);
}
}
} }
} }
@@ -624,30 +629,36 @@ void LocalHand::switchRounds() {
myGui->refreshGameLabels((GameState)getCurrentRound()); myGui->refreshGameLabels((GameState)getCurrentRound());
switch(currentRound) { switch(currentRound) {
case 0: { case 0: {
// start preflop // start preflop
myGui->preflopAnimation1(); myGui->preflopAnimation1();
} break; }
case 1: { break;
// start flop case 1: {
myGui->flopAnimation1(); // start flop
} break; myGui->flopAnimation1();
case 2: { }
// start turn break;
myGui->turnAnimation1(); case 2: {
// start turn
myGui->turnAnimation1();
} break; }
case 3: { break;
// start river case 3: {
myGui->riverAnimation1(); // start river
myGui->riverAnimation1();
} break; }
case 4: { break;
// start post river case 4: {
myGui->postRiverAnimation1(); // start post river
myGui->postRiverAnimation1();
} break; }
default: {} break;
default:
{}
@@ -655,7 +666,8 @@ void LocalHand::switchRounds() {
} }
PlayerListIterator LocalHand::getSeatIt(unsigned uniqueId) const { PlayerListIterator LocalHand::getSeatIt(unsigned uniqueId) const
{
PlayerListIterator it; PlayerListIterator it;
@@ -669,7 +681,8 @@ PlayerListIterator LocalHand::getSeatIt(unsigned uniqueId) const {
} }
PlayerListIterator LocalHand::getActivePlayerIt(unsigned uniqueId) const { PlayerListIterator LocalHand::getActivePlayerIt(unsigned uniqueId) const
{
PlayerListIterator it; PlayerListIterator it;
@@ -683,7 +696,8 @@ PlayerListIterator LocalHand::getActivePlayerIt(unsigned uniqueId) const {
} }
PlayerListIterator LocalHand::getRunningPlayerIt(unsigned uniqueId) const { PlayerListIterator LocalHand::getRunningPlayerIt(unsigned uniqueId) const
{
PlayerListIterator it; PlayerListIterator it;
@@ -698,7 +712,8 @@ PlayerListIterator LocalHand::getRunningPlayerIt(unsigned uniqueId) const {
} }
void LocalHand::setLastActionPlayer(unsigned theValue) { void LocalHand::setLastActionPlayer(unsigned theValue)
lastActionPlayer = theValue; {
myBoard->setLastActionPlayer(theValue); lastActionPlayer = theValue;
myBoard->setLastActionPlayer(theValue);
} }
+102 -39
View File
@@ -31,57 +31,120 @@
class Log; class Log;
class LocalHand : public HandInterface{ class LocalHand : public HandInterface
{
public: public:
LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface*, boost::shared_ptr<BoardInterface>, Log*, PlayerList, PlayerList, PlayerList, int, int, unsigned, int, int); LocalHand(boost::shared_ptr<EngineFactory> f, GuiInterface*, boost::shared_ptr<BoardInterface>, Log*, PlayerList, PlayerList, PlayerList, int, int, unsigned, int, int);
~LocalHand(); ~LocalHand();
void start(); void start();
PlayerList getSeatsList() const {return seatsList;} PlayerList getSeatsList() const {
PlayerList getActivePlayerList() const {return activePlayerList;} return seatsList;
PlayerList getRunningPlayerList() const {return runningPlayerList;} }
PlayerList getActivePlayerList() const {
return activePlayerList;
}
PlayerList getRunningPlayerList() const {
return runningPlayerList;
}
boost::shared_ptr<BoardInterface> getBoard() const { return myBoard; } boost::shared_ptr<BoardInterface> getBoard() const {
boost::shared_ptr<BeRoInterface> getPreflop() const { return myBeRo[GAME_STATE_PREFLOP]; } return myBoard;
boost::shared_ptr<BeRoInterface> getFlop() const { return myBeRo[GAME_STATE_FLOP]; } }
boost::shared_ptr<BeRoInterface> getTurn() const { return myBeRo[GAME_STATE_TURN]; } boost::shared_ptr<BeRoInterface> getPreflop() const {
boost::shared_ptr<BeRoInterface> getRiver() const { return myBeRo[GAME_STATE_RIVER]; } return myBeRo[GAME_STATE_PREFLOP];
GuiInterface* getGuiInterface() const { return myGui; } }
boost::shared_ptr<BeRoInterface> getCurrentBeRo() const { return myBeRo[currentRound]; } boost::shared_ptr<BeRoInterface> getFlop() const {
return myBeRo[GAME_STATE_FLOP];
}
boost::shared_ptr<BeRoInterface> getTurn() const {
return myBeRo[GAME_STATE_TURN];
}
boost::shared_ptr<BeRoInterface> getRiver() const {
return myBeRo[GAME_STATE_RIVER];
}
GuiInterface* getGuiInterface() const {
return myGui;
}
boost::shared_ptr<BeRoInterface> getCurrentBeRo() const {
return myBeRo[currentRound];
}
void setMyID(int theValue) { myID = theValue; } void setMyID(int theValue) {
int getMyID() const { return myID; } myID = theValue;
}
int getMyID() const {
return myID;
}
void setStartQuantityPlayers(int theValue) { startQuantityPlayers = theValue; } void setStartQuantityPlayers(int theValue) {
int getStartQuantityPlayers() const { return startQuantityPlayers; } startQuantityPlayers = theValue;
}
int getStartQuantityPlayers() const {
return startQuantityPlayers;
}
void setCurrentRound(int theValue) { currentRound = theValue; } void setCurrentRound(int theValue) {
int getCurrentRound() const { return currentRound; } currentRound = theValue;
}
int getCurrentRound() const {
return currentRound;
}
void setDealerPosition(int theValue) { dealerPosition = theValue; } void setDealerPosition(int theValue) {
int getDealerPosition() const { return dealerPosition; } dealerPosition = theValue;
}
int getDealerPosition() const {
return dealerPosition;
}
void setSmallBlind(int theValue) { smallBlind = theValue; } void setSmallBlind(int theValue) {
int getSmallBlind() const { return smallBlind; } smallBlind = theValue;
}
int getSmallBlind() const {
return smallBlind;
}
void setAllInCondition(bool theValue) { allInCondition = theValue; } void setAllInCondition(bool theValue) {
bool getAllInCondition() const { return allInCondition; } allInCondition = theValue;
}
bool getAllInCondition() const {
return allInCondition;
}
void setStartCash(int theValue) { startCash = theValue; } void setStartCash(int theValue) {
int getStartCash() const { return startCash; } startCash = theValue;
}
int getStartCash() const {
return startCash;
}
void setBettingRoundsPlayed(int theValue) { bettingRoundsPlayed = theValue; } void setBettingRoundsPlayed(int theValue) {
int getBettingRoundsPlayed() const { return bettingRoundsPlayed; } bettingRoundsPlayed = theValue;
}
int getBettingRoundsPlayed() const {
return bettingRoundsPlayed;
}
void setLastPlayersTurn(int theValue) { lastPlayersTurn = theValue; } void setLastPlayersTurn(int theValue) {
int getLastPlayersTurn() const { return lastPlayersTurn; } lastPlayersTurn = theValue;
}
int getLastPlayersTurn() const {
return lastPlayersTurn;
}
void setLastActionPlayer ( unsigned theValue ); void setLastActionPlayer ( unsigned theValue );
unsigned getLastActionPlayer() const { return lastActionPlayer; } unsigned getLastActionPlayer() const {
return lastActionPlayer;
}
void setCardsShown(bool theValue) { cardsShown = theValue; } void setCardsShown(bool theValue) {
bool getCardsShown() const { return cardsShown; } cardsShown = theValue;
}
bool getCardsShown() const {
return cardsShown;
}
void assignButtons(); void assignButtons();
@@ -97,25 +160,25 @@ private:
boost::shared_ptr<EngineFactory> myFactory; boost::shared_ptr<EngineFactory> myFactory;
GuiInterface *myGui; GuiInterface *myGui;
boost::shared_ptr<BoardInterface> myBoard; boost::shared_ptr<BoardInterface> myBoard;
Log *myLog; Log *myLog;
PlayerList seatsList; // all player PlayerList seatsList; // all player
PlayerList activePlayerList; // all player who are not out PlayerList activePlayerList; // all player who are not out
PlayerList runningPlayerList; // all player who are not folded, not all in and not out PlayerList runningPlayerList; // all player who are not folded, not all in and not out
std::vector<boost::shared_ptr<BeRoInterface> > myBeRo; std::vector<boost::shared_ptr<BeRoInterface> > myBeRo;
int myID; int myID;
int startQuantityPlayers; int startQuantityPlayers;
unsigned dealerPosition; unsigned dealerPosition;
unsigned smallBlindPosition; unsigned smallBlindPosition;
unsigned bigBlindPosition; unsigned bigBlindPosition;
int currentRound; //0 = preflop, 1 = flop, 2 = turn, 3 = river int currentRound; //0 = preflop, 1 = flop, 2 = turn, 3 = river
int smallBlind; int smallBlind;
int startCash; int startCash;
int lastPlayersTurn; int lastPlayersTurn;
unsigned lastActionPlayer; unsigned lastActionPlayer;
bool allInCondition; bool allInCondition;
bool cardsShown; bool cardsShown;
File diff suppressed because it is too large. Load diff
+152 -55
View File
@@ -30,7 +30,8 @@ class CardsValue;
class ConfigFile; class ConfigFile;
class HandInterface; class HandInterface;
class LocalPlayer : public PlayerInterface{ class LocalPlayer : public PlayerInterface
{
public: public:
LocalPlayer(ConfigFile*, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB); LocalPlayer(ConfigFile*, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB);
@@ -38,92 +39,178 @@ public:
void setHand(HandInterface *); void setHand(HandInterface *);
int getMyID() const { return myID; } int getMyID() const {
unsigned getMyUniqueID() const { return myUniqueID; } return myID;
PlayerType getMyType() const { return myType; } }
unsigned getMyUniqueID() const {
return myUniqueID;
}
PlayerType getMyType() const {
return myType;
}
void setMyDude(int theValue) { myDude = theValue; } void setMyDude(int theValue) {
int getMyDude() const { return myDude; } myDude = theValue;
}
int getMyDude() const {
return myDude;
}
void setMyDude4(int theValue) { myDude4 = theValue; } void setMyDude4(int theValue) {
int getMyDude4() const { return myDude4; } myDude4 = theValue;
}
int getMyDude4() const {
return myDude4;
}
void setMyName(const std::string& theValue) { myName = theValue; } void setMyName(const std::string& theValue) {
std::string getMyName() const { return myName; } myName = theValue;
}
std::string getMyName() const {
return myName;
}
void setMyAvatar(const std::string& theValue) { myAvatar = theValue; } void setMyAvatar(const std::string& theValue) {
std::string getMyAvatar() const { return myAvatar; } myAvatar = theValue;
}
std::string getMyAvatar() const {
return myAvatar;
}
void setMyCash(int theValue) { myCash = theValue; } void setMyCash(int theValue) {
int getMyCash() const { return myCash; } myCash = theValue;
}
int getMyCash() const {
return myCash;
}
void setMySet(int theValue) { myLastRelativeSet = theValue; mySet += theValue; myCash -= theValue; } void setMySet(int theValue) {
void setMySetAbsolute(int theValue) { mySet = theValue; } myLastRelativeSet = theValue;
void setMySetNull() { mySet = 0; myLastRelativeSet = 0; } mySet += theValue;
int getMySet() const { return mySet;} myCash -= theValue;
int getMyLastRelativeSet() const { return myLastRelativeSet; } }
void setMySetAbsolute(int theValue) {
mySet = theValue;
}
void setMySetNull() {
mySet = 0;
myLastRelativeSet = 0;
}
int getMySet() const {
return mySet;
}
int getMyLastRelativeSet() const {
return myLastRelativeSet;
}
void setMyAction(int theValue, bool blind = 0) { void setMyAction(int theValue, bool blind = 0) {
myAction = theValue; myAction = theValue;
// logging for human player // logging for human player
if(myAction && !blind) currentHand->getGuiInterface()->logPlayerActionMsg(myName, myID, myAction, mySet); if(myAction && !blind) currentHand->getGuiInterface()->logPlayerActionMsg(myName, myID, myAction, mySet);
}
int getMyAction() const {
return myAction;
} }
int getMyAction() const { return myAction; }
void setMyButton(int theValue) { myButton = theValue; } void setMyButton(int theValue) {
int getMyButton() const { return myButton; } myButton = theValue;
}
int getMyButton() const {
return myButton;
}
void setMyActiveStatus(bool theValue) { myActiveStatus = theValue; } void setMyActiveStatus(bool theValue) {
bool getMyActiveStatus() const { return myActiveStatus; } myActiveStatus = theValue;
}
bool getMyActiveStatus() const {
return myActiveStatus;
}
void setMyStayOnTableStatus(bool theValue) { myStayOnTableStatus = theValue; } void setMyStayOnTableStatus(bool theValue) {
bool getMyStayOnTableStatus() const { return myStayOnTableStatus; } myStayOnTableStatus = theValue;
}
bool getMyStayOnTableStatus() const {
return myStayOnTableStatus;
}
void setMyCards(int* theValue) { int i; for(i=0; i<2; i++) myCards[i] = theValue[i]; } void setMyCards(int* theValue) {
void getMyCards(int* theValue) const { int i; for(i=0; i<2; i++) theValue[i] = myCards[i]; } int i;
for(i=0; i<2; i++) myCards[i] = theValue[i];
}
void getMyCards(int* theValue) const {
int i;
for(i=0; i<2; i++) theValue[i] = myCards[i];
}
void setMyTurn(bool theValue){ myTurn = theValue;} void setMyTurn(bool theValue) {
bool getMyTurn() const{ return myTurn;} myTurn = theValue;
}
bool getMyTurn() const {
return myTurn;
}
void setMyCardsFlip(bool theValue, int state){ void setMyCardsFlip(bool theValue, int state) {
myCardsFlip = theValue; myCardsFlip = theValue;
// log flipping cards // log flipping cards
if(myCardsFlip) { if(myCardsFlip) {
switch(state) { switch(state) {
case 1: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt); case 1:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt);
break; break;
case 2: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1]); case 2:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1]);
break; break;
case 3: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt, "has"); case 3:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt, "has");
break; break;
default: ; default:
;
} }
} }
} }
bool getMyCardsFlip() const{ return myCardsFlip;} bool getMyCardsFlip() const {
return myCardsFlip;
}
void setMyCardsValueInt(int theValue) { myCardsValueInt = theValue;} void setMyCardsValueInt(int theValue) {
int getMyCardsValueInt() const { return myCardsValueInt; } myCardsValueInt = theValue;
}
int getMyCardsValueInt() const {
return myCardsValueInt;
}
void setMyBestHandPosition(int* theValue) void setMyBestHandPosition(int* theValue) {
{
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
myBestHandPosition[i] = theValue[i]; myBestHandPosition[i] = theValue[i];
} }
void getMyBestHandPosition(int* theValue) const void getMyBestHandPosition(int* theValue) const {
{
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
theValue[i] = myBestHandPosition[i]; theValue[i] = myBestHandPosition[i];
} }
void setMyRoundStartCash(int theValue) { myRoundStartCash = theValue;} void setMyRoundStartCash(int theValue) {
int getMyRoundStartCash() const { return myRoundStartCash; } myRoundStartCash = theValue;
}
int getMyRoundStartCash() const {
return myRoundStartCash;
}
void setLastMoneyWon ( int theValue ) { lastMoneyWon = theValue; } void setLastMoneyWon ( int theValue ) {
int getLastMoneyWon() const { return lastMoneyWon; } lastMoneyWon = theValue;
}
int getLastMoneyWon() const {
return lastMoneyWon;
}
void setMyAverageSets(int theValue) { myAverageSets[0] = myAverageSets[1]; myAverageSets[1] = myAverageSets[2]; myAverageSets[2] = myAverageSets[3]; myAverageSets[3] = theValue; } void setMyAverageSets(int theValue) {
int getMyAverageSets() const { return (myAverageSets[0]+myAverageSets[1]+myAverageSets[2]+myAverageSets[3])/4; } myAverageSets[0] = myAverageSets[1];
myAverageSets[1] = myAverageSets[2];
myAverageSets[2] = myAverageSets[3];
myAverageSets[3] = theValue;
}
int getMyAverageSets() const {
return (myAverageSets[0]+myAverageSets[1]+myAverageSets[2]+myAverageSets[3])/4;
}
void setMyAggressive(bool theValue) { void setMyAggressive(bool theValue) {
int i; int i;
@@ -140,17 +227,27 @@ public:
return sum; return sum;
} }
void setSBluff ( int theValue ) { sBluff = theValue; } void setSBluff ( int theValue ) {
int getSBluff() const { return sBluff; } sBluff = theValue;
}
int getSBluff() const {
return sBluff;
}
void setSBluffStatus ( bool theValue ) { sBluffStatus = theValue; } void setSBluffStatus ( bool theValue ) {
bool getSBluffStatus() const { return sBluffStatus; } sBluffStatus = theValue;
}
bool getSBluffStatus() const {
return sBluffStatus;
}
void setMyWinnerState ( bool theValue, int pot ) { void setMyWinnerState ( bool theValue, int pot ) {
if(theValue) myWinnerState = theValue; if(theValue) myWinnerState = theValue;
currentHand->getGuiInterface()->logPlayerWinsMsg(myName, pot, theValue); currentHand->getGuiInterface()->logPlayerWinsMsg(myName, pot, theValue);
} }
bool getMyWinnerState() const { return myWinnerState;} bool getMyWinnerState() const {
return myWinnerState;
}
@@ -214,7 +311,7 @@ private:
int myAction; // 0 = none, 1 = fold, 2 = check, 3 = call, 4 = bet, 5 = raise, 6 = allin int myAction; // 0 = none, 1 = fold, 2 = check, 3 = call, 4 = bet, 5 = raise, 6 = allin
int myButton; // 0 = none, 1 = dealer, 2 =small, 3 = big int myButton; // 0 = none, 1 = dealer, 2 =small, 3 = big
bool myActiveStatus; // 0 = inactive, 1 = active bool myActiveStatus; // 0 = inactive, 1 = active
bool myStayOnTableStatus; // 0 = left, 1 = stay bool myStayOnTableStatus; // 0 = left, 1 = stay
bool myTurn; // 0 = no, 1 = yes bool myTurn; // 0 = no, 1 = yes
bool myCardsFlip; // 0 = cards are not fliped, 1 = cards are already flipped, bool myCardsFlip; // 0 = cards are not fliped, 1 = cards are already flipped,
int myRoundStartCash; int myRoundStartCash;
+4 -4
View File
@@ -25,10 +25,10 @@ Replay::Replay() : replaySqliteLogDb(0)
// replaySqliteLogDb = new QSqlDatabase(); // replaySqliteLogDb = new QSqlDatabase();
// //
// *replaySqliteLogDb = QSqlDatabase::addDatabase("QSQLITE"); // *replaySqliteLogDb = QSqlDatabase::addDatabase("QSQLITE");
//replaySqliteLogDb->setDatabaseName(myLogDir->absolutePath()+"/pokerth-log-"+currentTime.toString("yyyy-MM-dd_hh.mm.ss")+".pdb"); //replaySqliteLogDb->setDatabaseName(myLogDir->absolutePath()+"/pokerth-log-"+currentTime.toString("yyyy-MM-dd_hh.mm.ss")+".pdb");
//if(!mySqliteLogDb->open()) { //if(!mySqliteLogDb->open()) {
// QMessageBox::critical(0, tr("ERROR"),mySqliteLogDb->lastError().text().toUtf8().data(), QMessageBox::Cancel); // QMessageBox::critical(0, tr("ERROR"),mySqliteLogDb->lastError().text().toUtf8().data(), QMessageBox::Cancel);
//} //}
} }
+4 -4
View File
@@ -24,12 +24,12 @@
class Replay class Replay
{ {
public: public:
Replay(); Replay();
~Replay(); ~Replay();
private: private:
QSqlDatabase *replaySqliteLogDb; QSqlDatabase *replaySqliteLogDb;
}; };
+6 -8
View File
@@ -27,7 +27,8 @@
using namespace std; using namespace std;
void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool different, int* bad, int countBad) { void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool different, int* bad, int countBad)
{
int r = end-start+1; int r = end-start+1;
unsigned char rand_buf[4]; unsigned char rand_buf[4];
@@ -39,8 +40,7 @@ void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool
for (i=0; i<howMany; i++) { for (i=0; i<howMany; i++) {
if(!RAND_bytes(rand_buf, 4)) if(!RAND_bytes(rand_buf, 4)) {
{
LOG_MSG("RAND_bytes failed!"); LOG_MSG("RAND_bytes failed!");
} }
@@ -54,14 +54,13 @@ void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool
} }
} }
} } else {
else {
int *tempArray = new int[end-start+1]; int *tempArray = new int[end-start+1];
for (i=0; i<(end-start+1); i++) tempArray[i]=1; for (i=0; i<(end-start+1); i++) tempArray[i]=1;
if(bad) { if(bad) {
for(i=0;i<countBad;i++) { for(i=0; i<countBad; i++) {
tempArray[bad[i]]=0; tempArray[bad[i]]=0;
} }
} }
@@ -69,8 +68,7 @@ void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool
int counter(0); int counter(0);
while (counter < howMany) { while (counter < howMany) {
if(!RAND_bytes(rand_buf, 4)) if(!RAND_bytes(rand_buf, 4)) {
{
LOG_MSG("RAND_bytes failed!"); LOG_MSG("RAND_bytes failed!");
} }
+2 -1
View File
@@ -20,7 +20,8 @@
#ifndef TOOLS_H #ifndef TOOLS_H
#define TOOLS_H #define TOOLS_H
class Tools{ class Tools
{
public: public:
static void getRandNumber(int, int, int, int*, bool, int* = 0, int = 0); static void getRandNumber(int, int, int, int*, bool, int* = 0, int = 0);
+175 -173
View File
@@ -32,238 +32,240 @@ using namespace std;
Log::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false) Log::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false)
{ {
if(SQLITE_LOG) { if(SQLITE_LOG) {
// logging activated // logging activated
if(logOnOffInt) { if(logOnOffInt) {
logOnOff = true; logOnOff = true;
DIR *logDir; DIR *logDir;
logDir = opendir(logDirString.c_str()); logDir = opendir(logDirString.c_str());
bool dirExists = logDir != NULL; bool dirExists = logDir != NULL;
closedir(logDir); closedir(logDir);
// check if logging path exist // check if logging path exist
if(logDirString != "" && dirExists) { if(logDirString != "" && dirExists) {
string sql; string sql;
char *errmsg; char *errmsg;
// detect current time // detect current time
char curDateTime[20]; char curDateTime[20];
char curDate[11]; char curDate[11];
char curTime[9]; char curTime[9];
time_t now = time(NULL); time_t now = time(NULL);
tm *z = localtime(&now); tm *z = localtime(&now);
strftime(curDateTime,20,"%Y-%m-%d_%H.%M.%S",z); strftime(curDateTime,20,"%Y-%m-%d_%H.%M.%S",z);
strftime(curDate,11,"%Y-%m-%d",z); strftime(curDate,11,"%Y-%m-%d",z);
strftime(curTime,9,"%H:%M:%S",z); strftime(curTime,9,"%H:%M:%S",z);
string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str()); string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str());
mySqliteLogFileName += "pokerth-log-" + boost::lexical_cast<string>(curDateTime) + ".pdb"; mySqliteLogFileName += "pokerth-log-" + boost::lexical_cast<string>(curDateTime) + ".pdb";
// open sqlite-db // open sqlite-db
sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb); sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb);
if( mySqliteLogDb != 0 ) { if( mySqliteLogDb != 0 ) {
int i; int i;
// create session table // create session table
sql = "CREATE TABLE Session ("; sql = "CREATE TABLE Session (";
sql += "PokerTH_Version TEXT NOT NULL"; sql += "PokerTH_Version TEXT NOT NULL";
sql += ",Date TEXT NOT NULL"; sql += ",Date TEXT NOT NULL";
sql += ",Time TEXT NOT NULL"; sql += ",Time TEXT NOT NULL";
sql += ", PRIMARY KEY(Date,Time))"; sql += ", PRIMARY KEY(Date,Time))";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
sqlite3_free(errmsg); sqlite3_free(errmsg);
} }
sql = "INSERT INTO Session ("; sql = "INSERT INTO Session (";
sql += "PokerTH_Version"; sql += "PokerTH_Version";
sql += ",Date"; sql += ",Date";
sql += ",Time"; sql += ",Time";
sql += ") VALUES ("; sql += ") VALUES (";
sql += "\"" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + "\","; sql += "\"" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + "\",";
sql += "\"" + boost::lexical_cast<string>(curDate) + "\","; sql += "\"" + boost::lexical_cast<string>(curDate) + "\",";
sql += "\"" + boost::lexical_cast<string>(curTime) + "\")"; sql += "\"" + boost::lexical_cast<string>(curTime) + "\")";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
sqlite3_free(errmsg); sqlite3_free(errmsg);
} }
// create game table // create game table
sql = "CREATE TABLE Game ("; sql = "CREATE TABLE Game (";
sql += "GameID INTEGER NOT NULL PRIMARY KEY"; sql += "GameID INTEGER NOT NULL PRIMARY KEY";
sql += ",Startmoney INTEGER NOT NULL"; sql += ",Startmoney INTEGER NOT NULL";
sql += ",StartSb INTEGER NOT NULL"; sql += ",StartSb INTEGER NOT NULL";
sql += ",DealerPos INTEGER NOT NULL"; sql += ",DealerPos INTEGER NOT NULL";
for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) { for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + " TEXT"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + " TEXT";
} }
sql += ",Winner_Seat INTEGER"; sql += ",Winner_Seat INTEGER";
sql += ")"; sql += ")";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
sqlite3_free(errmsg); sqlite3_free(errmsg);
} }
// create hand table // create hand table
sql = "CREATE TABLE Hand ("; sql = "CREATE TABLE Hand (";
sql += "HandID INTEGER NOT NULL"; sql += "HandID INTEGER NOT NULL";
sql += ",GameID INTEGER NOT NULL"; sql += ",GameID INTEGER NOT NULL";
sql += ",Dealer_Seat INTEGER"; sql += ",Dealer_Seat INTEGER";
sql += ",Sb_Amount INTEGER NOT NULL"; sql += ",Sb_Amount INTEGER NOT NULL";
sql += ",Sb_Seat INTEGER NOT NULL"; sql += ",Sb_Seat INTEGER NOT NULL";
sql += ",Bb_Amount INTEGER NOT NULL"; sql += ",Bb_Amount INTEGER NOT NULL";
sql += ",Bb_Seat INTEGER NOT NULL"; sql += ",Bb_Seat INTEGER NOT NULL";
for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) { for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash INTEGER"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash INTEGER";
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_1 INTEGER"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_1 INTEGER";
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_2 INTEGER"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_2 INTEGER";
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_text TEXT"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_text TEXT";
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_int INTEGER"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_int INTEGER";
} }
for(i=1; i<=5; i++) { for(i=1; i<=5; i++) {
sql += ",BoardCard_" + boost::lexical_cast<std::string>(i) + " INTEGER"; sql += ",BoardCard_" + boost::lexical_cast<std::string>(i) + " INTEGER";
} }
sql += ",PRIMARY KEY(HandID,GameID))"; sql += ",PRIMARY KEY(HandID,GameID))";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
sqlite3_free(errmsg); sqlite3_free(errmsg);
} }
// create action table // create action table
sql = "CREATE TABLE Action ("; sql = "CREATE TABLE Action (";
sql += "ActionID INTEGER PRIMARY KEY AUTOINCREMENT"; sql += "ActionID INTEGER PRIMARY KEY AUTOINCREMENT";
sql += ",HandID INTEGER NOT NULL"; sql += ",HandID INTEGER NOT NULL";
sql += ",GameID INTEGER NOT NULL"; sql += ",GameID INTEGER NOT NULL";
sql += ",BeRo INTEGER NOT NULL"; sql += ",BeRo INTEGER NOT NULL";
sql += ",Player INTEGER NOT NULL"; sql += ",Player INTEGER NOT NULL";
sql += ",Action TEXT NOT NULL"; sql += ",Action TEXT NOT NULL";
sql += ",Amount INTEGER"; sql += ",Amount INTEGER";
sql += ")"; sql += ")";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
sqlite3_free(errmsg); sqlite3_free(errmsg);
} }
} }
} }
} }
} }
} }
Log::~Log() Log::~Log()
{ {
if(SQLITE_LOG) { if(SQLITE_LOG) {
sqlite3_close(mySqliteLogDb); sqlite3_close(mySqliteLogDb);
} }
} }
void void
Log::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList) { Log::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList)
{
curGameID = gameID; curGameID = gameID;
if(SQLITE_LOG) { if(SQLITE_LOG) {
if(logOnOff) { if(logOnOff) {
//if write logfiles is enabled //if write logfiles is enabled
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
string sql; string sql;
char *errmsg; char *errmsg;
if( mySqliteLogDb != 0 ) { if( mySqliteLogDb != 0 ) {
// sqlite-db is open // sqlite-db is open
int i; int i;
sql = "INSERT INTO Game ("; sql = "INSERT INTO Game (";
sql += "GameID"; sql += "GameID";
sql += ",Startmoney"; sql += ",Startmoney";
sql += ",StartSb"; sql += ",StartSb";
sql += ",DealerPos"; sql += ",DealerPos";
for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) { for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
sql += ",Seat_" + boost::lexical_cast<std::string>(i); sql += ",Seat_" + boost::lexical_cast<std::string>(i);
} }
sql += ") VALUES ("; sql += ") VALUES (";
sql += boost::lexical_cast<string>(curGameID); sql += boost::lexical_cast<string>(curGameID);
sql += "," + boost::lexical_cast<string>(startCash); sql += "," + boost::lexical_cast<string>(startCash);
sql += "," + boost::lexical_cast<string>(startSmallBlind); sql += "," + boost::lexical_cast<string>(startSmallBlind);
sql += "," + boost::lexical_cast<string>(dealerPosition); sql += "," + boost::lexical_cast<string>(dealerPosition);
for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) { for(it_c = seatsList->begin(); it_c!=seatsList->end(); it_c++) {
if((*it_c)->getMyActiveStatus()) { if((*it_c)->getMyActiveStatus()) {
sql += ",\"" + (*it_c)->getMyName() +"\""; sql += ",\"" + (*it_c)->getMyName() +"\"";
} else { } else {
sql += ",NULL"; sql += ",NULL";
} }
} }
sql += ")"; sql += ")";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
} }
} }
} }
} }
} }
void void
Log::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList) { Log::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList)
{
if(SQLITE_LOG) { if(SQLITE_LOG) {
if(logOnOff) { if(logOnOff) {
//if write logfiles is enabled //if write logfiles is enabled
PlayerListConstIterator it_c; PlayerListConstIterator it_c;
string sql; string sql;
char *errmsg; char *errmsg;
if( mySqliteLogDb != 0 ) { if( mySqliteLogDb != 0 ) {
// sqlite-db is open // sqlite-db is open
int i; int i;
sql = "INSERT INTO Hand ("; sql = "INSERT INTO Hand (";
sql += "HandID"; sql += "HandID";
sql += ",GameID"; sql += ",GameID";
sql += ",Dealer_Seat"; sql += ",Dealer_Seat";
sql += ",Sb_Amount"; sql += ",Sb_Amount";
sql += ",Sb_Seat"; sql += ",Sb_Seat";
sql += ",Bb_Amount"; sql += ",Bb_Amount";
sql += ",Bb_Seat"; sql += ",Bb_Seat";
for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) { for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash"; sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash";
} }
sql += ") VALUES ("; sql += ") VALUES (";
sql += boost::lexical_cast<string>(handID); sql += boost::lexical_cast<string>(handID);
sql += "," + boost::lexical_cast<string>(curGameID); sql += "," + boost::lexical_cast<string>(curGameID);
sql += "," + boost::lexical_cast<string>(dealerPosition+1); sql += "," + boost::lexical_cast<string>(dealerPosition+1);
sql += "," + boost::lexical_cast<string>(smallBlind); sql += "," + boost::lexical_cast<string>(smallBlind);
sql += "," + boost::lexical_cast<string>(smallBlindPosition+1); sql += "," + boost::lexical_cast<string>(smallBlindPosition+1);
sql += "," + boost::lexical_cast<string>(bigBlind); sql += "," + boost::lexical_cast<string>(bigBlind);
sql += "," + boost::lexical_cast<string>(bigBlindPosition+1); sql += "," + boost::lexical_cast<string>(bigBlindPosition+1);
for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) { for(it_c = seatsList->begin(); it_c!=seatsList->end(); it_c++) {
if((*it_c)->getMyActiveStatus()) { if((*it_c)->getMyActiveStatus()) {
sql += "," + boost::lexical_cast<string>((*it_c)->getMyCash()); sql += "," + boost::lexical_cast<string>((*it_c)->getMyCash());
} else { } else {
sql += ",NULL"; sql += ",NULL";
} }
} }
sql += ")"; sql += ")";
if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) { if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl; cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
} }
} }
} }
} }
} }
//void //void
+7 -7
View File
@@ -28,19 +28,19 @@ class Log
{ {
public: public:
Log(std::string logDirString, int logOnOffInt); Log(std::string logDirString, int logOnOffInt);
~Log(); ~Log();
void logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList); void logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList);
void logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList); void logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList);
// void closeLogDbAtExit(); // void closeLogDbAtExit();
private: private:
sqlite3 *mySqliteLogDb; sqlite3 *mySqliteLogDb;
int curGameID; int curGameID;
bool logOnOff; bool logOnOff;
}; };
+3 -3
View File
@@ -20,9 +20,9 @@
#include "clientbero.h" #include "clientbero.h"
ClientBeRo::ClientBeRo(HandInterface* hi, int /*id*/, unsigned /*dP*/, int sB, GameState gS) ClientBeRo::ClientBeRo(HandInterface* hi, int /*id*/, unsigned /*dP*/, int sB, GameState gS)
: BeRoInterface(), myBeRoID(gS), myHand(hi), highestCardsValue(0), smallBlindPositionId(0), bigBlindPositionId(0), currentPlayersTurnId(0), : BeRoInterface(), myBeRoID(gS), myHand(hi), highestCardsValue(0), smallBlindPositionId(0), bigBlindPositionId(0), currentPlayersTurnId(0),
firstRoundLastPlayersTurnId(0), highestSet(0), firstRound(true), smallBlindPosition(0), smallBlind(sB), minimumRaise(2*sB), fullBetRule(false), firstRoundLastPlayersTurnId(0), highestSet(0), firstRound(true), smallBlindPosition(0), smallBlind(sB), minimumRaise(2*sB), fullBetRule(false),
lastActionPlayer(0) lastActionPlayer(0)
{ {
} }
+4 -3
View File
@@ -28,7 +28,8 @@ class HandInterface;
/** /**
@author FThauer FHammer <webmaster@pokerth.net> @author FThauer FHammer <webmaster@pokerth.net>
*/ */
class ClientBeRo : public BeRoInterface{ class ClientBeRo : public BeRoInterface
{
public: public:
ClientBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS); ClientBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS);
~ClientBeRo(); ~ClientBeRo();
@@ -38,8 +39,8 @@ public:
int getHighestCardsValue() const; int getHighestCardsValue() const;
void setHighestCardsValue(int theValue); void setHighestCardsValue(int theValue);
void setLastActionPlayer ( unsigned theValue ); void setLastActionPlayer ( unsigned theValue );
unsigned getLastActionPlayer() const; unsigned getLastActionPlayer() const;
void setSmallBlindPositionId(unsigned theValue); void setSmallBlindPositionId(unsigned theValue);
unsigned getSmallBlindPositionId() const; unsigned getSmallBlindPositionId() const;
+5 -5
View File
@@ -24,7 +24,7 @@
using namespace std; using namespace std;
ClientBoard::ClientBoard(unsigned dp) ClientBoard::ClientBoard(unsigned dp)
: pot(0), sets(0), dealerPosition(dp), allInCondition(false), lastActionPlayer(0) : pot(0), sets(0), dealerPosition(dp), allInCondition(false), lastActionPlayer(0)
{ {
myCards[0] = myCards[1] = myCards[2] = myCards[3] = myCards[4] = 0; myCards[0] = myCards[1] = myCards[2] = myCards[3] = myCards[4] = 0;
} }
@@ -90,15 +90,15 @@ ClientBoard::setSets(int theValue)
void void
ClientBoard::setAllInCondition(bool theValue) ClientBoard::setAllInCondition(bool theValue)
{ {
boost::recursive_mutex::scoped_lock lock(m_syncMutex); boost::recursive_mutex::scoped_lock lock(m_syncMutex);
allInCondition = theValue; allInCondition = theValue;
} }
void void
ClientBoard::setLastActionPlayer(unsigned theValue) ClientBoard::setLastActionPlayer(unsigned theValue)
{ {
boost::recursive_mutex::scoped_lock lock(m_syncMutex); boost::recursive_mutex::scoped_lock lock(m_syncMutex);
lastActionPlayer = theValue; lastActionPlayer = theValue;
} }
void void
+6 -6
View File
@@ -31,7 +31,7 @@ class HandInterface;
class ClientBoard : public BoardInterface class ClientBoard : public BoardInterface
{ {
public: public:
ClientBoard(unsigned dealerPosition); ClientBoard(unsigned dealerPosition);
~ClientBoard(); ~ClientBoard();
void setPlayerLists(PlayerList, PlayerList, PlayerList); void setPlayerLists(PlayerList, PlayerList, PlayerList);
@@ -44,8 +44,8 @@ public:
int getSets() const; int getSets() const;
void setSets(int theValue); void setSets(int theValue);
void setAllInCondition(bool theValue); void setAllInCondition(bool theValue);
void setLastActionPlayer(unsigned theValue); void setLastActionPlayer(unsigned theValue);
void collectSets(); void collectSets();
void collectPot(); void collectPot();
@@ -72,9 +72,9 @@ private:
int myCards[5]; int myCards[5];
int pot; int pot;
int sets; int sets;
unsigned dealerPosition; unsigned dealerPosition;
bool allInCondition; bool allInCondition;
unsigned lastActionPlayer; unsigned lastActionPlayer;
}; };
#endif #endif
+4 -4
View File
@@ -22,15 +22,15 @@
using namespace std; using namespace std;
ClientHand::ClientHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost::shared_ptr<BoardInterface> b, Log *l, PlayerList sl, PlayerList apl, PlayerList rpl, int id, int sP, int dP, int sB,int sC) ClientHand::ClientHand(boost::shared_ptr<EngineFactory> f, GuiInterface *g, boost::shared_ptr<BoardInterface> b, Log *l, PlayerList sl, PlayerList apl, PlayerList rpl, int id, int sP, int dP, int sB,int sC)
: myFactory(f), myGui(g), myBoard(b), myLog(l), seatsList(sl), activePlayerList(apl), runningPlayerList(rpl), myID(id), startQuantityPlayers(sP), dealerPosition(dP), currentRound(0), : myFactory(f), myGui(g), myBoard(b), myLog(l), seatsList(sl), activePlayerList(apl), runningPlayerList(rpl), myID(id), startQuantityPlayers(sP), dealerPosition(dP), currentRound(0),
smallBlind(sB), startCash(sC), lastPlayersTurn(-1), allInCondition(0), smallBlind(sB), startCash(sC), lastPlayersTurn(-1), allInCondition(0),
cardsShown(false), bettingRoundsPlayed(0) cardsShown(false), bettingRoundsPlayed(0)
{ {
PlayerListIterator it; PlayerListIterator it;
for(it=seatsList->begin(); it!=seatsList->end(); ++it) { for(it=seatsList->begin(); it!=seatsList->end(); ++it) {
(*it)->setHand(this); (*it)->setHand(this);
// myFlipCards auf 0 setzen // myFlipCards auf 0 setzen
(*it)->setMyCardsFlip(0, 0); (*it)->setMyCardsFlip(0, 0);
} }
+63 -63
View File
@@ -32,97 +32,97 @@
class ClientHand : public HandInterface class ClientHand : public HandInterface
{ {
public: public:
ClientHand ( boost::shared_ptr<EngineFactory> f, GuiInterface*, boost::shared_ptr<BoardInterface>, Log*, PlayerList, PlayerList, PlayerList , int, int, int, int, int ); ClientHand ( boost::shared_ptr<EngineFactory> f, GuiInterface*, boost::shared_ptr<BoardInterface>, Log*, PlayerList, PlayerList, PlayerList , int, int, int, int, int );
~ClientHand(); ~ClientHand();
void start(); void start();
PlayerList getSeatsList() const; PlayerList getSeatsList() const;
PlayerList getActivePlayerList() const; PlayerList getActivePlayerList() const;
PlayerList getRunningPlayerList() const; PlayerList getRunningPlayerList() const;
boost::shared_ptr<BoardInterface> getBoard() const; boost::shared_ptr<BoardInterface> getBoard() const;
boost::shared_ptr<BeRoInterface> getPreflop() const; boost::shared_ptr<BeRoInterface> getPreflop() const;
boost::shared_ptr<BeRoInterface> getFlop() const; boost::shared_ptr<BeRoInterface> getFlop() const;
boost::shared_ptr<BeRoInterface> getTurn() const; boost::shared_ptr<BeRoInterface> getTurn() const;
boost::shared_ptr<BeRoInterface> getRiver() const; boost::shared_ptr<BeRoInterface> getRiver() const;
GuiInterface* getGuiInterface() const; GuiInterface* getGuiInterface() const;
boost::shared_ptr<BeRoInterface> getCurrentBeRo() const; boost::shared_ptr<BeRoInterface> getCurrentBeRo() const;
void setMyID ( int theValue ); void setMyID ( int theValue );
int getMyID() const; int getMyID() const;
void setCurrentQuantityPlayers ( int theValue ); void setCurrentQuantityPlayers ( int theValue );
int getCurrentQuantityPlayers() const; int getCurrentQuantityPlayers() const;
void setStartQuantityPlayers ( int theValue ); void setStartQuantityPlayers ( int theValue );
int getStartQuantityPlayers() const; int getStartQuantityPlayers() const;
void setCurrentRound ( int theValue ); void setCurrentRound ( int theValue );
int getCurrentRound() const; int getCurrentRound() const;
void setDealerPosition ( int theValue ); void setDealerPosition ( int theValue );
int getDealerPosition() const; int getDealerPosition() const;
void setSmallBlind ( int theValue ); void setSmallBlind ( int theValue );
int getSmallBlind() const; int getSmallBlind() const;
void setAllInCondition ( bool theValue ); void setAllInCondition ( bool theValue );
bool getAllInCondition() const; bool getAllInCondition() const;
void setStartCash ( int theValue ); void setStartCash ( int theValue );
int getStartCash() const; int getStartCash() const;
void setBettingRoundsPlayed ( int theValue ); void setBettingRoundsPlayed ( int theValue );
int getBettingRoundsPlayed() const; int getBettingRoundsPlayed() const;
void setLastPlayersTurn ( int theValue ); void setLastPlayersTurn ( int theValue );
int getLastPlayersTurn() const; int getLastPlayersTurn() const;
void setLastActionPlayer ( unsigned theValue ); void setLastActionPlayer ( unsigned theValue );
unsigned getLastActionPlayer() const; unsigned getLastActionPlayer() const;
void setCardsShown ( bool theValue ); void setCardsShown ( bool theValue );
bool getCardsShown() const; bool getCardsShown() const;
void switchRounds(); void switchRounds();
protected: protected:
PlayerListIterator getSeatIt(unsigned) const; PlayerListIterator getSeatIt(unsigned) const;
PlayerListIterator getActivePlayerIt(unsigned) const; PlayerListIterator getActivePlayerIt(unsigned) const;
PlayerListIterator getRunningPlayerIt(unsigned) const; PlayerListIterator getRunningPlayerIt(unsigned) const;
private: private:
mutable boost::recursive_mutex m_syncMutex; mutable boost::recursive_mutex m_syncMutex;
boost::shared_ptr<EngineFactory> myFactory; boost::shared_ptr<EngineFactory> myFactory;
GuiInterface *myGui; GuiInterface *myGui;
boost::shared_ptr<BoardInterface> myBoard; boost::shared_ptr<BoardInterface> myBoard;
Log *myLog; Log *myLog;
PlayerList seatsList; PlayerList seatsList;
PlayerList activePlayerList; PlayerList activePlayerList;
PlayerList runningPlayerList; PlayerList runningPlayerList;
std::vector<boost::shared_ptr<BeRoInterface> > myBeRo; std::vector<boost::shared_ptr<BeRoInterface> > myBeRo;
int myID; int myID;
int startQuantityPlayers; int startQuantityPlayers;
unsigned dealerPosition; unsigned dealerPosition;
int currentRound; //0 = preflop, 1 = flop, 2 = turn, 3 = river int currentRound; //0 = preflop, 1 = flop, 2 = turn, 3 = river
int smallBlind; int smallBlind;
int startCash; int startCash;
int lastPlayersTurn; int lastPlayersTurn;
unsigned lastActionPlayer; unsigned lastActionPlayer;
bool allInCondition; bool allInCondition;
bool cardsShown; bool cardsShown;
// hier steht bis zu welcher bettingRound der human player gespielt hat: 0 - nur Preflop, 1 - bis Flop, ... // hier steht bis zu welcher bettingRound der human player gespielt hat: 0 - nur Preflop, 1 - bis Flop, ...
int bettingRoundsPlayed; int bettingRoundsPlayed;
}; };
#endif #endif
+18 -17
View File
@@ -23,10 +23,10 @@ using namespace std;
ClientPlayer::ClientPlayer(ConfigFile *c, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB) ClientPlayer::ClientPlayer(ConfigFile *c, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB)
: PlayerInterface(), myConfig(c), currentHand(0), myCardsValue(0), myID(id), myUniqueID(uniqueId), myType(type), : PlayerInterface(), myConfig(c), currentHand(0), myCardsValue(0), myID(id), myUniqueID(uniqueId), myType(type),
myName(name), myAvatar(avatar), myDude(0), myDude4(0), myCardsValueInt(0), myOdds(-1.0), myCash(sC), mySet(0), myLastRelativeSet(0), myName(name), myAvatar(avatar), myDude(0), myDude4(0), myCardsValueInt(0), myOdds(-1.0), myCash(sC), mySet(0), myLastRelativeSet(0),
myAction(0), myButton(mB), myActiveStatus(aS), myStayOnTableStatus(true), myTurn(false), myCardsFlip(false), myRoundStartCash(0), myAction(0), myButton(mB), myActiveStatus(aS), myStayOnTableStatus(true), myTurn(false), myCardsFlip(false), myRoundStartCash(0),
lastMoneyWon(0), sBluff(0), sBluffStatus(false), myWinnerState(false) lastMoneyWon(0), sBluff(0), sBluffStatus(false), myWinnerState(false)
{ {
myBestHandPosition[0] = myBestHandPosition[1] = myBestHandPosition[2] = myBestHandPosition[3] = myBestHandPosition[4] = 0; myBestHandPosition[0] = myBestHandPosition[1] = myBestHandPosition[2] = myBestHandPosition[3] = myBestHandPosition[4] = 0;
myNiveau[0] = myNiveau[1] = myNiveau[2] = 0; myNiveau[0] = myNiveau[1] = myNiveau[2] = 0;
@@ -266,13 +266,17 @@ ClientPlayer::setMyCardsFlip(bool theValue, int state)
// log flipping cards // log flipping cards
if (myCardsFlip) { if (myCardsFlip) {
switch(state) { switch(state) {
case 1: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt); case 1:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt);
break; break;
case 2: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1]); case 2:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1]);
break; break;
case 3: currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt, "has"); case 3:
currentHand->getGuiInterface()->logFlipHoleCardsMsg(myName, myID, myCards[0], myCards[1], myCardsValueInt, "has");
break; break;
default: ; default:
;
} }
} }
} }
@@ -363,8 +367,7 @@ void
ClientPlayer::setMyAggressive(bool theValue) ClientPlayer::setMyAggressive(bool theValue)
{ {
boost::recursive_mutex::scoped_lock lock(m_syncMutex); boost::recursive_mutex::scoped_lock lock(m_syncMutex);
for (int i=0; i<6; i++) for (int i=0; i<6; i++) {
{
myAggressive[i] = myAggressive[i+1]; myAggressive[i] = myAggressive[i+1];
} }
myAggressive[6] = theValue; myAggressive[6] = theValue;
@@ -375,8 +378,7 @@ ClientPlayer::getMyAggressive() const
{ {
boost::recursive_mutex::scoped_lock lock(m_syncMutex); boost::recursive_mutex::scoped_lock lock(m_syncMutex);
int sum = 0; int sum = 0;
for (int i=0; i<7; i++) for (int i=0; i<7; i++) {
{
sum += myAggressive[i]; sum += myAggressive[i];
} }
return sum; return sum;
@@ -527,10 +529,9 @@ bool ClientPlayer::checkIfINeedToShowCards()
{ {
boost::recursive_mutex::scoped_lock lock(m_syncMutex); boost::recursive_mutex::scoped_lock lock(m_syncMutex);
std::list<unsigned> playerNeedToShowCardsList = currentHand->getBoard()->getPlayerNeedToShowCards(); std::list<unsigned> playerNeedToShowCardsList = currentHand->getBoard()->getPlayerNeedToShowCards();
for(std::list<unsigned>::iterator it = playerNeedToShowCardsList.begin(); it != playerNeedToShowCardsList.end(); ++it) for(std::list<unsigned>::iterator it = playerNeedToShowCardsList.begin(); it != playerNeedToShowCardsList.end(); ++it) {
{ if(*it == myUniqueID) return true;
if(*it == myUniqueID) return true; }
}
return false; return false;
} }
+6 -3
View File
@@ -29,7 +29,8 @@ class CardsValue;
class ConfigFile; class ConfigFile;
class HandInterface; class HandInterface;
class ClientPlayer : public PlayerInterface{ class ClientPlayer : public PlayerInterface
{
public: public:
ClientPlayer(ConfigFile*, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB); ClientPlayer(ConfigFile*, int id, unsigned uniqueId, PlayerType type, std::string name, std::string avatar, int sC, bool aS, int mB);
~ClientPlayer(); ~ClientPlayer();
@@ -134,7 +135,9 @@ public:
boost::shared_ptr<SessionData> getNetSessionData(); boost::shared_ptr<SessionData> getNetSessionData();
// unused as client // unused as client
unsigned getActionTimeoutCounter() const {return 0;} unsigned getActionTimeoutCounter() const {
return 0;
}
void incrementActionTimeoutCounter() {} void incrementActionTimeoutCounter() {}
void resetActionTimeoutCounter() {} void resetActionTimeoutCounter() {}
@@ -171,7 +174,7 @@ private:
int myAction; // 0 = none, 1 = fold, 2 = check, 3 = call, 4 = bet, 5 = raise, 6 = allin int myAction; // 0 = none, 1 = fold, 2 = check, 3 = call, 4 = bet, 5 = raise, 6 = allin
int myButton; // 0 = none, 1 = dealer, 2 =small, 3 = big int myButton; // 0 = none, 1 = dealer, 2 =small, 3 = big
bool myActiveStatus; // 0 = inactive, 1 = active bool myActiveStatus; // 0 = inactive, 1 = active
bool myStayOnTableStatus; // 0 = left, 1 = stay bool myStayOnTableStatus; // 0 = left, 1 = stay
bool myTurn; // 0 = no, 1 = yes bool myTurn; // 0 = no, 1 = yes
bool myCardsFlip; // 0 = cards are not fliped, 1 = cards are already flipped, bool myCardsFlip; // 0 = cards are not fliped, 1 = cards are already flipped,
int myRoundStartCash; int myRoundStartCash;
+4 -3
View File
@@ -25,7 +25,8 @@
class SessionData; class SessionData;
class PlayerInterface{ class PlayerInterface
{
public: public:
virtual ~PlayerInterface() =0; virtual ~PlayerInterface() =0;
@@ -66,8 +67,8 @@ public:
virtual void setMyActiveStatus(bool theValue) =0; virtual void setMyActiveStatus(bool theValue) =0;
virtual bool getMyActiveStatus() const =0; virtual bool getMyActiveStatus() const =0;
virtual void setMyStayOnTableStatus(bool theValue) =0; virtual void setMyStayOnTableStatus(bool theValue) =0;
virtual bool getMyStayOnTableStatus() const =0; virtual bool getMyStayOnTableStatus() const =0;
virtual void setMyCards(int* theValue) =0; virtual void setMyCards(int* theValue) =0;
virtual void getMyCards(int* theValue) const =0; virtual void getMyCards(int* theValue) const =0;
+21 -28
View File
@@ -32,12 +32,12 @@ using namespace std;
Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory, Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
const PlayerDataList &playerDataList, const GameData &gameData, const PlayerDataList &playerDataList, const GameData &gameData,
const StartData &startData, int gameId, Log* log) const StartData &startData, int gameId, Log* log)
: myFactory(factory), myGui(gui), myLog(log), startQuantityPlayers(startData.numberOfPlayers), : myFactory(factory), myGui(gui), myLog(log), startQuantityPlayers(startData.numberOfPlayers),
startCash(gameData.startMoney), startSmallBlind(gameData.firstSmallBlind), startCash(gameData.startMoney), startSmallBlind(gameData.firstSmallBlind),
myGameID(gameId), currentSmallBlind(gameData.firstSmallBlind), currentHandID(0), dealerPosition(0), myGameID(gameId), currentSmallBlind(gameData.firstSmallBlind), currentHandID(0), dealerPosition(0),
lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData), lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData),
blindsTimer(boost::posix_time::time_duration(0, 0, 0), boost::timers::portable::second_timer::manual_start) blindsTimer(boost::posix_time::time_duration(0, 0, 0), boost::timers::portable::second_timer::manual_start)
{ {
blindsList = myGameData.manualBlindsList; blindsList = myGameData.manualBlindsList;
@@ -56,8 +56,7 @@ Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
PlayerDataList::const_iterator player_i = playerDataList.begin(); PlayerDataList::const_iterator player_i = playerDataList.begin();
PlayerDataList::const_iterator player_end = playerDataList.end(); PlayerDataList::const_iterator player_end = playerDataList.end();
while (player_i != player_end) while (player_i != player_end) {
{
if ((*player_i)->GetUniqueId() == dealerPosition) if ((*player_i)->GetUniqueId() == dealerPosition)
break; break;
++player_i; ++player_i;
@@ -66,7 +65,7 @@ Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
throw LocalException(__FILE__, __LINE__, ERR_DEALER_NOT_FOUND); throw LocalException(__FILE__, __LINE__, ERR_DEALER_NOT_FOUND);
// create board // create board
currentBoard = myFactory->createBoard(dealerPosition); currentBoard = myFactory->createBoard(dealerPosition);
// create player lists // create player lists
seatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >); seatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);
@@ -84,8 +83,7 @@ Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
PlayerType type = PLAYER_TYPE_COMPUTER; PlayerType type = PLAYER_TYPE_COMPUTER;
boost::shared_ptr<SessionData> myNetSession; boost::shared_ptr<SessionData> myNetSession;
if (player_i != player_end) if (player_i != player_end) {
{
uniqueId = (*player_i)->GetUniqueId(); uniqueId = (*player_i)->GetUniqueId();
type = (*player_i)->GetType(); type = (*player_i)->GetType();
myName = (*player_i)->GetName(); myName = (*player_i)->GetName();
@@ -110,8 +108,8 @@ Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
currentBoard->setPlayerLists(seatsList, activePlayerList, runningPlayerList); currentBoard->setPlayerLists(seatsList, activePlayerList, runningPlayerList);
// log game data // log game data
myLog->logNewGameMsg(myGameID, startCash, startSmallBlind, dealerPosition, seatsList); myLog->logNewGameMsg(myGameID, startCash, startSmallBlind, dealerPosition, seatsList);
//start timer //start timer
blindsTimer.reset(); blindsTimer.reset();
@@ -154,7 +152,7 @@ void Game::initHand()
while( it!=activePlayerList->end() ) { while( it!=activePlayerList->end() ) {
if((*it)->getMyCash() == 0) { if((*it)->getMyCash() == 0) {
(*it)->setMyActiveStatus(false); (*it)->setMyActiveStatus(false);
it = activePlayerList->erase(it); it = activePlayerList->erase(it);
} else { } else {
++it; ++it;
@@ -165,7 +163,7 @@ void Game::initHand()
(*runningPlayerList) = (*activePlayerList); (*runningPlayerList) = (*activePlayerList);
// create Hand // create Hand
currentHand = myFactory->createHand(myFactory, myGui, currentBoard, myLog, seatsList, activePlayerList, runningPlayerList, currentHandID, startQuantityPlayers, dealerPosition, currentSmallBlind, startCash); currentHand = myFactory->createHand(myFactory, myGui, currentBoard, myLog, seatsList, activePlayerList, runningPlayerList, currentHandID, startQuantityPlayers, dealerPosition, currentSmallBlind, startCash);
// shifting dealer button -> TODO exception-rule !!! // shifting dealer button -> TODO exception-rule !!!
bool nextDealerFound = false; bool nextDealerFound = false;
@@ -207,10 +205,8 @@ boost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id)
boost::shared_ptr<PlayerInterface> tmpPlayer; boost::shared_ptr<PlayerInterface> tmpPlayer;
PlayerListIterator i = getSeatsList()->begin(); PlayerListIterator i = getSeatsList()->begin();
PlayerListIterator end = getSeatsList()->end(); PlayerListIterator end = getSeatsList()->end();
while (i != end) while (i != end) {
{ if ((*i)->getMyUniqueID() == id) {
if ((*i)->getMyUniqueID() == id)
{
tmpPlayer = *i; tmpPlayer = *i;
break; break;
} }
@@ -227,7 +223,8 @@ boost::shared_ptr<PlayerInterface> Game::getCurrentPlayer()
return tmpPlayer; return tmpPlayer;
} }
void Game::raiseBlinds() { void Game::raiseBlinds()
{
bool raiseBlinds = false; bool raiseBlinds = false;
@@ -236,8 +233,7 @@ void Game::raiseBlinds() {
raiseBlinds = true; raiseBlinds = true;
lastHandBlindsRaised = currentHandID; lastHandBlindsRaised = currentHandID;
} }
} } else {
else {
if (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()/60) { if (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()/60) {
raiseBlinds = true; raiseBlinds = true;
lastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()/60; lastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()/60;
@@ -248,18 +244,15 @@ void Game::raiseBlinds() {
// Now we check how the blinds should be raised // Now we check how the blinds should be raised
if (myGameData.raiseMode == DOUBLE_BLINDS) { if (myGameData.raiseMode == DOUBLE_BLINDS) {
currentSmallBlind *= 2; currentSmallBlind *= 2;
} } else {
else {
if(!blindsList.empty()) { if(!blindsList.empty()) {
currentSmallBlind = blindsList.front(); currentSmallBlind = blindsList.front();
blindsList.pop_front(); blindsList.pop_front();
} } else {
else {
// The position exceeds the list // The position exceeds the list
if (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) { if (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) {
currentSmallBlind *= 2; currentSmallBlind *= 2;
} } else {
else {
if(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) { if(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) {
currentSmallBlind += myGameData.afterMBAlwaysRaiseValue; currentSmallBlind += myGameData.afterMBAlwaysRaiseValue;
} }
+51 -20
View File
@@ -35,12 +35,13 @@ struct GameData;
struct StartData; struct StartData;
class Game { class Game
{
public: public:
Game(GuiInterface *gui, boost::shared_ptr<EngineFactory> factory, Game(GuiInterface *gui, boost::shared_ptr<EngineFactory> factory,
const PlayerDataList &playerDataList, const GameData &gameData, const PlayerDataList &playerDataList, const GameData &gameData,
const StartData &startData, int gameId, Log *myLog); const StartData &startData, int gameId, Log *myLog);
~Game(); ~Game();
@@ -50,28 +51,58 @@ public:
boost::shared_ptr<HandInterface> getCurrentHand(); boost::shared_ptr<HandInterface> getCurrentHand();
const boost::shared_ptr<HandInterface> getCurrentHand() const; const boost::shared_ptr<HandInterface> getCurrentHand() const;
PlayerList getSeatsList() const {return seatsList;} PlayerList getSeatsList() const {
PlayerList getActivePlayerList() const {return activePlayerList;} return seatsList;
PlayerList getRunningPlayerList() const {return runningPlayerList;} }
PlayerList getActivePlayerList() const {
return activePlayerList;
}
PlayerList getRunningPlayerList() const {
return runningPlayerList;
}
void setStartQuantityPlayers(int theValue) { startQuantityPlayers = theValue; } void setStartQuantityPlayers(int theValue) {
int getStartQuantityPlayers() const { return startQuantityPlayers; } startQuantityPlayers = theValue;
}
int getStartQuantityPlayers() const {
return startQuantityPlayers;
}
void setStartSmallBlind(int theValue) { startSmallBlind = theValue; } void setStartSmallBlind(int theValue) {
int getStartSmallBlind() const { return startSmallBlind; } startSmallBlind = theValue;
}
int getStartSmallBlind() const {
return startSmallBlind;
}
void setStartCash(int theValue) { startCash = theValue; } void setStartCash(int theValue) {
int getStartCash() const { return startCash; } startCash = theValue;
}
int getStartCash() const {
return startCash;
}
int getMyGameID() const { return myGameID; } int getMyGameID() const {
return myGameID;
}
void setCurrentSmallBlind(int theValue) { currentSmallBlind = theValue; } void setCurrentSmallBlind(int theValue) {
int getCurrentSmallBlind() const { return currentSmallBlind; } currentSmallBlind = theValue;
}
int getCurrentSmallBlind() const {
return currentSmallBlind;
}
void setCurrentHandID(int theValue) { currentHandID = theValue; } void setCurrentHandID(int theValue) {
int getCurrentHandID() const { return currentHandID; } currentHandID = theValue;
}
int getCurrentHandID() const {
return currentHandID;
}
unsigned getDealerPosition() const { return dealerPosition; } unsigned getDealerPosition() const {
return dealerPosition;
}
boost::shared_ptr<PlayerInterface> getPlayerByUniqueId(unsigned id); boost::shared_ptr<PlayerInterface> getPlayerByUniqueId(unsigned id);
boost::shared_ptr<PlayerInterface> getCurrentPlayer(); boost::shared_ptr<PlayerInterface> getCurrentPlayer();
@@ -82,7 +113,7 @@ private:
boost::shared_ptr<EngineFactory> myFactory; boost::shared_ptr<EngineFactory> myFactory;
GuiInterface *myGui; GuiInterface *myGui;
Log *myLog; Log *myLog;
boost::shared_ptr<HandInterface> currentHand; boost::shared_ptr<HandInterface> currentHand;
boost::shared_ptr<BoardInterface> currentBoard; boost::shared_ptr<BoardInterface> currentBoard;
+68 -71
View File
@@ -43,99 +43,96 @@
#define RANKING_GAME_RAISE_EVERY_HAND 11 #define RANKING_GAME_RAISE_EVERY_HAND 11
enum ServerMode { enum ServerMode {
SERVER_MODE_LAN, SERVER_MODE_LAN,
SERVER_MODE_INTERNET_NOAUTH, SERVER_MODE_INTERNET_NOAUTH,
SERVER_MODE_INTERNET_AUTH SERVER_MODE_INTERNET_AUTH
}; };
enum ServerTransportProtocol { enum ServerTransportProtocol {
TRANSPORT_PROTOCOL_TCP = 1, TRANSPORT_PROTOCOL_TCP = 1,
TRANSPORT_PROTOCOL_SCTP = 2, TRANSPORT_PROTOCOL_SCTP = 2,
TRANSPORT_PROTOCOL_TCP_SCTP = 3}; TRANSPORT_PROTOCOL_TCP_SCTP = 3
};
enum GameState { enum GameState {
GAME_STATE_PREFLOP = 0, GAME_STATE_PREFLOP = 0,
GAME_STATE_FLOP, GAME_STATE_FLOP,
GAME_STATE_TURN, GAME_STATE_TURN,
GAME_STATE_RIVER, GAME_STATE_RIVER,
GAME_STATE_POST_RIVER, GAME_STATE_POST_RIVER,
GAME_STATE_PREFLOP_SMALL_BLIND = 0xF0, GAME_STATE_PREFLOP_SMALL_BLIND = 0xF0,
GAME_STATE_PREFLOP_BIG_BLIND = 0xF1 }; GAME_STATE_PREFLOP_BIG_BLIND = 0xF1
};
enum PlayerAction { enum PlayerAction {
PLAYER_ACTION_NONE = 0, PLAYER_ACTION_NONE = 0,
PLAYER_ACTION_FOLD, PLAYER_ACTION_FOLD,
PLAYER_ACTION_CHECK, PLAYER_ACTION_CHECK,
PLAYER_ACTION_CALL, PLAYER_ACTION_CALL,
PLAYER_ACTION_BET, PLAYER_ACTION_BET,
PLAYER_ACTION_RAISE, PLAYER_ACTION_RAISE,
PLAYER_ACTION_ALLIN }; PLAYER_ACTION_ALLIN
enum PlayerActionCode
{
ACTION_CODE_VALID = 0,
ACTION_CODE_INVALID_STATE,
ACTION_CODE_NOT_YOUR_TURN,
ACTION_CODE_NOT_ALLOWED
}; };
enum DenyKickPlayerReason enum PlayerActionCode {
{ ACTION_CODE_VALID = 0,
KICK_DENIED_INVALID_STATE = 0, ACTION_CODE_INVALID_STATE,
KICK_DENIED_TOO_FEW_PLAYERS, ACTION_CODE_NOT_YOUR_TURN,
KICK_DENIED_TEMPORARY, ACTION_CODE_NOT_ALLOWED
KICK_DENIED_OTHER_IN_PROGRESS,
KICK_DENIED_INVALID_PLAYER_ID
}; };
enum KickVote enum DenyKickPlayerReason {
{ KICK_DENIED_INVALID_STATE = 0,
KICK_VOTE_AGAINST = 0, KICK_DENIED_TOO_FEW_PLAYERS,
KICK_VOTE_IN_FAVOUR KICK_DENIED_TEMPORARY,
KICK_DENIED_OTHER_IN_PROGRESS,
KICK_DENIED_INVALID_PLAYER_ID
}; };
enum DenyVoteReason enum KickVote {
{ KICK_VOTE_AGAINST = 0,
VOTE_DENIED_INVALID_PETITION = 0, KICK_VOTE_IN_FAVOUR
VOTE_DENIED_ALREADY_VOTED
}; };
enum EndPetitionReason enum DenyVoteReason {
{ VOTE_DENIED_INVALID_PETITION = 0,
PETITION_END_ENOUGH_VOTES = 0, VOTE_DENIED_ALREADY_VOTED
PETITION_END_NOT_ENOUGH_PLAYERS,
PETITION_END_PLAYER_LEFT,
PETITION_END_TIMEOUT
}; };
enum DenyGameInvitationReason enum EndPetitionReason {
{ PETITION_END_ENOUGH_VOTES = 0,
DENY_GAME_INVITATION_NO = 0, PETITION_END_NOT_ENOUGH_PLAYERS,
DENY_GAME_INVITATION_BUSY PETITION_END_PLAYER_LEFT,
PETITION_END_TIMEOUT
};
enum DenyGameInvitationReason {
DENY_GAME_INVITATION_NO = 0,
DENY_GAME_INVITATION_BUSY
}; };
enum Button { enum Button {
BUTTON_NONE = 0, BUTTON_NONE = 0,
BUTTON_DEALER, BUTTON_DEALER,
BUTTON_SMALL_BLIND, BUTTON_SMALL_BLIND,
BUTTON_BIG_BLIND }; BUTTON_BIG_BLIND
enum NetTimeoutReason {
NETWORK_TIMEOUT_GENERIC = 0,
NETWORK_TIMEOUT_GAME_ADMIN_IDLE
}; };
struct ServerStats enum NetTimeoutReason {
{ NETWORK_TIMEOUT_GENERIC = 0,
ServerStats() NETWORK_TIMEOUT_GAME_ADMIN_IDLE
: numberOfPlayersOnServer(0), numberOfGamesOpen(0), totalPlayersEverLoggedIn(0), };
totalGamesEverCreated(0), maxGamesOpen(0), maxPlayersLoggedIn(0) {}
unsigned numberOfPlayersOnServer; struct ServerStats {
unsigned numberOfGamesOpen; ServerStats()
unsigned totalPlayersEverLoggedIn; : numberOfPlayersOnServer(0), numberOfGamesOpen(0), totalPlayersEverLoggedIn(0),
unsigned totalGamesEverCreated; totalGamesEverCreated(0), maxGamesOpen(0), maxPlayersLoggedIn(0) {}
unsigned maxGamesOpen; unsigned numberOfPlayersOnServer;
unsigned maxPlayersLoggedIn; unsigned numberOfGamesOpen;
unsigned totalPlayersEverLoggedIn;
unsigned totalGamesEverCreated;
unsigned maxGamesOpen;
unsigned maxPlayersLoggedIn;
}; };
#endif #endif
+12 -21
View File
@@ -28,43 +28,37 @@
typedef std::list<unsigned> PlayerIdList; typedef std::list<unsigned> PlayerIdList;
enum GameMode enum GameMode {
{
GAME_MODE_CREATED = 1, GAME_MODE_CREATED = 1,
GAME_MODE_STARTED, GAME_MODE_STARTED,
GAME_MODE_CLOSED GAME_MODE_CLOSED
}; };
enum GameType enum GameType {
{
GAME_TYPE_NORMAL = 1, GAME_TYPE_NORMAL = 1,
GAME_TYPE_REGISTERED_ONLY, GAME_TYPE_REGISTERED_ONLY,
GAME_TYPE_INVITE_ONLY, GAME_TYPE_INVITE_ONLY,
GAME_TYPE_RANKING GAME_TYPE_RANKING
}; };
enum RaiseIntervalMode enum RaiseIntervalMode {
{
RAISE_ON_HANDNUMBER = 1, RAISE_ON_HANDNUMBER = 1,
RAISE_ON_MINUTES RAISE_ON_MINUTES
}; };
enum RaiseMode enum RaiseMode {
{
DOUBLE_BLINDS = 1, DOUBLE_BLINDS = 1,
MANUAL_BLINDS_ORDER MANUAL_BLINDS_ORDER
}; };
enum AfterManualBlindsMode enum AfterManualBlindsMode {
{
AFTERMB_DOUBLE_BLINDS = 1, AFTERMB_DOUBLE_BLINDS = 1,
AFTERMB_RAISE_ABOUT, AFTERMB_RAISE_ABOUT,
AFTERMB_STAY_AT_LAST_BLIND AFTERMB_STAY_AT_LAST_BLIND
}; };
// For the sake of simplicity, this is a struct. // For the sake of simplicity, this is a struct.
struct GameData struct GameData {
{
GameData() : gameType(GAME_TYPE_NORMAL), maxNumberOfPlayers(0), startMoney(0), GameData() : gameType(GAME_TYPE_NORMAL), maxNumberOfPlayers(0), startMoney(0),
firstSmallBlind(0), raiseIntervalMode(RAISE_ON_HANDNUMBER), firstSmallBlind(0), raiseIntervalMode(RAISE_ON_HANDNUMBER),
raiseSmallBlindEveryHandsValue(8), raiseSmallBlindEveryMinutesValue(1), raiseSmallBlindEveryHandsValue(8), raiseSmallBlindEveryMinutesValue(1),
@@ -87,8 +81,7 @@ struct GameData
int playerActionTimeoutSec; int playerActionTimeoutSec;
}; };
struct GameInfo struct GameInfo {
{
GameInfo() : mode(GAME_MODE_CREATED), adminPlayerId(0), isPasswordProtected(false) {} GameInfo() : mode(GAME_MODE_CREATED), adminPlayerId(0), isPasswordProtected(false) {}
std::string name; std::string name;
GameData data; GameData data;
@@ -98,19 +91,17 @@ struct GameInfo
bool isPasswordProtected; bool isPasswordProtected;
}; };
struct StartData struct StartData {
{
StartData() : startDealerPlayerId(0), numberOfPlayers(0) {} StartData() : startDealerPlayerId(0), numberOfPlayers(0) {}
unsigned startDealerPlayerId; unsigned startDealerPlayerId;
int numberOfPlayers; int numberOfPlayers;
}; };
struct VoteKickData struct VoteKickData {
{
VoteKickData() VoteKickData()
: petitionId(0), kickPlayerId(0), numVotesToKick(0), : petitionId(0), kickPlayerId(0), numVotesToKick(0),
numVotesInFavourOfKicking(0), numVotesAgainstKicking(0), timeLimitSec(0), numVotesInFavourOfKicking(0), numVotesAgainstKicking(0), timeLimitSec(0),
voteTimer(boost::posix_time::time_duration(0, 0, 0), boost::timers::portable::microsec_timer::auto_start) {} voteTimer(boost::posix_time::time_duration(0, 0, 0), boost::timers::portable::microsec_timer::auto_start) {}
unsigned petitionId; unsigned petitionId;
unsigned kickPlayerId; unsigned kickPlayerId;
int numVotesToKick; int numVotesToKick;
+189 -48
View File
@@ -25,7 +25,7 @@ using namespace std;
ServerGuiWrapper::ServerGuiWrapper(ConfigFile *config, ClientCallback *clientcb, ServerCallback *servercb, IrcCallback *irccb) ServerGuiWrapper::ServerGuiWrapper(ConfigFile *config, ClientCallback *clientcb, ServerCallback *servercb, IrcCallback *irccb)
: myConfig(config), myClientcb(clientcb), myServercb(servercb), myIrccb(irccb) : myConfig(config), myClientcb(clientcb), myServercb(servercb), myIrccb(irccb)
{ {
} }
@@ -117,57 +117,198 @@ void ServerGuiWrapper::logPlayerWinGame(std::string /*playerName*/, int /*gameID
void ServerGuiWrapper::flushLogAtGame(int /*gameID*/) {} void ServerGuiWrapper::flushLogAtGame(int /*gameID*/) {}
void ServerGuiWrapper::flushLogAtHand() {} void ServerGuiWrapper::flushLogAtHand() {}
void ServerGuiWrapper::SignalNetClientServerListAdd(unsigned serverId) { if (myClientcb) myClientcb->SignalNetClientServerListAdd(serverId); } void ServerGuiWrapper::SignalNetClientServerListAdd(unsigned serverId)
void ServerGuiWrapper::SignalNetClientServerListClear() { if (myClientcb) myClientcb->SignalNetClientServerListClear(); } {
void ServerGuiWrapper::SignalNetClientServerListShow() { if (myClientcb) myClientcb->SignalNetClientServerListShow(); } if (myClientcb) myClientcb->SignalNetClientServerListAdd(serverId);
}
void ServerGuiWrapper::SignalNetClientServerListClear()
{
if (myClientcb) myClientcb->SignalNetClientServerListClear();
}
void ServerGuiWrapper::SignalNetClientServerListShow()
{
if (myClientcb) myClientcb->SignalNetClientServerListShow();
}
void ServerGuiWrapper::SignalNetClientLoginShow() { if (myClientcb) myClientcb->SignalNetClientLoginShow(); } void ServerGuiWrapper::SignalNetClientLoginShow()
void ServerGuiWrapper::SignalNetClientPostRiverShowCards(unsigned playerId) { if (myClientcb) myClientcb->SignalNetClientPostRiverShowCards(playerId); } {
if (myClientcb) myClientcb->SignalNetClientLoginShow();
}
void ServerGuiWrapper::SignalNetClientPostRiverShowCards(unsigned playerId)
{
if (myClientcb) myClientcb->SignalNetClientPostRiverShowCards(playerId);
}
void ServerGuiWrapper::SignalNetClientConnect(int actionID) { if (myClientcb) myClientcb->SignalNetClientConnect(actionID); } void ServerGuiWrapper::SignalNetClientConnect(int actionID)
void ServerGuiWrapper::SignalNetClientGameInfo(int actionID) { if (myClientcb) myClientcb->SignalNetClientGameInfo(actionID); } {
void ServerGuiWrapper::SignalNetClientError(int errorID, int osErrorID) { if (myClientcb) myClientcb->SignalNetClientError(errorID, osErrorID); } if (myClientcb) myClientcb->SignalNetClientConnect(actionID);
void ServerGuiWrapper::SignalNetClientNotification(int notificationId) { if (myClientcb) myClientcb->SignalNetClientNotification(notificationId); } }
void ServerGuiWrapper::SignalNetClientStatsUpdate(const ServerStats &stats) { if (myClientcb) myClientcb->SignalNetClientStatsUpdate(stats); } void ServerGuiWrapper::SignalNetClientGameInfo(int actionID)
void ServerGuiWrapper::SignalNetClientShowTimeoutDialog(NetTimeoutReason reason, unsigned remainingSec) { if (myClientcb) myClientcb->SignalNetClientShowTimeoutDialog(reason, remainingSec); } {
void ServerGuiWrapper::SignalNetClientRemovedFromGame(int notificationId) { if (myClientcb) myClientcb->SignalNetClientRemovedFromGame(notificationId); } if (myClientcb) myClientcb->SignalNetClientGameInfo(actionID);
void ServerGuiWrapper::SignalNetClientSelfJoined(unsigned playerId, const string &playerName, bool isGameAdmin) { if (myClientcb) myClientcb->SignalNetClientSelfJoined(playerId, playerName, isGameAdmin); } }
void ServerGuiWrapper::SignalNetClientPlayerJoined(unsigned playerId, const string &playerName, bool isGameAdmin) { if (myClientcb) myClientcb->SignalNetClientPlayerJoined(playerId, playerName, isGameAdmin); } void ServerGuiWrapper::SignalNetClientError(int errorID, int osErrorID)
void ServerGuiWrapper::SignalNetClientPlayerChanged(unsigned playerId, const string &newPlayerName) { if (myClientcb) myClientcb->SignalNetClientPlayerChanged(playerId, newPlayerName); } {
void ServerGuiWrapper::SignalNetClientPlayerLeft(unsigned playerId, const string &playerName, int removeReason) { if (myClientcb) myClientcb->SignalNetClientPlayerLeft(playerId, playerName, removeReason); } if (myClientcb) myClientcb->SignalNetClientError(errorID, osErrorID);
void ServerGuiWrapper::SignalNetClientNewGameAdmin(unsigned playerId, const string &playerName) { if (myClientcb) myClientcb->SignalNetClientNewGameAdmin(playerId, playerName); } }
void ServerGuiWrapper::SignalNetClientGameListNew(unsigned gameId) { if (myClientcb) myClientcb->SignalNetClientGameListNew(gameId); } void ServerGuiWrapper::SignalNetClientNotification(int notificationId)
void ServerGuiWrapper::SignalNetClientGameListRemove(unsigned gameId) { if (myClientcb) myClientcb->SignalNetClientGameListRemove(gameId); } {
void ServerGuiWrapper::SignalNetClientGameListUpdateMode(unsigned gameId, GameMode mode) { if (myClientcb) myClientcb->SignalNetClientGameListUpdateMode(gameId, mode); } if (myClientcb) myClientcb->SignalNetClientNotification(notificationId);
void ServerGuiWrapper::SignalNetClientGameListUpdateAdmin(unsigned gameId, unsigned adminPlayerId) { if (myClientcb) myClientcb->SignalNetClientGameListUpdateAdmin(gameId, adminPlayerId); } }
void ServerGuiWrapper::SignalNetClientGameListPlayerJoined(unsigned gameId, unsigned playerId) { if (myClientcb) myClientcb->SignalNetClientGameListPlayerJoined(gameId, playerId); } void ServerGuiWrapper::SignalNetClientStatsUpdate(const ServerStats &stats)
void ServerGuiWrapper::SignalNetClientGameListPlayerLeft(unsigned gameId, unsigned playerId) { if (myClientcb) myClientcb->SignalNetClientGameListPlayerLeft(gameId, playerId); } {
void ServerGuiWrapper::SignalNetClientGameStart(boost::shared_ptr<Game> game) { if (myClientcb) myClientcb->SignalNetClientGameStart(game); } if (myClientcb) myClientcb->SignalNetClientStatsUpdate(stats);
void ServerGuiWrapper::SignalNetClientGameChatMsg(const string &playerName, const string &msg) { if (myClientcb) myClientcb->SignalNetClientGameChatMsg(playerName, msg); } }
void ServerGuiWrapper::SignalNetClientLobbyChatMsg(const string &playerName, const string &msg) { if (myClientcb) myClientcb->SignalNetClientLobbyChatMsg(playerName, msg); } void ServerGuiWrapper::SignalNetClientShowTimeoutDialog(NetTimeoutReason reason, unsigned remainingSec)
void ServerGuiWrapper::SignalNetClientMsgBox(const string &msg) { if (myClientcb) myClientcb->SignalNetClientMsgBox(msg); } {
void ServerGuiWrapper::SignalNetClientMsgBox(unsigned msgId) { if (myClientcb) myClientcb->SignalNetClientMsgBox(msgId); } if (myClientcb) myClientcb->SignalNetClientShowTimeoutDialog(reason, remainingSec);
void ServerGuiWrapper::SignalNetClientWaitDialog() { if (myClientcb) myClientcb->SignalNetClientWaitDialog(); } }
void ServerGuiWrapper::SignalNetClientWarningAutoFoldInRankingGame(unsigned remainingAutoFolds) { if (myClientcb) myClientcb->SignalNetClientWarningAutoFoldInRankingGame(remainingAutoFolds); } void ServerGuiWrapper::SignalNetClientRemovedFromGame(int notificationId)
{
if (myClientcb) myClientcb->SignalNetClientRemovedFromGame(notificationId);
}
void ServerGuiWrapper::SignalNetClientSelfJoined(unsigned playerId, const string &playerName, bool isGameAdmin)
{
if (myClientcb) myClientcb->SignalNetClientSelfJoined(playerId, playerName, isGameAdmin);
}
void ServerGuiWrapper::SignalNetClientPlayerJoined(unsigned playerId, const string &playerName, bool isGameAdmin)
{
if (myClientcb) myClientcb->SignalNetClientPlayerJoined(playerId, playerName, isGameAdmin);
}
void ServerGuiWrapper::SignalNetClientPlayerChanged(unsigned playerId, const string &newPlayerName)
{
if (myClientcb) myClientcb->SignalNetClientPlayerChanged(playerId, newPlayerName);
}
void ServerGuiWrapper::SignalNetClientPlayerLeft(unsigned playerId, const string &playerName, int removeReason)
{
if (myClientcb) myClientcb->SignalNetClientPlayerLeft(playerId, playerName, removeReason);
}
void ServerGuiWrapper::SignalNetClientNewGameAdmin(unsigned playerId, const string &playerName)
{
if (myClientcb) myClientcb->SignalNetClientNewGameAdmin(playerId, playerName);
}
void ServerGuiWrapper::SignalNetClientGameListNew(unsigned gameId)
{
if (myClientcb) myClientcb->SignalNetClientGameListNew(gameId);
}
void ServerGuiWrapper::SignalNetClientGameListRemove(unsigned gameId)
{
if (myClientcb) myClientcb->SignalNetClientGameListRemove(gameId);
}
void ServerGuiWrapper::SignalNetClientGameListUpdateMode(unsigned gameId, GameMode mode)
{
if (myClientcb) myClientcb->SignalNetClientGameListUpdateMode(gameId, mode);
}
void ServerGuiWrapper::SignalNetClientGameListUpdateAdmin(unsigned gameId, unsigned adminPlayerId)
{
if (myClientcb) myClientcb->SignalNetClientGameListUpdateAdmin(gameId, adminPlayerId);
}
void ServerGuiWrapper::SignalNetClientGameListPlayerJoined(unsigned gameId, unsigned playerId)
{
if (myClientcb) myClientcb->SignalNetClientGameListPlayerJoined(gameId, playerId);
}
void ServerGuiWrapper::SignalNetClientGameListPlayerLeft(unsigned gameId, unsigned playerId)
{
if (myClientcb) myClientcb->SignalNetClientGameListPlayerLeft(gameId, playerId);
}
void ServerGuiWrapper::SignalNetClientGameStart(boost::shared_ptr<Game> game)
{
if (myClientcb) myClientcb->SignalNetClientGameStart(game);
}
void ServerGuiWrapper::SignalNetClientGameChatMsg(const string &playerName, const string &msg)
{
if (myClientcb) myClientcb->SignalNetClientGameChatMsg(playerName, msg);
}
void ServerGuiWrapper::SignalNetClientLobbyChatMsg(const string &playerName, const string &msg)
{
if (myClientcb) myClientcb->SignalNetClientLobbyChatMsg(playerName, msg);
}
void ServerGuiWrapper::SignalNetClientMsgBox(const string &msg)
{
if (myClientcb) myClientcb->SignalNetClientMsgBox(msg);
}
void ServerGuiWrapper::SignalNetClientMsgBox(unsigned msgId)
{
if (myClientcb) myClientcb->SignalNetClientMsgBox(msgId);
}
void ServerGuiWrapper::SignalNetClientWaitDialog()
{
if (myClientcb) myClientcb->SignalNetClientWaitDialog();
}
void ServerGuiWrapper::SignalNetClientWarningAutoFoldInRankingGame(unsigned remainingAutoFolds)
{
if (myClientcb) myClientcb->SignalNetClientWarningAutoFoldInRankingGame(remainingAutoFolds);
}
void ServerGuiWrapper::SignalNetServerSuccess(int actionID) { if (myServercb) myServercb->SignalNetServerSuccess(actionID); } void ServerGuiWrapper::SignalNetServerSuccess(int actionID)
void ServerGuiWrapper::SignalNetServerError(int errorID, int osErrorID) { if (myServercb) myServercb->SignalNetServerError(errorID, osErrorID); } {
if (myServercb) myServercb->SignalNetServerSuccess(actionID);
}
void ServerGuiWrapper::SignalNetServerError(int errorID, int osErrorID)
{
if (myServercb) myServercb->SignalNetServerError(errorID, osErrorID);
}
void ServerGuiWrapper::SignalIrcConnect(const string &server) { if (myIrccb) myIrccb->SignalIrcConnect(server); } void ServerGuiWrapper::SignalIrcConnect(const string &server)
void ServerGuiWrapper::SignalIrcSelfJoined(const string &nickName, const std::string &channel) { if (myIrccb) myIrccb->SignalIrcSelfJoined(nickName, channel); } {
void ServerGuiWrapper::SignalIrcPlayerJoined(const string &nickName) { if (myIrccb) myIrccb->SignalIrcPlayerJoined(nickName); } if (myIrccb) myIrccb->SignalIrcConnect(server);
void ServerGuiWrapper::SignalIrcPlayerChanged(const string &oldNick, const string &newNick) { if (myIrccb) myIrccb->SignalIrcPlayerChanged(oldNick, newNick); } }
void ServerGuiWrapper::SignalIrcPlayerKicked(const string &nickName, const string &byWhom, const string &reason) { if (myIrccb) myIrccb->SignalIrcPlayerKicked(nickName, byWhom, reason); } void ServerGuiWrapper::SignalIrcSelfJoined(const string &nickName, const std::string &channel)
void ServerGuiWrapper::SignalIrcPlayerLeft(const string &nickName) { if (myIrccb) myIrccb->SignalIrcPlayerLeft(nickName); } {
void ServerGuiWrapper::SignalIrcChatMsg(const string &nickName, const string &msg) { if (myIrccb) myIrccb->SignalIrcChatMsg(nickName, msg); } if (myIrccb) myIrccb->SignalIrcSelfJoined(nickName, channel);
void ServerGuiWrapper::SignalIrcError(int errorCode) { if (myIrccb) myIrccb->SignalIrcError(errorCode); } }
void ServerGuiWrapper::SignalIrcServerError(int errorCode) {if (myIrccb) myIrccb->SignalIrcServerError(errorCode); } void ServerGuiWrapper::SignalIrcPlayerJoined(const string &nickName)
{
if (myIrccb) myIrccb->SignalIrcPlayerJoined(nickName);
}
void ServerGuiWrapper::SignalIrcPlayerChanged(const string &oldNick, const string &newNick)
{
if (myIrccb) myIrccb->SignalIrcPlayerChanged(oldNick, newNick);
}
void ServerGuiWrapper::SignalIrcPlayerKicked(const string &nickName, const string &byWhom, const string &reason)
{
if (myIrccb) myIrccb->SignalIrcPlayerKicked(nickName, byWhom, reason);
}
void ServerGuiWrapper::SignalIrcPlayerLeft(const string &nickName)
{
if (myIrccb) myIrccb->SignalIrcPlayerLeft(nickName);
}
void ServerGuiWrapper::SignalIrcChatMsg(const string &nickName, const string &msg)
{
if (myIrccb) myIrccb->SignalIrcChatMsg(nickName, msg);
}
void ServerGuiWrapper::SignalIrcError(int errorCode)
{
if (myIrccb) myIrccb->SignalIrcError(errorCode);
}
void ServerGuiWrapper::SignalIrcServerError(int errorCode)
{
if (myIrccb) myIrccb->SignalIrcServerError(errorCode);
}
void ServerGuiWrapper::SignalLobbyPlayerJoined(unsigned playerId, const std::string &nickName) { if (myClientcb) myClientcb->SignalLobbyPlayerJoined(playerId, nickName); } void ServerGuiWrapper::SignalLobbyPlayerJoined(unsigned playerId, const std::string &nickName)
void ServerGuiWrapper::SignalLobbyPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason) { if (myClientcb) myClientcb->SignalLobbyPlayerKicked(nickName, byWhom, reason); } {
void ServerGuiWrapper::SignalLobbyPlayerLeft(unsigned playerId) { if (myClientcb) myClientcb->SignalLobbyPlayerLeft(playerId); } if (myClientcb) myClientcb->SignalLobbyPlayerJoined(playerId, nickName);
}
void ServerGuiWrapper::SignalLobbyPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason)
{
if (myClientcb) myClientcb->SignalLobbyPlayerKicked(nickName, byWhom, reason);
}
void ServerGuiWrapper::SignalLobbyPlayerLeft(unsigned playerId)
{
if (myClientcb) myClientcb->SignalLobbyPlayerLeft(playerId);
}
void ServerGuiWrapper::SignalSelfGameInvitation(unsigned gameId, unsigned playerIdFrom) { if (myClientcb) myClientcb->SignalSelfGameInvitation(gameId, playerIdFrom); } void ServerGuiWrapper::SignalSelfGameInvitation(unsigned gameId, unsigned playerIdFrom)
void ServerGuiWrapper::SignalPlayerGameInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom) { if (myClientcb) myClientcb->SignalPlayerGameInvitation(gameId, playerIdWho, playerIdFrom); } {
void ServerGuiWrapper::SignalRejectedGameInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason) { if (myClientcb) myClientcb->SignalRejectedGameInvitation(gameId, playerIdWho, reason); } if (myClientcb) myClientcb->SignalSelfGameInvitation(gameId, playerIdFrom);
}
void ServerGuiWrapper::SignalPlayerGameInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom)
{
if (myClientcb) myClientcb->SignalPlayerGameInvitation(gameId, playerIdWho, playerIdFrom);
}
void ServerGuiWrapper::SignalRejectedGameInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason)
{
if (myClientcb) myClientcb->SignalRejectedGameInvitation(gameId, playerIdWho, reason);
}
+112 -108
View File
@@ -28,146 +28,150 @@ class gameTableImpl;
class ServerGuiWrapper : public GuiInterface class ServerGuiWrapper : public GuiInterface
{ {
public: public:
ServerGuiWrapper(ConfigFile *config, ClientCallback *clientcb, ServerCallback *servercb, IrcCallback *irccb); ServerGuiWrapper(ConfigFile *config, ClientCallback *clientcb, ServerCallback *servercb, IrcCallback *irccb);
~ServerGuiWrapper(); ~ServerGuiWrapper();
void initGui(int speed); void initGui(int speed);
boost::shared_ptr<Session> getSession(); boost::shared_ptr<Session> getSession();
void setSession(boost::shared_ptr<Session> session); void setSession(boost::shared_ptr<Session> session);
gameTableImpl* getMyW() const {return NULL;} gameTableImpl* getMyW() const {
guiLog* getMyGuiLog() const {return NULL;} return NULL;
}
guiLog* getMyGuiLog() const {
return NULL;
}
void refreshSet() const; void refreshSet() const;
void refreshCash() const; void refreshCash() const;
void refreshAction(int =-1, int =-1) const; void refreshAction(int =-1, int =-1) const;
void refreshChangePlayer() const; void refreshChangePlayer() const;
void refreshPot() const; void refreshPot() const;
void refreshGroupbox(int =-1, int =-1) const; void refreshGroupbox(int =-1, int =-1) const;
void refreshAll() const; void refreshAll() const;
void refreshPlayerName() const; void refreshPlayerName() const;
void refreshButton() const; void refreshButton() const;
void refreshGameLabels(GameState state) const; void refreshGameLabels(GameState state) const;
void setPlayerAvatar(int myUniqueID, const std::string &myAvatar) const; void setPlayerAvatar(int myUniqueID, const std::string &myAvatar) const;
void waitForGuiUpdateDone() const; void waitForGuiUpdateDone() const;
void dealBeRoCards(int); void dealBeRoCards(int);
void dealHoleCards(); void dealHoleCards();
void dealFlopCards(); void dealFlopCards();
void dealTurnCard(); void dealTurnCard();
void dealRiverCard(); void dealRiverCard();
void nextPlayerAnimation(); void nextPlayerAnimation();
void beRoAnimation2(int); void beRoAnimation2(int);
void preflopAnimation1(); void preflopAnimation1();
void preflopAnimation2(); void preflopAnimation2();
void flopAnimation1(); void flopAnimation1();
void flopAnimation2(); void flopAnimation2();
void turnAnimation1(); void turnAnimation1();
void turnAnimation2(); void turnAnimation2();
void riverAnimation1(); void riverAnimation1();
void riverAnimation2(); void riverAnimation2();
void postRiverAnimation1(); void postRiverAnimation1();
void postRiverRunAnimation1(); void postRiverRunAnimation1();
void flipHolecardsAllIn(); void flipHolecardsAllIn();
void nextRoundCleanGui(); void nextRoundCleanGui();
void meInAction(); void meInAction();
void updateMyButtonsState(); void updateMyButtonsState();
void disableMyButtons(); void disableMyButtons();
void startTimeoutAnimation(int playerNum, int timeoutSec); void startTimeoutAnimation(int playerNum, int timeoutSec);
void stopTimeoutAnimation(int playerNum); void stopTimeoutAnimation(int playerNum);
void startVoteOnKick(unsigned playerId, unsigned voteStarterPlayerId, int timeoutSec, int numVotesNeededToKick); void startVoteOnKick(unsigned playerId, unsigned voteStarterPlayerId, int timeoutSec, int numVotesNeededToKick);
void changeVoteOnKickButtonsState(bool showHide); void changeVoteOnKickButtonsState(bool showHide);
void refreshVotesMonitor(int currentVotes, int numVotesNeededToKick); void refreshVotesMonitor(int currentVotes, int numVotesNeededToKick);
void endVoteOnKick(); void endVoteOnKick();
void logPlayerActionMsg(std::string playerName, int playerID, int action, int setValue) ; void logPlayerActionMsg(std::string playerName, int playerID, int action, int setValue) ;
void logNewGameHandMsg(int gameID, int handID) ; void logNewGameHandMsg(int gameID, int handID) ;
void logPlayerWinsMsg(std::string playerName, int pot, bool main); void logPlayerWinsMsg(std::string playerName, int pot, bool main);
void logPlayerSitsOut(std::string playerName); void logPlayerSitsOut(std::string playerName);
void logNewBlindsSetsMsg(int sbSet, int bbSet, std::string sbName, std::string bbName); void logNewBlindsSetsMsg(int sbSet, int bbSet, std::string sbName, std::string bbName);
void logDealBoardCardsMsg(int roundID, int card1, int card2, int card3, int card4 = -1, int card5 = -1) ; void logDealBoardCardsMsg(int roundID, int card1, int card2, int card3, int card4 = -1, int card5 = -1) ;
void logFlipHoleCardsMsg(std::string playerName, int playerID, int card1, int card2, int cardsValueInt = -1, std::string showHas = "shows") ; void logFlipHoleCardsMsg(std::string playerName, int playerID, int card1, int card2, int cardsValueInt = -1, std::string showHas = "shows") ;
void logPlayerWinGame(std::string playerName, int gameID); void logPlayerWinGame(std::string playerName, int gameID);
void flushLogAtGame(int gameID); void flushLogAtGame(int gameID);
void flushLogAtHand(); void flushLogAtHand();
void SignalNetClientConnect(int actionID); void SignalNetClientConnect(int actionID);
void SignalNetClientGameInfo(int actionID); void SignalNetClientGameInfo(int actionID);
void SignalNetClientError(int errorID, int osErrorID); void SignalNetClientError(int errorID, int osErrorID);
void SignalNetClientNotification(int notificationId); void SignalNetClientNotification(int notificationId);
void SignalNetClientStatsUpdate(const ServerStats &stats); void SignalNetClientStatsUpdate(const ServerStats &stats);
void SignalNetClientShowTimeoutDialog(NetTimeoutReason reason, unsigned remainingSec); void SignalNetClientShowTimeoutDialog(NetTimeoutReason reason, unsigned remainingSec);
void SignalNetClientRemovedFromGame(int notificationId); void SignalNetClientRemovedFromGame(int notificationId);
void SignalNetClientSelfJoined(unsigned playerId, const std::string &playerName, bool isGameAdmin); void SignalNetClientSelfJoined(unsigned playerId, const std::string &playerName, bool isGameAdmin);
void SignalNetClientPlayerJoined(unsigned playerId, const std::string &playerName, bool isGameAdmin); void SignalNetClientPlayerJoined(unsigned playerId, const std::string &playerName, bool isGameAdmin);
void SignalNetClientPlayerChanged(unsigned playerId, const std::string &newPlayerName); void SignalNetClientPlayerChanged(unsigned playerId, const std::string &newPlayerName);
void SignalNetClientPlayerLeft(unsigned playerId, const std::string &playerName, int removeReason); void SignalNetClientPlayerLeft(unsigned playerId, const std::string &playerName, int removeReason);
void SignalNetClientNewGameAdmin(unsigned playerId, const std::string &playerName); void SignalNetClientNewGameAdmin(unsigned playerId, const std::string &playerName);
void SignalNetClientGameChatMsg(const std::string &playerName, const std::string &msg); void SignalNetClientGameChatMsg(const std::string &playerName, const std::string &msg);
void SignalNetClientLobbyChatMsg(const std::string &playerName, const std::string &msg); void SignalNetClientLobbyChatMsg(const std::string &playerName, const std::string &msg);
void SignalNetClientWaitDialog(); void SignalNetClientWaitDialog();
void SignalNetClientWarningAutoFoldInRankingGame(unsigned remainingAutoFolds); void SignalNetClientWarningAutoFoldInRankingGame(unsigned remainingAutoFolds);
void SignalNetClientGameListNew(unsigned gameId); void SignalNetClientGameListNew(unsigned gameId);
void SignalNetClientGameListRemove(unsigned gameId); void SignalNetClientGameListRemove(unsigned gameId);
void SignalNetClientGameListUpdateMode(unsigned gameId, GameMode mode); void SignalNetClientGameListUpdateMode(unsigned gameId, GameMode mode);
void SignalNetClientGameListUpdateAdmin(unsigned gameId, unsigned adminPlayerId); void SignalNetClientGameListUpdateAdmin(unsigned gameId, unsigned adminPlayerId);
void SignalNetClientGameListPlayerJoined(unsigned gameId, unsigned playerId); void SignalNetClientGameListPlayerJoined(unsigned gameId, unsigned playerId);
void SignalNetClientGameListPlayerLeft(unsigned gameId, unsigned playerId); void SignalNetClientGameListPlayerLeft(unsigned gameId, unsigned playerId);
void SignalNetClientGameStart(boost::shared_ptr<Game> game); void SignalNetClientGameStart(boost::shared_ptr<Game> game);
void SignalNetClientServerListAdd(unsigned serverId); void SignalNetClientServerListAdd(unsigned serverId);
void SignalNetClientServerListClear(); void SignalNetClientServerListClear();
void SignalNetClientServerListShow(); void SignalNetClientServerListShow();
void SignalNetClientLoginShow(); void SignalNetClientLoginShow();
void SignalNetClientPostRiverShowCards(unsigned playerId); void SignalNetClientPostRiverShowCards(unsigned playerId);
void SignalNetServerSuccess(int actionID); void SignalNetServerSuccess(int actionID);
void SignalNetServerError(int errorID, int osErrorID); void SignalNetServerError(int errorID, int osErrorID);
void SignalIrcConnect(const std::string &server); void SignalIrcConnect(const std::string &server);
void SignalIrcSelfJoined(const std::string &nickName, const std::string &channel); void SignalIrcSelfJoined(const std::string &nickName, const std::string &channel);
void SignalIrcPlayerJoined(const std::string &nickName); void SignalIrcPlayerJoined(const std::string &nickName);
void SignalIrcPlayerChanged(const std::string &oldNick, const std::string &newNick); void SignalIrcPlayerChanged(const std::string &oldNick, const std::string &newNick);
void SignalIrcPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason); void SignalIrcPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason);
void SignalIrcPlayerLeft(const std::string &nickName); void SignalIrcPlayerLeft(const std::string &nickName);
void SignalIrcChatMsg(const std::string &nickName, const std::string &msg); void SignalIrcChatMsg(const std::string &nickName, const std::string &msg);
void SignalNetClientMsgBox(const std::string &msg); void SignalNetClientMsgBox(const std::string &msg);
void SignalNetClientMsgBox(unsigned msgId); void SignalNetClientMsgBox(unsigned msgId);
void SignalIrcError(int errorCode); void SignalIrcError(int errorCode);
void SignalIrcServerError(int errorCode); void SignalIrcServerError(int errorCode);
void SignalLobbyPlayerJoined(unsigned playerId, const std::string &nickName); void SignalLobbyPlayerJoined(unsigned playerId, const std::string &nickName);
void SignalLobbyPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason); void SignalLobbyPlayerKicked(const std::string &nickName, const std::string &byWhom, const std::string &reason);
void SignalLobbyPlayerLeft(unsigned playerId); void SignalLobbyPlayerLeft(unsigned playerId);
void SignalSelfGameInvitation(unsigned gameId, unsigned playerIdFrom); void SignalSelfGameInvitation(unsigned gameId, unsigned playerIdFrom);
void SignalPlayerGameInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom); void SignalPlayerGameInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom);
void SignalRejectedGameInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason); void SignalRejectedGameInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason);
private: private:
boost::shared_ptr<Session> mySession; boost::shared_ptr<Session> mySession;
ConfigFile *myConfig; ConfigFile *myConfig;
ClientCallback *myClientcb; ClientCallback *myClientcb;
ServerCallback *myServercb; ServerCallback *myServercb;
IrcCallback *myIrccb; IrcCallback *myIrccb;
}; };
#endif #endif
+61 -60
View File
@@ -31,84 +31,85 @@ class guiLog;
class Session; class Session;
class gameTableImpl; class gameTableImpl;
class GuiInterface : public ClientCallback, public ServerCallback, public IrcCallback { class GuiInterface : public ClientCallback, public ServerCallback, public IrcCallback
{
public: public:
virtual ~GuiInterface(); virtual ~GuiInterface();
virtual void initGui(int speed) =0; virtual void initGui(int speed) =0;
virtual boost::shared_ptr<Session> getSession() =0; virtual boost::shared_ptr<Session> getSession() =0;
virtual void setSession(boost::shared_ptr<Session> session) =0; virtual void setSession(boost::shared_ptr<Session> session) =0;
virtual gameTableImpl *getMyW() const=0; virtual gameTableImpl *getMyW() const=0;
virtual guiLog* getMyGuiLog() const=0; virtual guiLog* getMyGuiLog() const=0;
//refresh-Funktionen //refresh-Funktionen
virtual void refreshSet() const=0; virtual void refreshSet() const=0;
virtual void refreshCash() const=0; virtual void refreshCash() const=0;
virtual void refreshAction(int =-1, int =-1) const=0; virtual void refreshAction(int =-1, int =-1) const=0;
virtual void refreshChangePlayer() const=0; virtual void refreshChangePlayer() const=0;
virtual void refreshPot() const=0; virtual void refreshPot() const=0;
virtual void refreshGroupbox(int =-1, int =-1) const=0; virtual void refreshGroupbox(int =-1, int =-1) const=0;
virtual void refreshAll() const=0; virtual void refreshAll() const=0;
virtual void refreshPlayerName() const=0; virtual void refreshPlayerName() const=0;
virtual void refreshButton() const =0; virtual void refreshButton() const =0;
virtual void refreshGameLabels(GameState state) const=0; virtual void refreshGameLabels(GameState state) const=0;
virtual void setPlayerAvatar(int myUniqueID, const std::string &myAvatar) const=0; virtual void setPlayerAvatar(int myUniqueID, const std::string &myAvatar) const=0;
virtual void waitForGuiUpdateDone() const=0; virtual void waitForGuiUpdateDone() const=0;
// Karten-Funktionen // Karten-Funktionen
virtual void dealBeRoCards(int) =0; virtual void dealBeRoCards(int) =0;
virtual void dealHoleCards()=0; virtual void dealHoleCards()=0;
virtual void dealFlopCards()=0; virtual void dealFlopCards()=0;
virtual void dealTurnCard()=0; virtual void dealTurnCard()=0;
virtual void dealRiverCard()=0; virtual void dealRiverCard()=0;
virtual void nextPlayerAnimation()=0; virtual void nextPlayerAnimation()=0;
virtual void beRoAnimation2(int)=0; virtual void beRoAnimation2(int)=0;
virtual void preflopAnimation1()=0; virtual void preflopAnimation1()=0;
virtual void preflopAnimation2()=0; virtual void preflopAnimation2()=0;
virtual void flopAnimation1()=0; virtual void flopAnimation1()=0;
virtual void flopAnimation2()=0; virtual void flopAnimation2()=0;
virtual void turnAnimation1()=0; virtual void turnAnimation1()=0;
virtual void turnAnimation2()=0; virtual void turnAnimation2()=0;
virtual void riverAnimation1()=0; virtual void riverAnimation1()=0;
virtual void riverAnimation2()=0; virtual void riverAnimation2()=0;
virtual void postRiverAnimation1()=0; virtual void postRiverAnimation1()=0;
virtual void postRiverRunAnimation1()=0; virtual void postRiverRunAnimation1()=0;
virtual void flipHolecardsAllIn()=0; virtual void flipHolecardsAllIn()=0;
virtual void nextRoundCleanGui()=0; virtual void nextRoundCleanGui()=0;
virtual void meInAction()=0; virtual void meInAction()=0;
virtual void updateMyButtonsState()=0; virtual void updateMyButtonsState()=0;
virtual void disableMyButtons()=0; virtual void disableMyButtons()=0;
virtual void startTimeoutAnimation(int playerNum, int timeoutSec) =0; virtual void startTimeoutAnimation(int playerNum, int timeoutSec) =0;
virtual void stopTimeoutAnimation(int playerNum) =0; virtual void stopTimeoutAnimation(int playerNum) =0;
virtual void startVoteOnKick(unsigned playerId, unsigned voteStarterPlayerId, int timeoutSec, int numVotesNeededToKick) =0; virtual void startVoteOnKick(unsigned playerId, unsigned voteStarterPlayerId, int timeoutSec, int numVotesNeededToKick) =0;
virtual void changeVoteOnKickButtonsState(bool showHide) =0; virtual void changeVoteOnKickButtonsState(bool showHide) =0;
virtual void refreshVotesMonitor(int currentVotes, int numVotesNeededToKick) =0; virtual void refreshVotesMonitor(int currentVotes, int numVotesNeededToKick) =0;
virtual void endVoteOnKick() =0; virtual void endVoteOnKick() =0;
//log.cpp //log.cpp
virtual void logPlayerActionMsg(std::string playName, int playerID, int action, int setValue) =0; virtual void logPlayerActionMsg(std::string playName, int playerID, int action, int setValue) =0;
virtual void logNewGameHandMsg(int gameID, int HandID) =0; virtual void logNewGameHandMsg(int gameID, int HandID) =0;
virtual void logPlayerWinsMsg(std::string playerName, int pot, bool main) = 0; virtual void logPlayerWinsMsg(std::string playerName, int pot, bool main) = 0;
virtual void logPlayerSitsOut(std::string playerName) = 0; virtual void logPlayerSitsOut(std::string playerName) = 0;
virtual void logNewBlindsSetsMsg(int sbSet, int bbSet, std::string sbName, std::string bbName) =0; virtual void logNewBlindsSetsMsg(int sbSet, int bbSet, std::string sbName, std::string bbName) =0;
virtual void logDealBoardCardsMsg(int roundID, int card1, int card2, int card3, int card4 = -1, int card5 = -1) = 0; virtual void logDealBoardCardsMsg(int roundID, int card1, int card2, int card3, int card4 = -1, int card5 = -1) = 0;
virtual void logFlipHoleCardsMsg(std::string playerName, int playerID, int card1, int card2, int cardsValueInt = -1, std::string showHas = "shows") = 0; virtual void logFlipHoleCardsMsg(std::string playerName, int playerID, int card1, int card2, int cardsValueInt = -1, std::string showHas = "shows") = 0;
virtual void logPlayerWinGame(std::string playerName, int gameID) =0; virtual void logPlayerWinGame(std::string playerName, int gameID) =0;
virtual void flushLogAtGame(int gameID) =0; virtual void flushLogAtGame(int gameID) =0;
virtual void flushLogAtHand() =0; virtual void flushLogAtHand() =0;
}; };
+2 -2
View File
@@ -24,7 +24,7 @@
aboutPokerthImpl::aboutPokerthImpl(QWidget *parent, ConfigFile *c) aboutPokerthImpl::aboutPokerthImpl(QWidget *parent, ConfigFile *c)
: QDialog(parent), myConfig(c) : QDialog(parent), myConfig(c)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
@@ -53,7 +53,7 @@ aboutPokerthImpl::aboutPokerthImpl(QWidget *parent, ConfigFile *c)
} }
label_logo->setPixmap(QPixmap(":/gfx/logoChip3D.png")); label_logo->setPixmap(QPixmap(":/gfx/logoChip3D.png"));
label_pokerthVersion->setStyleSheet("QLabel { font-size: 16px; font-weight: bold;}"); label_pokerthVersion->setStyleSheet("QLabel { font-size: 16px; font-weight: bold;}");
label_pokerthVersion->setText(QString(tr("PokerTH %1").arg(POKERTH_BETA_RELEASE_STRING))); label_pokerthVersion->setText(QString(tr("PokerTH %1").arg(POKERTH_BETA_RELEASE_STRING)));
+4 -3
View File
@@ -24,10 +24,11 @@
class ConfigFile; class ConfigFile;
class aboutPokerthImpl: public QDialog, public Ui::aboutPokerth { class aboutPokerthImpl: public QDialog, public Ui::aboutPokerth
Q_OBJECT {
Q_OBJECT
public: public:
aboutPokerthImpl(QWidget *parent = 0, ConfigFile *c =0); aboutPokerthImpl(QWidget *parent = 0, ConfigFile *c =0);
private: private:
@@ -23,7 +23,7 @@
changeCompleteBlindsDialogImpl::changeCompleteBlindsDialogImpl(QWidget *parent, ConfigFile *c) changeCompleteBlindsDialogImpl::changeCompleteBlindsDialogImpl(QWidget *parent, ConfigFile *c)
: QDialog(parent), myConfig(c), settingsCorrect(TRUE) : QDialog(parent), myConfig(c), settingsCorrect(TRUE)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
@@ -37,33 +37,40 @@ changeCompleteBlindsDialogImpl::changeCompleteBlindsDialogImpl(QWidget *parent,
} }
void changeCompleteBlindsDialogImpl::exec() { void changeCompleteBlindsDialogImpl::exec()
{
QDialog::exec(); QDialog::exec();
} }
void changeCompleteBlindsDialogImpl::updateSpinBoxInputMinimum(int value) { spinBox_input->setMinimum(value+1); } void changeCompleteBlindsDialogImpl::updateSpinBoxInputMinimum(int value)
{
spinBox_input->setMinimum(value+1);
}
void changeCompleteBlindsDialogImpl::addBlindValueToList() { void changeCompleteBlindsDialogImpl::addBlindValueToList()
{
if(listWidget_blinds->count() == 30) { if(listWidget_blinds->count() == 30) {
QMessageBox::warning(this, tr("Manual Blinds Order"), QMessageBox::warning(this, tr("Manual Blinds Order"),
tr("You cannot set more than 30 manual blinds."), tr("You cannot set more than 30 manual blinds."),
QMessageBox::Close); } QMessageBox::Close);
else { } else {
listWidget_blinds->addItem(QString::number(spinBox_input->value(),10)); listWidget_blinds->addItem(QString::number(spinBox_input->value(),10));
sortBlindsList(); sortBlindsList();
} }
} }
void changeCompleteBlindsDialogImpl::removeBlindFromList() { void changeCompleteBlindsDialogImpl::removeBlindFromList()
{
listWidget_blinds->takeItem(listWidget_blinds->currentRow()); listWidget_blinds->takeItem(listWidget_blinds->currentRow());
sortBlindsList(); sortBlindsList();
} }
void changeCompleteBlindsDialogImpl::sortBlindsList() { void changeCompleteBlindsDialogImpl::sortBlindsList()
{
int i; int i;
QList<int> tempIntList; QList<int> tempIntList;
@@ -27,16 +27,19 @@
class ConfigFile; class ConfigFile;
class changeCompleteBlindsDialogImpl: public QDialog, public Ui::changeCompleteBlindsDialog { class changeCompleteBlindsDialogImpl: public QDialog, public Ui::changeCompleteBlindsDialog
Q_OBJECT {
Q_OBJECT
public: public:
changeCompleteBlindsDialogImpl(QWidget *parent = 0, ConfigFile *c = 0); changeCompleteBlindsDialogImpl(QWidget *parent = 0, ConfigFile *c = 0);
void exec(); void exec();
public slots: public slots:
bool getSettingsCorrect() const { return settingsCorrect;} bool getSettingsCorrect() const {
return settingsCorrect;
}
void updateSpinBoxInputMinimum(int); void updateSpinBoxInputMinimum(int);
void addBlindValueToList(); void addBlindValueToList();
@@ -23,88 +23,89 @@
#include "configfile.h" #include "configfile.h"
changeContentDialogImpl::changeContentDialogImpl(QWidget *parent, ConfigFile *config, DialogType t) changeContentDialogImpl::changeContentDialogImpl(QWidget *parent, ConfigFile *config, DialogType t)
: QDialog(parent), myConfig(config), myType(t) : QDialog(parent), myConfig(config), myType(t)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog); setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog);
#endif #endif
setupUi(this); setupUi(this);
switch (myType) { switch (myType) {
case CHANGE_HUMAN_PLAYER_NAME: { case CHANGE_HUMAN_PLAYER_NAME: {
label_Message->setText(tr("You cannot join Internet-Game-Lobby with \"Human Player\" as nickname.\nPlease choose another one.")); label_Message->setText(tr("You cannot join Internet-Game-Lobby with \"Human Player\" as nickname.\nPlease choose another one."));
label_lineLabel->setText(tr("Nick name:")); label_lineLabel->setText(tr("Nick name:"));
lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str())); lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str()));
lineEdit->setMaxLength(12); lineEdit->setMaxLength(12);
checkBox->hide(); checkBox->hide();
this->setGeometry(this->x(), this->y(), this->width(), this->height()-20 ); this->setGeometry(this->x(), this->y(), this->width(), this->height()-20 );
} }
break; break;
case CHANGE_NICK_ALREADY_IN_USE: { case CHANGE_NICK_ALREADY_IN_USE: {
label_Message->setText(tr("Your player name is already used by another player.\nPlease choose a different name.")); label_Message->setText(tr("Your player name is already used by another player.\nPlease choose a different name."));
label_lineLabel->setText(tr("Nick name:")); label_lineLabel->setText(tr("Nick name:"));
lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str())); lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str()));
lineEdit->setMaxLength(12); lineEdit->setMaxLength(12);
} }
break; break;
case CHANGE_NICK_INVALID: { case CHANGE_NICK_INVALID: {
label_Message->setText(tr("The player name is too short, too long or invalid. Please choose another one.")); label_Message->setText(tr("The player name is too short, too long or invalid. Please choose another one."));
label_lineLabel->setText(tr("Nick name:")); label_lineLabel->setText(tr("Nick name:"));
lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str())); lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("MyName").c_str()));
lineEdit->setMaxLength(12); lineEdit->setMaxLength(12);
} }
break; break;
case CHANGE_INET_GAME_NAME_IN_USE: { case CHANGE_INET_GAME_NAME_IN_USE: {
label_Message->setText(tr("There is already a game with your chosen game name.\nPlease choose another one!")); label_Message->setText(tr("There is already a game with your chosen game name.\nPlease choose another one!"));
label_lineLabel->setText(tr("Game name:")); label_lineLabel->setText(tr("Game name:"));
lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str())); lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str()));
lineEdit->setMaxLength(48); lineEdit->setMaxLength(48);
} }
break; break;
case CHANGE_INET_BAD_GAME_NAME: { case CHANGE_INET_BAD_GAME_NAME: {
label_Message->setText(tr("There is a forbidden word in your chosen game name.\nPlease choose another one!")); label_Message->setText(tr("There is a forbidden word in your chosen game name.\nPlease choose another one!"));
label_lineLabel->setText(tr("Game name:")); label_lineLabel->setText(tr("Game name:"));
lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str())); lineEdit->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str()));
lineEdit->setMaxLength(48); lineEdit->setMaxLength(48);
} }
break; break;
} }
connect(this, SIGNAL(accepted ()), this, SLOT(saveContent())); connect(this, SIGNAL(accepted ()), this, SLOT(saveContent()));
} }
void changeContentDialogImpl::saveContent() { void changeContentDialogImpl::saveContent()
{
switch (myType) { switch (myType) {
case CHANGE_HUMAN_PLAYER_NAME: { case CHANGE_HUMAN_PLAYER_NAME: {
myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData()); myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData());
} }
break; break;
case CHANGE_NICK_ALREADY_IN_USE: { case CHANGE_NICK_ALREADY_IN_USE: {
if(checkBox->isChecked()) { if(checkBox->isChecked()) {
myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData()); myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData());
} }
} }
break; break;
case CHANGE_NICK_INVALID: { case CHANGE_NICK_INVALID: {
if(checkBox->isChecked()) { if(checkBox->isChecked()) {
myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData()); myConfig->writeConfigString("MyName", lineEdit->text().toUtf8().constData());
} }
} }
break; break;
case CHANGE_INET_BAD_GAME_NAME: case CHANGE_INET_BAD_GAME_NAME:
case CHANGE_INET_GAME_NAME_IN_USE: { case CHANGE_INET_GAME_NAME_IN_USE: {
if(checkBox->isChecked()) { if(checkBox->isChecked()) {
myConfig->writeConfigString("InternetGameName", lineEdit->text().toUtf8().constData()); myConfig->writeConfigString("InternetGameName", lineEdit->text().toUtf8().constData());
} }
} }
break; break;
} }
//write buffer to disc //write buffer to disc
myConfig->writeBuffer(); myConfig->writeBuffer();
} }
@@ -28,18 +28,19 @@ enum DialogType { CHANGE_HUMAN_PLAYER_NAME=0, CHANGE_NICK_ALREADY_IN_USE, CHANGE
class ConfigFile; class ConfigFile;
class changeContentDialogImpl: public QDialog, public Ui::changeContentDialog { class changeContentDialogImpl: public QDialog, public Ui::changeContentDialog
Q_OBJECT {
Q_OBJECT
public: public:
changeContentDialogImpl(QWidget *parent, ConfigFile *config, DialogType t); changeContentDialogImpl(QWidget *parent, ConfigFile *config, DialogType t);
public slots: public slots:
void saveContent(); void saveContent();
private: private:
ConfigFile *myConfig; ConfigFile *myConfig;
DialogType myType; DialogType myType;
}; };
+153 -139
View File
@@ -30,8 +30,8 @@ using namespace std;
ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo) ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo)
{ {
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str()); myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList"); ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
} }
@@ -39,197 +39,211 @@ ChatTools::~ChatTools()
{ {
} }
void ChatTools::sendMessage() { void ChatTools::sendMessage()
{
if(myLineEdit->text().size() && mySession) { if(myLineEdit->text().size() && mySession) {
fillChatLinesHistory(myLineEdit->text()); fillChatLinesHistory(myLineEdit->text());
if(myChatType == INGAME_CHAT) { if(myChatType == INGAME_CHAT) {
mySession->sendGameChatMessage(myLineEdit->text().toUtf8().constData()); mySession->sendGameChatMessage(myLineEdit->text().toUtf8().constData());
} } else {
else { mySession->sendLobbyChatMessage(myLineEdit->text().toUtf8().constData());
mySession->sendLobbyChatMessage(myLineEdit->text().toUtf8().constData()); }
} myLineEdit->setText("");
myLineEdit->setText(""); }
}
} }
void ChatTools::receiveMessage(QString playerName, QString message) { void ChatTools::receiveMessage(QString playerName, QString message)
{
if(myTextBrowser) { if(myTextBrowser) {
message = message.replace("<","&lt;"); message = message.replace("<","&lt;");
message = message.replace(">","&gt;"); message = message.replace(">","&gt;");
//refresh myNick if it was changed during runtime //refresh myNick if it was changed during runtime
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str()); myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
QString tempMsg; QString tempMsg;
if(myChatType == INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) { if(myChatType == INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) {
tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>"); tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>");
//play beep sound only in INET-lobby-chat //play beep sound only in INET-lobby-chat
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) { if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0); myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
} }
} } else if(message.contains(myNick, Qt::CaseInsensitive)) {
else if(message.contains(myNick, Qt::CaseInsensitive)) {
switch (myChatType) { switch (myChatType) {
case INET_LOBBY_CHAT: { case INET_LOBBY_CHAT: {
tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>"); tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
//play beep sound only in INET-lobby-chat //play beep sound only in INET-lobby-chat
// TODO dont play when message is from yourself // TODO dont play when message is from yourself
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) { if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0); myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
} }
} }
break; break;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>"); case LAN_LOBBY_CHAT:
break; tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>");
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>"); break;
break; case INGAME_CHAT:
default: tempMsg = message; tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>");
} break;
} default:
else if(playerName == myNick) { tempMsg = message;
switch (myChatType) { }
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>"); } else if(playerName == myNick) {
break; switch (myChatType) {
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>"); case INET_LOBBY_CHAT:
break; tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>"); break;
break; case LAN_LOBBY_CHAT:
default: tempMsg = message; tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
} break;
} case INGAME_CHAT:
else { tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
switch (myChatType) { break;
case INET_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>"); default:
break; tempMsg = message;
case LAN_LOBBY_CHAT: tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>"); }
break; } else {
case INGAME_CHAT: tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>"); switch (myChatType) {
break; case INET_LOBBY_CHAT:
default: tempMsg = message; tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>");
} break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT:
tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
break;
default:
tempMsg = message;
}
} }
bool nickFoundOnIgnoreList = false; bool nickFoundOnIgnoreList = false;
list<std::string>::iterator it1; list<std::string>::iterator it1;
for(it1=ignoreList.begin(); it1 != ignoreList.end(); ++it1) { for(it1=ignoreList.begin(); it1 != ignoreList.end(); ++it1) {
if(playerName == QString::fromUtf8(it1->c_str())) { if(playerName == QString::fromUtf8(it1->c_str())) {
nickFoundOnIgnoreList = true; nickFoundOnIgnoreList = true;
} }
} }
if(!nickFoundOnIgnoreList) { if(!nickFoundOnIgnoreList) {
if(message.indexOf(QString("/me "))==0) { if(message.indexOf(QString("/me "))==0) {
myTextBrowser->append(tempMsg.replace("/me ","<i>*"+playerName+" ")+"</i>"); myTextBrowser->append(tempMsg.replace("/me ","<i>*"+playerName+" ")+"</i>");
} } else {
else { myTextBrowser->append(playerName + ": " + tempMsg);
myTextBrowser->append(playerName + ": " + tempMsg); }
} }
} }
}
} }
void ChatTools::clearChat() { void ChatTools::clearChat()
{
if(myTextBrowser) if(myTextBrowser)
myTextBrowser->clear(); myTextBrowser->clear();
} }
void ChatTools::checkInputLength(QString string) { void ChatTools::checkInputLength(QString string)
{
if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length()); if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length());
} }
void ChatTools::fillChatLinesHistory(QString fillString) { void ChatTools::fillChatLinesHistory(QString fillString)
{
chatLinesHistory << fillString; chatLinesHistory << fillString;
if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst(); if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst();
} }
void ChatTools::showChatHistoryIndex(int index) { void ChatTools::showChatHistoryIndex(int index)
{
if(index <= chatLinesHistory.size()) { if(index <= chatLinesHistory.size()) {
// cout << chatLinesHistory.size() << " : " << index << endl; // cout << chatLinesHistory.size() << " : " << index << endl;
if(index > 0) if(index > 0)
myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index))); myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index)));
else else
myLineEdit->setText(""); myLineEdit->setText("");
} }
} }
void ChatTools::nickAutoCompletition() { void ChatTools::nickAutoCompletition()
{
QString myChatString = myLineEdit->text(); QString myChatString = myLineEdit->text();
QStringList myChatStringList = myChatString.split(" "); QStringList myChatStringList = myChatString.split(" ");
QStringList matchStringList; QStringList matchStringList;
if(nickAutoCompletitionCounter == 0) { if(nickAutoCompletitionCounter == 0) {
if(myNickListModel) { if(myNickListModel) {
int it = 0; int it = 0;
while (myNickListModel->item(it)) { while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString(); QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") { if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") {
matchStringList << text; matchStringList << text;
} }
++it; ++it;
} }
} }
if(!myNickStringList.isEmpty()) { if(!myNickStringList.isEmpty()) {
QStringListIterator it(myNickStringList); QStringListIterator it(myNickStringList);
while (it.hasNext()) { while (it.hasNext()) {
QString next = it.next(); QString next = it.next();
if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "")
matchStringList << next; matchStringList << next;
} }
} }
} }
if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) { if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) {
myChatStringList.removeLast(); myChatStringList.removeLast();
// cout << nickAutoCompletitionCounter << endl; // cout << nickAutoCompletitionCounter << endl;
if(nickAutoCompletitionCounter == 0) { if(nickAutoCompletitionCounter == 0) {
//first one //first one
lastChatString = myChatStringList.join(" "); lastChatString = myChatStringList.join(" ");
lastMatchStringList = matchStringList; lastMatchStringList = matchStringList;
} }
if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0; if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0;
// cout << nickAutoCompletitionCounter << "\n"; // cout << nickAutoCompletitionCounter << "\n";
if(lastChatString == "") if(lastChatString == "")
myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": "); myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": ");
else else
myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" "); myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" ");
nickAutoCompletitionCounter++; nickAutoCompletitionCounter++;
} }
} }
void ChatTools::setChatTextEdited() { void ChatTools::setChatTextEdited()
{
nickAutoCompletitionCounter = 0; nickAutoCompletitionCounter = 0;
} }
void ChatTools::refreshIgnoreList() void ChatTools::refreshIgnoreList()
{ {
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList"); ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
} }
+45 -33
View File
@@ -34,58 +34,70 @@ class gameLobbyDialogImpl;
class ChatTools : public QObject class ChatTools : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
ChatTools(QLineEdit*, ConfigFile*, ChatType, QTextBrowser *b = NULL, QStandardItemModel *m = NULL, gameLobbyDialogImpl *lo = NULL); ChatTools(QLineEdit*, ConfigFile*, ChatType, QTextBrowser *b = NULL, QStandardItemModel *m = NULL, gameLobbyDialogImpl *lo = NULL);
~ChatTools(); ~ChatTools();
void setSession(boost::shared_ptr<Session> session) { mySession = session; } void setSession(boost::shared_ptr<Session> session) {
mySession = session;
}
public slots: public slots:
void sendMessage(); void sendMessage();
void receiveMessage(QString playerName, QString message); void receiveMessage(QString playerName, QString message);
void clearChat(); void clearChat();
void checkInputLength(QString string); void checkInputLength(QString string);
void fillChatLinesHistory(QString fillString); void fillChatLinesHistory(QString fillString);
void showChatHistoryIndex(int index); void showChatHistoryIndex(int index);
int getChatLinesHistorySize() { return chatLinesHistory.size(); } int getChatLinesHistorySize() {
return chatLinesHistory.size();
}
void nickAutoCompletition(); void nickAutoCompletition();
void setChatTextEdited(); void setChatTextEdited();
void setPlayerNicksList(QStringList value) { myNickStringList = value; } void setPlayerNicksList(QStringList value) {
void setMyNick ( const QString& theValue ) { myNick = theValue; } myNickStringList = value;
QString getMyNick () { return myNick; } }
void setMyNick ( const QString& theValue ) {
myNick = theValue;
}
QString getMyNick () {
return myNick;
}
void setMyStyle ( GameTableStyleReader* theValue ) { myStyle = theValue; } void setMyStyle ( GameTableStyleReader* theValue ) {
void refreshIgnoreList(); myStyle = theValue;
}
void refreshIgnoreList();
private: private:
QStringList chatLinesHistory; QStringList chatLinesHistory;
QString lastChatString; QString lastChatString;
QStringList lastMatchStringList; QStringList lastMatchStringList;
int nickAutoCompletitionCounter; int nickAutoCompletitionCounter;
QLineEdit *myLineEdit; QLineEdit *myLineEdit;
QStandardItemModel *myNickListModel; QStandardItemModel *myNickListModel;
QStringList myNickStringList; QStringList myNickStringList;
QTextBrowser *myTextBrowser; QTextBrowser *myTextBrowser;
boost::shared_ptr<Session> mySession; boost::shared_ptr<Session> mySession;
ChatType myChatType; ChatType myChatType;
ConfigFile *myConfig; ConfigFile *myConfig;
QString myNick; QString myNick;
GameTableStyleReader *myStyle; GameTableStyleReader *myStyle;
gameLobbyDialogImpl *myLobby; gameLobbyDialogImpl *myLobby;
std::list<std::string> ignoreList; std::list<std::string> ignoreList;
}; };
#endif #endif
@@ -21,13 +21,13 @@
#include <net/socket_msg.h> #include <net/socket_msg.h>
connectToServerDialogImpl::connectToServerDialogImpl(QWidget *parent) connectToServerDialogImpl::connectToServerDialogImpl(QWidget *parent)
: QDialog(parent) : QDialog(parent)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog); setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog);
#endif #endif
setupUi(this); setupUi(this);
} }
void connectToServerDialogImpl::exec() void connectToServerDialogImpl::exec()
@@ -38,26 +38,37 @@ void connectToServerDialogImpl::exec()
QDialog::exec(); QDialog::exec();
} }
void connectToServerDialogImpl::refresh(int actionID) { void connectToServerDialogImpl::refresh(int actionID)
{
bool skip = false; bool skip = false;
switch (actionID) { switch (actionID) {
case MSG_SOCK_INIT_DONE: { label_actionMessage->setText(tr("Resolving address...")); } case MSG_SOCK_INIT_DONE: {
break; label_actionMessage->setText(tr("Resolving address..."));
case MSG_SOCK_SERVER_LIST_DONE : { label_actionMessage->setText(tr("Reading server list...")); } }
break; break;
case MSG_SOCK_RESOLVE_DONE: { label_actionMessage->setText(tr("Connecting to server...")); } case MSG_SOCK_SERVER_LIST_DONE : {
break; label_actionMessage->setText(tr("Reading server list..."));
case MSG_SOCK_CONNECT_DONE: { label_actionMessage->setText(tr("Starting session...")); } }
break; break;
case MSG_SOCK_SESSION_DONE: { label_actionMessage->setText(tr("Connection established!")); } case MSG_SOCK_RESOLVE_DONE: {
break; label_actionMessage->setText(tr("Connecting to server..."));
default: skip = true; }
break;
case MSG_SOCK_CONNECT_DONE: {
label_actionMessage->setText(tr("Starting session..."));
}
break;
case MSG_SOCK_SESSION_DONE: {
label_actionMessage->setText(tr("Connection established!"));
}
break;
default:
skip = true;
} }
if (!skip) if (!skip) {
{
progressBar->setValue(actionID*(100/MSG_SOCK_LIMIT_CONNECT)); progressBar->setValue(actionID*(100/MSG_SOCK_LIMIT_CONNECT));
if (actionID == MSG_SOCK_LIMIT_CONNECT) if (actionID == MSG_SOCK_LIMIT_CONNECT)
@@ -26,10 +26,11 @@
#include <QtCore> #include <QtCore>
class connectToServerDialogImpl: public QDialog, public Ui::connectToServerDialog { class connectToServerDialogImpl: public QDialog, public Ui::connectToServerDialog
Q_OBJECT {
Q_OBJECT
public: public:
connectToServerDialogImpl(QWidget *parent = 0); connectToServerDialogImpl(QWidget *parent = 0);
void exec(); void exec();
@@ -25,54 +25,58 @@
createInternetGameDialogImpl::createInternetGameDialogImpl(QWidget *parent, ConfigFile *c) createInternetGameDialogImpl::createInternetGameDialogImpl(QWidget *parent, ConfigFile *c)
: QDialog(parent), myConfig(c), currentGuestMode(false), currentPlayerName("") : QDialog(parent), myConfig(c), currentGuestMode(false), currentPlayerName("")
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog); setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog);
#endif #endif
setupUi(this); setupUi(this);
comboBox_gameType->setItemData(0, GAME_TYPE_NORMAL, Qt::UserRole); comboBox_gameType->setItemData(0, GAME_TYPE_NORMAL, Qt::UserRole);
comboBox_gameType->setItemData(1, GAME_TYPE_REGISTERED_ONLY, Qt::UserRole); comboBox_gameType->setItemData(1, GAME_TYPE_REGISTERED_ONLY, Qt::UserRole);
comboBox_gameType->setItemData(2, GAME_TYPE_INVITE_ONLY, Qt::UserRole); comboBox_gameType->setItemData(2, GAME_TYPE_INVITE_ONLY, Qt::UserRole);
comboBox_gameType->setItemData(3, GAME_TYPE_RANKING, Qt::UserRole); comboBox_gameType->setItemData(3, GAME_TYPE_RANKING, Qt::UserRole);
myChangeCompleteBlindsDialog = new changeCompleteBlindsDialogImpl; myChangeCompleteBlindsDialog = new changeCompleteBlindsDialogImpl;
startBlind = new QLabel(tr("<i>First small blind: $%1</i>").arg(RANKING_GAME_START_SBLIND)); startBlind = new QLabel(tr("<i>First small blind: $%1</i>").arg(RANKING_GAME_START_SBLIND));
raiseMode = new QLabel(tr("<i>Double blinds every %1'th hand</i>").arg(RANKING_GAME_RAISE_EVERY_HAND)); raiseMode = new QLabel(tr("<i>Double blinds every %1'th hand</i>").arg(RANKING_GAME_RAISE_EVERY_HAND));
startBlind->hide(); startBlind->hide();
raiseMode->hide(); raiseMode->hide();
gridLayout1->addWidget(startBlind, 0, 0, 1, 1); gridLayout1->addWidget(startBlind, 0, 0, 1, 1);
gridLayout1->addWidget(raiseMode, 1, 0, 1, 1); gridLayout1->addWidget(raiseMode, 1, 0, 1, 1);
connect( radioButton_changeBlindsSettings, SIGNAL( clicked(bool) ), this, SLOT( callChangeBlindsDialog(bool) ) ); connect( radioButton_changeBlindsSettings, SIGNAL( clicked(bool) ), this, SLOT( callChangeBlindsDialog(bool) ) );
connect( pushButton_cancel, SIGNAL( clicked() ), this, SLOT( cancel() ) ); connect( pushButton_cancel, SIGNAL( clicked() ), this, SLOT( cancel() ) );
connect( pushButton_createGame, SIGNAL( clicked() ), this, SLOT( createGame() ) ); connect( pushButton_createGame, SIGNAL( clicked() ), this, SLOT( createGame() ) );
connect( checkBox_Password, SIGNAL( toggled(bool) ), this, SLOT( clearGamePassword(bool)) ); connect( checkBox_Password, SIGNAL( toggled(bool) ), this, SLOT( clearGamePassword(bool)) );
connect( comboBox_gameType, SIGNAL(currentIndexChanged(int)), this, SLOT( gameTypeChanged() ) ); connect( comboBox_gameType, SIGNAL(currentIndexChanged(int)), this, SLOT( gameTypeChanged() ) );
} }
void createInternetGameDialogImpl::exec(bool guestMode, QString playerName) { void createInternetGameDialogImpl::exec(bool guestMode, QString playerName)
{
currentGuestMode = guestMode; currentGuestMode = guestMode;
currentPlayerName = playerName; currentPlayerName = playerName;
fillFormular(guestMode, playerName); fillFormular(guestMode, playerName);
QDialog::exec(); QDialog::exec();
} }
void createInternetGameDialogImpl::createGame() { void createInternetGameDialogImpl::createGame()
{
} }
void createInternetGameDialogImpl::cancel() { void createInternetGameDialogImpl::cancel()
{
} }
void createInternetGameDialogImpl::fillFormular(bool guestMode, QString playerName) { void createInternetGameDialogImpl::fillFormular(bool guestMode, QString playerName)
{
//Network Game Settings //Network Game Settings
spinBox_netDelayBetweenHands->setValue(myConfig->readConfigInt("NetDelayBetweenHands")); spinBox_netDelayBetweenHands->setValue(myConfig->readConfigInt("NetDelayBetweenHands"));
@@ -83,36 +87,42 @@ void createInternetGameDialogImpl::fillFormular(bool guestMode, QString playerNa
} }
if(guestMode) { if(guestMode) {
comboBox_gameType->setCurrentIndex(0); comboBox_gameType->setCurrentIndex(0);
comboBox_gameType->setDisabled(true); comboBox_gameType->setDisabled(true);
lineEdit_gameName->setText(tr("%1's game").arg(playerName)); lineEdit_gameName->setText(tr("%1's game").arg(playerName));
lineEdit_gameName->setDisabled(true); lineEdit_gameName->setDisabled(true);
} } else {
else { comboBox_gameType->setDisabled(false);
comboBox_gameType->setDisabled(false); comboBox_gameType->setCurrentIndex(myConfig->readConfigInt("InternetGameType"));
comboBox_gameType->setCurrentIndex(myConfig->readConfigInt("InternetGameType")); lineEdit_gameName->setDisabled(false);
lineEdit_gameName->setDisabled(false); lineEdit_gameName->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str()));
lineEdit_gameName->setText(QString::fromUtf8(myConfig->readConfigString("InternetGameName").c_str())); }
}
gameTypeChanged(); gameTypeChanged();
} }
void createInternetGameDialogImpl::keyPressEvent ( QKeyEvent * event ) { void createInternetGameDialogImpl::keyPressEvent ( QKeyEvent * event )
{
if (event->key() == 16777220) { pushButton_createGame->click(); } //ENTER if (event->key() == 16777220) {
pushButton_createGame->click(); //ENTER
}
} }
void createInternetGameDialogImpl::clearGamePassword(bool clear) { void createInternetGameDialogImpl::clearGamePassword(bool clear)
{
if(!clear) { lineEdit_Password->clear(); } if(!clear) {
lineEdit_Password->clear();
}
} }
void createInternetGameDialogImpl::callChangeBlindsDialog(bool show) { void createInternetGameDialogImpl::callChangeBlindsDialog(bool show)
{
if(show) { if(show) {
myChangeCompleteBlindsDialog->exec(); myChangeCompleteBlindsDialog->exec();
@@ -124,100 +134,100 @@ void createInternetGameDialogImpl::callChangeBlindsDialog(bool show) {
} }
} }
void createInternetGameDialogImpl::gameTypeChanged() { void createInternetGameDialogImpl::gameTypeChanged()
{
switch (comboBox_gameType->currentIndex()) { switch (comboBox_gameType->currentIndex()) {
case GAME_TYPE_NORMAL-1: { case GAME_TYPE_NORMAL-1: {
checkBox_Password->setDisabled(FALSE); checkBox_Password->setDisabled(FALSE);
spinBox_startCash->setDisabled(FALSE); spinBox_startCash->setDisabled(FALSE);
spinBox_quantityPlayers->setDisabled(FALSE); spinBox_quantityPlayers->setDisabled(FALSE);
spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers")); spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers"));
spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash")); spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash"));
radioButton_useSavedBlindsSettings->show(); radioButton_useSavedBlindsSettings->show();
radioButton_changeBlindsSettings->show(); radioButton_changeBlindsSettings->show();
startBlind->hide(); startBlind->hide();
raiseMode->hide(); raiseMode->hide();
} }
break; break;
case GAME_TYPE_REGISTERED_ONLY-1: { case GAME_TYPE_REGISTERED_ONLY-1: {
checkBox_Password->setDisabled(FALSE); checkBox_Password->setDisabled(FALSE);
spinBox_startCash->setDisabled(FALSE); spinBox_startCash->setDisabled(FALSE);
spinBox_quantityPlayers->setDisabled(FALSE); spinBox_quantityPlayers->setDisabled(FALSE);
spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers")); spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers"));
spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash")); spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash"));
radioButton_useSavedBlindsSettings->show(); radioButton_useSavedBlindsSettings->show();
radioButton_changeBlindsSettings->show(); radioButton_changeBlindsSettings->show();
startBlind->hide(); startBlind->hide();
raiseMode->hide(); raiseMode->hide();
} }
break; break;
case GAME_TYPE_INVITE_ONLY-1: { case GAME_TYPE_INVITE_ONLY-1: {
checkBox_Password->setChecked(FALSE); checkBox_Password->setChecked(FALSE);
checkBox_Password->setDisabled(TRUE); checkBox_Password->setDisabled(TRUE);
spinBox_startCash->setDisabled(FALSE); spinBox_startCash->setDisabled(FALSE);
spinBox_quantityPlayers->setDisabled(FALSE); spinBox_quantityPlayers->setDisabled(FALSE);
spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers")); spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers"));
spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash")); spinBox_startCash->setValue(myConfig->readConfigInt("NetStartCash"));
radioButton_useSavedBlindsSettings->show(); radioButton_useSavedBlindsSettings->show();
radioButton_changeBlindsSettings->show(); radioButton_changeBlindsSettings->show();
startBlind->hide(); startBlind->hide();
raiseMode->hide(); raiseMode->hide();
} }
break; break;
case GAME_TYPE_RANKING-1: { case GAME_TYPE_RANKING-1: {
checkBox_Password->setChecked(FALSE); checkBox_Password->setChecked(FALSE);
checkBox_Password->setDisabled(TRUE); checkBox_Password->setDisabled(TRUE);
spinBox_startCash->setValue(RANKING_GAME_START_CASH); spinBox_startCash->setValue(RANKING_GAME_START_CASH);
spinBox_startCash->setDisabled(TRUE); spinBox_startCash->setDisabled(TRUE);
spinBox_quantityPlayers->setValue(RANKING_GAME_NUMBER_OF_PLAYERS); spinBox_quantityPlayers->setValue(RANKING_GAME_NUMBER_OF_PLAYERS);
spinBox_quantityPlayers->setDisabled(TRUE); spinBox_quantityPlayers->setDisabled(TRUE);
radioButton_useSavedBlindsSettings->hide(); radioButton_useSavedBlindsSettings->hide();
radioButton_changeBlindsSettings->hide(); radioButton_changeBlindsSettings->hide();
startBlind->show(); startBlind->show();
raiseMode->show(); raiseMode->show();
} }
break; break;
} }
if(comboBox_gameType->currentIndex() == GAME_TYPE_RANKING-1) { if(comboBox_gameType->currentIndex() == GAME_TYPE_RANKING-1) {
//set static values //set static values
myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->setValue(RANKING_GAME_START_SBLIND); myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->setValue(RANKING_GAME_START_SBLIND);
myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtHands->setChecked(TRUE); myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtHands->setChecked(TRUE);
myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtMinutes->setChecked(FALSE); myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtMinutes->setChecked(FALSE);
myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryHands->setValue(11); myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryHands->setValue(11);
myChangeCompleteBlindsDialog->radioButton_alwaysDoubleBlinds->setChecked(TRUE); myChangeCompleteBlindsDialog->radioButton_alwaysDoubleBlinds->setChecked(TRUE);
myChangeCompleteBlindsDialog->radioButton_manualBlindsOrder->setChecked(FALSE); myChangeCompleteBlindsDialog->radioButton_manualBlindsOrder->setChecked(FALSE);
myChangeCompleteBlindsDialog->listWidget_blinds->clear(); myChangeCompleteBlindsDialog->listWidget_blinds->clear();
} } else {
else { //read config values
//read config values myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->setValue(myConfig->readConfigInt("NetFirstSmallBlind"));
myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->setValue(myConfig->readConfigInt("NetFirstSmallBlind")); myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtHands->setChecked(myConfig->readConfigInt("NetRaiseBlindsAtHands"));
myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtHands->setChecked(myConfig->readConfigInt("NetRaiseBlindsAtHands")); myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtMinutes->setChecked(myConfig->readConfigInt("NetRaiseBlindsAtMinutes"));
myChangeCompleteBlindsDialog->radioButton_raiseBlindsAtMinutes->setChecked(myConfig->readConfigInt("NetRaiseBlindsAtMinutes")); myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryHands->setValue(myConfig->readConfigInt("NetRaiseSmallBlindEveryHands"));
myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryHands->setValue(myConfig->readConfigInt("NetRaiseSmallBlindEveryHands")); myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryMinutes->setValue(myConfig->readConfigInt("NetRaiseSmallBlindEveryMinutes"));
myChangeCompleteBlindsDialog->spinBox_raiseSmallBlindEveryMinutes->setValue(myConfig->readConfigInt("NetRaiseSmallBlindEveryMinutes")); myChangeCompleteBlindsDialog->radioButton_alwaysDoubleBlinds->setChecked(myConfig->readConfigInt("NetAlwaysDoubleBlinds"));
myChangeCompleteBlindsDialog->radioButton_alwaysDoubleBlinds->setChecked(myConfig->readConfigInt("NetAlwaysDoubleBlinds")); myChangeCompleteBlindsDialog->radioButton_manualBlindsOrder->setChecked(myConfig->readConfigInt("NetManualBlindsOrder"));
myChangeCompleteBlindsDialog->radioButton_manualBlindsOrder->setChecked(myConfig->readConfigInt("NetManualBlindsOrder"));
myChangeCompleteBlindsDialog->listWidget_blinds->clear(); myChangeCompleteBlindsDialog->listWidget_blinds->clear();
myChangeCompleteBlindsDialog->spinBox_input->setMinimum(myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->value()+1); myChangeCompleteBlindsDialog->spinBox_input->setMinimum(myChangeCompleteBlindsDialog->spinBox_firstSmallBlind->value()+1);
std::list<int> myBlindsList = myConfig->readConfigIntList("NetManualBlindsList"); std::list<int> myBlindsList = myConfig->readConfigIntList("NetManualBlindsList");
std::list<int>::iterator it1; std::list<int>::iterator it1;
for(it1= myBlindsList.begin(); it1 != myBlindsList.end(); ++it1) { for(it1= myBlindsList.begin(); it1 != myBlindsList.end(); ++it1) {
myChangeCompleteBlindsDialog->listWidget_blinds->addItem(QString::number(*it1,10)); myChangeCompleteBlindsDialog->listWidget_blinds->addItem(QString::number(*it1,10));
} }
myChangeCompleteBlindsDialog->sortBlindsList(); myChangeCompleteBlindsDialog->sortBlindsList();
myChangeCompleteBlindsDialog->radioButton_afterThisAlwaysDoubleBlinds->setChecked(myConfig->readConfigInt("NetAfterMBAlwaysDoubleBlinds")); myChangeCompleteBlindsDialog->radioButton_afterThisAlwaysDoubleBlinds->setChecked(myConfig->readConfigInt("NetAfterMBAlwaysDoubleBlinds"));
myChangeCompleteBlindsDialog->radioButton_afterThisAlwaysRaiseAbout->setChecked(myConfig->readConfigInt("NetAfterMBAlwaysRaiseAbout")); myChangeCompleteBlindsDialog->radioButton_afterThisAlwaysRaiseAbout->setChecked(myConfig->readConfigInt("NetAfterMBAlwaysRaiseAbout"));
myChangeCompleteBlindsDialog->spinBox_afterThisAlwaysRaiseValue->setValue(myConfig->readConfigInt("NetAfterMBAlwaysRaiseValue")); myChangeCompleteBlindsDialog->spinBox_afterThisAlwaysRaiseValue->setValue(myConfig->readConfigInt("NetAfterMBAlwaysRaiseValue"));
myChangeCompleteBlindsDialog->radioButton_afterThisStayAtLastBlind->setChecked(myConfig->readConfigInt("NetAfterMBStayAtLastBlind")); myChangeCompleteBlindsDialog->radioButton_afterThisStayAtLastBlind->setChecked(myConfig->readConfigInt("NetAfterMBStayAtLastBlind"));
} }
} }
@@ -29,32 +29,35 @@ class Session;
class ConfigFile; class ConfigFile;
class changeCompleteBlindsDialogImpl; class changeCompleteBlindsDialogImpl;
class createInternetGameDialogImpl: public QDialog, public Ui::createInternetGameDialog { class createInternetGameDialogImpl: public QDialog, public Ui::createInternetGameDialog
Q_OBJECT {
Q_OBJECT
public: public:
createInternetGameDialogImpl(QWidget *parent = 0, ConfigFile *c = 0); createInternetGameDialogImpl(QWidget *parent = 0, ConfigFile *c = 0);
void exec(bool guestMode, QString playerName); void exec(bool guestMode, QString playerName);
changeCompleteBlindsDialogImpl* getChangeCompleteBlindsDialog() { return myChangeCompleteBlindsDialog; } changeCompleteBlindsDialogImpl* getChangeCompleteBlindsDialog() {
return myChangeCompleteBlindsDialog;
}
public slots: public slots:
void createGame(); void createGame();
void cancel(); void cancel();
void fillFormular(bool guestMode, QString playerName); void fillFormular(bool guestMode, QString playerName);
void keyPressEvent ( QKeyEvent * event ); void keyPressEvent ( QKeyEvent * event );
void clearGamePassword(bool); void clearGamePassword(bool);
void gameTypeChanged(); void gameTypeChanged();
void callChangeBlindsDialog(bool); void callChangeBlindsDialog(bool);
private: private:
ConfigFile *myConfig; ConfigFile *myConfig;
changeCompleteBlindsDialogImpl *myChangeCompleteBlindsDialog; changeCompleteBlindsDialogImpl *myChangeCompleteBlindsDialog;
bool currentGuestMode; bool currentGuestMode;
QString currentPlayerName; QString currentPlayerName;
QLabel *startBlind; QLabel *startBlind;
QLabel *raiseMode; QLabel *raiseMode;
}; };
@@ -23,13 +23,13 @@
#include "changecompleteblindsdialogimpl.h" #include "changecompleteblindsdialogimpl.h"
createNetworkGameDialogImpl::createNetworkGameDialogImpl(QWidget *parent, ConfigFile *c) createNetworkGameDialogImpl::createNetworkGameDialogImpl(QWidget *parent, ConfigFile *c)
: QDialog(parent), myConfig(c) : QDialog(parent), myConfig(c)
{ {
#ifdef __APPLE__ #ifdef __APPLE__
setWindowModality(Qt::ApplicationModal); setWindowModality(Qt::ApplicationModal);
setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog); setWindowFlags(Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint | Qt::Dialog);
#endif #endif
setupUi(this); setupUi(this);
myChangeCompleteBlindsDialog = new changeCompleteBlindsDialogImpl; myChangeCompleteBlindsDialog = new changeCompleteBlindsDialogImpl;
@@ -47,21 +47,25 @@ createNetworkGameDialogImpl::createNetworkGameDialogImpl(QWidget *parent, Config
} }
void createNetworkGameDialogImpl::exec() { void createNetworkGameDialogImpl::exec()
{
fillFormular(); fillFormular();
QDialog::exec(); QDialog::exec();
} }
void createNetworkGameDialogImpl::createGame() { void createNetworkGameDialogImpl::createGame()
{
} }
void createNetworkGameDialogImpl::cancel() { void createNetworkGameDialogImpl::cancel()
{
} }
void createNetworkGameDialogImpl::fillFormular() { void createNetworkGameDialogImpl::fillFormular()
{
//Network Game Settings //Network Game Settings
spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers")); spinBox_quantityPlayers->setValue(myConfig->readConfigInt("NetNumberOfPlayers"));
@@ -95,20 +99,25 @@ void createNetworkGameDialogImpl::fillFormular() {
myChangeCompleteBlindsDialog->radioButton_afterThisStayAtLastBlind->setChecked(myConfig->readConfigInt("NetAfterMBStayAtLastBlind")); myChangeCompleteBlindsDialog->radioButton_afterThisStayAtLastBlind->setChecked(myConfig->readConfigInt("NetAfterMBStayAtLastBlind"));
} }
void createNetworkGameDialogImpl::showDialog() { void createNetworkGameDialogImpl::showDialog()
{
fillFormular(); fillFormular();
exec(); exec();
} }
void createNetworkGameDialogImpl::keyPressEvent ( QKeyEvent * event ) { void createNetworkGameDialogImpl::keyPressEvent ( QKeyEvent * event )
{
if (event->key() == 16777220) { pushButton_createGame->click(); } //ENTER if (event->key() == 16777220) {
pushButton_createGame->click(); //ENTER
}
} }
void createNetworkGameDialogImpl::callChangeBlindsDialog(bool show) { void createNetworkGameDialogImpl::callChangeBlindsDialog(bool show)
{
if(show) { if(show) {
myChangeCompleteBlindsDialog->exec(); myChangeCompleteBlindsDialog->exec();
@@ -30,13 +30,16 @@ class ConfigFile;
class changeCompleteBlindsDialogImpl; class changeCompleteBlindsDialogImpl;
class createNetworkGameDialogImpl: public QDialog, public Ui::createNetworkGameDialog { class createNetworkGameDialogImpl: public QDialog, public Ui::createNetworkGameDialog
Q_OBJECT {
Q_OBJECT
public: public:
createNetworkGameDialogImpl(QWidget *parent = 0, ConfigFile *c = 0); createNetworkGameDialogImpl(QWidget *parent = 0, ConfigFile *c = 0);
void exec(); void exec();
changeCompleteBlindsDialogImpl* getChangeCompleteBlindsDialog() { return myChangeCompleteBlindsDialog; } changeCompleteBlindsDialogImpl* getChangeCompleteBlindsDialog() {
return myChangeCompleteBlindsDialog;
}
public slots: public slots:
File diff suppressed because it is too large. Load diff
+125 -111
View File
@@ -35,134 +35,148 @@ class MyNickListSortFilterProxyModel;
@author FThauer FHammer <webmaster@pokerth.net> @author FThauer FHammer <webmaster@pokerth.net>
*/ */
class gameLobbyDialogImpl: public QDialog, public Ui::gameLobbyDialog { class gameLobbyDialogImpl: public QDialog, public Ui::gameLobbyDialog
Q_OBJECT {
Q_OBJECT
public: public:
gameLobbyDialogImpl(startWindowImpl *parent = 0, ConfigFile* = 0); gameLobbyDialogImpl(startWindowImpl *parent = 0, ConfigFile* = 0);
~gameLobbyDialogImpl(); ~gameLobbyDialogImpl();
void exec(); void exec();
ChatTools *getMyChat() { return myChat; } ChatTools *getMyChat() {
return myChat;
}
void setSession(boost::shared_ptr<Session> session); void setSession(boost::shared_ptr<Session> session);
boost::shared_ptr<Session> getSession() { assert(mySession.get()); return mySession; } boost::shared_ptr<Session> getSession() {
assert(mySession.get());
return mySession;
}
void setMyW ( gameTableImpl* theValue ) { myW = theValue; } void setMyW ( gameTableImpl* theValue ) {
myW = theValue;
}
public slots: public slots:
void createGame(); void createGame();
void joinGame(); void joinGame();
void joinAnyGame(); void joinAnyGame();
void gameSelected(const QModelIndex &); void gameSelected(const QModelIndex &);
void updateGameItem(QList <QStandardItem*>, unsigned gameId); void updateGameItem(QList <QStandardItem*>, unsigned gameId);
void addGame(unsigned gameId); void addGame(unsigned gameId);
void updateGameMode(unsigned gameId, int newMode); void updateGameMode(unsigned gameId, int newMode);
void updateGameAdmin(unsigned gameId, unsigned adminPlayerId); void updateGameAdmin(unsigned gameId, unsigned adminPlayerId);
void removeGame(unsigned gameId); void removeGame(unsigned gameId);
void gameAddPlayer(unsigned gameId, unsigned playerId); void gameAddPlayer(unsigned gameId, unsigned playerId);
void gameRemovePlayer(unsigned gameId, unsigned playerId); void gameRemovePlayer(unsigned gameId, unsigned playerId);
void playerJoinedLobby(unsigned playerId, QString playerName); void playerJoinedLobby(unsigned playerId, QString playerName);
void playerLeftLobby(unsigned playerId); void playerLeftLobby(unsigned playerId);
void updateStats(ServerStats stats); void updateStats(ServerStats stats);
void refreshGameStats(); void refreshGameStats();
void refreshPlayerStats(); void refreshPlayerStats();
void setCurrentGameName ( const QString& theValue ) { currentGameName = theValue; } void setCurrentGameName ( const QString& theValue ) {
QString getCurrentGameName() const { return currentGameName; } currentGameName = theValue;
gameTableImpl* getMyW() const { return myW; } }
void checkPlayerQuantity(); QString getCurrentGameName() const {
void blinkingStartButtonAnimation(); return currentGameName;
void joinedNetworkGame(unsigned, QString, bool); }
void addConnectedPlayer(unsigned, QString, bool); gameTableImpl* getMyW() const {
void updatePlayer(unsigned, QString); return myW;
void removePlayer(unsigned, QString); }
void newGameAdmin(unsigned, QString); void checkPlayerQuantity();
void refreshConnectedPlayerAvatars(); void blinkingStartButtonAnimation();
void playerSelected(QTreeWidgetItem*, QTreeWidgetItem*); void joinedNetworkGame(unsigned, QString, bool);
void refresh(int actionID); void addConnectedPlayer(unsigned, QString, bool);
void removedFromGame(int reason); void updatePlayer(unsigned, QString);
void startGame(); void removePlayer(unsigned, QString);
void leaveGame(); void newGameAdmin(unsigned, QString);
void kickPlayer(); void refreshConnectedPlayerAvatars();
void joinedGameDialogUpdate(); void playerSelected(QTreeWidgetItem*, QTreeWidgetItem*);
void leftGameDialogUpdate(); void refresh(int actionID);
void updateDialogBlinds(const GameData &gameData); void removedFromGame(int reason);
void clearDialog(); void startGame();
void keyPressEvent(QKeyEvent * keyEvent); void leaveGame();
bool event(QEvent * event); void kickPlayer();
void showGameDescription(bool show); void joinedGameDialogUpdate();
void showWaitStartGameMsgBox(); void leftGameDialogUpdate();
void joinAnyGameButtonRefresh(); void updateDialogBlinds(const GameData &gameData);
void reject(); void clearDialog();
void closeEvent(QCloseEvent *event); void keyPressEvent(QKeyEvent * keyEvent);
void writeDialogSettings(int); bool event(QEvent * event);
void readDialogSettings(); void showGameDescription(bool show);
void changeGameListFilter(int); void showWaitStartGameMsgBox();
void changeNickListFilter(int); void joinAnyGameButtonRefresh();
void changeGameListSorting(); void reject();
void registeredUserMode(); void closeEvent(QCloseEvent *event);
void guestUserMode(); void writeDialogSettings(int);
void showNickListContextMenu(QPoint); void readDialogSettings();
void invitePlayerToCurrentGame(); void changeGameListFilter(int);
void showInfoMsgBox(); void changeNickListFilter(int);
void showInvitationDialog(unsigned gameId, unsigned playerIdFrom); void changeGameListSorting();
void chatInfoPlayerInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom); void registeredUserMode();
void chatInfoPlayerRejectedInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason); void guestUserMode();
void putPlayerOnIgnoreList(); void showNickListContextMenu(QPoint);
bool playerIsOnIgnoreList(unsigned playerid); void invitePlayerToCurrentGame();
void searchForPlayerRegExpChanged(); void showInfoMsgBox();
void showAutoStartTimer(); void showInvitationDialog(unsigned gameId, unsigned playerIdFrom);
void updateAutoStartTimer(); void chatInfoPlayerInvitation(unsigned gameId, unsigned playerIdWho, unsigned playerIdFrom);
void chatInfoPlayerRejectedInvitation(unsigned gameId, unsigned playerIdWho, DenyGameInvitationReason reason);
void putPlayerOnIgnoreList();
bool playerIsOnIgnoreList(unsigned playerid);
void searchForPlayerRegExpChanged();
void showAutoStartTimer();
void updateAutoStartTimer();
private: private:
gameTableImpl* myW; gameTableImpl* myW;
startWindowImpl* myStartWindow; startWindowImpl* myStartWindow;
ConfigFile *myConfig; ConfigFile *myConfig;
boost::shared_ptr<Session> mySession; boost::shared_ptr<Session> mySession;
createInternetGameDialogImpl *myCreateInternetGameDialog; createInternetGameDialogImpl *myCreateInternetGameDialog;
QString currentGameName; QString currentGameName;
unsigned myPlayerId; unsigned myPlayerId;
bool isGameAdministrator; bool isGameAdministrator;
bool inGame; bool inGame;
bool guestMode; bool guestMode;
QString myAppDataPath; QString myAppDataPath;
QMessageBox *waitStartGameMsgBox; QMessageBox *waitStartGameMsgBox;
QTimer *waitStartGameMsgBoxTimer; QTimer *waitStartGameMsgBoxTimer;
QTimer *blinkingButtonAnimationTimer; QTimer *blinkingButtonAnimationTimer;
QTimer *showInfoMsgBoxTimer; QTimer *showInfoMsgBoxTimer;
QTimer *autoStartTimer; QTimer *autoStartTimer;
bool blinkingButtonAnimationState; bool blinkingButtonAnimationState;
QColor defaultStartButtonColor; QColor defaultStartButtonColor;
QColor defaultStartButtonTextColor; QColor defaultStartButtonTextColor;
QColor disabledStartButtonColor; QColor disabledStartButtonColor;
QColor disabledStartButtonTextColor; QColor disabledStartButtonTextColor;
ChatTools *myChat; ChatTools *myChat;
int keyUpCounter; int keyUpCounter;
QStandardItemModel *myGameListModel; QStandardItemModel *myGameListModel;
QItemSelectionModel *myGameListSelectionModel; QItemSelectionModel *myGameListSelectionModel;
MyGameListSortFilterProxyModel *myGameListSortFilterProxyModel; MyGameListSortFilterProxyModel *myGameListSortFilterProxyModel;
QMenu *nickListContextMenu; QMenu *nickListContextMenu;
QAction *nickListInviteAction; QAction *nickListInviteAction;
QAction *nickListIgnorePlayerAction; QAction *nickListIgnorePlayerAction;
QMenu *nickListPlayerInfoSubMenu; QMenu *nickListPlayerInfoSubMenu;
QAction *nickListPlayerInGameInfo; QAction *nickListPlayerInGameInfo;
int infoMsgToShowId; int infoMsgToShowId;
int currentInvitationGameId; int currentInvitationGameId;
bool inviteDialogIsCurrentlyShown; bool inviteDialogIsCurrentlyShown;
QStandardItemModel *myNickListModel; QStandardItemModel *myNickListModel;
QItemSelectionModel *myNickListSelectionModel; QItemSelectionModel *myNickListSelectionModel;
MyNickListSortFilterProxyModel *myNickListSortFilterProxyModel; MyNickListSortFilterProxyModel *myNickListSortFilterProxyModel;
QLabel *autoStartTimerOverlay; QLabel *autoStartTimerOverlay;
int autoStartTimerCounter; int autoStartTimerCounter;
protected: protected:
bool eventFilter(QObject *obj, QEvent *event); bool eventFilter(QObject *obj, QEvent *event);
}; };
@@ -3,21 +3,22 @@
#include <QtCore> #include <QtCore>
MyGameListSortFilterProxyModel::MyGameListSortFilterProxyModel(QObject *parent) MyGameListSortFilterProxyModel::MyGameListSortFilterProxyModel(QObject *parent)
: QSortFilterProxyModel(parent) : QSortFilterProxyModel(parent)
{ {
} }
bool MyGameListSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { bool MyGameListSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent); QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent); QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
QModelIndex index3 = sourceModel()->index(sourceRow, 3, sourceParent); QModelIndex index3 = sourceModel()->index(sourceRow, 3, sourceParent);
QModelIndex index4 = sourceModel()->index(sourceRow, 4, sourceParent); QModelIndex index4 = sourceModel()->index(sourceRow, 4, sourceParent);
return ((sourceModel()->data(index1, 16).toString().contains(column1RegExp) return ((sourceModel()->data(index1, 16).toString().contains(column1RegExp)
&& sourceModel()->data(index2, 16).toString().contains(column2RegExp) && sourceModel()->data(index2, 16).toString().contains(column2RegExp)
&& sourceModel()->data(index3, 16).toString().contains(column3RegExp) && sourceModel()->data(index3, 16).toString().contains(column3RegExp)
&& sourceModel()->data(index4, 16).toString().contains(column4RegExp)) || sourceModel()->data(index0, 16) == "MeInThisGame"); && sourceModel()->data(index4, 16).toString().contains(column4RegExp)) || sourceModel()->data(index0, 16) == "MeInThisGame");
} }
@@ -5,23 +5,31 @@
class MyGameListSortFilterProxyModel : public QSortFilterProxyModel class MyGameListSortFilterProxyModel : public QSortFilterProxyModel
{ {
Q_OBJECT Q_OBJECT
public: public:
MyGameListSortFilterProxyModel(QObject *parent = 0); MyGameListSortFilterProxyModel(QObject *parent = 0);
void setColumn1RegExp(QRegExp column1) { column1RegExp = column1; } void setColumn1RegExp(QRegExp column1) {
void setColumn2RegExp(QRegExp column2) { column2RegExp = column2; } column1RegExp = column1;
void setColumn3RegExp(QRegExp column3) { column3RegExp = column3; } }
void setColumn4RegExp(QRegExp column4) { column4RegExp = column4; } void setColumn2RegExp(QRegExp column2) {
column2RegExp = column2;
}
void setColumn3RegExp(QRegExp column3) {
column3RegExp = column3;
}
void setColumn4RegExp(QRegExp column4) {
column4RegExp = column4;
}
protected: protected:
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
private: private:
QRegExp column1RegExp; QRegExp column1RegExp;
QRegExp column2RegExp; QRegExp column2RegExp;
QRegExp column3RegExp; QRegExp column3RegExp;
QRegExp column4RegExp; QRegExp column4RegExp;
}; };
@@ -16,7 +16,7 @@
using namespace std; using namespace std;
MyGameListTreeWidget::MyGameListTreeWidget(QDialog* parent) MyGameListTreeWidget::MyGameListTreeWidget(QDialog* parent)
: QTreeWidget(parent) : QTreeWidget(parent)
{ {
//set the pixmap cache size in the main function only one time //set the pixmap cache size in the main function only one time
@@ -28,7 +28,8 @@ MyGameListTreeWidget::~MyGameListTreeWidget()
{ {
} }
void MyGameListTreeWidget::setGameListBackgroundImage(QString pmString) { void MyGameListTreeWidget::setGameListBackgroundImage(QString pmString)
{
gameListBGPixmap.load(pmString); gameListBGPixmap.load(pmString);
} }
@@ -53,7 +54,8 @@ void MyGameListTreeWidget::setGameListBackgroundImage(QString pmString) {
// QTreeWidget::paintEvent(event); // QTreeWidget::paintEvent(event);
// } // }
void MyGameListTreeWidget::scrollContentsBy ( int dx, int dy ) { void MyGameListTreeWidget::scrollContentsBy ( int dx, int dy )
{
viewport()->update(); viewport()->update();
@@ -17,11 +17,11 @@
class MyGameListTreeWidget : public QTreeWidget class MyGameListTreeWidget : public QTreeWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
MyGameListTreeWidget(QDialog*); MyGameListTreeWidget(QDialog*);
~MyGameListTreeWidget(); ~MyGameListTreeWidget();
public slots: public slots:
@@ -3,59 +3,59 @@
#include <QtCore> #include <QtCore>
MyNickListSortFilterProxyModel::MyNickListSortFilterProxyModel(QObject *parent) MyNickListSortFilterProxyModel::MyNickListSortFilterProxyModel(QObject *parent)
: QSortFilterProxyModel(parent), filterState(0) : QSortFilterProxyModel(parent), filterState(0)
{ {
} }
bool MyNickListSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const bool MyNickListSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{ {
switch(filterState) { switch(filterState) {
case 0: { case 0: {
return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
} }
break; break;
case 1: { case 1: {
return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
} }
break; break;
case 2: { case 2: {
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
return sourceModel()->data(index0, 34).toString().contains("idle") && QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); return sourceModel()->data(index0, 34).toString().contains("idle") && QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
} }
break; break;
} }
return false; return false;
} }
bool MyNickListSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const bool MyNickListSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{ {
switch(filterState) { switch(filterState) {
case 0: { case 0: {
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);
} }
break; break;
case 1: { case 1: {
QString leftCountryAndName(sourceModel()->data(left, 33).toString().toUpper()+sourceModel()->data(left, Qt::DisplayRole).toString().toLower()); QString leftCountryAndName(sourceModel()->data(left, 33).toString().toUpper()+sourceModel()->data(left, Qt::DisplayRole).toString().toLower());
QString rightCountryAndName(sourceModel()->data(right, 33).toString().toUpper()+sourceModel()->data(right, Qt::DisplayRole).toString().toLower()); QString rightCountryAndName(sourceModel()->data(right, 33).toString().toUpper()+sourceModel()->data(right, Qt::DisplayRole).toString().toLower());
return leftCountryAndName < rightCountryAndName; return leftCountryAndName < rightCountryAndName;
} }
break; break;
case 2: { case 2: {
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);
} }
break; break;
} }
return false; return false;
} }
void MyNickListSortFilterProxyModel::setFilterState(int state) void MyNickListSortFilterProxyModel::setFilterState(int state)
{ {
filterState = state; filterState = state;
} }
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more