-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTictactoe.cpp
123 lines (97 loc) · 2.89 KB
/
Tictactoe.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
using namespace std;
class TicTacToe {
private:
char gameBoard[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
char currentPlayer;
int row, column;
bool winner;
public:
// generator for first player
TicTacToe(){
currentPlayer = 'O';
}
// print current board
void printBoard(){
cout << " | | " << endl;
cout << " " << gameBoard[0][0] << " | " << gameBoard[0][1] << " | " << gameBoard[0][2] << endl;
cout << "___|___|___" << endl;
cout << " | | " << endl;
cout << " " << gameBoard[1][0] << " | " << gameBoard[1][1] << " | " << gameBoard[1][2] << endl;
cout << "___|___|___" << endl;
cout << " | | " << endl;
cout << " " << gameBoard[2][0] << " | " << gameBoard[2][1] << " | " << gameBoard[2][2] << endl;
cout << " | | " << endl;
}
// change current player
void changePlayer(){
if (currentPlayer == 'O'){
currentPlayer = 'X';
}
else
if (currentPlayer == 'X'){
currentPlayer = 'O';
}
}
// record the move played aka change the board
void changeBoard(){
gameBoard[row][column] = currentPlayer;
}
// ask the user for the move
void enterMove(){
cout << "Player "<< currentPlayer << ":" << endl << "Enter your move: (row, column)" << endl;
cin >> row >> column;
}
// check if the board has a winner
bool checkWinner(){
// check rows
for (int r = 0; r < 3; r++) {
if (gameBoard[r][0] != ' ' && gameBoard[r][0] == gameBoard[r][1] && gameBoard[r][1] == gameBoard[r][2]) {
winner = true;;
break;
}
}
// check columns
for (int c = 0; c < 3; c++) {
if (gameBoard[0][c] != ' ' && gameBoard[0][c] == gameBoard[1][c] && gameBoard[1][c] == gameBoard[2][c]) {
winner = true;;
break;
}
}
// check diagonals
if (gameBoard[0][0] != ' ' && gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2]) {
winner = true;
}
else if (gameBoard[0][2] != ' ' && gameBoard[0][2] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][0]) {
winner = true;
}
return winner;
}
// display winner
void displayWinner(){
cout<<"Game Over!"<< endl << "Player "<< currentPlayer <<" Won.";
}
};
int main(){
TicTacToe t;
for (int i = 0; i<9; i++){
t.printBoard();
t.enterMove();
t.changeBoard();
if (t.checkWinner()){
t.printBoard();
t.displayWinner();
break;
}
t.changePlayer();
if (i==8){
t.printBoard();
cout<<"Game Over!\nIt's a draw.";
}
}
return 0;
}