I\'m creating a TicTacToe class that contains a 3 by 3 rectangular array of integers & is played by 2 human players. \"1\" is used for the first player\'s move & \"2\" i
As Iiya has said, you're going to have to through through all the win cases. There's many ways to do that but the very gist of it in code would be
private bool checkWinner(int player)
{
// check rows
if (board[0, 0] == player && board[0, 1] == player && board[0, 2] == player) { return true; }
if (board[1, 0] == player && board[1, 1] == player && board[1, 2] == player) { return true; }
if (board[2, 0] == player && board[2, 1] == player && board[2, 2] == player) { return true; }
// check columns
if (board[0, 0] == player && board[1, 0] == player && board[2, 0] == player) { return true; }
if (board[0, 1] == player && board[1, 1] == player && board[2, 1] == player) { return true; }
if (board[0, 2] == player && board[1, 2] == player && board[2, 2] == player) { return true; }
// check diags
if (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player) { return true; }
if (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player) { return true; }
return false;
}
You can optimise this however which way you'd like (using for loops or matrices). Note the checkWinner()
function requires a player
input.
One simple approach is to try every square (for i = 0; i < 3; for j = 0; j < 3) then if that square is not blank go in every of the eight possible directions, counting each square with the same 'color' until you go off the board. If your count ever reaches the value three then you have a winner position for the color of the starting square.
I will try to answer how to detect the draw, as all others have focused only on checking if someone won.
The game can only be drawn when the board is fully completed, and no other winning combination is formed. So it's not difficult to detect after you checked for winner and haven't found one.
I wont code it for you but here is the logic you can use:
1) For each column check if all rows are the same, if yes declare winner. If not go to step 2.
2) For each row check if all column values are the same, if yes declare winner. If not go to step 3.
3) Now check diagonals, there are only two possibilities here [0,0] [1,1] [2,2] and also [0,2] [1,1] [2,0] if they are the same declare winner, if not check whether all values in array are filled, if yes declare draw if not make users enter values.