Hey, I've written a tic tac toe program.
Computer makes some random moves, but i want it to be smarter and make some intellegent moves.
any idea how to approach it?

here's the code i've written.
Although it's not that high-level, it's working fine.

#include<stdio.h>


#define BOARDSIZE 9
#define USER 'O'
#define COMPUTER 'X'


// List of function prototypes 
void playOneGame();
void clearGameBoard(char board[]);
bool winner(char board[]);
bool RowIsWinner(char s1, char s2, char s3);
char TTTopponent(char player);
void displayHorizontalLine();
void displayOneLine(char a,char b,char c);
void displayGameBoard(const char board[]);
void displayGameBoard(const char board[]);
int findEmptySpot(char[]);
void computerPlay(char board[]);
int userChoice(char board[]);
void userPlay(char board[]);
bool ValueInRange(int value,char board[]);
bool userWantsToPlay();
bool Filled(char board[]);
void announceResult(int, char);
bool isDraw(char board[]);
int gameOver(char[]);
void displayverticalLine();
void displayInstructions();

//The main function of the Tic-Tac-Toe,Calls the "palyOneGame()" function 
//and ask the user if he wants to play again.
// pre: None.
// post: Return zero .
int main()
{
    displayInstructions();  
    do
    {
     playOneGame();     
     }while(userWantsToPlay());
    printf("Have a good Time\n");
    getchar();
    getchar();
    return 0;   
}

//Play one game, display and clear the game board,announce the winner and let player 
//and computer play.
//Pre: None.
//Post: None.
void playOneGame()
{
    char gameboard[BOARDSIZE]={'1','2','3','4','5','6','7','8','9'};
    displayGameBoard(gameboard);
    clearGameBoard(gameboard); 
    char player=USER;
    int result;    
    do
    {
         if(player==USER){
             userPlay(gameboard);
    } 
         else
         {
              printf("\t\t\t U R too young to bit me!!!\n");
              computerPlay(gameboard);              
         }
         displayGameBoard(gameboard);     
         player=TTTopponent(player);
         result = gameOver(gameboard);                 
    }while(result ==0);    
    announceResult(result, player);   
}    
    
//Clears all the squares of the game board.
//Pre: Game board passed to the function.
//Post: None.
void clearGameBoard(char board[])
{
     for(int i=0;i<9;i++)
     {
         board[i]=' ';
     }   
} 
    
//Determines if any of the horizontal, vertical and diagonal line is a winning line.
//Pre: Game board passed to the bool type function.
//Post: The function returns true if there is a winning row and false otherwise.
bool winner(char board[])
{
    return (RowIsWinner(board[0], board[1],board[2])||RowIsWinner(board[3], board[4], board[5])
         || RowIsWinner(board[6], board[7],board[8])||RowIsWinner(board[0], board[3],board[6])
         || RowIsWinner(board[1], board[4],board[7])||RowIsWinner(board[2], board[5],board[8])
         || RowIsWinner(board[0], board[4],board[8])||RowIsWinner(board[2], board[4],board[6]));   
    
} 
  
//The bool type function determines if a row is a winning and there is no empty spot in it.
//Pre: Three char type defined [s1,s2,s3] values passed to the function.
//Post: Returns true if the squares have equal values and not empty and returns false otherwise. 
bool RowIsWinner(char s1, char s2, char s3)
{
   return (s1==s2 && s2 ==s3&& s2!=' ');  
     
}

//The char type function switch the opponent.
//Pre: The predifined symbols passed to the char type function.
//Post: Returns the switched value.
char TTTopponent(char player)
{
     if(player==COMPUTER)
          return USER;
     else
          return COMPUTER;
}

//The void function only display a horizontal row.
//Pre: None.
//Post: None.
void displayHorizontalLine()
{
     printf("\t\t\t\t --- --- ---\n");
}

//The void function only displays the vertical lines.
//Pre: None.
//Post: None.
void displayverticalLine()
{
     printf("\t\t\t\t|   |   |   |\n");
} 
    
//The void function displays character within the vertical lines.
//Pre: Three defined char type value a,b,c passed to the function.
//post: None.
void displayOneLine(char a,char b,char c)
{
     printf("\t\t\t\t| %c | %c | %c | \n",a,b,c);
}

