Esempio n. 1
0
Board* MinimaxDecision(Board* board, int turn, clock_t st){
    BoardQueue *q;
    q = board->successor(turn);
    cout << endl;
    
    Board* tmpboard = NULL;
    int tmpvalue = -99999;
    int min;
    
    while(!q->isEmpty()){
        Board* b = q->dequeue();
        min = MinValue(b, changeTurn(turn),st);
        if(min > tmpvalue){
            tmpvalue = min;
            if(tmpboard != NULL){
                Board* tmmp = tmpboard;
                tmpboard = b;
                delete tmmp;
            }else{
                tmpboard = b;
            }
        }else{
            delete b;/////// Burayı control et hacıııı
        }
    }
    tmpboard->resetLevel();
    cout << "Min : " << tmpvalue << endl;
    return tmpboard;
}
Esempio n. 2
0
void Game::tryMovement(int vaoId, int caseX, int caseY)
{
    Player &current = (turn == 1)?player1:player2;
    Player &opponent = (turn == 1)?player2:player1;
    Piece *current_piece = current.getPieceByVao(vaoId);

    if (current_piece != nullptr)
    {
        std::cout << "--> Player " << turn << " selected vao" << vaoId << "(" << current_piece->getPosition()[0] << ";" << current_piece->getPosition()[1] << ") and clicked on cell (" << caseX << "," << caseY << ")" <<  std::endl;

        if (current_piece->canMoveTo(caseX, caseY))
        {
            std::vector<int> tempPos = current_piece->getPosition();
            current_piece->moveTo(caseX,caseY);
            opponent.computeAvailableMovements(opponent.getPieces(),current.getPieces());
            if (check(current, opponent, current.getKing()->getPosition()).size() == 0){
                current_piece->moveTo(tempPos);
                ejectPiece(caseX, caseY);
                board.movePieceTo(current_piece->getVaoID(), caseX, caseY);
                changeTurn();
            }else{
                std::cout  << "\tMouvement non valide, votre roi est en échec !\n";
                current_piece->moveTo(tempPos);
                opponent.computeAvailableMovements(opponent.getPieces(),current.getPieces());

            }

        }
        else{
            std::cout  << "\tMouvement non valide\n"; }
    }
    else
        std::cout << "--> Player " << turn << " selected vao" << vaoId << " and clicked on cell (" << caseX << "," << caseY << ") VAO NULLPOINTER" <<  std::endl;
}
void GameMainWindow::newGame()
{
  gameController = new GameController();
  startDialog = new StartDialog(this);

  this->setupConnections();

  if(startDialog->exec() == QDialog::Accepted)
    {
      gameBoard = new GameBoard(this);
        connect(gameController, SIGNAL(triggerPlanetLocate(Planet*, int, int)), gameBoard, SLOT(onAddPlanet(Planet*, int, int)));
	connect(gameBoard, SIGNAL(changeTurn()), gameController, SLOT(onChangeTurn()));
	connect(gameController, SIGNAL(displayControl(QString)), gameBoard, SLOT(onDisplayControl(QString)));
	connect(gameController, SIGNAL(displayInfo(QString)), gameBoard, SLOT(onDisplayInfo(QString)));
	connect(gameController, SIGNAL(displayShipNumber()), gameBoard, SLOT(onDisplayShipNumber()));
	connect(gameBoard, SIGNAL(setFleetShipNumber(int)), gameController, SLOT(onSetFleetShipNumber(int)));
	gameController->onStartGame();

	fleetAction->setEnabled(true);
	this->setCentralWidget(gameBoard);

      
    }
  else
    {
      delete gameController;
    }
}
Esempio n. 4
0
/*
	Reset the board and display.
*/
void ViewBoard::reset()
{
	m_negamax	->reset();
	m_cubeWid	->reset();

	changeTurn();
}
Esempio n. 5
0
/*
	Computer turn to move
	Connected from TTT3DNegamax.
	This function will only be called if the game is active and computer is enabled.
*/
void ViewBoard::computerMove(int move)
{
	if (!m_computerEnabled)
		return;

	// translating 1D location in the array to 3D location for the Cube to display.
	int x, y, z, temp, current;
	z 		= move%3;
	temp 		= move/3;
	y		= temp%3;
	x		= temp/3;

	// set the location.
	m_cubeWid	->setAxis(x, y, z);

	current		= m_negamax->currentPlayer();
	// mark the cube.
	m_cubeWid	->markCube((Cube::PlayerCube)(current ^= 0x3));

	if(m_negamax	->checkVictory())
		return;

	m_cubeWid	->grabKeyboard();
	changeTurn();
	current		^= 0x3;

	setCursor(QCursor(Qt::ArrowCursor));

	/*
		Find out who is the next one to go.
		Mainly concern if the next player is a computer,
			if not, this function will return and await the next human player to click.
		When computer is in the process of moving, all keyboard inputs are blocked.
	*/
	if (current == 1)
	{
		if (m_player1 == Computer)
		{
			m_cubeWid	->releaseKeyboard();
			setCursor(QCursor(Qt::BusyCursor));
			m_negamax	->computerMove(1);
		}
	}
	else if (current == 2)
	{
		if (m_player2 == Computer)
		{
			m_cubeWid	->releaseKeyboard();
			setCursor(QCursor(Qt::BusyCursor));
			m_negamax	->computerMove(2);
		}
	}
}
Esempio n. 6
0
int MinValue(Board* state, int turn, clock_t st){
    int beta = 99999;
    if(CutOffTest(state, st)){        
        return state->getValue();
    }
    
    BoardQueue *q;
    q = state->successor(turn);
    //    cout << endl;
    while(!q->isEmpty()){
        Board* s = q->dequeue();
        beta = Min(beta, MaxValue(s,changeTurn(turn), st));
        delete s;
    }
    delete q;
    return beta;
}
Esempio n. 7
0
/*
	Human player has selected a move.
	Find out which square is activated; translate the location in grid
		to 1D array of the game board (stored in TTT3DNegamax).
*/
void ViewBoard::humanMove(int move)
{	// move comes from Cube.
	int current;
	bool good;
	current		= m_negamax->currentPlayer();

	// not blank, return
	good = m_cubeWid->markCube((Cube::PlayerCube)(current));
	if (!good)
		return;

	// make the move in TTT3DNegamax (marking the board array).
	m_negamax	->makeMove(move, current);
	if (m_negamax	->checkVictory())
		return;

	changeTurn();
	current		^= 0x3;

	/*
		Find out who is the next one to go.
		Mainly concern if the next player is a computer,
			if not, this function will return and await the next human player to click.
		When computer is in the process of moving, all keyboard inputs are blocked.
	*/
	if (current == 1)
	{
		if (m_player1 == Computer)
		{
			m_cubeWid	->releaseKeyboard();
			setCursor(QCursor(Qt::BusyCursor));
			m_negamax	->computerMove(1);
		}
	}
	else if (current == 2)
	{
		if (m_player2 == Computer)
		{
			m_cubeWid	->releaseKeyboard();
			setCursor(QCursor(Qt::BusyCursor));
			m_negamax	->computerMove(2);
		}
	}
}
Esempio n. 8
0
void check(int pick,int initime)
{
    int time = initime - clock();
    if(count==pick)
    {
        if(time<WAIT_TIME)
        {
            winTimes++;
            changeTurn();
        }
        else
        {
            Loser();
        }
    }
    else
    {
        Loser();
    }
}
Esempio n. 9
0
void Application::update(){
	static float lastTime = SDL_GetTicks() / 1000.0f;
	//static float windDelay = WIND_DELAY;

	float timeSinceLastTime = (SDL_GetTicks() / 1000.0f) - lastTime;
	lastTime = SDL_GetTicks() / 1000.0f;

	if(toChangeTurn){
		changeTurn();
	}
	joinServerOrHostServer();
	if(isBotGame){
		createBot();
	}
	if(!isBotGame){
		createSecondPlayer();
	}	
			
	handleReceivedData();
	Object::updateAll(timeSinceLastTime);
	
}
Esempio n. 10
0
int Game::update()
{
	//This is probably graphical stuff and thus commented out
	//int currTime = (int)clock.getElapsedTime().asSeconds() + timeOffset;
	// Update clockstring
	//This is probably graphical stuff and thus commented out
	//clockText.setString(std::to_string(currTime / 60) + ":" + std::to_string(currTime % 60));
	 // Make sure that no moves is asked after checkmate or stalemate
			// Start new thread and calculate time elapsed for algorithm
			//clock.restart();
	std::pair<int, int> aimove = getAiMove();
	movePiece(aimove);
	//std::cout << "AI(lvl:" << playerOnTurn->getLevel() << ") calculated next turn in " << std::endl;



	


	return changeTurn();

}
Esempio n. 11
0
void GameBoard::onTurnButton()
{
  emit changeTurn();
}
Esempio n. 12
0
int bestMJalt(PGAME orgGame, PGAME game, int d, int f, int returnScore){
    
    int i;
    int bestIndex = 0;
    int bestIndexScore = 0;
    
    
    
    for(i = 0; i < game->mjCount && d > 0; i++){
        
        
        GAME newGame;
        
        memcpy(&newGame, game, sizeof(GAME));
        
        if (newGame.canJ) {
            makeJump(i, &newGame);
        }else{
            makeMove(i, &newGame);
        }
        
        changeTurn(&newGame);
        cleanUp(&newGame);
        
        findJumpersForGame(&newGame);
        
        if (!newGame.canJ) {
            findMoversForGame(&newGame);
        }
        
        
        int tempScore;
                
        if(f > 0 && d > 0){
            tempScore = bestMJalt(orgGame, &newGame, d-1, f, 1);
        }        
        
        if(tempScore > bestIndexScore){
            bestIndexScore = tempScore;
            bestIndex = i;
            
        }else{
            
            if(tempScore == bestIndexScore && returnScore == 0){
                if(rand()%2 == 0){
                    bestIndexScore = tempScore;
                    bestIndex = i;
                }                
            }
            
        }

        
        
    }
    
    
    if(game->turn != orgGame->turn)
    bestIndexScore = -bestIndexScore;
    
    if(returnScore)
    return bestIndexScore;
    
    return bestIndex;
}
Esempio n. 13
0
int bestMJ(PGAME orgGame, PGAME game, int d, int f){

    int i;
    int bestIndex = 0;
    int bestIndexScore = 0;
    
    
    
    for(i = 0; i < game->mjCount && d > 0; i++){
        
            
        GAME newGame;
        
        memcpy(&newGame, game, sizeof(GAME));
        
        if (newGame.canJ) {
            makeJump(i, &newGame);
        }else{
            makeMove(i, &newGame);
        }
        
        changeTurn(&newGame);
        cleanUp(&newGame);
        
        findJumpersForGame(&newGame);
        
        if (!newGame.canJ) {
            findMoversForGame(&newGame);
        }
        
        
        int tempScore = scoreGames(orgGame, &newGame);
       
        if(tempScore > bestIndexScore){
            bestIndexScore = tempScore;
            bestIndex = i;
            f++;

        }else{
            
            if(tempScore == bestIndexScore){
                if(rand()%2 == 0){
                    bestIndexScore = tempScore;
                    bestIndex = i;
                }
                f++;

            }else{
                f--;

            }
            
        }
        
        
        
        if(f > 0 && d > 0){
            bestMJ(orgGame, &newGame, d-1, f);
        }
        
        
    }

    return bestIndex;
}
Esempio n. 14
0
void PlayingState::changeTurn() {
    changeTurn((turnTeam == Team::BLUE) ? Team::RED : Team::BLUE);
}
Esempio n. 15
0
void PlayingState::update(const float dt) {
    sf::Vector2i mousePos = sf::Mouse::getPosition(game->window);
    game->updateCursorHelper(task == Task::PlacementTransition, mousePos);

    std::list<Animation*>::iterator i = animations.begin();
    while(i != animations.end()) {
        if((*i)->update(dt) == false) {
            i = animations.erase(i);
        } else {
            ++i;
        }
    }

    playButton->contains(mousePos);

    for(Player* player : players) {
        if(player->contains(mousePos)) {
            if(!player->getSelectable()) {
                game->updateCursorHelper(true, mousePos);
            }
        }
    }

    for(FieldCard* card : fieldCards) {
        card->contains(sf::Mouse::getPosition(game->window));
    }


    for(ActionCard* card : currentCards) {
        card->contains(sf::Mouse::getPosition(game->window));
    }

    if(task == Task::PlacementTransition) {
        needleRotation += needleVel * dt;
        if(needleRotation > 360) needleRotation -= 360;

        rouletteNeedle.setRotation(needleRotation);
        if(needleVel > 0) {
            needleVel -= 1000.0f * dt;
        } else {
            needleVel = 0;
            Team selectedTeam = (needleRotation >= 180.0f) ? Team::BLUE : Team::RED;
            
            animations.push_back(new PosAnimation(*playButton,
                                                  playButton->getPosition() + sf::Vector2f(600.0f, 0.0f),
                                                  2.0f, Easing::INOUT));
            animations.push_back(new PosAnimation(roulette,
                                                  roulette.getPosition() + sf::Vector2f(600.0f, 0.0f),
                                                  2.2f, Easing::INOUT));
            animations.push_back(new PosAnimation(rouletteNeedle,
                                                  rouletteNeedle.getPosition() + sf::Vector2f(600.0f, 0.0f),
                                                  2.2f, Easing::INOUT));

            for(Player* player : players) {
                if(player->gameCoords == sf::Vector2i(2, 1) && selectedTeam == player->team) {
                    moveBallToPlayer(player);
                    task = Task::ActionSelection;
                    changeTurn(selectedTeam);
                    updateTextScore();
                    drawableEntities.push_back(&textAP);
                    return;
                }
            }
        }
    }

    updatePlayerHalo();
}
Esempio n. 16
0
//função irá atualizar a situação atual do tabuleiro e suas condições
FEN* updateFEN (FEN* fen, OBJETO *** const table, PLAY * play)
{
	changeTurn (fen);

	// ************************************************* atualizar a configuração do tabuleiro no fen
	char *update = (char*)malloc(sizeof(char));
	*update = '\0';
	int i, j;
	int spaces;
	int size;
	for(i = 0; i < TABLE_ROWS; i++)
	{
		spaces = 0;
		for(j = 0; j < TABLE_COLS; j++)
		{
			//contagem de espaços vazios
			if(table[i][j] == NULL)
				spaces ++;
			//acréscimo de espaços e de peças na notação
			else
			{
				size = strlen(update);
				//se houve espaços entre peças na horizontal acrescental o salto na notação
				if(spaces)
				{
					update = (char*)realloc(update, sizeof(char)*(++size + 1));
					update[size - 1] = '0' + size;
				}
				//acréscimo das peças na notação
				update = (char*)realloc(update, sizeof(char)*(++size + 1));
				update[size - 1] = getType(table[i][j]);
			}
		}
		if(spaces)
		{
			size = strlen(update);
			update = (char*)realloc(update, sizeof(char)*(++size + 1));
			update[size - 1] = '0' + size;
		}
		//adicionar uma barra para cada linha do tabuleiro
		size = strlen(update);
		update = (char*)realloc(update, sizeof(char)*(++size + 1));
		update[size - 1] = '/';
	}

	//eliminar a ultima '/' da string
	size = strlen(update);
	update = (char*)realloc(update, sizeof(char)*(--size + 1));
	update[size] = '\0';

	int turn = (fen->turn == 'w') ? 1: 0;

	// ********************************* verificar condições de roque futuro
	char *newRock = (char*)malloc(sizeof(char));
	strcpy(newRock, "");
	int adj = 7;

	//analisar a jogada anterior
	turn = !turn;

	strcpy(fen->rock, "-");
	if(getType(table[adj * turn][4]) == 'k' - (32 * turn))
	{
		int rockSize = strlen(fen->rock);
		int newSize = 0;
		char *paux = fen->rock;
		int i;
		for(i = 0; i < rockSize; i++)
		{
			if(paux[i] == 'q' - !turn * 32)
			{
				newSize = strlen(newRock);
				newRock = (char*)realloc(newRock, sizeof(char)*(++newSize + 1));
				newRock[newSize - 1] = 'q' - !turn * 32;
			}
			//verificar se a torre para lado da rainha não foi movida
			else if(paux[i] == 'q' - turn * 32 && getType(table[adj * turn][0]) == 'q' - turn * 32)
			{
				newSize = strlen(newRock);
				newRock = (char*)realloc(newRock, sizeof(char)*(++newSize + 1));
				newRock[newSize - 1] = 'q' - turn * 32;
			}

			else if(paux[i] == 'k' - !turn * 32)
			{
				newSize = strlen(newRock);
				newRock = (char*)realloc(newRock, sizeof(char)*(++newSize + 1));
				newRock[newSize - 1] = 'k' - !turn * 32;
			}
			//verificar se a torre para o lado do rei não foi movida
			else if(paux[i] == 'k' - turn * 32 && getType(table[adj * turn][0]) == 'k' - turn * 32)
			{
				newSize = strlen(newRock);
				newRock = (char*)realloc(newRock, sizeof(char)*(++newSize + 1));
				newRock[newSize - 1] = 'k' - turn * 32;
			}

		}//for
		if(newSize)
			strcpy(fen->rock, newRock); //->rock contem por padrão "", a ser modificada pelo switch
	}

	// ********************************* verificar descartar formação de en passant anterior e verificar a atual
	strcpy(fen->pass, "-");
	for(i = 0; i < TABLE_COLS; i++)
	{
		//se o turno é do White então os peões estão na linha 5 da matriz, senão, na linha 2 da matriz.
		if(table[adj * turn + 2 - 4*turn][i] == play->obj && getType(play->obj) == 'p' - turn * 32)
		{
			//função update será chamada antes de atualizar a coordenada da struct da peça
			int diff = abs(play->fromRow - getObjectRow(play->obj));

			//se houve salto de 2 casas do peão
			if(diff == 2)
			{
				char newPass[3];
				newPass[0] = 'a' + i;
				newPass[1] = '1' + 7*!turn - 1 + 2*turn;
				newPass[2] = '/';
				strcpy(fen->pass, newPass);
			}
			break;
		}
	}

	// ********************************** verificar o acréscimo do meio turno
		//se movimento foi feito de peão ou foi feito uma captura
	if(getType(play->obj) == 'p' - turn * 32 || fen->fullTurn == getObjectTurn (play->obj))
		fen->halfTurn ++;

	// ********************************** verificar o acréscimo do turno completo
		//se a jogada foi feita pela lado Preto
	if(turn)
		fen->fullTurn++;

	//voltar para o turno atual
	turn = !turn;

	//guardar a nova notação do estado atual do tabuleiro
	strcpy(fen->pieces, update);

	return fen;
}