目录
一、基本原理
五子棋的规则很简单,即横或竖或四个斜方向有连续五个颜色一样的棋子,就获胜。所以由此可以得到五子棋判断输赢基本的原理:运用计数器,每下一步,若有横/竖/四个斜方向连续的棋子,则计数器+1,判断计数器是否大于等于5,若大于等于5,则判断获胜
二、实现步骤
1.左右方向判断连续相同颜色棋子个数
public int left_right(int[][] chessArray, int r, int c) {
// 定义一个计数器
int count = 0;
// 取出当前下的棋子
int chessNum = chessArray[r][c];
// 遍历判断 先向右 列向右遍历,行不变
// 遍历起点: 当前棋子的列+1
for (int i = c + 1; i < chessArray[r].length; i++) {
// 判断右边棋子是否与当前棋子一致
if (chessNum == chessArray[r][i]) {
count++;// 找到了一颗相同数值的棋子
} else {
break;// 找到了一颗不同数值的棋子 不再继续找
}
}
//向左
for(int i = c-1;i>=0;i--){
if(chessNum == chessArray[r][i]){
count++;
}else{
break;
}
}
count++;// 包括当前下的这颗棋子
System.out.println(count);
return count;
}
2.上下方向判断连续相同颜色棋子个数
public int up_down(int[][] chessArray, int r, int c){
int count = 0;
int chessNum = chessArray[r][c];
//向上
for(int i = c-1; i>=0;i--){
if(chessNum == chessArray[i][c]){
count++;
}else{
break;
}
}
//向下
for(int i = c+1;i<chessArray.length;i++){
if(chessNum == chessArray[i][c]){
count++;
}else{
break;
}
}
count++;
System.out.println(count);
return count;
}
3.左上/右下方向判断棋子的个数
public int leftUp_RightDown(int[][] chessArray, int r, int c){
int count = 0;
int chessNum = chessArray[r][c];
//右下
for(int i = r+1,j=c+1;i<chessArray.length&&j<chessArray[r].length;i++,j++){
if(chessNum == chessArray[i][j]){
count++;
}else{
break;
}
}
//左上
for(int i=r-1,j=c-1;i>=0&&j>=0;i--,j--){
if(chessNum == chessArray[i][j]){
count++;
}else{
break;
}
}
count++;
System.out.println(count);
return count;
}
4.左下/右上方向判断棋子个数
public int leftDown_RightUp(int[][] chessArray, int r, int c){
int count = 0;
int chessNum = chessArray[r][c];
//左下
for(int i = r+1,j=c-1;i<chessArray.length&&j>=0;i++,j--){
if(chessNum == chessArray[i][j]){
count++;
}else{
break;
}
}
//右上
for(int i=r-1,j=c+1;i>=0&&j<chessArray[r].length;i--,j++){
if(chessNum == chessArray[i][j]){
count++;
}else{
break;
}
}
count++;
System.out.println(count);
return count;
}
5.实现判断输赢函数
public boolean isWin(int[][] chessArray, int r, int c){
if(left_right (chessArray, r, c) >= 5
|| up_down (chessArray, r, c) >= 5
|| leftUp_RightDown(chessArray, r, c) >= 5
){
return true;
}
return false;
}
6.写一个测试主函数
public static void main(String[] args){
int[][] chessArray = {
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 1},
{0, 1, 0, 0, 1, 0, 1, 0},
{0, 1, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
};
IsWin iw = new IsWin ();
iw.isWin (chessArray,1,1);
}
运行后测试结果: