JavaScript-开发一个简单的贪吃蛇小游戏

JavaScript开发一个简单的贪吃蛇小游戏

对于很多JavaScript初学者而言,使用JS开发出自己的第一个网页小游戏是很有成就感的事情,那么我们怎么使用JS来开发一个简单的小游戏呢?希望初学JS的同学可以通过这段代码加深对构造函数以及原型的理解,代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .map {
            width: 800px;
            height: 600px;
            margin: 0 auto;
            background-color: #ccc;
            position: relative;
        }
        .left {
            width: 200px;
            height: 600px;
            background-color: orangered;
            position: absolute;
            left: -200px;
        }
        #start {
            width: 90px;
            height: 50px;
            margin: 50px 55px;
            background-color: #ccc;
            border: 1px solid blue;
            border-radius: 5px;
            cursor: pointer;
        }
        .score {
            width: 150px;
            height: 100px;
            margin: 50px 25px;
            text-align: center;
            line-height: 100px;
            background-color: #fff;
            border-radius: 10px;
        }
    </style>
</head>
<body>
<div class="map">
    <div class="left">
        <button id="start">开始游戏</button>
        <div class="score" id="score">当前分数:0</div>
    </div>
</div>
<script>
    // 自调用函数-食物
    (function(window){
        var elements = [];//用来保存每个小方块食物的
        // 定义构造函数
        function Food (x,y,width,height,color){
            //横纵坐标
            this.x = x||0;
            this.y = y||0;
            //宽高
            this.width = width||20;
            this.height = height||20;
            //背景颜色
            this.color = color||"green";
        }
        // 为原型添加初始化方法(作用:在页面上显示这个食物)
        Food.prototype.init = function (map) {
            // 初始化删除食物
            remove();
            // 创建div
            var div = document.createElement("div");
            // 加到父节点下
            map.appendChild(div);
            // 设置样式
            div.style.width = this.width+"px";
            div.style.height = this.height+"px";
            div.style.backgroundColor = this.color;
            div.style.position = "absolute";
            // 随机横纵坐标
            this.x = parseInt(Math.random()*map.offsetWidth/this.width)*this.width;
            this.y = parseInt(Math.random()*map.offsetHeight/this.height)*this.height;
            div.style.left = this.x+"px";
            div.style.top = this.y+"px";
            // 把div加入到数组elements中
            elements.push(div);
        };
        // 删除食物
        function remove (){
            // elements数组中有这个食物
            for(var i = 0; i < elements.length; i++){
                var ele = elements[i];
                // 删除元素
                ele.parentNode.removeChild(ele);
                // 删除数组中的该元素
                elements.splice(i,1);
            }
        }
        // 把Food暴露给window
        window.Food = Food;
    }(window));

    // 自调用函数-蛇
    (function(window){
        var elements = [];// 存放小蛇的每个身体部分

        // 定义构造函数
        function Snake (width,height,direction) {
            // 小蛇每个部位的宽高
            this.width = width||20;
            this.height = height||20;

            // 小蛇的身体
            this.body = [
                {x:3,y:2,color:"red"},   // 头
                {x:2,y:2,color:"orange"},// 身体
                {x:1,y:2,color:"orange"} // 身体
            ];

            // 方向
            this.direction = direction||"right";
        }

        // 为原型添加方法 -- 小蛇初始化
        Snake.prototype.init = function ( map ) {
            // 删除之前的小蛇
            remove();
            // 循环创建div
            for (var i = 0; i < this.body.length; i++) {
                var div = document.createElement("div");
                map.appendChild(div);
                // 设置div的样式
                div.style.position = "absolute";
                div.style.width = this.width+"px";
                div.style.height = this.height+"px";
                div.style.left = this.body[i].x*this.width+"px";
                div.style.top = this.body[i].y*this.height+"px ";
                div.style.backgroundColor = this.body[i].color;
                elements.push(div);
            }
        };

        // 为原型添加方法-- 移动
        Snake.prototype.move = function ( food,map ){
            // 改变小蛇身体的坐标位置
            for (var i = this.body.length-1; i > 0; i--) {
                this.body[i].x = this.body[i-1].x;
                this.body[i].y = this.body[i-1].y;
            }

            // 判断方向----改变小蛇的头的坐标位置
            switch (this.direction) {
                case "right": this.body[0].x += 1;
                break;
                case "left": this.body[0].x -= 1;
                break;
                case "top": this.body[0].y -= 1;
                break;
                case "bottom": this.body[0].y += 1;
            }

            // 判断是否吃到食物
            var headX = this.body[0].x*this.width;
            var headY = this.body[0].y*this.height;
            var scoreDiv = document.querySelector("#score");
            if(headX === food.x && headY === food.y){
                // 获取小蛇的最后的尾巴
                var last = this.body[this.body.length-1];
                this.body.push({
                    x: last.x,
                    y: last.y,
                    color: last.color
                });
                food.init(map);
                score += 1;
                scoreDiv.innerHTML = "当前分数:"+score;
            };
        };

        // 删除小蛇的函数
        function remove () {
            // 获取数组
            for (var i = elements.length-1; i >= 0; i--){
                var ele = elements[i];
                ele.parentNode.removeChild(ele);
                elements.splice(i,1);
            }
        }
        window.Snake = Snake;
    }(window));

    // 自调用函数-游戏对象
    (function(window){
        var that = null;
        // 定义构造函数
        function Game(map){
            this.food = new Food();
            this.snake = new Snake();
            this.map = map;
            that = this;
        }
        Game.prototype.init = function () {
            // 初始化游戏
            this.food.init(this.map);
            this.snake.init(this.map);
            this.runSnake(this.food,this.map);
            this.bindKey();
        };
        // 添加原型方法---小蛇移动
        Game.prototype.runSnake = function (food,map) {
            // 自动移动
            var timeId = setInterval(function(){
                this.snake.move(food,map);
                // 初始化小蛇
                this.snake.init(map);
                var maxX = map.offsetWidth/this.snake.width;
                var maxY = map.offsetHeight/this.snake.height;
                // 蛇头的坐标
                var headX = this.snake.body[0].x;
                var headY = this.snake.body[0].y;
                for (var i = 1; i < this.snake.body.length; i++) { 
                // 循环判断蛇头的坐标和身体任一部位的坐标是否相同
                    if(headX === this.snake.body[i].x && headY === this.snake.body[i].y ){
                        clearInterval(timeId);
                        alert("游戏结束");
                    }
                }
                // 判断蛇头是否出界
                if (headX<0||headX>=maxX) {
                    // 停止定时器
                    clearInterval(timeId);
                    alert("游戏结束");
                }
                if (headY < 0 || headY >= maxY) {
                    clearInterval(timeId);
                    alert("游戏结束");
                }
            }.bind(that),150);
        };
        // 添加原型方法---添加按键事件
        Game.prototype.bindKey = function () {
            // 获取用户按键,改变小蛇的方向
            document.addEventListener("keydown",function(e){
                switch(e.keyCode){
                    case 37: this.snake.direction = "left";
                    break;
                    case 38: this.snake.direction = "top";
                    break;
                    case 39: this.snake.direction = "right";
                    break;
                    case 40: this.snake.direction = "bottom";
                    break;
                };
            }.bind(that),false);
        };
        window.Game = Game;
    }(window));
    // 通过开始按钮来开始游戏
    var gameStart = document.querySelector("#start");
    gameStart.onclick = function () {
        var game = new Game(document.querySelector(".map"));
        game.init();
    };
    // 游戏计分
    var score = 0;

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

这样,我们就做出了一个简单的贪吃蛇小游戏,快去试试你能得多少分吧!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值