消除类游戏的算法实现
![]() |
//鼠标点击、移动、释放的算法
private function onMouseClick(e:MouseEvent):void
{
var cell:Cell = e.target as Cell;
if (!cell)
{
return;
}
curType = cell.type;
anchorArray.push(cell);
gameContainer.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
private function onMouseMove(e:MouseEvent):void
{
var cell:Cell = e.target as Cell;
if (cell && anchorArray.indexOf(cell) == -1)
{
if (cell.type == curType)
{
anchorArray.push(cell);
lineAnchor();
}
else
{
onMouseUp(null);
}
}
gameContainer.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
private function onMouseUp(e:MouseEvent):void
{
gameContainer.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
trace(anchorArray);
eraseAndFill();
lineContainer.graphics.clear();
anchorArray = [];
}
//删除和更新网格的算法
if (anchorArray.length < 3)
{
return;
}
for (var i:int; i < anchorArray.length; i++)
{
var cell:Cell = anchorArray[i];
cellArray[cell.xPostion][cell.yPostion] = null;
}
for (i=0; i < cellArray.length; i++)
{
var tempArray:Array = cellArray[i];
for (var j:int = 0; j < tempArray.length; j++)
{
if (tempArray[j] == null)
{
var type:int = Math.floor(Math.random() * 3);
var cellToAdd:Cell = new Cell(type);
tempArray.unshift(cellToAdd);
tempArray.splice(j + 1, 1);
}
}
}
for (i=0; i < cellArray.length; i++)
{
var tempArray2:Array = cellArray[i];
for (j=0; j < tempArray2.length; j++)
{
var cell2:Cell = tempArray2[j];
cell2.xPostion = i;
cell2.yPostion = j;
}
}
主要思路为:
使用数组存储网格内各个单元格内球的状态
鼠标点击之后开始记录可以添加进anchorArray数组的单元格
{
与当前的Cell相同,插入数组,否则数组置空,清楚鼠标事件。
}
删除anchorArray数组内的单元格,空缺的位置顺次填补,并在顶端加入随即产生的新的Cell。
重新绘制整个网格。
目前存在的问题:
删除anchorArray数组内的单元格之后,移动和填充的算法有些冗余,应该有更好的可以改进的办法。
可以在iphone做一下试一试。