HTML and CSS Reference
In-Depth Information
}
}
At the end of the nested for:next loop, we make sure to test each piece to see whether its
selected propertyis true .Ifso,wepushitintothe selectedList localarraysothatwecan
perform the swap operation on the pieces:
iif ( board [ c ][ r ]. selected ) {
selectedList . push ({ col : c , row : r })
}
}
}
Swapping two elements in a two-dimensional array
Nowweneedtotesttoseewhethertwopieceshavebeenmarkedas selected .Ifso,weswap
thepositionsofthosepieces.Inthisway,itappearsthattheplayerisclickingonpuzzlepieces
and changing their locations to try to solve the puzzle.
To achieve the swap, we use a classic three-way swap programming construct utilizing a tem-
porary variable, tempPiece1 , as a placeholder for the values we are going to swap. First, we
need to create a couple variables to hold the selected pieces. We will use selected1 and se-
lected2 forthatpurpose.Next,wemovethereferencetothepiecerepresentedby selected1
into the tempPiece1 variable:
iif ( selectedList . length == 2 ) {
var
var selected1 = selectedList [ 0 ];
var
var selected2 = selectedList [ 1 ];
var
var tempPiece1 = board [ selected1 . col ][ selected1 . row ];
Next, we move the piece referenced by selected2 to the location in the board array of the
piece represented by selected1 (the first swap). Then we apply the piece referenced in se-
lected1 to the position represented by selected2 (the second swap). Finally, now that they
are swapped, we make sure to set the selected properties of both pieces to false :
board [ selected1 . col ][ selected1 . row ] = board [ selected2 . col ]
[ selected2 . row ];
board [ selected2 . col ][ selected2 . row ] = tempPiece1 ;
board [ selected1 . col ][ selected1 . row ]. selected = false
false ;
board [ selected2 . col ][ selected2 . row ]. selected = false
false ;
}
}
Search WWH ::




Custom Search