vue + element UI【实战】打字闯关(含按键监听、按键音效、字符匹配、动态样式、结果判定、数据统计、音效获取和剪辑等实用技巧)

简介: vue + element UI【实战】打字闯关(含按键监听、按键音效、字符匹配、动态样式、结果判定、数据统计、音效获取和剪辑等实用技巧)

效果预览

点我在线预览

实现思路

  • 将目标字符串按字符转换为数组,遍历展示
      this.stringLib[this.step].split("").forEach((item) => {
        this.targetList.push({
          text: item,
        });
      });
  • 监听键盘事件
created() {
  this.keyDown();
},

// 按下按键
keyDown() {
   // function内的this不再是vue实例,需提前将 this 存入 that以便在 function内使用
   let that = this;
   document.onkeydown = function (e) {
       console.log(e.key) // 按下键盘上的 A 时会打印 a
   }
}
  • 根据按键值判断输入是否正确,若正确则添加属性 type 为 success ,字符变绿 ;输入错误则添加属性 type 为 danger,字符变红 (type 值来自 el-tag 对应的效果)
// 用下标 index 跟踪标记输入进度
let targetText = that.targetList[that.index].text;
if (e.key === targetText) {
  // 使用 $set 页面才能及时响应对象的变化
  that.$set(that.targetList[that.index], "type", "success");
} else {
  that.$set(that.targetList[that.index], "type", "danger");
}
  • 当前关的字符输入完后,按任意键都会判定通关结果,输入全部正确才能通关
// 输入的正确字符数与目标字符数相等时,通过当前关
if (that.rightCharNum === that.targetList.length) {
  // 若已是最后一关,则全部通关,闯关结束
  if (that.step === that.totalStep) {
    that.over();
  } else {
    that.result = "success";
    // 通过当前关时播放通关成功的音效
    that.$refs.successAudio.play();
  }
} else {
  that.result = "fail";
  // 存在错误字符时播放通关失败的音效
  that.$refs.failAudio.play();
}
  • 判定结果后,按回车键/空格键,若通关则开始下一关,若失败则重新挑战
if (that.result) {
  if (e.key === "Enter" || e.key === " ") {
    if (that.result === "success") {
      that.nextStep();
    }
    if (that.result === "fail") {
      that.replay();
    }
  }
  return;
}
  • 为提升用户体验,每一次输入都会配音效,并统计输入正确和错误的次数
 if (e.key === targetText) {
   that.$set(that.targetList[that.index], "type", "success");
   // 为避免输入过快时声音反应不及时,在每次输入时让音频从头开始播放
   that.$refs.inputAudio.currentTime = 0;
   that.$refs.inputAudio.play();
   that.rightNum++;
 } else {
   that.$set(that.targetList[that.index], "type", "danger");
   that.$refs.errorAudio.currentTime = 0;
   that.$refs.errorAudio.play();
   that.wrongNum++;
 }

重要提示

element UI 需升级到 2.15.7 以上版本,否则不支持 el-result 标签

升级 element UI 的方法可以参考 https://blog.csdn.net/weixin_41192489/article/details/126013674


音效素材可从以下网站搜索下载

https://sc.chinaz.com/tag_yinxiao/peiyin.html


本范例的音效素材,可通过以下链接下载

https://pan.baidu.com/s/1wCVuOebxLAAAMBe4eCNREA?pwd=4kym


过长的音效,可通过软件 Audacity 剪辑 (腾讯管家软件库中可下载)

完整范例代码

