贪吃蛇

2017-10-13  本文已影响0人  伏渊

1.思路:

一、找对象

            属性              方法
蛇       长度、颜色、位置、头、移动方向     吃、移动、长大
食物      大小、颜色、位置            改变位置
游戏引擎    场景、蛇、食物             开始、结束

二、实现对象

游戏引擎
    写一个食物food

这是将食物随机出现和表格先先写好的部分代码
      <style>
table {
    border-collapse: collapse;
    border: 1px solid black;
}

td {
    width: 15px;
    height: 15px;
    border: 1px solid black;
}

.food{

background:red;
}
</style>

</head>
<body>
<script>
//1.游戏引擎

//定义  游戏引擎  对象
var  gameBox = {
    
    rows:40,//行数

    cols:40,//列数

    allTds:[],//储存所有的td元素
    
    //方法:游戏开始

        start:function(){
        
            var oTable = document.createElement("table")

            //添加tr
            for (var i=0;i<gameBox.rows ; i++){

            //每一行定义一个空数组
            var arr = [];

            var oTr = document.createElement("tr");

                //添加td
                for (var j=0;j<gameBox.cols ; j++){
                
                var oTd = document.createElement("td");

                //把元素oTd添加到空数组arr中
                arr.push(oTd);

                //把td添加到tr
                oTr.appendChild(oTd);

                }

            oTable.appendChild(oTr);

把元素td放在数组arr中,在将td添加到t中,再将tr放中入table中,最后将table放入body,一级一级传入
// 把arr放到allTds中去
gameBox.allTds.push(arr);
}

            //添加到body
        document.body.appendChild(oTable);

        new Food();这是建立一个新的对象food将他写如表格里
    }

};



//给gameBox中的allTds设置一个属性
//gameBox.allTds[9][0].className = "food"

这一块是给food写一个随机让食物在表格中随机出现
//给food写一个随机,放到gameBox
function Food() {

    // 坐标
    this.x = 0;
    this.y = 0;

    // 一开始就随机位置,当食物刚出现时就随机
    this.change();
}

// 方法1: 出现在环境中
Food.prototype.show = function() {
    gameBox.allTds[this.y][this.x].className = "food";
}

// 方法2: 改变位置, 随机的
Food.prototype.change = function() {
    this.x = parseInt(Math.random() * gameBox.rows);给行写一个随机
    this.y = parseInt(Math.random() * gameBox.cols);给列写一个随机

    this.show();调用函数show
}
gameBox.start();让游戏开始


</script>

</body>

上一篇 下一篇

猜你喜欢

热点阅读