Lab2 p3 围棋吃子的算法实现

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:59   3999   0

简单介绍下框架:

1.声明一维数组block[]作为一个临时变量记录一个块的大小,声明一个整型blockLength记录这个块的长度。

2.kill()为吃子的主函数。

recersion(int i,int j)为遍历周围棋子的函数在kill函数中调用。

hasQi()判断该块是否有气在kill函数中调用。

isInBlock(int neighbor)用来判断在遍历周围棋子中是否已经遍历,在recersion函数中调用。

这之中传入的board 实际上就是围棋的用二维数组实现的棋盘

/**
* kill the pieces which have no breath 也就是实现围棋的提子功能,如果提子,则返回提子的位置以及种类
* @param board is the go board
*/
int[] block;
int blockLength;
public void kill(goboard board){
gopiece[][] maps=board.getMaps();
for(int i = 0;i < 19; i++){
for(int j = 0;j < 19; j++){
if(maps[i][j] == null)
continue;
else{
block = new int[361];
blockLength = 1;
block[0] = i*100 + j;

recursion(board,i,j);

if(hasQi(board))
continue;
else {
for(int t = 0;t < blockLength; t++) {//吃子
System.out.println(maps[block[t]/100][block[t]%100]+" at ("+block[t]/100+","+block[t]%100+")"+" was eaten ");
maps[block[t]/100][block[t]%100] = null;
}
}
}
}
}
}
/**
* add the piece to the block
* @param board is the go board
* @param I is the abscissa .
* @param j is the ordinate.
*/
public void recursion(goboard board,int i,int j){
gopiece[][] maps=board.getMaps();
//Left
if(i-1 >= 0 &&maps[i-1][j]!=null&& maps[i][j]!=null&&maps[i-1][j].getColor().equals(maps[i][j].getColor()) && isInBlock((i-1)*100+j)){
block[blockLength] = (i-1)*100 + j;
blockLength++;
recursion(board,i-1,j);
}
//Up
if(j-1 >= 0 &&maps[i][j-1]!=null&& maps[i][j]!=null&& maps[i][j-1].getColor().equals(maps[i][j].getColor()) && isInBlock(i*100+j-1)){
block[blockLength] = i*100 + j-1;
blockLength++;
recursion(board,i,j-1);
}
//Right
if(i+1 < 19 &&maps[i+1][j]!=null&& maps[i][j]!=null&& maps[i+1][j].getColor().equals(maps[i][j].getColor()) && isInBlock((i+1)*100+j)){
block[blockLength] = (i+1)*100 + j;
blockLength++;
recursion(board,i+1,j);
}
//Down
if(j+1 < 19 &&maps[i][j+1]!=null&& maps[i][j]!=null&& maps[i][j+1].getColor().equals(maps[i][j].getColor()) && isInBlock(i*100+j+1)){
block[blockLength] = i*100 + j+1;
blockLength++;
recursion(board,i,j+1);
}
}
/**
* Judging whether there is gas in a block
* @param board is the go board
*/
public boolean hasQi(goboard board){
gopiece[][] maps=board.getMaps();
int i,j;
for(int t = 0;t < blockLength; t++){
i = block[t]/100;
j = block[t]%100;
if(i-1 >= 0 && maps[i-1][j] == null) return true;
if(i+1 < 19 && maps[i+1][j] == null) return true;
if(j-1 >= 0 && maps[i][j-1] == null) return true;
if(j+1 < 19 && maps[i][j+1] == null) return true;
}
return false;
}
/**
* Judging whether piece is in the block
* @param neighbor is the position in block
*/

public boolean isInBlock(int neighbor){
for(int i = 0;i < blockLength; i++)
{
if (block[i] == neighbor) return false;//在块中返回false
}
return true;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP