首页 > Web开发 > 详细

js初识模块化开发-制作弹球效果

时间:2020-04-12 18:11:19      阅读:55      评论:0      收藏:0      [点我收藏+]

模块化开发是什么:模块化开发是一种生产方式,这种方式生产效率高,维护成本低。从软件开发的角度说,模块化开发是一种开发模式,写代码的一种方式,开发效率高,维护成本低。

这篇文章就通过弹球游戏这个案例来初步认识什么是模块化编程,具体怎么使用。
技术分享图片
附上未进行模块化的整体代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html {
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <script>
      class Ball {
        box;
        size = Math.floor(Math.random() * 30) + 30;
        x = Math.floor(Math.random() *(document.documentElement.clientWidth - this.size * 2)) + this.size;
        y =Math.floor(Math.random() *(document.documentElement.clientHeight - this.size * 2)) + this.size;
        speedX = Math.random() > 0.5 ? Math.floor(Math.random() * 2) + 1 : Math.floor(Math.random() * 2) - 3;
        speedY =Math.random() > 0.5 ? Math.floor(Math.random() * 2) + 1 : Math.floor(Math.random() * 2) - 3;
        constructor() {
          this.box = this.createElem();
        }
        createElem() {
          let div = document.createElement("div");
          div.style.width = this.size + "px";
          div.style.height = this.size + "px";
          div.style.borderRadius = "50%";
          div.style.backgroundColor = this.randomColor();
          div.style.position = "absolute";
          div.style.left = this.x + "px";
          div.style.top = this.y + "px";
          return div;
        }
        randomColor() {
          let color = "#";
          for (let i = 0; i < 6; i++) {
            color += Math.floor(Math.random() * 16).toString(16);
          }
          return color;
        }
        update() {
          this.x += this.speedX;
          this.y += this.speedY;
          if (this.x <= 0 || this.x + this.size >= document.documentElement.clientWidth)
            this.speedX = -this.speedX;
          if (this.y <= 0 || this.y + this.size >= document.documentElement.clientHeight)
            this.speedY = -this.speedY;
          this.box.style.left = this.x + "px";
          this.box.style.top = this.y + "px";
        }
        appendTo(parent) {
          if (typeof parent === "string") {
            parent = document.querySelector(parent);
          }
          parent.appendChild(this.box);
        }
      }
      class Main {
        static list = [];
        static init() {
          for (let i = 0; i < 10; i++) {
            let ball = new Ball();
            ball.appendTo("body");
            this.list.push(ball);
          }
          setInterval(Main.animation, 16);
        }
        static animation() {
          for (let i = 0; i < Main.list.length; i++) {
            Main.list[i].update();
            for (let j = 0; j < Main.list.length; j++) {
              if (i !== j) {
                let dx =Main.list[i].x + Main.list[i].size / 2 - (Main.list[j].x + Main.list[j].size / 2);
                let dy =Main.list[i].y + Main.list[i].size / 2 - (Main.list[j].y + Main.list[j].size / 2);
                let distance = Math.sqrt(dx * dx + dy * dy);
                if (distance <= (Main.list[i].size + Main.list[j].size) / 2) {
                  Main.list[i].speedX = -Main.list[i].speedX;
                  Main.list[i].speedY = -Main.list[i].speedY;
                  Main.list[j].speedX = -Main.list[j].speedX;
                  Main.list[j].speedY = -Main.list[j].speedY;
                }
              }
            }
          }
        }
      }
      Main.init();
    </script>
  </body>
</html>

 

该代码的大致思路就是,先生成大小,颜色,水平速度,垂直速度,绝对位置随机的小球,增加位置判断和小球碰撞检测功能,然后使用定时器函数进行位置更新。
下图方便对小球之间,以及小球和可视窗口的位置关系进行理解。

技术分享图片

1、创建Ball.js文件,我们将生成小球的类函数放入进去,因为要被引用,所以要在类名前添加export default,这是写模块化代码要注意的第一点。

export default class Ball{
    box;//定义生成的小球(元素)
    size=Math.floor(Math.random()*30)+30;  //小球的直径,30-60之间
     //小球的绝对位置left,取值范围是0-(可视窗口宽度-小球直径)
    x=Math.floor(Math.random()*(document.documentElement.clientWidth-this.size*2))+this.size; 
    //小球的绝对位置top,取值范围是0-(可视窗口高度-小球直径)
    y=Math.floor(Math.random()*(document.documentElement.clientHeight-this.size*2))+this.size;
   //小球的水平速度,使用三目运算,随机生成速度在1~3,-3~-1的整数值,避免速度为0
    speedX=Math.random()>0.5 ? Math.floor(Math.random()*2)+1 : Math.floor(Math.random()*2)-3;
     //小球的垂直速度,使用三目运算,随机生成速度在1~3,-3~-1的整数值,避免速度为0
    speedY=Math.random()>0.5 ? Math.floor(Math.random()*2)+1 : Math.floor(Math.random()*2)-3;
    constructor(){
        this.box=this.createElem();//box为生成的div元素
    }
    createElem(){ //创建div,生成小球
        let div=document.createElement(‘div‘);
        div.style.width=this.size+‘px‘;  //
        div.style.height=this.size+‘px‘;  //
        div.style.borderRadius=‘50%‘;  //弧度,变成球形
        div.style.backgroundColor=this.randomColor();  //随机背景颜色
        div.style.position=‘absolute‘;  //绝对定位
        div.style.left=this.x+‘px‘;  //初始left值
        div.style.top=this.y+‘px‘;  //初始top值
        return div;  //将创建好的元素返回给box
    }
    randomColor(){  //创建随机背景色
        let color=‘#‘;
        for(let i=0;i<6;i++){
            color+=Math.floor(Math.random()*16).toString(16);  //生成0-15的随机整数,转换成16进制字符
        }
        return color;
    }
    update(){  //小球位置更新函数
        this.x+=this.speedX;  //小球每次水平位置更新,都与小球的水平速度相加
        this.y+=this.speedY;  //小球每次垂直位置更新,都与小球的垂直速度相加
        // 如果水平位置超出左边或者右边,就让小球的水平速度翻转,正值变负值,负值变正值
        if(this.x<=0||this.x+this.size>=document.documentElement.clientWidth) this.speedX=-this.speedX;
        // 如果垂直位置超出上边或者下边,就让小球的垂直速度翻转,正值变负值,负值变正值
        if(this.y<=0||this.y+this.size>=document.documentElement.clientHeight) this.speedY=-this.speedY;
        this.box.style.left=this.x+‘px‘;  //x值就是绝对定位,左边的距离
        this.box.style.top=this.y+‘px‘;  //y值就是绝对定位,上边的距离
    }
    appendTo(parent){  //将生成的元素赋予父元素
        if(typeof parent===‘string‘){   //判断输入的参数是不是符合字符串规范
            parent=document.querySelector(parent);
        }
        parent.appendChild(this.box);
    }
}

 


2、创建Main.js文件,执行小球的生成与位置更新,因为要用到 class Ball的东西,所以这里需要声明引入import Ball from "./Ball.js",同时Main.js也要被引用,因此也要添加export default ,这是写模块化代码要注意的第二点。

import Ball from "./Ball.js";  //引入class Ball
export default class Main{
    static list=[];  //声明静态数组,用来存放小球对象
    static init(){   //声明静态方法
        for(let i=0;i<10;i++){   //循环10次,将生成的10个小球对象设置父元素为body,将小球都放入数组中
            let ball=new Ball();
            ball.appendTo(‘body‘);
            Main.list.push(ball);
        }
        setInterval(Main.animation,16);  //定时器执行静态方法animation,执行位置更新和碰撞检测
    }
    static animation(){
        for(let i=0;i<Main.list.length;i++){
            Main.list[i].update();    //根据小球个数执行循环次数,执行位置更新
            for(let j=0;j<Main.list.length;j++){
                if(i!==j){   //双重循环,比较当前小球和其它小球
                    let dx = (Main.list[i].x+Main.list[i].size/2) - (Main.list[j].x+Main.list[j].size/2);  //两个小球圆心之间的水平距离
                    let dy =(Main.list[i].y+Main.list[i].size/2) - (Main.list[j].y+Main.list[j].size/2);  //两个小球圆心之间的垂直距离
                    let distance = Math.sqrt(dx * dx + dy * dy);  //两个小球圆心之间的直线距离
                    //如果两个小球圆心之间的直线距离小于等于两个小球圆心之间的直线距离,则判定为两个小球碰撞了
                    if (distance <= (Main.list[i].size + Main.list[j].size)/2) { 
                        Main.list[i].speedX = -(Main.list[i].speedX);  //当前小球与碰撞小球的水平垂直速度都取反
                        Main.list[i].speedY = -(Main.list[i].speedY);
                        Main.list[j].speedX = -(Main.list[j].speedX);
                        Main.list[j].speedY = -(Main.list[j].speedY);
                        //当前小球与碰撞小球的背景色重新随机改变
                        Main.list[i].box.style.backgroundColor=Main.list[i].randomColor();
                        Main.list[j].box.style.backgroundColor=Main.list[j].randomColor();
                    }}
                
            }
        }
    }  
}

 


3、创建html文件,引入Main.js,需要注意script type="module"这里添加了类型,才能成功引入。然后将要引入的文件添加进去import Main from "./js/Main.js",这是写模块化代码要注意的第三点。而且采用模块化方式,不能通过双击html文件打开,只能通过服务器打开。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html{overflow: hidden;}
    </style>
</head>
<body>
   <script type="module">
       import Main from "./js/Main.js";  //引入Main.js 
    Main.init();  //执行Main中的init函数,生成小球和更新小球位置
   </script>
</body>
</html>

 

js初识模块化开发-制作弹球效果

原文:https://www.cnblogs.com/shenyunfeng123/p/12686283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!