请完成一个五子棋的java代码
时间: 2024-03-06 09:47:59 浏览: 62
以下是一个简单的五子棋 Java 代码,使用了 Swing 图形库实现了 GUI 界面:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Gobang extends JFrame {
private static final long serialVersionUID = 1L;
private int ROWS = 15;
private int COLS = 15;
private int CELL_SIZE = 30;
private int[][] board = new int[ROWS][COLS];
private boolean isBlack = true;
public static void main(String[] args) {
Gobang game = new Gobang();
game.init();
}
public void init() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
GobangBoard boardPanel = new GobangBoard();
mainPanel.add(boardPanel, BorderLayout.CENTER);
this.setContentPane(mainPanel);
this.setTitle("五子棋");
this.setSize(ROWS * CELL_SIZE, COLS * CELL_SIZE);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class GobangBoard extends JPanel {
private static final long serialVersionUID = 1L;
public GobangBoard() {
addMouseListener(new GobangListener());
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, ROWS * CELL_SIZE, COLS * CELL_SIZE);
g.setColor(Color.BLACK);
for (int i = 0; i < ROWS; i++) {
g.drawLine(0, i * CELL_SIZE, ROWS * CELL_SIZE, i * CELL_SIZE);
}
for (int i = 0; i < COLS; i++) {
g.drawLine(i * CELL_SIZE, 0, i * CELL_SIZE, COLS * CELL_SIZE);
}
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] == 1) {
g.setColor(Color.BLACK);
g.fillOval(i * CELL_SIZE + 2, j * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4);
} else if (board[i][j] == 2) {
g.setColor(Color.WHITE);
g.fillOval(i * CELL_SIZE + 2, j * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4);
}
}
}
}
class GobangListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
int x = e.getX() / CELL_SIZE;
int y = e.getY() / CELL_SIZE;
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
return;
}
if (board[x][y] != 0) {
return;
}
board[x][y] = isBlack ? 1 : 2;
isBlack = !isBlack;
repaint();
}
}
}
}
```
这个程序包含一个 `Gobang` 类和一个 `GobangBoard` 类。`Gobang` 类负责初始化界面,包括设置标题、大小、关闭操作等;`GobangBoard` 类继承自 `JPanel`,负责绘制棋盘和处理用户的鼠标事件。在 `GobangBoard` 类中,`paint` 方法用于绘制棋盘和棋子,`GobangListener` 类用于处理用户的鼠标点击事件。
阅读全文