帮我写一个五子棋的Java代码,包含换背景的功能
时间: 2023-08-28 11:16:04 浏览: 83
五子棋的Java代码
好的,以下是一个简单的五子棋的Java代码示例,包含了换背景的功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gobang extends JFrame implements ActionListener {
private JButton[][] board; // 棋盘
private int[][] gameState; // 游戏状态数组
private int currentPlayer; // 当前玩家,1为黑,2为白
private ImageIcon blackIcon; // 黑棋图片
private ImageIcon whiteIcon; // 白棋图片
private JMenuBar menuBar; // 菜单栏
private JMenu menu; // 菜单
private JMenuItem item; // 菜单项
private JRadioButtonMenuItem[] rbItems; // 单选按钮菜单项
private ButtonGroup bg; // 单选按钮组
public Gobang() {
setTitle("五子棋");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setResizable(false);
// 初始化棋盘
board = new JButton[15][15];
gameState = new int[15][15];
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = new JButton();
board[i][j].setPreferredSize(new Dimension(30, 30));
board[i][j].addActionListener(this);
gameState[i][j] = 0;
}
}
// 初始化图片
blackIcon = new ImageIcon("black.png");
whiteIcon = new ImageIcon("white.png");
// 初始化菜单
menuBar = new JMenuBar();
menu = new JMenu("背景颜色");
rbItems = new JRadioButtonMenuItem[3];
rbItems[0] = new JRadioButtonMenuItem("蓝色", true);
rbItems[1] = new JRadioButtonMenuItem("绿色");
rbItems[2] = new JRadioButtonMenuItem("红色");
bg = new ButtonGroup();
for (int i = 0; i < 3; i++) {
rbItems[i].addActionListener(this);
bg.add(rbItems[i]);
menu.add(rbItems[i]);
}
menuBar.add(menu);
setJMenuBar(menuBar);
// 添加组件
JPanel panel = new JPanel(new GridLayout(15, 15));
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
panel.add(board[i][j]);
}
}
add(panel);
// 初始化玩家
currentPlayer = 1;
}
// 处理按钮点击事件
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (e.getSource() == board[i][j]) {
if (gameState[i][j] == 0) {
if (currentPlayer == 1) {
board[i][j].setIcon(blackIcon);
gameState[i][j] = 1;
currentPlayer = 2;
} else {
board[i][j].setIcon(whiteIcon);
gameState[i][j] = 2;
currentPlayer = 1;
}
}
}
}
}
// 处理菜单点击事件
for (int i = 0; i < 3; i++) {
if (e.getSource() == rbItems[i]) {
switch (i) {
case 0:
getContentPane().setBackground(Color.BLUE);
break;
case 1:
getContentPane().setBackground(Color.GREEN);
break;
case 2:
getContentPane().setBackground(Color.RED);
break;
}
}
}
}
public static void main(String[] args) {
Gobang game = new Gobang();
game.setVisible(true);
}
}
```
这个示例中,我们使用了Java的Swing框架来创建GUI界面,实现了一个简单的五子棋游戏,同时还添加了一个菜单栏,包含了一个单选按钮菜单项,可以切换背景颜色。你可以根据自己的需求修改代码来实现更丰富的功能。
阅读全文