-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame.java
102 lines (83 loc) · 2.96 KB
/
Game.java
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
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import board.Board;
import board.Chessboard;
import board.Move;
import board.Space;
import pieces.Piece;
import player.ComputerPlayer;
import player.HumanPlayer;
import player.Player;
import pieces.King;
public class Game {
private Player[] players;
private Board board;
private Chessboard cb;
private Player currentTurn;
private GameStatus status;
private List<Move> movesPlayed;
public void initialise(Player p1, Player p2) {
players[0] = p1;
players[1] = p2;
board.resetBoard();
this.currentTurn = (p1.isWhite()) ? p1 : p2;
movesPlayed.clear();
}
public boolean isEnd() {
return this.getStatus() != GameStatus.ACTIVE;
}
public GameStatus getStatus() {
return this.status;
}
public void setStatus(GameStatus status) {
this.status = status;
}
public boolean playerMove(Player player, int startX, int startY, int endX, int endY) throws Exception {
Space startSpace = board.getSpace(startX, startY);
Space endSpace = board.getSpace(endX, endY);
Move move = new Move(player, startSpace, endSpace);
return this.makeMove(move, player);
}
public boolean makeMove(Move move, Player player) {
Piece sourcePiece = move.getStart().getPiece();
if(sourcePiece == null
|| player != currentTurn
|| sourcePiece.isWhite() != player.isWhite()
|| !sourcePiece.canMove(board, move.getStart(), move.getEnd()))
return false;
Piece destPiece = move.getEnd().getPiece();
if(destPiece != null) {
destPiece.setKilled(true);
move.setPieceKilled(destPiece);
}
if(sourcePiece instanceof King && ((King) sourcePiece).isCastlingMove(move.getStart(), move.getEnd()))
move.setCastlingMove(true);
movesPlayed.add(move);
move.getEnd().setPiece(move.getStart().getPiece());
move.getStart().setPiece(null);
if(destPiece instanceof King) {
if(player.isWhite()) this.setStatus(GameStatus.WHITE_WIN);
else this.setStatus(GameStatus.BLACK_WIN);
}
this.currentTurn = this.currentTurn == players[0] ? players[1] : players[0];
return true;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
Chessboard cb = new Chessboard();
JFrame f = new JFrame("Chess");
f.add(cb.getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}