SAE21_2023/SudokuButtonListener.java

77 lines
2.6 KiB
Java
Raw Normal View History

2024-04-28 01:40:14 +02:00
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SudokuButtonListener implements ActionListener {
private int row;
2024-04-28 01:40:14 +02:00
private int col;
private Sudoku sudoku;
private JButton[][] buttons;
2024-04-28 01:40:14 +02:00
public SudokuButtonListener(int row, int col, Sudoku sudoku, JButton[][] buttons) {
this.row = row;
2024-04-28 01:40:14 +02:00
this.col = col;
this.sudoku = sudoku;
this.buttons = buttons;
2024-04-28 01:40:14 +02:00
}
@Override
public void actionPerformed(ActionEvent e) {
String input = JOptionPane.showInputDialog("Entrez un nombre :");
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(""); // Case vide si le nombre est 0
} else {
buttons[row][col].setText(String.valueOf(num));
}
if (!isValid(num, row, col)) {
buttons[row][col].setForeground(Color.RED); // Met le texte en rouge en cas de mouvement invalide
} else {
buttons[row][col].setForeground(Color.BLACK); // Réinitialise la couleur du texte
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Veuillez entrer un nombre valide.");
2024-04-30 12:20:16 +02:00
}
2024-04-28 01:40:14 +02:00
}
}
private boolean isValid(int num, int row, int col) {
return isValidRow(num, row) && isValidCol(num, col) && isValidBox(num, row - row % 3, col - col % 3);
2024-04-28 01:40:14 +02:00
}
private boolean isValidRow(int num, int row) {
2024-04-28 01:40:14 +02:00
for (int i = 0; i < 9; i++) {
if (sudoku.getGrid().getCell(row, i).getValue() == num && i != col) {
2024-04-28 01:40:14 +02:00
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) {
2024-04-28 01:40:14 +02:00
return false;
}
}
return true;
}
private boolean isValidBox(int num, int boxStartRow, int boxStartCol) {
2024-04-28 01:40:14 +02:00
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)) {
2024-04-28 01:40:14 +02:00
return false;
}
}
}
return true;
}
}