为什么我的数组值不能反映我在屏幕上看到的内容?

时间:2017-06-01 11:07:56

标签: javascript arrays

我正在进行一场蛇游戏。当我的蛇“吃”一块蓝色食物时,我在它的尾巴上加了另一块。但是,当我在console.log中使用蛇形数组时,我没有看到每个蛇形片的各个数据属性。我只看到根据蛇的当前长度重复蛇头的位置。

这是否发生是因为使蛇移动的setInterval太短了?蛇是如此快速地移动,以至于当console.log发生时,每一块都正在经过头部移动的地方?或者我在屏幕上看到的内容和蛇阵列的位置有一些延迟? 如何修复我的代码,以便获得蛇形数组中每个部分的准确值?我希望数组反映我在屏幕上看到的内容。

如果按shift键,蛇将暂停,但console.log仍然不会显示正确的值。箭头键控制蛇的运动。首先单击网格开始播放。



//In the moveSnake function I had to use code from the below link in order to ignore multiple keydown events.
//https://stackoverflow.com/questions/9098901/how-to-disable-repetitive-keydown-in-jquery

$(document).ready(function() {
  makebox();
  addSnake();
  moveSnake();
  addFood();
  killSnake();
  addToSnake();
  });

function makebox() {

  var size = 24;  //24
  var boxSize = 12; //12
  for (i=1;i<=size*size;i++) {
    $("#container").append("<div class='box'></div>");
  };
  $("#container").width(size*boxSize + "px");
  $(".box").width(boxSize + "");
  $(".box").height(boxSize + "px");
  $(".box").each( function(i) {
    $(this).attr('data', (i+1));
  });
  };

function addSnake () {

var rightTime, leftTime, downTime, upTime, right, left, up, lildown;

moveRight = function() {
console.log(snake);
  right = true;
  left= false;
  up = false;
  lildown = false;
  down = {}
  rightTime = setInterval(function(){
  for (var i=0;i<snake.length;i++) {
    snake[i]++
$('*[data="' + snake[i] + '"]').addClass("hover")
$('*[data="' + (snake[snake.length-1]-snake.length) + '"]').removeClass("hover");

} }, 150)

};

moveLeft = function() {
  console.log(snake);
  right = false;
  left= true;
  up = false;
  lildown = false;
  down = {}
  leftTime = setInterval(function(){ //snake -= 1
    for (var i = 0; i <snake.length;i++){
        snake[i] -= 1
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1]+snake.length ) + '"]').removeClass("hover");
} }, 150)

};

moveDown = function() {
console.log(snake);
  right = false;
  left= false;
  up = false;
  lildown = true;
  down = {}
  downTime = setInterval(function(){ //snake += 25
    for (var i = 0; i <snake.length;i++){
        snake[i] += 18
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1] - 18 * snake.length) + '"]').removeClass("hover");


} }, 150)

};

moveUp = function() {
console.log(snake);
  right = false;
  left= false;
  up = true;
  lildown = false;
  down = {}
  upTime = setInterval(function(){ //snake -= 25
for (var i = 0; i <snake.length;i++){
        snake[i] -= 18
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1] + 18 * snake.length) + '"]').removeClass("hover");
} }, 150)

};

addTail = function() {
    snake.push(snake[snake.length - 1])
console.log(snake)
  }

var snake = [42]

$('*[data="' + snake[0] + '"]').addClass("hover");

var down = {};

removeExtra = function(){

var array = [];

  $(".hover").each(function() {
      array.push($(this).attr("data"));
  });

var len = array.length
var len2 = snake.length - 1
var combo = len-len2

  //for (var i=0;i<len2;i++){
    //array.splice(0,i)
    //$('*[data="' + (array[i]) + '"]').removeClass("hover");}

 }

  moveSnake = function() {

    $(document).keydown(function(event){

   var keycode = (event.keyCode ? event.keyCode : event.which);


   if(keycode == '39'){
        if (down['39'] == null) {
          window.clearInterval(leftTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveRight();
          removeExtra();
          down['39'] = true;

                             }
   }

  else if(keycode == '37'){
        if (down['37'] == null) {
          window.clearInterval(rightTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveLeft();
        removeExtra();
          down['37'] = true;
                    }
   }

   else if(keycode == '40'){
         if (down['40'] == null) {
           window.clearInterval(leftTime);
           window.clearInterval(rightTime);
           window.clearInterval(upTime);
           moveDown();
        removeExtra();
           down['40'] = true;
                     }
    }

    else if(keycode == '38'){
          if (down['38'] == null) {
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            moveUp();
        removeExtra();
            down['38'] = true;
                      }
     }
      
          else if(keycode == '16'){
                                
            window.clearInterval(upTime);
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            console.log(snake)
          }


 });

 addToSnake = function(){
   var count = 0;

     var config = { attributes: true, childList: true, characterData: true };

     $(".box, .food").each(function () {
       var target = this;
       var observer = new MutationObserver(function(mutations) {
         mutations.forEach(function(mutation) {
          if ($(".food").hasClass("hover") == true){
            $(".box").removeClass("food")
            addTail();
            addFood();
                      }
                    });
                  });

      observer.observe(target, config);

   });

           }

  killSnake = function() {
    var config = { attributes: true, childList: true, characterData: true, subtree:true };

    $(".right-border, .left-border, .top-border, .bottom-border").each(function () {
      var target = this;
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          console.log("Game over!")
        });
      });

    observer.observe(target, config);
  });
          }
}

