五子棋连珠原理

五子棋是一款休闲益智类的游戏,老少皆宜。游戏的玩法很简单,即在棋盘的一条线上连成颜色相同的五子及获胜,可你知道在游戏的制作的内部,是怎么判定五子棋获胜的吗?

我们先来看一张图 ,该图是五子棋的棋盘,五子棋的棋盘是 x为(0,14),y为(0,14)既 x, y各为15行

以该图的中心棋子为例,我们知道要五子连珠,无非就是四种可能 ,如图所示红线,绿线,蓝线,黑线,连成5子

这就有了四种扫描棋子的方式,(1,0)红线方向 1是扫描一颗棋子的偏移量

(0,1)绿线方向

(1,1)蓝线方向

(1,-1)黑线方向

这些是扫描棋子的偏移量offset

在开始可以定义数组来存储棋子的位置//生成棋子的位置 int[] pos = new int[2];

int [,]grid = new int [15,15];//记录棋子的信息

int linkNum //记录同色棋子连在一起的数量

我们假定下黑子 grid[pos[0],pos[1]] =1;白子为grid[pos[0],pos[1]] =2;

假设从中间的棋子开始扫描,从红线这条线开始扫描可以分为左边和右边,右边是(1,0),左边则是(-1,0)

,那么AI(电脑)是怎么判定的呢?

首先走红线的话,如果往右边走,扫描如果是黑子则linkNum++;如果是空子则返回方法;如果是白子也返回该方法

同样的道理走完左边也是一样的原理

以中心棋子为例,扫描四个方向 当linkNum>4,即五子的时候,就会判定游戏的胜利

具体代码实现如下

 public ChessType turn = ChessType.Black; //当前轮到黑字下棋

//turn 是该谁下棋了,(int)turn 代表棋子的颜色

//扫描一行棋子的方法

public bool CheckOneLine(int[] pos, int[] offset)
    {
        int linkNum = 1;
        //右边
        for (int i = offset[0], j = offset[1]; (pos[0] + i >= 0 && pos[0] + i < 15) &&
            pos[1] + j >= 0 && pos[1] + j < 15; i += offset[0], j += offset[1])
        {
            if (grid[pos[0] + i, pos[1] + j] == (int)turn)
            {
                linkNum++;
            }
            else
            {
                break;
            }
        }
        //左边
        for (int i = -offset[0], j = -offset[1]; (pos[0] + i >= 0 && pos[0] + i < 15) &&
            pos[1] + j >= 0 && pos[1] + j < 15; i -= offset[0], j -= offset[1])
        {
            if (grid[pos[0] + i, pos[1] + j] == (int)turn)
            {
                linkNum++;
            }
            else
            {
                break;
            }
        }

        if (linkNum > 4) return true;

        return false;
    }
 

//判定是否嬴

 public bool CheckWinner(int[] pos)
    {
        if (CheckOneLine(pos, new int[2] { 1, 0 })) return true;
        if (CheckOneLine(pos, new int[2] { 0, 1 })) return true;
        if (CheckOneLine(pos, new int[2] { 1, 1 })) return true;
        if (CheckOneLine(pos, new int[2] { 1, -1 })) return true;
        return false;
    }


猜你喜欢

转载自blog.csdn.net/weixin_41765385/article/details/80738383