贪吃蛇 HTML5 Canvas代码

首先建立一个二维类

function Class_Dim(cx, cy){
    var x = cx;
    var y = cy;
    this.getx = function(){
        return x;
    };
    this.gety = function(){
        return y;
    };
    this.setx = function(tx){
        x = tx;
    };
    this.sety = function(ty){
        y = ty;
    };
};

然后设置一些全局变量

var gameRunning = true;//游戏是否进行中
var canvas = document.getElementById(‘scen‘);//获取canvas
var sceneWidth = 10;//格子列数
var sceneHeight = 10;//格子行数
var canvasWidth = canvas.width;//canvas宽度
var canvasHeight = canvas.height;//canvas长度
var unitWidth = canvasWidth / sceneWidth;//
var unitHeight = canvasHeight / sceneHeight;
var snake = new Array();
var addBlocks = new Class_Dim(Math.floor((sceneWidth-1) * Math.random()) + 1, Math.floor(((sceneHeight-1) * Math.random()) + 1));//食物
var snakeDir = new Class_Dim(0, -1);//贪吃蛇移动方向
snake.unshift(new Class_Dim(sceneWidth / 2, sceneHeight / 2));//初始化

下面是绘制蛇的函数

function drawSnake(){
    var context = canvas.getContext(‘2d‘);
    context.fillStyle = ‘#223344‘;
    for(var i=0;i<snake.length;i++){
        context.fillRect(snake[i].getx() * unitWidth, snake[i].gety() * unitHeight, unitWidth, unitHeight);
    };
};

然后是绘制食物(可以考虑做成数组)


function drawAddBlocks(){
    var context = canvas.getContext(‘2d‘);
    context.fillStyle = ‘#66FF99‘;
    context.fillRect(addBlocks.getx() * unitWidth, addBlocks.gety() * unitHeight, unitWidth, unitHeight);
}

然后是贪吃蛇根据方向移动,蛇身每一段都存放在一个有序列内
首先第一个元素根据方向移动,下一个元素继承上一个元素的位置,即是贪吃蛇整体的移动方式。
判断蛇是否移动后死亡,只需判断蛇头位置。

function moveSnake(){
    var rememberx = snake[0].getx();
    var remembery = snake[0].gety();
    var isEated = false;
    var eatedBlockPointer;
    if(addBlocks.getx() == rememberx + snakeDir.getx() && addBlocks.gety() == remembery + snakeDir.gety()){
        isEated = true;
    };

    if(isEated){
        snake.unshift(new Class_Dim(addBlocks.getx(), addBlocks.gety()));
        do{
            var isLoop = false;
            addBlocks = new Class_Dim(Math.floor((sceneWidth-1) * Math.random()) + 1, Math.floor(((sceneHeight-1) * Math.random()) + 1));
            for(var i = 0; i < snake.length; i++){
                if(addBlocks.getx() == snake[i].getx() && addBlocks.gety() == snake[i].gety()) isLoop = true;
            }
        }while(isLoop);


    }
    else{
        snake[0].setx(rememberx + snakeDir.getx());
        snake[0].sety(remembery + snakeDir.gety());

        if(snake[0].getx() < 0 || snake[0].getx() >= sceneWidth || snake[0].gety() < 0 || snake[0].gety() >= sceneHeight){
            gameRunning = false;
        };

        for(var i=1;i<snake.length;i++){
            var tmpx = snake[i].getx();
            var tmpy = snake[i].gety();
            if(snake[0].getx() == tmpx && snake[0].gety() == tmpy){
                gameRunning = false;
            };
            snake[i].setx(rememberx);
            snake[i].sety(remembery);
            rememberx = tmpx;
            remembery = tmpy;
        };
    };

};

下面是完整代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset=‘utf-8‘ />
    <title>贪吃蛇</title>
</head>
<body>
<canvas id="scen" width=‘600‘ height=‘600‘></canvas>

<script>
function Class_Dim(cx, cy){
    var x = cx;
    var y = cy;
    this.getx = function(){
        return x;
    };
    this.gety = function(){
        return y;
    };
    this.setx = function(tx){
        x = tx;
    };
    this.sety = function(ty){
        y = ty;
    };
};
var gameRunning = true;
var canvas = document.getElementById(‘scen‘);
var sceneWidth = 10;
var sceneHeight = 10;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var unitWidth = canvasWidth / sceneWidth;
var unitHeight = canvasHeight / sceneHeight;
var snake = new Array();
var addBlocks = new Class_Dim(Math.floor((sceneWidth-1) * Math.random()) + 1, Math.floor(((sceneHeight-1) * Math.random()) + 1));
var snakeDir = new Class_Dim(0, -1);
snake.unshift(new Class_Dim(sceneWidth / 2, sceneHeight / 2));

