- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudokuGUI.java
More file actions
Latest commit
666 lines (585 loc) · 23.6 KB
/
Copy pathSudokuGUI.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
importjavax.swing.*;
importjavax.swing.border.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.util.Stack;
importjava.util.Observer;
importjava.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" })
publicclassSudokuGUIextendsJPanelimplementsObserver {
privateintGRID_SIZE;//The size of the grid
privateSudokutheGame;
privateintmoveCount;//The number of moves made
privateStack<Assign> uStack;
privateStack<Assign> rStack;
privateJButton[][] cells; //Array of buttons to represent the cells
privateJButtonsaveButton, loadButton, clearButton, undoButton, redoButton, helpButton, quitButton;
privateJTextAreastatusArea;
privateJTextAreamoveHistoryArea;
privateJLabelmoveCountLabel;
privateJLabelremainingMovesLabel;
privateDifficultyManagerdifficultyManager;
/**
*
* 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.
*
*/
publicSudokuGUI() {
theGame = newSudoku();
difficultyManager = newDifficultyManager();
this.GRID_SIZE = theGame.getGameSize(); // Sets the grid size based on the game file automatically
//Setting up the difficulty Label
difficultyManager = newDifficultyManager();
remainingMovesLabel = newJLabel("");
remainingMovesLabel.setHorizontalAlignment(JLabel.CENTER);
remainingMovesLabel.setBorder(newLineBorder(Color.BLACK));
//Setting up the move count Label
moveCount = 0;
moveCountLabel = newJLabel("Moves: 0");
moveCountLabel.setHorizontalAlignment(JLabel.CENTER);
moveCountLabel.setBorder(newLineBorder(Color.BLACK));
// Setting up the border and padding for the main game grid
BorderroundedCornerBorder = newLineBorder(Color.BLACK, 1, true);
BorderpaddingBorder = newEmptyBorder(10, 10, 10, 10);
BordercompoundBorder = newCompoundBorder(roundedCornerBorder, paddingBorder);
// Setting up the main game grid
JPanelgridPanel = newJPanel(newGridLayout(GRID_SIZE, GRID_SIZE));
gridPanel.setBorder(compoundBorder);
cells = newJButton[GRID_SIZE][GRID_SIZE];
for (introw = 0; row < GRID_SIZE; row++) {
for (intcol = 0; col < GRID_SIZE; col++) {
cells[row][col] = createCellButton(row, col);
cells[row][col].setBorder(newRoundedBorder(10));
gridPanel.add(cells[row][col]);
}
}
// Setting up the buttons
saveButton = newJButton("Save");
saveButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
saveGame();
}
});
loadButton = newJButton("Load");
loadButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
loadGame();
}
});
clearButton = newJButton("Clear");
clearButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
clearGame();
}
});
undoButton = newJButton("Undo");
undoButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
undoMove();
}
});
redoButton = newJButton("Redo");
redoButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
redoMove();
}
});
helpButton = newJButton("Help");
helpButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
newHelpClass().displayHelpDialog();
}
});
quitButton = newJButton("Quit");
quitButton.addActionListener(newActionListener() {
@Override
publicvoidactionPerformed(ActionEventae) {
System.exit(0);
}
});
// Customize buttons with rounded corners
saveButton.setBorder(newRoundedBorder(20));
loadButton.setBorder(newRoundedBorder(20));
clearButton.setBorder(newRoundedBorder(20));
undoButton.setBorder(newRoundedBorder(20));
redoButton.setBorder(newRoundedBorder(20));
helpButton.setBorder(newRoundedBorder(20));
quitButton.setBorder(newRoundedBorder(20));
// Setting up the button panel
JPanelbuttonPanel = newJPanel();
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 = newJTextArea(2, 20);
statusArea.setEditable(false);
JPanelstatusPanel = newJPanel(newBorderLayout());
statusPanel.add(newJScrollPane(statusArea), BorderLayout.CENTER);
statusPanel.setBorder(BorderFactory.createTitledBorder(compoundBorder, "Instructions"));
// Setting up the move history area
moveHistoryArea = newJTextArea(5, 20);
moveHistoryArea.setEditable(false);
JPanelmoveHistoryPanel = newJPanel(newBorderLayout());
moveHistoryPanel.add(newJScrollPane(moveHistoryArea), BorderLayout.CENTER);
moveHistoryPanel.setBorder(BorderFactory.createTitledBorder(compoundBorder, "Keeping Track!"));
// Setting up the main panel layout
setLayout(newBorderLayout(10, 10));
add(statusPanel, BorderLayout.NORTH);
add(gridPanel, BorderLayout.CENTER);
add(moveHistoryPanel, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Initialize the stacks
uStack = newStack<>();
rStack = newStack<>();
// Observing the changes
for (introw = 0; row < GRID_SIZE; row++) {
for (intcol = 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
*
*/
classRoundedBorderimplementsBorder {
privateintradius;
RoundedBorder(intradius) {
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
publicInsetsgetBorderInsets(Componentc) {
returnnewInsets(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
publicbooleanisBorderOpaque() {
returnfalse;
}
/**
*
* 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
publicvoidpaintBorder(Componentc, Graphicsg, intx, inty, intwidth, intheight) {
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
*/
privateJButtoncreateCellButton(introw, intcol) {
JButtonbutton = newJButton();
button.addActionListener(e -> cellSelect(row, col));
returnbutton;
}
/**
* moveCountLabel
* Updates the label that displays the current move count.
*/
privatevoidmoveCountLabel() {
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.
*/
publicvoidinitializeDifficulty() {
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
*
*/
privatevoidlatestCellValue(introw, intcol) {
JButtoncellButton = cells[row][col];
StringcellValue = 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.
*
*/
privatevoidcellGraphics() {
for (introw = 0; row < GRID_SIZE; row++) {
for (intcol = 0; col < GRID_SIZE; col++) {
JButtoncell = cells[row][col];
if (this.isCellFillable(row, col)) {
cell.setBackground(Color.GREEN);
} else {
cell.setBackground(Color.WHITE);
}
cell.setForeground(Color.BLACK);
cell.setFont(newFont("Manrope", Font.BOLD, 20));
cell.setBorder(newRoundedBorder(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.
*
*/
privatevoidreplayGame() {
intplayAgainOption = 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.
*
*
*/
publicvoiddisplayGame() {
for (introw = 0; row < GRID_SIZE; row++) {
for (intcol = 0; col < GRID_SIZE; col++) {
JButtoncellButton = cells[row][col];
StringcellValue = 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 (JButtoncell : 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.
*
*/
privatevoidcellSelect(introw, intcol) {
if (!isCellFillable(row, col)) {
statusArea.setText("This cell cannot be changed.");
return;
}
intmaxValidNumber = GRID_SIZE == 9 ? 9 : 4;
Stringnumber = 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 + "]")) {
StringprevState = theGame.getIndividualMove(row, col);
// Check if the number is already in the same row or column
booleannumberExists = isNumberInRowOrColumn(row, col, number);
if (theGame.makeMove(Integer.toString(row), Integer.toString(col), number)) {
uStack.push(newAssign(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.
*/
privatebooleanisNumberInRowOrColumn(introw, intcol, Stringnumber) {
for (intc = 0; c < GRID_SIZE; c++) {
if (c != col) {
StringcellValue = theGame.getIndividualMove(row, c);
if (number.equals(cellValue)) {
returntrue; // Number found in the same column
}
}
}
for (intr = 0; r < GRID_SIZE; r++) {
if (r != row) {
StringcellValue = theGame.getIndividualMove(r, col);
if (number.equals(cellValue)) {
returntrue; // Number found in the same column
}
}
}
returnfalse; // Number not found in the same row or column
}
/**
* Saves the current game state to a file using the FileDriver class.
*/
privatevoidsaveGame() {
FileDriver.saveGame(theGame, GRID_SIZE, statusArea);
}
/**
* loads the saved game state from a file using the FileDriver class.
*/
privatevoidloadGame() {
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
*
*/
privatevoidclearGame() {
theGame = newSudoku(); // 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
*
*/
privatevoidundoMove() {
if (uStack.isEmpty())
{
statusArea.setText("No moves to undo.");
} else {
Assigntop = 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
*
*/
privatevoidredoMove() {
if (!rStack.isEmpty())
{
Assigntop = 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
*/
privatevoidupdateMoveHistory(Stringmove) {
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
*/
publicbooleanisCellFillable(introw, intcol) {
returntheGame.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
*/
privatevoidselectDifficulty() {
Object[] options = {"Easy", "Hard"};
intchoice = 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);
} elseif (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
*/
privatevoidupdateRemainingMovesLabel() {
if (difficultyManager.getDifficulty() == DifficultyManager.Difficulty.HARD) {
intremainingMoves = 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
publicvoidupdate(Observableo, Objectarg) {
// This method is called whenever the observed object is changed
for (introw = 0; row < GRID_SIZE; row++) {
for (intcol = 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
*
*/
publicstaticvoidmain(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrameframe = newJFrame("Sudoku");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SudokuGUIsudokuGUI = newSudokuGUI();
sudokuGUI.initializeDifficulty();
frame.getContentPane().add(sudokuGUI);
frame.pack();
frame.setVisible(true);
});
}
}//end of class SudoKuGUI