Thread: Tic Tac Toe!

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    33

    Tic Tac Toe!

    I need help with my code. I successfully wrote code to play tic tac toe against a friend but i miss read the assignment because i was supposed to make one to play against the computer and I have no clue on where to began altering my code so that I can play against the computer not a friend. The computer just has to pic any random number no strategy. Also at the end I was supposed to have it display all the moves through out the game. My teacher said the best way to do this is to have them save to a file but once again not sure how to save all the moves to a file then display it at the end. Any help would be great thanks.

    Here is my current code.

    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0;  /* i will represent my main loop counter */
        int player = 0; /* represents a play */
        int turn = 0; /* How you select your square when it's your turn */
        int row = 0; /* a row for the squares */
        int column = 0; /* colomuns for the squares */
        int line = 0;  /* used in the check for winner */
        int victor = 0;
        char board[3][3] = {                         /* The board */
                           {'1','2','3'},          
                           {'4','5','6'},        
                           {'7','8','9'}  };
        
        
        for ( i = 0; i<9 && victor==0; i++) /* The loop for the game that ends if all nine moves are made */
        {                                        /* as long as someone is not declared the victor prior */
        printf("\n");
        printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]); /* creates the top row */
        printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]); /* creates the middle row */
        printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]); /* creates the bottom row */
    
        player = i%2 + 1;  /* selects the player */
    
        do
        {
            printf("\nPlayer %d selcet the number of the square where you want to place your %c: ", player,(player==1)?'X':'O');
            scanf("%d", &turn);
            
             row = --turn/3;                                 /* Get row of square */
             column = turn%3;                                /* Get column of square */
            }while(turn<0 || turn>9 || board[row][column]>'9'); /* do while it is less than the max number of turns */ 
            
            board[row][column] = (player == 1) ? 'X' : 'O';        /* put player symbol in square */ 
         
         
          if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) ||   /* Check for a winning diagonals*/ 
             (board[0][2] == board[1][1] && board[0][2] == board[2][0]))
            victor = player;
         
          else
          
          for(line = 0; line <= 2; line ++) /* Check for a winning lines/columns*/ 
          if((board[line][0] == board[line][1] && board[line][0] == board[line][2])||
             (board[0][line] == board[1][line] && board[0][line] == board[2][line]))
            victor = player;
    
     }
        printf("\n");
        printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]); /* creates the top row */
        printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]); /* creates the middle row */
        printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]); /* creates the bottom row */
    
      
       if(victor==0) /* Display result message */
          printf("\nIt's a cat scratch\n");
       else
          printf("\nWinner Winner Chicken Dinner Congrats, Player %d, YOU ARE THE WINNER!\n", victor);
    
    
    
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Assuming player 1 is the human and player 2 is the computer, you don't have much to change:
    1. If it's player 1's turn, ask for user input (you already have this code written, it's your do-while loop).
    2. Create a function that picks a square for the computer (this can be a simple random function for now).
    3. If it's player 2's turn, call a your new function to get a square. Keep calling it until you get an unoccupied square.
    4. If you want the computer to be smart, analyze the board in your square picking function and choose accordingly. I'm sure Google will turn up plenty of tic-tac-toe strategy pages.


    As for saving the game state to a file, all you have to do is every time you print the board to the screen, make an fprintf call that sends the same data to a file you have opened for writing.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    I kinda understand what you are saying but i really have no clue how to write that

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    bump

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Your code indentation is not good. It's not obvious where the do while loop ends, but that is the main play loop. Your printing to a file should be inside that loop. You'll want to open the file before the do while loop, and close it afterward, to avoid file re-opening, and re-closing problems.

    It's "select", not "selcet".

    Simple strategy for TTT is move first to the center square, if available. If not take a corner square that stops one of the opponents future threats (Every move your opponent makes will have future threats along a row, and/or a column and/or a diagonal).

    Always stop his winning move, if it could happen on his next move. That is the primary check, after the first move.

  6. #6
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    Sorry about my lack of skills and knowledge in writing code i really have little to no experience . I Still have no clue what to do to get the code to where I can get a good grade.

  7. #7
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Quote Originally Posted by anduril462 View Post
    Assuming player 1 is the human and player 2 is the computer, you don't have much to change:
    1. If it's player 1's turn, ask for user input (you already have this code written, it's your do-while loop).
    2. Create a function that picks a square for the computer (this can be a simple random function for now).
    3. If it's player 2's turn, call a your new function to get a square. Keep calling it until you get an unoccupied square.
    4. If you want the computer to be smart, analyze the board in your square picking function and choose accordingly. I'm sure Google will turn up plenty of tic-tac-toe strategy pages.


    As for saving the game state to a file, all you have to do is every time you print the board to the screen, make an fprintf call that sends the same data to a file you have opened for writing.
    Quote Originally Posted by Adak View Post
    Your code indentation is not good. It's not obvious where the do while loop ends, but that is the main play loop. Your printing to a file should be inside that loop. You'll want to open the file before the do while loop, and close it afterward, to avoid file re-opening, and re-closing problems.

    It's "select", not "selcet".

    Simple strategy for TTT is move first to the center square, if available. If not take a corner square that stops one of the opponents future threats (Every move your opponent makes will have future threats along a row, and/or a column and/or a diagonal).

    Always stop his winning move, if it could happen on his next move. That is the primary check, after the first move.
    Lots of 'clues' here. If you're waiting for someone to just hand you the code, don't hold your breath. To say you're clueless and yet be tackling an intermediate level C problem... for a grade no-less, is kind of bewildering.

    If you're lost on how to handle the algorithm, stop thinking in code for a bit, and figure out how you would behave like a computer to select a square to draw in. Ask yourself, how do I select a square to look at and then how do I determine if I will write in it. Do I just start at the first square or do I pick one at random? And so on. Start simple, figure out the step-by-step algorithm to the solution, then write the code. If you want a better algorithm, go back and figure out a better step-by-step strategy.

    If you have a more specific question, it would go a long way to someone here being able to help you.

  8. #8
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    Im not really looking for any one to write my code but that would be great haha. But what i am looking for is like what commands would i use for when it is the computers turn?

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    No commands are needed. After the (weak, small-minded, conflicted) human has made his/her move, then the computer will know (of course), that it should move, and will begin calculating same. (and continue their pursuit of perfection. They are the Borg. You will be assimilated. Resistance is futile.

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This is the kind of a framework that I would start with for a TTT program. Right now, it won't compile, let alone run or play a game - it won't even draw a TTT board yet, but those are details. First thing I want to do is lay out the overall flow of the program:

    main>> menu>> playGame>> drawBoard>> getMove>> isLegal>> isOver, etc.

    All the functions aren't in here, yet, but it's the way I like to start a program that isn't trivial - put off the details and get the overall flow of the functions in place.

    Code:
    #include <stdio.h>
    
    
    /* normally a bad idea, but I make an exception here for a global board */
    int board[3][3];
    
    int main(void) {
       int choice=0;
    
       
    
    
    
    
       return 0;
    }
    int menu(void) {
       int play=1;
       
       do {
    
        //print up a little banner of what the program and game is
        //then a menu with:
          play a game
          or quit
    
    
    
    
       }while(play);
    
    
    
       return 0;
    }
    /* handles everything for 1 game, then return to the menu function */
    void playTTT(void) {
       do you want to move first with the X's or move second with the O's?
       get choice
    
    
    
    
    }
       
       
       /* get the next move */
    void getMove(void) {
       int move;
    
    
       
    }
    void drawBoard(void) {
    
    
    
    }
    /* is the move being offered, legal? */
    int isLegal(int move) {
       
    
    
      return move; //a return of 0 indicates an illegal move 
    }
    Using several functions makes debugging and making any changes I find I want later on, much easier. It helps to have all the <input, processing, output, etc.> kind of code, all in their own smaller function.

    A good TTT program can get pretty long to have in just one function, although yours strikes me as short, atm.
    Last edited by Adak; 11-17-2011 at 04:41 AM.

  11. #11
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    I just don't know like what lines to write for the computer to take his turn? I would prefer it to be a random function but i don't know how?

  12. #12
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Simply generate a random number from 0 to 8 (rand() % 9). That will give you one of 9 numbers, which correspond to the 9 squares. You can map, say, 0 to the upper left, 1 to the upper-middle, 2 to the upper-right, etc. That's the computer's move. If the square is already occupied, generate a new number, and keep doing that until the computer picks an open square.

  13. #13
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    The random number thing is very helpful but i don't understand how to designate the computers turn like i know i have code writen that says player one or player two but how do i designate player to as the comp and make it so i use the random number code as his action

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You don't need to "designate" the player as the computer, at least not from a programming point of view. You ask the user for their move, then after they input, you just call your computer_move() function or whatever:
    Code:
    do
        ask for user input
        get user input
        computer_move
    while game is not over

  15. #15
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    I don't know what to write for the computer to go because I don't really know how i made it so that its Player vs. Player

Popular pages Recent additions subscribe to a feed