/*************************************************************************** qgtp.cpp - description ------------------- begin : Thu Nov 29 2001 copyright : (C) 2001 by PALM Thomas , DINTILHAC Florian, HIVERT Anthony, PIOC Sebastien email : ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include //#include #include #include #include enum CommandType {PROTOCOL, BOARDSIZE, KNOWN_COMMAND, LEVEL, KOMI, PLAY_BLACK, PLAY_WHITE, GENMOVE}; #include "qgtp.h" #ifdef Q_OS_WIN #include #endif /* Function: open a session * Arguments: name and path of go program * Fails: never * Returns: nothing */ QGtp::QGtp() { /*openGtpSession(filename);*/ programProcess = NULL; // This to permit proper ending responseReceived = false; answer = ""; busy = false; } QGtp::~QGtp() { if (programProcess) programProcess->kill(); // not very clean (should use tryTerminate) } /* Code */ /* Function: get the last message from gnugo * Arguments: none * Fails: never * Returns: last message from GO */ QString QGtp::getLastMessage() { return _response; } int QGtp::openGtpSession(QString path, QString args, int size, float komi, int handicap) { _cpt = 1000; programProcess = new QProcess(); programProcess->setReadChannel(QProcess::StandardOutput); QStringList arguments = args.split(' ',QString::SkipEmptyParts); issueCmdNb = false; if (path.contains(QRegExp("gnugo$", Qt::CaseInsensitive))) issueCmdNb = true; // FIXME: are command numbers really gnugo-specific? connect(programProcess, &QProcess::readyRead, this, &QGtp::slot_readFromStdout); connect(programProcess, QOverload::of(&QProcess::finished), this, &QGtp::slot_processExited); qDebug() << "QGtp::openGtpSession(" << path << "," << args << ")"; programProcess->start(path, arguments); if (!programProcess->waitForStarted()) { _response="Could not start "+path; return FAIL ; } //?? never know ... otherwise, I get a segfault with sprint ... if ((outFile = (char *)malloc (100)) == NULL) { _response="Yuck ! Could not allocate 100 bytes !!!" ; return FAIL ; } if (protocolVersion()==OK) { if(getLastMessage().toInt() !=2) { qDebug("Protocol version problem???"); // quit(); _response="Protocol version not supported"; // return FAIL; } if(setBoardsize(size)==FAIL) { return FAIL; } if(clearBoard()==FAIL) { // removed by frosla -> protocol changes... // return FAIL; } /* if(knownCommand("level")==FAIL) { return FAIL; } else if (getLastMessage().contains("true")) { if (setLevel(level)==FAIL) { return FAIL; } } */ if(setKomi(komi)==FAIL) { return FAIL; } if(fixedHandicap(handicap)==FAIL) { return FAIL; } } else { quit(); _response="Protocol version error"; return FAIL; } busy = false; return OK; } // Read from stdout void QGtp::slot_readFromStdout() { int number; int pos; while (programProcess->canReadLine()) { answer = programProcess->readLine(); answer.chop(1); // remove the trailing '\n' responseReceived = ((! answer.isEmpty()) && ((answer.at(0) == '=') || (answer.at(0) == '?'))); if (responseReceived) break; } if (!responseReceived) return; _response = answer; qDebug("** QGtp::slot_readFromStdout(): %s" , _response.toLatin1().constData()); // do we have any answer after the command number ? pos = _response.indexOf(" "); number = _response.mid(1,pos).toInt(); if (pos < 1) _response = ""; else _response = _response.right(_response.length() - pos - 1); int i = moveRequests.indexOf(number); if (i == -1) return; // Otherwise we have an answer to a move request. // This is the one case in which we currently do not busy-wait. busy=false; moveRequests.removeAt(i); if (_response == "resign") { emit computerResigned(); return; } else if (_response.contains("Pass",Qt::CaseInsensitive)) { emit computerPassed(); return; } int x = _response[0].unicode() - QChar::fromLatin1('A').unicode() + 1; // skip 'J' if (x > 8) x--; int y; if (_response[2] >= '0' && _response[2] <= '9') y = _response.mid(1,2).toInt(); else y = _response[1].digitValue(); emit signal_computerPlayed( x, y ); } // exit void QGtp::slot_processExited(int exitCode, QProcess::ExitStatus exitStatus) { qDebug("Process Exited with exit code %i and status %d", exitCode, exitStatus); // fflush ("quit"); // return waitResponse(); } /* Function: wait for a go response * Arguments: none * Fails: never * Returns: nothing */ int QGtp::waitResponse() { busy=true; do //FIXME : use the readyRead signal of the process { programProcess->waitForReadyRead(10); qApp->processEvents(); } while (!responseReceived); qDebug("** QGtp::waitResponse(): \'%s\'" , _response.toLatin1().constData()); responseReceived = false; busy=false; return ((answer.at(0) == '=') ? OK : FAIL ); } /**************************** * Program identity. * ****************************/ /* Function: Report the name of the program. * Arguments: none * Fails: never * Returns: program name */ int QGtp::name () { fflush("name"); return waitResponse(); } /* Function: Report protocol version. * Arguments: none * Fails: never * Returns: protocol version number */ int QGtp::protocolVersion () { fflush("protocol_version"); return waitResponse(); } void QGtp::fflush(QByteArray s) { if (issueCmdNb) { s = QString().setNum(_cpt++).toLatin1() + " " + s; } qDebug("flush -> %s",s.constData()); s += '\n'; int i= programProcess->write(s); if ( i != s.size()) qDebug("Error writing %s",s.constData()); } /**************************** * Administrative commands. * ****************************/ /* Function: Quit * Arguments: none * Fails: never * Returns: nothing */ int QGtp::quit () { fflush("quit"); return waitResponse(); } /* Function: Report the version number of the program. * Arguments: none * Fails: never * Returns: version number */ int QGtp::version () { fflush("version"); return waitResponse(); } /*************************** * Setting the board size. * ***************************/ /* Function: Set the board size to NxN. * Arguments: integer * Fails: board size outside engine's limits * Returns: nothing */ int QGtp::setBoardsize (int size) { fflush("boardsize "+intToQByteArray(size)); return waitResponse(); } /* Function: Find the current boardsize * Arguments: none * Fails: never * Returns: board_size */ int QGtp::queryBoardsize() { fflush ("query_boardsize"); return waitResponse(); } /*********************** * Clearing the board. * ***********************/ /* Function: Clear the board. * Arguments: none * Fails: never * Returns: nothing */ int QGtp::clearBoard () { fflush ("clear_board"); return waitResponse(); } /*************************** * Setting. * ***************************/ /* Function: Set the komi. * Arguments: float * Fails: incorrect argument * Returns: nothing */ int QGtp::setKomi(float f) { fflush (QString("komi %1").arg(f,0,'f',2).toLatin1()); return waitResponse(); } /* Function: Set the playing level. * Arguments: int * Fails: incorrect argument * Returns: nothing */ int QGtp::setLevel (int level) { fflush ("level "+intToQByteArray(level)); return waitResponse(); } /****************** * Playing moves. * ******************/ /* Function: Play a black stone at the given vertex. * Arguments: vertex * Fails: invalid vertex, illegal move * Returns: nothing */ int QGtp::playblack (int x, int y) { fflush (QByteArray("play black ")+encodeCoors(x,y)); return waitResponse(); } /* Function: Black pass. * Arguments: None * Fails: never * Returns: nothing */ int QGtp::playblackPass () { fflush ("play black pass"); return waitResponse(); } /* Function: Play a white stone at the given vertex. * Arguments: vertex * Fails: invalid vertex, illegal move * Returns: nothing */ int QGtp::playwhite (int x, int y) { fflush ("play white "+encodeCoors(x,y)); return waitResponse(); } /* Function: White pass. * Arguments: none * Fails: never * Returns: nothing */ int QGtp::playwhitePass () { fflush ("play white pass"); return waitResponse(); } /* Function: Set up fixed placement handicap stones. * Arguments: number of handicap stones * Fails: invalid number of stones for the current boardsize * Returns: list of vertices with handicap stones */ int QGtp::fixedHandicap (int handicap) { if (handicap < 2) return OK; fflush ("fixed_handicap "+intToQByteArray(handicap)); return waitResponse(); } int QGtp::set_free_handicap(QList handicap_stones) { QByteArray message("set_free_handicap"); for ( int i=0; i 8) x++; QByteArray result; char c1 = x - 1 + 'A'; result.append(c1); result.append(QString().setNum(y).toLatin1()); return result; } QByteArray QGtp::intToQByteArray(int i) { return QString().setNum(i).toLatin1(); } /* Function: Turn uncertainty reports from owl_attack * and owl_defend on or off. * Arguments: "on" or "off" * Fails: invalid argument * Returns: nothing */ int QGtp::reportUncertainty (QString s) { fflush(QByteArray("report_uncertainty ")+s.toLatin1()); return waitResponse(); } /* Function: List the stones of a worm * Arguments: the location * Fails: if called on an empty or off-board location * Returns: list of stones */ int QGtp::wormStones() { fflush("worm_stones"); return waitResponse(); } int QGtp::shell(QString s) { fflush(s.toLatin1()); return waitResponse(); }