【问题标题】:Snake Game with Controller Buttons for Mobile Use **UPDATED**带有移动使用控制器按钮的蛇游戏**更新**
【发布时间】:2015-06-02 23:46:12
【问题描述】:

** 注意:我已经编辑了下面的 javascript 并链接到一个新的 JSFiddle,但仍然没有像键盘上的箭头键那样控制蛇的移动 **

我正在尝试为项目创建一个真正简单的蛇游戏,但需要它有按钮,以便游戏可以在移动设备上运行。这几乎就在那里,除了我需要让按钮控制屏幕上蛇的移动:

HTML:

<div class="game-container">

<div class="container">

    <div class="SplashScreen">
        <h1>
            Snake
        </h1>
        <h2>
            Click To Start.
        </h2>
        <input class="StartButton" type="button" value="Start" />
    </div>

    <div class="FinishScreen" style="display:none">
        <h1>
            Game Over
        </h1>
        <p>
            Your score was: <span id="score"></span>
        </p>
        <input class="StartButton" type="button" value="Restart" />
    </div>

    <canvas id="canvasArea" width="450" height="450" style="display:none;"></canvas>

</div>

<div class="button-pad">

    <div class="btn-up">
        <button type="submit" class="up">
            <img src="http://aaronblomberg.com/sites/ez/images/btn-up.png" />
        </button>
    </div>

    <div class="btn-right">
        <button type="submit" class="right">
            <img src="http://aaronblomberg.com/sites/ez/images/btn-right.png" />
        </button>
    </div>

    <div class="btn-down">
        <button type="submit" class="down">
            <img src="http://aaronblomberg.com/sites/ez/images/btn-down.png" />
        </button>
    </div>

    <div class="btn-left">
        <button type="submit" class="left">
            <img src="http://aaronblomberg.com/sites/ez/images/btn-left.png" />
        </button>
    </div>

</div>

jQuery:

