Practice exercises CHAPTER 13 531
$(document).ready(function () {
jQuery.event.props.push('dataTransfer');
createBoard();
addTiles();
$('#gameBoard').on('dragstart', dragStarted);
$('#gameBoard').on('dragend', dragEnded);
$('#gameBoard').on('dragenter', preventDefault);
$('#gameBoard').on('dragover', preventDefault);
$('#gameBoard').on('drop', drop);
scramble();
});
- At the bottom of the default.js file, add the following scramble function.
function scramble() {
for (var i = 0; i < 128; i++) {
var random = Math.random()
var sourceLocation;
if (random < 0.5) {
var column = emptySquare % 4
if (column == 0 || (random < 0.25 && column != 3)) {
sourceLocation = emptySquare + 1;
}
else {
sourceLocation = emptySquare - 1;
}
}
else {
var row = Math.floor(emptySquare / 4)
if (row == 0 || (random < 0.75 && row != 3)) {
sourceLocation = emptySquare + 4;
}
else {
sourceLocation = emptySquare - 4;
}
}
swapTileAndEmptySquare(sourceLocation);
}
}
The scramble function executes a loop of 128 random movements to scramble the
tiles. Each time the loop executes, a new random number is created, and, based on its
value, an adjacent tile is moved to the empty square. - In the drop function, add code to call the checkForWinner function that you create
next.
Your code should look like the following.
function drop(e) {
var $square = $(e.target);
if ($square.hasClass('square')) {
var destinationLocation = $square.data('square');
if (emptySquare != destinationLocation) return;
var sourceLocation = Number(e.dataTransfer.getData('text'));
moveTile(sourceLocation);