Game Development Reference
In-Depth Information
protected function movePiece(piece:IGamePiece, newIndex:int):
void {
piece.movePiece(piece.width * (newIndex % _columns),
piece.height * Math.floor(newIndex / _columns));
piece.currentIndex = newIndex;
}
I have grouped these methods together because they are all
interrelated and easier to look at in the context of each other. The
pieceClicked method is called when
a piece is
clicked. It checks if another piece has already been selected. If not,
this piece becomes the currently selected piece. If this piece is
already selected, it will be deselected. If a different piece has
already been selected, the game dispatches a PIECE_SWAP event
and proceeds to exchange the two pieces
you guessed it
positions. The movePiece
function calls the same method on the corresponding piece and
updates its currentIndex property. Once moved, the position of the
piece is evaluated by the checkPiece method. If the piece
'
'
s current-
Index matches its original index, the piece is in place and is locked.
Finally, once the two pieces have been moved and checked, check-
Win is called to determine if all the pieces are now in their correct
positions. If they are, the game deactivates itself and dispatches the
GAME_OVER event.
protected function randomize(vector:Vector. < IGamePiece > ):
Vector. < IGamePiece > {
for (var i:int = 0; i < vector.length-1; i++) {
var randomIndex:int = Math.round(Math.random()*
(vector.length 1 i)) + i;
swapElements(vector, i, randomIndex);
}
return vector;
}
protected function swapElements(vector:Vector. < IGamePiece > ,
index1:int,index2:int):void {
var temp:IGamePiece =vector[index1];
vector[index1]=vector[index2];
vector[index2]=temp;
temp=null;
}
These two final methods of the GameBoard class are not speci-
fic to the game logic but are actually generic utility functions that I
wrote originally to manipulate Arrays. Here, they have been modi-
fied to do the same with vectors of a specific type. The randomize
method shuffles the vector so that all of the elements are in new
positions. By swapping each index with a random one after it, we
Search Nedrilad ::




Custom Search