当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS高级---案例:随机小方块 (贪吃蛇的食物部分)

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

2020年01月01日  | 移动技术网IT编程  | 我要评论
案例:随机小方块 产生随机数对象,自调用构造函数 产生小方块对象,自调用构造函数,里面存放: 食物的构造函数 给原型对象添加方法:初始化小方块的显示的效果及位置 显示地图上 给原型对象添加方法,产生随机位置 实例化对象 <!DOCTYPE html> <html lang="en"> <head> ...

案例:随机小方块

 

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

产生小方块对象,自调用构造函数,里面存放:
食物的构造函数
给原型对象添加方法:初始化小方块的显示的效果及位置---显示地图上
给原型对象添加方法,产生随机位置
实例化对象
 
<!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>

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网