function drawSnake(){
    var context = canvas.getContext(‘2d‘);
    context.fillStyle = ‘#223344‘;
    for(var i=0;i<snake.length;i++){
        context.fillRect(snake[i].getx() * unitWidth, snake[i].gety() * unitHeight, unitWidth, unitHeight);
    };
};

function drawAddBlocks(){
    var context = canvas.getContext(‘2d‘);
    context.fillStyle = ‘#66FF99‘;
    context.fillRect(addBlocks.getx() * unitWidth, addBlocks.gety() * unitHeight, unitWidth, unitHeight);
}

function clearAll(){
    var context = canvas.getContext(‘2d‘);
    context.clearRect(0, 0, canvasWidth, canvasWidth);
}

function moveSnake(){
    var rememberx = snake[0].getx();
    var remembery = snake[0].gety();
    var isEated = false;
    var eatedBlockPointer;
    if(addBlocks.getx() == rememberx + snakeDir.getx() && addBlocks.gety() == remembery + snakeDir.gety()){
        isEated = true;
    };

    if(isEated){
        snake.unshift(new Class_Dim(addBlocks.getx(), addBlocks.gety()));
        do{
            var isLoop = false;
            addBlocks = new Class_Dim(Math.floor((sceneWidth-1) * Math.random()) + 1, Math.floor(((sceneHeight-1) * Math.random()) + 1));
            for(var i = 0; i < snake.length; i++){
                if(addBlocks.getx() == snake[i].getx() && addBlocks.gety() == snake[i].gety()) isLoop = true;
            }
        }while(isLoop);


    }
    else{
        snake[0].setx(rememberx + snakeDir.getx());
        snake[0].sety(remembery + snakeDir.gety());

        if(snake[0].getx() < 0 || snake[0].getx() >= sceneWidth || snake[0].gety() < 0 || snake[0].gety() >= sceneHeight){
            gameRunning = false;
        };

        for(var i=1;i<snake.length;i++){
            var tmpx = snake[i].getx();
            var tmpy = snake[i].gety();
            if(snake[0].getx() == tmpx && snake[0].gety() == tmpy){
                gameRunning = false;
            };
            snake[i].setx(rememberx);
            snake[i].sety(remembery);
            rememberx = tmpx;
            remembery = tmpy;
        };
    };

};

function drawNet(){
    var context = canvas.getContext(‘2d‘);
    for(var loopPointer = 0; loopPointer <= sceneWidth; loopPointer++)
    {
        context.beginPath();
        context.moveTo(loopPointer * unitWidth, 0);
        context.lineTo(loopPointer * unitWidth, canvasHeight);
        context.lineWidth = 1.0;
        context.strokeStyle = ‘#9988CC‘;
        context.stroke();
    };
    for(var loopPointer = 0; loopPointer <= sceneHeight; loopPointer++){
        context.beginPath();
        context.moveTo(0, loopPointer * unitHeight);
        context.lineTo(canvasWidth, loopPointer * unitHeight);
        context.lineWidth = 1.0;
        context.strokeStyle = ‘#9988CC‘;
        context.stroke();
    };
};

function run(){
        moveSnake();
    if(gameRunning){
        clearAll();
        drawNet();
        drawSnake();
        drawAddBlocks();
    }

}

document.onkeypress = function(e){
    switch(e.which){
        case 119:
            if(snakeDir.gety() != 1){
                snakeDir = new Class_Dim(0, -1);
            }
        break;
        case 115:
            if(snakeDir.gety() != -1){
                snakeDir = new Class_Dim(0, 1);
            }
        break;
        case 97:
            if(snakeDir.getx() != 1){
                snakeDir = new Class_Dim(-1, 0);
            }
        break;
        case 100:
            if(snakeDir.getx() != -1){
                snakeDir = new Class_Dim(1, 0);
            }
        break;
    }
}

setInterval("run()",300);

</script>
</body>
</html>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。