贪吃蛇

作者: qzuser_8165 | 来源:发表于2017-10-16 09:09 被阅读0次

    首先创造一个游戏引擎构造函数里面有行数列数属性跟一个初始化的方法
    初始化方法里创建出table tr td 分别使用for循环来创建出你想要的tr td数量把tr添加到td中td添加到table中table添加到body中
    ...
    var gGameBox = { //游戏引擎
    rows:10, //行数

    cols:10,    //列数
    
    alltds:[],
    kaishi:function(){          //初始化方法
        var oTable = document.createElement("table");   //创建一个table
        for(var i = 0 ; i<gGameBox.rows ; i++){         //创建10个tr
            var oTr = document.createElement("tr");
            var arr = [];                               //创建一个arr空数组
            for(var j = 0 ; j<gGameBox.cols ; j++){     //创建10个td
            var oTd = document.createElement("td");
            oTr.appendChild(oTd);                       //把创建的td放入tr里
            arr.push(oTd);                              //把td添加到arr数组中 
            }
            oTable.appendChild(oTr);                    //把创建的tr放入table
            gGameBox.alltds.push(arr);                  //把arr添加到alltds里 
        }
        document.body.appendChild(oTable);              //把创建的table放入body
    }
    

    };

    再创建一个开始的构造函数里面有2个属性分别为this.x跟this.y。
    在创建的构造函数原型里面添加2个方法一个是蛇出现在游戏中跟随机位置。
    再把出现位置里的className修改成一个不同颜色的表示为虫子
    随机位置的方法里调用出现在游戏中这个函数。
    开始的构造函数中调用随机位置的函数。
    这样蛇就会在开始的时候出现之后再改变他的位子。
    ...
    function Food(){ //开始

    this.y = 0;     //y坐标 
    
    this.x = 0;     //x坐标
    this.gaibian();
    

    }
    Food.prototype.chuxian = function(){ //出现在游戏里
    gGameBox.allTds[this.y][this.x].className = "chongzi"
    }

    //改变位子,随机的
    Food.prototype.gaibian = function(){
    this.x = paseInt(Math.random()* gGameBox.rows);
    this.y = paseInt(Math.random()* gGameBox.clos);
    this.chuxian();
    }

    相关文章

      网友评论

          本文标题:贪吃蛇

          本文链接:https://www.haomeiwen.com/subject/hrnwyxtx.html