SAE21_2023/SudokuButtonListener.java

73 lines
2.4 KiB
Java

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 Grid grid;
private JButton[][] buttons;
public SudokuButtonListener(int row, int col, Grid grid, JButton[][] buttons) {
this.row = row;
this.col = col;
this.grid = grid;
this.buttons = buttons;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
grid.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 (grid.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 (grid.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 (grid.getCell(row, col).getValue() == num && (row != this.row || col != this.col)) {
return false;
}
}
}
return true;
}
}