Example #1
0
void CuteChessApplication::newDefaultGame()
{
	// default game is a human versus human game using standard variant and
	// infinite time control
	ChessGame* game = new ChessGame(Chess::BoardFactory::create("standard"),
		new PgnGame());

	game->setTimeControl(TimeControl("inf"));
	game->pause();

	connect(game, SIGNAL(started(ChessGame*)),
		this, SLOT(newGameWindow(ChessGame*)));

	gameManager()->newGame(game,
			       new HumanBuilder(userName()),
			       new HumanBuilder(userName()));
}
Example #2
0
void MainWindow::newGame()
{
	EngineManager* engineManager = CuteChessApplication::instance()->engineManager();
	NewGameDialog dlg(engineManager, this);
	if (dlg.exec() != QDialog::Accepted)
		return;

	PlayerBuilder* player[2] = { nullptr, nullptr };
	ChessGame* game = new ChessGame(Chess::BoardFactory::create(dlg.selectedVariant()),
		new PgnGame());

	game->setTimeControl(dlg.timeControl());

	for (int i = 0; i < 2; i++)
	{
		Chess::Side side = Chess::Side::Type(i);

		if (dlg.playerType(side) == NewGameDialog::CPU)
		{
			int index = dlg.selectedEngineIndex(side);
			player[i] = new EngineBuilder(engineManager->engineAt(index));
		}
		else
		{
			player[i] = new HumanBuilder(CuteChessApplication::userName());
			if (side == Chess::Side::White)
				game->pause();
		}
	}

	// Start the game in a new tab
	connect(game, SIGNAL(started(ChessGame*)),
		this, SLOT(addGame(ChessGame*)));
	connect(game, SIGNAL(startFailed(ChessGame*)),
		this, SLOT(onGameStartFailed(ChessGame*)));
	CuteChessApplication::instance()->gameManager()->newGame(game,
		player[0], player[1]);
}
Example #3
0
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
	ChessGame *game = new ChessGame();


	game->board->PrintBoard(); //print board to console for debugging

	if(SDL_Init(SDL_INIT_VIDEO) < 0)//this case happens if SDL does not initialize properly
	{
		fprintf(stderr, "Unable to initialize SDL %s", SDL_GetError());
		exit(1);
	}
	if(SDL_SetVideoMode(windowWidth,windowHeight, 0, SDL_OPENGL) == NULL) //will occur if video mode does not initialize properly
	{
		fprintf(stderr, "Unable to create OpenGL Scene %s", SDL_GetError());
		exit(2);
	}

	game->initGL(windowWidth, windowHeight); //initialize me

	int ind = 0; //temp index

	int done = false;

	//while looping, get event and see if it is the queue, then process those events.
	while (!done)
	{
		//keys1 = SDL_GetKeyState(NULL);


		Uint32 time_before = SDL_GetTicks();   //creates a timestamp of current time in miliseconds

		//Handle Mouse Controls
#pragma region Mouse Controls
		SDL_GetMouseState(&game->state.x, &game->state.y);
		//which button down            //macro, specifying button number                       
		game->state.LeftButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(1);
		game->state.MiddleButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(2);
		game->state.RightButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(3);
#pragma endregion


		game->drawScene();

		Uint32 time_after = SDL_GetTicks(); //creates a timestamp of current time in miliseconds
		int delta = time_after - time_before; //change in time
		int time_wait = (1000/60) - delta; //convert to seconds

		if(time_wait > 0) //delay for x seconds
		{
			SDL_Delay(time_wait);
		}


		SDL_Event event;

		if(SDL_PollEvent(&event)) //poll for events. 
		{
			if(event.type == SDL_QUIT) 
				done = 1;  //exit app
			if(event.type == SDL_KEYDOWN)  
			{
				SDLKey keyPressed = event.key.keysym.sym;
				switch(keyPressed)
				{
				case SDLK_ESCAPE: 
					done = 1; //exit app
					break;
				}
				if((char)keyPressed >='a' && (char)keyPressed <= 'h' || (char)keyPressed >=1 +0x30 && (char)keyPressed <=8+0x30)  //make sure we pressed a coordinate
				{
					Command[ind] = (char) keyPressed;
					ind = (ind+1)%4;
					if(!ind)
						game->buffFull = true;
					else
						game->buffFull = false;
				}
			}
			if(game->buffFull) //after getting 4 characters
			{
				game->populateLegalMoves(); //begin moving
				game->buffFull = false;  //refresh buffer
			}
			keys = SDL_GetKeyState(NULL);

		}

		if(game->checkKeys()) //check for keypresses
			done = 1;

	}
	game->Uninitialize();// shut down glEngine and clean up memory 
	SDL_Quit(); //quit application
	
	return 0;
}
Example #4
0
    //--------------------------------------------------------------
    //  The following function should return true if the Move
    //  was read successfully, or false to abort the game.
    //  The move does not have to be legal; if an illegal move
    //  is returned, the caller will repeatedly call until a
    //  legal move is obtained.
    //--------------------------------------------------------------
    virtual bool ReadMove ( 
        ChessBoard  &board, 
        int         &source, 
        int         &dest, 
        SQUARE      &promPieceIndex )   // set to 0 (P_INDEX) if no promotion, or call to PromotePawn is needed; set to N_INDEX..Q_INDEX to specify promotion.
    {
        promPieceIndex = P_INDEX;

        bool boardWasAlreadyPrinted = AutoPrintBoard;

        // accept either of the following two formats: e2e4, g7g8q
        while (true)
        {
            if (IsFirstPrompt)
            {
                IsFirstPrompt = false;
                TheTerminal.printline("Enter 'help' for info and more options.");
            }
            TheTerminal.print("Your move? ");
            std::string line = TheTerminal.readline();

            // =================================================================
            // REMEMBER:  Update "PrintHelp()" every time you add a command!
            // =================================================================

            if (line == "board")
            {
                ReallyDrawBoard(board);
                boardWasAlreadyPrinted = true;
            }
            else if (line == "help")
            {
                PrintHelp();
            }
            else if (line == "new")
            {                
                if (human)
                {
                    human->SetQuitReason(qgr_startNewGame);     // suppress saying that the player resigned
                }
                return false;   // Start a new game.
            }
            else if (line == "quit")
            {
                throw "Chess program exited.";
            }
            else if (line == "show")
            {
                AutoPrintBoard = true;
                if (!boardWasAlreadyPrinted)
                {
                    ReallyDrawBoard(board);
                    boardWasAlreadyPrinted = true;
                }
            }
            else if (line == "swap")
            {
                if (game)
                {
                    humanSide = OppositeSide(humanSide);
                    if (humanSide == SIDE_WHITE)
                    {
                        game->SetPlayers(human, computer);
                    }
                    else
                    {
                        game->SetPlayers(computer, human);
                    }
                    TheTerminal.print("You are now playing as ");
                    TheTerminal.print(SideName(humanSide));
                    TheTerminal.printline(".");

                    source = 0;
                    dest = SPECIAL_MOVE_NULL;
                    return true;
                }
            }
            else if (line == "time")
            {
                // Adjust computer's think time.
                TheTerminal.print("The computer's max think time is now ");
                TheTerminal.printChessTime(ComputerThinkTime);
                TheTerminal.printline(".");
                TheTerminal.print("Enter new think time (0.1 .. 600): ");
                std::string line = TheTerminal.readline();
                double thinkTime = atof(line.c_str());
                if ((thinkTime >= 0.1) && (thinkTime < 600.0))
                {
                    ComputerThinkTime = static_cast<int>(100.0*thinkTime + 0.5);    // round seconds to integer centiseconds
                    if (computer)
                    {
                        computer->SetTimeLimit(ComputerThinkTime);
                    }
                }
                else
                {
                    TheTerminal.printline("Invalid think time - ignoring.");
                }
            }
            else
            {
                if (ParseFancyMove(line.c_str(), board, source, dest, promPieceIndex))
                {
                    return true;
                }
            }
        }
    }
