Ajout Grille + Swing UI Grille Sudoku
This commit is contained in:
77
SudokuButtonListener.java
Normal file
77
SudokuButtonListener.java
Normal file
@@ -0,0 +1,77 @@
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
|
||||
public class SudokuButtonListener implements ActionListener {
|
||||
private int row;
|
||||
private int col;
|
||||
private Sudoku sudoku;
|
||||
private JButton[][] buttons;
|
||||
|
||||
public SudokuButtonListener(int row, int col, Sudoku sudoku, JButton[][] buttons) {
|
||||
this.row = row;
|
||||
this.col = col;
|
||||
this.sudoku = sudoku;
|
||||
this.buttons = buttons;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
String input = JOptionPane.showInputDialog("Enter a number:");
|
||||
if (input != null && input.length() > 0) {
|
||||
try {
|
||||
int num = Integer.parseInt(input);
|
||||
sudoku.getGrid().getCell(row, col).setValue(num);
|
||||
if (num == 0) {
|
||||
buttons[row][col].setText(""); // Empty cell if the number is 0
|
||||
} else {
|
||||
buttons[row][col].setText(String.valueOf(num));
|
||||
}
|
||||
if (!isValidMove(num, row, col)) {
|
||||
buttons[row][col].setForeground(Color.RED); // Set text color to red for invalid move
|
||||
} else {
|
||||
buttons[row][col].setForeground(Color.BLACK); // Reset text color
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isValidMove(int num, int row, int col) {
|
||||
return isValidRow(num, row) && isValidCol(num, col) && isValidBox(num, row - row % 3, col - col % 3);
|
||||
}
|
||||
|
||||
private boolean isValidRow(int num, int row) {
|
||||
for (int i = 0; i < 9; i++) {
|
||||
if (sudoku.getGrid().getCell(row, i).getValue() == num && i != col) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isValidCol(int num, int col) {
|
||||
for (int i = 0; i < 9; i++) {
|
||||
if (sudoku.getGrid().getCell(i, col).getValue() == num && i != row) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isValidBox(int num, int boxStartRow, int boxStartCol) {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
int row = i + boxStartRow;
|
||||
int col = j + boxStartCol;
|
||||
if (sudoku.getGrid().getCell(row, col).getValue() == num && (row != this.row || col != this.col)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user