使用javascript实现贪吃蛇游戏

当自己用代码实贪吃蛇游戏时,是很有成就感的一件事情。同时在写的过程中也是自己对javascript基本语法的复习与体会。

以下就是代码以及一些代码注释:(bug是有的,浏览器的兼容性,本人的能力无法解决)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        div {
            border: 1px solid #0094ff;
            width: 20px;
            height: 20px;
            background-color: yellow;
        }

        table {
            margin: 10px auto;
        }
    </style>
    <script type="text/javascript">
        //全局变量
        var colCount = 12; //12列
        var rowCount = 14;  //14行

        //--------------window.onload在这里-------------
        window.onload=function () {
            //画小方块12x14
            for (var i = 0; i < rowCount; i++) {
                var createtr = document.createElement("tr");
                for (var j = 0; j < colCount; j++) {
                    var createtd = document.createElement("td");
                    createtd.appendChild(CreateDiv(i, j));
                    createtr.appendChild(createtd);
                }
                document.getElementById("tabMain").appendChild(createtr);
            }
            //游戏逻辑方法
            GameController();
        }

        //--------------封装的方法以及自定义的类---------------

        //获得指定rowIndex和colIndex的div
        function GetDiv(rowIndex, colIndex) {
            var divs = document.getElementsByTagName("div");
            for (var i = 0; i < divs.length; i++) {
                if (divs[i].getAttribute("rowIndex") == rowIndex && divs[i].getAttribute("colIndex") == colIndex) {
                    return divs[i];

                }
            }
            return undefined;
        }

        //生成小方块的方法
        function CreateDiv(rowIndex, colIndex) {
            var xdiv = document.createElement("div");
            //添加自定义属性,为每个单元格做标记.
            xdiv.setAttribute("rowIndex", rowIndex);
            xdiv.setAttribute("colIndex",colIndex);
            xdiv.setAttribute("food", false);
            return xdiv;
        }

        //单元格
        var Unit = {
            colIndex: 0,
            rowIndex: 0,
            //单元格方向
            dir: "Left",
            olddir: "Left",
            Draw: function (rowIndex, colIndex) {
                GetDiv(rowIndex, colIndex).style.backgroundColor = "red";
            },
            Wipe: function (rowIndex, colIndex) {
                GetDiv(rowIndex, colIndex).style.backgroundColor = "yellow";
            },
            MoveLeft: function () {
                this.colIndex--;
            },
            MoveRight: function () {
                this.colIndex++;
            },
            MoveUp: function () {
                this.rowIndex--;
            },
            MoveDown: function () {
                this.rowIndex++;
            }
        }

        //存放单元格集合类
        var UnitList = {
            //存放单元格的数组
            body: new Array(),
            //添加三个单元格到数组,这里代码写的不好,本想每次吃到食物就调用AddBody方法的,后来就把这个方法写死了。
            AddBody: function () {
                var unit = Object.create(Unit);
                unit.rowIndex = 8;
                unit.colIndex = 8;
                this.body[this.body.length] = unit;
                //测试代码
                var unit2 = Object.create(Unit);
                unit2.rowIndex = 8;
                unit2.colIndex = 9;
                this.body[this.body.length] = unit2;
                var unit3 = Object.create(Unit);
                unit3.rowIndex = 8;
                unit3.colIndex = 10;
                this.body[this.body.length] = unit3;

            },

            Draw: function () {
                for (var i = 0; i < this.body.length; i++) {
                    this.body[i].Draw(this.body[i].rowIndex, this.body[i].colIndex);
                }
            },
            Wipe: function () {
                for (var i = 0; i < this.body.length; i++) {
                    this.body[i].Wipe(this.body[i].rowIndex, this.body[i].colIndex);
                }
            },
            AutoMoveTo: function () {
                //先擦除
                this.Wipe();
                //移动
                for (var i = 0; i < this.body.length; i++) {
                    switch (this.body[i].dir) {
                        case "Left":
                            this.body[i].MoveLeft();
                            break;
                        case "Right":
                            this.body[i].MoveRight();
                            break;
                        case "Down":
                            this.body[i].MoveDown();
                            break;
                        case "Up":
                            this.body[i].MoveUp();
                            break;
                    }
                    this.body[i].olddir = this.body[i].dir;
                    if (this.body[i - 1] != undefined) {
                        this.body[i].dir = this.body[i - 1].olddir;
                    }
                }
                //重画
                this.Draw();
            }
        }

        //----------------游戏逻辑方法-------------
        function GameController() {
            var U = Object.create(UnitList);
            U.AddBody();
            U.Draw();
            AddFood();
            var set = window.setInterval(function () { MoveMove() }, 500);
            //移动方法
            function MoveMove() {
                //判断是否能移动
                if (IsAbleMove()) {
                    //判断是否吃到自己
                    if (IsEatMySelf()) {
                        window.clearInterval(set);
                        alert("吃到自己了");
                    }
                    //判断是否吃到食物
                    if (IsEatFood()) {
                        //新增一个unit
                        var newU = Object.create(Unit);
                        newU.rowIndex = U.body[U.body.length - 1].rowIndex;
                        newU.colIndex = parseInt(U.body[U.body.length - 1].colIndex) + 1;
                        U.body[U.body.length] = newU;
                        //新增一个食物
                        AddFood();
                    }
                    U.AutoMoveTo();
                }
                else {
                    //   关闭setInterval
                    window.clearInterval(set);
                    alert("结束");
                }

            }
            //判断越界
            function IsAbleMove() {
                var rowIndex = U.body[0].rowIndex;
                var colIndex = U.body[0].colIndex;
                switch (U.body[0].dir) {
                    case "Left":
                        colIndex--;
                        break;
                    case "Right":
                        colIndex++;
                        break;
                    case "Down":
                        rowIndex++;
                        break;
                    case "Up":
                        rowIndex--;
                        break;

                }
                if (rowIndex < 0 || colIndex < 0 || rowIndex > 13 || colIndex > 11) {
                    return false;
                }
                return true;
            }
            //生成食物
            function AddFood() {
                var rowIndex;
                var colIndex;
                random();
                function random() {
                    rowIndex = parseInt(Math.random() * 14);
                    colIndex = parseInt(Math.random() * 12);
                    for (var i = 0; i < U.body.length; i++) {
                        if (rowIndex == U.body[i].rowIndex && colIndex == U.body[i].colIndex) {
                           // alert("haha");
                            random();

                        }

                    }
                };
                GetDiv(rowIndex, colIndex).style.backgroundColor = "green";
                GetDiv(rowIndex, colIndex).setAttribute("food", true);
            }
            //是否吃到食物
            function IsEatFood() {
                if (GetDiv(U.body[0].rowIndex, U.body[0].colIndex).getAttribute("food") == "true") {
                    GetDiv(U.body[0].rowIndex, U.body[0].colIndex).setAttribute("food", false);
                    return true;
                }
                return false;
            }
            //是否吃到自己
            function IsEatMySelf() {
                var rowIndex = U.body[0].rowIndex;
                var colIndex = U.body[0].colIndex;
                for (var i = 1; i < U.body.length; i++) {
                    if (U.body[i].rowIndex == rowIndex && U.body[i].colIndex == colIndex) {
                        return true;
                    }
                }
                return false;
            }
            //监听键盘事件
            window.onkeydown = function () {
                switch (event.keyCode) {
                    case 37:
                        //alert("你按了左方向键");
                        if (U.body[0].dir != "Right") {
                            U.body[0].dir = "Left";
                        }
                        break;
                    case 38:
                        //alert("你按了上");
                        if (U.body[0].dir != "Down") {
                            U.body[0].dir = "Up";
                        }
                        break;
                    case 39:
                        //alert("你按了右方向键");
                        if (U.body[0].dir != "Left") {
                            U.body[0].dir = "Right";
                        }
                        break;
                    case 40:
                        //alert("你按了下方向键");
                        if (U.body[0].dir != "Up") {
                            U.body[0].dir = "Down";
                        }
                        break;
                }
            }
        }
    </script>
