Using a struct/char array for Tic Tac Toe Game

Hello,

I spent my entire winter vacation basically taking a 5-unit Calculus class (in 5-weeks) for over four hours a day, every day of the week, so I'm a little bit rusty (didn't have time to practice programming).

I basically just want a function that tells me if 'X' or 'O' won in a tic-tac-toe game. I don't care about the visuals, I just want a function that tells me if 'X' or 'O' won. If X wins, return 0. If Y wins, return 1.

I kind of get how to do the diagonals, but as far as the across and down wins, I know I have to use a nested for loop, but am a little stuck, as to exactly how to set it up.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

struct TTT{
char array[3][3];
unsigned moves;
};

unsigned whoHasWon( const TTT & game );


int main(){

	TTT x = {{{'X','O',' '}, {' ','X',' '}, {'O',' ','X'}}, 5};
	cout <<whoHasWon( x ); 

return 0;

}

unsigned whoHasWon( const TTT & game ){

	if (game.array[0][2] == game.array[1][1] == game.array[2][0]{
	return 0;
	}

	else if (game.array[0][0] == game.array[1][1] == game.array[2][2]){
        return 0;
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

typedef char board_type[3][3] ;

bool check_win( const board_type& board )
{
    // 1, check rows
    for( const auto& row : board )
        if( row[0] == row[1] && row[1] == row[2] ) return true ;

    // 2. check cols
    for( int c = 0 ; c < 3 ; ++c )
        if( board[0][c] == board[1][c] && board[1][c] == board[2][c] ) return true ;

    // 3. check diagonals
    if( board[0][0] == board[1][1] && board[1][1] == board[2][2] ) return true ;
    if( board[2][0] == board[1][1] && board[1][1] == board[0][2] ) return true ;

   return false ;
}

int main()
{
    {
        board_type b { {'X','O',' '}, {'X','O',' '}, {'X',' ','O'} } ;
        char last_move_made_by = 'X' ;

        if( check_win(b) ) std::cout << last_move_made_by << " has won.\n" ;
    }

    {
        board_type b { {'X',' ',' '}, {' ','X','X'}, {'O','O','O'} } ;
        char last_move_made_by = 'O' ;

        if( check_win(b) ) std::cout << last_move_made_by << " has won.\n" ;
    }
}
Topic archived. No new replies allowed.