五子棋AI算法简易实现(一)

基础篇


(1)胜负判定

五子棋的胜负判定的条件是其中一方下棋以后,横线、竖线、右上斜线或者右下斜线任一方向出现五子相连,即可判定获胜。此处用递归方法即可实现。

var is_win = false;

var ModuleWinnerCheck = {

    checkWinner: function(color, num) {
        var col = num % 15;
        var row = (num-col) / 15;
        map[row][col] = color;

        var count = 1;
        is_win = this._checkControl(row, col, color);
        if(is_win)
            return -1;
        else
            return num;
    },

    _checkControl: function(row, col, color) {
        //递归后当前位置的下子会重复计数,因此结果要减1
        if(this._checkWinnerScan(row, col, color, 0) + this._checkWinnerScan(row, col, color, 4) - 1 < 5)
            if(this._checkWinnerScan(row, col, color, 1) + this._checkWinnerScan(row, col, color, 5) - 1 < 5)
                if(this._checkWinnerScan(row, col, color, 2) + this._checkWinnerScan(row, col, color, 6) - 1 < 5)
                    if(this._checkWinnerScan(row, col, color, 3) + this._checkWinnerScan(row, col, color, 7) - 1 < 5)
                        return false;
        return true;
    },

    _checkWinnerScan: function(row, col, color, state) {
        //数组越界或者连子中断时,结束递归
        if(row < 0 || row > 14 || col < 0 || col > 14 || map[row][col] != color){
            return 0;
        }
        else if(!is_win && state == 0){
            return 1 + this._checkWinnerScan(row-1, col, color, 0);
        }
        else if(!is_win && state == 1){
            return 1 + this._checkWinnerScan(row-1, col+1, color, 1);
        }
        else if(!is_win && state == 2){
            return 1 + this._checkWinnerScan(row, col+1, color, 2);
        }
        else if(!is_win && state == 3){
            return 1 + this._checkWinnerScan(row+1, col+1, color, 3);
        }
        else if(!is_win && state == 4){
            return 1 + this._checkWinnerScan(row+1, col, color, 4);
        }
        else if(!is_win && state == 5){
            return 1 + this._checkWinnerScan(row+1, col-1, color, 5);
        }
        else if(!is_win && state == 6){
            return 1 + this._checkWinnerScan(row, col-1, color, 6);
        }
        else if(!is_win && state == 7){
            return 1 + this._checkWinnerScan(row-1, col-1, color, 7);
        }
        else{
            return 0;
        }
    }
};

用途解析

五子棋的棋盘大小为 15 * 15,因此我们使用一个 15 * 15 大小的二维数组即可将其表现出来
以上这段代码就是利用递归的方式在记录下子位置的棋盘上进行胜负的判定

函数说明

checkWinner(color, num)

传入的两个参数分别代表当前棋手所持的颜色(color)和当前下棋的位置的编号(num){范围是:0-255}

_checkControl(row, col, color)

传入的三个参数分别代表num经过处理后得到的在二维数组中的当前位置(row:行;col:列)以及当前棋手所持的颜色(color)

_checkWinnerScan(row, col, color, state)

前三个参数与上面的参数意义相同,最后一个参数是当前递归搜索的模式(state:0-7),表示从竖直往上开始顺时针旋转的八个方向,即 ↑(0),↗(1),→(2),↘(3),↓(4),↙(5),←(6),↖(7)

项目地址:https://github.com/huangzhutao/Gomoku.git

猜你喜欢

转载自blog.csdn.net/think_a_lot/article/details/79451716