1.思路:
一、找對象
屬性 方法
蛇 長度、顏色汰蜘、位置、頭之宿、移動(dòng)方向 吃族操、移動(dòng)、長大
食物 大小比被、顏色色难、位置 改變位置
游戲引擎 場景、蛇等缀、食物 開始枷莉、結(jié)束
二、實(shí)現(xiàn)對象
游戲引擎
寫一個(gè)食物food
這是將食物隨機(jī)出現(xiàn)和表格先先寫好的部分代碼
<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,//行數(shù)
cols:40,//列數(shù)
allTds:[],//儲存所有的td元素
//方法:游戲開始
start:function(){
var oTable = document.createElement("table")
//添加tr
for (var i=0;i<gameBox.rows ; i++){
//每一行定義一個(gè)空數(shù)組
var arr = [];
var oTr = document.createElement("tr");
//添加td
for (var j=0;j<gameBox.cols ; j++){
var oTd = document.createElement("td");
//把元素oTd添加到空數(shù)組arr中
arr.push(oTd);
//把td添加到tr
oTr.appendChild(oTd);
}
oTable.appendChild(oTr);
把元素td放在數(shù)組arr中尺迂,在將td添加到t中笤妙,再將tr放中入table中,最后將table放入body噪裕,一級一級傳入
// 把a(bǔ)rr放到allTds中去
gameBox.allTds.push(arr);
}
//添加到body
document.body.appendChild(oTable);
new Food();這是建立一個(gè)新的對象food將他寫如表格里
}
};
//給gameBox中的allTds設(shè)置一個(gè)屬性
//gameBox.allTds[9][0].className = "food"
這一塊是給food寫一個(gè)隨機(jī)讓食物在表格中隨機(jī)出現(xiàn)
//給food寫一個(gè)隨機(jī)蹲盘,放到gameBox
function Food() {
// 坐標(biāo)
this.x = 0;
this.y = 0;
// 一開始就隨機(jī)位置,當(dāng)食物剛出現(xiàn)時(shí)就隨機(jī)
this.change();
}
// 方法1: 出現(xiàn)在環(huán)境中
Food.prototype.show = function() {
gameBox.allTds[this.y][this.x].className = "food";
}
// 方法2: 改變位置, 隨機(jī)的
Food.prototype.change = function() {
this.x = parseInt(Math.random() * gameBox.rows);給行寫一個(gè)隨機(jī)
this.y = parseInt(Math.random() * gameBox.cols);給列寫一個(gè)隨機(jī)
this.show();調(diào)用函數(shù)show
}
gameBox.start();讓游戲開始
</script>
</body>