ShambalaG
ShambalaG

Reputation: 356

Drag & Drop - Check item was dropped in the correct place

I'm teaching myself javascript/jquery and decided as a side project to create a drag and drop game. I've based it on other tutorials I've found and just adapted it really, so go easy on the code - hopefully its not too scary.

I'm using the jquery ui dropable library to implement the game and currently I check once the item is dropped if it is in the correct place, if it is I increment the score by one.

However the problem I have is I can't get the score to go down by one when the item is dropped in the wrong place.

If a square is placed on the correct placeholder it adds 1 to the score but if that same square gets removed from the correct place holder then it needs to take 1 off the score.

Heres a demo here of what I've done so far http://creativelabel.co.uk/drag-and-drop/

Any ideas?

Upvotes: 2

Views: 6046

Answers (2)

Pez Cuckow
Pez Cuckow

Reputation: 14422

One way to approach this is to store in the dropped element whether it was placed in a valid square. This means when it is moved to an invalid square you can check if it was previously in a valid one and if this is the case reduce the score by one.

Hope this is clear!

See http://jsfiddle.net/pET3y/ for a live demo

Relevant code:

  if ( slotNumber == imgNumber ) {
    ui.draggable.addClass( 'img-match' );
    ui.draggable.data("valid", true);

    imgMatch++;
  }  else {
      if(ui.draggable.data("valid")) {
         imgMatch--;
         ui.draggable.data("valid", false); 
      }
  }

Note: the the fiddle has an alert alert(ui.draggable.data("valid")); for debug

--

Changing for on drag the score goes down

What you do now is listen for the drag event (called activate), and when this is called run a function. The function checks if the element being dragged was previously in the correct position and if it was, marks it as not in the correct position and decreases the score.

See: http://jsfiddle.net/3NkwJ/1/

      drop: handleDropEvent,
      activate: handleDragEvent //add new event
} );

And add the below:

  function handleDragEvent( event, ui ) {
    if(ui.draggable.data("valid")) {
             imgMatch--;
             $('input[name=Score]').val(imgMatch);
             $('#score h1').text(imgMatch);
             ui.draggable.data("valid", false); 
    }      
  }

Upvotes: 1

Tom Prats
Tom Prats

Reputation: 7931

i only skimmed the code but after this block

if ( slotNumber == imgNumber ) {
    ui.draggable.addClass( 'img-match' );
    imgMatch++;
}

can you just add an else statement

else
    imgMatch--;

Upvotes: 0

Related Questions