( function( $ ) {

$( function() {



    $(document).ready(function () {

        $(".StartButton").click(function () {
            $(".SplashScreen").hide();
            $(".FinishScreen").hide();
            $("#canvasArea").show();
            init();
        });

        //Canvas stuff
        var canvas = $("#canvasArea")[0];
        var ctx = canvas.getContext("2d");
        var w = $("#canvasArea").width();
        var h = $("#canvasArea").height();

        //Lets save the cell width in a variable for easy control
        var sw = 10;
        var direction;
        var nd;
        var food;
        var score;

        //Lets create the snake now
        var snake_array; //an array of cells to make up the snake

        function endGame() {
            $("#canvasArea").hide();
            $("#score").text(score);
            $(".FinishScreen").show();
        }

        function init() {
            direction = "right"; //default direction
            nd = [];
            create_snake();
            create_food(); //Now we can see the food particle
            //finally lets display the score
            score = 0;

            //Lets move the snake now using a timer which will trigger the paint function
            //every 60ms
            if (typeof game_loop != "undefined") clearInterval(game_loop);
            game_loop = setInterval(paint, 60);
        }

        function create_snake() {
            var length = 5; //Length of the snake
            snake_array = []; //Empty array to start with
            for (var i = length - 1; i >= 0; i--) {
                //This will create a horizontal snake starting from the top left
                snake_array.push({
                    x: i,
                    y: 0
                });
            }
        }

        //Lets create the food now
        function create_food() {
            food = {
                x: Math.round(Math.random() * (w - sw) / sw),
                y: Math.round(Math.random() * (h - sw) / sw),


            };
            //This will create a cell with x/y between 0-44
            //Because there are 45(450/10) positions accross the rows and columns

        }

        //Lets paint the snake now
        function paint() {
            if (nd.length) {
                direction = nd.shift();
            }

            //To avoid the snake trail we need to paint the BG on every frame
            //Lets paint the canvas now
            ctx.fillStyle = "#0056a0";
            ctx.fillRect(0, 0, w, h);
            ctx.strokeStyle = "#ffffff";
            ctx.strokeRect(0, 0, w, h);

            //The movement code for the snake to come here.
            //The logic is simple
            //Pop out the tail cell and place it infront of the head cell
            var nx = snake_array[0].x;
            var ny = snake_array[0].y;

            //These were the position of the head cell.
            //We will increment it to get the new head position
            //Lets add proper direction based movement now
            if (direction == "right") nx++;
            else if (direction == "left") nx--;
            else if (direction == "up") ny--;
            else if (direction == "down") ny++;

            //Lets add the game over clauses now
            //This will restart the game if the snake hits the wall
            //Lets add the code for body collision
            //Now if the head of the snake bumps into its body, the game will restart
            if (nx == -1 || nx == w / sw || ny == -1 || ny == h / sw || check_collision(nx, ny, snake_array)) {
                //end game
                return endGame();
            }

            //Lets write the code to make the snake eat the food
            //The logic is simple
            //If the new head position matches with that of the food,
            //Create a new head instead of moving the tail
            if (nx == food.x && ny == food.y) {
                var tail = {
                    x: nx,
                    y: ny
                };
                score++;

                //Create new food
                create_food();
            } else

            {
                var tail = snake_array.pop(); //pops out the last cell
                tail.x = nx;
                tail.y = ny;
            }

            //The snake can now eat the food.
            snake_array.unshift(tail); //puts back the tail as the first cell

            for (var i = 0; i < snake_array.length; i++) {
                var c = snake_array[i];

                //Lets paint 10px wide cells
                paint_cell(c.x, c.y);
            }

            //Lets paint the food
            paint_cell(food.x, food.y);

            //Lets paint the score
            var score_text = "Score: " + score;
            ctx.fillStyle = "#ffffff";
            ctx.fillText(score_text, 5, h - 5);

            //Set the font and font size
            ctx.font = '12px Arial';

            //position of the fill text counter
            ctx.fillText(itemCounter, 10, 10);

        }

        //Lets first create a generic function to paint cells
        function paint_cell(x, y) {
            ctx.fillStyle = "#d8d8d8";
            ctx.fillRect(x * sw, y * sw, sw, sw);
        }

        function check_collision(x, y, array) {
            //This function will check if the provided x/y coordinates exist
            //in an array of cells or not
            for (var i = 0; i < array.length; i++) {
                if (array[i].x == x && array[i].y == y) return true;
            }

            return false;
        }

        // Lets prevent the default browser action with arrow key usage
        var keys = {};
        window.addEventListener("keydown",
            function(e){
                keys[e.keyCode] = true;
                switch(e.keyCode){
                    case 37: case 39: case 38:  case 40: // Arrow keys
                    case 32: e.preventDefault(); break; // Space
                    default: break; // do not block other keys
                }
            },
        false);
        window.addEventListener('keyup',
            function(e){
                keys[e.keyCode] = false;
            },
        false);


        //Lets add the keyboard controls now
        $(document).keydown(function (e) {
            var key = e.which;
            var td;
            if (nd.length) {
                var td = nd[nd.length - 1];

            } else {
                td = direction;
            }

            //We will add another clause to prevent reverse gear
            if (key == "37" && td != "right") nd.push("left");
            else if (key == "38" && td != "down") nd.push("up");
            else if (key == "39" && td != "left") nd.push("right");
            else if (key == "40" && td != "up") nd.push("down");

            //The snake is now keyboard controllable

        });

    });


    $(document).on('click', '.button-pad > button', function(e) {
        if ($(this).hasClass('left-btn')) {
            e = 37;
        }
        else if ($(this).hasClass('up-btn')) {
            e = 38;
        }
        else if ($(this).hasClass('right-btn')) {
            e = 39;
        }
        else if ($(this).hasClass('down-btn')) {
            e = 40;
        }
        $.Event("keydown", {keyCode: e});
    }); 

});

})( jQuery );

