Jquery、时间间隔和 if 语句

Jquery, timeinterval and if statements

我在玩某种 jQuery 游戏时卡住了。我需要两件事的帮助。

  1. 我有一个带玩家的棋盘。玩家在键盘上的箭头的帮助下移动。我的问题是玩家离开了游戏板,我不想要这个。应该怎么做才能让它不能跳出盒子

  2. 我制作了某种 "food",每次刷新时它都会在随机的 X 位置生成。但是我希望它每隔一秒在一个随机位置生成,例如,因此板上可以有多个 "food"。

这是我的:

$(document).ready(function() {
  $(document).keydown(function(e) { 
    if (e.keyCode ==39 && $("#spelare").css("left") < '880px')  
      $("#spelare").animate({left: '+=20px'}, 0);
    else if (e.keyCode ==37 && $("#spelare").css("left") > '0px') 
      $("#spelare").animate({left: '-=20px'}, 0);
  });

  $('.food').each(function() {
    var spelplanWidth = $('#spelplan').width();//Screen width
    var foodPosX = Math.floor((Math.random() * spelplanWidth));

    $(this).css('left', foodPosX);
    setInterval(function() {
      var spelplanWidth = $('#spelplan').width();//Screen width
      var foodPosX = Math.floor((Math.random()*spelplanWidth));
     
      $(this).css('left', foodPosX);
    }, 1000);
  });
});
body {
  text-align: center;
  background-color:black;
}

#spelplan{
  width: 50%;
  height:65vh;
  position:absolute;
  margin-left:25%;
  box-shadow: inset 0px 0px 50px;
  background-color: green;
}
#spelare{
  width:15%;
  height: 12vh;
  position: relative;
  top:53.4vh;
  background-color:red;
}

.food{
  width:5%;
  height:5vh;
  position:relative;
  background-color:blue;
}

p {
  position:relative;
  font-family: 'Electrolize', sans-serif;
}

#poäng{
  color:white;
  bottom:17vh;
  right:45%;
}

#liv{
  color:white;
  bottom:18vh;
  right:46.5%;
}

.fa-heart{
  color:red;
  bottom:21.5vh;
  right:43.5%;
  position:relative;
}

#info{
  color:white;
  font-family: 'Electrolize', sans-serif;
  margin-top:68vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 style="color:white">JQUERY SPEL</h2>
<div id="spelplan">
  <div id="spelare"> </div>
  <div class="food"> </div>
  <p id="poäng"> Poäng:   </p>
  <p id="liv"> Liv: </p>
  <i class="fa fa-heart" aria-hidden="true"></i>
</div>

1) 为了防止玩家移动太远,您需要在每个方向移动之前在 if 语句中添加一个条件,以确保它不会超出您的游戏板

2) 使用setInterval代替setTimeoutsetTimeout 在设定的时间段后调用该函数一次。 setInterval 一直重复,直到被告知停止 clearInterval()。如果您需要,必须将 setInterval 函数分配给您稍后可以访问的变量。

$(document).ready(function(){
  $(document).keydown(function(e){ 
        if (e.keyCode ==39 && $("#spelare").css("left") < 800) //or whatever your right most position is
            $("#spelare").animate({left: '+=20px'}, 0);
        else if (e.keyCode ==37 && $("#spelare").css("left") > 100) 
            $("#spelare").animate({left: '-=20px'}, 0);
    });

  setInterval(spawnFood,1000);
});

function spawnFood(){
   var spelplanWidth = $('#spelplan').width();
   var foodPosX = Math.floor((Math.random()*spelplanWidth));
   var element = "<div class='food'></div>"
   $(element).css('left',foodPosX);
   $("#spelplan").append(element);
}