【问题标题】:Snake eating food (HTML5 canvas game)蛇吃食物(HTML5画布游戏)
【发布时间】:2014-01-31 11:25:48
【问题描述】:

这是我的第一篇文章,所以我希望我把所有的东西都正确地放在这里! :-P

我有问题。目前我正在和我的一个学校朋友做一个蛇游戏。我们正在使用 node.js 制作蛇游戏,因此我们可以创建多人蛇游戏。没有什么真正极端的只是基本的蛇游戏,但是有更多的玩家。

目前我已经创建了一个可以移动蛇的代码,并且还会在画布上随机放置食物(我正在使用 HTML5 Canvas 元素来玩游戏)。

现在我被困住了,因为我想创建一个让蛇吃掉食物然后长得更长的函数。据我所知,我拥有应有的功能,但由于某种原因它不起作用。我对 javascript 的了解非常基础,所以我在这里所做的一切对我来说都是全新的。我将把整个代码放在下面,这样你就可以看穿了。

我创建了 2 个 javascript 文件。一个里面有蛇代码,另一个里面有食物代码。我所指的函数在 Snake.prototype.move 下的 Snake 脚本中

我真的希望有人可以帮助我,这样我就可以继续我们的游戏了。

这是主要代码(蛇代码):

    var game;

$(document).ready(function(){
    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");
    var w = $("#canvas").width();
    var h = $("#canvas").height();
    var cw = 10;

    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, w, h);
    ctx.strokeStyle = "black";
    ctx.strokeRect(0, 0, w, h);


    var GameObject = function() {
        this.snakes = [];
        this.foods = [];
    }

    game = new GameObject();

    var snake = new Snake(1, 15, 'testnaam'); 
    snake.create();
    game.snakes.push(snake);
    game.foods.push(new Food(w, cw));

    function loop() {
        window.setTimeout(loop, 60);    

        ctx.clearRect(0, 0, w, h);

        if(game.snakes.lenght !== 0) {
            for(i = 0; i < game.snakes.length; i++) {
                var s = game.snakes[i];
                s.paint(ctx, game);
            }
        } else {

        }

        if(game.foods.length !== 0) {
            for(var i = 0; i < game.foods.length; i++) {
                var f = game.foods[i];
                f.paint(ctx);
            }
        } else {

        }

    }

    loop();


    document.addEventListener('keydown', function(e) {
        e.preventDefault();
        var key = e.which;
            if(key == "37" && snake.direction !="right") snake.direction = "left";
            else if(key == "38" && snake.direction !="down") snake.direction = "up";
            else if(key == "39" && snake.direction !="left") snake.direction = "right";
            else if(key == "40" && snake.direction !="up") snake.direction = "down";            

    }, false);


});

var Snake = function(player, length, alias){
    this.length = length;   
    this.pieces = [];       
    this.player = player;   
    this.position = {x: 0, y: 0}; 
    this.direction = "right";   
    this.color = this.color();
    this.getName = alias;

}


Snake.prototype.create = function(){ 
        for(var i = this.length -1; i >= 0; i--) {
        this.pieces.push({x: i, y: 0});
    }   
};
Snake.prototype.paint = function(ctx, game){

    this.move(game);
    for(var i = 0; i < this.pieces.length; i++){
            var c = this.pieces[i];

            ctx.fillStyle = this.color; 
            ctx.fillRect(c.x*10, c.y*10, 10, 10);   
        }
};

Snake.prototype.color = function(){ 
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
};

Snake.prototype.getName = function() {
    return this.alias;
}

Snake.prototype.getPosition = function() {
    return {x: this.x, y: this.y }
}

Snake.prototype.move =  function(game) { 
    var nx = this.pieces[0].x; 
    var ny = this.pieces[0].y;

    if(this.direction == "right")nx++; 
    else if(this.direction == "left")nx--;      
    else if(this.direction == "up")ny--;
    else if(this.direction == "down")ny++;


    if(Snake == game.foods[0].position.x && Snake == game.foods[0].position.y){ 
            console.log("raak");
            var tail = {
                x: nx,
                y: ny
            };
            Food.create();

    } else{
            var tail = this.pieces.pop();
            tail.x = nx; 
            tail.y = ny;
        }

    this.pieces.unshift(tail);  

};

Snake.prototype.collision = function(x, y, array){ 
    for(var i = 0; i < array.length; i++){
        if(array[i].x == x && array[i].y == y)
        return true;
    }   
    return false;
};

这是食物的代码

    var Food = function(w, cw){
    this.w = w;
    this.cw = cw;
    this.position = this.create();
    console.log(this.position);
};

Food.prototype.create = function(){

    var min = 0;
    var max = (this.w/this.cw);

    return position = {
        x: Math.round(min + Math.random()* (Math.abs(min)+(max)))*this.cw, 
        y: Math.round(min + Math.random()* (Math.abs(min)+(max)))*this.cw
    } 
};

Food.prototype.paint = function(ctx){
    ctx.fillStyle = "#000";
    ctx.fillRect(this.position.x,this.position.y,10,10) 
};

非常感谢!

【问题讨论】:

  • 如果你把这一切归结为你遇到的麻烦——蛇的生长,你可能会得到更多的帮助。
  • 首先看...你在loop()中有一个错字:game.snakes.lenght(长度拼写错误)。
  • 我已调整错字。没有改变问题,但感谢您看到!
  • 我很想在其中粘贴一段代码,但我不确定人们是否需要代码的其他部分或其他内容。所以我只是想把整个代码放进去^^

标签: javascript html canvas


【解决方案1】:

Live demo

我不得不摆弄它很多..代码中有很多奇怪之处,但这是我主要为了让它工作而搞砸的区域。

  Snake.prototype.move = function (game) {
       var nx = this.pieces[0].x;
       var ny = this.pieces[0].y;

       if (this.direction == "right") nx++;
       else if (this.direction == "left") nx--;
       else if (this.direction == "up") ny--;
       else if (this.direction == "down") ny++;

       /*
           * you werent testing the front pieces x and y, also since your multiplying the snake
           * pieces by 10, you need to divide the food positions by 10 for the coords to match up
       */
       if (this.pieces[0].x == game.foods[0].position.x / 10 && this.pieces[0].y == game.foods[0].position.y / 10) {
           console.log("raak");
           var tail = {
               x: nx,
               y: ny
           };
           // push your piece
           this.pieces.push(tail);
           // you have an array for prob to eventually have more than one on the screen.
           // for now i set food[0] to be a new piece of food. We dont have ref's to w and cw in this
           // func to I passed in the values.
           game.foods[0] = new Food(canvas.width, 10);

       } else {
           var tail = this.pieces.pop();
           tail.x = nx;
           tail.y = ny;
           // only unshift when we havent added a piece
           this.pieces.unshift(tail);
       }
   };

基本上,您根本没有测试位置,并且在检查时您没有将食物位置除以 10,因此蛇的位置永远不会与食物匹配。

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2011-12-21
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多