分析一下用到的对象(这个案例的地图过于简单,可以不用创建为对象)
食物对象(food)
蛇对象(snake)
游戏对象(game)
1.food对象
属性 :x, y, width, height, color
方法: render 随机创建一个食物对象,输出到mup(地图)上
(function () {
var elements = []; // 记录上一次创建的食物,为删除做准备
function Food(options) {
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
this.width = options.width || 20;
this.height = options.height || 20;
this.color = options.color || 'green';
}
// 渲染
Food.prototype.render = function (map) {
remove();// 删除之前创建的食物
// 随机设置x和y的值
this.x = getRandom(0, map.offsetWidth/this.width - 1) * this.width;
this.y = getRandom(0, map.offsetHeight/this.height - 1) * this.height;
// 动态创建div 页面上显示的食物
var div = document.createElement('div');
map.appendChild(div);
elements.push(div);
// 设置div的样式
div.style.position = 'absolute';
div.style.left = this.x + 'px';
div.style.top = this.y + 'px';
div.style.width = this.width + 'px';
div.style.height = this.height + 'px';
div.style.backgroundColor = this.color;
}
function remove() {
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].parentNode.removeChild(elements[i]); // 删除div
elements.splice(i, 1);// 删除数组中的元素
}
}
window.Food = Food;
})()
2.snake对象
属性:width(蛇节的宽度默认20),height(蛇节的高默认20),body(数组,蛇的头和身体,第一个位置是头),
direction(蛇的运动方向,默认是left)
方法:render 把蛇渲染到map(地图)上
move 移动(对蛇头和蛇身分别作不同处理)
(function () {
var elements = []; // 记录之前创建的蛇
function Snake(options) {
options = options || {};
// 蛇节 的大小
this.width = options.width || 20;
this.height = options.height || 20;
this.direction = options.direction || 'right'; // 蛇移动的方向
// 蛇的身体(蛇节) 第一个元素是蛇头
this.body = [
{x: 3, y: 2, color: 'red'},
{x: 2, y: 2, color: 'blue'},
{x: 1, y: 2, color: 'blue'}
];
}
Snake.prototype.render = function (map) {
remove(); // 删除之前创建的蛇
// 把每一个蛇节渲染到地图上
for (var i = 0, len = this.body.length; i < len; i++) {
var object = this.body[i];
var div = document.createElement('div');
map.appendChild(div);
elements.push(div); // 记录当