连接四个垂直赢家

时间:2015-06-08 23:02:39

标签: java

由于某些原因,当内部四个循环完成运行时,此方法不会在外部for循环中将col添加1。我只能在col设置为的列中获得垂直连接四。例如,如果col等于2,则计算机只能识别第2列中的垂直连接4。出了什么问题?

public Player colWinner(){
        for(int col = 0; col < grid[0].length; col++){
            for(int row = 0; row < grid.length/2; row++){
                Player currP = getCell(row,col);
                if((currP == getCell(row + 1, col)) && (currP == getCell(row + 2, col)) && (currP == getCell(row + 3, col))){ 
                    return currP;
                }
                else{
                    continue;
                }
            }
            for(int row = grid.length/2; row < grid.length; row++){
                Player currP = getCell(row,col);
                if((currP == getCell(row - 1, col)) && (currP == getCell(row - 2, col)) && (currP == getCell(row - 3, col))){ 
                    return currP;
                }
                else{
                    continue;
                }
            }
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

我认为您的代码允许4个垂直空序列。 每个if语句都需要添加currP != null

public Player colWinner(){
    for(int col = 0; col < grid[0].length; col++){
        for(int row = 0; row < grid.length/2; row++){
            Player currP = getCell(row,col);
            if(currP != null && currP == getCell(row + 1, col) && currP == getCell(row + 2, col) && currP == getCell(row + 3, col)){ 
                return currP;
            }
        }
        for(int row = grid.length/2; row < grid.length; row++){
            Player currP = getCell(row,col);
            if(currP != null && currP == getCell(row - 1, col) && currP == getCell(row - 2, col) && currP == getCell(row - 3, col)){ 
                return currP;
            }
        }
    }
    return null;
}