0

How can I add a point to the score after the black and green divs is in collision? After you move the black div with the up, down, left, right and it intersects the green div I would like to add a point to the score in the #score div. I use collision function and it gives me the error in the title.

The code can be rewritten if you have other suggestions. I will appreciate any help.

var pane = $('#pane'),
    box = $('#box'),
    boxGreen=$('#box-green'),
    w = pane.width() - box.width(),
    d = {},
    x = 3;

function newv(v,a,b) {
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return n < 0 ? 0 : n > w ? w : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
    box.css({
        left: function(i,v) { return newv(v, 37, 39); },
        top: function(i,v) { return newv(v, 38, 40); }
    });
}, 20);

var randomNumberAppearGreenBox=Math.floor(Math.random() * 10000);

// make position sensitive to size and document's width
var divsize = ((Math.random()*100) + 20).toFixed();
var posx = (Math.random() * (pane.width() - divsize)).toFixed();
var posy = (Math.random() * (pane.height() - divsize)).toFixed();
 
setInterval(function() {
    boxGreen.css({
        'left':posx+'px',
        'top':posy+'px',
        'display':'block'
    });
}, randomNumberAppearGreenBox);

 hit_div = $("#box").collision("#box-green");
  if (hit_div.length != 0) {
      alert("welcome Earthling!");
 }
     
#pane {
    position:relative;
    width:300px; height:300px;
    border:2px solid red;
}
    
#box {
    position:absolute; top:140px; left:140px;
    width:20px; height:20px;          
    background-color:black;
}

#box-green{
    position:absolute;
    width:20px; height:20px; 
    display:none;
    background-color:green;
}

.score{
  font-size:25px;
  font-weight:bold;
}

.score span{
  display:inline-block;
 }

#score{
  display:inline-block;
}
<div id="pane">
    <div id="box"></div>
    <div id="box-green"></div>
</div>

<div class="score">
<span>Score:  </span><div id="score">0</div>
</div>

https://codepen.io/andreighervan/pen/rPZgoZ

ryy77
  • 1,134
  • 5
  • 20
  • 36

0 Answers0