JSFiddle

http://jsfiddle.net/aaronblomberg/9w3gk3ma/3/

这几乎是我需要它的地方,但我需要向上、向下、向左和向右箭头按钮来控制蛇...

任何帮助将不胜感激。

【问题讨论】:

  • 好的,我建议您添加按钮,然后使用这些按钮而不是键。
  • 停止依赖于键盘。无论事件在何处触发,都具有管理方向的功能。然后为调用该“moveDirection”按钮的键盘和按钮单击添加事件侦听器。您需要学习将游戏逻辑与演示逻辑分开。就目前而言,这段代码有点到处都是,在某些地方是多余的(两个关键事件监听器?jQuery 为你处理)。
  • 为什么会有两个 wait for document ready 嵌套函数?这很傻
  • 将所有状态放在一堆闭包变量中与使用全局变量一样糟糕。为什么不将不同类型的状态分解为有限状态机并将它们与消息(函数调用或自定义事件)链接在一起。

标签: javascript jquery jquery-mobile html5-canvas


【解决方案1】:

你冷做这样的东西:

var isMobile;
checkMobile = function() {
    if ($(window).width() <= 766) {
        isMobile = true;
    }
    else {
        isMobile = false;
    }
}


$(window).resize(checkMobile());
$(document).ready(checkMobile());    

if (isMobile) {
    $('.button-pad').show();
}
else {
    $('.button-pad').hide();
}

.button-pad:

$(document).on('click', '.button-pad > button', function(e) {
    if ($(this).hasClass('left')) {
        e = 37;
    }
    else if ($(this).hasClass('up')) {
        e = 38;
    }
    else if ($(this).hasClass('right')) {
        e = 39;
    }
    else if ($(this).hasClass('down')) {
        e = 40;
    }
    $.Event("keydown", {keyCode: e});
}

【讨论】:

  • 谢谢,我创建了一个新的 JSFiddle 并进行了一些调整。但是,“按钮”仍然不能控制蛇的运动。看看这里:jsfiddle.net/aaronblomberg/9w3gk3ma/3
  • 我不明白为什么要附加到键盘事件然后附加按钮单击以模拟键盘,而您只需创建一个处理移动命令的changeDirection 函数并让每个事件侦听器确定要发送哪个命令?
  • @Sukima:我正在添加语法,而不是更改,我会制作一个 Snake 函数()并将所有东西都扔在那里,(吃的食物,方向,行为)我试图让这个工作到目前为止做了什么。 Aaron Blomberg:问题是 JQuery.Event 由于某种原因没有被触发,并且 jquery 语法没有很好地格式化为您的 html,还必须检查。
【解决方案2】:

这是给贪吃蛇游戏添加moile控制的代码; (如果你想要蛇游戏的完整代码,请评论);

//Here is javascript;

// left key
  function l() {
    if(snake.dx === 0) {
      snake.dx = -grid;
      snake.dy = 0;
    }
  }

  // up key
  function u() {
    if(snake.dy === 0) {
      snake.dy = -grid;
      snake.dx = 0;
    }
  }

  // right key 
  function r() {
    if(snake.dx === 0) {
      snake.dx = grid;
      snake.dy = 0;
    }
  }
  // down key 
  function d() {
    if(snake.dy === 0) {
      snake.dy = grid;
      snake.dx = 0;
    }
  }

这里是 HTML;

<div>
  <button onclick="u()" type="button" id="U">U</button>
  <button onclick="l()" type="button" id="L">L</button>
  <button onclick="r()" type="button" id="R">R</button>
  <button onclick="d()" type="button" id="D">D</button>
</div>

描述: 我只是在 html 页面中添加了四个按钮,在 js 中创建了四个函数,它们将移动蛇,因为它应该向不同的方向移动,并将它们添加到 'onclick' 属性中分别是不同的按钮。

【讨论】:

  • 您也可以将这些功能用于箭头键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 2015-07-04
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多