辞职了忙着找工作,不想遇上了什么鬼互联网寒冬,一时半会也没有着落闲暇之余打算复习一下Android(我的天,全忘了),决定从这个最简单的小拼图游戏开始,并简单记录一下。
首先呢是界面,就不说了,刷刷的去写xml就好了,我审美水平就这样子了,完成后大体就是这样子了,也没遇到什么大问题了。
接着开始给什么按钮呀,imageview呀注册事件,编写逻辑,也不多说了,都简单,最后开始编写游戏逻辑了,于是遇到了一个小问题,所以记录一下。
游戏的逻辑很简单:
1.根据指定大小生成随机的图片网格,并留一个空白网格。
2.点击网格项的时候,如果其上下左右存在空白网格,则该项和空白网格互换,最终如果所有网格都复位的话,游戏结束。
本来说,随机网格嘛,只要把一个图片数组打乱顺序就好了,于是我就这样:
Bitmap bitMapArray[] = new Bitmap[]{...};
Random rom = new Random(new Date().getTime());
for(int i = 0; i < loopCount; i++) {
int tmpIndex1 = rom.nextInt(size);
int tmpIndex2 = rom.nextInt(size);
Bitmap tmp1 = bitMapArray[tmpIndex1 ];
Bitmap tmp2 = bitMapArray[tmpIndex2 ];
bitMapArray[tmpIndex1 ] = tmp2 ;
bitMapArray[tmpIndex2 ] = tmp1;
}
随机网格成了,虽然有时候不是真的那么随机,但是在执行游戏逻辑的时候发现,有时候无论你怎么弄,有两个方块没办法复位,游戏没法结束,仔细一想,假如我随机互换第一块和第五块,在这种情况下按照拼图的规则,你是没有办法使它们复位的,于是乎,这种随机方法是不可行的,只能另想他法了,我的想法是从空白块开始,随机选择一个方向【上下左右】互换,然后不停的循环,最后,按照最近路径将空白块换回最后一个方块,这样就不存在游戏无法结束的情况了,下面是我的实现(代码很烂,不喜勿喷):
void randomIndex(int size) {
Random rom = new Random(System.currentTimeMillis());
int indexArray[] = new int[size * size];
for(int i = 0; i < indexArray.length; i++) {
indexArray[i] = i;
}
for(int i = 0; i < indexArray.length; i++) {
int romIndex = rom.nextInt(indexArray.length);
int romIndex1 = rom.nextInt(indexArray.length);
if(romIndex == indexArray.length - 1 || romIndex1 == indexArray.length - 1) {
continue;
}
int tmp = indexArray[romIndex1];
indexArray[romIndex1] = indexArray[romIndex];
indexArray[romIndex] = tmp;
}
for (int i = 0; i < indexArray.length; i++) {
int tagIndex = indexArray[i];
int curIndex = (int) curText.getTag();
int curx = curIndex % size, cury = curIndex / size;
int x = tagIndex % size, y = tagIndex / size;
while (true) {
if(tagIndex == curIndex) {
break;
}
if(x < curx) {
move(subPic[--curx][cury]);
}
if(x > curx) {
move(subPic[++curx][cury]);
}
if(y > cury) {
move(subPic[curx][++cury]);
}
if(y < cury) {
move(subPic[curx][--cury]);
}
if(curx == x && cury == y) {
break;
}
}
}
}
int[][] dirArray = new int[][]{
{0,1},
{1,0},
{-1,0},
{0,-1}
};
public void move(View view) {
int index = (int)view.getTag();
int x = index % size;
int y = index / size;
String text = "" + subPic[y][x].getText();
Bitmap bitmap = subPic[y][x].getImg();
int realIndex = subPic[y][x].getRealIndex();
subPic[y][x].setText(curText.getText());
subPic[y][x].setImg(curText.getImg());
subPic[y][x].setRealIndex(curText.getRealIndex());
curText.setText(text);
curText.setImg(bitmap);
curText.setRealIndex(realIndex);
curText = subPic[y][x];
moveCount++;
}
github地址:https://github.com/monsterCry/pintu