-
Notifications
You must be signed in to change notification settings - Fork 2
/
KeyCollectorGame.java
529 lines (472 loc) · 16.2 KB
/
KeyCollectorGame.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import java.util.Random;
import java.util.ArrayList;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Singleton class for the game
public class KeyCollectorGame extends javax.swing.JFrame implements ActionListener {
// Create an single STATIC instance of this class
private static KeyCollectorGame instance = new KeyCollectorGame();
// Method to retrieve the only object instantiated
public static KeyCollectorGame getInstance() {
return instance;
}
// Game objects
private Tile[][] tiles = new Tile[9][9];
private Player[] players = new Player[4];
private Key[] keys = new Key[6];
private Player current_player;
private Tile current_tile;
private int round = 0;
private Boolean gameOver = false;
private String gameStatus;
// GUI components
// Create status panel
private JPanel statusPanel = new JPanel(new FlowLayout());
private javax.swing.JLabel statusLabel = new javax.swing.JLabel("");
// Create action panel
private JPanel actionPanel = new JPanel(new BorderLayout());
private javax.swing.JLabel actionLabel = new javax.swing.JLabel("");
// Create menu panel
private JPanel menuPanel = new JPanel(new FlowLayout());
public static void main(String[] args) throws FileNotFoundException {
// Get the game (only one instance available)
KeyCollectorGame game = KeyCollectorGame.getInstance();
}
// Make constructor private so it cannot be instantiated
private KeyCollectorGame() {
super("Key Collector Game");
// Create map panel
JPanel mapPanel = new JPanel(new java.awt.GridLayout(9, 9));
// Add tiles
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tiles[i][j] = new Tile(i, j);
tiles[i][j].setFocusable(false);
tiles[i][j].setBackground(new java.awt.Color(104, 69, 5));
tiles[i][j].addActionListener(this);
mapPanel.add(tiles[i][j]);
}
}
// Initialize game
initialize();
// Add components to panels
statusPanel.add(statusLabel);
actionPanel.add(actionLabel, "North");
JButton newBtn = new JButton("New");
JButton loadBtn = new JButton("Load");
JButton saveBtn = new JButton("Save");
newBtn.addActionListener(this);
loadBtn.addActionListener(this);
saveBtn.addActionListener(this);
menuPanel.add(newBtn);
menuPanel.add(loadBtn);
menuPanel.add(saveBtn);
actionPanel.add(menuPanel, "South");
// Add panels
add(statusPanel, "North");
add(mapPanel, "Center");
add(actionPanel, "South");
// JFrame settings
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 700);
setVisible(true);
}
// Done By: Goh Kun Shun
private void initialize() {
// Reset game over
gameOver = false;
round = 0;
// Generate players
Player bangei = new Player("Ban Gei", "icons/1.gif", 0, 0);
Player arkimides = new Player("Ark Imides", "icons/2.gif", 0, 8);
Player canser = new Player("Can Ser", "icons/3.gif", 8, 0);
Player dozciztem = new Player("Doz Ciztem", "icons/4.gif", 8, 8);
// Put players into an array
players[0] = bangei;
players[1] = arkimides;
players[2] = canser;
players[3] = dozciztem;
// Generate keys
Key treasurechest = new Key("Treasure Chest", "icons/5.gif", new Movement(0, 0, 0, false));
Key pinkey = new Key("Pinkey", "icons/a.gif", new Movement(1, 1, 1, false));
Key donkey = new Key("Donkey", "icons/b.gif", new Movement(0, 0, 3, false));
Key keydisk = new Key("Key Disk", "icons/c.gif", new Movement(3, 3, 0, false));
Key keynote = new Key("Key Note", "icons/d.gif", new Movement(2, 2, 2, true));
Key monkey = new Key("Monkey", "icons/e.gif", new Movement(3, 3, 3, false));
// Put keys into array
keys[0] = treasurechest;
keys[1] = pinkey;
keys[2] = donkey;
keys[3] = keydisk;
keys[4] = keynote;
keys[5] = monkey;
// Place player on tiles
tiles[0][0].setPlayer(bangei);
tiles[0][8].setPlayer(arkimides);
tiles[8][0].setPlayer(canser);
tiles[8][8].setPlayer(dozciztem);
// Place treasure chest in the middle
tiles[4][4].setKey(treasurechest);
// Place keys on tile
randomPlaceKeys();
// Initialize first player
current_player = players[0];
current_tile = tiles[current_player.getX()][current_player.getY()];
// Check walkable tiles for first player
checkWalkable();
// Update text labels
updateGameStatus();
updateActionLabel("");
}
// Done By: Goh Kun Shun
private void randomPlaceKeys() {
// ArrayList to store coordinates of unoccupied tiles
ArrayList<Integer> xList = new ArrayList<Integer>();
ArrayList<Integer> yList = new ArrayList<Integer>();
// Random seed
Random rand = new Random();
// Check and store the coordinates with no player and key occupied
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!tiles[i][j].hasPlayer() && !tiles[i][j].hasKey()) {
xList.add(i);
yList.add(j);
}
}
}
//
for (int i = 1; i < 6; i++) {
// Generate a number between 0 to the (size of available tiles - 1)
int n = rand.nextInt(xList.size() - 1);
// Get the nth integer from xList and yList and load as x and y
int x = xList.get(n);
int y = yList.get(n);
// Remove nth integer from xList and yList, so it won't be repeated
xList.remove(n);
yList.remove(n);
// Set ith key to tiles[x][y]
tiles[x][y].setKey(keys[i]);
}
}
// Done By: Goh Kun Shun
private void checkWalkable() {
// Get movement of current player
Movement m = current_player.getMovement();
// Reset all tile's walkable status
resetWalkable();
// Change colour of current tile
current_tile.setBackground(new java.awt.Color(0, 255, 0));
// Set tiles's walkable status
if (m.mustSkip()) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// Check for: Up, Down,
// Left, Right,
// Bottom Left, Bottom Right,
// Top Left, Top Right
if (i == current_player.getX() && j == current_player.getY()-m.getVertical() ||
i == current_player.getX() && j == current_player.getY()+m.getVertical() ||
i == current_player.getX()-m.getHorizontal() && j == current_player.getY() ||
i == current_player.getX()+m.getHorizontal() && j == current_player.getY() ||
i == current_player.getX()+m.getDiagonal() && j == current_player.getY()-m.getDiagonal() ||
i == current_player.getX()+m.getDiagonal() && j == current_player.getY()+m.getDiagonal() ||
i == current_player.getX()-m.getDiagonal() && j == current_player.getY()-m.getDiagonal() ||
i == current_player.getX()-m.getDiagonal() && j == current_player.getY()+m.getDiagonal()) {
tiles[i][j].setWalkable(true);
}
}
}
}
else {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// Check vertical
for (int k = 1; k <= m.getVertical(); k++) {
if (i == current_player.getX() && j == current_player.getY()-k ||
i == current_player.getX() && j == current_player.getY()+k) {
tiles[i][j].setWalkable(true);
}
}
// Check horizontal
for (int k = 1; k <= m.getHorizontal(); k++) {
if (i == current_player.getX()-k && j == current_player.getY() ||
i == current_player.getX()+k && j == current_player.getY()) {
tiles[i][j].setWalkable(true);
}
}
// Check diagonal
for (int k = 1; k <= m.getDiagonal(); k++) {
if (i == current_player.getX()+k && j == current_player.getY()-k ||
i == current_player.getX()+k && j == current_player.getY()+k ||
i == current_player.getX()-k && j == current_player.getY()-k ||
i == current_player.getX()-k && j == current_player.getY()+k) {
tiles[i][j].setWalkable(true);
}
}
}
}
}
// Make treasure chest unwalkable if player haven't collected all keys
if (current_player.numKeysCollected() < 5) {
tiles[4][4].setWalkable(false);
}
}
// Done By: Ng Jing Keong
private void resetWalkable() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tiles[i][j].setWalkable(false);
// Reset colour
tiles[i][j].setBackground(new java.awt.Color(104, 69, 5));
}
}
}
// Done By: Ng Jing Keong
private void updateGameStatus() {
if (!gameOver)
gameStatus = "<html><b>" + current_player.getName() + "</b>'s turn.<br>";
else
gameStatus = "<html><b>" + tiles[4][4].getPlayer().getName() + "</b> wins!<br>";
for (int i = 0; i < 4; i++) {
gameStatus += "<b>" + players[i].getName() + "</b>'s collected: " + players[i].keysCollected() + "<br>";
}
gameStatus += "</html>";
statusLabel.setText(gameStatus);
}
// Done By: Ong Koon Hua
private void updateActionLabel(String s) {
String action = "<html>" + s + "</html>";
actionLabel.setText(action);
}
// Done By: Ong Koon Hua
private void newGame() {
// Clear the tiles
clearBoard();
// Reinitialize
initialize();
}
// Done By: Ong Koon Hua
private void clearBoard() {
// Clear the tiles
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tiles[i][j].setPlayer(null);
tiles[i][j].setKey(null);
}
}
}
// Done By: Christopher Too Wei Bin
private void loadGame() {
String s = null;
int x = -1;
int y = -1;
try {
// Open save file
FileInputStream in = new FileInputStream("save.txt");
// Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Clear the tiles
clearBoard();
// Load round number
if ((s = br.readLine()) != null) {
round = Integer.parseInt(s);
}
// Load current player
if ((s = br.readLine()) != null) {
for (int i = 0; i < 4; i++) {
// Clear all player's key
players[i].clearKeys();
// Set current player
if (players[i].getName().equals(s)) {
current_player = players[i];
}
}
}
// Load current tile (x, y)
if ((s = br.readLine()) != null) {
x = Integer.parseInt(s);
}
if ((s = br.readLine()) != null) {
y = Integer.parseInt(s);
}
current_tile = tiles[x][y];
// Load player's collected keys
for (int i = 0; i < 4; i++) {
if ((s = br.readLine()) != null) {
// Remove comma
String[] keys = s.split(",");
for (int j = 0; j < keys.length; j++) {
// Remove spacing
keys[j] = keys[j].replace(" ", "");
if (keys[j].equals("Pinkey")) {
players[i].addKey(new Key("Pinkey", "icons/a.gif", new Movement(1, 1, 1, false)));
} else if (keys[j].equals("Donkey")) {
players[i].addKey(new Key("Donkey", "icons/b.gif", new Movement(0, 0, 3, false)));
} else if (keys[j].equals("Monkey")) {
players[i].addKey(new Key("Monkey", "icons/e.gif", new Movement(3, 3, 3, false)));
} else if (keys[j].equals("KeyDisk")) {
players[i].addKey(new Key("Key Disk", "icons/c.gif", new Movement(3, 3, 0, false)));
} else if (keys[j].equals("KeyNote")) {
players[i].addKey(new Key("Key Note", "icons/d.gif", new Movement(2, 2, 2, true)));
}
}
}
}
// Load all tiles
for (int i = 0; i < 81; i++) {
for (int j = 0; j < 9; j++) {
// Load player if any
if ((s = br.readLine()) != null) {
if (s.equals("Ban Gei")) {
tiles[i][j].setPlayer(players[0]);
players[0].setCoordinates(i, j);
} else if (s.equals("Ark Imides")) {
tiles[i][j].setPlayer(players[1]);
players[1].setCoordinates(i, j);
} else if (s.equals("Can Ser")) {
tiles[i][j].setPlayer(players[2]);
players[2].setCoordinates(i, j);
} else if (s.equals("Doz Ciztem")) {
tiles[i][j].setPlayer(players[3]);
players[3].setCoordinates(i, j);
}
}
// Load key if any
if ((s = br.readLine()) != null) {
if (s.equals("Treasure Chest")) {
tiles[i][j].setKey(keys[0]);
} else if (s.equals("Pinkey")) {
tiles[i][j].setKey(keys[1]);
} else if (s.equals("Donkey")) {
tiles[i][j].setKey(keys[2]);
} else if (s.equals("Key Disk")) {
tiles[i][j].setKey(keys[3]);
} else if (s.equals("Key Note")) {
tiles[i][j].setKey(keys[4]);
} else if (s.equals("Monkey")) {
tiles[i][j].setKey(keys[5]);
}
}
}
}
// Close file
in.close();
// Recalculate walkable
checkWalkable();
// Update status
updateGameStatus();
}
catch (FileNotFoundException ex) {
updateActionLabel("Error opening save file.");
}
catch (IOException io) {
updateActionLabel("Error loading save file.");
}
}
// Done By: Christopher Too Wei Bin
private void saveGame() {
String s = "";
if (!gameOver) {
try {
// Create or load save file
FileOutputStream out = new FileOutputStream("save.txt");
// Save current round number
s += round + System.getProperty("line.separator");
// Save current player and tile
s += current_player.getName() + System.getProperty("line.separator");
s += current_player.getX() + System.getProperty("line.separator");
s += current_player.getY() + System.getProperty("line.separator");
// Save player's key
for (int i = 0; i < 4; i++) {
s += players[i].keysCollected() + System.getProperty("line.separator");
}
// Save all tiles status
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (tiles[i][j].getPlayer() != null)
s += tiles[i][j].getPlayer().getName() + System.getProperty("line.separator");
else
s += System.getProperty("line.separator");
if (tiles[i][j].getKey() != null)
s += tiles[i][j].getKey().getName() + System.getProperty("line.separator");
else
s += System.getProperty("line.separator");
}
}
byte data[] = s.getBytes();
out.write(data);
out.close();
}
catch (FileNotFoundException ex) {
}
catch (IOException io) {
}
} else {
updateActionLabel("Can't save after game over! Click 'New' to start a new game.");
}
}
// Done By: Goh Kun Shun
@Override
public void actionPerformed(ActionEvent ae) {
// Convert action event source to button
JButton clickedButton = (JButton)ae.getSource();
if (clickedButton.getText().equals("New")) {
newGame();
}
else if (clickedButton.getText().equals("Load")) {
loadGame();
}
else if (clickedButton.getText().equals("Save")) {
saveGame();
}
else {
// Only allow any actions if the game haven't end
if (!gameOver) {
// Convert action event source to tile
Tile clickedTile = (Tile)ae.getSource();
// // Debugging placeholder
// int x = clickedTile.getTileX();
// int y = clickedTile.getTileY();
// String player = "";
// String key = "";
// if (clickedTile.hasPlayer())
// player = tiles[x][y].getPlayer().getName();
// if (clickedTile.hasKey())
// key = tiles[x][y].getKey().getName();
// System.out.println("(" + x +", " + y + ") - " + player + key);
// Attempt to move to clicked tile
if (current_tile.attemptMove(clickedTile)) {
// Clear action label
updateActionLabel("");
// Update current player coordinates
current_player.setCoordinates(clickedTile.getTileX(), clickedTile.getTileY());
// Game over if current player occupied the tile treasure is on
gameOver = (tiles[4][4].getPlayer() == current_player);
// Game loop
if (!gameOver) {
// Increase round
round++;
// Set current player
current_player = players[round%4];
current_tile = tiles[current_player.getX()][current_player.getY()];
// Refresh walkables
checkWalkable();
}
else {
// Update game status
resetWalkable();
}
// Update game status
updateGameStatus();
}
else {
updateActionLabel("Invalid tile to move to.");
}
}
}
}
}