首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Jquery中制作的Snake游戏中计算分数

在Jquery中制作的Snake游戏中计算分数
EN

Stack Overflow用户
提问于 2021-06-28 01:17:04
回答 1查看 31关注 0票数 1

我用jQuery做了一个蛇游戏。现在我想给它加个分数。我添加了一个变量"score“,并在每次蛇吃东西时将其递增,并试图在控制台上打印它,但得到的结果是"NaN”。有没有人能帮我弄到正确的分数…

因为当代码很大的时候,它不能用更少的文本来发布,所以我输入了所有这些无意义的单词。请原谅我所做的一切

代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-28 01:28:46

score最初是undefined,因为在声明它时没有给它赋值。

undefined上加上10显然是NaN

相反,可以像这样声明scorevar score = 0;

试试这个:

代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68153627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档