532 CHAPTER 13 Drag and drop
checkForWinner();
}
}
- At the bottom of the default.js file, add a checkForWinner function. In this function,
add a statement to check that the empty square is at the lower-right corner. Add a
loop to retrieve each tile and check its parent square to see whether the tile is in the
correct square. If not, exit the checkForWinner function by using a return statement. If
you make it to the bottom of the function, change the message to “Winner!”
Your code should look like the following.
function checkForWinner() {
if (emptySquare != squareCount - 1) return;
for (var i = 0; i < emptySquare; i++) {
if ($('#tile' + i).parent().attr('id') != 'square' + i) return;
}
$('#message').html('Winner!');
}
The following is the completed default.js file.
/// <reference path="jquery-1.8.3.js" />
var squareCount = 16
var emptySquare;
$(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();
});
function createBoard() {
for (var i = 0; i < squareCount; i++) {
var $square = $('<div id="square' + i + '" data-square="' + i
+ '" class="square"></div>');
$square.appendTo($('#gameBoard'));
}
}
function addTiles() {
emptySquare = squareCount - 1;
for (var i = 0; i < emptySquare; i++) {
var $square = $('#square' + i);
var $tile = $('<div draggable="true" id="tile' + i
+ '" class="tile">' + (i + 1) + '</div>');
$tile.appendTo($square);
}
}