<template>
  <div class="mainBox">
    <h1 class="center">【 打字闯关 】第 {{ step }} 关</h1>
    <el-row type="flex" class="pageBanner" justify="center">
      <el-pagination
        :pager-count="20"
        :total="totalStep"
        :page-size="1"
        @current-change="currentPageChange"
        :current-page="step"
        layout="prev, pager, next"
      >
      </el-pagination>
    </el-row>
    <el-row type="flex" justify="center">
      <el-tag
        :key="index"
        v-for="(item, index) in targetList"
        :type="item.type"
      >
        {{ item.text }}
      </el-tag>
    </el-row>

    <el-row :gutter="10" type="flex" justify="center">
      <el-col class="center" :span="2"> 正确:{{ rightNum }} 次 </el-col>
      <el-col class="center" :span="2"> 错误:{{ wrongNum }} 次</el-col>
      <el-col class="center" :span="4" v-if="result">
        正确字符:{{ rightCharNum }} 个</el-col
      >
      <el-col class="center" :span="4" v-if="result">
        错误字符:{{ wrongCharNum }} 个</el-col
      >
    </el-row>

    <el-result
      v-if="result === 'success'"
      icon="success"
      title="恭喜通关"
      subTitle="你真棒!"
    >
      <template slot="extra">
        <el-button type="primary" size="medium" @click="nextStep"
          >下一关</el-button
        >
      </template>
    </el-result>

    <el-result
      v-if="result === 'over'"
      icon="success"
      title="恭喜您,已全部通关"
      subTitle="这大腿,俺抱定了!"
    >
    </el-result>

    <el-result
      v-if="result === 'fail'"
      icon="error"
      title="挑战失败"
      subTitle="失败是成功的妈妈,再试一次吧!"
    >
      <template slot="extra">
        <el-button type="primary" size="medium" @click="replay"
          >重新挑战</el-button
        >
      </template>
    </el-result>

    <audio ref="overAudio" controls="controls" hidden>
      <source src="./audios/全部通关.wav" type="audio/mpeg" />
    </audio>

    <audio ref="successAudio" controls="controls" hidden>
      <source src="./audios/通关.wav" type="audio/mpeg" />
    </audio>

    <audio ref="failAudio" controls="controls" hidden>
      <source src="./audios/一片嘘声.wav" type="audio/mpeg" />
    </audio>

    <audio ref="inputAudio" controls="controls" hidden>
      <source src="./audios/键盘输入音.mp3" type="audio/mpeg" />
    </audio>

    <audio ref="errorAudio" controls="controls" hidden>
      <source src="./audios/错误提示音.wav" type="audio/mpeg" />
    </audio>
  </div>