//The void function displays the game board on the screen.
//Pre: Char type array board with constant cells is passed to the function.
//Post:None.
void displayGameBoard(const char board[])
{
     displayHorizontalLine();
     displayverticalLine();
     displayOneLine(board[0],board [1],board [2]);
     displayverticalLine();
     displayHorizontalLine();
     displayverticalLine();
     displayOneLine(board[3],board [4],board [5]);
     displayverticalLine();
     displayHorizontalLine();
     displayverticalLine();
     displayOneLine(board[6],board [7],board [8]);
     displayverticalLine();
     displayHorizontalLine();
     printf("\n\n\n");
}

//The void function displays the instruction of the game.
//Pre: None.
//Post: None.
void displayInstructions()
{
     printf("\t\t\tThe game starts by the user, Using an 'O'\n");
     printf("\t\t\t     and computer, using an 'X'.\n");
     printf("\t\t\tThe first one who completes a row is winner.\n");
}

//The int type function find the empty spots in the game board.
//Pre: The char type board array is passed to the function.
//Post: Returns integer.
int findEmptySpot(char board[])
{
    for(int i=0;i<=9;i++)
    {
       if(board[i]==' ')
        return i;  
    }         
}

//The void type function that make moves as if computer is playing.
//Pre: Char type board[] is passed to the function.
//Post: None.                         
void computerPlay(char board[])
{
     int empty = findEmptySpot(board);
     
     board[empty]='X'; 
}
 
//The char type function that lets the user choose a valid number that is in range.
//Pre: Char type array is passed to the function.
//Post: Returns 
int userChoice(char board[])
{
     int i;
     printf("\t\t\t   It`s your turn buddy!!!\n");
     printf("\t\t\t   choose an empty square\n"); 
     scanf("%d", &i);
     while(!ValueInRange(i-1,board))
     {
       printf("Your Choice is not valid.Please enter another one\n");
       getchar();
            
       scanf("%d", &i);
     }
     return (i-1);
} 

//The void type function that lets the user play and make a choice and also calls
//the "userChoice()" function within.
//Pre: The char type board array is passed to the function.
//Post: None.
void userPlay(char board[])
{
      int userSpot;
      userSpot= userChoice(board);
      board[userSpot] = USER;
} 

//A bool type function checks the value to be in range.
//Pre: A defined integer value and a char type board is passed to the function.
//Post: Returns true if the value is in range and not an space. 
bool ValueInRange(int value,char board[])
{
     return(board[value]==' '&& value<10);                  
} 
    
//A bool type function that ask if the user wants to play.
//Pre: None.
//Post: True if yes and false otherwise.
bool userWantsToPlay()
{
     char yesNo;
     printf("\n Do you want to continue? (Y/N) ");
     getchar();
     scanf("%c",&yesNo);
     return (yesNo =='Y' || yesNo =='y');
}

//A bool type function that check all the board cells to find out if empty or not.
//Pre: A char type value board is passed to the function.
//Post: Returns true if the board is full and false otherwise.
bool Filled(char board[])
{
    for(int i=0;i<9;i++)
    {
        if(board[i]==' ')
        return false;
    }
    return true;
} 
     
//A void type function that announce the winner of the game.
//Pre: The int type "result" and char type "player" is passed to the function.
//Post: None.  
void announceResult(int result, char player)
{
     if (result==1)
     {
     player=TTTopponent(player);  
     printf("\t\t\tThe winner is:%c", player);
     }     
     else
     printf("\t\t\tThe Game Is Draw(Tie)");   
}
        
//A bool type function that determines if the game is draw.
//Pre:The char type "board[]" is passed to the function.
//Post:Ture is the board is full.
bool isDraw(char board[])
{
       return(Filled(board));
} 
       
//An int type function that determine if the game is over or not by selection.
//Pre: The char type "board[]" is passed to the function.
//Post: Returns integer 1 if there is a winner and 2 if the game is draw and 0 
//if the game is no over yet. 
int gameOver(char board[])
{
 if (winner(board))
    return 1;
 if (isDraw(board))
    return 2;
 else
     return 0;
}

Recommended Answers

All 2 Replies

The first step would be to detect if the opponent is one move away from a winning move, then block that move.

X|0|.
X|.|0
O|.|.

In other words, detect that there are two 'X' in a line, and playing the red '0' is a damn fine idea at this point.

One possible way to implement this is using a magic square:

4|3|8
------
9|5|1
------
2|7|6

It was effective when I wrote TTT the first time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.