用JS实现一个简单的打砖块游戏


Posted in Javascript onDecember 11, 2019

话不多说,先看看效果:

用JS实现一个简单的打砖块游戏

HTML架构部分

<!-- HTML结构 -->
<div class="content">
    <div class="game"></div>
    <div class="container">
      <h2>打砖块小游戏</h2>
      <hr />
      <center>
        <button id="start"
          style="width: 120px;height: 22px;margin: 20px auto;border-radius: 10px;border: none;outline: none;color: rgba(145, 146, 146, 0.918);cursor:pointer;">开始游戏</button>
      </center>
      <div style="width: 219px;border: 1px solid rgba(145, 146, 146, 0.918);"></div>
      <center>
        <button id="reset"
          style="width: 120px;height: 22px;margin: 20px auto;border-radius: 10px;border: none;outline: none;color: rgba(145, 146, 146, 0.918);cursor:pointer;">再来一局</button>
      </center>
      <center>
        <!-- 分数 -->
        <div id="score"></div>
      </center>
    </div>

  </div>

CSS样式部分

<!-- CSS样式 -->
<style>
    * {
      padding: 0;
      margin: 0;
    }

    /* body>div {
      width: 550px;
      height: 520px;
      display: flex;
      margin: 20px auto;
    } */

    .container {
      width: 220px;
      height: 500px;
      border: 1px solid rgba(145, 146, 146, 0.918);
      margin-top: 20px;
      margin-right: 120px;
    }

    h2 {
      text-align: center;
      font-size: 26px;
      color: rgba(145, 146, 146, 0.918);
      margin-bottom: 2px;
    }

    .content {
      position: relative;
      width: 800px;
      height: 600px;
      margin: 0 auto;
      overflow: hidden;
      display: flex;
    }

    .game {
      position: relative;
      width: 456px;
      height: 500px;
      border: 1px solid rgba(145, 146, 146, 0.918);
      margin: 20px auto 0;
    }

    .brick {
      position: absolute;
      width: 50px;
      height: 20px;
      background-color: rgb(238, 17, 28);
    }

    /* 画挡板 */
    .flap {
      position: absolute;
      width: 120px;
      height: 10px;
      bottom: 0;
      left: 0;
      background-color: royalblue;
    }

    .ball {
      position: absolute;
      width: 20px;
      height: 20px;
      bottom: 10px;
      left: 52px;
      border-radius: 50%;
      background-color: blue;
    }

    #score {
      width: 100px;
      height: 30px;
      right: 0;
      top: 10%;
      color: rgba(145, 146, 146, 0.918);
    }
  </style>

JavaScript脚本语言部分