addFood = function(){
  var random = Math.floor(Math.random() * (500 - 1 + 1)) + 1;
  $('*[data="' + random + '"]').addClass("food")

};

};
&#13;
.box {
  display: inline-block;
  border: 2px grey solid;

}


#container {
  display: block;
  border: 2px black solid;
  border-radius: 5px;
  font-size: 0;
  margin: 10px auto;
}
.hover {
  background-color: black;
}

.food {
  background-color: blue;
}

.white {
  background-color: white;
}

.right-border, .left-border, .top-border, .bottom-border {
  background: red;
  border: 2px red solid;

}
&#13;
<!DOCTYPE html>

<html lang="en">

<head>

  <title>Snake</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <link rel="stylesheet" href="style.css">

  <script type="text/javascript" src="script.js"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

</head>

<body>

  <div class="container">

    <center>
      <h1>Snake</h1>
      
      <div id="container"></div>
    </center>

  </div>

</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

Wellll ..我设法以某种方式修复了这个游戏,主要是做了两件事:

  • 拆分最后一块瓷砖&amp;添加第一个tile来更新snake索引(数组中的值)。你的代码中存在其他数组值的错误,并且它们以这种方式修复。
  • 添加记住蛇已经去过的最后一个字段的变量,并在蛇吃东西时使用该变量添加图块。这是你问题的主要解决方法,就像以前一样,你基本上是在一个数组中复制值,它只是错误地工作(坏循环)。

