April 9th, 2009, 03:06 PM
Computer Moves for Tic Tac Toe
Hi, I am making a TicTacToe game. Right now I am trying to design the computer's moves. I want the computer player to check for possible wins, then check for possible blocks and otherwise just make a strategic move.
I have the computer checking for possible wins using the function below. I am wondering what people think of the design I am using. I wanted to create my own algorithm instead of just using google to find one that is already made. There are alot of comments on the function so it should be clear what I am doing.
This only checks the 3 vertical "winning lines". I will use the same idea for the 3 horizontal and 2 diagonal. I also think i can use almost the same exact approach for finding a "blocking move" to block the player from winning.
The human players moves are denoted by X.
The computers moves are denoted by O.
* Pre: 2D char array is filled with previous moves
* Post: 2D char array possibly modified with a computer move
* Returns true if a move was made.
* Deff: This function acts as the computer player. It will
* check for possible winning moves and make one if possible.
bool winningMove(char board[COLS])
bool moveMade= false;
int emptyRow= 0;
int emptyCol= 0;
/* These values are used to determine player positions on the board */
const int xValue= 5; /* Player moves are valued at 5 */
const int oValue= 4; /* Computer moves are valued at 4 */
/* If a line adds up to 8 then the computer can make a winning move*/
const int winningLine = 8;
/* Checking Vertical Lines */
for(int i=0;i<COLS;i++,lineTotal= 0)
if(board[j][i] == 'O')
lineTotal += oValue;
else if(board[j][i] == 'X')
lineTotal += xValue;
else if(board[j][i] == ' ') //<-- Catches Empty Cell (possible win)*/
/* If the current line provides a winning move, take it*/
if(lineTotal == winningLine)
board[emptyRow][emptyCol] = 'O';
if( !moveMade )
/* CHECK HORIZONTAL LINES */
if( !moveMade )
/* CHECK DIAGONAL LINES */
This function does work for every test case I tried on it. Does this look like a good way to simulate the computer player?
Last edited by g.eckert; April 9th, 2009 at 03:10 PM.
Tags for this Thread
Click Here to Expand Forum to Full Width