</head>
<body>
    <table id="tabMain">
    </table>
</body>
</html>
时间: 2024-08-01 13:18:07

使用javascript实现贪吃蛇游戏的相关文章

javascript -- (贪吃蛇游戏)

界面设置 /***body**/ <body> <h1>贪吃蛇游戏</h1> /***score记录成绩**/ <p id="score">0</p> /***地图**/ <div id="snake_map"> /***地图的绘制通过js实现**/ </div> /***三个按钮**/ <div class = "box"> <button t

WebGL实现HTML5的3D贪吃蛇游戏

js1k.com收集了小于1k的javascript小例子,里面有很多很炫很酷的游戏和特效,今年规则又增加了新花样,传统的classic类型基础上又增加了WebGL类型,以及允许增加到2K的++类型,多次想尝试提交个小游戏但总无法写出让自己满意还能控制在这么小的字节范围. 自己写不出来,站在巨人肩膀总是有机会吧,想起<基于HTML5的电信网管3D机房监控应用>这篇提到的threejs,babylonjs和Hightopo的几种基于WebGL的3D引擎,突然想挑战下自己实现个100行JS的3D小

javascript实现贪吃蛇

<html> <head> <style> body { background:#444; } .rect { border:1px solid #94F; width:680px; height:680px; } .gridred { width:38px; height:38px; background:red; border:1px #555 solid; float:left } .gridgreen { width:38px; height:38px; bac

《结对-网页贪吃蛇游戏-需求分析》

一. 介绍:贪吃蛇游戏是一款经典的益智游戏,有PC和手机等多平台版本.既简单又耐玩,深受人们喜爱. 二. 用户需求:1.可在浏览器上进行游戏. 2.可以调节难度. 3.可查看历史战绩. 4.可以更改背景,游戏的开始暂停以及分辨率的调节. 5.可显示游戏的实时分数. 三. 实施做法:应用html,css,javascript,语言进行代码编写,运用sublime,DW进行代码编写调试运行. 四. 游戏特点:无需下载,用户可以随时打开浏览器进行游戏. 五. 游戏规定:游戏者通过键盘的上下左右控制蛇头

可选择关卡的贪吃蛇游戏

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>可选择关卡的贪吃蛇游戏石家庄拓展公司<

JS贪吃蛇游戏

<!DOCTYPE html><html> <head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <title>JS贪吃蛇游戏</title>    <style>    * {        margin: 0;    

用Java开发贪吃蛇游戏

贪吃蛇游戏的设计步骤: Part 1: 设计游戏图纸 画出900*700的白色窗口 在窗口上添加画布 在画布上添加标题 在画布上添加黑色游戏区 Part 2: 放置静态的蛇:一个头.两个身体 加上开始提示:按空格键开始游戏 让蛇动起来:监听Timer事件,平移数据 实现游戏暂停 实现转向功能 Part 3: 添加食物 吃掉食物 添加死亡条件 实现“重新开始”功能 添加分数和长度 游戏图纸如下: 蛇及游戏框的素材如下:                              Snake主类: 1

Qt版贪吃蛇游戏

Qt版贪吃蛇游戏 转载请标明出处:牟尼的专栏 http://blog.csdn.net/u012027907 最近在学习Qt,用了一个多月的时间掌握了Qt中最基本的知识,也完成了<Qt版音乐播放器>.<Qt版贪吃蛇游戏>.<Qt版双人俄罗斯方块>以及<Qt版科学计算器>等,之前在VC下写过这些程序,所以在Qt下只是改变了显示等语句,我写过<C++版贪吃蛇游戏>.<VC版贪吃蛇游戏>,当时将与显示等无关的东西封装起来,在Qt下直接用,只

【141030】VC++贪吃蛇游戏源码(Win32+API)

不错的贪吃蛇游戏,运用了Win32的API.完整源代码,在VS2005下编译通过.内附有编程要点,很好的学习范例. 游戏源码下载地址:点击下载