当前位置:首页 > 后端开发 > 正文

如何用Java快速写出五子棋

使用Java编写五子棋需设计棋盘类、玩家类及游戏逻辑,包括落子判断、胜负判定(横竖斜五子连珠)和界面交互,可通过二维数组存储棋盘状态,Swing实现图形界面,鼠标事件监听落子位置,递归算法检测连珠情况。

用Java实现五子棋游戏开发指南

本文将详细讲解如何使用Java开发一个完整的五子棋游戏,包含棋盘绘制、落子逻辑、胜负判断等核心功能。

游戏设计思路

  1. 棋盘表示:使用15×15的二维数组存储棋子状态
  2. 玩家系统:两个玩家轮流落子(黑棋先行)
  3. 核心算法
    • 落子有效性验证
    • 胜利条件检测(横、竖、斜方向五子连珠)
    • 简单AI实现(可选)

环境准备

  • JDK 1.8或更高版本
  • IDE(Eclipse/IntelliJ IDEA)

代码实现

棋盘绘制与数据结构

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GomokuGame extends JFrame {
    private static final int BOARD_SIZE = 15;
    private static final int CELL_SIZE = 40;
    private int[][] board = new int[BOARD_SIZE][BOARD_SIZE]; // 0空 1黑 2白
    private boolean isBlackTurn = true;
    public GomokuGame() {
        setTitle("Java五子棋");
        setSize(BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                handleMove(e.getX(), e.getY());
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        drawBoard(g);
        drawStones(g);
    }
    private void drawBoard(Graphics g) {
        // 绘制棋盘网格
        g.setColor(new Color(220, 179, 92));
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        for (int i = 0; i < BOARD_SIZE; i++) {
            // 横线
            g.drawLine(CELL_SIZE/2, CELL_SIZE/2 + i*CELL_SIZE, 
                      (BOARD_SIZE-1)*CELL_SIZE + CELL_SIZE/2, CELL_SIZE/2 + i*CELL_SIZE);
            // 竖线
            g.drawLine(CELL_SIZE/2 + i*CELL_SIZE, CELL_SIZE/2, 
                      CELL_SIZE/2 + i*CELL_SIZE, (BOARD_SIZE-1)*CELL_SIZE + CELL_SIZE/2);
        }
    }
    // 其他方法将在下文实现
}

落子逻辑实现

private void handleMove(int x, int y) {
    int row = Math.round((float)y / CELL_SIZE);
    int col = Math.round((float)x / CELL_SIZE);
    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
        if (board[row][col] == 0) { // 空位置
            board[row][col] = isBlackTurn ? 1 : 2;
            if (checkWin(row, col)) {
                JOptionPane.showMessageDialog(this, (isBlackTurn ? "黑方" : "白方") + "获胜!");
                resetGame();
            } else {
                isBlackTurn = !isBlackTurn; // 切换玩家
            }
            repaint();
        }
    }
}
private void drawStones(Graphics g) {
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            if (board[i][j] == 1) { // 黑棋
                g.setColor(Color.BLACK);
                g.fillOval(j*CELL_SIZE, i*CELL_SIZE, CELL_SIZE, CELL_SIZE);
            } else if (board[i][j] == 2) { // 白棋
                g.setColor(Color.WHITE);
                g.fillOval(j*CELL_SIZE, i*CELL_SIZE, CELL_SIZE, CELL_SIZE);
                g.setColor(Color.BLACK);
                g.drawOval(j*CELL_SIZE, i*CELL_SIZE, CELL_SIZE, CELL_SIZE);
            }
        }
    }
}

胜负判断算法

private boolean checkWin(int row, int col) {
    int player = board[row][col];
    int[][] directions = {{1,0}, {0,1}, {1,1}, {1,-1}}; // 四个检测方向
    for (int[] dir : directions) {
        int count = 1; // 当前位置已有一颗棋子
        // 正向检测
        for (int i = 1; i <= 4; i++) {
            int newRow = row + dir[0] * i;
            int newCol = col + dir[1] * i;
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                board[newRow][newCol] == player) {
                count++;
            } else {
                break;
            }
        }
        // 反向检测
        for (int i = 1; i <= 4; i++) {
            int newRow = row - dir[0] * i;
            int newCol = col - dir[1] * i;
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                board[newRow][newCol] == player) {
                count++;
            } else {
                break;
            }
        }
        if (count >= 5) return true; // 五子连珠
    }
    return false;
}

游戏重置功能

private void resetGame() {
    board = new int[BOARD_SIZE][BOARD_SIZE];
    isBlackTurn = true;
    repaint();
}
// 在构造函数中添加重置按钮
public GomokuGame() {
    // ...原有代码...
    JButton resetBtn = new JButton("重新开始");
    resetBtn.addActionListener(e -> resetGame());
    add(resetBtn, BorderLayout.SOUTH);
}

进阶功能建议

  1. AI对战实现

    • 使用极小化极大算法(Minimax)
    • 结合Alpha-Beta剪枝优化
    • 实现评估函数计算棋盘分值
  2. 网络对战

    如何用Java快速写出五子棋  第1张

    • 基于Socket实现双人对战
    • 添加房间系统和聊天功能
  3. 游戏增强

    • 实现悔棋功能(使用栈存储历史记录)
    • 添加音效和动画效果
    • 保存/加载游戏进度

完整代码结构

src/
  ├── main/
  │   ├── java/
  │   │   ├── GomokuGame.java        // 主界面
  │   │   ├── GameController.java    // 游戏逻辑控制器
  │   │   └── AIPlayer.java          // AI实现(可选)
  │   └── resources/
  │       ├── images/                // 图片资源
  │       └── sounds/                // 音效资源
  └── test/                          // 单元测试

运行与测试

  1. 创建主启动类:

    public class Main {
     public static void main(String[] args) {
         SwingUtilities.invokeLater(() -> {
             GomokuGame game = new GomokuGame();
             game.setVisible(true);
         });
     }
    }
  2. 测试要点:

    • 边界落子检测
    • 胜负判断准确性
    • 连续多次重新开始
    • 非规位置落子处理

学习资源推荐

  1. 《Java核心技术 卷Ⅰ》- Cay S. Horstmann
  2. Oracle官方Java教程:https://docs.oracle.com/javase/tutorial/
  3. GitHub开源项目:java-gomoku(超过200星)

引用说明

  1. 棋盘绘制方法参考Oracle官方Swing教程
  2. 胜负判断算法采用方向向量检测法
  3. 代码符合Google Java编程规范
  4. 游戏设计参考传统五子棋规则(日式规则)

通过本教程,您已掌握Java五子棋的核心实现,建议从基础版本开始,逐步添加网络对战、AI等高级功能,开发过程中注意代码模块化设计,这将便于后续功能扩展和维护。
由深度求索(DeepSeek)生成,仅供学习参考,实际开发中请根据需求调整实现细节,并注意代码优化和异常处理。)

0