<!-- JS结构 -->
  <script>
    /*
    // 获取canvas元素
    const canvas = document.getElementById('canvas');
    // 获取到上下文,创建context对象
    const ctx = canvas.getContext('2d');
    let raf;
    // 定义一个小球
    const ball = {
      x: 100,  // 小球的 x 坐标
      y: 100,  // 小球的 y 坐标
      raduis: 20, // 小球的半径
      color: 'blue', // 小球的颜色
      vx: 3, // 小球在 x 轴移动的速度
      vy: 2, // 小球在 y 轴移动的速度
      // 绘制方法
      draw: function () {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.raduis, Math.PI * 2, false);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
      }
    }
    // 该函数为绘制函数:主要逻辑就是清空画布,重新绘制小球
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ball.draw();
      // 进行边界的判断
      if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
        ball.vy = -ball.vy;
      }
      if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
        ball.vx = -ball.vx;
      }
      ball.x += ball.vx;
      ball.y += ball.vy;
      raf = window.requestAnimationFrame(draw);
    }
    raf = window.requestAnimationFrame(draw);
    */
    // 加载窗口 = init
    window.onload = init;
    function init() {
      // 获取元素
      let gameArea = document.getElementsByClassName("game")[0];
      // 设置10列
      let rows = 10;
      // 设置8行
      let cols = 8;
      // 砖块与砖块之间的宽度
      let b_width = 58;
      // 砖块与砖块之间的高度
      let b_height = 28;
      // 用数组的形式来装砖块
      let bricks = [];
      // 小球的X轴方向(上下左右来回的运动)
      let speedX = 5;
      // 小球Y轴方向(上下左右来回的运动)
      let speedY = -5;
      // 在内部里,小球上下左右来回的运动,【小球碰撞到砖块 = null】
      let interId = null;
      // 左边距离为0
      let lf = 0;
      // 上边距离为0
      let tp = 0;
      // 挡板
      let flap;
      // 挡板上面的小球
      let ball;
      // 分数记录(初始值为0)
      let n = 0;
      // 获取开始游戏按钮的元素
      let st = document.getElementById("start");
      // 获取再来一局(重新渲染)按钮的元素
      let rt = document.getElementById("reset");
      // 获取分数记录的元素
      let score = document.getElementById("score");
      score.innerHTML = "分数:" + n;
      // 提供(渲染)Dom[渲染砖块] 方法
      renderDom();
      // 键盘的操作(A与D;askm查询:A:65,需-32,D:68,需+32)方法
      bindDom();
      // 进行渲染砖块
      function renderDom() {
        getBrick();
        // 画砖块
        function getBrick() {
          for (let i = 0; i < rows; i++) {
            let tp = i * b_height;
            let brick = null;
            for (let j = 0; j < cols; j++) {
              let lf = j * b_width;
              brick = document.createElement("div");
              brick.className = "brick";
              brick.setAttribute("style", "top:" + tp + "px;left:" + lf + "px;");
              // 获取背景的颜色
              brick.style.backgroundColor = getColor();
              bricks.push(brick);
              gameArea.appendChild(brick);
            }
          }
        }
        //添加挡板
        flap = document.createElement("div");
        flap.className = "flap";
        gameArea.appendChild(flap);
        //添加挡板+小球
        ball = document.createElement("div");
        ball.className = "ball";
        gameArea.appendChild(ball);
      }
      // 键盘的操作
      function bindDom() {
        flap = document.getElementsByClassName("flap")[0];
        window.onkeydown = function (e) {
          let ev = e || window.event;
          // 左边移动
          let lf = null;
          // A键往左移动
          if (e.keyCode == 65) {
            lf = flap.offsetLeft - 32;
            if (lf < 0) {
              lf = 0;
            }
            flap.style.left = lf + "px";
            // D键往右移动
          } else if (e.keyCode == 68) {
            lf = flap.offsetLeft + 32;
            if (lf >= gameArea.offsetWidth - flap.offsetWidth) {
              lf = gameArea.offsetWidth - flap.offsetWidth
            }
            flap.style.left = lf + "px";
          }
        }
        // 为开始游戏按钮添加点击事件
        st.onclick = function () {
          // 实现小球上下左右不断移动
          ballMove();
          st.onclick = null;
        }
        // 为再来一局按钮添加点击事件
        rt.onclick = function () {
          window.location.reload();
        }
      }
      // 获得砖块的颜色 rgb ===>>> 随机颜色;random() = 随机数方法
      function getColor() {
        let r = Math.floor(Math.random() * 256);
        let g = Math.floor(Math.random() * 256);
        let b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
      }
      // 实现小球上下左右不断移动
      function ballMove() {
        ball = document.getElementsByClassName("ball")[0];
        interId = setInterval(function () {
          // 左边(X轴方向)的移动速度
          lf = ball.offsetLeft + speedX;
          // 上边(Y轴方向)的移动速度
          tp = ball.offsetTop + speedY;
          // 用for(){}循环实现小球与砖块碰撞后从而消失
          for (let i = 0; i < bricks.length; i++) {
            let bk = bricks[i];
            // if进行判断,判断小球与砖块接触 【若:接触到:面板的宽度:offset ===>>> 抵消的意思,使它/2,简单的说就是:X轴=宽,Y轴=高,边距:上边offsetTop;左边offsetLeft.从什么地方反回到某一个地方接触一次则记为碰撞一次,从而进行让砖块抵消】
            if ((lf + ball.offsetWidth / 2) >= bk.offsetLeft && (lf + ball.offsetWidth / 2) <= (bk.offsetLeft + bk.offsetWidth) && (bk.offsetTop + bk.offsetHeight) >= ball.offsetTop) {
              // 执行时 = none时 ===>>> 消失 
              bk.style.display = "none";
              // Y轴的移动速度
              speedY = 5;
              // 小球与砖块碰撞抵消后,分数+1(n++)
              n++;
              score.innerHTML = "分数:" + n;
            }
          }

          if (lf < 0) {
            speedX = -speedX;
          }
          if (lf >= (gameArea.offsetWidth - ball.offsetWidth)) {
            speedX = -speedX;
          }
          if (tp <= 0) {
            speedY = 5;
          } else if ((ball.offsetTop + ball.offsetHeight) >= flap.offsetTop && (ball.offsetLeft + ball.offsetWidth / 2) >= flap.offsetLeft && (ball.offsetLeft + ball.offsetWidth / 2) <= (flap.offsetLeft + flap.offsetWidth)) {
            speedY = -5;
          } else if (ball.offsetTop >= flap.offsetTop) {
            // 游戏结束
            gameOver();
          }
          ball.style.left = lf + 'px';
          ball.style.top = tp + "px";
          // 让小球移动是时间参数随便给
        }, 40)
      }

      //判断游戏是否结束
      function gameOver() {
        // 弹框提示游戏该结束
        alert("游戏结束!" + "\n" + score.innerHTML);
        // 清除间隔
        clearInterval(interId);
      }
    }
  </script>

