-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessValidator.cpp
More file actions
396 lines (344 loc) · 14.3 KB
/
Copy pathChessValidator.cpp
File metadata and controls
396 lines (344 loc) · 14.3 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// ============================================================
// Project 10: Mini Chess Move Validator
// OOP: Piece (base), King, Queen, Rook, Bishop, Knight, Pawn
// Board, MoveValidator, GameEngine classes
// DSA: 2D array (board), algorithms (move generation/validation)
// Domain: Algorithms / Game AI
// ============================================================
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
#include <memory>
using namespace std;
// ---------- Color & Piece Types ----------
enum class Color { WHITE, BLACK, NONE };
enum class PieceType { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN, EMPTY };
string colorStr(Color c) { return c == Color::WHITE ? "White" : c == Color::BLACK ? "Black" : "None"; }
// ---------- Square ----------
struct Square {
int row, col;
Square(int r = -1, int c = -1) : row(r), col(c) {}
bool isValid() const { return row >= 0 && row < 8 && col >= 0 && col < 8; }
bool operator==(const Square& o) const { return row == o.row && col == o.col; }
bool operator!=(const Square& o) const { return !(*this == o); }
string toChessNotation() const {
if (!isValid()) return "??";
return string(1, (char)('a' + col)) + to_string(8 - row);
}
static Square fromNotation(const string& s) {
if (s.size() < 2) return {-1,-1};
int c = s[0] - 'a';
int r = 8 - (s[1] - '0');
return {r, c};
}
};
// ---------- Base Piece ----------
class Piece {
protected:
PieceType type;
Color color;
public:
Piece(PieceType t, Color c) : type(t), color(c) {}
virtual ~Piece() {}
Color getColor() const { return color; }
PieceType getType() const { return type; }
virtual vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const = 0;
virtual char symbol() const = 0;
char displayChar() const {
char s = symbol();
return color == Color::WHITE ? toupper(s) : tolower(s);
}
bool isEnemy(Color other) const {
return color != Color::NONE && other != Color::NONE && color != other;
}
protected:
// Helper: slide in a direction until blocked
void slide(Square pos, int dr, int dc,
const vector<vector<shared_ptr<Piece>>>& board,
vector<Square>& moves) const {
int r = pos.row + dr, c = pos.col + dc;
while (r >= 0 && r < 8 && c >= 0 && c < 8) {
Square sq(r, c);
auto& piece = board[r][c];
if (!piece || piece->getColor() == Color::NONE) {
moves.push_back(sq);
} else {
if (piece->getColor() != color) moves.push_back(sq); // capture
break;
}
r += dr; c += dc;
}
}
};
// ---------- Empty Square ----------
class EmptyPiece : public Piece {
public:
EmptyPiece() : Piece(PieceType::EMPTY, Color::NONE) {}
vector<Square> getMoves(Square, const vector<vector<shared_ptr<Piece>>>&) const override { return {}; }
char symbol() const override { return '.'; }
};
// ---------- King ----------
class King : public Piece {
public:
King(Color c) : Piece(PieceType::KING, c) {}
char symbol() const override { return 'K'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) {
if (!dr && !dc) continue;
Square sq(pos.row+dr, pos.col+dc);
if (!sq.isValid()) continue;
auto& p = board[sq.row][sq.col];
if (!p || p->getColor() == Color::NONE || p->getColor() != color)
moves.push_back(sq);
}
return moves;
}
};
// ---------- Queen ----------
class Queen : public Piece {
public:
Queen(Color c) : Piece(PieceType::QUEEN, c) {}
char symbol() const override { return 'Q'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
for (auto [dr, dc] : vector<pair<int,int>>{{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}})
slide(pos, dr, dc, board, moves);
return moves;
}
};
// ---------- Rook ----------
class Rook : public Piece {
public:
Rook(Color c) : Piece(PieceType::ROOK, c) {}
char symbol() const override { return 'R'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
for (auto [dr, dc] : vector<pair<int,int>>{{1,0},{-1,0},{0,1},{0,-1}})
slide(pos, dr, dc, board, moves);
return moves;
}
};
// ---------- Bishop ----------
class Bishop : public Piece {
public:
Bishop(Color c) : Piece(PieceType::BISHOP, c) {}
char symbol() const override { return 'B'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
for (auto [dr, dc] : vector<pair<int,int>>{{1,1},{1,-1},{-1,1},{-1,-1}})
slide(pos, dr, dc, board, moves);
return moves;
}
};
// ---------- Knight ----------
class Knight : public Piece {
public:
Knight(Color c) : Piece(PieceType::KNIGHT, c) {}
char symbol() const override { return 'N'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
for (auto [dr, dc] : vector<pair<int,int>>{{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}}) {
Square sq(pos.row+dr, pos.col+dc);
if (!sq.isValid()) continue;
auto& p = board[sq.row][sq.col];
if (!p || p->getColor() == Color::NONE || p->getColor() != color)
moves.push_back(sq);
}
return moves;
}
};
// ---------- Pawn ----------
class Pawn : public Piece {
public:
Pawn(Color c) : Piece(PieceType::PAWN, c) {}
char symbol() const override { return 'P'; }
vector<Square> getMoves(Square pos, const vector<vector<shared_ptr<Piece>>>& board) const override {
vector<Square> moves;
int dir = (color == Color::WHITE) ? -1 : 1;
int startRow = (color == Color::WHITE) ? 6 : 1;
// Forward 1
Square fwd(pos.row + dir, pos.col);
if (fwd.isValid()) {
auto& p = board[fwd.row][fwd.col];
if (!p || p->getColor() == Color::NONE) {
moves.push_back(fwd);
// Forward 2 from start
Square fwd2(pos.row + 2*dir, pos.col);
if (pos.row == startRow && fwd2.isValid()) {
auto& p2 = board[fwd2.row][fwd2.col];
if (!p2 || p2->getColor() == Color::NONE)
moves.push_back(fwd2);
}
}
}
// Diagonal captures
for (int dc : {-1, 1}) {
Square cap(pos.row + dir, pos.col + dc);
if (cap.isValid()) {
auto& p = board[cap.row][cap.col];
if (p && p->getColor() != Color::NONE && p->getColor() != color)
moves.push_back(cap);
}
}
return moves;
}
};
// ---------- Board ----------
class Board {
private:
vector<vector<shared_ptr<Piece>>> grid;
shared_ptr<Piece> empty() { return make_shared<EmptyPiece>(); }
public:
Board() : grid(8, vector<shared_ptr<Piece>>(8)) {
for (auto& row : grid) for (auto& sq : row) sq = empty();
}
void setupStandard() {
// Black pieces
grid[0] = {make_shared<Rook>(Color::BLACK), make_shared<Knight>(Color::BLACK),
make_shared<Bishop>(Color::BLACK), make_shared<Queen>(Color::BLACK),
make_shared<King>(Color::BLACK), make_shared<Bishop>(Color::BLACK),
make_shared<Knight>(Color::BLACK), make_shared<Rook>(Color::BLACK)};
for (int c = 0; c < 8; c++) grid[1][c] = make_shared<Pawn>(Color::BLACK);
// White pieces
grid[7] = {make_shared<Rook>(Color::WHITE), make_shared<Knight>(Color::WHITE),
make_shared<Bishop>(Color::WHITE), make_shared<Queen>(Color::WHITE),
make_shared<King>(Color::WHITE), make_shared<Bishop>(Color::WHITE),
make_shared<Knight>(Color::WHITE), make_shared<Rook>(Color::WHITE)};
for (int c = 0; c < 8; c++) grid[6][c] = make_shared<Pawn>(Color::WHITE);
}
shared_ptr<Piece> at(Square sq) const { return grid[sq.row][sq.col]; }
void set(Square sq, shared_ptr<Piece> p) { grid[sq.row][sq.col] = p; }
const vector<vector<shared_ptr<Piece>>>& getGrid() const { return grid; }
bool movePiece(Square from, Square to) {
auto piece = at(from);
if (!piece || piece->getType() == PieceType::EMPTY) return false;
auto moves = piece->getMoves(from, grid);
if (find(moves.begin(), moves.end(), to) == moves.end()) return false;
grid[to.row][to.col] = piece;
grid[from.row][from.col] = empty();
return true;
}
bool isSquareAttacked(Square sq, Color byColor) const {
for (int r = 0; r < 8; r++)
for (int c = 0; c < 8; c++) {
auto& p = grid[r][c];
if (!p || p->getColor() != byColor) continue;
auto moves = p->getMoves({r, c}, grid);
if (find(moves.begin(), moves.end(), sq) != moves.end()) return true;
}
return false;
}
Square findKing(Color c) const {
for (int r = 0; r < 8; r++)
for (int col = 0; col < 8; col++)
if (grid[r][col]->getType() == PieceType::KING && grid[r][col]->getColor() == c)
return {r, col};
return {-1,-1};
}
bool isInCheck(Color c) const {
Square king = findKing(c);
if (!king.isValid()) return false;
Color enemy = (c == Color::WHITE) ? Color::BLACK : Color::WHITE;
return isSquareAttacked(king, enemy);
}
void print(const vector<Square>& highlights = {}) const {
cout << "\n a b c d e f g h\n";
cout << " +-----------------+\n";
for (int r = 0; r < 8; r++) {
cout << (8-r) << " | ";
for (int c = 0; c < 8; c++) {
Square sq(r, c);
bool hl = find(highlights.begin(), highlights.end(), sq) != highlights.end();
if (hl) cout << "* ";
else {
char ch = grid[r][c]->displayChar();
cout << ch << " ";
}
}
cout << "| " << (8-r) << "\n";
}
cout << " +-----------------+\n";
cout << " a b c d e f g h\n";
}
};
// ---------- Move Validator ----------
class MoveValidator {
public:
static void showMoves(Board& board, const string& squareStr) {
Square sq = Square::fromNotation(squareStr);
if (!sq.isValid()) { cout << " Invalid square: " << squareStr << "\n"; return; }
auto piece = board.at(sq);
if (!piece || piece->getType() == PieceType::EMPTY) {
cout << " No piece at " << squareStr << "\n"; return;
}
auto moves = piece->getMoves(sq, board.getGrid());
cout << "\n " << colorStr(piece->getColor()) << " "
<< piece->displayChar() << " at " << squareStr
<< " can move to " << moves.size() << " squares: ";
for (auto& m : moves) cout << m.toChessNotation() << " ";
cout << "\n";
board.print(moves);
}
static bool tryMove(Board& board, const string& from, const string& to) {
Square f = Square::fromNotation(from), t = Square::fromNotation(to);
auto piece = board.at(f);
if (!piece || piece->getType() == PieceType::EMPTY) {
cout << " No piece at " << from << "\n"; return false;
}
Color c = piece->getColor();
bool ok = board.movePiece(f, t);
if (ok) {
cout << " " << colorStr(c) << " " << piece->displayChar()
<< " " << from << " -> " << to;
if (board.isInCheck(c == Color::WHITE ? Color::BLACK : Color::WHITE))
cout << " [CHECK!]";
cout << "\n";
} else {
cout << " Invalid move: " << from << " -> " << to << "\n";
}
return ok;
}
};
// ---------- Main ----------
int main() {
cout << "========================================\n";
cout << " Mini Chess Move Validator\n";
cout << "========================================\n";
Board board;
board.setupStandard();
cout << "\n[Starting Position]\n";
board.print();
cout << "\n--- Showing Valid Moves ---\n";
MoveValidator::showMoves(board, "e2"); // White pawn
MoveValidator::showMoves(board, "g1"); // White knight
MoveValidator::showMoves(board, "d1"); // White queen (blocked)
cout << "\n--- Playing Some Moves ---\n";
MoveValidator::tryMove(board, "e2", "e4"); // e4
board.print();
MoveValidator::tryMove(board, "e7", "e5"); // e5
board.print();
MoveValidator::tryMove(board, "d1", "h5"); // Queen to h5 (Scholar's mate start)
board.print();
MoveValidator::showMoves(board, "h5"); // Show queen moves
MoveValidator::tryMove(board, "f7", "f6"); // Black blunder
board.print();
MoveValidator::tryMove(board, "h5", "e8"); // Fool's mate attempt (not valid - king protected)
cout << "\n--- Check Detection Test ---\n";
Board b2;
b2.setupStandard();
MoveValidator::tryMove(b2, "e2", "e4");
MoveValidator::tryMove(b2, "f7", "f5");
MoveValidator::tryMove(b2, "d1", "h5");
MoveValidator::tryMove(b2, "g7", "g6");
cout << "\n Attempting Scholar's Mate move...\n";
MoveValidator::tryMove(b2, "h5", "e8"); // Check
cout << "\n White in check? " << (b2.isInCheck(Color::WHITE) ? "Yes" : "No") << "\n";
cout << " Black in check? " << (b2.isInCheck(Color::BLACK) ? "Yes" : "No") << "\n";
b2.print();
return 0;
}