Пример #1
0
static int playOut(struct Board* board){
    struct Move moves[MAX_MOVES];
    int moveCount = getMoves(board, moves, 1);
    enum Color turn = board->turn;
    
    struct Move* move;
    
    int depth = 0;
    while(moveCount > 0 && depth < MAX_SIM_DEPTH){
        //TODO: switch to Mersenne twister RNG
        
        move = &moves[rand() % moveCount];
        
        //If forcing a capture, find a random capture move
        if(((double) rand() / (double) RAND_MAX) < SIM_FORCE_CAPTURE_CHANCE
           && board->pinCount[!turn] > 1){
            
            struct Move captureMoves[MAX_MOVES];
            int captureCount = getCaptureMoves(moves, moveCount, captureMoves);
            
            if(captureCount){
                move = &captureMoves[rand() % captureCount];
            }
        }
        
        makeMove(board, move);
        moveCount = getMoves(board, moves, 1);
        depth++;
    }
    
    //If max depth reached
    if(depth == MAX_SIM_DEPTH){
        if(board->pinCount[turn] > board->pinCount[!turn]){
            return 1;
        } else if(board->pinCount[!turn] > board->pinCount[turn]){
            return -1;
        } else{
            return 0;
        }
    }
    
    //If a win is found
    if(moveCount == -1){
        if(board->turn == turn){
            return 1;
        }else{
            return -1;
        }
    }
    
    //Draw due to no moves
    return 0;
}
Пример #2
0
/*Build Minimax Tree of fixed depth via DFS*/
MinimaxNode *getMinimaxTreeFixedDepth(Game *game, int depth, Move *move, Color uCol) {
    MinimaxNode *curr = (MinimaxNode*)malloc(sizeof(MinimaxNode));
    if (curr == NULL) exitOnError("malloc");
    curr->game = (Game*)malloc(sizeof(Game));
    if (curr->game == NULL) exitOnError("malloc");
    struct ListNode *moves;
    int i = 0;
    curr->depth = depth;
    copyGame(game, curr->game);
    curr->sons = NULL;
    curr->sonsK = 0;
    if (move != NULL) {
        updateBoard(curr->game, move);
    }
    if (depth == 1) {
        curr->move = move;
    }
    else {
        freeMove(move);
        curr->move = NULL;
    }
    if (depth == game->difficulty) {
        return curr;
    }
    if ((depth % 2 == 0 && uCol == WHITE) || (depth % 2 == 1 && uCol == BLACK)) {
        moves = getMoves(curr->game, WHITE);
    }
    else {
        moves = getMoves(curr->game, BLACK);
    }
    int size = listSize(moves);
    curr->sonsK = size;
    if (!size) {
        free(moves);
        return curr;
    }
    else {
        curr->sons = (MinimaxNode**)malloc(sizeof(MinimaxNode)*size);
        if (curr->sons == NULL) exitOnError("malloc");
        struct ListNode *temp = moves;
        for (i = 0; i < size; i++) {
            Move* tMove = copyMove(temp->move);
            curr->sons[i] = getMinimaxTreeFixedDepth(curr->game, depth + 1, tMove, uCol);
            temp = temp->next;
        }
        freeList(moves);
    }
    return curr;
}
Пример #3
0
void execute(Robot *r, int *b)
{
	Move *m = getMoves(r);
	int i;
	
  #pragma omp for private(i)
	for (i=0;i<4;++i)
  {
    Move move = *(m+i);
	  if (moveValid(move,b))
    {
	    if (isFinal(move))
	      myResult++;
	    else 
      {
	      Robot *newRobot = (Robot*)malloc(sizeof(Robot));
	      newRobot->x = move.x;
	      newRobot->y = move.y;
	      newRobot->steps = r->steps+1;
	      newRobot->r = r;
	      execute(newRobot,b);
	      free(newRobot);
	    }
	  }
	}
	free(m);
}
Пример #4
0
bitboard Chess::getPieceMoves(const int sq_source)
{

    //Init all moves to 0;
    memset(moves, 0, STORE_SIZE*sizeof(move));

    int player = pos.toPlay;
    int piece = getPieceToPlay(sq_source);
    int numMoves = 0;
    numMoves += getMoves(&pos, player, piece, NORMAL, &moves[numMoves]);
    numMoves += getMoves(&pos, player, piece, CAPTURE, &moves[numMoves]);

    bitboard realMoves = 0;
    realMoves = getRealMoves(moves, sq_source, numMoves);
    return realMoves;
}
Пример #5
0
void FlowContextController::startRoute(QPoint location)
{
    if (!isInRange(location)) return;

    int dot_color = m_board->getColorAt(location);
    int context_color = m_stable->getColorAt(location);
    int color = dot_color != -1 ?
                dot_color : context_color;

    setCurrentColor(color);

    if (getCurrentColor() == -1)
        // on the board
        return;

    // update moves count
    if (getCurrentColor() != m_previous_legal_color) {
        setMoves(getMoves() + 1);
        // save for undo
        m_undo.push(new FlowContext(m_board, this));
        m_stable->cloneTo(*m_undo.top());
    }
    m_previous_legal_color = getCurrentColor();

    if (dot_color != -1)
        // is a terminal
        m_current_route.clear();
    else
        // is on a existing route
        m_current_route = m_stable->getRouteOf(color);
    m_stable->clearRouteOf(color);

    newRoutePoint(location);
}
Пример #6
0
treeNode* myTree(treeNode *head,char inBoard[BOARDROWS][BOARDCOLS],char pColour, char cColour){
    char boardHolder[BOARDROWS][BOARDCOLS];
    int numChildren;
    node* ptr;
    if (head->board[0][0] != 'W' && head->board[0][0] != 'B' && head->board[0][0] != 'O' ){  
        copyBoard(inBoard,head->board);
    }
    if (head->numChildren == 0){
        node* moves = getMoves(head->board,cColour,pColour);
        numChildren = getListSize(moves);
        head->numChildren = numChildren;
        //printf("Generated %i moves from the head node.\n", numChildren);
        head->children = malloc(sizeof(treeNode) * numChildren);
        for(int i=0;i<numChildren;i++){
	  // printf("for\n");
            copyBoard(head->board,boardHolder);
            applyMove(moves,boardHolder);
	    //printBoard(boardHolder);
            head->children[i] = malloc(sizeof(treeNode));
            copyBoard(boardHolder,head->children[i]->board);
            head->children[i]->numChildren = 0;
	    ptr = moves->next;
	    free(moves);
	    moves = ptr;
        }
    }else{//this should happen when there are already children in the tree
      for(int i=0;i<head->numChildren;i++){
	head->children[i] = myTree(head->children[i],head->children[i]->board,cColour,pColour);
      }
    }
    return head;
}
void MoveEliminationPass::runOnKernel(ir::IRKernel& k)
{
	report("Eliminating moves in kernel " << k.name << "");
	
	auto dfg = static_cast<analysis::DataflowGraph*>(
		getAnalysis("DataflowGraphAnalysis"));
	assert(dfg != 0);

	dfg->convertToSSAType(analysis::DataflowGraph::Minimal);

	auto moves = getMoves(dfg);
	
	bool eliminatedAny = false;
	
	report(" Eliminating moves");
	
	for(auto move = moves.begin(); move != moves.end(); ++move)
	{
		if(canEliminate(*move))
		{
			report("  " << (*move)->i->toString());
			eliminate(*move);
			eliminatedAny = true;
		}
	}
	
	if(eliminatedAny)
	{
		invalidateAnalysis("DataflowGraphAnalysis");
	}
	
	report("finished...");
}
Пример #8
0
void ConsoleManager::probeBook() const {
  uint64_t hash = record_.getBoard().getHash();
  auto p = book_.find(hash);
  if (p == nullptr) {
    std::cout << "(empty)" << std::endl;
    return;
  }

  uint32_t totalCount = p->getCount();
  const auto& bookMoves = p->getMoves();

  struct Element {
    Move move;
    uint32_t count;
  };
  std::vector<Element> moves;
  for (const auto& bookMove : bookMoves) {
    moves.push_back({ bookMove.move, bookMove.count });
  }
  std::sort(moves.begin(), moves.end(), [](const Element& l, const Element& r) {
    return l.count > r.count;
  });
  for (const auto& element : moves) {
    float percentage = (float)element.count / totalCount * 100.0f;
    std::cout << element.move.toString() << "(" << std::fixed << std::setprecision(1) << percentage << "%) ";
  }
  std::cout << std::endl;
}
Пример #9
0
list<square> Rook::selectPiece(){
	list<square> moves;
	if(active){
		selected = true;
		getMoves(moves);
	}
	return moves;
}
Пример #10
0
struct Move think(struct Board* board){
    int start = time(0);

