利用html,css,js来制作一个简单贪吃蛇小游戏

这篇博客详细介绍了如何使用HTML5、CSS和JavaScript构建一个简单的贪吃蛇游戏。从创建游戏界面、定义事件监听、创建地图、生成食物、控制蛇的运动到碰撞检测,每个步骤都有清晰的代码展示。此外,还涉及到了游戏难度的设置和重新开始功能的实现,为读者提供了一个完整的互动游戏开发实例。
摘要由CSDN通过智能技术生成

首先是制作两个按钮,分别是开始游戏和暂停游戏

<div id="main">
        <input class="btn begin" type="button" value="开始游戏">
        <input class="btn pause" type="button" value="暂停游戏">
    </div>

 两个按钮的css样式

 body {
        margin: 0px;
        padding: 0px;
    }

    #main {
        margin: 100px;
    }

    .btn {
        widows: 100px;
        height: 40px;
    }

分别为两个按钮绑定事件,先定义一个变量timer为事件

<script>
        var timer; //变量可以提升

        document.querySelector(".begin").onclick = function () {
            clearInterval(timer)
            timer = setInterval(function () {
                console.log("begin")
            }, 300)
        }

        document.querySelector(".pause").onclick = function () {
            clearInterval(timer)
        }
    </script>

声明和创建游戏地图

  //初始化地图
        var main = document.querySelector("#main")
        var showcanvas = true;
        /**
         * 地图对象的构造方法
         * @param {*} atom 原子,可以想象成一个正方形小单位,整个地图由一个个原子组成
         * @param {*} xnum  横向原子的数量
         * @param {*} ynum  纵向原子的数量
         * @return {*}
         */
        function Map(atom, xnum, ynum) {
            this.atom = atom;
            this.xnum = xnum;
            this.ynum = ynum;

            this.canvas = null;

            //创建画布(地图)的方法
            this.create = function () {
                this.canvas = document.createElement("div");
                this.canvas.style.cssText = "position:relative;top:40px;border:1px solid darkred;background:#FAFAFA";
                this.canvas.style.width = this.atom * this.xnum + "px"; //地图的宽
                this.canvas.style.height = this.atom * this.ynum + "px"; //地图的高
                main.appendChild(this.canvas);

                //选择是否显示其单位原子出来,要是showcanvas是true则显示,反之不显示
                if (showcanvas) {
                    for (var y = 0; y < ynum; y++) {
                        for (var x = 0; x < xnum; x++) {
                            var a = document.createElement("div");
                            a.style.cssText = "border:1px solid yellow";
                            a.style.width = this.atom + "px";
                            a.style.height = this.atom + "px";
                            a.style.backgroundColor = "green";
                            this.canvas.appendChild(a);
                            a.style.position = "absolute";
                            a.style.left = x * this.atom + "px";
                            a.style.top = y * this.atom + "px";
                        }
                    }
                }
            }
        }

        //创建地图对象,调用其创建方法,此时自定义的原子单位为20*20像素,地图为40原子宽,20原子高
        var map = new Map(20, 40, 20);
        map.create();

接下来是添加食物

  //创建食物的构造方法
        function Food(map) {
            this.width = map.atom;
            this.height = map.atom;
            this.backgroundColor = "rgb(" + Math.floor(Math.random() * 200) + "," + Math.floor(Math.random() * 200) + "," + Math.floor(Math.random() * 200) + ")";

            this.x = Math.floor(Math.random() * map.xnum); //设置食物出现的位置不能超过地图的长
            this.y = Math.floor(Math.random() * map.ynum);

            //创建食物的对象
            this.flag = document.createElement("div");
            this.flag.style.width = this.width + "px";
            this.flag.style.height = this.height + "px";

            this.flag.style.backgroundColor = this.backgroundColor;
            this.flag.style.borderRadius = "50%";
            this.flag.style.position = "absolute";
            this.flag.style.left = this.x * this.width + "px";
            this.flag.style.top = this.y * this.height + "px";

            //添加食物到地图上
            map.canvas.appendChild(this.flag);
        }
        var food = new Food(map);

