Practice exercises CHAPTER 13 533
function dragStarted(e) {
var $tile = $(e.target)
$tile.addClass('dragged');
var sourceLocation = $tile.parent().data('square');
e.dataTransfer.setData('text', sourceLocation.toString());
e.dataTransfer.effectAllowed = 'move';
}
function dragEnded(e) {
$(e.target).removeClass('dragged');
}
function preventDefault(e) {
e.preventDefault();
}
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);
checkForWinner();
}
}
function moveTile(sourceLocation) {
var distance = sourceLocation - emptySquare;
if (distance < 0) distance = -(distance);
if (distance == 1 || distance == 4) {
swapTileAndEmptySquare(sourceLocation);
}
}
function swapTileAndEmptySquare(sourceLocation) {
var $draggedItem = $('#square' + sourceLocation).children();
$draggedItem.detach();
var $target = $('#square' + emptySquare);
$draggedItem.appendTo($target);
emptySquare = sourceLocation;
}
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;
}