Actualiser src/windowInterface/MyInterface.java

This commit is contained in:
Guillaume VALLENET 2025-04-25 16:31:03 +02:00
parent e3b81bf579
commit 98e5ce6346
1 changed files with 127 additions and 51 deletions

View File

@ -36,48 +36,62 @@ import javax.swing.JToggleButton;
import javax.swing.JRadioButton; import javax.swing.JRadioButton;
import javax.swing.JCheckBox; import javax.swing.JCheckBox;
/**
* This class creates the main window interface for a chess game.
* It handles the game display, controls, and timer functionality.
*/
public class MyInterface extends JFrame { public class MyInterface extends JFrame {
private static final long serialVersionUID = -6840815447618468846L; private static final long serialVersionUID = -6840815447618468846L;
// Main panel that holds all components
private JPanel contentPane; private JPanel contentPane;
private JLabel turnLabel; // Labels to show game information
private JLabel borderLabel; private JLabel turnLabel; // Shows whose turn it is
private JLabel speedLabel; private JLabel borderLabel; // Shows border information
private JLabel speedLabel; // Shows speed information
// The chess board drawing panel
private JPanelChessBoard panelDraw; private JPanelChessBoard panelDraw;
// The game logic handler
private Game game; private Game game;
// Label showing current action mode (playing, adding piece, etc.)
private JLabel actionLabel; private JLabel actionLabel;
// Checkboxes to enable AI players
private JCheckBox chckbxBlackAI; private JCheckBox chckbxBlackAI;
private JCheckBox chckbxWhiteAI; private JCheckBox chckbxWhiteAI;
// Timer-related components // Timer-related components
private JLabel whiteTimerLabel; private JLabel whiteTimerLabel; // Shows white player's remaining time
private JLabel blackTimerLabel; private JLabel blackTimerLabel; // Shows black player's remaining time
private JCheckBox chckbxEnableTimer; private JCheckBox chckbxEnableTimer; // Checkbox to turn timer on/off
private JSpinner timeSpinner; private JSpinner timeSpinner; // Sets the initial time amount
/** /**
* Create the frame. * Create the chess game window with all its components.
*/ */
public MyInterface() { public MyInterface() {
// Set up the main window properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(10, 10, 650, 650); setBounds(10, 10, 650, 650); // Set window position and size
contentPane = new JPanel(); contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0)); contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane); setContentPane(contentPane);
// Create top panel for game controls
JPanel panelTop = new JPanel(); JPanel panelTop = new JPanel();
contentPane.add(panelTop, BorderLayout.NORTH); contentPane.add(panelTop, BorderLayout.NORTH);
// Create right panel for additional controls
JPanel panelRight = new JPanel(); JPanel panelRight = new JPanel();
contentPane.add(panelRight, BorderLayout.EAST); contentPane.add(panelRight, BorderLayout.EAST);
panelRight.setLayout(new GridLayout(7, 1, 0, 5)); // Increased number of rows for timer controls panelRight.setLayout(new GridLayout(7, 1, 0, 5)); // 7 rows, 1 column layout
// Timer panel at the bottom // Create timer panel at the bottom
JPanel timerPanel = new JPanel(); JPanel timerPanel = new JPanel();
timerPanel.setLayout(new GridLayout(2, 2, 5, 5)); timerPanel.setLayout(new GridLayout(2, 2, 5, 5)); // 2 rows, 2 columns layout
contentPane.add(timerPanel, BorderLayout.SOUTH); contentPane.add(timerPanel, BorderLayout.SOUTH);
// White timer // Set up white player's timer display
JPanel whiteTimerPanel = new JPanel(); JPanel whiteTimerPanel = new JPanel();
whiteTimerLabel = new JLabel("10:00"); whiteTimerLabel = new JLabel("10:00");
whiteTimerLabel.setFont(new Font("Monospaced", Font.BOLD, 20)); whiteTimerLabel.setFont(new Font("Monospaced", Font.BOLD, 20));
@ -86,7 +100,7 @@ public class MyInterface extends JFrame {
whiteTimerPanel.add(whiteTimerLabel); whiteTimerPanel.add(whiteTimerLabel);
timerPanel.add(whiteTimerPanel); timerPanel.add(whiteTimerPanel);
// Black timer // Set up black player's timer display
JPanel blackTimerPanel = new JPanel(); JPanel blackTimerPanel = new JPanel();
blackTimerLabel = new JLabel("10:00"); blackTimerLabel = new JLabel("10:00");
blackTimerLabel.setFont(new Font("Monospaced", Font.BOLD, 20)); blackTimerLabel.setFont(new Font("Monospaced", Font.BOLD, 20));
@ -95,118 +109,140 @@ public class MyInterface extends JFrame {
blackTimerPanel.add(blackTimerLabel); blackTimerPanel.add(blackTimerLabel);
timerPanel.add(blackTimerPanel); timerPanel.add(blackTimerPanel);
// Timer controls // Create timer control panel with enable checkbox and time spinner
JPanel timerControls = new JPanel(); JPanel timerControls = new JPanel();
timerControls.setLayout(new FlowLayout()); timerControls.setLayout(new FlowLayout());
// Add checkbox to enable/disable timer
chckbxEnableTimer = new JCheckBox("Enable Timer"); chckbxEnableTimer = new JCheckBox("Enable Timer");
chckbxEnableTimer.addActionListener(new ActionListener() { chckbxEnableTimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
toggleTimer(); toggleTimer(); // Call method to turn timer on/off
} }
}); });
timerControls.add(chckbxEnableTimer); timerControls.add(chckbxEnableTimer);
// Add spinner to set timer minutes
timerControls.add(new JLabel("Minutes:")); timerControls.add(new JLabel("Minutes:"));
timeSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 60, 1)); timeSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 60, 1)); // Default 10 min, range 1-60
timeSpinner.addChangeListener(new ChangeListener() { timeSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) { public void stateChanged(ChangeEvent e) {
updateInitialTime(); updateInitialTime(); // Call method when time value changes
} }
}); });
timerControls.add(timeSpinner); timerControls.add(timeSpinner);
timerPanel.add(timerControls); timerPanel.add(timerControls);
// Create label to show current game action status
actionLabel = new JLabel("Waiting For Start"); actionLabel = new JLabel("Waiting For Start");
panelTop.add(actionLabel); panelTop.add(actionLabel);
// Create start/restart button
JButton btnGo = new JButton("Start/Restart"); JButton btnGo = new JButton("Start/Restart");
btnGo.addActionListener(new ActionListener() { btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicButtonStart(); clicButtonStart(); // Call method when button is clicked
} }
}); });
panelTop.add(btnGo); panelTop.add(btnGo);
// Create turn indicator label
turnLabel = new JLabel("Turn : X"); turnLabel = new JLabel("Turn : X");
panelTop.add(turnLabel); panelTop.add(turnLabel);
// Create load game button
JButton btnLoad = new JButton("Load File"); JButton btnLoad = new JButton("Load File");
btnLoad.addActionListener(new ActionListener() { btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicLoadFileButton(); clicLoadFileButton(); // Call method when button is clicked
} }
}); });
panelRight.add(btnLoad); panelRight.add(btnLoad);
// Create save game button
JButton btnSave = new JButton("Save To File"); JButton btnSave = new JButton("Save To File");
btnSave.addActionListener(new ActionListener() { btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicSaveToFileButton(); clicSaveToFileButton(); // Call method when button is clicked
} }
}); });
panelRight.add(btnSave); panelRight.add(btnSave);
// Create button to add pieces manually
JButton btnAdder = new JButton("Add Piece"); JButton btnAdder = new JButton("Add Piece");
btnAdder.addActionListener(new ActionListener() { btnAdder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clickButtonAdder(); clickButtonAdder(); // Call method when button is clicked
} }
}); });
panelRight.add(btnAdder); panelRight.add(btnAdder);
// Create button to select piece type when adding
JButton btnPieceSelector = new JButton("Piece Select"); JButton btnPieceSelector = new JButton("Piece Select");
btnPieceSelector.addActionListener(new ActionListener() { btnPieceSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clickButtonSelector(); clickButtonSelector(); // Call method when button is clicked
} }
}); });
panelRight.add(btnPieceSelector); panelRight.add(btnPieceSelector);
// Create undo move button
JButton btnUndo = new JButton("Undo"); JButton btnUndo = new JButton("Undo");
btnUndo.addActionListener(new ActionListener() { btnUndo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicUndoButton(); clicUndoButton(); // Call method when button is clicked
} }
}); });
panelTop.add(btnUndo); panelTop.add(btnUndo);
// Create checkbox to enable AI for white player
chckbxWhiteAI = new JCheckBox("WhiteAI"); chckbxWhiteAI = new JCheckBox("WhiteAI");
chckbxWhiteAI.addActionListener(new ActionListener() { chckbxWhiteAI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicAIToggle(true); clicAIToggle(true); // Call method with true for white
} }
}); });
panelTop.add(chckbxWhiteAI); panelTop.add(chckbxWhiteAI);
// Create checkbox to enable AI for black player
chckbxBlackAI = new JCheckBox("BlackAI"); chckbxBlackAI = new JCheckBox("BlackAI");
chckbxBlackAI.addActionListener(new ActionListener() { chckbxBlackAI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { public void actionPerformed(ActionEvent arg0) {
clicAIToggle(false); clicAIToggle(false); // Call method with false for black
} }
}); });
panelTop.add(chckbxBlackAI); panelTop.add(chckbxBlackAI);
// Create and add the chess board panel
panelDraw = new JPanelChessBoard(this); panelDraw = new JPanelChessBoard(this);
contentPane.add(panelDraw, BorderLayout.CENTER); contentPane.add(panelDraw, BorderLayout.CENTER);
} }
/**
* Update the turn display label
*/
public void setStepBanner(String s) { public void setStepBanner(String s) {
turnLabel.setText(s); turnLabel.setText(s);
} }
/**
* Update the border information label
*/
public void setBorderBanner(String s) { public void setBorderBanner(String s) {
borderLabel.setText(s); borderLabel.setText(s);
} }
/**
* Get the chess board panel
*/
public JPanelChessBoard getPanelDessin() { public JPanelChessBoard getPanelDessin() {
return panelDraw; return panelDraw;
} }
/**
* Create a new game if none exists
*/
public void instantiateSimu() { public void instantiateSimu() {
if(game==null) { if(game==null) {
game = new Game(this); game = new Game(this);
@ -215,23 +251,36 @@ public class MyInterface extends JFrame {
} }
} }
/**
* Start or restart the game with default piece setup
*/
public void clicButtonStart() { public void clicButtonStart() {
this.instantiateSimu(); this.instantiateSimu();
game.setDefaultSetup(); game.setDefaultSetup();
// Reset and start the timer if enabled // Start the timer if it's enabled
if (game.isTimerEnabled()) { if (game.isTimerEnabled()) {
game.startTimer(); game.startTimer();
} }
} }
/**
* Switch to piece adding mode
*/
public void clickButtonAdder() { public void clickButtonAdder() {
panelDraw.toggleAdderMode(); panelDraw.toggleAdderMode();
} }
/**
* Switch to piece selection mode
*/
public void clickButtonSelector() { public void clickButtonSelector() {
panelDraw.togglePieceSelector(); panelDraw.togglePieceSelector();
} }
/**
* Undo the last move
*/
private void clicUndoButton() { private void clicUndoButton() {
if(game == null) { if(game == null) {
System.out.println("error : can't undo while no game present"); System.out.println("error : can't undo while no game present");
@ -240,6 +289,9 @@ public class MyInterface extends JFrame {
} }
} }
/**
* Turn AI on or off for a player
*/
public void clicAIToggle(boolean isWhite) { public void clicAIToggle(boolean isWhite) {
if(game == null) { if(game == null) {
System.out.println("error : can't activate AI while no game present"); System.out.println("error : can't activate AI while no game present");
@ -254,7 +306,7 @@ public class MyInterface extends JFrame {
} }
/** /**
* Toggle timer on/off * Turn the chess timer on or off
*/ */
private void toggleTimer() { private void toggleTimer() {
if (game == null) { if (game == null) {
@ -265,11 +317,11 @@ public class MyInterface extends JFrame {
game.setTimerEnabled(isEnabled); game.setTimerEnabled(isEnabled);
if (isEnabled) { if (isEnabled) {
game.startTimer(); game.startTimer(); // Start the timer
} else { } else {
game.stopTimer(); game.stopTimer(); // Stop the timer
// Reset the displayed time // Reset the displayed time to initial value
updateTimers( updateTimers(
((Integer)timeSpinner.getValue()) * 60 * 1000, ((Integer)timeSpinner.getValue()) * 60 * 1000,
((Integer)timeSpinner.getValue()) * 60 * 1000 ((Integer)timeSpinner.getValue()) * 60 * 1000
@ -279,22 +331,22 @@ public class MyInterface extends JFrame {
} }
/** /**
* Update initial time when spinner changes * Update the initial time when spinner value changes
*/ */
private void updateInitialTime() { private void updateInitialTime() {
if (game != null) { if (game != null) {
int minutes = (Integer)timeSpinner.getValue(); int minutes = (Integer)timeSpinner.getValue();
game.setInitialTime(minutes); game.setInitialTime(minutes);
// Update timer labels // Update timer display labels
long timeMillis = minutes * 60 * 1000; long timeMillis = minutes * 60 * 1000; // Convert to milliseconds
whiteTimerLabel.setText(ChessTimer.formatTime(timeMillis)); whiteTimerLabel.setText(ChessTimer.formatTime(timeMillis));
blackTimerLabel.setText(ChessTimer.formatTime(timeMillis)); blackTimerLabel.setText(ChessTimer.formatTime(timeMillis));
} }
} }
/** /**
* Update timer display * Update both timer displays with current times
*/ */
public void updateTimers(long whiteTimeMillis, long blackTimeMillis) { public void updateTimers(long whiteTimeMillis, long blackTimeMillis) {
whiteTimerLabel.setText(ChessTimer.formatTime(whiteTimeMillis)); whiteTimerLabel.setText(ChessTimer.formatTime(whiteTimeMillis));
@ -302,7 +354,7 @@ public class MyInterface extends JFrame {
} }
/** /**
* Handle time expiration * Show message when a player runs out of time
*/ */
public void timeExpired(boolean isWhiteExpired) { public void timeExpired(boolean isWhiteExpired) {
String message = (isWhiteExpired ? "White" : "Black") + " player's time has expired. " + String message = (isWhiteExpired ? "White" : "Black") + " player's time has expired. " +
@ -310,12 +362,16 @@ public class MyInterface extends JFrame {
JOptionPane.showMessageDialog(this, message, "Game Over", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(this, message, "Game Over", JOptionPane.INFORMATION_MESSAGE);
} }
/**
* Load a game from a file
*/
public void clicLoadFileButton() { public void clicLoadFileButton() {
Game loadedSim = new Game(this); Game loadedSim = new Game(this);
String fileName=SelectFile(); String fileName = SelectFile(); // Open file chooser dialog
LinkedList<String> lines = new LinkedList<String>(); LinkedList<String> lines = new LinkedList<String>();
if (fileName.length()>0) { if (fileName.length() > 0) {
try { try {
// Read all lines from the file
BufferedReader fileContent = new BufferedReader(new FileReader(fileName)); BufferedReader fileContent = new BufferedReader(new FileReader(fileName));
String line = fileContent.readLine(); String line = fileContent.readLine();
int colorID = 0; int colorID = 0;
@ -323,6 +379,7 @@ public class MyInterface extends JFrame {
lines.add(line); lines.add(line);
line = fileContent.readLine(); line = fileContent.readLine();
} }
// Set up the board with the file content
loadedSim.setBoard(Arrays.stream(lines.toArray()).map(Object::toString).toArray(String[]::new)); loadedSim.setBoard(Arrays.stream(lines.toArray()).map(Object::toString).toArray(String[]::new));
fileContent.close(); fileContent.close();
} catch (Exception e) { } catch (Exception e) {
@ -330,18 +387,24 @@ public class MyInterface extends JFrame {
} }
game = loadedSim; game = loadedSim;
panelDraw.setGame(game); panelDraw.setGame(game);
this.repaint(); this.repaint(); // Redraw the board
} }
} }
/**
* Save the current game to a file
*/
public void clicSaveToFileButton() { public void clicSaveToFileButton() {
String fileName=SelectFile(); String fileName = SelectFile(); // Open file chooser dialog
if (fileName.length()>0) { if (fileName.length() > 0) {
String[] content = game.getFileRepresentation(); String[] content = game.getFileRepresentation();
writeFile(fileName, content); writeFile(fileName, content); // Write game data to file
} }
} }
/**
* Open a file chooser dialog and return the selected file path
*/
public String SelectFile() { public String SelectFile() {
String s; String s;
JFileChooser chooser = new JFileChooser(); JFileChooser chooser = new JFileChooser();
@ -350,14 +413,17 @@ public class MyInterface extends JFrame {
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true); chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
s=chooser.getSelectedFile().toString(); s = chooser.getSelectedFile().toString();
} else { } else {
System.out.println("No Selection "); System.out.println("No Selection ");
s=""; s = "";
} }
return s; return s;
} }
/**
* Write string array to a file
*/
public void writeFile(String fileName, String[] content) { public void writeFile(String fileName, String[] content) {
FileWriter csvWriter; FileWriter csvWriter;
try { try {
@ -373,14 +439,24 @@ public class MyInterface extends JFrame {
} }
} }
/**
* Update the display with current game information
*/
public void update(int turnCount, boolean turnIsWhite) { public void update(int turnCount, boolean turnIsWhite) {
turnLabel.setText("Turn : "+turnCount+", "+ (turnIsWhite?"White":"Black")); // Update turn information
actionLabel.setText(panelDraw.isPieceAdderMode()?"Adding Piece": turnLabel.setText("Turn : " + turnCount + ", " + (turnIsWhite ? "White" : "Black"));
(panelDraw.isPieceSelectorMode()?"Selecting Piece to Add":
// Update action mode information
actionLabel.setText(panelDraw.isPieceAdderMode() ? "Adding Piece" :
(panelDraw.isPieceSelectorMode() ? "Selecting Piece to Add" :
"Playing")); "Playing"));
this.repaint();
this.repaint(); // Redraw the window
} }
/**
* Clear all information labels
*/
public void eraseLabels() { public void eraseLabels() {
this.setStepBanner("Turn : X"); this.setStepBanner("Turn : X");
} }