嗯
利用二维数组可以解决,每走一步,统计该坐标的水平、垂直、对角线是否连续达到4个。下面是一个简单的demo:
public class Game {
private int[][] chessboard;
private boolean gameover = false;
private int winLength;
private int current;
private int total;
/**
* @param size 棋盘大小
* @param winLength 赢的连续数量
*/
public Game(int size,int winLength){
if(size<1||size<winLength){
throw new RuntimeException("棋局参数错误!");
}
chessboard = new int[size][size];
total = size*size;
this.winLength = winLength;
}
public int step(int v,int h,int player){
if(gameover||current==total){
System.out.println("游戏已经结束");
return 0;
}
if(chessboard[v][h]==0){
chessboard[v][h] = player;
current ++;
return judge(v, h, player);
}
return -1;
}
private int judge(int v,int h,int player){
int count = 0;
//判断水平方向是否满足4连
count += statsHorizontal(v, player, -1, h-1);
count += statsHorizontal(v, player, 1, h);
//前面和后面的数量达到4,胜出
if(count>=winLength){
win(count, player);
return count;
}
count = 0;
//判断垂直方向是否满足4连
count += statsVertical(h, player, -1, v-1);
count += statsVertical(h, player, 1, v);
if(count>=winLength){
win(count, player);
return count;
}
count = 0;
//对角线4连 \方向
count += statsDiagonal_1(v, h, player);
if(count>=winLength){
win(count, player);
return count;
}
count = 0;
//对角线4连 /方向
count += statsDiagonal_2(v, h, player);
if(count>=winLength){
win(count, player);
return count;
}
return count;
}
private void win(int count,int player){
System.out.println("Player "+player+" win");
gameover = true;
}
/**
* 统计水平方向连续数量
*/
private int statsHorizontal(int v, int player,int step,int position) {
int count = 0;
for(int i=position;i>=0&&i<chessboard[v].length;i+=step){
if (chessboard[v] == player) {
count++;
continue;
}
break;
}
return count;
}
/**
* 统计垂直方向连续数量
*/
private int statsVertical(int h,int player,int step,int position){
int count = 0;
for(int i=position;i>=0&&i<chessboard.length;i+=step){
if(chessboard[h]==player){
count++;
continue;
}
break;
}
return count;
}
private int statsDiagonal_1(int v,int h,int player){
int count=0;
for(int i=1;v-i>=0&&h-i>=0;i++){
if(chessboard[v-i][h-i] == player){
count++;
continue;
}
break;
}
for(int i=0;v+i<chessboard.length&&h+i<chessboard[v+i].length;i++){
if(chessboard[v+i][h+i] == player){
count++;
continue;
}
break;
}
return count;
}
private int statsDiagonal_2(int v,int h,int player){
int count=0;
for(int i=v;v+i<chessboard.length&&h-i>=0;i++){
if(chessboard[v+i][h-i] == player){
count++;
continue;
}
break;
}
for(int i=h;v-i>=0&&h+i<chessboard[v-i].length;i++){
if(chessboard[v-i][h+i] == player){
count++;
continue;
}
break;
}
return count;
}
public static void main(String[] args) {
Game g = new Game(5,4);
g.step(0, 0, 1);
g.step(1, 1, 1);
g.step(2, 2, 1);
g.step(3, 3, 1);
}
} |