我正在iPad上为孩子们制作一些拼图游戏。
这个代码适用于3个谜题,但是我重复了很多代码,我想知道如何更改代码,以便可以使用类文件。希望有人能帮助我。
var puzzel1:Array = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16];
var puzzel1k:Array = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16];
for each(var current_piece:MovieClip in puzzel1){
current_piece.visible = true;
current_piece.addEventListener(MouseEvent.MOUSE_DOWN, drag_piece_puzzel1);
current_piece.addEventListener(MouseEvent.MOUSE_UP, stop_piece_puzzel1);
}
for each(var target_piece:MovieClip in puzzel1k){
target_piece.visible = true;
}
//alle pieces van puzzel 1 worden hiermee gedragd
function drag_piece_puzzel1(e: MouseEvent): void {
current_piece = MovieClip(e.currentTarget);
current_piece.startDrag();
current_piece.scaleX = 0.85;
current_piece.scaleY = 0.85;
addChild(current_piece);
if(current_piece == p1){target_piece = t1;}
if(current_piece == p2){target_piece = t2;}
if(current_piece == p3){target_piece = t3;}
if(current_piece == p4){target_piece = t4;}
if(current_piece == p5){target_piece = t5;}
if(current_piece == p6){target_piece = t6;}
if(current_piece == p7){target_piece = t7;}
if(current_piece == p8){target_piece = t8;}
if(current_piece == p9){target_piece = t9;}
if(current_piece == p10){target_piece = t10;}
if(current_piece == p11){target_piece = t11;}
if(current_piece == p12){target_piece = t12;}
if(current_piece == p13){target_piece = t13;}
if(current_piece == p14){target_piece = t14;}
if(current_piece == p15){target_piece = t15;}
if(current_piece == p16){target_piece = t16;}
}
function stop_piece_puzzel1(e: MouseEvent): void {
current_piece.stopDrag();
if (target_piece.hitTestObject(current_piece)) {
current_piece.scaleX = 1;
current_piece.scaleY = 1;
current_piece.x = target_piece.x;
current_piece.y = target_piece.y;
if (array_pieces.indexOf(current_piece) == -1) {
counter = counter +1;
puzzlepiece = current_piece;
array_pieces.push(this["puzzlepiece"]);
}
}
}
答案 0 :(得分:0)
有很多方法可以做到这一点,但这是一个快速的方法,基于你的puzzel1
和puzzel1k
数组排成一行:
所有这样的行:
if(current_piece == p1){target_piece = t1;}
可以替换为以下几行:
var current_piece_index:int = puzzel1.indexOf(current_piece);
target_piece = puzzel1k[current_piece_index];
另一种解决方案是使用类似数组的Dictionary
,但不是处于[0]
和[4]
之类的位置,键是其他对象。
要设置它,你将遍历你的数组,使用作为键的片段和作为相关值的目标,如下所示:
var targetsByPieces:Dictionary = new Dictionary();
for(var i:uint = 0; i<puzzel1.length; i++){
targetsByPieces[puzzel1[i]] = puzzel1k[i];
}
然后要使用它,您只需查找目标,以便将所有if(current_piece == p1){target_piece = t1;}
代码替换为一行:
target_piece = targetsByPieces[current_piece];
这些解决方案都没有处理可能没有匹配的目标 - 但通常拼图没有“备件”所以我想这对你来说不是问题。