JS高級---案例:隨機小方塊 (貪吃蛇的食物部分)

案例:隨機小方塊

 

產生隨機數對象,自調用構造函數html

產生小方塊對象,自調用構造函數,裏面存放:
食物的構造函數
給原型對象添加方法:初始化小方塊的顯示的效果及位置---顯示地圖上
給原型對象添加方法,產生隨機位置
實例化對象
 
<!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>
相關文章
相關標籤/搜索