I'm trying to write a checkers AI program with a GUI in java. I've managed to initialise and fill the board so far (with pieces written as "B" and "W" for now). I've created a 2D JButton panel for the board.
I don't know how to proceed when moving pieces. My current issue is I need the player to select a preexisting piece (action 1) and then an empty space to place the selected piece (action 2). Of course these actions are dependent, and I need action 1 to happen first.
Here's what I've got so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class Checkers implements ActionListener{
private static final int BOARD_SIZE = 8;
Random random = new Random();
JFrame frame = new JFrame();
JPanel title_panel = new JPanel();
JPanel button_panel = new JPanel();
JLabel textfield = new JLabel();
JButton[][] buttons = new JButton[BOARD_SIZE][BOARD_SIZE];
Checkers(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,800);
frame.getContentPane().setBackground(new Color(50, 50, 50));
frame.setLayout(new BorderLayout());
frame.setVisible(true);
textfield.setBackground(new Color(25,25,25));
textfield.setForeground(new Color(25, 255, 0));
textfield.setFont(new Font("Arial", Font.BOLD, 75));
textfield.setHorizontalAlignment(JLabel.CENTER);
textfield.setText("Checkers");
textfield.setOpaque(true);
title_panel.setLayout(new BorderLayout());
title_panel.setBounds(0,0,800, 100);
button_panel.setLayout(new GridLayout(BOARD_SIZE,BOARD_SIZE));
button_panel.setBackground(new Color(150,150,150));
for (int i=0; i<BOARD_SIZE; i++){
for (int j=0; j<BOARD_SIZE; j++){
buttons[i][j] = new JButton();
button_panel.add(buttons[i][j]);
buttons[i][j].setFont(new Font("Arial",Font.BOLD, 30));
buttons[i][j].setFocusable(false);
buttons[i][j].addActionListener(this);
}
}
title_panel.add(textfield);
frame.add(title_panel, BorderLayout.NORTH);
frame.add(button_panel);
initialiseBoard(buttons);
}
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (e.getSource() == buttons[i][j]) {
String moving_piece = buttons[i][j].getText();
}
}
}
}
// method that fills the initial board.
public void initialiseBoard(JButton[][] buttons){
for (int i=0; i<BOARD_SIZE; i++){
for (int j=0; j<BOARD_SIZE; j++){
if (i<3){
if (i%2==0){
if (j%2 != 0){
buttons[i][j].setText("W");
}
}
else {
if (j%2==0){
buttons[i][j].setText("W");
}
}
}
if (i>=BOARD_SIZE-3){
if (i%2 == 0){
if (j%2 != 0){
buttons[i][j].setText("B");
}
}
else {
if (j%2==0){
buttons[i][j].setText("B");
}
}
}
}
}
}
}
