原生js实现贪吃蛇之食物随机出现部分

  • html部分
<div class="map"></div>
  • css部分
 .map {
            width: 800px;
            height: 800px;
            /*渐变*/
            background: linear-gradient(to bottom, rgb(10, 10, 50) 10%, rgb(60, 10, 60) 100%);
            position: relative;
        }
  • js部分

    //产生食物对象
    (function () {
        //获取地图对象
        var map = document.querySelector(".map");
        //食物的构造函数
        function Food(width, height, color, x, y) {
            //设置食物的属性(包括默认值)
            this.width = width || 20;
            this.height = height || 20;
            this.color = color || "green";
            this.x = x || 0;//横坐标随机产生的
            this.y = y || 0;//纵坐标随机产生的
        }

        //初始化小方块的显示的效果及位置---显示地图上
        Food.prototype.init = function (map) {
            //创建食物的div
            var div = document.createElement("div");
            //加入到地图中
            map.appendChild(div);
            //设置食物的属性
            div.style.width = this.width + "px";//食物的宽等于当前调用这个构造函数的实例对象的宽
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            div.style.position = "absolute";
            this.render(map);   //构造函数的原型中的方法可以互相访问
            div.style.left = this.x + "px";
            div.style.top = this.y + "px"
        };
        //产生随机位置(呈现)
        Food.prototype.render = function (map) {
            this.x = parseInt(Math.random() * map.offsetWidth / this.width) * this.width;
            this.y = parseInt(Math.random() * map.offsetHeight / this.height) * this.height;
        };
        //把Food函数和map变量暴露在外面
      window.Food=Food;
      window.map=map;
    }());
    //实例化对象
    var fd = new Food(20, 20, "yellow");
    fd.init(map);
    //测试代码
    console.log(fd.x + "====" + fd.y);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值