所以,现在它应该按预期工作,buuuut ..

  1. 在游戏中使用jquery是对上帝的亵渎,与香草相比它具有可怕的表现,并且不会以任何可能的方式帮助你。
  2. 运动&amp;更新应该在1个间隔/帧循环内进行,而不是在4个循环内,这是对DRY规则的严重犯罪。
  3. 它可能更容易使用二维数组。
  4. 和其他几个人
  5. &#13;
    &#13;
    //In the moveSnake function I had to use code from the below link in order to ignore multiple keydown events.
    //https://stackoverflow.com/questions/9098901/how-to-disable-repetitive-keydown-in-jquery
    
    $(document).ready(function() {
      makebox();
      addSnake();
      moveSnake();
      addFood();
      killSnake();
      addToSnake();
      });
    
      var previousSnake = null;
    
    function makebox() {
    
      var size = 24;  //24
      var boxSize = 12; //12
      for (i=1;i<=size*size;i++) {
        $("#container").append("<div class='box'></div>");
      };
      $("#container").width(size*boxSize + "px");
      $(".box").width(boxSize + "");
      $(".box").height(boxSize + "px");
      $(".box").each( function(i) {
        $(this).attr('data', (i+1));
      });
      };
    
    
    
    function addSnake () {
    
    
    
    var rightTime, leftTime, downTime, upTime, right, left, up, lildown;
    
    moveRight = function() {
    console.log(snake);
      right = true;
      left= false;
      up = false;
      lildown = false;
      down = {}
      rightTime = setInterval(function(){
    
    $('*[data="' + (snake[0]+1) + '"]').addClass("hover")
    $('*[data="' + snake[snake.length-1] + '"]').removeClass("hover");
    previousSnake = snake[snake.length-1]
    updateSnakeNumbers(snake[0]+1)
     }, 150)
     
    
    };
    
    moveLeft = function() {
      console.log(snake);
      right = false;
      left= true;
      up = false;
      lildown = false;
      down = {}
      leftTime = setInterval(function(){ //snake -= 1
      console.log('llll',JSON.stringify(snake))
      $('*[data="' + (snake[0]-1) + '"]').addClass("hover");
      $('*[data="' + snake[snake.length-1]  + '"]').removeClass("hover");
      previousSnake = snake[snake.length-1]
      console.log('llll',JSON.stringify(snake))
      updateSnakeNumbers(snake[0]-1)
      console.log('llll',JSON.stringify(snake))
     }, 150)
    
    };
    
    moveDown = function() {
    console.log(snake);
      right = false;
      left= false;
      up = false;
      lildown = true;
      down = {}
      downTime = setInterval(function(){ //snake += 25
      $('*[data="' + (snake[0]+18) + '"]').addClass("hover");
      $('*[data="' + snake[snake.length-1] + '"]').removeClass("hover");
      previousSnake = snake[snake.length-1]
    updateSnakeNumbers(snake[0]+18)
    
    }, 150)
    
    };
    
    moveUp = function() {
    console.log(JSON.stringify(snake));
      right = false;
      left= false;
      up = true;
      lildown = false;
      down = {}
      upTime = setInterval(function(){ //snake -= 25
      $('*[data="' + (snake[0]-18) + '"]').addClass("hover");
      $('*[data="' + snake[snake.length-1]  + '"]').removeClass("hover");
      previousSnake = snake[snake.length-1]
      updateSnakeNumbers(snake[0]-18)
     }, 150)
    
    };
    
    addTail = function() {
      console.log(JSON.stringify(snake),previousSnake)
        snake.push(previousSnake)
    console.log(JSON.stringify(snake),previousSnake)
      }
    
    var snake = [42]
    
    function updateSnakeNumbers(head){
      var prevNum = head
      snake = snake.map(n=>{
        var tmpPrev = prevNum;
        prevNum = n;
        return tmpPrev
      })
    }
    
    $('*[data="' + snake[0] + '"]').addClass("hover");
    
    var down = {};
    
    removeExtra = function(){
    
    var array = [];
    
      $(".hover").each(function() {
          array.push($(this).attr("data"));
      });
    
    var len = array.length
    var len2 = snake.length - 1
    var combo = len-len2
    
      //for (var i=0;i<len2;i++){
        //array.splice(0,i)
        //$('*[data="' + (array[i]) + '"]').removeClass("hover");}
    
     }
    
      moveSnake = function() {
    
        $(document).keydown(function(event){
    
       var keycode = (event.keyCode ? event.keyCode : event.which);
    
    
       if(keycode == '39'){
            if (down['39'] == null) {
              window.clearInterval(leftTime);
              window.clearInterval(downTime);
              window.clearInterval(upTime);
              moveRight();
              removeExtra();
              down['39'] = true;
    
                                 }
       }
    
      else if(keycode == '37'){
            if (down['37'] == null) {
              window.clearInterval(rightTime);
              window.clearInterval(downTime);
              window.clearInterval(upTime);
              moveLeft();
            removeExtra();
              down['37'] = true;
                        }
       }
    
       else if(keycode == '40'){
             if (down['40'] == null) {
               window.clearInterval(leftTime);
               window.clearInterval(rightTime);
               window.clearInterval(upTime);
               moveDown();
            removeExtra();
               down['40'] = true;
                         }
        }
    
        else if(keycode == '38'){
              if (down['38'] == null) {
                window.clearInterval(leftTime);
                window.clearInterval(rightTime);
                window.clearInterval(downTime);
                moveUp();
            removeExtra();
                down['38'] = true;
                          }
         }
          
              else if(keycode == '16'){
                                    
                window.clearInterval(upTime);
                window.clearInterval(leftTime);
                window.clearInterval(rightTime);
                window.clearInterval(downTime);
                console.log(snake)
              }
    
    
     });
    
     addToSnake = function(){
       var count = 0;
    
         var config = { attributes: true, childList: true, characterData: true };
    
         $(".box, .food").each(function () {
           var target = this;
           var observer = new MutationObserver(function(mutations) {
             mutations.forEach(function(mutation) {
              if ($(".food").hasClass("hover") == true){
                $(".box").removeClass("food")
                addTail();
                addFood();
                          }
                        });
                      });
    
          observer.observe(target, config);
    
       });
    
               }
    
      killSnake = function() {
        var config = { attributes: true, childList: true, characterData: true, subtree:true };
    
        $(".right-border, .left-border, .top-border, .bottom-border").each(function () {
          var target = this;
          var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
              console.log("Game over!")
            });
          });
    
        observer.observe(target, config);
      });
              }
    }
    
    addFood = function(){
      var random = Math.floor(Math.random() * (500 - 1 + 1)) + 1;
      $('*[data="' + random + '"]').addClass("food")
    
    };
    
    };
    &#13;
    .box {
      display: inline-block;
      border: 2px grey solid;
    
    }
    
    
    #container {
      display: block;
      border: 2px black solid;
      border-radius: 5px;
      font-size: 0;
      margin: 10px auto;
    }
    .hover {
      background-color: black;
    }
    
    .food {
      background-color: blue;
    }
    
    .white {
      background-color: white;
    }
    
    .right-border, .left-border, .top-border, .bottom-border {
      background: red;
      border: 2px red solid;
    
    }
    &#13;
    <!DOCTYPE html>
    
    <html lang="en">
    
    <head>
    
      <title>Snake</title>
    
      <meta charset="utf-8">
    
      <meta name="viewport" content="width=device-width, initial-scale=1">
    
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
      <link rel="stylesheet" href="style.css">
    
      <script type="text/javascript" src="script.js"></script>
    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    
    </head>
    
    <body>
    
      <div class="container">
    
        <center>
          <h1>Snake</h1>
          
          <div id="container"></div>
        </center>
    
      </div>
    
    </body>
    
    </html>
    &#13;
    &#13;
    &#13;