4.改进程序 (1)记录历史步骤,以便可以悔棋: 记录历史步骤的方法是
实现一个 History 类,这个类实际上是一个 Vector 的封装,用来保存每一步的走法,走法
被定义为一个包含 5 个元素的数组,分别是 X,Y,width,height,direction. 这
里需要注意的是,当中实际上是没有局部变量的,每一个局部变量都需要 new 出来,所
以在使用 Vector 的 addElement()函数时,由于它是传引用, 我们必须要新创建一
个 element,而不能使用全局的,因为如果使用全局的,下一次 addElement 时,会因为该
变 了 变 量 的 值 使 得 刚 才 加 到 Vector 中 的 值 也 改 变 了 。 import
java.util.Vector; /** * * @author lin */ public class History {
private static Vector steps = new Vector(); /** Creates a new instance of History */
public History() { clear(); } public static void addStep(Object step)
{ steps.addElement(step); } public static void removeLastStep() {
steps.removeElement(steps.lastElement()); } public static Object getLastStep()
{ return steps.lastElement(); } public static Object getStepAt(int index)
{ return steps.elementAt(index); } public static int getSize() {
return steps.size(); } private void clear() { if (!steps.isEmpty())
steps.removeAllElements(); } } 在每一步移动结束后,记录这一步的信
息: ContorlLogic.java: Move() ...... moves++;// 增加移动的步骤 byte[]
step = new byte[5]; //五个参数分别为,前四个和 SelectArea 一样,最后一个表示上 1,下
2,左 3,右 4。 //将此次移动记录到历史记录当中; step[0]= this.SelectArea[0];
step[1]= this.SelectArea[1]; step[2]= this.SelectArea[2]; step[3]= this.SelectArea[3];
step[4]= this.getMoveDirection(); history.addStep(step); ...... 增加一个悔棋的
按钮,增加一个 unMove()函数: public void unMove() { if ( moves ==
0 ) return; byte[] step = new byte[5]; //五个参数分别为,前四个和 SelectArea 一
样,最后一个表示上 1,下 2,左 3,右 4。 step = (byte []) history.getLastStep();//取得
上一步移动 history.removeLastStep();//减少一步; moves--; for (int i= 0;
i< 4;i++) { this.MoveArea = step;//重设 MoveArea this.SelectArea =
step;//重设 SelectArea } if (step[4] == 1) { this.SelectArea[1] =
(byte) (step[1]-1); this.loc[1]++; } else if (step[4] == 2) {
this.SelectArea[1] = (byte) (step[1]+1); this.loc[1]--; } else if (step[4] ==
3) { this.SelectArea[0] = (byte) (step[0]-1); this.loc[0]++; }
else if (step[4] == 4) { this.SelectArea[0] = (byte) (step[0]+1);
this.loc[0]--; } //移动回来. byte[][] temp = new byte[this.SelectArea[3]]
[this.SelectArea[2]]; //复制要移动的区域,因为这块区域可能会被覆盖掉 for
(int i = 0; i < this.SelectArea[2]; i++) { for (int j = 0; j < this.SelectArea[3]; j++)
{ temp[j] = this.MyMap.Grid[this.SelectArea[1] +j][this.SelectArea[0] + i];
} } //将要移动的区域移动到刚选中的区域(即要移动到的区域) for
(int i = 0; i < this.SelectArea[2]; i++) { for (int j = 0; j < this.SelectArea[3]; j++)
{ this.MyMap.Grid[this.MoveArea[1] + j][this.MoveArea[0] + i] = temp[j];
} } // 将 要 移 动 的 区 域 中 无 用 内 容 置 成 空 白 for (int i = 0; i <
this.SelectArea[3]; i++) { for (int j = 0; j < this.SelectArea[2]; j++) {
if (!isInRange2(this.SelectArea[0] + j,this.SelectArea[1] + i)) { //该点
是不在要移动到的区域之内,需置空 this.MyMap.Grid[this.SelectArea[1] + i]
[this.SelectArea[0] + j] = Images.BLANK; } } } //SelectArea