学习 JS/JQuQuery 尝试创建“开始”按钮

learning js/jquery trying to create a start button

本文关键字:开始 按钮 创建 JS JQuQuery 学习      更新时间:2023-09-26

在js/jquery上上上课,游戏运行良好,但你必须刷新页面才能重新启动它。 我正在尝试创建一个按钮并让它"重新启动游戏",但我就是无法让它工作。

任何帮助/资源/建议将不胜感激!!

索引.html:

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src='https://code.jquery.com/jquery-2.1.3.js'></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src='js/script.js'></script>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="row-md-6 row-md-offset-3">
            <h1>The Snake Game!!</h1>
            <canvas class='snake-game' width ='600px' height='500px'></canvas>
            <button type='button' class='start'>Start Game</button>
            </div>
        </div>
    </div>
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

js/jquery

jQuery(document).ready(function(){
    var snakeCanvas = $('canvas.snake-game')[0],
    context = snakeCanvas.getContext('2d'),
    width = snakeCanvas.width,
    height = snakeCanvas.height,
    snakeSize = 10,
    snake = [
        { 'x': 0,'y': 0 },
        { 'x': 1, 'y': 0 },
        { 'x': 2, 'y': 0 },
        { 'x': 3, 'y': 0 },
        { 'x': 4, 'y': 0 },
        ],
        direction = 'right',
        gameSpeed = 50,
        score = 0;
    var foodX,
        foodY,
        gameLoop
    start();
    $('.start')on('click', function(){
        start();
    })
    function createNewFood(){
        foodX = parseInt(Math.random() * width/snakeSize);
        foodY = parseInt(Math.random() * yeah itheight/snakeSize);
    }
    function checkCollision(snakeArrayInput, foodXinput, foodYinput){
        var collision = 'nothing';
        snakeArrayInput.every(function(element){
          if(element.x == foodXinput && element.y == foodYinput){
            collision = "food";
            return false;
          }else if(element.x == -1 ||
                   element.y == -1 ||
                   element.x == width/snakeSize ||
                   element.y == height/snakeSize){
            collision = "wall";
            return false;
          }else{
            return true;
          }
        });
        return collision;
  }
    paint(0, 0, width, height, 'white', 'black');
    function start(){
        createNewFood();
        gameLoop = setInterval(reDraw, gameSpeed);    
    }
    function stop(){
        clearInterval(gameLoop);
    }

    function reDraw(){
        drawBg();
        drawSnake(snake);
        drawFood();
        drawScore();
        //checkCollision(snakeArrayInput, foodXinput, foodYinput);
        var collisionStatus = checkCollision(snake, foodX, foodY);
        if(collisionStatus == 'food'){
            score ++;
            createNewFood();
            snake.unshift(updateDirection(snake, direction));
        } else if (collisionStatus == 'wall'){
            stop();
            alert('Your score was: ' + score);
            score = 0;
        }
    };
    function drawFood(){
        paint(foodX*snakeSize, foodY*snakeSize, snakeSize, snakeSize, 'green', 'black');
    }
    function drawScore(){
        context.fillStyle = 'grey';
        context.fillText('Score: ' + score, width-596, height-6);
    }
    function drawBg(){
        paint(0,0,width, height, 'white', 'black');
    }
    function drawSnake(snakeInput){
        updateSnake(snakeInput);
        snakeInput.forEach(function(element){
            paint(element.x*10, element.y*10, snakeSize, snakeSize, 'orange', 'black');
        });
    }
    function paint(x, y, w, h, bgColor, borderColor){
        context.fillStyle = bgColor;
        context.fillRect(x, y, w, h);
        context.strokeStyle = borderColor;
        context.strokeRect(x, y, w, h);
    }
    function updateSnake(snakeInput){
    snakeInput.shift();
    snakeInput.push(updateDirection(snakeInput, direction));
    }
    function updateDirection(snakeInput, direction){
        var cellX = snakeInput[snakeInput.length-1].x;
        var cellY = snakeInput[snakeInput.length-1].y;
        if(direction == 'right'){
            cellX = cellX + 1;
        } else if (direction == 'left') {
            cellX = cellX - 1;
        } else if (direction == 'top') {
            cellY = cellY - 1;
        } else if (direction == 'bottom') {
            cellY = cellY + 1;
        }
        return {'x':cellX, 'y':cellY};
    }
    $(document).on('keydown', function(e){
        if(e.which == '37' && direction != 'right'){ // left keydown
          direction = 'left';
        }else if(e.which == '38' && direction != 'bottom'){ // top keydown
          direction = 'top';
        }else if(e.which == '39' && direction != 'left'){ // right keydown
          direction = 'right';
        }else if(e.which == '40' && direction != 'top'){ // bottom keydown
          direction = 'bottom';
        }
  });
});
$('.start')on('click', function(){
        start();
    })

缺少点,更改为$('.start').on('click', function(){

function createNewFood(){
        foodX = parseInt(Math.random() * width/snakeSize);
        foodY = parseInt(Math.random() * yeah itheight/snakeSize);
    }

foodY = parseInt(Math.random() * yeah itheight/snakeSize);更改为 foodY = parseInt(Math.random() * height/snakeSize);

编辑:因此,如果您希望将开始游戏设置为可玩状态,则需要重新初始化游戏参数,以下是更改:

function start(){
    // Set init states.
    snakeSize = 10,
    snake = [
    { 'x': 0,'y': 0 },
    { 'x': 1, 'y': 0 },
    { 'x': 2, 'y': 0 },
    { 'x': 3, 'y': 0 },
    { 'x': 4, 'y': 0 },
    ],
    direction = 'right',
    gameSpeed = 50,
    score = 0;
    createNewFood();
    gameLoop = setInterval(reDraw, gameSpeed);    
}

修复了它,并且有效,然后开始游戏,请重新启动可玩的游戏。

小提琴