用java编写一个五子棋的游戏
时间: 2024-04-29 14:22:36 浏览: 59
写一个五子棋游戏需要考虑以下几个方面:
1. 游戏界面:需要使用图形界面(GUI)来展示棋盘,并实现玩家下棋的功能。
2. 游戏逻辑:需要实现五子棋的规则,判断谁获胜。
3. 游戏数据:需要储存棋盘上每个点的状态,以及记录玩家下棋的步数。
下面是一份简单的五子棋代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gobang extends JFrame {
private static final long serialVersionUID = 1L;
private int width = 15;
private int height = 15;
private int blockSize = 30;
private JButton[][] chessBoard;
private boolean isBlack = true;
public Gobang() {
chessBoard = new JButton[height][width];
Container container = getContentPane();
container.setLayout(new GridLayout(height, width));
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
chessBoard[i][j] = new JButton();
chessBoard[i][j].setSize(blockSize, blockSize);
chessBoard[i][j].addActionListener(new ChessAction(i, j));
container.add(chessBoard[i][j]);
}
}
setSize(blockSize * width, blockSize * height);
setTitle("五子棋");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
private class ChessAction implements ActionListener {
private int x;
private int y;
public ChessAction(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.getText().length() == 0) {
if (isBlack) {
button.setText("●");
} else {
button.setText("○");
}
isBlack = !isBlack;
button.setEnabled(false);
}
}
}
public static void main(String[] args) {
阅读全文