Skip to content

Commit 42a75b3

Browse files
Added Multi player chess using java
1 parent ec021c9 commit 42a75b3

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

multiplayerchess.java

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import javax.swing.*;
2+
import java.awt.*;
3+
import java.awt.event.ActionEvent;
4+
import java.awt.event.ActionListener;
5+
6+
public class ChessGame {
7+
private JFrame frame;
8+
private JButton[][] boardButtons;
9+
private String currentPlayer = "White";
10+
11+
public ChessGame() {
12+
frame = new JFrame("Multiplayer Chess Game");
13+
boardButtons = new JButton[8][8];
14+
frame.setLayout(new GridLayout(8, 8));
15+
initializeBoard();
16+
frame.setSize(600, 600);
17+
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18+
frame.setVisible(true);
19+
}
20+
21+
// Initialize the board with buttons
22+
private void initializeBoard() {
23+
for (int row = 0; row < 8; row++) {
24+
for (int col = 0; col < 8; col++) {
25+
JButton button = new JButton();
26+
button.setBackground((row + col) % 2 == 0 ? Color.WHITE : Color.GRAY);
27+
button.setOpaque(true);
28+
button.setBorderPainted(false);
29+
boardButtons[row][col] = button;
30+
button.addActionListener(new ButtonClickListener(row, col));
31+
frame.add(button);
32+
}
33+
}
34+
setupInitialPieces();
35+
}
36+
37+
// Set up the initial positions of the pieces
38+
private void setupInitialPieces() {
39+
// For simplicity, setting up only pawns. Add other pieces as needed.
40+
for (int col = 0; col < 8; col++) {
41+
boardButtons[1][col].setText("P"); // Black pawns
42+
boardButtons[6][col].setText("P"); // White pawns
43+
}
44+
// Add other pieces (King, Queen, Rook, Knight, Bishop) here
45+
}
46+
47+
// Handle button click events
48+
private class ButtonClickListener implements ActionListener {
49+
private int row;
50+
private int col;
51+
52+
public ButtonClickListener(int row, int col) {
53+
this.row = row;
54+
this.col = col;
55+
}
56+
57+
@Override
58+
public void actionPerformed(ActionEvent e) {
59+
JButton clickedButton = boardButtons[row][col];
60+
if (clickedButton.getText().isEmpty()) {
61+
System.out.println(currentPlayer + " clicked on an empty square at (" + row + ", " + col + ")");
62+
} else {
63+
System.out.println(currentPlayer + " clicked on a piece at (" + row + ", " + col + ")");
64+
}
65+
switchPlayer();
66+
}
67+
}
68+
69+
// Switch the current player
70+
private void switchPlayer() {
71+
currentPlayer = currentPlayer.equals("White") ? "Black" : "White";
72+
System.out.println("Current player: " + currentPlayer);
73+
}
74+
75+
public static void main(String[] args) {
76+
SwingUtilities.invokeLater(ChessGame::new);
77+
}
78+
}

0 commit comments

Comments
 (0)