首页 > 解决方案 > 在 Jquery 制作的 Snake 游戏中计算分数

问题描述

我使用 jQuery 制作了一个蛇游戏。现在我想给它加分。我添加了一个变量“分数”并在每次蛇吃食物并尝试在控制台上打印它时增加它,但我得到的只是“NaN”。有人请帮助我正确获得分数...

由于代码很大时无法用更少的文字发布,所以我正在输入所有这些无意义的单词。请原谅我

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
   init();
});
var score;
var move;
function init() {
    board.initBoard();
    createSnake();
    food.createFood();
}

function play() {
    $('.newGame').hide();
    $('.playgame').hide();
    moveSnake();
    getSnakeDir();
}

function gameover() {
 console.log(score);
    clearTimeout(move);
    $('.newGame').show();
}

function playGame() {
score=0;
    $('#gameboard').empty();
    $('.newGame').hide();
    init();
    play();
}

var board = {
    DIM: 20,
    initBoard: function() {
        for (var i = 0; i < board.DIM; i++) {
            var row = $('<div class="row-' + i + '"></div>');
            
            for (var j = 0; j < board.DIM; j++) {
                var col = ('<div class="col-' + j + '-' + i + '"></div>');
                $(row).append(col);
            }
            $("#gameboard").append(row);
        }
    }
}

var snake = {
    position: ['10-10', '10-11', '10-12'],
    direction: 'r',
    speed: 200,
};

function createSnake() {
    $('.col-10-10').addClass('snake');
    $('.col-11-10').addClass('snake');
    snake.position = ['10-10', '10-11', '10-12'];
}

function getSnakeDir() {
    $(document).keydown(function(event) {
        //event.preventDefault();
        if (event.which == 38) {
            snake.direction = 'u';
        } else if (event.which == 39) {
            snake.direction = 'r';
        } else if (event.which == 40) {
            snake.direction = 'd';
        } else if (event.which == 37) {
            snake.direction = 'l';
        }
    });
}

function moveSnake() {
    var tail = snake.position.pop();
    $('.col-' + tail).removeClass('snake');
    var coords = snake.position[0].split('-');
    var x = parseInt(coords[0]);
    var y = parseInt(coords[1]);

    if (snake.direction == 'r') {
        x = x + 1;
    } else if (snake.direction == 'd') {
        y = y + 1;
    } else if (snake.direction == 'l') {
        x = x - 1;
    } else if (snake.direction == 'u') {
        y = y - 1;
    }
    
    var currentcoords = x + '-' + y;
    snake.position.unshift(currentcoords);

    $('.col-' + currentcoords).addClass('snake');

    //when snake eats food
    if (currentcoords == food.coords) {
        console.log('true');
        score= score+10;
        console.log(score);
        $('.col-' + food.coords).removeClass('food');
        snake.position.push(tail);
        food.createFood();
    }

    //game over
    if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
        gameover();
        return;
    
    }

    //if snake touch itself
    if (hitItself(snake.position) == true) {
        gameover();
        return;
    }
    
    move=setTimeout(moveSnake, 200);
}

var food = {
    coords: "",

    createFood: function() {
        var x = Math.floor(Math.random() * (board.DIM-1)) + 1;
        var y = Math.floor(Math.random() * (board.DIM-1)) + 1;
        var fruitCoords = x + '-' + y;
        $('.col-' + fruitCoords).addClass('food');
        food.coords = fruitCoords;
    },
}

function hitItself(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}
</script>
<style>
.buttonnewgame {
     position: relative;
}

.newGame {
    position: absolute;
    top: 45%;
    left: 20%;
    padding: 15px;
    font-size: 1em;
     font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    
    font-weight: bold;
    font-size: 1em;
    background-color: #FF69B4;
       
}
.instructions
{
margin-left: 5px;
float: left;
position : relative;
color: #c603fc;
    font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 15px;
    font-weight: bold;

}
.gameContainer{
    width:100%;
}

#gameboard {
    background-color:#eee;
    padding:3px;
}

.playgame {
    position: absolute;
    top: 45%;
    left: 20%;
    padding: 15px;
    font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    
    font-weight: bold;
    font-size: 1em;
    background-color: #FF69B4;
       
}

/* styling the board */
div[class^='row'] {
    height: 15px;
    text-align: center;
}

div[class*='col']{
    display: inline-block;
    border: 1px solid grey;
    width: 15px;
    height: 15px;
}

/*display the snake*/
.snake {

    background-color: blue;
    z-index: 99;
}

.food {
    background: red;
    z-index: 99;
}
</style>
<table>
<tr>
<td><div class="game">
    <div class="buttonnewgame">
       <center><input type="button" name="New game" value="New game" class="newGame" style="display:none;" onclick="playGame()" />
        <button class="playgame" onclick="play()">Play Game</button></center> 
        <div class="gameContainer">
      
            <div id="gameboard">
                <!-- snake game in here -->
            </div>
        </div>
        </div></div></td>
        <td width="150">
    <div class="instructions" >
      OBJECT: Get as many pieces of "food" as possible using your arrow keys.  Each time you do this, you will grow.   You want to try to get as big as possible without crashing into a wall or back onto yourself.  Good Luck!!
      </div></td></tr></table>

标签: htmljquery

解决方案


