-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessMatch.java
More file actions
401 lines (333 loc) · 14.9 KB
/
ChessMatch.java
File metadata and controls
401 lines (333 loc) · 14.9 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
397
398
399
400
401
package chess;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import board.Board;
import board.Piece;
import board.Position;
import chess.pieces.Bishop;
import chess.pieces.King;
import chess.pieces.Knight;
import chess.pieces.Pawn;
import chess.pieces.Queen;
import chess.pieces.Rook;
// coracao do nosso
// sistema de xadrez
public class ChessMatch {
// tabuleiro do jogo
private Board board;
// variaveis da jogabilidade
private int turn;
private Color currentPlayer;
private boolean check; // por padrão ela é falsa
private boolean checkMate;
// jogadas especiais
private ChessPiece enPassantVulnerable;
private ChessPiece promoted;
// controle das peças comidas
private List<Piece> piecesOnTheBoard = new ArrayList<>();
private List<Piece> capturedPieces = new ArrayList<>();
public ChessMatch() {
board = new Board(8, 8);
currentPlayer = Color.WHITE;
turn = 1;
initialSetup();
}
public int getTurn() {
return turn;
}
public boolean getCheck() {
return check;
}
public boolean getCheckMate() {
return checkMate;
}
public Color getCurrentPlayer() {
return currentPlayer;
}
public ChessPiece getEnPassantVulnerable() {
return enPassantVulnerable;
}
public ChessPiece getPromoted() {
return promoted;
}
// as peças do tipo Piece não são retornadas e sim
// uma variacao delas, isto acontece para evitar erros
// durante o desenvolvimento
public ChessPiece[][] getPieces() {
ChessPiece[][] matrix = new ChessPiece[board.getRows()][board.getColumns()];
for (int i = 0; i < board.getRows(); i++) {
for (int j = 0; j < board.getColumns(); j++) {
matrix[i][j] = (ChessPiece) board.piece(i, j);
}
}
return matrix;
}
// metodo que faz uma
// jogada de xadrez
public ChessPiece performChessMove(ChessPosition sourcePosition, ChessPosition targetPosition) {
Position source = sourcePosition.toPosition();
Position target = targetPosition.toPosition();
validateSourcePosition(source);
validateTargetPosition(source, target);
Piece capturedPiece = makeMove(source, target);
if (testCheck(currentPlayer)) {
undoMove(source, target, capturedPiece);
throw new ChessException("Não podes se colocar em check...");
}
ChessPiece movedPiece = (ChessPiece) board.piece(target);
// fica aqui pois é possivel
// que a nova peça
// deixe o jogo em check
// #specialmove promotion
promoted = null;
if (movedPiece instanceof Pawn) {
if ((movedPiece.getColor() == Color.WHITE && target.getRow() == 0)
|| (movedPiece.getColor() == Color.BLACK && target.getRow() == 7)) {
promoted = (ChessPiece) board.piece(target);
promoted = replacePromotedPiece("Q");
}
}
check = (testCheck((opponent(currentPlayer)))) ? true : false;
if (testCheckMate(opponent(currentPlayer))) {
checkMate = true;
} else {
nextTurn();
}
// #specialmove en passant
if (movedPiece instanceof Pawn
&& (target.getRow() == source.getRow() - 2 || target.getRow() == source.getRow() + 2)) {
enPassantVulnerable = movedPiece;
} else {
enPassantVulnerable = null;
}
return (ChessPiece) capturedPiece;
}
public ChessPiece replacePromotedPiece(String type) {
if (promoted == null) {
throw new IllegalStateException("There is no piece to be promoted");
}
if (!type.equals("B") && !type.equals("N") && !type.equals("R") & !type.equals("Q")) {
return promoted;
}
Position pos = promoted.getChessPosition().toPosition();
Piece p = board.removePiece(pos);
piecesOnTheBoard.remove(p);
ChessPiece newPiece = newPiece(type, promoted.getColor());
board.placePiece(newPiece, pos);
piecesOnTheBoard.add(newPiece);
return newPiece;
}
private ChessPiece newPiece(String type, Color color) {
if (type.equals("B") ||type.equals("b") )
return new Bishop(board, color);
if (type.equals("N") ||type.equals("n") )
return new Knight(board, color);
if (type.equals("Q") ||type.equals("q") )
return new Queen(board, color);
return new Rook(board, color);
}
public boolean[][] possibleMoves(ChessPosition sourcePosition) {
Position position = sourcePosition.toPosition();
validateSourcePosition(position);
return board.piece(position).possibleMoves();
}
private Piece makeMove(Position sourcePosition, Position targetPosition) {
ChessPiece capturingPiece = (ChessPiece) board.removePiece(sourcePosition);
capturingPiece.increaseMoveCount();
Piece capturedPiece = board.removePiece(targetPosition);
board.placePiece(capturingPiece, targetPosition);
if (capturedPiece != null) {
piecesOnTheBoard.remove(capturedPiece);
capturedPieces.add(capturedPiece);
}
// #specialmove castling kingside rook
if (capturingPiece instanceof King && targetPosition.getColumn() == sourcePosition.getColumn() + 2) {
Position sourceT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() + 3);
Position targetT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() + 1);
ChessPiece rook = (ChessPiece) board.removePiece(sourceT);
board.placePiece(rook, targetT);
rook.increaseMoveCount();
}
// #specialmove castling queenside rook
if (capturingPiece instanceof King && targetPosition.getColumn() == sourcePosition.getColumn() - 2) {
Position sourceT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() - 4);
Position targetT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() - 1);
ChessPiece rook = (ChessPiece) board.removePiece(sourceT);
board.placePiece(rook, targetT);
rook.increaseMoveCount();
}
// #specialmove en passant
if (capturingPiece instanceof Pawn) {
if (sourcePosition.getColumn() != targetPosition.getColumn() && capturedPiece == null) {
Position pawnPosition;
if (capturingPiece.getColor() == Color.WHITE) {
pawnPosition = new Position(targetPosition.getRow() + 1, targetPosition.getColumn());
} else {
pawnPosition = new Position(targetPosition.getRow() - 1, targetPosition.getColumn());
}
capturedPiece = board.removePiece(pawnPosition);
capturedPieces.add(capturedPiece);
piecesOnTheBoard.remove(capturedPiece);
}
}
return capturedPiece;
}
// desfazendo o metodo acima
private void undoMove(Position sourcePosition, Position targetPosition, Piece capturedPiece) {
ChessPiece piece = (ChessPiece) board.removePiece(targetPosition);
piece.decreaseMoveCount();
board.placePiece(piece, sourcePosition);
// voltando a peça para o tabuleiro
if (capturedPiece != null) {
board.placePiece(capturedPiece, targetPosition);
capturedPieces.remove(capturedPiece);
piecesOnTheBoard.add(capturedPiece);
}
// #specialmove castling kingside rook
if (piece instanceof King && targetPosition.getColumn() == sourcePosition.getColumn() + 2) {
Position sourceT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() + 3);
Position targetT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() + 1);
ChessPiece rook = (ChessPiece) board.removePiece(targetT);
board.placePiece(rook, sourceT);
rook.decreaseMoveCount();
}
// #specialmove castling queenside rook
if (piece instanceof King && targetPosition.getColumn() == sourcePosition.getColumn() - 2) {
Position sourceT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() - 4);
Position targetT = new Position(sourcePosition.getRow(), sourcePosition.getColumn() - 1);
ChessPiece rook = (ChessPiece) board.removePiece(targetT);
board.placePiece(rook, sourceT);
rook.decreaseMoveCount();
}
// #specialmove en passant
if (piece instanceof Pawn) {
if (sourcePosition.getColumn() != targetPosition.getColumn() && capturedPiece == enPassantVulnerable) {
ChessPiece pawn = (ChessPiece) board.removePiece(targetPosition);
Position pawnPosition;
if (piece.getColor() == Color.WHITE) {
pawnPosition = new Position(3, targetPosition.getColumn());
} else {
pawnPosition = new Position(4, targetPosition.getColumn());
}
board.placePiece(pawn, pawnPosition);
}
}
}
private void validateSourcePosition(Position position) {
if (!board.thereIsAPiece(position)) {
throw new ChessException("Não tem peça na posição de origem.");
}
if (currentPlayer != ((ChessPiece) board.piece(position)).getColor()) {
throw new ChessException("A peça escolhida não é do seu time.");
}
if (!board.piece(position).isThereAnyPossibleMove()) {
throw new ChessException("Não existem movimentos possiveis para a peça escolhida.");
}
}
private void validateTargetPosition(Position source, Position target) {
if (!board.piece(source).possibleMove(target)) {
throw new ChessException("A peça escolhida nao pode se mover para a posição selecionada.");
}
}
private void nextTurn() {
turn++;
currentPlayer = (currentPlayer == Color.WHITE) ? Color.BLACK : Color.WHITE;
}
private Color opponent(Color color) {
return (color == Color.WHITE) ? Color.BLACK : Color.WHITE;
}
// metodo que busca a peca REI
// finding the King
private ChessPiece king(Color color) {
List<Piece> list = piecesOnTheBoard.stream().filter(piece -> ((ChessPiece) piece).getColor() == color)
.collect(Collectors.toList());
for (Piece p : list) {
if (p instanceof King) {
return (ChessPiece) p;
}
}
throw new IllegalStateException("Não existe o rei da equipe " + color);
}
// compara a matrix de movimentos
// de todas as peças do oponente
// com a pos do rei
private boolean testCheck(Color color) {
Position kingPosition = king(color).getChessPosition().toPosition();
List<Piece> opponentList = piecesOnTheBoard.stream()
.filter(piece -> ((ChessPiece) piece).getColor() == opponent(color))
.collect(Collectors.toList());
for (Piece p : opponentList) {
boolean[][] mat = p.possibleMoves();
if (mat[kingPosition.getRow()][kingPosition.getColumn()])
return true;
}
return false;
}
private boolean testCheckMate(Color color) {
if (!testCheck(color)) {
return false;
}
List<Piece> pieces = piecesOnTheBoard.stream()
.filter(piece -> ((ChessPiece) piece).getColor() == color)
.collect(Collectors.toList());
for (Piece p : pieces) {
boolean[][] mat = p.possibleMoves();
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
if (mat[i][j]) {
// testar se o movimento possivel tira do check
Position source = ((ChessPiece) p).getChessPosition().toPosition();
Position target = new Position(i, j);
Piece capturedPiece = makeMove(source, target);
boolean testCheck = testCheck(color);
// desfazendo o movimento
// utilizado apenas para testar
undoMove(source, target, capturedPiece);
if (!testCheck)
return false;
}
}
}
}
return true;
}
private void placeNewPiece(char column, int row, ChessPiece piece) {
board.placePiece(piece, new ChessPosition(column, row).toPosition());
piecesOnTheBoard.add(piece);
}
private void initialSetup() {
placeNewPiece('a', 1, new Rook(board, Color.WHITE));
placeNewPiece('b', 1, new Knight(board, Color.WHITE));
placeNewPiece('c', 1, new Bishop(board, Color.WHITE));
placeNewPiece('d', 1, new Queen(board, Color.WHITE));
placeNewPiece('e', 1, new King(board, Color.WHITE, this));
placeNewPiece('f', 1, new Bishop(board, Color.WHITE));
placeNewPiece('g', 1, new Knight(board, Color.WHITE));
placeNewPiece('h', 1, new Rook(board, Color.WHITE));
placeNewPiece('a', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('b', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('c', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('d', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('e', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('f', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('g', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('h', 2, new Pawn(board, Color.WHITE, this));
placeNewPiece('a', 8, new Rook(board, Color.BLACK));
placeNewPiece('b', 8, new Knight(board, Color.BLACK));
placeNewPiece('c', 8, new Bishop(board, Color.BLACK));
placeNewPiece('d', 8, new Queen(board, Color.BLACK));
placeNewPiece('e', 8, new King(board, Color.BLACK, this));
placeNewPiece('f', 8, new Bishop(board, Color.BLACK));
placeNewPiece('g', 8, new Knight(board, Color.BLACK));
placeNewPiece('h', 8, new Rook(board, Color.BLACK));
placeNewPiece('a', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('b', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('c', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('d', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('e', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('f', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('g', 7, new Pawn(board, Color.BLACK, this));
placeNewPiece('h', 7, new Pawn(board, Color.BLACK, this));
}
}