基於 Swing 的桌面五子棋實現,涵蓋棋盤繪製、鼠標交互、落子規則、勝負判定(橫豎斜四向連線)、重置功能。適合 Java GUI 入門練習。
MainFrame extends JFrame:主窗口,菜單欄、邊欄(顯示當前落子方)、中心棋盤。CanvasFrame extends JPanel:棋盤繪製組件,重寫 paint(Graphics g)。Point 列表分別記錄黑白棋座標。
public void paint(Graphics g) {
// 背景
g.setColor(Color.PINK);
g.fillRect(0, 0, size, size);
// 網格線
g.setColor(Color.BLACK);
for (int i = START; i <= HL; i += ONE) {
g.drawLine(i, START, i, HL); // 豎線
g.drawLine(START, i, HL, i); // 橫線
}
// 邊框
g.setColor(Color.YELLOW);
g.drawRect(START/2, START/2, HL+1, HL+1);
// 繪製棋子
g.setColor(Color.BLACK);
for (Point p : blackList) g.fillOval(p.x, p.y, 20, 25);
g.setColor(Color.WHITE);
for (Point p : whiteList) g.fillOval(p.x, p.y, 20, 25);
}
canvas.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
// 像素座標對齊到網格交叉點
int x = (e.getX() / ONE) * ONE;
int y = (e.getY() / ONE) * ONE;
Point p = new Point(x, y);
// 校驗:不可重複落子
if (blackList.contains(p) || whiteList.contains(p)) {
JOptionPane.showMessageDialog(null, "此處已有棋子");
return;
}
// 落子並判勝
if (isBlackTurn) blackList.add(p);
else whiteList.add(p);
if (checkWin(currentList)) {
JOptionPane.showMessageDialog(null, (isBlackTurn ? "黑方" : "白方") + "獲勝!");
resetGame();
}
isBlackTurn = !isBlackTurn;
canvas.repaint();
}
}
});
private boolean checkWin(List<Point> list) {
for (Point p : list) {
int x = p.x, y = p.y;
// 四個方向:橫(1,0)、豎(0,1)、主對角(1,1)、副對角(1,-1)
int[][] dirs = {{1,0}, {0,1}, {1,1}, {1,-1}};
for (int[] d : dirs) {
int count = 1;
// 正向
for (int i = 1; i < 5; i++) {
if (list.contains(new Point(x + i*d[0]*ONE, y + i*d[1]*ONE))) count++;
else break;
}
// 反向
for (int i = 1; i < 5; i++) {
if (list.contains(new Point(x - i*d[0]*ONE, y - i*d[1]*ONE))) count++;
else break;
}
if (count >= 5) return true;
}
}
return false;
}
此 Demo 代碼結構清晰,邏輯與視圖分離度尚可,是 Swing 事件驅動、自定義繪製、集合操作的綜合練習佳例。