    struct Move moves[MAX_MOVES];
    int moveCount = getMoves(board, moves, 1);
    int i;
    
    //Take a win without thinking
    if(moveCount == -1){
        fprintf(stderr, "Taking win. Good game!\n");
        return moves[0];
    }
        
    struct Node* root = makeNode(NULL, moves[0]); //Second arg meaningless here
    int iterations;
    for(iterations = 0; iterations < ITERATIONS ; iterations++){
        struct Board testBoard = *board;

        float result = solver(&testBoard, root);
        if(result == INFINITY || result == -INFINITY){
            break;
        }
    }

    //Final move selection
    float bestScore = -INFINITY;
    struct Node* bestChild = NULL;
    for(i = 0; i < root->childrenCount; i++){
        struct Node* child = root->children[i];
        float score = -child->value + (AK / sqrt(child->visits));

        if(score >= bestScore){
            bestScore = score;
            bestChild = child;
        }
    }

    struct Move finalMove = bestChild->move;
    
    int end = time(0);
    
    int elapsed = end - start;
    
    //TODO: can't remember the stderr output functions except fprintf--fix once have internet
    fprintf(stderr, "Move:\t\t");
    printMoveStdErr(&finalMove);
    fprintf(stderr, "\n");
    fprintf(stderr, "Score:\t\t%f\n", -bestChild->value);
    fprintf(stderr, "Visits:\t\t%d\n", bestChild->visits);
    fprintf(stderr, "Focus:\t\t%f\n", 100.0*bestChild->visits/iterations);
    fprintf(stderr, "Iterations:\t%d\n", iterations);
    fprintf(stderr, "Elapsed:\t%ds\n", elapsed);
    fprintf(stderr, "\n");