score最初undefined是因为你在声明它时没有给它一个值。

加10undefined显然是NaN

相反,score像这样声明:var score = 0;.

尝试这个:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  jQuery(document).ready(function($) {
    init();
  });
  var score = 0;
  var move;

  function init() {
    board.initBoard();
    createSnake();
    food.createFood();
  }

  function play() {
    $('.newGame').hide();
    $('.playgame').hide();
    moveSnake();
    getSnakeDir();
  }

  function gameover() {
    console.log(score);
    clearTimeout(move);
    $('.newGame').show();
  }

  function playGame() {
    score = 0;
    $('#gameboard').empty();
    $('.newGame').hide();
    init();
    play();
  }

  var board = {
    DIM: 20,
    initBoard: function() {
      for (var i = 0; i < board.DIM; i++) {
        var row = $('<div class="row-' + i + '"></div>');

        for (var j = 0; j < board.DIM; j++) {
          var col = ('<div class="col-' + j + '-' + i + '"></div>');
          $(row).append(col);
        }
        $("#gameboard").append(row);
      }
    }
  }

  var snake = {
    position: ['10-10', '10-11', '10-12'],
    direction: 'r',
    speed: 200,
  };

  function createSnake() {
    $('.col-10-10').addClass('snake');
    $('.col-11-10').addClass('snake');
    snake.position = ['10-10', '10-11', '10-12'];
  }

  function getSnakeDir() {
    $(document).keydown(function(event) {
      //event.preventDefault();
      if (event.which == 38) {
        snake.direction = 'u';
      } else if (event.which == 39) {
        snake.direction = 'r';
      } else if (event.which == 40) {
        snake.direction = 'd';
      } else if (event.which == 37) {
        snake.direction = 'l';
      }
    });
  }

  function moveSnake() {
    var tail = snake.position.pop();
    $('.col-' + tail).removeClass('snake');
    var coords = snake.position[0].split('-');
    var x = parseInt(coords[0]);
    var y = parseInt(coords[1]);

    if (snake.direction == 'r') {
      x = x + 1;
    } else if (snake.direction == 'd') {
      y = y + 1;
    } else if (snake.direction == 'l') {
      x = x - 1;
    } else if (snake.direction == 'u') {
      y = y - 1;
    }

    var currentcoords = x + '-' + y;
    snake.position.unshift(currentcoords);

    $('.col-' + currentcoords).addClass('snake');

    //when snake eats food
    if (currentcoords == food.coords) {
      console.log('true');
      score = score + 10;
      console.log(score);
      $('.col-' + food.coords).removeClass('food');
      snake.position.push(tail);
      food.createFood();
    }

    //game over
    if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
      gameover();
      return;

    }

    //if snake touch itself
    if (hitItself(snake.position) == true) {
      gameover();
      return;
    }

    move = setTimeout(moveSnake, 200);
  }

  var food = {
    coords: "",

    createFood: function() {
      var x = Math.floor(Math.random() * (board.DIM - 1)) + 1;
      var y = Math.floor(Math.random() * (board.DIM - 1)) + 1;
      var fruitCoords = x + '-' + y;
      $('.col-' + fruitCoords).addClass('food');
      food.coords = fruitCoords;
    },
  }

  function hitItself(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
      var value = array[i];
      if (value in valuesSoFar) {
        return true;
      }
      valuesSoFar[value] = true;
    }
    return false;
  }
</script>
<style>
  .buttonnewgame {
    position: relative;
  }
  
  .newGame {
    position: absolute;
    top: 45%;
    left: 20%;
    padding: 15px;
    font-size: 1em;
    font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-weight: bold;
    font-size: 1em;
    background-color: #FF69B4;
  }
  
  .instructions {
    margin-left: 5px;
    float: left;
    position: relative;
    color: #c603fc;
    font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 15px;
    font-weight: bold;
  }
  
  .gameContainer {
    width: 100%;
  }
  
  #gameboard {
    background-color: #eee;
    padding: 3px;
  }
  
  .playgame {
    position: absolute;
    top: 45%;
    left: 20%;
    padding: 15px;
    font: normal;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-weight: bold;
    font-size: 1em;
    background-color: #FF69B4;
  }
  /* styling the board */
  
  div[class^='row'] {
    height: 15px;
    text-align: center;
  }
  
  div[class*='col'] {
    display: inline-block;
    border: 1px solid grey;
    width: 15px;
    height: 15px;
  }
  /*display the snake*/
  
  .snake {
    background-color: blue;
    z-index: 99;
  }
  
  .food {
    background: red;
    z-index: 99;
  }
</style>
<table>
  <tr>
    <td>
      <div class="game">
        <div class="buttonnewgame">
          <center><input type="button" name="New game" value="New game" class="newGame" style="display:none;" onclick="playGame()" />
            <button class="playgame" onclick="play()">Play Game</button></center>
          <div class="gameContainer">

            <div id="gameboard">
              <!-- snake game in here -->
            </div>
          </div>
        </div>
      </div>
    </td>
    <td width="150">
      <div class="instructions">
        OBJECT: Get as many pieces of "food" as possible using your arrow keys. Each time you do this, you will grow. You want to try to get as big as possible without crashing into a wall or back onto yourself. Good Luck!!
      </div>
    </td>
  </tr>
</table>


推荐阅读