-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudokuGUI.java
More file actions
666 lines (585 loc) · 23.6 KB
/
SudokuGUI.java
File metadata and controls
666 lines (585 loc) · 23.6 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Stack;
import java.util.Observer;
import java.util.Observable;
/**
* SudokuGUI
* This class is the GUI for the Sudoku game. It contains the main method and the GUI elements.
* The class extends JPanel and implements Observer to observe changes in the game.
*
* @author Arun Kumar Sekar
* @version January 2024
*/
@SuppressWarnings({ "deprecation", "serial" })
public class SudokuGUI extends JPanel implements Observer {
private int GRID_SIZE;//The size of the grid
private Sudoku theGame;
private int moveCount;//The number of moves made
private Stack<Assign> uStack;
private Stack<Assign> rStack;
private JButton[][] cells; //Array of buttons to represent the cells
private JButton saveButton, loadButton, clearButton, undoButton, redoButton, helpButton, quitButton;
private JTextArea statusArea;
private JTextArea moveHistoryArea;
private JLabel moveCountLabel;
private JLabel remainingMovesLabel;
private DifficultyManager difficultyManager;
/**
*
* SudokuGUI
* This is the constructor for the SudokuGUI class.
* Initializes the Sudoku game model and sets up the graphical user interface components.
* This includes creating the game grid, setting up control buttons (Save, Load, Clear, Undo, Redo, Help, Quit),
* It also sets up the stacks for undo and redo.Constructor for the SudokuGUI class.
*
*/
public SudokuGUI() {
theGame = new Sudoku();
difficultyManager = new DifficultyManager();
this.GRID_SIZE = theGame.getGameSize(); // Sets the grid size based on the game file automatically
//Setting up the difficulty Label
difficultyManager = new DifficultyManager();
remainingMovesLabel = new JLabel("");
remainingMovesLabel.setHorizontalAlignment(JLabel.CENTER);
remainingMovesLabel.setBorder(new LineBorder(Color.BLACK));
//Setting up the move count Label
moveCount = 0;
moveCountLabel = new JLabel("Moves: 0");
moveCountLabel.setHorizontalAlignment(JLabel.CENTER);
moveCountLabel.setBorder(new LineBorder(Color.BLACK));
// Setting up the border and padding for the main game grid
Border roundedCornerBorder = new LineBorder(Color.BLACK, 1, true);
Border paddingBorder = new EmptyBorder(10, 10, 10, 10);
Border compoundBorder = new CompoundBorder(roundedCornerBorder, paddingBorder);
// Setting up the main game grid
JPanel gridPanel = new JPanel(new GridLayout(GRID_SIZE, GRID_SIZE));
gridPanel.setBorder(compoundBorder);
cells = new JButton[GRID_SIZE][GRID_SIZE];
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
cells[row][col] = createCellButton(row, col);
cells[row][col].setBorder(new RoundedBorder(10));
gridPanel.add(cells[row][col]);
}
}
// Setting up the buttons
saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
saveGame();
}
});
loadButton = new JButton("Load");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
loadGame();
}
});
clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
clearGame();
}
});
undoButton = new JButton("Undo");
undoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
undoMove();
}
});
redoButton = new JButton("Redo");
redoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
redoMove();
}
});
helpButton = new JButton("Help");
helpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
new HelpClass().displayHelpDialog();
}
});
quitButton = new JButton("Quit");
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
// Customize buttons with rounded corners
saveButton.setBorder(new RoundedBorder(20));
loadButton.setBorder(new RoundedBorder(20));
clearButton.setBorder(new RoundedBorder(20));
undoButton.setBorder(new RoundedBorder(20));
redoButton.setBorder(new RoundedBorder(20));
helpButton.setBorder(new RoundedBorder(20));
quitButton.setBorder(new RoundedBorder(20));
// Setting up the button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(paddingBorder);
buttonPanel.add(saveButton);
buttonPanel.add(loadButton);
buttonPanel.add(clearButton);
buttonPanel.add(undoButton);
buttonPanel.add(redoButton);
buttonPanel.add(helpButton);
buttonPanel.add(quitButton);
buttonPanel.add(moveCountLabel);
buttonPanel.add(remainingMovesLabel);
// Setting up the status display area
statusArea = new JTextArea(2, 20);
statusArea.setEditable(false);
JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.add(new JScrollPane(statusArea), BorderLayout.CENTER);
statusPanel.setBorder(BorderFactory.createTitledBorder(compoundBorder, "Instructions"));
// Setting up the move history area
moveHistoryArea = new JTextArea(5, 20);
moveHistoryArea.setEditable(false);
JPanel moveHistoryPanel = new JPanel(new BorderLayout());
moveHistoryPanel.add(new JScrollPane(moveHistoryArea), BorderLayout.CENTER);
moveHistoryPanel.setBorder(BorderFactory.createTitledBorder(compoundBorder, "Keeping Track!"));
// Setting up the main panel layout
setLayout(new BorderLayout(10, 10));
add(statusPanel, BorderLayout.NORTH);
add(gridPanel, BorderLayout.CENTER);
add(moveHistoryPanel, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Initialize the stacks
uStack = new Stack<>();
rStack = new Stack<>();
// Observing the changes
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
theGame.getMoves()[row][col].addObserver(this);
}
}
// Display the initial state of the game
displayGame();
// Update the cell appearance
cellGraphics();
//updating the remaining moves label
updateRemainingMovesLabel();
}
/**
*
* This class is used to create a rounded border
* It is used as a helper class for the SudokuGUI class.
* The Rounded border ovverides the default border
*
*/
class RoundedBorder implements Border {
private int radius;
RoundedBorder(int radius) {
this.radius = radius;
}
/**
*
* It returns the insets of the border.
*
* @param c The component for which this border insets value applies
* @return The insets of the border
*
*/
@Override
public Insets getBorderInsets(Component c) {
return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
}
/**
*
* Says whether the border is opaque or not.
*
* @return True if the border is opaque, false otherwise
*
*/
@Override
public boolean isBorderOpaque() {
return false;
}
/**
*
* This method paints the border of the specific component.
*
* @param c The component for which this border is being painted
* @param g The graphics context to use for painting the border
* @param x,y The x and y position of the painted border
* @param width,height The width and height of the painted border
*
*/
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawRoundRect(x, y, width-1, height-1, radius, radius);
}
}
/**
* createCellButton
* This method creates a new cell for the Sudoku grid.
*
* @param row The row number of the button
* @param col The column number of the button
* @return A JButton configured corresponding to the row and column
*/
private JButton createCellButton(int row, int col) {
JButton button = new JButton();
button.addActionListener(e -> cellSelect(row, col));
return button;
}
/**
* moveCountLabel
* Updates the label that displays the current move count.
*/
private void moveCountLabel() {
moveCountLabel.setText("Moves: " + moveCount);
}
/**
* initializeDifficulty
* Initializes the select difficulty frame of the Sudoku game.
* This method sets the difficulty and updates the label displaying the remaining moves.
*/
public void initializeDifficulty() {
selectDifficulty();
updateRemainingMovesLabel();
}
/**
* latestCellValue
* Updates the value of the the specific cell
* Sets the text to the current value
* Also checks if the cell is fillable or not
*
* @param row The row number of the cell
* @param col The column number of the cell
*
*/
private void latestCellValue(int row, int col) {
JButton cellButton = cells[row][col];
String cellValue = theGame.getIndividualMove(row, col);
cellButton.setText(cellValue.equals("-") ? "" : cellValue);
cellButton.setEnabled(isCellFillable(row, col));
}
/**
*
* cellGraphics
* This method defines graphical properties of all cells in the Sudoku grid.
* This includes the background color, text color, font, and border.
*
*/
private void cellGraphics() {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
JButton cell = cells[row][col];
if (this.isCellFillable(row, col)) {
cell.setBackground(Color.GREEN);
} else {
cell.setBackground(Color.WHITE);
}
cell.setForeground(Color.BLACK);
cell.setFont(new Font("Manrope", Font.BOLD, 20));
cell.setBorder(new RoundedBorder(10));
}
}
}
/**
*
* replayGame
* Asks the user to play another game upon successfully solving the puzzle.
* If the user chooses to play again, the game state is reset. Otherwise, the application exits.
*
*/
private void replayGame() {
int playAgainOption = JOptionPane.showConfirmDialog(this, "Yaaaayyyyyyyyy!!!!!!, you solved the puzzle\nWould you like to play again?", "Play Again?", JOptionPane.YES_NO_OPTION);
if (playAgainOption == JOptionPane.YES_OPTION) {
clearGame();
} else {
System.exit(0);
}
}
/**
*
* displayGame
* Updates the display of the entire game grid based on the current state of the game.
* Each cell's text is set to display the value of the corresponding cell in the game model.
* Once the grid is updated, the method checks if the game has been won. If so, it disables all cells.
*
*
*/
public void displayGame() {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
JButton cellButton = cells[row][col];
String cellValue = theGame.getIndividualMove(row, col);
cellButton.setText(cellValue.equals("-") ? "" : cellValue);
cellButton.setEnabled(isCellFillable(row, col)); // Enable based on fillability
}
}
// Check if the game is solved and prompt to play again
if (theGame.checkWin()) {
for (JButton[] cellRow : cells) {
for (JButton cell : cellRow) {
cell.setEnabled(false); // Disable all cells if the game is won
}
}
replayGame();
}
}
/**
* CellSelect
* Handles user interaction when a cell is selected in the Sudoku grid.
* If a cell is fillable, it prompts the user to enter a number for the cell.
* Validates the input to ensure it's a valid number for the specific Sudoku grid[9x9 or 4x4].
*
* Also checks against the difficulty settings to limit the moves
*
* @param row The row number of the clicked cell.
* @param col The column number of the clicked cell.
*
*/
private void cellSelect(int row, int col) {
if (!isCellFillable(row, col)) {
statusArea.setText("This cell cannot be changed.");
return;
}
int maxValidNumber = GRID_SIZE == 9 ? 9 : 4;
String number = JOptionPane.showInputDialog(this, "Enter a number for this box:(1-" + maxValidNumber + "): ");
// Validate the input number
while (number != null && !number.matches("[1-" + maxValidNumber + "]")) {
statusArea.setText("Invalid input. Please enter a number between 1 and " + maxValidNumber + ".");
number = JOptionPane.showInputDialog(this, "Enter a number for this box (1-" + maxValidNumber + "):");
}
if (number != null && number.matches("[1-" + maxValidNumber + "]")) {
String prevState = theGame.getIndividualMove(row, col);
// Check if the number is already in the same row or column
boolean numberExists = isNumberInRowOrColumn(row, col, number);
if (theGame.makeMove(Integer.toString(row), Integer.toString(col), number)) {
uStack.push(new Assign(theGame, row, col, number, prevState));
cells[row][col].setText(number);
cells[row][col].setForeground(Color.BLACK);
cells[row][col].setEnabled(true);
displayGame();
moveCount++;
moveCountLabel();
updateMoveHistory("Move made at row " + row + ", column " + col + " = " + number + ". Total moves: " + moveCount);
if (numberExists) {
statusArea.setText("Number " + number + " already exists in the same row or column. You can undo this.");
cells[row][col].setForeground(Color.RED);
} else {
updateMoveHistory("Move made at row " + row + ", column " + col + " = " + number);
statusArea.setText("Valid Move");
cells[row][col].repaint();
}
} else {
statusArea.setText("Invalid move. Please try again.");
}
}
if (difficultyManager.canMakeMove(moveCount, GRID_SIZE)) {
updateRemainingMovesLabel();
} else {
JOptionPane.showMessageDialog(this, "No more moves allowed on Hard difficulty.", "Move Limit Reached!!", JOptionPane.ERROR_MESSAGE);
return;
}
}
/**
* Checks if a given number exists in the same row or column as the specified cell.
*
* @param row The row of the cell being checked.
* @param col The column of the cell being checked.
* @param number The number to check for in the same row or column.
*
* @return true if the number exists in the same row or column, false otherwise.
*/
private boolean isNumberInRowOrColumn(int row, int col, String number) {
for (int c = 0; c < GRID_SIZE; c++) {
if (c != col) {
String cellValue = theGame.getIndividualMove(row, c);
if (number.equals(cellValue)) {
return true; // Number found in the same column
}
}
}
for (int r = 0; r < GRID_SIZE; r++) {
if (r != row) {
String cellValue = theGame.getIndividualMove(r, col);
if (number.equals(cellValue)) {
return true; // Number found in the same column
}
}
}
return false; // Number not found in the same row or column
}
/**
* Saves the current game state to a file using the FileDriver class.
*/
private void saveGame() {
FileDriver.saveGame(theGame, GRID_SIZE, statusArea);
}
/**
* loads the saved game state from a file using the FileDriver class.
*/
private void loadGame() {
FileDriver.loadGame(theGame, GRID_SIZE, statusArea, this);
}
/**
* clearGame
* This method resets the current game to a new game
* It resets all the stacks
* Also the UI and move counts are updated to a new game
*
*/
private void clearGame() {
theGame = new Sudoku(); // Reset the game
uStack.clear(); // Clear the move history
rStack.clear();
displayGame(); // Update the UI
statusArea.setText("Game cleared.");
moveCount = 0;
moveCountLabel();
}
/**
* undoMove
* This method performs the undo move resulting in the poping the last-in value in the ustack
* It will also push the move back onto the redo stack in case the user wants to redo the move again
* If there are no moves(empty stack), the method prints out "No moves to undo"
* Updates the move count, the move history area and the status area
*
*/
private void undoMove() {
if (uStack.isEmpty())
{
statusArea.setText("No moves to undo.");
} else {
Assign top = uStack.pop();
rStack.push(top); // Save the undone move for redoing
theGame.makeMove(Integer.toString(top.getRow()), Integer.toString(top.getCol()), top.getPrevMove());
displayGame();
cellGraphics();
statusArea.setText("Move undone.");
moveCount--;
moveCountLabel();
updateMoveHistory("Undo made at row " + top.getRow() + ", column " + top.getCol() + ". Total moves: " + moveCount);
}
}
/**
*
* This method implement redoMove to pop from value from the rStack if there are any and make the move again
* It will also push the move back onto the undo stack in case the user wants to undo the move again
* If there are no moves(empty stack), the method prints out "No moves to redo"
* Updates the move count, the move history area and the status area
*
*/
private void redoMove() {
if (!rStack.isEmpty())
{
Assign top = rStack.pop();
uStack.push(top); // Push the redone move back onto the undo stack
theGame.makeMove(Integer.toString(top.getRow()), Integer.toString(top.getCol()), top.getNumber());
displayGame();
cellGraphics();
statusArea.setText("Move redone.");
moveCount++;
moveCountLabel();
updateMoveHistory("Redo made at row " + top.getRow() + ", column " + top.getCol() + ". Total moves: " + moveCount);
} else {
statusArea.setText("No moves to redo.");
}
}
/**
* updateMoveHistory
* This method updates the move history area with the latest move
*
* @param move
*/
private void updateMoveHistory(String move) {
moveHistoryArea.append(move + "\n"); // Append the move to the text area
moveHistoryArea.setCaretPosition(moveHistoryArea.getDocument().getLength()); // Auto-scroll to the latest move
}
/**
* isCellFillable
* This method checks if the cell is fillable or not
*
* @param row
* @param col
* @return boolean true is the cell is fillable, false otherwise
*/
public boolean isCellFillable(int row, int col) {
return theGame.getMoves()[row][col].getFillable();
}
/**
* selectDifficulty
* This method displays the difficulty selection frame
* It sets the difficulty based on the user selection [EASY, HARD]
* Uses the difficulty manager class to set the moves based on the difficulty
* calls the updateRemainingMovesLabel() to update the remaining moves label
*/
private void selectDifficulty() {
Object[] options = {"Easy", "Hard"};
int choice = JOptionPane.showOptionDialog(this,
"Select Difficulty Level:",
"Difficulty Selection",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null, options, options[0]);
if (choice == 0) {
difficultyManager.setDifficulty(DifficultyManager.Difficulty.EASY);
} else if (choice == 1) {
difficultyManager.setDifficulty(DifficultyManager.Difficulty.HARD);
}
updateRemainingMovesLabel();
clearGame();
}
/**
* updateRemainingMovesLabel
* This method updates the remaining moves label based on the difficulty
* If the difficulty is hard, it will display the remaining moves
* If the difficulty is easy, it will display unlimited moves
*/
private void updateRemainingMovesLabel() {
if (difficultyManager.getDifficulty() == DifficultyManager.Difficulty.HARD) {
int remainingMoves = difficultyManager.getRemainingMoves(moveCount, GRID_SIZE);
remainingMovesLabel.setText("Remaining Moves: " + remainingMoves);
} else {
remainingMovesLabel.setText("Unlimited Moves");
}
}
/**
* Called whenever an observed object is changed. This method is part of the Observer implementation.
* It updates the value displayed in a cell if the corresponding Observable object (a move) has changed.
*
* @param o The observable object.
* @param arg An argument passed to the notifyObservers method (not used here).
*/
@Override
public void update(Observable o, Object arg) {
// This method is called whenever the observed object is changed
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
if (o == theGame.getMoves()[row][col]) {
latestCellValue(row, col); // Update the specific cell
}
}
}
}
/**
* main method
* This is the main method of the SudokuGUI class
* It creates a new JFrame and adds the SudokuGUI to the frame
*
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Sudoku");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SudokuGUI sudokuGUI = new SudokuGUI();
sudokuGUI.initializeDifficulty();
frame.getContentPane().add(sudokuGUI);
frame.pack();
frame.setVisible(true);
});
}
}//end of class SudoKuGUI