基于面向对象 来写一个简单的贪吃蛇小游戏(代码可直接用)

分析一下用到的对象(这个案例的地图过于简单,可以不用创建为对象)

    食物对象(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); // 记录当
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值