首先我们在画板上绘制两个按钮,我们用两张图片表示,一张代表悔棋,一张代表重新开始,我们用LinkedList来存储我们操作的每个步骤,然后从LinkedList中提取每一步的操作
//两个按钮的图片
Bitmap[] button = new Bitmap[2];
//为两个按钮绑定资源
button[0] = BitmapFactory.decodeResource(this.getResources(), R.drawable.restart);
button[1] = BitmapFactory.decodeResource(this.getResources(), R.drawable.regret);
//绘制按钮
canvas.drawBitmap(button[0], screenWidth/2-30-button[0].getWidth(), 40, paint);
canvas.drawBitmap(button[1], screenWidth/2+30, 40, paint);
在触摸事件函数中添加记录操作的语句:
LinkedList<Map<String,Integer>> list = new LinkedList<Map<String,Integer>>();
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("index_x", index_x);//二维数组中x值
map.put("index_y", index_y);//二维数组中y值
list.add(map);
对触摸在按钮区间的动作进行监听:
//监听按钮事件,重新开始
if(touchX >screenWidth/2-30-button[0].getWidth() && touchX<screenWidth/2-30 && touchY>40 &&touchY<40+button[0].getHeight())
{
for(int i=0;i<GRID_NUM;i++)
{
for(int j=0;j<GRID_NUM;j++)
{
chess[i][j] = 0;
winFlag = false;
chess_flag = 0;
}
}
}
//悔棋
if(touchX >screenWidth/2+30 && touchX<screenWidth/2+30+button[1].getWidth() && touchY>40 &&touchY<40+button[1].getHeight())
{
int size = list.size();
if(chess[list.get(size-1).get("index_x")][list.get(size-1).get("index_y")] == CHESS_BLACK)
{
chess_flag = CHESS_WHITE;
chess[list.get(size-1).get("index_x")][list.get(size-1).get("index_y")] = 0;
}
else if(chess[list.get(size-1).get("index_x")][list.get(size-1).get("index_y")] == CHESS_WHITE)
{
chess_flag = CHESS_BLACK;
chess[list.get(size-1).get("index_x")][list.get(size-1).get("index_y")] = 0;
}
list.removeLast();//删除最后一次的操作
winFlag = false;
}
效果图:
悔棋后: