Draggable/Droppable for Battleship game

試著忘記壹切 提交于 2019-12-08 08:24:58

问题


I've been experimenting with the jQuery UI draggable/droppable interaction to allow a user to set ships for a game of Battleship. As far as I can tell, droppable interactions work just fine when the drop location is appropriately sized to fit a draggable item, but in the Battleship game, you have ships of several different lengths that fit into a number of squares ranging 2-5.

If you check out this jsFiddle (http://jsfiddle.net/cDqGN/), and mess around with the ship of length two (versus the single block), you'll see it's fairly easy to screw up the drop, with the ship getting stuck between squares, or getting dragged a square to the right of where you intended to drop it.

Does anyone know of any tricks with this interaction to get it to go better?

In particular, this is the interaction as I have it now:

function handleDrop( event, ui ) {
    ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
    ui.draggable.draggable( 'option', 'revert', false );
}

回答1:


I found a solution using the grid option; I added the line below into your handleDrop function:

ui.draggable.draggable( "option", "grid", [ 52, 52 ] );

(It's 52x52 because the squares are 50x50, plus 1 on each side for the line width). After the ship is dragged to the board, you can then place the ship more precisely.

Here is the update jsFiddle: http://jsfiddle.net/cDqGN/1/



来源:https://stackoverflow.com/questions/18088833/draggable-droppable-for-battleship-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!