HTML5贪吃蛇游戏

以保存对javascript的些许理解

/****************/
/*****game.js****/
/****************/
Array.prototype.remove = function (obj) {
    for (var i = 0, l = this.length; i < l; i++) {

        if (this[i] == obj) {
            this.splice(i, 1);
            break;
        }
    }
}

var Game = {
    //循环ID
    timeId: -1,
    //context2d对象
    gamebg: null,
    //游戏背景信息
    gameinfo: {},
    //开始按钮
    btn: null,
    //初始化
    snake: null,
    food: null,
    init: function () {
        //获取游戏背景dom
        var game_dom = document.getElementById('gamebg'),
        This = this;
        //设置游戏背景信息
        this.gameinfo = {
            width: game_dom.clientWidth,
            height: game_dom.clientHeight,
            left: game_dom.offsetLeft,
            top: game_dom.offsetTop
        };
        //获取context2d对象
        this.gamebg = game_dom.getContext('2d');
        //绑定键盘按下事件
        document.onkeydown = function (e) { This.keyDown(e); };
        //创建小球
        this.snake = new Snake(7, this.gameinfo.width, this.gameinfo.height);
        this.food = new Food(100, 100, 4, 'red');
        //this.createFood();
    },

    keyDown: function (e) {
        var d = this.snake.direction;
        switch (e.keyCode) {
            case 37:
                d = 9;
                break;
            case 38:
                d = 12;
                break;
            case 39:
                d = 3;
                break;
            case 40:
                d = 6;
                break;
            case 32:
                this.pause(document.getElementById('Button2'));
                break;
        }
        if (Math.abs(this.snake.direction - d) != 6) {
            this.snake.oldDirection = this.snake.direction;
            this.snake.direction = d;
        }
        else {
            this.snake.back = 1;
        }
    },

    //btn:开始按钮dom
    start: function (btn) {

        if (this.btn) this.reset();

        this.btn = btn;
        this.btn.disabled = 'disabled';
        var This = this;
        this.init();
        //开始画画
        this.timeId = setInterval(function () {
            This.process();
        }, 80);
    },

    process: function () {
        //清除画面
        this.gamebg.clearRect(0, 0, this.gameinfo.width, this.gameinfo.height);
        this.snake.update(this.food);
        var body = this.snake.Body;
        Canvas.arc(this.gamebg, this.food.X, this.food.Y, this.food.Radius, this.food.Color);
        for (var i = 0; i < body.length; i++) {
            Canvas.arc(this.gamebg, body[i].X, body[i].Y, body[i].Radius, body[i].Color);
        }

        //判断游戏是否结束
        if (this.snake.Body.length == 0) {
            clearInterval(this.timeId);
            var score = document.getElementById("score");
            alert('您的分数是:' + score.innerHTML);
            this.btn.disabled = '';
        }
    },

    //重置游戏数据
    reset: function () {
        this.food = null;
        this.snake = null;
        this.timeId = -1;
        this.gamebg = null;
        this.gameinfo = {};
        var score = document.getElementById("score");
        score.innerHTML = 0;
    },

    pause: function (btn) {
        if (btn.value == 'Pause') {
            clearInterval(this.timeId);
            btn.value = 'Run';
        }
        else if (btn.value == 'Run') {
            btn.value = 'Pause';
            var This = this;
            this.timeId = setInterval(function () {
                This.process();
            }, 80);
        }
    }

}

 

/****************/
/*****food.js****/
/****************/
var Food = function (x, y, radius, color) {
    this.X = x;
    this.Y = y;
    this.Radius = radius;
    this.Color = color;
    this.fpt = 10000;
    this.lastUpdata = 0;
}

Food.prototype =
{
    update: function () {
        this.X = parseInt(Math.random() * 380 + 8, 10);
        this.Y = parseInt(Math.random() * 380 + 8, 10);
    }

}

 

 

/****************/
/*****Canvas.js****/
/****************/
var Canvas = {
    //画圆
    //ctx:context2d对象,x:圆心x坐标,y:圆心y坐标,radius:半径,color:颜色
    arc: function (cxt, x, y, radius, color) {
        cxt.fillStyle = color;
        cxt.beginPath();
        cxt.arc(x, y, radius, 0, Math.PI * 2, true);
        cxt.closePath();
        cxt.fill();
    }

}

 

 

/****************/
/*****Bone.js****/
/****************/
var Bone = function (x, y, radius, color) {
    this.X = x;
    this.Y = y;
    this.Radius = radius;
    this.Color = color;

}

 

