蛇吃食物(HTML5帆布游戏)

时间:2014-01-12 19:13:26

标签: javascript html5 canvas

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

我有问题。目前,我和我的一位学校朋友正在进行蛇形游戏。我们正在使用node.js进行蛇游戏,因此我们可以创建一个多人游戏蛇游戏。没有什么比基本的蛇游戏更真实,但随后有更多玩家。

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

现在我被卡住了,因为我想创造一种功能,让蛇吃食物然后长得更长。据我所知,我有应有的功能,但由于某种原因,它不起作用。我对javascript的了解非常基础,所以我在这里做的对我来说都是新的。我将整个代码放在下面,以便您可以看到它。

我创建了2个javascript文件。一个有蛇代码,另一个有食物代码。我所指的功能是在Snake.prototype.move

下的Snake脚本中

我真的希望有人可以帮助我,这样我就可以开始游戏了。

这是主要代码(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) 
};

非常感谢!

1 个答案:

答案 0 :(得分: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,所以蛇的位置永远不会与食物相匹配。