-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXO_Classes.cpp
More file actions
95 lines (75 loc) · 2.83 KB
/
XO_Classes.cpp
File metadata and controls
95 lines (75 loc) · 2.83 KB
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
//--------------------------------------- IMPLEMENTATION
#include <iostream>
#include <iomanip>
#include <cctype> // for toupper()
#include "XO_Classes.h"
using namespace std;
//--------------------------------------- X_O_Board Implementation
X_O_Board::X_O_Board() : Board(3, 3) {
// Initialize all cells with blank_symbol
for (auto& row : board)
for (auto& cell : row)
cell = blank_symbol;
}
bool X_O_Board::update_board(Move<char>* move) {
int x = move->get_x();
int y = move->get_y();
char mark = move->get_symbol();
// Validate move and apply if valid
if (!(x < 0 || x >= rows || y < 0 || y >= columns) &&
(board[x][y] == blank_symbol || mark == 0)) {
if (mark == 0) { // Undo move
n_moves--;
board[x][y] = blank_symbol;
}
else { // Apply move
n_moves++;
board[x][y] = toupper(mark);
}
return true;
}
return false;
}
bool X_O_Board::is_win(Player<char>* player) {
const char sym = player->get_symbol();
auto all_equal = [&](char a, char b, char c) {
return a == b && b == c && a != blank_symbol;
};
// Check rows and columns
for (int i = 0; i < rows; ++i) {
if ((all_equal(board[i][0], board[i][1], board[i][2]) && board[i][0] == sym) ||
(all_equal(board[0][i], board[1][i], board[2][i]) && board[0][i] == sym))
return true;
}
// Check diagonals
if ((all_equal(board[0][0], board[1][1], board[2][2]) && board[1][1] == sym) ||
(all_equal(board[0][2], board[1][1], board[2][0]) && board[1][1] == sym))
return true;
return false;
}
bool X_O_Board::is_draw(Player<char>* player) {
return (n_moves == 9 && !is_win(player));
}
bool X_O_Board::game_is_over(Player<char>* player) {
return is_win(player) || is_draw(player);
}
//--------------------------------------- XO_UI Implementation
XO_UI::XO_UI() : UI<char>("Weclome to FCAI X-O Game by Dr El-Ramly", 3) {}
Player<char>* XO_UI::create_player(string& name, char symbol, PlayerType type) {
// Create player based on type
cout << "Creating " << (type == PlayerType::HUMAN ? "human" : "computer")
<< " player: " << name << " (" << symbol << ")\n";
return new Player<char>(name, symbol, type);
}
Move<char>* XO_UI::get_move(Player<char>* player) {
int x, y;
if (player->get_type() == PlayerType::HUMAN) {
cout << "\nPlease enter your move x and y (0 to 2): ";
cin >> x >> y;
}
else if (player->get_type() == PlayerType::COMPUTER) {
x = rand() % player->get_board_ptr()->get_rows();
y = rand() % player->get_board_ptr()->get_columns();
}
return new Move<char>(x, y, player->get_symbol());
}