1
void player2_move (void){
  srand(time(NULL));
  int i = rand() % 3;
  int j = rand() % 3;

  for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++)
      if (matrix[i][j] == ' ') 
        break;
    if (matrix[i][j] == ' ')
      break;
  }
  if (i * j == 9)
  {
    printf ("Neither player wins\n"); 
    exit (0);
  }
  else
    matrix[i][j] = 'X';
}

This is for Homework

I have to make a game of TicTacToe and the issue I'm having is how to have the computer have randomized moves against the player. When I compile the computer just ends up choosing the same moves every game. How do I make this completely random? Ill attach a picture of what the compiler is showing.

The program is still a work in progress-so the product is still a bit messy

https://i.stack.imgur.com/H8fR1.png

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
chrisHG
  • 80
  • 1
  • 2
  • 18
  • 2
    Only call `srand(time(NULL));` once at the beginning of your program for starters.... You then need to compute the random move and check whether the array element is `'_'`. (if I recall correctly that is what you used for empty cells in your last question). If not, continue your random selection until the move is available. – David C. Rankin Nov 20 '17 at 06:32
  • The info in your image is text-only. Please replace the image link by text in your question. – Yunnosch Nov 20 '17 at 06:35
  • Glad to help. Keep at it, you will get this project done (and a good amount of learning along the way). Take it one step at a time. For the computer part of it, just put yourself in its shoes and ask "What would I need to know before I take the next step?" (e.g. which cells are available for move?, Do I have a move that would result in 3-in-a-row? Do I have a move that would put 2 of my `'X'` or `'O'` together? Would that leave an empty cell at either end? .... and then think about coding each part as you go... – David C. Rankin Nov 20 '17 at 06:50

0 Answers0