</template>
<script>
export default {
  data() {
    return {
      index: 0,
      targetList: [],
      rightNum: 0,
      wrongNum: 0,
      result: null,
      wrongCharNum: 0,
      rightCharNum: 0,
      stringLib: {
        1: "aaaa ssss dddd ffff",
        2: "jjjj kkkk llll ;;;;",
        3: "qqqq wwww eeee rrrr",
        4: "uuuu iiii oooo pppp",
        5: "zzzz xxxx cccc vvvv",
        6: "mmmm ,,,, .... ",
        7: "tttt yyyy gggg hhhh",
        8: "bbbb nnnn 1111 2222",
        9: "3333 4444 5555 6666",
        10: "7777 8888 9999 0000",
      },
      // 关卡数
      step: 1,
      // 总关卡数
      totalStep: 10,
    };
  },
  created() {
    this.keyDown();
  },
  mounted() {
    this.init();
  },
  methods: {
    currentPageChange(newPage) {
      this.step = newPage;
      this.init();
    },
    // 重玩
    replay() {
      this.init();
    },
    // 下一关
    nextStep() {
      if (!this.stringLib[this.step + 1]) {
        this.over();
        return;
      }
      this.step++;
      this.init();
    },
    // 初始化
    init() {
      this.result = null;
      this.rightNum = 0;
      this.wrongNum = 0;
      this.rightCharNum = 0;
      this.wrongCharNum = 0;
      this.index = 0;
      this.targetList = [];

      this.stringLib[this.step].split("").forEach((item) => {
        this.targetList.push({
          text: item,
        });
      });
    },
    // 全部通关
    over() {
      this.result = "over";
      this.$refs.overAudio.play();
    },
    // 按下按键
    keyDown() {
      let that = this;
      document.onkeydown = function (e) {
        if (that.result) {
          if (e.key === "Enter" || e.key === " ") {
            if (that.result === "success") {
              that.nextStep();
            }
            if (that.result === "fail") {
              that.replay();
            }
          }
          return;
        }

        if (that.index > that.targetList.length - 1) {
          that.targetList.forEach((item) => {
            if (item.type === "success") {
              that.rightCharNum++;
            } else {
              that.wrongCharNum++;
            }
          });
          // 输入的正确字符数与目标字符数相等时,通过当前关
          if (that.rightCharNum === that.targetList.length) {
            // 若已是最后一关,则全部通关,闯关结束
            if (that.step === that.totalStep) {
              that.over();
            } else {
              that.result = "success";
              // 通过当前关时播放通关成功的音效
              that.$refs.successAudio.play();
            }
          } else {
            that.result = "fail";
            // 存在错误字符时播放通关失败的音效
            that.$refs.failAudio.play();
          }
          return;
        }

        if (e.key === "Backspace") {
          if (that.index > 0) {
            that.index--;
            that.$set(that.targetList[that.index], "type", "");
          }

          return;
        }

        let targetText = that.targetList[that.index].text;
        if (e.key === targetText) {
          that.$set(that.targetList[that.index], "type", "success");
          // 为避免输入过快时声音反应不及时,在每次输入时让音频从头开始播放
          that.$refs.inputAudio.currentTime = 0;
          that.$refs.inputAudio.play();
          that.rightNum++;
        } else {
          that.$set(that.targetList[that.index], "type", "danger");
          that.$refs.errorAudio.currentTime = 0;
          that.$refs.errorAudio.play();
          that.wrongNum++;
        }

        that.index++;
      };
    },
  },
};
</script>
<style  scoped>
.center {
  text-align: center;
}
.mainBox {
  padding: 30px;
}
.el-tag {
  margin: 10px;
  height: 100px;
  width: 100px;
  font-size: 60px;
  line-height: 100px;
  border-radius: 10%;
  text-align: center;
}
</style>

目录
相关文章
|
2天前
element UI 组件封装--搜索表单(含插槽和内嵌组件)
element UI 组件封装--搜索表单(含插槽和内嵌组件)
14 5
|
2天前
|
JavaScript
vue + element UI 表单中内嵌自定义组件的表单校验触发方案
vue + element UI 表单中内嵌自定义组件的表单校验触发方案
18 5
|
2天前
Element UI【级联选择器】el-cascader 获取选中内容的 label 数据,鼠标悬浮显示超长内容
Element UI【级联选择器】el-cascader 获取选中内容的 label 数据,鼠标悬浮显示超长内容
12 3
|
1天前
|
数据安全/隐私保护
Element UI 密码输入框--可切换显示隐藏,自定义图标
Element UI 密码输入框--可切换显示隐藏,自定义图标
6 0
|
1天前
Element UI 表格【列宽自适应】
Element UI 表格【列宽自适应】
4 0
|
1天前
|
前端开发
ElementPlus卡片如何能够一行呈四,黑马UI前端布局视频资料,element样式具体的细节无法修改,F12找到那个位置,可能在其他组件写了错误,找到那个位置,围绕着位置解决问题最快了,卡片下边
ElementPlus卡片如何能够一行呈四,黑马UI前端布局视频资料,element样式具体的细节无法修改,F12找到那个位置,可能在其他组件写了错误,找到那个位置,围绕着位置解决问题最快了,卡片下边
|
1天前
Element UI 【表格合计】el-table 实战范例 -- 添加单位,自定义计算逻辑
Element UI 【表格合计】el-table 实战范例 -- 添加单位,自定义计算逻辑
6 0
|
2月前
|
前端开发 搜索推荐 开发者
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
|
2月前
|
JavaScript 前端开发 开发者
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍
|
2月前
|
前端开发 JavaScript API
SAP UI5 sap.ui.require.toUrl 的作用介绍
SAP UI5 sap.ui.require.toUrl 的作用介绍