一、五子连珠
落子以后,我们只能以下几个方向(及其偏移量)进行遍历
(一)横:
右:(1,0)
左:(-1,0)
(二)竖:
上:(0,1)
下:(0,-1)
(三)正斜(/):
右上:(1,1)
左下:(-1,-1)
(四)反斜(\):
右下:(1,-1)
左上:(-1,1)
按照偏移量可以再细分四类:
{1,0} — (1,0)、(-1,0)
{ 0, 1 } — (0,1)、(0,-1)
{1,1} — (1,1)、(-1,-1)
{1,-1} — (1,-1)、(-1,1)
用两个for循环,一个纯+偏移量,一个纯-偏移量
二、代码书写
在写代码的过程中,可能少打一个空格多打一个空格,看起来不是那么规范得体
我们可以Crtl+A全选,再依次按下K、F键,自动格式化代码
方向检查函数CheckLine
public bool CheckLine(int[] pos,int[] offsets)
{
int count = 1;
//纯+
for (int i = pos[0] + offsets[0], j = pos[1] + offsets[1]; (i >= 0 && i <= 14) && (j >= 0 && j <= 14);
i += offsets[0], j += offsets[1])
{
if (grid[i, j] == (int)turn)
{
count ++;
}
else
{
break;
}
}
//纯-
for (int i = pos[0] - offsets[0], j = pos[1] - offsets[1]; (i >= 0 && i <= 14) && (j >= 0 && j <= 14);
i -= offsets[0], j -= offsets[1])
{
if (grid[i, j] == (int)turn)
{
count++;
}
else
{
break;
}
}
if (count >= 5)
{
return true;
}
return false;
}
传入偏移量:
public bool CheckIsWin(int[] pos)
{
if (CheckLine(pos, new int[2] { 1, 0 })) return true;
if (CheckLine(pos, new int[2] { 0, 1 })) return true;
if (CheckLine(pos, new int[2] { 1, 1 })) return true;
if (CheckLine(pos, new int[2] { 1, -1 })) return true;
return false;
}
游戏结束
private void GameEnd()
{
gameState = false;
Debug.Log(turn + "胜利!!");
}
三、总结
演示视频链接:
https://live.csdn.net/v/119546
这样子,双人对战ok了,接下来整一下关卡模式选择和单机五子棋
四、点击在棋盘才有效,其他地方不可以
EventSystem.current.IsPointerOverGameObject()方法,作用:判断鼠标是否点击在UI上