You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现Connect4二维数组水平/对角线连续4同色检测方案

Connect4 四连胜利检测实现方案

核心需求

实现Connect4游戏的完整胜利判定:对二维棋盘枚举数组的水平线、两个对角线方向做连续同色检测,判定是否存在至少4个连续同色元素;现有代码已完成垂直线检测逻辑,剩余方向实现优先使用Stream API。

项目现有定义与代码

  • 二维棋盘数组定义:
private Zelle[][] board = new Zelle[width][height];
  • 格子枚举类型定义:
public enum Zelle {
        RED("RED   "),
        YELLOW("YELLOW"),
        Empty("EMPTY ");
}
  • 已实现的垂直线检测方法isConnect4():
public void isConnect4(int col) {
    for (int i = 0; i < height; i++) {
        //vertical
        switch (board[col][i]) {
            case RED -> --counter;
            case YELLOW -> ++counter;
            case Empty -> counter = 0;
        }
    }
    if (Math.abs(counter) == 4  ) {
        System.out.println("Es liegt ein Gewinner vor");
        winner = true;
    }
}
  • 落子逻辑makeMove(int col),每次落子完成后会自动调用胜利检测方法:
public void makeMove(int col) {
    if (start && !winner && (IntStream.rangeClosed(0, 6).boxed().toList().contains(col))
            && board[col][0].equals(Zelle.Empty)) {
        board[col][IntStream.rangeClosed(0, 6).map(i -> 5 - i).
                filter(i -> board[col][i].equals(Zelle.Empty)).findFirst().getAsInt()] = currentPlayer();
        next();

        System.out.println(printBoard());
    } else if (!(board[col][0].equals(Zelle.Empty))) {
        System.out.println("You cannot move there, please pick another Column");
    } else if (!start){
        System.out.println("Game has not started yet");
    }
    else {
        System.out.println("Game Over! Winner is: " + currentplayer );
    }
    isConnect4(col);
}

初步实现思路

  • 水平方向检测:先定位本次落子的具体行列位置,向左右两侧各探查最多3格
  • 对角线方向检测:覆盖左上-右下、右上-左下两个对角线方向,即沿左上、左下、右上、右下四个方向延伸探查,初步伪代码如下:
// 四个检测方向:左上、左下、右上、右下
for(int i = 0; i <3; i++){
    switch (board[col+i][currentPosition]) {
        case RED -> --counter;
        case YELLOW -> ++counter;
        case Empty -> counter = 0;
    }
}

咨询诉求

给出该需求的最优实现方案,优先使用Stream API完成开发。

内容的提问来源于stack exchange,提问作者blumentopf111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 15:36:26