创建蛇对象,并创建其中的运动方法以及判断游戏结束条件

 //创建蛇对象
        function Snake(map) {
            //设置蛇的宽高
            this.width = map.atom;
            this.height = map.atom;

            //设置默认蛇头前进的方向
            this.direction = "right";

            //设置蛇总体,用数组对象来存放
            this.body = [
                { x: 2, y: 0 }, //蛇头
                { x: 1, y: 0 }, //蛇身
                { x: 0, y: 0 }, //蛇尾
            ]

            //显示蛇出现的方法
            this.display = function () {
                for (var i = 0; i < this.body.length; i++) {
                    if (this.body[i].x !== null) { //当蛇吃到食物时,x==null,不能创建,不然会在(0,0)坐标创建蛇
                        var s = document.createElement("div");
                        //将蛇节点保存到一个状态变量中,以便删除使用
                        this.body[i].flag = s;

                        //设置蛇样式
                        s.style.width = this.width + "px";
                        s.style.height = this.height + "px";
                        s.style.backgroundColor = "rgb(" + Math.floor(Math.random() * 200) + "," + Math.floor(Math.random() * 200) + "," + Math.floor(Math.random() * 200) + ")";
                        // s.style.borderRadius = "50%"

                        //设置蛇出现的位置
                        s.style.position = "absolute";
                        s.style.left = this.body[i].x * this.width + "px";
                        s.style.top = this.body[i].y * this.height + "px";

                        //将蛇添加到地图上
                        map.canvas.appendChild(s);
                    }
                }
            }

            //让蛇运动
            this.run = function () {
                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 "up": this.body[0].y -= 1; break;
                    case "down": this.body[0].y += 1; break;
                    case "left": this.body[0].x -= 1; break;
                    case "right": this.body[0].x += 1; break;
                }

                //当蛇吃掉食物时,判断蛇头的xy坐标是否与食物的xy坐标重合
                if (this.body[0].x == food.x && this.body[0].y == food.y) {
                    //给蛇增加一节身体
                    this.body.push({ x: null, y: null, flag: null });

                    //判断难度级别
                    if (this.body.length > l.slength){
                        l.set();
                    }
                        //吃掉食物消失
                        map.canvas.removeChild(food.flag);
                    food = new Food(map);

                }

                //当蛇头撞到地图边界
                if (this.body[0].x < 0 || this.body[0].x > map.xnum - 1 || this.body[0].y < 0 || this.body[0].y > map.ynum - 1) {
                    clearInterval(timer); //清楚定时器
                    alert("游戏结束");

                    //游戏重新开始
                    restart(map, this);
                    return false;

                }

                //当蛇撞到自己
                for (var i = 4; i < this.body.length; i++) {
                    if (this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
                        clearInterval(timer); //清楚定时器
                        alert("游戏结束");

                        //游戏重新开始
                        restart(map, this);
                        return false;
                    }
                }

                //消除之前的蛇
                for (var i = 0; i < this.body.length; i++) {
                    if (this.body[i].flag != null) {
                        map.canvas.removeChild(this.body[i].flag);
                    }

                }
                this.display();
            }

        }

        //游戏重新开始
        function restart(map, snake) {
            //消除蛇
            for (var i = 0; i < snake.body.length; i++) {
                map.canvas.removeChild(snake.body[i].flag);
            }
            //初始化新蛇
            snake.body = [
                { x: 2, y: 0 }, //蛇头
                { x: 1, y: 0 }, //蛇身
                { x: 0, y: 0 }, //蛇尾
            ];
            snake.direction = "right";
            snake.display();

            //消除食物
            map.canvas.removeChild(food.flag);
            food = new Food(map);
        }

        //构造蛇对象
        var snake = new Snake(map);
        snake.display();

要是想提升游戏难度可另外设置个方法,用来定义游戏难度,并且重新封装游戏开始方法

 //设置游戏难度对象
        function Level() {
            this.num = 1; //起始默认难度为1
            this.speed = 300; //速度,每升一关减少时间,相当于增加了蛇的运行速度
            this.slength = 5; //用来判断蛇的长度,每达到一次这个长度则难度提升

            this.set = function () {
                this.num++;
                if (this.speed <= 50) {
                    this.speed = 50 //最小速度是50
                } else {
                    this.speed -= 50;
                }
                this.slength += 1; 

                start();//速度加快
            }
        }
        //创建对象
        var l = new Level();

//定义游戏开始方法
        var start = function () {
            clearInterval(timer)
            timer = setInterval(function () {
                snake.run();
            }, l.speed)
        }

        document.querySelector(".begin").onclick = function () {
            start();
        }

附上源码连接:(10条消息) 利用html,css,js写的简单贪吃蛇小游戏-Javascript文档类资源-CSDN下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值