예제 #1
0
파일: sudoku.c 프로젝트: texruska/Sudoku
int solutionCount(sudokuGrid *game,int solutionsCuttoff) {
	//this function destroys the board in the process of counting the number of solutions//
	int position, trialValue, count;
	
	//if the board is full up, we are done
	if (isBoardFull(game)) {
		count = 1;
	} else {
		count = 0;
		
		position = getEmptyCell(game);
		trialValue = MIN_VALUE;
		while ((count < solutionsCuttoff) && (trialValue <= MAX_VALUE)) {
			if (isLegalMove(game,position,trialValue)) {
				commitMove(game,position,trialValue);
				if (solutionCount(game,1)) {
					//game with trial value in this position is solvable
					count++;
				}
				
				//reset to a blank value to try another solution
				commitMove(game,position,BLANK_VALUE);
			}
			
			trialValue++;
		}
	}
	
	return count;
}
예제 #2
0
void makeMove (Game g, Action a, int row, int col) {
    int player;
    if (g->checkersBoard[row][col] == BLACK_CHECKER || g->checkersBoard[row][col] == BLACK_CROWNED_CHECKER) {
        player = 2;
    } else if (g->checkersBoard[row][col] == WHITE_CHECKER || g->checkersBoard[row][col] == WHITE_CROWNED_CHECKER) {
        player = 1;
    }
    if (isLegalMove(g, a, row, col, player) == 1) {
        if (a->actionCode == MOVE_BACKWARD_LEFT) {
            g->checkersBoard[row - 2][col - 2] = g->checkersBoard[row][col];
            g->checkersBoard[row][col] = NO_PIECE;
            moveChecks (g, a, row, col, player);
        } else if (a->actionCode == MOVE_BACKWARD_RIGHT) {
            g->checkersBoard[row - 2][col + 2] = g->checkersBoard[row][col];
            g->checkersBoard[row][col] = NO_PIECE;
            moveChecks (g, a, row, col, player);
        } else if (a->actionCode == MOVE_FORWARD_LEFT) {
            g->checkersBoard[row + 2][col - 2] = g->checkersBoard[row][col];
            g->checkersBoard[row][col] = NO_PIECE;
            moveChecks (g, a, row, col, player);
        } else if (a->actionCode == MOVE_FORWARD_RIGHT) {
            g->checkersBoard[row + 2][col + 2] = g->checkersBoard[row][col];
            g->checkersBoard[row][col] = NO_PIECE;
            moveChecks (g, a, row, col, player);
        }
    }
}
예제 #3
0
파일: sudoku.c 프로젝트: texruska/Sudoku
int hasSolution(sudokuGrid *game) {
	int position, trialValue, solved;
	
	//if the board is full, we are done
	if (isBoardFull(game)) {
		solved = TRUE;
	} else {
		solved = FALSE;
		position = getEmptyCell(game);
		trialValue = MIN_VALUE;
		
		while (!solved && (trialValue <= MAX_VALUE)) {
			if (isLegalMove(game,position,trialValue)) {
				commitMove(game,position,trialValue);
				
				if (hasSolution(game)) {
					//game with trial value in this position is solvable
					solved = TRUE;
				} else {
					//reset to a blank value to try another solution
					commitMove(game,position,BLANK_VALUE);
				}
			}
			
			trialValue++;
		}
	}
	
	return solved;
}
예제 #4
0
void TicTacToe::play() {
  //player array is 0 indexed, so player 1 is at index 0. 
  int current_player = 0;
  //resets the board. 
  reset();
  printBoard();
  while(!isDone()) {
    std::cout << "Player " << current_player + 1 << "'s turn. \n";
    //getCoordinateFromUser is a BoardGame function
    Coordinate nextMove(getCoordinateFromUser());
    while(!isLegalMove(nextMove, player_list_[current_player].getSymbol())) {
      std::cout << "Invalid move. Please try again.\n";
      nextMove = getCoordinateFromUser();
    }
    doMove(nextMove, player_list_[current_player].getSymbol());
    printBoard();
    
    if(current_player == 0)
      current_player = 1;
    else
      current_player = 0;
  }
  results();
  
  
}
int num_valid_moves(char self, char opp, char grid[8][8])   {
	int count = 0, i, j;
	for(i=0; i<8; i++)
		for(j=0; j<8; j++)
			if(isLegalMove(self, opp, grid, i, j)) count++;
	return count;
}
예제 #6
0
파일: stats.cpp 프로젝트: epgfm/CERI
/**
 * \brief Get game stats.
 *
 * Walk the game arena and get satistics about the current state. 
 * Those include:
 *  - Number of discs for each player.
 *  - Number of legal moves for each players.
 *  - Number of corners owned by each player.
 *
 */
