bool Board::GetWin(int &winner) const{// All possible wins static int winLines[8][3] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6} }; bool won(false); // loops through the winLines list and checks it across the board for(int i(0); i < 8; ++i) { if(mBoard[winLines[0]] > 0 && mBoard[winLines[0]] == mBoard[winLines[1]] && mBoard[winLines[1]] == mBoard[winLines[2]]) { winner = mBoard[winLines[0]]; won = true; break; } } return won;}
So my code for my ai i dont think is too bad but it could probably be improved by quite a bit
int Move(std::array board, int player){/* set score to -2 which is 1 less than a loss so any move that is * found the score of the worst outcome -1(a loss) so even if the * only move is to lose it is the best move*/ int move(-1), score(-2); for(std::size_t where(0); where < board.size(); ++where) { if(board[where] == 0) { board[where] = player;/* The ai returns a score related to the player in that iteraton so * we need to get the inverse of that score to apply to the player * we are looking for a move for */ int tempScore(-AI::MiniMax(board, (player == 1 ? 2 : 1))); if(tempScore > score) { score = tempScore; move = where; } board[where] = 0; // change the square back to unused } } if(move == -1) { return 0; // Shouldn't ever be reached } return move;}
the MiniMax function is pretty much the same as the Move function except it returns the score rather than the move and checks if it is a winning position
int MiniMax(std::array board, int player){int score(-2);{ int win(AI::Win(board)); if(win > 0) score = (win == player ? 1 : -1);}
That about wraps it up the game and source can be found at github