-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connect4.java
468 lines (405 loc) · 13.1 KB
/
Connect4.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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* This class contains the main method for running the game.
*
*/
//import view.Connect4TextView;
import view.Connect4View;
import view.DialogBox;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observer;
import controller.Connect4Controller;
import model.Connect4Model;
import model.Connect4MoveMessage;
import model.IllegalArgumentException;
import model.Minimax_AlphaBeta;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.scene.control.Alert;
public class Connect4 extends Application implements Runnable {
private Observer currentView;
private Observer guiView;
private BorderPane window;
private Connect4Model gameModel;
private static final int width = 344;
private static final int height = 326;
private static final String SERIALIZED_MODEL_NAME = "save_game.dat";
private DialogBox dialogBox;
private ServerSocket server;
private Socket socket;
Connect4MoveMessage mvMsg = null;
public static void main(String[] args) {
launch(args);
}
/**
* This method is to generate a GUI that can interact with the user and contains
* a menu item to start a new game, and close with a saved game
*
* @param primaryStage the window of the GUI
*/
@Override
public void start(Stage primaryStage) {
boolean foundSerializedFile = this.deserializeGameModel();
if (!foundSerializedFile) {
initGame();
} else {
}
primaryStage.setTitle("Connect 4");
window = new BorderPane();
Scene scene = new Scene(window, width, height);
// Add MenuBar
MenuBar menuBar = new MenuBar();
// Do this for more responsive UI when resizing the window.
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
MenuItem newGameButton = new MenuItem();
Menu FileMenu = new Menu();
FileMenu.setText("File");
MenuItem networkedButton = new MenuItem("Networked Game");
newGameButton.setText("New Game");
// construct a new game model
newGameButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent ae) {
// gameModel.newGame();
gameModel = new Connect4Model();
modelSetting(foundSerializedFile, true, false, true);
}
});
networkedButton.setOnAction(event -> {
dialogBox = new DialogBox();
dialogBox.setTitle("Network Setup");
dialogBox.initModality(Modality.APPLICATION_MODAL);
dialogBox.getOk().setOnAction(e -> {
gameModel = new Connect4Model();
if (dialogBox.serverIsCheck() || dialogBox.clientIsCheck()) {
if (dialogBox.humanIsCheck() || dialogBox.computerIsCheck()) {
if (dialogBox.serverIsCheck()) {
modelSetting(false, dialogBox.humanIsCheck(), true, true);
createServer(dialogBox.getPort());
} else {
modelSetting(false, dialogBox.humanIsCheck(), true, false);
createClient(dialogBox.getServerName(), dialogBox.getPort());
}
} else {
new Alert(Alert.AlertType.ERROR, "Please select Human or Computer").showAndWait();
return;
}
} else {
new Alert(Alert.AlertType.ERROR, "Please select Server or Client").showAndWait();
return;
}
Thread networkThread = new Thread(this);
networkThread.start();
dialogBox.close();
});
dialogBox.show();
});
FileMenu.getItems().add(newGameButton);
FileMenu.getItems().add(networkedButton);
menuBar.getMenus().add(FileMenu);
window.setTop((Node) menuBar);
modelSetting(foundSerializedFile, true, false, true);
// if the game is not over, create a file storing the game(model object)
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
if (gameModel.isOver())
((Connect4View) guiView).deleteSerializedFile();
else
serializeGameModel();
}
});
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest((event) -> {
closeNetwork();
});
primaryStage.show();
}
/**
* This method is to set up the model by linking it to the GUIView(Observer) and
* controller
*
* @param foundSerializedFile true means that there is a serializedFile under
* the current directory otherwise not
*/
private void modelSetting(boolean foundSerializedFile, boolean isFirstHuman, boolean isNetworkGame,
boolean moveFirst) {
Connect4Controller gameController = new Connect4Controller(gameModel);
guiView = new Connect4View(gameModel, gameController, foundSerializedFile, isFirstHuman, isNetworkGame,
moveFirst);
setViewTo(guiView);
gameModel.addObserver(guiView);
gameModel.addObserver(currentView);
}
private void createServer(int port) {
try {
server = new ServerSocket(port);
socket = server.accept();
System.out.println("Client connected: " + socket.getInetAddress());
} catch (IOException e) {
e.printStackTrace();
}
}
private void createClient(String serverName, int port) {
try {
socket = new Socket(serverName, port);
System.out.println("Connected to server at: " + socket.getInetAddress() + " with port: " + port);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method is to create a new instance for gameModel
*/
private void initGame() {
gameModel = new Connect4Model();
}
/**
* This method is to set the GUI to the center of the pane
*
* @param newView Passing a new view to
*/
private void setViewTo(Observer newView) {
window.setCenter(null);
currentView = newView;
window.setCenter((Node) currentView);
}
/**
* This method is to serialize the game model object.
*/
public void serializeGameModel() {
try {
FileOutputStream outputFile = new FileOutputStream("./" + SERIALIZED_MODEL_NAME);
ObjectOutputStream oos = new ObjectOutputStream(outputFile);
oos.writeObject(gameModel);
oos.close();
outputFile.close();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
/**
* This method will return true if found a serialized file to deserialize from
* and false otherwise.
*
* @return True if found a serialized file to deserialize from.
*/
public boolean deserializeGameModel() {
try {
FileInputStream inputFile = new FileInputStream("./" + SERIALIZED_MODEL_NAME);
ObjectInputStream ois = new ObjectInputStream(inputFile);
this.gameModel = (Connect4Model) ois.readObject();
this.gameModel.setComputerPlayer(new Minimax_AlphaBeta());
System.out.println("Found a serialized file.");
ois.close();
inputFile.close();
return true;
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
return false;
} catch (ClassNotFoundException ex) {
System.err.println(ex.getStackTrace());
return false;
}
}
@Override
public void run() {
Connect4MoveMessage oldMvMsg = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
// This instance of program is a server.
try {
output = new ObjectOutputStream(socket.getOutputStream());
input = new ObjectInputStream(socket.getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
while (!gameModel.isOver() && socket.isConnected()) {
System.out.println("Networking thread is still running.");
if (server != null) {
try {
if (gameModel.isHumanMove()) {
if (!dialogBox.humanIsCheck()) {
gameModel.computerMove(gameModel.getHumanChar(), true);
mvMsg = gameModel.getMoveMsg();
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
continue;
}
mvMsg = gameModel.getMoveMsg();
if (mvMsg == null)
continue;
if (oldMvMsg != null) {
if ((mvMsg.getRow() == oldMvMsg.getRow() && mvMsg.getColumn() == oldMvMsg.getColumn()
&& mvMsg.getColor() == oldMvMsg.getColor()))
continue;
}
System.out.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
if (!mvMsg.equals(oldMvMsg)) {
if (oldMvMsg == null) {
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
} else {
if ((mvMsg.getRow() != oldMvMsg.getRow()) || mvMsg.getColumn() != oldMvMsg.getColumn()
|| mvMsg.getColor() != oldMvMsg.getColor()) {
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
}
}
}
} else {
mvMsg = (Connect4MoveMessage) input.readObject();
if (mvMsg == null)
continue;
if (oldMvMsg != null) {
if ((mvMsg.getRow() == oldMvMsg.getRow() && mvMsg.getColumn() == oldMvMsg.getColumn()
&& mvMsg.getColor() == oldMvMsg.getColor()))
continue;
}
if (!mvMsg.equals(oldMvMsg)) {
if (oldMvMsg == null) {
System.out.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
((Connect4View) currentView).getController().placeToken(mvMsg.getColumn());
gameModel.printRawBoard();
gameModel.switchTurn();
} else {
if ((mvMsg.getRow() != oldMvMsg.getRow()) || mvMsg.getColumn() != oldMvMsg.getColumn()
|| mvMsg.getColor() != oldMvMsg.getColor()) {
System.out
.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
((Connect4View) currentView).getController().placeToken(mvMsg.getColumn());
gameModel.printRawBoard();
gameModel.switchTurn();
}
}
oldMvMsg = mvMsg;
mvMsg = null;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This instance of program is a client.
} else {
try {
if (!gameModel.isHumanMove()) {
if (!dialogBox.humanIsCheck()) {
gameModel.computerMove(gameModel.getComputerChar(), false);
mvMsg = gameModel.getMoveMsg();
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
continue;
}
mvMsg = gameModel.getMoveMsg();
if (mvMsg == null)
continue;
if (oldMvMsg != null) {
if ((mvMsg.getRow() == oldMvMsg.getRow() && mvMsg.getColumn() == oldMvMsg.getColumn()
&& mvMsg.getColor() == oldMvMsg.getColor()))
continue;
}
System.out.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
if (!mvMsg.equals(oldMvMsg)) {
if (oldMvMsg == null) {
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
} else {
if ((mvMsg.getRow() != oldMvMsg.getRow()) || mvMsg.getColumn() != oldMvMsg.getColumn()
|| mvMsg.getColor() != oldMvMsg.getColor()) {
output.writeObject(mvMsg);
output.flush();
oldMvMsg = mvMsg;
gameModel.switchTurn();
mvMsg = null;
}
}
}
} else {
mvMsg = (Connect4MoveMessage) input.readObject();
if (mvMsg == null)
continue;
if (oldMvMsg != null) {
if ((mvMsg.getRow() == oldMvMsg.getRow() && mvMsg.getColumn() == oldMvMsg.getColumn()
&& mvMsg.getColor() == oldMvMsg.getColor()))
continue;
}
if (!mvMsg.equals(oldMvMsg)) {
if (oldMvMsg == null) {
System.out.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
((Connect4View) currentView).getController().placeToken(mvMsg.getColumn());
gameModel.printRawBoard();
gameModel.switchTurn();
} else {
if ((mvMsg.getRow() != oldMvMsg.getRow()) || mvMsg.getColumn() != oldMvMsg.getColumn()
|| mvMsg.getColor() != oldMvMsg.getColor()) {
System.out
.println(mvMsg.getRow() + " " + mvMsg.getColumn() + " " + mvMsg.getColor());
((Connect4View) currentView).getController().placeToken(mvMsg.getColumn());
gameModel.printRawBoard();
gameModel.switchTurn();
}
}
oldMvMsg = mvMsg;
mvMsg = null;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void closeNetwork() {
try {
if (server != null)
server.close();
if (socket != null)
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}