1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+
5
+
6
+ char board[3 ][3 ] = { {' 1' ,' 2' ,' 3' }, {' 4' ,' 5' ,' 6' }, {' 7' ,' 8' ,' 9' } };
7
+ char current_marker;
8
+ int current_player;
9
+
10
+
11
+
12
+
13
+ void drawBoard () {
14
+ cout << " " << board[0 ][0 ] << " | " << board[0 ][1 ] << " | " << board[0 ][2 ] << endl;
15
+ cout << " ---|---|---" << endl;
16
+ cout << " " << board[1 ][0 ] << " | " << board[1 ][1 ] << " | " << board[1 ][2 ] << endl;
17
+ cout << " ---|---|---" << endl;
18
+ cout << " " << board[2 ][0 ] << " | " << board[2 ][1 ] << " | " << board[2 ][2 ] << endl;
19
+ }
20
+
21
+ bool placeMarker (int slot) {
22
+ int row = (slot - 1 ) / 3 ;
23
+ int col = (slot - 1 ) % 3 ;
24
+
25
+ if (board[row][col] != ' X' && board[row][col] != ' O' ) {
26
+ board[row][col] = current_marker;
27
+ return true ;
28
+ } else {
29
+ return false ;
30
+ }
31
+ }
32
+
33
+
34
+ int winner () {
35
+ // Rows
36
+ for (int i = 0 ; i < 3 ; i++) {
37
+ if (board[i][0 ] == board[i][1 ] && board[i][1 ] == board[i][2 ]) return current_player;
38
+ }
39
+
40
+ // Columns
41
+ for (int i = 0 ; i < 3 ; i++) {
42
+ if (board[0 ][i] == board[1 ][i] && board[1 ][i] == board[2 ][i]) return current_player;
43
+ }
44
+
45
+ // Diagonals
46
+ if (board[0 ][0 ] == board[1 ][1 ] && board[1 ][1 ] == board[2 ][2 ]) return current_player;
47
+ if (board[0 ][2 ] == board[1 ][1 ] && board[1 ][1 ] == board[2 ][0 ]) return current_player;
48
+
49
+ return 0 ;
50
+ }
51
+
52
+ void swapPlayerAndMarker () {
53
+ if (current_marker == ' X' ) current_marker = ' O' ;
54
+ else current_marker = ' X' ;
55
+
56
+ if (current_player == 1 ) current_player = 2 ;
57
+ else current_player = 1 ;
58
+ }
59
+
60
+
61
+
62
+
63
+ void game () {
64
+ cout << " Player 1, choose your marker: X or O: " ;
65
+ char marker_p1;
66
+ cin >> marker_p1;
67
+
68
+ current_player = 1 ;
69
+ current_marker = marker_p1;
70
+
71
+ drawBoard ();
72
+
73
+ int player_won;
74
+
75
+ for (int i = 0 ; i < 9 ; i++) {
76
+ cout << " It's player " << current_player << " 's turn. Enter your slot: " ;
77
+ int slot;
78
+ cin >> slot;
79
+
80
+ if (slot < 1 || slot > 9 || !placeMarker (slot)) {
81
+ cout << " Invalid move, try again.\n " ;
82
+ i--;
83
+ continue ;
84
+ }
85
+
86
+ drawBoard ();
87
+ player_won = winner ();
88
+
89
+ if (player_won == 1 ) { cout << " Player 1 wins!\n " ; break ; }
90
+ if (player_won == 2 ) { cout << " Player 2 wins!\n " ; break ; }
91
+
92
+ swapPlayerAndMarker ();
93
+ }
94
+
95
+ if (player_won == 0 ) cout << " It's a tie!\n " ;
96
+ }
97
+
98
+ int main () {
99
+ bool yorn=true ;
100
+ while (yorn){
101
+ cout<<" Do you want to play?" <<" \n Y/N" <<endl;
102
+ char ch;
103
+ cin>>ch;
104
+ if (ch==' Y' ){
105
+ yorn==true ;
106
+ }
107
+ else {
108
+ yorn==false ;
109
+ break ;
110
+ }
111
+ game ();
112
+ }
113
+ return 0 ;
114
+ }
0 commit comments