2

I'm working on a homework assignment in C where we need to make a tic-tac-toe game that can be played between two players. I have all of my code working at this point, except for the function that checks to find a winner. Here's an example of the outcome of a game I tested with:

  0 1 2
0  |x| 
  -----
1  |o| 
  -----
2  |x| 
Congratulations to player 1!  You won!

To which I say, no. No, player 1 definitely didn't win. My checks are (forgive me) a series of nested if statements like so:

...
else if (gameboard[0][1] != ' ')
    if (gameboard[1][1] == gameboard[0][1])
        if(gameboard[2][1] == gameboard[1][1])
            return 1;
...

gameboard[0][1] is an 'x' value, yet the comparison says that gameboard[1][1] is equal to it. Why is this happening and how do I fix it?

Thiago Silveira
  • 5,033
  • 4
  • 26
  • 29
bourgtai
  • 367
  • 1
  • 4
  • 9
  • You might have a `=` that should be a `==` in your code - did you copy/paste that snippet here or retype it? We'll need to see some more details to tell you what's going wrong. There's nothing that looks noticeably wrong with the bit you've already shown. – Carl Norum Apr 05 '11 at 01:02
  • You will need to post code showing how you declare/create `gameboard` and how you assign things to it. `==` is certainly how you would compare two `char` values. – Brian Roach Apr 05 '11 at 01:03
  • have your program print out gameboard[0] and gameboard[1] so that you can verify the strings are what you think they should be. – jcomeau_ictx Apr 05 '11 at 01:04
  • 2
    post all the `if..else` block, you have maybe some missing `{}` – manji Apr 05 '11 at 01:10
  • You should probably have a bunch of functions that talk in terms of the board rather the array which would clean up your code and make it more readable. – Noufal Ibrahim Apr 05 '11 at 01:19

1 Answers1

1

Your gameboard might be set up differently from what you are thinking.

#include <stdio.h>

int main()
{
    char gameboard[3][3] =
    { {' ', 'x', ' '},
      {' ', 'o', ' '},
      {' ', 'x', ' '}
    };

    if (gameboard[0][0] == ' ')
    {
        printf("0,0 is empty\n");
    }

    if (gameboard[0][1] != ' ')
    {
        printf("0,1 has %c\n", gameboard[0][1]);
    }

    if (gameboard[1][1] == gameboard[0][1])
    {
        printf("1,1 equals 0,1\n");
    }
    else
    {
        printf("1,1 is different from 0,1\n");
    }    
}

Outputs:

0,0 is empty
0,1 has x
1,1 is different from 0,1
karlphillip
  • 92,053
  • 36
  • 243
  • 426