/****************/
/*****Snake.js****/
/****************/
var Snake = function (length, width, height) {
    this.fpt = 40;
    this.Body = [];
    this.lastUpdata = 0;
    this.speed = 8;
    this.oldDirection = 6;
    this.direction = 6;
    var centerX = parseInt(width / 2, 10);
    var centerY = parseInt(height / 2, 10);

    var bone = new Bone(centerX, centerY, 4, 'blue');
    this.Body.push(bone);

    for (var i = 0; i < length - 1; i++) {
        var bone = new Bone(centerX, centerY - (8 * (i + 1)), 4, 'blue');
        this.Body.push(bone);
    }

    this.cornerX = centerX;
    this.cornerY = centerY;
    this.back = 0;
}

Snake.prototype =
{
    update: function (food) {
        if (this.lastUpdata % this.fpt == 0) {

            if (this.back == 1) {
                this.back = 0;
                var last = this.Body[this.Body.length - 1];
                var secondLast = this.Body[this.Body.length - 2];

                if (last.Y - secondLast.Y > 0) {
                    this.direction = 6;
                }
                else if (last.Y - secondLast.Y < 0) {
                    this.direction = 12;
                }
                else if (last.X - secondLast.X < 0) {
                    this.direction = 9;
                }
                else if (last.X - secondLast.X > 0) {
                    this.direction = 3;
                }
                this.Body.reverse();
            }


            //记录蛇头的原始坐标
            this.cornerX = this.Body[0].X;
            this.cornerY = this.Body[0].Y;

            //定义蛇头的新位置
            switch (this.direction) {
                case 12:
                    this.Body[0].Y -= this.speed;
                    break;
                case 6:
                    this.Body[0].Y += this.speed;
                    break;
                case 3:
                    this.Body[0].X += this.speed;
                    break;
                case 9:
                    this.Body[0].X -= this.speed;
                    break;
                default:
                    break;
            }
            //蛇身的新位置为前一个节点的位置
            for (var i = this.Body.length - 1; i > 1; i--) {
                this.Body[i].X = this.Body[i - 1].X;
                this.Body[i].Y = this.Body[i - 1].Y;
            }

            //定义蛇尾的新位置
            this.Body[1].X = this.cornerX;
            this.Body[1].Y = this.cornerY;

            this.eatFood(food);
            var over = false;
            for (var j = 0; j < this.Body.length; j++) {
                var bone = this.Body[j];
                if (bone.X < 0 || bone.Y < 0 || bone.X > 400 || bone.Y > 400) {
                    over = true;
                    break;
                }
            }

            if (over) {
                this.Body.length = 0;
            }
        }

        //时间累加
        this.lastUpdata += 10;
    },

    eatFood: function (food) {
        var i, l, bone, isTouch = false;
        //遍历蛇身体
        for (i = 0, l = this.Body.length; i < l; i++) {
            var bone = this.Body[i];
            //判断蛇身与食物的圆心距
            if (Math.sqrt(Math.pow(bone.X - food.X, 2) + Math.pow(bone.Y - food.Y, 2)) <= bone.Radius + food.Radius) {
                isTouch = true;
                break;
            }
        }

        //给蛇增加一节
        if (isTouch) {
            var head = this.Body[0];
            var x = head.X;
            var y = head.Y;
            switch (this.direction) {
                case 12:
                    y = y - head.Radius * 2;
                    break;
                case 3:
                    x = x + head.Radius * 2;
                    break;
                case 6:
                    y = y + head.Radius * 2;
                    break;
                case 9:
                    x = x - head.Radius * 2;
                    break;
            }
            var newBone = new Bone(x, y, head.Radius, head.Color);
            this.Body.push(newBone);

            //随机改变食物的位置
            food.X = -100;
            food.Y = -100;
            setTimeout(function () {
                food.update();
            }, 800);
            var score = document.getElementById("score");
            score.innerHTML = parseInt(score.innerHTML) + 1;
            if (this.fpt > 10) {
                this.fpt -= 10;
            }
        }
    }

} 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="game.js" type="text/javascript"></script>
    <script src="Bone.js" type="text/javascript"></script>
    <script src="Canvas.js" type="text/javascript"></script>
    <script src="Snake.js" type="text/javascript"></script>
    <script src="food.js" type="text/javascript"></script>
</head>
<body>
    <canvas id="gamebg" width="400" height="400" style="background: Black;">您的浏览器不支持html5,请使用chrome或者ff</canvas>
    <input id="Button1" type="button" value="Start" onclick="Game.start(this)" />
    <input id="Button2" type="button" value="Pause" onclick="Game.pause(this)" />
    <br />
<div id="score">0</div>
</body>

</html> 

 

 

posted @ 2011-11-16 16:58  Teddy  阅读(748)  评论(0编辑  收藏  举报