-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolitaireGUI.java
More file actions
464 lines (417 loc) · 17.4 KB
/
SolitaireGUI.java
File metadata and controls
464 lines (417 loc) · 17.4 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
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
package org.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* The graphical user interface for the Klondike Solitaire game.
* It handles the display of cards, user interactions, and game messages.
*
* @author Mika Edenfield
*/
public class SolitaireGUI {
private JFrame frame;
private JButton drawButton;
private JPanel tableauPanel, foundationPanel, deckPanel, drawnCardContainer, drawnCardPanel, timePanel;
private GameLogic gameLogic;
private KlondikeSolitaire klondikeSolitaire;
private JLabel drawnCardLabel, timeLabel;
private int selectedColumn = -1;
private Card selectedCard = null;
private Card drawnCard = null;
private Timer timer;
private long startTime;
private long elapsedTime;
/**
* Constructs the SolitaireGUI, initializing the main frame, panels, buttons,
* and setting up the initial game display. It also starts the game timer.
*
* @param klondikeSolitaire The main game instance.
*/
public SolitaireGUI(KlondikeSolitaire klondikeSolitaire) {
this.klondikeSolitaire = klondikeSolitaire;
this.gameLogic = klondikeSolitaire.getGameLogic();
frame = new JFrame("Klondike Solitaire");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setLayout(new BorderLayout());
frame.setResizable(true);
// Create the draw button
drawButton = new JButton("Draw Card");
drawButton.addActionListener(e -> gameLogic.drawCard());
// Initialize panels
tableauPanel = new JPanel(new GridLayout(1, 7));
foundationPanel = new JPanel(new GridLayout(1, 4));
drawnCardContainer = new JPanel(new FlowLayout());
this.timePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// Initialize time label
this.timeLabel = new JLabel("Time: 00:00");
this.timePanel.add(this.timeLabel);
// Add components to the main frame
frame.add(drawButton, BorderLayout.NORTH);
frame.add(tableauPanel, BorderLayout.CENTER);
frame.add(foundationPanel, BorderLayout.SOUTH);
frame.add(drawnCardContainer, BorderLayout.EAST);
frame.add(this.timePanel, BorderLayout.WEST);
updateGUI(false);
startGameTimer(); // Start the timer when the GUI is initialized
frame.setVisible(true);
}
/**
* Starts the game timer, recording the start time and initiating updates
* to the time display every second.
*/
private void startGameTimer() {
startTime = System.currentTimeMillis();
timer = new Timer(1000, new ActionListener() { // Update every 1 second
@Override
public void actionPerformed(ActionEvent e) {
elapsedTime = System.currentTimeMillis() - startTime;
updateTimeDisplay();
}
});
timer.start();
}
/**
* Stops the game timer if it is currently running.
*/
private void stopGameTimer() {
if (timer != null && timer.isRunning()) {
timer.stop();
}
}
/**
* Updates the time display label with the elapsed time in MM:SS format.
*/
private void updateTimeDisplay() {
long minutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime) % 60;
this.timeLabel.setText(String.format("Time: %02d:%02d", minutes, seconds));
}
/**
* Updates the graphical user interface to reflect the current state of the game,
* including the tableau, drawn card, and foundation piles.
*
* @param normalUpdate Indicates if this is a regular update (true) or an initial setup (false).
*/
public void updateGUI(boolean normalUpdate) {
// Clear previous state
tableauPanel.removeAll();
drawnCardContainer.removeAll();
// Drawn card display
JButton drawnCardButton;
if (drawnCard != null && drawnCard.isFaceUp()) {
drawnCardButton = new JButton(drawnCard.toString());
setCardColor(drawnCardButton, drawnCard);
drawnCardButton.addActionListener(e -> {
handleDrawnCardClick();
});
drawnCardContainer.add(new JLabel("Drawn Card: "));
drawnCardContainer.add(drawnCardButton);
} else {
drawnCardContainer.add(new JLabel("Drawn Card: "));
drawnCardContainer.add(new JButton("None"));
}
tableauPanel.setLayout(new GridLayout(1, 7));
for (int i = 0; i < 7; i++) {
List<Card> columnCards = klondikeSolitaire.getTableau().getColumnCards(i);
JPanel columnPanel = new JPanel();
columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.Y_AXIS));
columnPanel.setPreferredSize(new Dimension(100, columnCards.size() * 150));
if (columnCards.isEmpty()) {
// Empty column: add a placeholder button
JButton emptyButton = new JButton("Empty Column");
emptyButton.setPreferredSize(new Dimension(100, 150));
int columnIndex = i;
emptyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (selectedCard != null && selectedCard.getRank() == Card.Rank.KING) {
if (gameLogic.moveBetweenTableaus(selectedColumn, columnIndex)) {
updateColumnPanel(columnIndex);
if(selectedColumn != -1) {
updateColumnPanel(selectedColumn);
}
updateGUI(true);
selectedCard = null;
selectedColumn = -1;
} else {
JOptionPane.showMessageDialog(frame, "Invalid move.");
}
}
}
});
columnPanel.add(emptyButton);
} else {
// Non-empty column: add card buttons
for (Card card : columnCards) {
JButton cardButton;
if (card.isFaceUp()) {
cardButton = new JButton(card.toString());
setCardColor(cardButton, card);
} else {
cardButton = new JButton("Face Down");
cardButton.setForeground(Color.BLACK);
}
cardButton.setPreferredSize(new Dimension(100, 150));
int columnIndex = i;
cardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleCardClick(columnIndex, card);
}
});
columnPanel.add(cardButton);
}
}
tableauPanel.add(columnPanel);
}
tableauPanel.revalidate();
tableauPanel.repaint();
// Update foundations state
foundationPanel.removeAll();
foundationPanel.setLayout(new GridLayout(2, 4));
Card.Suit[] suits = Card.Suit.values(); // Get the suit values
for (int i = 0; i < 4; i++) {
final int foundationIndex = i;
List<Card> foundationCards = klondikeSolitaire.getFoundation().getFoundationCards(i);
String displayText = foundationCards.isEmpty() ? "Empty" : foundationCards.get(foundationCards.size() - 1).toString();
JButton foundationButton = new JButton(displayText);
if (!foundationCards.isEmpty()) {
Card topCard = foundationCards.get(foundationCards.size() - 1);
setCardColor(foundationButton, topCard);
}
foundationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (selectedCard != null) {
if (gameLogic.moveToFoundation(selectedColumn, foundationIndex)) {
if(selectedColumn != -1){
updateColumnPanel(selectedColumn);
}
updateGUI(true);
selectedCard = null;
selectedColumn = -1;
} else {
JOptionPane.showMessageDialog(frame, "Invalid move to foundation.");
}
}
}
});
foundationPanel.add(foundationButton);
}
foundationPanel.revalidate();
foundationPanel.repaint();
frame.revalidate();
frame.repaint();
}
/**
* Sets the currently drawn card from the stock.
*
* @param card The drawn card.
*/
public void setDrawnCard(Card card) {
this.drawnCard = card;
}
/**
* Returns the currently drawn card from the stock.
*
* @return The drawn card, or null if no card has been drawn.
*/
public Card getDrawnCard() {
return drawnCard;
}
/**
* Sets the color of a card button based on the suit of the card.
* Red for Hearts and Diamonds, Black for Clubs and Spades.
*
* @param cardButton The button representing the card.
* @param card The card associated with the button.
*/
private void setCardColor(JButton cardButton, Card card) {
if (card.getSuit() == Card.Suit.HEARTS || card.getSuit() == Card.Suit.DIAMONDS) {
cardButton.setForeground(Color.RED);
} else {
cardButton.setForeground(Color.BLACK);
}
}
/**
* Handles the click event on the drawn card. If a card is drawn, it becomes the
* currently selected card for potential moves.
*/
private void handleDrawnCardClick() {
if (drawnCard != null) {
selectedCard = drawnCard;
}
}
/**
* Handles the click event on a card in the tableau. It manages the selection
* of cards for moving and initiates move attempts through the game logic.
*
* @param columnIndex The index of the column where the card was clicked.
* @param card The clicked card.
*/
private void handleCardClick(int columnIndex, Card card) {
List<Card> columnCards = klondikeSolitaire.getTableau().getColumnCards(columnIndex);
if (selectedCard == null) {
if (columnCards.contains(card) && card.isFaceUp()) {
selectedCard = card;
selectedColumn = columnIndex;
}
} else {
if (selectedCard == drawnCard) {
if (gameLogic.moveBetweenTableaus(-1, columnIndex)) {
SwingUtilities.invokeLater(() -> {
updateColumnPanel(columnIndex);
updateGUI(true);
});
} else {
JLabel errorLabel = new JLabel("Invalid Move, Try Again");
JOptionPane.showMessageDialog(frame, errorLabel);
}
selectedCard = null;
selectedColumn = -1;
return;
}
Card movedCard = selectedCard;
if (gameLogic.moveBetweenTableaus(selectedColumn, columnIndex)) {
SwingUtilities.invokeLater(() -> {
updateColumnPanel(columnIndex);
if (selectedColumn != -1) {
updateColumnPanel(selectedColumn);
}
SwingUtilities.invokeLater(() -> {
updateGUI(true);
});
});
} else {
JLabel errorLabel = new JLabel("Invalid Move, Try Again");
JOptionPane.showMessageDialog(frame, errorLabel);
}
selectedCard = null;
selectedColumn = -1;
}
}
/**
* Updates the visual representation of a single tableau column.
*
* @param columnIndex The index of the column to update.
*/
public void updateColumnPanel(int columnIndex) {
JPanel columnPanel = (JPanel) tableauPanel.getComponent(columnIndex);
columnPanel.removeAll();
List<Card> columnCards = klondikeSolitaire.getTableau().getColumnCards(columnIndex);
if (columnCards.isEmpty()) {
JButton emptyButton = new JButton("Empty Column");
emptyButton.setPreferredSize(new Dimension(100, 150));
emptyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (selectedCard != null && selectedCard.getRank() == Card.Rank.KING) {
if (gameLogic.moveBetweenTableaus(selectedColumn, columnIndex)) {
updateColumnPanel(columnIndex);
if(selectedColumn != -1) {
updateColumnPanel(selectedColumn);
}
updateGUI(true);
selectedCard = null;
selectedColumn = -1;
} else {
JOptionPane.showMessageDialog(frame, "Invalid move.");
}
}
}
});
columnPanel.add(emptyButton);
} else {
for (int i = 0; i < columnCards.size(); i++) {
Card card = columnCards.get(i);
JButton cardButton;
if (card.isFaceUp()) {
cardButton = new JButton(card.toString());
setCardColor(cardButton, card);
} else {
cardButton = new JButton("Face Down");
cardButton.setForeground(Color.BLACK);
}
if (i == columnCards.size() - 1) {
cardButton.setPreferredSize(new Dimension(100, 150));
} else {
cardButton.setPreferredSize(new Dimension(100, 30));
}
int colIndex = columnIndex;
cardButton.addActionListener(e -> handleCardClick(colIndex, card));
columnPanel.add(cardButton);
columnPanel.add(Box.createVerticalStrut(5));
}
}
columnPanel.revalidate();
columnPanel.repaint();
}
/**
* Handles the win condition of the game. Stops the timer, displays a
* congratulatory message with the final time, and offers options to
* play again or close the game.
*/
public void handleWinCondition() {
stopGameTimer(); // Stop the timer when the game is won
long minutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime) % 60;
long seconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime) % 60;
String timeString = String.format("%02d:%02d", minutes, seconds);
String message = "Congratulations!\nYour time was " + timeString + "\nPlay Again?";
int option = JOptionPane.showConfirmDialog(
frame,
message,
"You Won!",
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
restartGame();
} else if (option == JOptionPane.NO_OPTION) {
frame.dispose(); // Close the game window
}
}
/**
* Restarts the game by creating a new KlondikeSolitaire instance and
* closing the current game window.
*/
private void restartGame() {
stopGameTimer(); // Ensure the timer is stopped
new KlondikeSolitaire();
frame.dispose(); // Close the current game window
}
/**
* Prints a debug message to the console.
*
* @param message The message to print.
*/
private void debug(String message) {
System.out.println("[DEBUG] " + message);
}
/**
* Returns the currently selected card by the user.
*
* @return The selected Card object, or null if no card is selected.
*/
public Card getSelectedCard(){
return selectedCard;
}
/**
* Sets the GameLogic instance for this GUI.
*
* @param gameLogic The GameLogic object.
*/
public void setGameLogic(GameLogic gameLogic){
this.gameLogic = gameLogic;
}
/**
* Main method to start the Solitaire GUI (although the game is initiated from KlondikeSolitaire).
*
* @param args Command line arguments (not used).
*/
public static void main(String[] args) {
new KlondikeSolitaire();
}
}