Beispiel #1
0
State onAIsTurn(Game* game) {
  /* added clear screen -Cesar 1/27 */
  char cmd[255];
  int result;
  clearScreen();
  assert(game);
  printBoard(game);
  printf("Turn number: %d, ", game->turn+1);
  if(game->turn%2 == 0)
	  printf("WHITE's turn\n");
  else
	  printf("BLACK's turn\n");
  
  if(check500Turns(game))
	  return MainMenu;


  getDecisionFromAI(game, cmd);
  /* Normally this state should return to player's turn.
   * If AI vs. AI is need, then we should modify here.
   */
  result = gameLogic(game, cmd);
  if(result == 9 || result == 10)
	  result = promotion(game, cmd, 'Q');
  if(result == 7)
  {
	  printf("CHECKMATE\n");
	  saveLog(game, "lastGameLog.log");
	  printBoard(game);
	  getchar();
	  return MainMenu;
  }
  else if(result == 8)
  {
	  printf("STALEMATE\n");
	  saveLog(game, "lastGameLog.log");
	  printBoard(game);
	  getchar();
	  return MainMenu;
  }
  

  /*
  if (result == 7 || game->turn > 100)
    return TurnPlayer;
  else
    return TurnAI;
  */

  if(game->setting->gameMode == 2)
    return TurnAI;
  else
    return TurnPlayer;


}
void onLoadCMClicked(HWND hWnd)
{
	setStatusBarText(L"Загрузка...");
	if (currentDeviceNumber < 0)
	{
		setStatusBarText(L"Не выбрано устройство!");
		return;
	}

	auto szFileName = new char[MAX_PATH];
	GetWindowTextA(confWayLE, szFileName, MAX_PATH);
	std::string pathToCommodFile(szFileName);	
	delete[] szFileName;

	if (!isFileExists(pathToCommodFile)) {
		setStatusBarText(L"Не найден файл конфигурации");
		return;
	}
	auto manager = new StrategyDeployment(pathToCommodFile);
	incrProgressBar(hWnd, 20);
	bool isOK;
	if (fileSize(pathToCommodFile) > 0x10000)
	{
		manager->setZip(true);
		manager->setCreateCompressedFile(true);
		manager->setZipLocation(getZipLocation(hWnd));
		manager->setParse(true);
		manager->setzipCompressionLevel(7);
		isOK = manager->convert();
	}	
	incrProgressBar(hWnd, 30);
	isOK = manager->validateCurrentConfiguration();	
	if (!isOK)
	{
		incrProgressBar(hWnd, 50);
		SetWindowTextA(stateSB, "Ошибка: неверная конфигурация! Отмена загрузки.");
		manager->saveLog();
		delete manager;
		return;
	}
		
	incrProgressBar(hWnd, 20);
	isOK = manager->loadConfiguration(currentDeviceNumber);
	manager->saveLog();
	auto resultLog(manager->getLastConfName());
	delete manager;
	incrProgressBar(hWnd, 30);
	isOK ? resultLog.append(" - конфигурация загружена успешно.") :
		resultLog.append(" -конфигурация не загружена.");
	
	SetWindowTextA(stateSB, resultLog.c_str());
}
Beispiel #3
0
int emct_main::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: exitChild(); break;
        case 1: closeEvent((*reinterpret_cast< QCloseEvent*(*)>(_a[1]))); break;
        case 2: getPath(); break;
        case 3: executeOption(); break;
        case 4: saveLog(); break;
        case 5: helpPdf(); break;
        case 6: { int _r = readConfigFile();
            if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;
        case 7: openCon((*reinterpret_cast< QWidget*(*)>(_a[1]))); break;
        case 8: disableButtons(); break;
        case 9: enableButtons(); break;
        case 10: changeEStatus((*reinterpret_cast< std::string(*)>(_a[1]))); break;
        case 11: { int _r = readVersionFile();
            if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;
        case 12: logAppend((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 13: logAppendError((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 14: logAppendOp((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 15;
    }
    return _id;
}
void printTicketTypeToLog(int type, int cnf, char * buff){

	switch(type){
	   case 0: sprintf(buff,"ticket type: Mega Million; confidence= %d\n",cnf); break;
	   case 1: sprintf(buff,"ticket type: Power Ball; confidence= %d\n",cnf); break;
	   default: sprintf(buff,"ticket type: ???\n"); break;
	}
	 saveLog("", buff);
}
Beispiel #5
0
DebugGadgetWidget::DebugGadgetWidget(QWidget *parent) : QLabel(parent)
{
    m_config = new Ui_Form();
    m_config->setupUi(this);
    debugengine *de = new debugengine();
    QxtLogger::getInstance()->addLoggerEngine("debugplugin", de);
    connect(de, SIGNAL(dbgMsg(QString, QList<QVariant>)), this, SLOT(dbgMsg(QString, QList<QVariant>)));
    connect(de, SIGNAL(dbgMsgError(QString, QList<QVariant>)), this, SLOT(dbgMsgError(QString, QList<QVariant>)));
    connect(m_config->pushButton, SIGNAL(clicked()), this, SLOT(saveLog()));
}
Beispiel #6
0
string ofxEliza::ask(string _inputString){
    // gets input from the user
    save_prev_input();
    m_sInput = _inputString;
    saveLog("USER");
    
    // Finds and display a response
    // to the current input of the user.
    // removes punctuation from the input
    // and do some more preprocessing
    if(m_sInput.length() > 0) {
		tok.cleanString(m_sInput, " ?!,;");
		trimRight(m_sInput, '.');
		UpperCase(m_sInput);
		m_sInput.insert(0, " ");
		m_sInput.append(" ");
	}
    
    save_prev_responses();
    save_prev_response();
    
    if(null_input()) {
        handle_null_input();
    } else if(user_repeat()) {
        handle_user_repetition();
    } else if(short_input()) {
        handle_short_input();
    }
    else {
        reset_repeat_count();
        reset_short_input_count();
        find_response();
    }
    
    select_response();
    preProcessResponse();
    handle_repetition();
    
    saveLog("ELIZA");
    
    return m_sResponse;
}
Beispiel #7
0
State onGameMain(Game* game) {
	/*IGNORE*/
	int choice = 0;
	char filename[255];
	printGameMenu(game);
	choice = getInput();
	/* 
	"0. Restart a new game"
	"1. Load from a old game"
	"2. Save log"
	"3. Save this game"
	"4. Allow redo [%s]"
	"5. Allow illegal move [%s]"
	"6. Select default opponent [%s]"
	"7. Select default difficulty"
	"8. Return to the game"
	"9. Exit"
	*/
	switch(choice) {
	case 0:
		resetGame(game);
		return NewGame;
	case 1:
		/*loadGame(game);
		*/return NewGame;
	case 2:
		printf("Enter the file name you want to save \n");
		scanf("%s", filename);
		saveLog(game, filename);
		break;
	case 3:
		/*saveGame(game);
		*/break;
	case 4:
		game->setting->allowRedo ^= 1;
		break;
	case 5:
		game->setting->allowIllegalMove ^= 1;
		break;
	case 6:
		selectOpponent(game);
		break;
	case 7:
		selectDifficulty(game);
		break;
	case 8:
		return TurnPlayer;
	case 9:
		return Exit;
	default:
		return GameMenu;
	}
	return GameMenu;
}
Beispiel #8
0
SDL_Surface* Text::generate(SDL_Surface *texture,const std::string text,int size)
{

    tmp = texture;
    stringstream ss;
    ss << "Oh My Goodness, an error "<< TTF_GetError();
    if(font == NULL) saveLog(ss.str() );

    tmp = TTF_RenderText_Solid(font,text.c_str(),textColor);

    return tmp;
}
DebugGadgetWidget::DebugGadgetWidget(QWidget *parent) : QLabel(parent)
{
    m_config = new Ui_Form();
    m_config->setupUi(this);

    // m_textedit = m_config->plainTextEdit;
    // MyplainTextEdit=m_config->plainTextEdit;
    // debugengine *de = new debugengine();
    // qInstallMessageHandler(customMessageHandler);
    // connect(de, SIGNAL(dbgMsg(QString, QList<QVariant>)), this, SLOT(dbgMsg(QString, QList<QVariant>)));
    // connect(de, SIGNAL(dbgMsgError(QString, QList<QVariant>)), this, SLOT(dbgMsgError(QString, QList<QVariant>)));
    connect(m_config->pushButton, SIGNAL(clicked()), this, SLOT(saveLog()));
}
Beispiel #10
0
void Text::loadResources()
{
    try
    {
        font = TTF_OpenFont("resources/font/Ubuntu-B.ttf", 45);

    }
    catch(...)
    {
        if(font == NULL) saveLog("Error Opening Font File @TextRender.LoadResoureces");
        //std::terminate();
    }


}
Beispiel #11
0
void printFieldToLog(LPFIELDSRESULTS lpFieldsResults, char *buff){

	  saveLog("-------------------------------------------", "\n");
	  sprintf(buff,"Field= %s\n",lpFieldsResults->name);
      saveLog("", buff);
      saveLog("\n", "\n");
      saveLog(lpFieldsResults->result, "\n");
      saveLog("", "\n");
	  saveLog("-------------------------------------------", "\n");
}
Beispiel #12
0
void MainWindow::closeEvent(QCloseEvent *event)
{
    event->accept();

    if(project != nullptr)
    {
        delete(project);
    }

    for(int i = 0; i < recentProjectsQActions.size(); i++)
    {
        delete(recentProjectsQActions.at(i));
    }

    saveLog();
}
Beispiel #13
0
void printResultsToLog(LPTICKETRESULTS ticketResults){
	int i;
	char buff[500];

	 sprintf(buff,"Status= %d\n",ticketResults->status);
	 saveLog("", buff);
     printTicketTypeToLog(ticketResults->type, ticketResults->typeCnf, buff);
    for(i=0;i<NUMFIELDS_RESULTS;i++){
    	if(ticketResults->fieldsResults[i].name[0] != 0){
    		if(strcmp(ticketResults->fieldsResults[i].name, "NUMBERS") == 0) printFieldToLog(&ticketResults->fieldsResults[i], buff);
    		if(strcmp(ticketResults->fieldsResults[i].name, "PLAYER") == 0) printFieldToLog(&ticketResults->fieldsResults[i], buff);
    		if(strcmp(ticketResults->fieldsResults[i].name, "DATE") == 0) printFieldToLog(&ticketResults->fieldsResults[i], buff);
//    		if(strcmp(ticketResults->fieldsResults[i].name, "DATEN") == 0) printFieldToLog(&ticketResults->fieldsResults[i], buff);
//    		if(strcmp(ticketResults->fieldsResults[i].name, "DATEA") == 0) printFieldToLog(&ticketResults->fieldsResults[i], buff);
    	}
    }
}
Beispiel #14
0
/*
*  Constructs a logForm as a child of 'parent', with the
*  name 'name' and widget flags set to 'f'.
*
*  The dialog will by default be modeless, unless you set 'modal' to
*  TRUE to construct a modal dialog.
*/
logForm::logForm( QWidget* parent, bool modal, Qt::WFlags fl )
: QDialog( parent, fl )
{
   setModal( modal );
	setObjectName( "logForm" );

   //setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, 0, 0, sizePolicy().hasHeightForWidth() ) );
   setSizePolicy( QSizePolicy::Preferred , QSizePolicy::Preferred );
   setMinimumSize( QSize( 300, 300 ) );
   setMaximumSize( QSize( 600, 600 ) );
   setBaseSize( QSize( 400, 375 ) );
   logFormLayout = new QGridLayout( this ); //, 1, 1, 11, 6, "logFormLayout"); 

   layout3 = new QHBoxLayout( 0 ); 
   layout3->setSpacing( 6 );	
   spacer1 = new QSpacerItem( 210, 21, QSizePolicy::Expanding, QSizePolicy::Minimum );
   layout3->addItem( spacer1 );

   saveButton = new QPushButton( this );
   layout3->addWidget( saveButton );

   okButton = new QPushButton( this );
   layout3->addWidget( okButton );

   logFormLayout->addLayout( layout3, 1, 0 );

   logViewer = new QTextEdit( this );

   logFormLayout->addWidget( logViewer, 0, 0 );
   languageChange();
   resize( QSize(361, 365).expandedTo(minimumSizeHint()) );

   // signals and slots connections
   connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
   connect( saveButton, SIGNAL( clicked() ), this, SLOT( saveLog() ) );

   // tab order
   setTabOrder( okButton, saveButton );

   if( QFile::exists( logFile ) )
      loadLog();
   else 
      QMessageBox::warning( this, "Error", "MapIMG Log File Not Found." );
}
Beispiel #15
0
string ofxEliza::start(string _logFile){
    time_t ltime;
	time(&ltime);
	logfile.open( ofToDataPath(_logFile).c_str(), std::ios::out | std::ios::app);
	if(logfile.fail()) {
		throw std::string("can't save conversation log");
	}
	logfile << "\n\nConversation log - " << ctime(&ltime) << std::endl;
	response_list = signOn;
	select_response();
	
    if(m_sResponse.length() > 0) {
		std::cout << m_sResponse;
	}
    
	saveLog("ELIZA");
    
    return m_sResponse;
}
Beispiel #16
0
void Text::init()
{
    textColor = {255,255,0,200};

    try
    {
        if(TTF_Init()==-1)
        {
            throw 3;
        }
        loadResources();
    }
    catch(...)
    {
        saveLog("Could Not Init TTF");
        std::terminate();
    }

}
Beispiel #17
0
int check500Turns(Game* game)
{
  char maxTurnUserInput;
  assert(game);
  if(game->turn > 500)
  {
	  printf("Game has reached over 500 turns, do you want to stop? Y/N: ");
	  scanf("%c", &maxTurnUserInput);
	  printf("\n");
      fseek(stdin,0,SEEK_END);
	  if(maxTurnUserInput == 'Y'||maxTurnUserInput == 'y') {
		  return 1;
	  } else {
		  saveLog(game, "_Game.log");
		  game->turn = 0;
		  game->log[0] = 0;
		  return 0;
	  }
  }
  return 0;
}
Beispiel #18
0
LogViewer::LogViewer( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
	setName( "LogViewer" );
	setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, sizePolicy().hasHeightForWidth() ) );
	
 	QBoxLayout *logLayout = new QVBoxLayout( this, 5, 5); 
	
	textLog = new QTextEdit(this);
	textLog->setMinimumSize( QSize( 200, 80) );
	textLog->setTextFormat(Qt::LogText);
	QFont text_font(  textLog->font() );
	text_font.setFamily( "Courier" );
	text_font.setPointSize( 12 );
	textLog->setFont( text_font ); 
	
	clearButton = new QPushButton( this, "clearButton" );
	saveButton = new QPushButton( this, "saveButton" );
	closeButton = new QPushButton( this, "closeButton" );
	
	logLayout->addWidget( textLog, 2 );
	
	QBoxLayout *hLayout = new QHBoxLayout( logLayout ); 
	hLayout->addWidget(clearButton);
	hLayout->addWidget(saveButton);
	hLayout->addWidget(closeButton);
	
	languageChange();
	resize( QSize(700, 300).expandedTo(minimumSizeHint()) );
	clearWState( WState_Polished );
	
	// signals and slots connections
	connect( clearButton, SIGNAL( clicked() ), this, SLOT( clearLog() ) );
	connect( saveButton, SIGNAL( clicked() ), this, SLOT( saveLog() ) );
	connect( closeButton, SIGNAL( clicked() ), this, SLOT( closeLog() ) );
}
Beispiel #19
0
LogfileReader::LogfileReader(QWidget* parent, const QString& log, const QString& caption) : ChatWindow(parent)
{
    setType(ChatWindow::LogFileReader);
    setName(i18n("Logfile of %1", caption));

    fileName = log;

    setSpacing(0);

    toolBar = new KToolBar(this, true, true);
    toolBar->setObjectName("logfile_toolbar");
    toolBar->addAction(QIcon::fromTheme("document-save-as"), i18n("Save As..."), this, SLOT(saveLog()));
    toolBar->addAction(QIcon::fromTheme("view-refresh"), i18n("Reload"), this, SLOT(updateView()));
    toolBar->addAction(QIcon::fromTheme("edit-delete"), i18n("Clear Logfile"), this, SLOT(clearLog()));

    toolBar->addWidget(new QLabel(i18n("Show last:"),toolBar));
    sizeSpin = new QSpinBox(toolBar);
    sizeSpin->setMinimum(10);
    sizeSpin->setMaximum(1000);
    sizeSpin->setSingleStep(10);
    sizeSpin->setObjectName("logfile_size_spinbox");
    sizeSpin->setWhatsThis(i18n("Use this box to set the maximum size of the log file. This setting does not take effect until you restart Konversation. Each log file may have a separate setting."));
    sizeSpin->setValue(Preferences::self()->logfileBufferSize());
    sizeSpin->setSuffix(i18n(" KB"));
    sizeSpin->installEventFilter(this);
    toolBar->addWidget(sizeSpin);
    connect(sizeSpin, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LogfileReader::storeBufferSize);

    IRCViewBox* ircBox = new IRCViewBox(this);
    setTextView(ircBox->ircView());
    getTextView()->setWhatsThis(i18n("The messages in the log file are displayed here. The oldest messages are at the top and the most recent are at the bottom."));

    updateView();
    ircBox->ircView()->setFocusPolicy(Qt::StrongFocus);
    setFocusPolicy(Qt::StrongFocus);
    setFocusProxy(ircBox->ircView());

    updateAppearance();

    connect(getTextView(), SIGNAL(gotFocus()), getTextView(), SLOT(setFocus()));
}
 void NSFTraceLog::saveLog()
 {
     saveLog(getName());
 }
Beispiel #21
0
MainWindow::MainWindow()
  : m_settings(QString::fromAscii("Doxygen.org"), QString::fromAscii("Doxywizard"))
{
  QMenu *file = menuBar()->addMenu(tr("File"));
  file->addAction(tr("Open..."), 
                  this, SLOT(openConfig()), Qt::CTRL+Qt::Key_O);
  m_recentMenu = file->addMenu(tr("Open recent"));
  file->addAction(tr("Save"), 
                  this, SLOT(saveConfig()), Qt::CTRL+Qt::Key_S);
  file->addAction(tr("Save as..."), 
                  this, SLOT(saveConfigAs()), Qt::SHIFT+Qt::CTRL+Qt::Key_S);
  file->addAction(tr("Quit"),  
                  this, SLOT(quit()), Qt::CTRL+Qt::Key_Q);

  QMenu *settings = menuBar()->addMenu(tr("Settings"));
  settings->addAction(tr("Reset to factory defaults"),
                  this,SLOT(resetToDefaults()));
  settings->addAction(tr("Use current settings at startup"),
                  this,SLOT(makeDefaults()));
  settings->addAction(tr("Clear recent list"),
                  this,SLOT(clearRecent()));

  QMenu *help = menuBar()->addMenu(tr("Help"));
  help->addAction(tr("Online manual"), 
                  this, SLOT(manual()), Qt::Key_F1);
  help->addAction(tr("About"), 
                  this, SLOT(about()) );

  m_expert = new Expert;
  m_wizard = new Wizard(m_expert->modelData());

  // ----------- top part ------------------
  QWidget *topPart = new QWidget;
  QVBoxLayout *rowLayout = new QVBoxLayout(topPart);

  // select working directory
  QHBoxLayout *dirLayout = new QHBoxLayout;
  m_workingDir = new QLineEdit;
  m_selWorkingDir = new QPushButton(tr("Select..."));
  dirLayout->addWidget(m_workingDir);
  dirLayout->addWidget(m_selWorkingDir);

  //------------- bottom part --------------
  QWidget *runTab = new QWidget;
  QVBoxLayout *runTabLayout = new QVBoxLayout(runTab);

  // run doxygen
  QHBoxLayout *runLayout = new QHBoxLayout;
  m_run = new QPushButton(tr("Run doxygen"));
  m_run->setEnabled(false);
  m_runStatus = new QLabel(tr("Status: not running"));
  m_saveLog = new QPushButton(tr("Save log..."));
  m_saveLog->setEnabled(false);
  QPushButton *showSettings = new QPushButton(tr("Show configuration"));
  runLayout->addWidget(m_run);
  runLayout->addWidget(m_runStatus);
  runLayout->addStretch(1);
  runLayout->addWidget(showSettings);
  runLayout->addWidget(m_saveLog);

  // output produced by doxygen
  runTabLayout->addLayout(runLayout);
  runTabLayout->addWidget(new QLabel(tr("Output produced by doxygen")));
  QGridLayout *grid = new QGridLayout;
  m_outputLog = new QTextEdit;
  m_outputLog->setReadOnly(true);
  m_outputLog->setFontFamily(QString::fromAscii("courier"));
  m_outputLog->setMinimumWidth(600);
  grid->addWidget(m_outputLog,0,0);
  grid->setColumnStretch(0,1);
  grid->setRowStretch(0,1);
  QHBoxLayout *launchLayout = new QHBoxLayout;
  m_launchHtml = new QPushButton(tr("Show HTML output"));
  launchLayout->addWidget(m_launchHtml);

  launchLayout->addStretch(1);
  grid->addLayout(launchLayout,1,0);
  runTabLayout->addLayout(grid);

  QTabWidget *tabs = new QTabWidget;
  tabs->addTab(m_wizard,tr("Wizard"));
  tabs->addTab(m_expert,tr("Expert"));
  tabs->addTab(runTab,tr("Run"));

  rowLayout->addWidget(new QLabel(tr("Step 1: Specify the working directory from which doxygen will run")));
  rowLayout->addLayout(dirLayout);
  rowLayout->addWidget(new QLabel(tr("Step 2: Configure doxygen using the Wizard and/or Expert tab, then switch to the Run tab to generate the documentation")));
  rowLayout->addWidget(tabs);

  setCentralWidget(topPart);
  statusBar()->showMessage(tr("Welcome to Doxygen"),messageTimeout);

  m_runProcess = new QProcess;
  m_running = false;
  m_timer = new QTimer;

  // connect signals and slots
  connect(tabs,SIGNAL(currentChanged(int)),SLOT(selectTab(int)));
  connect(m_selWorkingDir,SIGNAL(clicked()),SLOT(selectWorkingDir()));
  connect(m_recentMenu,SIGNAL(triggered(QAction*)),SLOT(openRecent(QAction*)));
  connect(m_workingDir,SIGNAL(returnPressed()),SLOT(updateWorkingDir()));
  connect(m_runProcess,SIGNAL(readyReadStandardOutput()),SLOT(readStdout()));
  connect(m_runProcess,SIGNAL(finished(int, QProcess::ExitStatus)),SLOT(runComplete()));
  connect(m_timer,SIGNAL(timeout()),SLOT(readStdout()));
  connect(m_run,SIGNAL(clicked()),SLOT(runDoxygen()));
  connect(m_launchHtml,SIGNAL(clicked()),SLOT(showHtmlOutput()));
  connect(m_saveLog,SIGNAL(clicked()),SLOT(saveLog()));
  connect(showSettings,SIGNAL(clicked()),SLOT(showSettings()));
  connect(m_expert,SIGNAL(changed()),SLOT(configChanged()));

  loadSettings();
  updateLaunchButtonState();
  m_modified = false;
  updateTitle();
  m_wizard->refresh();
}
Beispiel #22
0
int main(void) {
	int running = 1;
	State currState = MainMenu;
	Game* game = NULL;
#ifdef DEBUG
	game = createGame();
	printf("---------------- Open the game successfully \n");
	if (!game->setting->useAI)
		selectOpponent(game);
	printf("---------------- Changing the game to AI mode \n");
	printf("---------------- Going to run 100 times AI vs AI \n");
	printf(" Press enter to continue \n");
	getchar();
	fflush(stdin);
	while (game->turn < 100) {
		onAIsTurn(game);
	}
	printf("---------------- AI and check is tested \n");
	saveLog(game, "log.txt");
	printf("---------------- Save record successfully \n");
	printf(" Press enter to continue \n");
	getchar();
	replay(game);
	printf("---------------- Replay successfully \n");
	printf(" Press enter to exit \n");
	getchar();
	deleteGame(game);
	printf("---------------- Delete the game successfully \n");
	exit(0);
#endif
	game = createGame();

	while (running) {
		switch(currState) {
		case MainMenu:
			/*printf("currState = MainMenu\n");*/
			currState = onMainMenu(game);
			break;
		case NewGame:
			/*printf("currState = NewGame\n");*/
			currState = onNewGame(game);
			break;
		case GameMenu:
			/*printf("currState = GameMenu\n");*/
			currState = onGameMain(game);
			break;
		case TurnPlayer:
			/*printf("currState = Player's Turn\n");*/
			currState = onPlayersTurn(game);
			break;
		case TurnAI:
			/*printf("currState = AI's Turn\n");*/
			currState = onAIsTurn(game);
			break;
		case Exit:
			/*printf("currState = Exit\n");*/
			running = 0;
			break;
		default:
			break;
		}
	}
	deleteGame(game);
	return 0; /* added by Cesar on 1/27 */
}
Beispiel #23
0
State onPlayersTurn(Game* game) {
  /* added clear screen -Cesar 1/27 */
  char cmd[255];
  char choice = 0;
  char userInput[255];
  char promotionChoice;
  char maxTurnUserInput;
  int result;
  int ox, oy, dx, dy;
  clearScreen();
  assert(game);
  printBoard(game);
  printf("Turn number: %d, ", game->turn+1);
  if(game->turn%2 == 0)
	  printf("WHITE's turn\n");
  else
	  printf("BLACK's turn\n");
  printUserMenu(game);
  getGameInput(cmd);
  choice = cmd[0];
  
  if(check500Turns(game))
	  return MainMenu;


  /* added by Cesar 1/26 */
  switch(choice)
    {
    case '0':
      return MainMenu;
    case '1':
      printHints(game);
      return TurnPlayer;
    case '2':
      redo(game);
      return TurnPlayer;
	case '3':
	  printLog(game);
	  return TurnPlayer;
    case '4':
      replay(game);
      return TurnPlayer;
    case '5':
	  printf("Enter the file name you want to save \n");
	  scanf("%s", userInput);
      saveLog(game, userInput);
      fseek(stdin,0,SEEK_END);
	  return TurnPlayer;
	case '6':
	  printf("Enter the file name you want to save: ");
	  scanf("%s", userInput);
	  printf("\n");
      fseek(stdin,0,SEEK_END);
	  saveGame(game, userInput);
	  return TurnPlayer;
	case '7':
		gameOptions(game);
		return TurnPlayer;
    default:
      break;
    }
  
  
	ox = cmd[0] - 97;
	oy = cmd[1] - 49;
	dx = cmd[2] - 97;
	dy = cmd[3] - 49;
	if((!checkBoarder(ox, oy))||(!checkBoarder(dx, dy)) || (isValidMove(game, ox, oy, dx, dy) <= 0))
	{
		printf("INVALID MOVE DETECTED");
		if(game->setting->allowIllegalMove == 1)
		{
			printf(", TRY AGAIN\n\n");
			return TurnPlayer;
		}
		else
		{
			printf(", GAME OVER!\n\n");
			return MainMenu;
		}
	}

  
  result = gameLogic(game, cmd);
  if(result == 9 || result == 10)
  {
	  promotionChoice = ' ';
	  while(promotionChoice != 'Q' && promotionChoice != 'R' && promotionChoice != 'N' && promotionChoice != 'B')
	  {
		  printf("Pawn promotion, enter the promotion choice (char to represent piece): ");
		  scanf("%c", &promotionChoice);
		  fseek(stdin,0,SEEK_END);
		  if(promotionChoice=='q') promotionChoice='Q';
		  else if(promotionChoice=='r') promotionChoice='R';
		  else if(promotionChoice=='n') promotionChoice='N';
		  else if(promotionChoice=='b') promotionChoice='B';
		  printf("%c\n",promotionChoice);
		  if(promotionChoice != 'Q' && promotionChoice != 'R' && promotionChoice != 'N' && promotionChoice != 'B')
			  printf("Invalid input, try again.\n");
	  }
      result = promotion(game, cmd, promotionChoice);
  }
  if(result == 7)
  {
	  printf("CHECKMATE\n");
	  getchar();
	  return MainMenu;
  }
  else if(result == 8)
  {
	  printf("STALEMATE\n");
	  getchar();
	  return MainMenu;
  }

  if(game->setting->gameMode == 0)
    return TurnAI;
  else if(game->setting->gameMode == 1)
    return TurnPlayer;
  else
    return MainMenu; /* game logic returns 0 meaning the game is end */
}
Beispiel #24
0
void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout, std::string result = "")
{
    assert(forkCount < forkMax);
    pid_t pid = fork();
    if (pid == -1) {
        std::cerr << "error: no more process to create\n";
        exit(EXIT_FAILURE);
    }
    if (pid == 0) {
        std::string path(url);
        size_t pos = path.rfind('.');
        if (pos != std::string::npos) {
            path.erase(pos);
            path += ".log";
        }
        std::string evaluation;
        std::string log;
        loadLog(path, evaluation, log);

        pid_t pid = -1;
        std::string output;
        switch (mode) {
        case GENERATE:
            evaluation = result;
            // FALL THROUGH
        case UPDATE:
            if (evaluation[0] == '?')
                break;
            // FALL THROUGH
        default:
            pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
            break;
        }

        if (0 < pid && output.empty())
            result = "fatal";
        else {
            switch (mode) {
            case HEADLESS:
                if (evaluation != "?" && output != log)
                    result = "uncertain";
                else
                    result = evaluation;
                break;
            case UPDATE:
            case GENERATE:
                result = evaluation;
                if (result[0] != '?') {
                    if (!saveLog(path, url, result, output)) {
                        std::cerr << "error: failed to open the report file\n";
                        exit(EXIT_FAILURE);
                    }
                }
                break;
            default:
                break;
            }
        }
        if (0 < pid)
            killTest(pid);
        int status = ES_NA;
        if (!result.compare(0, 4, "pass"))
            status = ES_PASS;
        else if (!result.compare(0, 5, "fatal"))
            status = ES_FATAL;
        else if (!result.compare(0, 4, "fail"))
            status = ES_FAIL;
        else if (!result.compare(0, 7, "invalid"))
            status = ES_INVALID;
        else if (!result.compare(0, 4, "skip"))
            status = ES_SKIP;
        else if (!result.compare(0, 9, "uncertain"))
            status = ES_UNCERTAIN;
        exit(status);
    } else {
        auto s = &forkStates[(forkTop + forkCount) % forkMax];
        s->url = url;
        s->pid = pid;
        ++forkCount;
        reduce(report, WNOHANG);
    }
}
void MainWindow::rlmSaveLogBtnClicked()
{
    saveLog("rlmLog", ui->rlmLog);
}
 void TcpThread::opeatorData()
 {
      OperatorSql w;
      char ch = data[2].at(0).toAscii(); //将QChar 转换为标准C语言的ASCII,上网找了,switch在QT中只能支持整型对象
                      //操作数据库

      if (!w.createConnection()) {


         sendMsg(tr("SQL_LINK_ERROR"));

         return;
      }


/*
      if(!w.verifyUser(data[0],data[1]))//用户名密码错误
     {


         sendMsg(tr("USER_PASSWORD_ERROR"));
         tcpSocket->disconnectFromHost();//断开连接
      QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
         qDebug()<< tr("用户或者密码不正确!")<<"\n";

         return;
     }

*/

       QString sqlstr = data[3];//取出SQL语句
         switch(ch)
         {

             case 'Q':  {

            w.queryRecode(sqlstr);

             saveLog();
             break;//保存日志
         }
         case 'A':  {
            if(w.addRecode(sqlstr))
            {
            sendMsg(tr("ADD_SUCCESS"));
            saveLog();
             break;
            }
            else
             {
                 sendMsg(tr("ADD_FAILED"));
                 break;
             }
             }
         case 'D': {

            if(w.deleteRecode(sqlstr))
            {
             sendMsg(tr("DELETE_SUCCESS")) ;
             saveLog();
             break;
         }
            else
             {
                 sendMsg(tr("DELETE_FAILED"));
                 break;
             }
              }
         case 'U':   {
            if( w.updateRecode(sqlstr)) {
              sendMsg(tr("UPDATE_SUCCESS"));
             saveLog();
             break;
         }
         else
                 {
                     sendMsg(tr("UPDATE_FAILED"));
                     break;
                 }
            }
             default:  sendMsg(tr("UNKOWN_ERROR")); break;


        }

}
Beispiel #27
0
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
    std::string path(url);
    size_t pos = path.rfind('.');
    if (pos != std::string::npos) {
        path.erase(pos);
        path += ".log";
    }
    std::string evaluation;
    std::string log;
    loadLog(path, evaluation, log);

    pid_t pid = -1;
    std::string output;
    switch (mode) {
    case REPORT:
        break;
    case UPDATE:
        if (evaluation[0] == '?')
            break;
        // FALL THROUGH
    default:
        pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
        break;
    }

    std::string result;
    if (0 < pid && output.empty())
        result = "fatal";
    else if (mode == INTERACTIVE) {
        std::cout << "## complete\n" << output;
        std::cout << '[' << url << "] ";
        if (evaluation.empty() || evaluation[0] == '?')
            std::cout << "pass? ";
        else {
            std::cout << evaluation << "? ";
            if (evaluation != "pass")
                std::cout << '\a';
        }
        std::getline(std::cin, result);
        if (result.empty()) {
            if (evaluation.empty() || evaluation[0] == '?')
                result = "pass";
            else
                result = evaluation;
        } else if (result == "p" || result == "\x1b")
            result = "pass";
        else if (result == "f")
            result = "fail";
        else if (result == "i")
            result = "invalid";
        else if (result == "k") // keep
            result = evaluation;
        else if (result == "n")
            result = "na";
        else if (result == "s")
            result = "skip";
        else if (result == "u")
            result = "uncertain";
        else if (result == "q" || result == "quit")
            exit(EXIT_FAILURE);
        else if (result == "z")
            result = "undo";
        if (result != "undo" && !saveLog(path, url, result, output)) {
            std::cerr << "error: failed to open the report file\n";
            exit(EXIT_FAILURE);
        }
    } else if (mode == HEADLESS) {
        if (evaluation != "?" && output != log)
            result = "uncertain";
        else
            result = evaluation;
    } else if (mode == REPORT) {
        result = evaluation;
    } else if (mode == UPDATE) {
        result = evaluation;
        if (result[0] != '?') {
            if (!saveLog(path, url, result, output)) {
                std::cerr << "error: failed to open the report file\n";
                exit(EXIT_FAILURE);
            }
        }
    }

    if (0 < pid)
        killTest(pid);
    if (mode != INTERACTIVE && result[0] != '?')
        std::cout << url << '\t' << result << '\n';
    return result;
}