本文主要介绍五子棋核心算法,利用了一个三维数组来判断4个方向的棋子数,具体代码如下:
public class block
{
//判断0为白棋1为黑棋
private int type;
public int Type
{
get { return type; }
set { type = value; }
}
private bool chessman;
public bool Chessman
{
get { return chessman; }
set { chessman = value; }
}
//是否被打开
private bool isopen;
public bool Isopen
{
get { return isopen; }
set { isopen = value; }
}
private Rect rect;
public Rect Rect
{
get { return rect; }
}
private int row ;
private int col;
public int[,,] del=new int[4,2,2] //4代表4个大方向,2代表4个大方向中的两个小方向,最后一个2带表中间2个小方向在分为两个小方向
比如4个方向代表水平,竖直,左斜,右斜,中间2个方向代表水平,竖直,或者左斜,右斜,最后2个方向代表水平中的左右,竖直中的上下,左斜中的左上,左下,右斜中的右上,右下;
{
//横向
{{ -1, 0 },{ 1, 0 }},
//竖向
{{0,-1},{0,1} },
//左斜
{{-1,-1},{1,1} },
//右斜
{{1,-1},{-1,1} } };
}
//判断输赢
public bool Iswin(int xpos, int ypos)
{
int tempxpos = xpos;
int tempypos = ypos;
for (int i = 0; i < 4; i++)//四个大方向
{
int count = 1;
for (int j = 0; j < 2; j++)//一个方向上的两个小方向
{
while (true)
{
tempxpos = tempxpos + de1[i, j, 0];//取值
tempypos = tempypos + de1[i, j, 1];//取值
if (!OverStep(tempxpos, tempypos) && blocks[xpos, ypos].Type == blocks[tempxpos, tempypos].Type)//OverStep防止越界
{
count++;
}
else
{
break;
}
}
tempxpos = xpos;
tempypos = ypos;
}
if (blocks[tempxpos, tempypos].Type == 1 && count >= 5)
{
Debug.Log("黑方胜");
Score2++;
hwin = true;
return true;
}
else if (blocks[tempxpos, tempypos].Type == 2 && count >= 5)
{
Debug.Log("白方胜");
Score1++;
bwin = true;
return true;
}
}
return false;
//防止越界
bool OverStep(int x,int y)
{
if (x >= 0 && x < row && y >= 0 && y < col)
{
return false;
}
return true;
}