Example #5
0
void MainWindow::setCurrentGame(const TabData& gameData)
{
	if (gameData.game == m_game && m_game != nullptr)
		return;

	for (int i = 0; i < 2; i++)
	{
		ChessPlayer* player(m_players[i]);
		if (player != nullptr)
		{
			disconnect(player, nullptr, m_engineDebugLog, nullptr);
			disconnect(player, nullptr, m_chessClock[0], nullptr);
			disconnect(player, nullptr, m_chessClock[1], nullptr);
		}
	}

	if (m_game != nullptr)
	{
		m_game->pgn()->setTagReceiver(nullptr);
		m_gameViewer->disconnectGame();
		disconnect(m_game, nullptr, m_moveList, nullptr);

		ChessGame* tmp = m_game;
		m_game = nullptr;

		// QObject::disconnect() is not atomic, so we need to flush
		// all pending events from the previous game before switching
		// to the next one.
		tmp->lockThread();
		CuteChessApplication::processEvents();
		tmp->unlockThread();

		// If the call to CuteChessApplication::processEvents() caused
		// a new game to be selected as the current game, then our
		// work here is done.
		if (m_game != nullptr)
			return;
	}

	m_game = gameData.game;

	lockCurrentGame();

	m_engineDebugLog->clear();

	m_moveList->setGame(m_game, gameData.pgn);

	if (m_game == nullptr)
	{
		m_gameViewer->setGame(gameData.pgn);

		for (int i = 0; i < 2; i++)
		{
			ChessClock* clock(m_chessClock[i]);
			clock->stop();
			clock->setInfiniteTime(true);
			clock->setPlayerName(gameData.pgn->playerName(Chess::Side::Type(i)));
		}

		updateWindowTitle();

		return;
	}
	else
		m_gameViewer->setGame(m_game);

	m_tagsModel->setTags(gameData.pgn->tags());
	gameData.pgn->setTagReceiver(m_tagsModel);

	for (int i = 0; i < 2; i++)
	{
		ChessPlayer* player(m_game->player(Chess::Side::Type(i)));
		m_players[i] = player;

		connect(player, SIGNAL(debugMessage(QString)),
			m_engineDebugLog, SLOT(appendPlainText(QString)));

		ChessClock* clock(m_chessClock[i]);

		clock->stop();
		clock->setPlayerName(player->name());
		connect(player, SIGNAL(nameChanged(QString)),
			clock, SLOT(setPlayerName(QString)));

		clock->setInfiniteTime(player->timeControl()->isInfinite());

		if (player->state() == ChessPlayer::Thinking)
			clock->start(player->timeControl()->activeTimeLeft());
		else
			clock->setTime(player->timeControl()->timeLeft());

		connect(player, SIGNAL(startedThinking(int)),
			clock, SLOT(start(int)));
		connect(player, SIGNAL(stoppedThinking()),
			clock, SLOT(stop()));
	}

	updateWindowTitle();
	unlockCurrentGame();
}
Example #6
0
void diagonal_moves(ChessGame& g, Square pos, char symbol, vector<UserMove>& vec)
{
    UserMove tmp;
    tmp.symbol = symbol;
    tmp.pos = pos;

    /// search up and right
    for (int i = 1; i < 8; i++)
    {
        if (!pos.next(i, i).valid())
        {
            break;
        }

        char c = g.get_piece(pos.next(i, i));
        if (c == ' ')
        {
            tmp.dest = pos.next(i, i);
            vec.push_back(tmp);
        } else if ((g.white() && islower(c)) || (!g.white() && isupper(c)))
        {
            tmp.dest = pos.next(i, i);
            tmp.capture = true;
            vec.push_back(tmp);
            break;
        } else
        {
            break;
        }
    }
    tmp.capture = false;

    /// search down and right
    for (int i = 1; i < 8; i++)
    {
        if (!pos.next(i, -1 * i).valid())
        {
            break;
        }

        char c = g.get_piece(pos.next(i, -1 * i));
        if (c == ' ')
        {
            tmp.dest = pos.next(i, -1 * i);
            vec.push_back(tmp);
        } else if ((g.white() && islower(c)) || (!g.white() && isupper(c)))
        {
            tmp.dest = pos.next(i, -1 * i);
            tmp.capture = true;
            vec.push_back(tmp);
            break;
        } else
        {
            break;
        }
    }
    tmp.capture = false;


    /// search up and left
    for (int i = 1; i < 8; i++)
    {
        if (!pos.next(-1 * i, i).valid())
        {
            break;
        }

        char c = g.get_piece(pos.next(-1 * i, i));
        if (c == ' ')
        {
            tmp.dest = pos.next(-1 * i, i);
            vec.push_back(tmp);
        } else if ((g.white() && islower(c)) || (!g.white() && isupper(c)))
        {
            tmp.dest = pos.next(-1 * i, i);
            tmp.capture = true;
            vec.push_back(tmp);
            break;
        } else
        {
            break;
        }
    }
    tmp.capture = false;

    /// search down and left
    for (int i = 1; i < 8; i++)
    {
        if (!pos.next(-1 * i, -1 * i).valid())
        {
            break;
        }

        char c = g.get_piece(pos.next(-1 * i, -1 * i));
        if (c == ' ')
        {
            tmp.dest = pos.next(-1 * i, -1 * i);
            vec.push_back(tmp);
        } else if ((g.white() && islower(c)) || (!g.white() && isupper(c)))
        {
            tmp.dest = pos.next(-1 * i, -1 * i);
            tmp.capture = true;
            vec.push_back(tmp);
            break;
        } else
        {
            break;
        }
    }
}