首先我們在畫板上繪製兩個按鈕,我們用兩張圖片表示,一張代表悔棋,一張代表重新開始,我們用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;}
:
悔棋後: