Need Help With Loop

inkedGFX

Well-known member
Joined
Feb 2, 2013
Messages
142
Programming Experience
Beginner
I am working on a tic tac toe game to learn how to generate a 2d array for the board. I can do this fine my question is how to loop over the board to see if there is a winner or a tie.
this is the code I have at the moment, I know there has to be a better way to do this , I am having a difficult time doing it .

here is what I have

C#:
 private bool calculateWinner()
        {
            bool isWinner = false;




            if (board[0, 0] == "X" && board[0, 1] == "X" && board[0, 2] == "X" ||
                board[1, 0] == "X" && board[1, 1] == "X" && board[1, 2] == "X" ||
                board[2, 0] == "X" && board[2, 1] == "X" && board[2, 2] == "X" ||
                board[0, 0] == "X" && board[1, 1] == "X" && board[2, 2] == "X" ||
                board[0, 0] == "X" && board[1, 1] == "X" && board[2, 2] == "X" ||
                board[0, 2] == "X" && board[1, 1] == "X" && board[2, 0] == "X")
            {
                winner = "Player 1";
                resetBoard();
                tie = 0;
                isWinner = true;
            }


            else if (board[0, 0] == "0" && board[0, 1] == "0" && board[0, 2] == "0" ||
                board[1, 0] == "0" && board[1, 1] == "0" && board[1, 2] == "0" ||
                board[2, 0] == "0" && board[2, 1] == "0" && board[2, 2] == "0" ||
                board[0, 0] == "0" && board[1, 1] == "0" && board[2, 2] == "0" ||
                board[0, 0] == "0" && board[1, 1] == "0" && board[2, 2] == "0" ||
                board[0, 2] == "0" && board[1, 1] == "0" && board[2, 0] == "0")
            {
                winner = "Player 2";
                resetBoard();
                tie = 0;
                isWinner = true;
            }
            else if (turn > 8)
            {
                tie = 1;
            }
        
            if (tie != 0)
            {
                winner = "Tie";
                isWinner = true;
                resetBoard();
            }
          
          


           return isWinner;
        }

this code works to check if X or 0 won but doesn't work in the case of a tie. is the anyway to do this with a for loop?

thank you for any help

-Inked
 
There are numerous options for this. One would to only consider the current player as they're the only one who could have won. That means passing in "X" or an "O" and only looking for three in a row of that type. I'd also suggest that you look for a winner without regard for whether the game is finished or not. Only once you've determined that there is no winner do you then check whether the game has finished. That means that the method that looks for a winner doesn't care about which move it is.
 
thank you for the quick reply. I will have to think about this differently it seems.

I will try to use a for loop and see if I can figure it out....thank you for the help

-Inked
 
Back
Top Bottom