Connect 4算法抛出异常 [英] Exception being thrown for connect 4 algorithm

查看:91
本文介绍了Connect 4算法抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在检查代码是否垂直存在连接4方面遇到问题.我的代码的序言:董事会有6行7列,变量player1保留用作芯片的字符的值,而playerID仅保留获得连接4的人的值.

So I keep running into a problem with my code for checking if there is a connect 4 vertically. Preface to my code: the board has 6 rows and 7 columns, the variable player1 holds the value of the character being used as a chip and playerID just holds the value of whoever gets the connect 4.

public int verticalWin() {
    int playerID = 0;

    for (int x = 0; x < board[x].length; x++) {
        int count = 1;
        for (int y = board.length-2; y >= 0; y--) {
            if (board[y][x] == board[y+1][x]) {
                count++;
                if (count == 4) {
                    if (board[y][x] == player1) {
                        playerID = 1;
                    } else {
                        playerID = 2;
                    }
                }
            } else {
                count = 1;
            }
        }
    }
    return playerID;
}

我一直遇到的问题是java.lang.ArrayIndexOutOfBoundsException: 6一直在发生,我认为它在第一行,但是我似乎找不到问题.

The problem I keep running into is that an exception java.lang.ArrayIndexOutOfBoundsException: 6 keeps happening and I think it's in the first line, but I can't seem to find the problem.

推荐答案

一些更简洁的代码

boolean isWinnerOnColumn(int playerID, int column) {
    int count = 0;

    for (int row = 0; row < 6; row++) {
        count = (board[row][column] == playerID) ? (count + 1) : 0;
        if (count == 4){
            return true;
        }
    }
    return false;
}

public int verticalWin() {
     for (int column = 0; column < 7; column++) {

         if (isWinnerOnColumn(1, column) {
            return 1;
         }

         if (isWinnerOnColumn(2, column) {
            return 2;
         }
     }
     return 0; // no winner
}

这篇关于Connect 4算法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