打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JS高级---案例:随机小方块 (贪吃蛇的食物部分)

案例:随机小方块

 

产生随机数对象,自调用构造函数

产生小方块对象,自调用构造函数,里面存放:
食物的构造函数
给原型对象添加方法:初始化小方块的显示的效果及位置---显示地图上
给原型对象添加方法,产生随机位置
实例化对象
 
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>title</title>  <style>    .map {      width: 800px;      height: 600px;      background-color: #CCC;      position: relative;    }  </style></head><body>  <div class="map" id="dv"></div>  <script src="common.js"></script>  <script>    //产生随机数对象的    (function (window) {      function Random() {      };      Random.prototype.getRandom = function (min, max) {        return Math.floor(Math.random() * (max - min) + min);      };      window.Random = new Random;    })(window); //自调用构造函数的方式, 分号一定要加上    //产生小方块对象    (function (window) {      var map = document.querySelector(".map");      //食物的构造函数      function Food(width, height, color) {        this.width = width || 20;        this.height = height || 20;        //横坐标,纵坐标        this.x = 0;//横坐标随机产生的        this.y = 0;//纵坐标随机产生的        this.color = color;//小方块的背景颜色        this.element = document.createElement("div");      }      //初始化小方块的显示的效果及位置---显示地图上      Food.prototype.init = function (map) {        //设置小方块的样式        var div = this.element;        div.style.position = "absolute";//脱离文档流        div.style.width = this.width + "px";        div.style.height = this.height + "px";        div.style.backgroundColor = this.color;        //把小方块加到map地图中        map.appendChild(div);        this.render(map);      };      //产生随机位置      Food.prototype.render = function (map) {        //随机产生横纵坐标        var x = Random.getRandom(0, map.offsetWidth / this.width) * this.width;        var y = Random.getRandom(0, map.offsetHeight / this.height) * this.height;        this.x = x;        this.y = y;        var div = this.element;        div.style.left = this.x + "px";        div.style.top = this.y + "px";      };      //实例化对象      var fd = new Food(20, 20, "green");      fd.init(map);      console.log(fd.x + "=====" + fd.y);    })(window);  </script></body></html>

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JavaScript把局部变量变成全局变量
百度地图Api进阶教程
js楼盘模型360度旋转动画效果
百度地图API详解之地图容器
【百度地图API】如何制作公交线路的搜索?如331路
10分钟学会Google Map API (一) - Google观察者 - ITPUB个...
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服