bool Othello::getGameState(PlayerStats & Player, PlayerStats & Enemy) {
    // Clear the previous stats.
    Player.numberOfDiscs = 0;           Enemy.numberOfDiscs = 0;
    Player.numberOfLegalMoves = 0;      Enemy.numberOfLegalMoves = 0;
    Player.numberOfCorners = 0;         Enemy.numberOfCorners = 0;
    
    // Count the corners.
    int max = arenaSize - 1;
    if (arena[0][0] == Player.id)
        ++Player.numberOfCorners;
    else if (arena[0][0] == Enemy.id)
        ++Enemy.numberOfCorners;

    if (arena[0][max] == Player.id)
        ++Player.numberOfCorners;
    else if (arena[0][max] == Enemy.id)
        ++Enemy.numberOfCorners;

    if (arena[max][0] == Player.id)
        ++Player.numberOfCorners;
    else if (arena[max][0] == Enemy.id)
        ++Enemy.numberOfCorners;

    if (arena[max][max] == Player.id)
        ++Player.numberOfCorners;
    else if (arena[max][max] == Enemy.id)
        ++Enemy.numberOfCorners;

    // Walk the board counting other stuff.
    for (int x = max ; x >= 0 ; --x)
        for (int y = max ; y >= 0 ; --y) {
            // Count the number of discs owned by each player.
            if (arena[y][x] == Player.id)
                ++Player.numberOfDiscs;
            else if (arena[y][x] == Enemy.id)
                ++Enemy.numberOfDiscs;
            else {
                // Count the number of legal moves for each player.
                if (isLegalMove(y, x, Player.id))
                    Player.pushMove(y, x);
                if (isLegalMove(y, x, Enemy.id))
                    Enemy.pushMove(y, x);
            }
        }
    // Return true if game over.
    return Player.numberOfLegalMoves == 0 && Enemy.numberOfLegalMoves == 0;
}
예제 #7
0
파일: parse.c 프로젝트: raimarHD/lcec
extern int parseUciMove(Board_t self, const char *line, int xMoves[maxMoves], int xlen, int *move)
{
        int ix = 0; // index into line
        int rawMove = 0;

        while (isspace(line[ix])) // Skip white space
                ix++;

        int castleLen;
        int nrOh = parseCastling(&line[ix], &castleLen);

        if (nrOh == 2) { // King-side castling
                int rank = (sideToMove(self) == white) ? rank1 : rank8;
                rawMove = move(square(fileE, rank), square(fileG, rank));
                ix += castleLen;
        } else if (nrOh == 3) { // Queen-side castling
                int rank = (sideToMove(self) == white) ? rank1 : rank8;
                rawMove = move(square(fileE, rank), square(fileC, rank));
                ix += castleLen;
        } else { // Regular move
                if ('a' > line[ix+0] || line[ix+0] > 'h'
                 || '1' > line[ix+1] || line[ix+1] > '8'
                 || 'a' > line[ix+2] || line[ix+2] > 'h'
                 || '1' > line[ix+3] || line[ix+3] > '8')
                        return 0;

                int fromFile = charToFile(line[ix++]);
                int fromRank = charToRank(line[ix++]);
                int toFile   = charToFile(line[ix++]);
                int toRank   = charToRank(line[ix++]);

                rawMove = move(square(fromFile, fromRank), square(toFile, toRank));

                if (line[ix] == 'q' || line[ix] == 'r'
                 || line[ix] == 'b' || line[ix] == 'n')
                        rawMove += promotionFlags[(int)line[ix++]];
        }

        if (!isspace(line[ix]) && line[ix] != '\0')
                return 0; // Reject garbage following the move

        // Find matching move from move list and verify its legality
        for (int i=0; i<xlen; i++) {
                int xMove = xMoves[i];
                if ((xMove & ~specialMoveFlag) == rawMove && isLegalMove(self, xMove)) {
                        *move = xMove;
                        return ix;
                }
        }
        return 0;
}
예제 #8
0
파일: moves.c 프로젝트: kervinck/floyd
void normalizeEnPassantStatus(Board_t self)
{
        int square = self->enPassantPawn;
        if (!square)
                return;

        int pawn = (sideToMove(self) == white) ? whitePawn : blackPawn;
        int step = (sideToMove(self) == white) ? stepN : stepS;

        if (file(square) != fileA && self->squares[square+stepW] == pawn) {
                int move = specialMove(square + stepW, square + step);
                if (isLegalMove(self, move))
                        return;
        }
        if (file(square) != fileH && self->squares[square+stepE] == pawn) {
                int move = specialMove(square + stepE, square + step);
                if (isLegalMove(self, move))
                        return;
        }

        self->hash ^= hashEnPassant(square);
        self->enPassantPawn = 0;
}
예제 #9
0
파일: ai.c 프로젝트: JiweiLiu/Scrabble-1
static void handlePossibleMove(int row, int col, wordRef wordToPlay,
                               direction dirToMove) {
    // adjust row, col: they are anchor co-ords

//    D("handling: (%d,%d) word = \"%s\" dir = %d\n",row,col,wordToPlay,dirToMove);
    if(isLegalMove(me, row, col, wordToPlay, dirToMove)) {
        int score = scoreMove(me, row, col, wordToPlay, dirToMove);
        if(score > bestScore) {
            bestRow = row;
            bestCol = col;
            bestScore = score;
            strncpy(bestWord, wordToPlay, BOARD_SIZE);
            bestDir = dirToMove;
        }
    }
}
예제 #10
0
파일: gui.c 프로젝트: ofrinevo/Chess
/*function that perform the user turn- return 1 if move was performed and 0 otherwise*/
int user_turn_func(move* user_move,SDL_Surface* screen){
	itemMove* moves = getMovesByCor(state, user_move->locStart);
	int ErrorHandle = isLegalMove(user_move, moves, state); // check if the Move is legal and return the appropriate message ( 0 if legal) 
	if (ErrorHandle != 0){
		destroyMoveList(moves);
		return 0; 
	}
	makeMoveInPlace(state->board, user_move);// the move is legal - make the move
	
	isCheckWithUpdate(state);
	update_gameState(state);

	COMPUTER_TURN = 1; // in case we playing player vs computer move- now its the computer turn
	USER_TURN = 0;
	destroyMoveList(moves);
	
	return 1;
}
예제 #11
0
파일: sudoku.c 프로젝트: texruska/Sudoku
int generateRandomBoard(sudokuGrid *game) {
	int position, trialValue, solved;
	int trialValues[NUM_VALUES];
	int i,j;
	
	//if the board is full, we are done
	if (isBoardFull(game)) {
		solved = TRUE;
	} else {
		//populate and then shuffle array of trial values
		j = 0;
		for (i = MIN_VALUE; i <= MAX_VALUE; i++) {
			trialValues[j] = i;
			j++;
		}
		shuffleArr(trialValues,NUM_VALUES);
		
		solved = FALSE;
		position = getEmptyCell(game);
		j = 0;
		
		while (!solved && (j < NUM_VALUES)) {
			trialValue = trialValues[j];
			
			if (isLegalMove(game,position,trialValue)) {
				commitMove(game,position,trialValue);
				
				if (generateRandomBoard(game)) {
					//game with trial value in this position is solvable
					solved = TRUE;
				} else {
					//reset to a blank value to try another solution
					commitMove(game,position,BLANK_VALUE);
				}
			}
			
			j++;
		}
	}
	
	return solved;
}
예제 #12
0
void decideMove (HunterView gameState) {
    printf("at start of code\n"); fflush(stdout);
	Graph g = newGraph();
    char *locations[] = {
        "AL", "AM", "AT", "BA", "BI", "BE", "BR", "BO", "BU", "BC", 
        "BD", "CA", "CG", "CD", "CF", "CO", "CN", "DU", "ED", "FL",
        "FR", "GA", "GW", "GE", "GO", "GR", "HA", "JM", "KL", "LE",
        "LI", "LS", "LV", "LO", "MA", "MN", "MR", "MI", "MU", "NA",
        "NP", "NU", "PA", "PL", "PR", "RO", "SA", "SN", "SR", "SJ",
        "SO", "ST", "SW", "SZ", "TO", "VA", "VR", "VE", "VI", "ZA",
        "ZU", "NS", "EC", "IS", "AO", "BB", "MS", "TS", "IO", "AS", 
        "BS", "C?", "S?", "HI", "D1", "D2", "D3", "D4", "D5", "TP"
	};
	int round = getRound(gameState);
	PlayerID id = getCurrentPlayer(gameState);
    LocationID move = getLocation(gameState, id);
    printf("the original loc is %d and health %d\n",move,getHealth(gameState,id));
	char * msg = "";
    printf("initialised all variables\n"); fflush(stdout);
	//set initial locations
	if (round - id == 0) {
	    if (id == PLAYER_LORD_GODALMING) {move = CASTLE_DRACULA; msg = "camping";}
	    else if (id == PLAYER_DR_SEWARD)  move = BELGRADE;
	    else if (id == PLAYER_VAN_HELSING) move = STRASBOURG;
	    else if (id == PLAYER_MINA_HARKER) move = MADRID;
	    registerBestPlay(locations[move], msg);
	    destroyGraph(g);
	    return;
    }
    printf("done initial moves\n"); fflush(stdout);

    //below code will throw errors if LG is killed
    //if (id == PLAYER_LORD_GODALMING) { registerBestPlay("CD","I'm camping MAN!!!"); return; }
	srand (time(NULL));
	int path[NUM_MAP_LOCATIONS];
    int amtLocs = 0;
    LocationID * adj = connectedLocations(&amtLocs, getLocation(gameState, id), id, round, ANY, g);
    LocationID target = UNKNOWN_LOCATION;
    int camper = 0, i, j;
    printf("setting up connected locs etc\n"); fflush(stdout);

    // check for campers
    // if the current player is camping, then the player
    // will stay camping and ai will return
    
    for (i = 0; i < NUM_HUNTERS; i++) {
        if (getLocation(gameState, i) == CASTLE_DRACULA) {
            camper = 1;
            if (id == i) {
	            registerBestPlay("CD", "Staying camping");
                destroyGraph(g);
                free(adj);
                return; 
            }
        }
    } 

    if (!camper) { //if no camper and hunter is shortest dist to castle dracula, move towards castle dracula
        int hunterDist[NUM_HUNTERS] = {UNKNOWN_LOCATION,UNKNOWN_LOCATION,UNKNOWN_LOCATION,UNKNOWN_LOCATION};
        int closestHunter = PLAYER_LORD_GODALMING;
        for (i = PLAYER_LORD_GODALMING; i < NUM_HUNTERS; i++) {
            hunterDist[i] = findShortestPath(getLocation(gameState, i), CASTLE_DRACULA, path, ANY, round);
            if (hunterDist[i] == -1) hunterDist[i] = 1000; //-1 is when there is no path, so don't want him to be shortest
            if ((hunterDist[closestHunter] > hunterDist[i]) || (hunterDist[closestHunter] == UNKNOWN_LOCATION)) closestHunter = i;
        }
        if (closestHunter == id) move = path[1];
    } else {
        LocationID draculaLoc[TRAIL_SIZE];
        getHistory (gameState, PLAYER_DRACULA, draculaLoc); //updates Dracula trail

        for (i = TRAIL_SIZE - 1; i >= 0 ; i--) //locations newer in trail will override older ones
            target = dracTarget(draculaLoc, i); //we have any useful info on his location...

        if (target != UNKNOWN_LOCATION) {
            //Note: Dracula cannot visit any location currently in his trail - hunters should not visit target itself!
            int pathLen = findShortestPath(getLocation(gameState, id), target, path, ANY, round); //success is any number not -1
        	if (getLocation(gameState, id) != target && pathLen != -1) { //path found, and not at rest on target (Drac's trail)
                if (path[1] != target) move = path[1]; 
                //don't move into Dracula's trail (see note above)
                else move = adj[rand() % amtLocs];
                for (i = 0; i < TRAIL_SIZE ; i++) if (path[1] == dracTarget(draculaLoc, i)) move = adj[rand() % amtLocs];
            } else move = adj[rand() % amtLocs];
		} else { //prevents doubling up of hunters when making a random move, since Dracula 404
            int occupied = 0, newLoc = UNKNOWN_LOCATION;
            move = adj[rand() % amtLocs];
            for (j = 0; j < NUM_HUNTERS; j++) if (move == getLocation(gameState, j)) occupied = 1;
            if (occupied) { 
                for (i = 0; i < amtLocs; i++) { 
                    occupied = 0;
                    for (j = 0; j < NUM_HUNTERS; j++) if (adj[i] == getLocation(gameState, j)) occupied = 1;
                    if (!occupied) {newLoc = i; break;}
                }
            }
            if (newLoc != UNKNOWN_LOCATION) move = adj[newLoc]; 
        }
    } 
    if (target != UNKNOWN_LOCATION) printf("*Moving from %s (%d) to target %s (%d) via %s (%d)*\n", locations[getLocation(gameState, id)], getLocation(gameState, id), locations[target], target, locations[move], move);
    else printf("*No target - moving from %s (%d) to %s (%d)*\n", locations[getLocation(gameState, id)], getLocation(gameState, id), locations[move], move);
    
	if (isLegalMove(gameState, id, move, round, g)) registerBestPlay(locations[move], "");
	else {
        printf("ERROR: Location is invalid! Registering default rest move...");
        registerBestPlay(locations[getLocation(gameState, id)], "");
    }
    destroyGraph(g);
    free(adj);
}