电梯框架广告报价单:拼图游戏的算法(推动的拼图)FLASH版

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/02 08:57:00
如果有随机排序,有可能造成无解,我试想了一个算法,可是我自己写出来以后导致有可能两个位置重叠。我的想法是让一个方块真实的移动,就是随机地上下左右移动,循环50次,以后拼图打乱了,而且是可还原的。
以下是我的代码(ActionScript):
//初始化位置:lct记录16个方块的位置,lct1保存排好时的位置
lct = new Array("0|0", "100|0", "200|0", "300|0", "0|100", "100|100", "200|100", "300|100", "0|200", "100|200", "200|200", "300|200", "0|300", "100|300", "200|300", "300|300");
lct1 = new Array("300|300", "0|0", "100|0", "200|0", "300|0", "0|100", "100|100", "200|100", "300|100", "0|200", "100|200", "200|200", "300|200", "0|300", "100|300", "200|300");
//随机变换位置:原算法
/*for (i=0; i<16; i++) {
a = lct[i];
b = int(Math.random()*16);
lct[i] = lct[b];
lct[b] = a;
}*/
//新随机放置算法
ept = 15; //移动的方块
for (i=0; i<50; i++) {
a = lct[ept];
b = int(Math.random()*100);
if (b<25) {
if (ept != 15 && ept != 3 && ept != 7 && ept != 11) {
chg = ept+1;
}
} else if (b<50 && b>25) {
if (ept != 15 && ept != 12 && ept != 13 && ept != 14) {
chg = ept+4;
}
} else if (b<75 && b>50) {
if (ept != 0 && ept != 1 && ept != 2 && ept != 3) {
chg = ept-4;
}
} else if (b>75) {
if (ept != 0 && ept != 4 && ept != 8 && ept != 12) {
chg = ept-1;
}
}
lct[ept] = lct[chg];
lct[chg] = a;
ept = chg;
}

不一定只让一个方块移动,算法可以是先把一张图片分割好,为每个方块指定一个整形的数字。然后写一个方法,让i行j列的方块随机往一个方向移动。调用这个方法若干次,效果上就像你让人家玩魔方前,自己手工把它打乱。

数据结构方面,由于AS并不支持真正的多维数组,你可以用数组的数组来存放N*N的方块:
var num:Number=10;
var blocks:Array=new Array();
var count:Number=0;
for(var i:Number=0;i<num;i++){
var row:Array=new Array();
for(var j:Number=0;j<num;j++){
row.push(count++);
}
blocks.push(row);
}
function randomMove(rowIndex:Number,colIndex:Number){
..
}

Good Luck