記錄:隨機小方塊的產生

<!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"></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頂級對象,就成了全局的對象
    window.Random=new Random();
  })(window);//自調用構造函數的方式,分號必定要加上


  //產生小方塊對象
  (function (window) {
    //console.log(Random.getRandom(0,5));
    //選擇器的方式來獲取元素對象
    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>
相關文章
相關標籤/搜索