首页 > 解决方案 > How should I implement a horizontal win algorithm for my Connect 4 program?

问题描述

I am making a connect 4 board game and I implemented this horizontal win algorithm. It doesn't seem to work for some reason. Based on the code I assumed the conditions I set in the algorithm would look over the values assigned to the array in generateBoard method but it did not.

What could a possible solution be? Any help is appreciated.

public static String[][] generateBoard(){
        String[][] board = new String[6][7]; //[row][column] 6 by 7
        for(int i = 0; i<board.length; i++) {
            for(int j = 0; j<board[i].length; j++) {
                if(j == 0) 
                    board[i][j] = "| |";
                else
                    board[i][j] = " |";
            }
        }
        return board;   
    }

Horizontal Win Algorithm:

        //Checks to see which player's turn it is
        String color = (redPlayerTurn) ? "R" : "Y";


        int pattern = 0; //Used as a flag for detecting a winner

        //HORIZONTAL Check
        for(int i = 1; i < board.length; i++) {
            String columnIndex = board[i][0];
            pattern = 1;
            for(int j = 1; j < board[i].length; j++) {
                if(!(board[i][j].contains("| |") || board[i][j].contains(" |"))) {
                    if(columnIndex == board[j][i] && pattern != 0)
                    pattern++;
                }else
                    columnIndex = board[i][j];
                    pattern = 0;
            }if(pattern == 4) {
                return true;
            }

        }

This is the result I keep getting: Result

标签: java

解决方案


//Checks to see which player's turn it is
String color = (redPlayerTurn) ? "R" : "Y";

int pattern = 0; //Used as a flag for detecting a winner

//HORIZONTAL Check
for(int i = 1; i < board.length; i++) {
    String columnIndex = board[i][0];
    pattern = 1;
    for(int j = 1; j < board[i].length; j++) {
       if(!board[i][j].contains("|")) {
          if(columnIndex == board[j][i] && pattern != 0) {
            pattern++;
          } else {
            columnIndex = board[i][j];
            pattern = 0; // <- missing {} will assign pattern to 0
          }
       }
    }
    if(pattern >= 4) {
       return true;
    }
}

推荐阅读