总结

以上所述是小编给大家介绍的用JS实现一个简单的打砖块游戏,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Javascript 相关文章推荐
解决iframe的frameborder在chrome/ff/ie下的差异
Aug 12 Javascript
JavaScript实现列表分页功能特效
May 15 Javascript
jQuery仅用3行代码实现的显示与隐藏功能完整实例
Oct 08 Javascript
javascript下拉列表中显示树形菜单的实现方法
Nov 17 Javascript
js实现的星星评分功能函数
Dec 09 Javascript
JQuery实现的按钮倒计时效果
Dec 23 Javascript
创建基于Bootstrap的下拉菜单的DropDownList的JQuery插件
Jun 02 Javascript
基于JS代码实现当鼠标悬停表格上显示这一格的全部内容
Jun 12 Javascript
jQuery动态增减行的实例代码解析(推荐)
Dec 05 Javascript
vue+webpack中配置ESLint
Nov 07 Javascript
JavaScript跳出循环的三种方法(break, return, continue)
Jul 30 Javascript
vue下使用nginx刷新页面404的问题解决
Aug 02 Javascript
js消除图片小游戏代码
Dec 11 #Javascript
详解vue中$nextTick和$forceUpdate的用法
Dec 11 #Javascript
基于jQuery实现可编辑的表格
Dec 11 #jQuery
jQuery实现可编辑的表格
Dec 11 #jQuery
vue element自定义表单验证请求后端接口验证
Dec 11 #Javascript
详解如何在JS代码中消灭for循环
Dec 11 #Javascript
Angular封装表单控件及思想总结
Dec 11 #Javascript
You might like
一个程序下载的管理程序(三)
2006/10/09 PHP
php将fileterms函数返回的结果变成可读的形式
2011/04/21 PHP
php获取网页标题和内容函数(不包含html标签)
2014/02/03 PHP
yii2.0数据库迁移教程【多个数据库同时同步数据】
2016/10/08 PHP
PHP实现无限极分类的两种方式示例【递归和引用方式】
2019/03/25 PHP
通过PHP实现用户注册后邮箱验证激活
2020/11/10 PHP
THREE.JS入门教程(2)着色器-上
2013/01/24 Javascript
asp.net刷新本页面的六种方法总结
2014/01/07 Javascript
javascript常见数据验证插件大全
2015/08/03 Javascript
概述VUE2.0不可忽视的很多变化
2016/09/25 Javascript
AngularJS中一般函数参数传递用法分析
2016/11/22 Javascript
Restify中接入Socket.io报Error:Can’t set headers的错误解决
2017/03/28 Javascript
强大的 Angular 表单验证功能详细介绍
2017/05/23 Javascript
你可能不知道的JSON.stringify()详解
2017/08/17 Javascript
Vue from-validate 表单验证的示例代码
2017/09/26 Javascript
vue框架搭建之axios使用教程
2018/07/11 Javascript
jQuery.extend 与 jQuery.fn.extend的用法及区别实例分析
2018/07/25 jQuery
JS立即执行函数功能与用法分析
2019/01/15 Javascript
详解nuxt 微信公众号支付遇到的问题与解决
2019/08/26 Javascript
使用konva和vue-konva库实现拖拽滑块验证功能
2020/04/27 Javascript
[40:04]Secret vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.23
2019/09/05 DOTA
Python Mysql数据库操作 Perl操作Mysql数据库
2009/01/12 Python
用实例详解Python中的Django框架中prefetch_related()函数对数据库查询的优化
2015/04/01 Python
Python最基本的输入输出详解
2015/04/25 Python
猎人靴英国官网:Hunter Boots
2017/02/02 全球购物
CheapTickets泰国:廉价航班,查看促销价格并预订机票
2019/12/28 全球购物
Net Remoting把服务器端激活两种模式
2014/01/22 面试题
好的自荐信包括什么内容
2013/11/07 职场文书
网页设计个人找工作求职信
2013/11/28 职场文书
兵马俑导游词
2015/02/02 职场文书
商务宴请邀请函范文
2015/02/02 职场文书
元旦联欢晚会主持词
2015/07/01 职场文书
银行求职信怎么写
2019/06/20 职场文书
告别网页搜索!教你用python实现一款属于自己的翻译词典软件
2021/06/03 Python
Spring Bean是如何初始化的详解
2022/03/22 Java/Android
Windows Server 2019 安装DHCP服务及相关配置
2022/04/28 Servers