Java五子棋游戏:带图形界面的简单实现
以下是一个简单的五子棋程序的Java代码,使用Swing库构建了图形界面:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Gobang extends JFrame {
private final int ROWS = 15;
private final int COLS = 15;
private final int CELL_SIZE = 40;
private final int WIDTH = COLS * CELL_SIZE;
private final int HEIGHT = ROWS * CELL_SIZE;
private int[][] board;
private boolean isBlackTurn;
public Gobang() {
setTitle('Gobang');
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
board = new int[ROWS][COLS];
isBlackTurn = true;
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
int x = col * CELL_SIZE;
int y = row * CELL_SIZE;
if (board[row][col] == 1) {
g.setColor(Color.BLACK);
g.fillOval(x, y, CELL_SIZE, CELL_SIZE);
} else if (board[row][col] == 2) {
g.setColor(Color.WHITE);
g.fillOval(x, y, CELL_SIZE, CELL_SIZE);
}
g.setColor(Color.BLACK);
g.drawRect(x, y, CELL_SIZE, CELL_SIZE);
}
}
}
};
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int x = e.getX() / CELL_SIZE;
int y = e.getY() / CELL_SIZE;
if (board[y][x] == 0) {
if (isBlackTurn) {
board[y][x] = 1;
} else {
board[y][x] = 2;
}
isBlackTurn = !isBlackTurn;
panel.repaint();
}
}
});
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Gobang();
}
}
运行以上代码,将会显示一个简单的五子棋界面。您可以通过鼠标点击来下棋,黑子和白子轮流下棋。
原文地址: https://www.cveoy.top/t/topic/fORR 著作权归作者所有。请勿转载和采集!