五子棋五个颜色相同的棋子相连就算获胜,那么我们可以遍历整个棋盘(我用的二位数组),从横竖斜几个方向来查找有没有五连子.但这样对整体性能会有影响. 新方法是获取当前子的X,Y的索引,从当前坐标开始,向上下左右斜向遍历.代码如下:
public boolean iswin(ChessBoard a,ChessMan c)
{
//横向起点的X 坐标
int startX = 0;
//竖向起点Y 坐标
int startY = 0;
//斜向起点Y
int startYY=0;
//横向结束X 坐标
int endX = 14;
//竖向结束Y 坐标
int endY = 14;
//斜向起点Y
int endYY =0;
//同条直线上相邻棋子累积数
int sameCountx = 0;//横
int sameCounty = 0;//竖
int sameCountxx = 0;//斜
int sameCountyy = 0;//斜
int temp = 0;
//计算起点的最小X 坐标与Y 坐标
temp = this.posX - 4;
startX = temp < 0 ? 0 : temp;
temp = this.posY - 4;
startY = temp < 0 ? 0 : temp;
//斜向检测初始最小XY坐标
startYY=startY;
//计算终点的最大X 坐标与Y 坐标
temp = this.posX + 4;
endX = temp > 14 ?14 : temp;
temp = this.posY + 4;
endY = temp > 14 ?14 : temp;
//斜向检测初始最小XY坐标
endYY=endY;
//从左到右方向计算相同相邻棋子的数目
String[][] board = a.returnBoard();
//竖向
for( int i = startY; i < endY; i++)
{
if( board[this.posX][i].equals((c.returnChessMan()+" ")) && board[this.posX][i+1] .equals((c.returnChessMan()+" ")) )
{
sameCounty++;
if(sameCounty==4)
{
return true;
}
}
else
{
sameCounty = 0;
}
}
//斜向
for( int i=startX;i<endX;i++)
{
if( board[i][endYY].equals( (c.returnChessMan()+" ")) && board[i+1][endYY-1].equals((c.returnChessMan()+" ")) )
{
sameCountyy++;
if(sameCountyy==4)
{
return true;
}
}
else
{
sameCountyy = 0;
}
endYY--;
if(endYY==0)
{
break;
}
}
//横向
for(int i=startX;i<endX;i++)
{
if(board[i][this.posY].equals((c.returnChessMan()+" ")) && board[i+1][this.posY].equals((c.returnChessMan()+" ")))
{
sameCountx++;
if(sameCountx==4)
{
return true;
}
}
else
{
sameCountx=0;
}
}
斜向
for(int i=startX;i<endX;i++)
{
if(board[i][startYY].equals((c.returnChessMan()+" ")) && board[i+1][startYY+1].equals((c.returnChessMan()+" ")))
{
sameCountxx++;
if(sameCountxx==4)
{
return true;
}
}
else
{
sameCountxx=0;
}
startYY++;
if(startYY==14)
{
break;
}
}
return false;
} |