连接4检查获胜算法 [英] Connect 4 Checking for a win algorithm

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

问题描述

我正在制作一个Connect 4游戏,并且我正在尝试检查获胜,到目前为止,我已经能够在游戏板上的任意位置对角线进行检查,现在我该如何对角线进行水平和垂直检查了?试图扭转方向检查对角左,但这没有用吗?我可以更改哪些以向左检查?水平和垂直

I am making a connect 4 game, and I am trying to check for a win, so far I have been able to check right diagonally anywhere on the game board, How do I now check diagonally left, horizontally and vertically, I tried reversing the direction to check on diagonally left but that did not work? What can I change to check towards the left? horizontal and vertical

//Column Size
private static final int COLS = 7; 
//Row Size
private static final int ROWS = 6; 
//Dynamic Array
private State [][]count = new State[COLS][ROWS];
//Length of Pattern to check FOUR counters in a row
public static final int LEN=4;


//trajectory
public State checkWinner() {
    for(int col=0; col<count.length;++col) {
        for(int row=0; row<count[col].length; ++row) {
            State result = checkWinner(col,row);
            if (result!=null) {
                return result;
            }
        }
    }
    return null;
}

public State checkWinner(int col, int row) {
    State cell = count[col][row];
    if (cell==null ||cell==State.BLANK) { return null; }

    // check Diagonally Right 
    if((col+LEN<=COLS) && (row+LEN<=ROWS)){
        boolean same = true;
        for(int i=1;i<LEN;++i) {
            if (count[col+i][row+i]!=cell) {
                same=false;
                break;                  
            }
        }
        if (same) {
            return cell;
        }   
    }
    return null;
}


推荐答案

您在checkWinner(int col,int row)仅检查三个位置;它应从i = 0而不是i = 1开始。要垂直检查,请使用count [col] [row + i],要水平检查,请使用count [col + i] [row]。反向检查时,请务必在循环之前修改if语句。

Your loop in checkWinner(int col, int row) is only checking three positions; it should start at i = 0 rather than i = 1. To check vertically use count[col][row+i], to check horizontally use count[col+i][row]. Be sure to modify the if statement prior to the loop when checking in the reverse direction.

这篇关于连接4检查获胜算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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