    freeNode(root);
    
    return finalMove;
}
Пример #11
0
minimaxRes minimaxPru(gameState* state, int depth, minimaxRes alpha, minimaxRes beta, int isMax){
	char colorOfPlayer = state->turn;
	char colorOfEnemy = BLACK;
	gameState* currState = (gameState*)malloc(sizeof(gameState));
	minimaxRes toRet;
	int index = 0, turn = 1;
	piece** currBoard;
	if (colorOfPlayer == BLACK){
		colorOfEnemy = WHITE;
		turn = -1;
	}
	if (depth == 0){ // End of rec
		toRet.index = 0;
		toRet.value = isMax * turn * scoreOfBoard(state);
		if (toRet.value == 4000)
			toRet.value *= -1;
		free(currState);
		return toRet;
	}
	itemMove* moves = getMoves(state);
	itemMove* head = moves;
	if (&(head->move) == NULL){//Is a leaf
		toRet.index = 0;
		toRet.value = isMax *  turn * scoreOfBoardWith(state, moves);
		if (toRet.value == 4000)
			toRet.value *= -1;
		destroyMoveList(moves);
		free(currState);
		return toRet;
	}
	while (head != NULL){
		if (!isMateWith(state,moves)){
			currBoard = makeMove(state->board, (head));
			copyDtoS(currState->board, currBoard);
			destroyBoard(currBoard);
			currState->turn = colorOfEnemy;
			if (beta.value <= alpha.value){

				break;
			}
			toRet = minimaxPru(currState, depth - 1, alpha, beta, -1 * isMax);
			if (isMax==1)
				replaceMMRs(&alpha, &toRet, isMax, index);
			else
				replaceMMRs(&beta, &toRet, isMax, index);
			head = head->next;
			index++;
		}
	}
	destroyMoveList(moves);
	free(currState);
	if (isMax==1)
		return alpha;
	else
		return beta;
}
Пример #12
0
static float solver(struct Board* board, struct Node* node){
    int i;

    //If the node's children haven't been generated, generate them
    if(node->childrenCount == NEEDS_CHILDREN){
        struct Move moves[MAX_MOVES];
        node->childrenCount = getMoves(board, moves, 1);

        for(i = 0; i < node->childrenCount; i++){
            struct Node* child = makeNode(node, moves[i]);
            node->children[i] = child;
        }
    }

    //If there's a win, take it. If there's no children, it's a draw.
    if(node->childrenCount == -1){
        update(node, INFINITY);
        return INFINITY;
    }else if(node->childrenCount == 0){
        //TODO: do we need to make this game-theoretical?
        update(node, 0);
        return 0;
    }

    struct Node* bestChild = select(node);
    makeMove(board, &bestChild->move);

    float r; //result for node value this iteration, *always from this node's perspective*

    if(bestChild->value != INFINITY && bestChild->value != -INFINITY){
        //If the nodes has no visits, simulate it
        if(bestChild->visits < MIN_SIMS){
            r = -playOut(board);
            update(bestChild, -r);
        }else{
            //Else go farther down the tree
            r = -solver(board, bestChild);
        }
    }else{
        //Game-theoretical value
        r = -bestChild->value;
    }

    if(r == -INFINITY){
        for(i = 0; i < node->childrenCount; i++){
            if(-node->children[i]->value != -INFINITY){
                r = -1;
                break;
            }
        }
    }
    
    update(node, r);
    return r;
}
void PokeMovesModel::loadData()
{
    QHash<int, QString> sets = getMoves(id, gen);
    storage.clear();

    foreach(int key, sets.uniqueKeys()) {
        storage.insert(MoveInfo::Name(key), QPair<int, QString>(key, sets[key]));
    }

    names = storage.keys();
}
Пример #14
0
//Print specific Commercial Ship info
void Commercial::printInfo() const
{
	cout << "\n\n--------------------------------------------------------------------------------" << endl;
	cout << "Information about the commercial ship C" << to_string(getID())[1] << to_string(getID())[2] << " at the map point [" << getX() << "," << getY() << "] :" << endl;
	cout << "\tCurrent Endurance : " << getCurEndur() << endl;
	cout << "\tTreasure Reserve : " << getTreasFund() << endl;
	cout << "\tSpeed : " << getSpeed() << endl;
	cout << "\tPositions moved since the beginning : " << getMoves() << endl;
	cout << "\tTreasure gained from port visits  since the beginning : " << getTreasPort() << endl;
	cout << "\tDamage taken since the beginning : " << getDamageTaken() << endl;
	cout << "--------------------------------------------------------------------------------\n\n" << endl;
}
QHash<int, QString> getMoves(const Pokemon::uniqueId &num, int gen, bool root = true) {
    QHash<int, QString> ret;
    if (gen != 1 && gen != 3) {
        ret = getMoves(num, gen-1, false);
    }
    return ret.unite(map_container_with_value(PokemonInfo::TMMoves(num, gen), root ? QObject::tr("TM/HM") : QObject::tr("%1G TM/HM").arg(gen)))
              .unite(map_container_with_value(PokemonInfo::TutorMoves(num, gen), root ? QObject::tr("Tutor") : QObject::tr("%1G Tutor").arg(gen)))
              .unite(map_container_with_value(PokemonInfo::LevelMoves(num, gen), root ? QObject::tr("Level") : QObject::tr("%1G Level").arg(gen)))
              .unite(map_container_with_value(PokemonInfo::PreEvoMoves(num, gen), root ? QObject::tr("Pre Evo") :QObject:: tr("%1G Pre Evo").arg(gen)))
              .unite(map_container_with_value(PokemonInfo::EggMoves(num, gen), root ? QObject::tr("Breeding") : QObject::tr("%1G Breeding").arg(gen)))
              .unite((gen == 5 ? map_container_with_value(PokemonInfo::dreamWorldMoves(num), QObject::tr("Dream World")) : QHash<int, QString>()))
              .unite(map_container_with_value(PokemonInfo::SpecialMoves(num, gen), root ? QObject::tr("Special", "Learning") : QObject::tr("%1G Special").arg(gen)));
}
Пример #16
0
void FlowContextController::undo(void)
{
    if (!m_undo.size()) return;

    setCurrentColor(-1);
    setMoves(getMoves() - 1);
    m_previous_legal_color = -1;

    FlowContext *top = m_undo.pop();
    top->cloneTo(*m_stable);
    top->cloneTo(*m_beta);
    delete top;
}
Пример #17
0
/*present the options of selecting depth for best_moves func and return the chosen the lise of the best_moves*/
itemMove* best_move_choise(SDL_Surface* screen){
	int dep_chosen, depth;
	itemMove* all_moves = getMoves(state);
	itemMove* best_moves;
	dep_chosen = select_depth(screen);
	if (dep_chosen == -1){
		quit = TRUE;
		destroyMoveList(all_moves);
		return NULL;
	}
	if (dep_chosen == 5){ depth = get_best_depth(state); }
	else{ depth = dep_chosen; }
	best_moves = get_best_moves(all_moves, state, state->board, depth);
	destroyMoveList(all_moves);
	return best_moves;
}
Пример #18
0
bool ChineseCheckersState::isValidMove(const Move &m) const {
  // Ensure from and to make sense
  if (board[m.from] != currentPlayer || board[m.to] != 0)
    return false;

  // NOTE: Checking validity in this way is inefficient

  // Get current available moves
  std::vector<Move> moves;
  getMoves(moves);

  // Find the move among the set of available moves
  bool found = std::find(moves.begin(), moves.end(), m) != moves.end();

  return found;
}
int ComPlayer::doMove(Board board)
{
	std::vector<int> moves = getMoves(board);

	int bestScore = -1;
	int bestMove = moves[0];
	for each(int move in moves)
	{
		Board tempBoard = board;
		int score = tempBoard.placeLine(move);
		if (score > bestScore)
		{
			bestScore = score;
			bestMove = move;
		}
	}
Пример #20
0
MoveList<MoveEntry>& MoveGenerator::getLegalMoves(Position& position, int depth, bool isCheck) {
    MoveList<MoveEntry>& legalMoves = getMoves(position, depth, isCheck);

    int size = legalMoves.size;
    legalMoves.size = 0;
    for (int i = 0; i < size; ++i) {
        int move = legalMoves.entries[i]->move;

        position.makeMove(move);
        if (!position.isCheck(Color::opposite(position.activeColor))) {
            legalMoves.entries[legalMoves.size++]->move = move;
        }
        position.undoMove(move);
    }

    return legalMoves;
}
Пример #21
0
treeNode * makeTree(node * list, int layer){
  char boardHolder[BOARDROWS][BOARDCOLS];
  node* ptr;
  if(layer==2) return NULL; //We should put the evaluation function here
  layer++;
  
  treeNode * temp = malloc(sizeof(treeNode));
  int listLength = getListSize(list);
  temp->numChildren = listLength;
  temp->children = malloc(sizeof(treeNode) * listLength);
  temp->nodePtr = malloc(sizeof(node));
  for(int i = 0; i < listLength; i++){
    applyMove(list,boardHolder);
    temp->children[i] = makeTree(getMoves(boardHolder, computerColour, playerColour), layer);
    setNode(temp->nodePtr, ptr->origin.x, ptr->origin.y, ptr->jumpDest.x, ptr->jumpDest.y, ptr->dir, ptr->jumps);
    printf("made %d child\n", i+1);
    ptr = list->next;
    free(list);
    list = ptr;
  }
  return temp;
}
Пример #22
0
/*function the present the page- GAME PLAY- and handle the events releated to him*/
int GamePlay(SDL_Surface* screen, char* fileName){
	int move_next_page;
	int COMPUTER_TURN, USER_TURN;
	int cnt = 0;
	int boardChanged = 1;
	int best_moves_chosen = 0;
	itemMove* best_moves;
	SDL_Surface* GameScreen = NULL;
	SDL_Event event;
	location loc1;
	location loc2;
	pixle pix;
	itemMove* moves;
	itemMove* all_moves;
	int x;
	int y;
	int save=FALSE;
	int skip;
	int cnt_op = 0;
	int cnt_op_moves = 0, cnt_op_best = 0;
	int show_moves = FALSE;
	int show_best = FALSE;
	int all_moves_freed=TRUE;
	char promBestMove = 'a';
	move_next_page = FALSE;
	GameScreen = SDL_LoadBMP(fileName);
	if (userColor == nextPlayer){ // deciding who will start the game
		USER_TURN = 1;
		COMPUTER_TURN = 0;
	}
	else{
		USER_TURN = 0;
		COMPUTER_TURN = 1;
	}

	state->turn = nextPlayer;
	//update screen
	apply_surface(0, 0, GameScreen, screen);
	fromStateToGui(screen, state->board, GAME);
	SDL_Flip(screen);

	while (quit == FALSE && move_next_page == FALSE){
		skip = 0;
		cnt_op = 0;
		if (SDL_PollEvent(&event)){
			if (game_mode == 1 || USER_TURN|| game_over==TRUE){ // communication with the user: (game_mode 1 or user turn in game mode2 ) 
				if (event.type == SDL_MOUSEBUTTONUP ){
					if (game_over==FALSE){ cnt_op = 1; }
					best_moves_chosen = 0;
					if (cnt_op_moves == 1){ /// for gui use.. dont ask me why.. its working
						destroyMoveList(moves);
						show_moves = FALSE;
						cnt_op_moves = 0;
					}
					if (cnt_op_best == 1){// for gui use.. dont ask me why.. its working
						destroyMoveList(best_moves);
						show_best = FALSE;
						cnt_op_best = 0;
					}
					//Get the mouse offsets
					x = event.button.x;
					y = event.button.y;
					pix.x = x;
					pix.y = y;
					//best move button:
					//send to best_move func and disaply the tiles for the best move coordinate
					if (game_over == FALSE && (x > 624) && (x < 624 + 155) && (y > 76) && (y < 76 + 70)){
						best_moves = best_move_choise(screen); best_moves_chosen = 1; show_best = TRUE; cnt_op_best++;
						if (best_moves == NULL && quit == TRUE){ break; }
						apply_surface(0, 0, GameScreen, screen);
						fromStateToGui(screen, state->board, GAME);

						if (best_moves->move.Promote != EMPTY)
							promBestMove = best_moves->move.Promote;
					}
					//save button
					else if ((x > 624) && (x < 624 + 155) && (y > 76 + 121) && (y < 76 + 121 + 70)){ 
						load_or_save_generic(screen, 0); 
						apply_surface(0, 0, GameScreen, screen);
						fromStateToGui(screen, state->board, GAME);
						save = TRUE; }
					//mainMenu:
					else if ((x > 624) && (x < 624 + 155) && (y > 76 + 121 * 2) && (y < 76 + 121 * 2 + 70)){ MainMenu(screen); }
					//quit:
					else if ((x > 624) && (x < 624 + 155) && (y > 76 + 121 * 3) && (y < 76 + 121 * 3 + 70)){ quit = TRUE; break; }
					// the move:
					else if (game_over == FALSE && (x < 0 + 8 * 75) && (y < 0 + 8 * 75)){
						move* user_move = (move*)malloc(sizeof(move));
						cnt++;
						if (cnt == 1){ loc1 = pixel_to_loc(pix); //one click on the game area check if the player clicked on his own solider. if yes- get the coordinate and the possible moves for that solider
						if (state->board[loc1.column][loc1.row].color != state->turn) { cnt = 0; free(user_move); continue; }
						moves = getMovesByCor(state, loc1); show_moves = TRUE; cnt_op_moves++;
						}
						if (cnt == 2){//second clicked- if cnt ==1 so we are trying to make a move- check if legal and do what u got to do..
							loc2 = pixel_to_loc(pix); user_move->locStart = loc1; user_move->locEnd = loc2; user_move->Promote = EMPTY;
							// if isLastRow- and the type is pawn- we need to prompt! so go to the prompt page..
							if (isLastRow(user_move, state) && (state->board[user_move->locStart.column][user_move->locStart.row].type)==PAWN){
								user_move->Promote = promoteScreen(screen, state->turn,promBestMove);
								promBestMove = 'a';
							}
							COMPUTER_TURN= user_turn_func(user_move,screen); // make the turn using a super special func that only geniuses can use
							USER_TURN = abs(1-COMPUTER_TURN); // in case user_turn didnt worked- computer_turn will be 0 and we keep playing with the user
							skip = 1; // skip the computer turn, only for gui updating stuff (blaa blaa..)
							cnt = 0;
							boardChanged = COMPUTER_TURN; // computer_turn =1 iff the user make his move -> the board changed
							apply_surface(0, 0, GameScreen, screen);
							fromStateToGui(screen, state->board, GAME);
						}
						free(user_move); // i really really miss garbage collector!
					}
					SDL_Flip(screen);
					if (cnt == 1 && show_moves){ add_tiles_to_possible_locations(screen, moves); }//show tiles for possible moves if needed
					if (best_moves_chosen == 1 && show_best){ add_tiles_to_best_move(screen, best_moves); }//show tiles for the best move if needed
					if ((game_over == FALSE && boardChanged == 1) || (cnt == 1 && show_moves) || (best_moves_chosen == 1 && show_best) || cnt_op == 1){
						SDL_Flip(screen); //update screen after tiles
					}
				}// end of handle key pressed
			}// end of user communication
			if (event.type == SDL_QUIT){ quit = TRUE; break; }
		}// end of handle event loop

		if (game_over==FALSE && COMPUTER_TURN && game_mode == 2 && skip == 0){
			all_moves = getMoves(state);
			all_moves_freed = FALSE;
			USER_TURN = computer_turn_func(screen,all_moves);//function for the computer play- less special then the user_turn_func but eh..
			COMPUTER_TURN = 0;
			boardChanged = 1;
			apply_surface(0, 0, GameScreen, screen);
			fromStateToGui(screen, state->board, GAME);
			SDL_Flip(screen);
			
		}
		if ((save&&game_over == TRUE)){
			SDL_Flip(screen); // if the game is over- and we get out from the save option we still want to display the game screen
		}

		if (all_moves_freed == FALSE){ destroyMoveList(all_moves); all_moves_freed = TRUE; }
		if (boardChanged == 1){
			all_moves = getMoves(state);
			all_moves_freed = FALSE;
			if (check_if_continue_playing_gui(screen, state, all_moves) == FALSE){ //check if the game is over- TIE/MATE
				game_over = TRUE; SDL_Flip(screen); }
			boardChanged = 0;
		}
		if (all_moves_freed == FALSE){ destroyMoveList(all_moves); all_moves_freed = TRUE; }
		
	}// end while
	SDL_FreeSurface(GameScreen);
	return quit;
}
Пример #23
0
int scoreBest(char* board,int player){
	linkedList *moves = getMoves(board, BLACK);
	if (moves->first == NULL){ // no possible moves for other player
		if (isCheck(board, BLACK)){ // check
			freeList(moves);
			return 2*kingScore; // the player wins
		}
		else // not in check
		{
			freeList(moves);
			return -0; // tie
		}
	}
	freeList(moves);
	moves = getMoves(board, WHITE);
	if (moves->first == NULL){ // no possible moves
		if (isCheck(board, WHITE)){ // check
			freeList(moves);
			return -2 * kingScore; // the player lost
		}
		else // not in check
		{
			freeList(moves);
			return -0; // tie
		}
	}
	freeList(moves);
	int score = 0;
	pos p;
	for (char x = 'a'; x <= 'h'; x++)
	{
		p.x = x;
		for (int y = 1; y <= 8; y++)
		{
			p.y = y;
			int ind = posToInd(p);
			char type = tolower(board[ind]);
			if (type == EMPTY)
			{
				continue;
			}
			int color = colorOfLoc(board, ind);
			int ind64 = color == WHITE ? posToBoard64(p) : 64 - posToBoard64(p);
			if (type == 'm')
			{
				score += pawnScore * (2 * color - 1);
				score += pawnTable[ind64];
			}
			else if (type == 'n'){
				score += knightScore * (2 * color - 1);
				score += knightTable[ind64];
			}
			else if (type == 'b'){
				score += bishopScore * (2 * color - 1);
				score += bishoptTable[ind64];
			}
			else if (type == 'r'){
				score += rookScore * (2 * color - 1);
				score += rookTable[ind64];
			}
			else if (type == 'q'){
				score += queenScore * (2 * color - 1);
				score += queenTable[ind64];
			}
		}
	}
	return score * (2 * player - 1);
}
Пример #24
0
int getAllMoves(const position * const pos, const int player, const int storeIndex)
{
    int numMoves = 0;

    if(WHITE == player) {
        numMoves += getMoves(pos, player, WHITE_KING, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_PAWN, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_KNIGHT, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_BISHOP, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_ROOK, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_QUEEN, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_KING, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_PAWN, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_KNIGHT, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_BISHOP, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_ROOK, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, WHITE_QUEEN, NORMAL, &_moveStore[storeIndex][numMoves]);
    }
    else {
        numMoves += getMoves(pos, player, BLACK_KING, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_PAWN, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_KNIGHT, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_BISHOP, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_ROOK, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_QUEEN, CAPTURE, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_KING, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_PAWN, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_KNIGHT, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_BISHOP, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_ROOK, NORMAL, &_moveStore[storeIndex][numMoves]);
        numMoves += getMoves(pos, player, BLACK_QUEEN, NORMAL, &_moveStore[storeIndex][numMoves]);
    }

    if(0 == numMoves) { /* no moves */
        if(inCheck(pos, player, pos->kingSquare[player])) {
            return LOST;
        }
        else {
            return STALEMATE;
        }
    }

    counterMove += numMoves;

    return numMoves;
}
Пример #25
0
/*Build Minimax Tree for Best Difficulty using BFS Algorithm*/
MinimaxNode *getMinimaxTreeBestDepth(Game *game, Color uCol) {
    MinimaxNode *root = (MinimaxNode*)malloc(sizeof(MinimaxNode));
    if (root == NULL)exitOnError("malloc");
    root->game = (Game*)malloc(sizeof(Game));
    if (root->game == NULL) exitOnError("malloc");
    root->val = 0;
    MinimaxNode *curr;
    ListNode *moves;
    int i;
    int leavesLocal = 1;
    Queue *q = setQueue(); /*Create empty Queue for BFS Traversing*/
    int size = 0;
    root->depth = 0;
    root->move = NULL;
    copyGame(game, root->game);
    root->sons = NULL;
    root->sonsK = 0;
    enqueue(q, root);
    /*While Queue is not empty and there are less than MAX_BOARDS_TO_EVAL Leaves in Tree*/
    while (q->size&&leavesLocal + size <= MAX_BOARDS_TO_EVAL) {
        curr = dequeue(q); /*Pop from Queue*/
        if (curr->depth % 2 == 0)moves = getMoves(curr->game, uCol); /*Get possible Moves at current Board state*/
        else moves = getMoves(curr->game, oppositeCol(uCol));
        size = listSize(moves);
        if (!size) {
            free(moves);
            continue;
        }
        curr->sons = (MinimaxNode**)malloc(sizeof(MinimaxNode)*size);
        if (curr->sons == NULL) exitOnError("malloc");
        curr->sonsK = size;
        ListNode *temp = moves;
        for (i = 0; i < size; i++) { /*Add Nodes for each possible Move*/
            curr->sons[i] = (MinimaxNode*)malloc(sizeof(MinimaxNode));
            if (curr->sons[i] == NULL) exitOnError("malloc");
            curr->sons[i]->game = (Game*)malloc(sizeof(Game));
            if (curr->sons[i]->game == NULL) exitOnError("malloc");
            curr->sons[i]->val = 0;
            copyGame(curr->game, curr->sons[i]->game);
            Move* tMove = copyMove(temp->move);
            updateBoard(curr->sons[i]->game, tMove);
            curr->sons[i]->depth = curr->depth + 1;
            if (curr->sons[i]->depth == 1) {
                curr->sons[i]->move = tMove;
            }
            else {
                freeMove(tMove);
                curr->sons[i]->move = NULL;
            }
            curr->sons[i]->sons = NULL;
            curr->sons[i]->sonsK = 0;
            enqueue(q, curr->sons[i]); /*Push to Queue*/
            temp = temp->next;
        }
        /*Update amount of Leaves in Tree*/
        freeList(moves);
        leavesLocal += size;
        if (size) leavesLocal--;
    }
    freeQueue(q);
    return root;
}
Пример #26
0
bool Piece::isValidMove(int _row,int _col){
	list<square> moves;
	getMoves(moves);
	return isMove(moves,_row,_col);
}
Пример #27
0
std::pair<int, Move> GameState::alphaBeta(int depth, int alpha, int beta, Player* player, Player* maximizingPlayer)
{
    int bestValue;
    Move bestMove;

    std::vector<Move> moves = getMoves(player);

    if (depth == 0 || moves.size() == 0)
    {
        return std::make_pair(getScore(maximizingPlayer), Move());
    }

    if (player == maximizingPlayer)
    {
        bestValue = -581357;

        for (Move move : moves)
        {
            board->doMove(move);

            std::pair <int, Move> pair = alphaBeta(depth - 1, alpha, beta, player->getOpponent(), maximizingPlayer);

            if (pair.first > bestValue) {
                bestValue = pair.first;
                bestMove = move;

                if (bestValue > alpha) {
                    alpha = bestValue;
                }
            }

            board->undoMove(move);

            if (beta <= alpha) {
                break;
            }
        }
        return std::make_pair(bestValue, bestMove);
    }

    else
    {
        bestValue = 581357;

        for (Move move : moves)
        {
            board->doMove(move);

            std::pair <int, Move> pair = alphaBeta(depth - 1, alpha, beta, player->getOpponent(), maximizingPlayer);

            if (pair.first < bestValue) {
                bestValue = pair.first;
                bestMove = move;

                if (bestValue < beta) {
                    beta = bestValue;
                }
            }

            board->undoMove(move);

            if (beta <= alpha) {
                break;
            }
        }
        return std::make_pair(bestValue, bestMove);
    }
}
Пример #28
0
int SearchMv::alphaBeta(int depth,int alpha, int beta, Board& board, int mate, vector<int>& pLine, bool allowNull,s_searchParamas* params)
{
	if ( (params->nodes & 2047) == 0) // go read input every 2048 node count.
		statusCheck(params);
	params->nodes++;
	 int val;
	 bool foundPV = false;
	 vector<int> line;

	  if (depth <= 0)
      //return evaluate(board);
     return quiescentSearch(alpha, beta, board,params);


      // null move forward prunning, will test more later
      /*
      if ( (depth >= 3) && (allowNull) && (board.isInCheck(board.turn) == false) && (isZugzwangChance(board) == false) )
      {
           myMaker.makeNullMove(board);
           val = -alphaBeta(depth - 1 - R, -beta, -beta + 1, board, mate - 1, line, false,params);
           myMaker.takeNullMove(board);
           if (val >= beta)
           return beta;
      }
      */
     
      vector<int> myMoves = getMoves(board);
      int numMoves = myMoves.size();
      if (board.isInCheck(board.turn))
      {
      	if (numMoves == 0)
      		return -mate;
      	else depth++; // in check extention
      }else
      {
         if (numMoves == 0) // draw
         	return 0; 
      }
       
       for (vector<int>::iterator it = myMoves.begin(), end = myMoves.end(); it != end; ++it)
     {
     	myMaker.makeMove(*it, board);
      if (isRepetion(board) || (board.hm_clock >= 50) || isInsuffcientMaterial(board))
      {
        myMaker.takeBack(board);
        return 0;
      }
     
        if (foundPV)
        {
        	val = -alphaBeta(depth - 1, -alpha - 1, -alpha, board ,mate - 1, line, true,params);
        	if ((val > alpha) && (val < beta)) // Check for failure.
        	 val = -alphaBeta(depth - 1,-beta,-alpha, board, mate - 1, line, true,params);
         }else
        val = -alphaBeta(depth - 1,-beta,-alpha, board, mate - 1, line, true,params);
        
     	myMaker.takeBack(board);

      if(params->stopped) 
      return 0;

     	if (val >= beta)
            return beta;
        if (val > alpha)
        {
            alpha = val;
            foundPV = true;
            pLine = line;
            pLine.insert(pLine.begin(), *it);
        }
      } 
     
       return alpha;
}
Пример #29
0
bool moveInLegalMoves(Move* move, char** board, int player) {
	MoveList* legalMoves = getMoves(board, player);
	bool legal = moveInList(legalMoves, move);
	freeMoves(legalMoves);
	return legal;
}
Пример #30
0
int AI::BFTS()
{
  //bool goal = false;
  Game origBoard = board;
  Wriggle wr;
  int counter = 0;
  bool root = true;
  do
  {
    if(outFlag == true)
    {
      cout<<"loop starting--------------------------\n"<<endl;
    }
    board = origBoard;
    //gets node here
    
    Move mv = tree.getNext();

    if(mv.index == -10 && root == false)
    {//gave a dummy node, empty frontier test
      return -1;
    }
    
    root =false;
    
    if(outFlag == true)
    {
      cout<<"got the next node: "<<mv<<endl;
    }
    
    vector<Move> moveList;
    tree.getMoveList(moveList);
    
    //generates map here
    while(!moveList.empty())
    {
      if (outFlag == true)
      {
        cout<<"mlMv:"<<moveList[moveList.size()-1]<<endl;
      }
      
      board.moveWriggler(moveList[moveList.size()-1]);
      moveList.pop_back();
    }
    
    if(board.isGoal() == true)
    {//goal test
      break;
    }
    
    if (outFlag == true)
    {
      cout<<"moveList is emptied printing board:"<<endl;
      cout<<board<<endl;
      
    }
    
    for(int i = 0; i < numWrigglers; i++)
    {//move generation here
      wr = board.getWriggler(i);
      getMoves(wr, i, HEAD);
      getMoves(wr, i, TAIL);
    }
    counter++;
  }
  while(!board.isGoal());
  //print moves
  vector<Move> moveList;
  tree.getMoveList(moveList);
  int retVal = moveList.size();
  while(!moveList.empty())
  {
    cout<<moveList[moveList.size()-1]<<endl; 
    moveList.pop_back();
  }
  cout<<endl;
  board.print();
  // num moves. ret val
  
  
  
  //*/
  return retVal;
}