当前位置:   article > 正文

一个可以接到“为所欲为”的成语接龙生成器_为所欲为生成器

为所欲为生成器

“为所欲为”成语接龙生成器

介绍

输入任意成语或汉字,会以最后一个字开头进行成语接龙,直到最后一个成语是“为所欲为”为止。

演示案例

实现逻辑

技术栈

  • vue
  • elementUI

依赖

  • cnchar
  • cnchar-idiom

cnchar 文档

动手搬砖

  1. 根据cnchar 文档安装上述两项依赖项
npm i cnchar
npm i cnchar-idiom
  • 1
  • 2
  1. 导入
import cnchar from 'cnchar'
import 'cnchar-idiom'
  • 1
  • 2
  1. 思路

    第一步:截取最后一个汉字,并获取该汉字的拼音;
    第二步:获取所有以该拼音开头的成语数组;
    第三步:遍历该数组,判断这个数组中最后一个字的拼音是否是“wei”,如果有“wei”结尾的成语,那么就结束;如果该数组中所有成语均没有以“wei”结尾,那么随机选取一个成语,重复第一步。

  2. 代码实现

// 获取最后一个汉字的拼音
getLastWordSpell(s) {
  s = s || ''
  return cnchar.spell(s.replace(/^(.*[n])*.*(.|n)$/g, '$2')).toLowerCase()
}
  • 1
  • 2
  • 3
  • 4
  • 5
// 主要函数
generator(lastWordSpell) {
  // 获取所有以该拼音开头的成语数组
  const tempResArr = cnchar.idiom(lastWordSpell, 'spell')
  if (!tempResArr.length) {
    // 没有以这个拼音开头的成语
    this.$message({
      type: 'warning',
      message: '矮鸭'
    })
    this.result = this.resultArr.join(' - ')
    return
  }
  // 判断最后一个字的拼音是否是“wei”
  const lastOneIsWei = tempResArr.some(el => {
    if (this.getLastWordSpell(el) === 'wei') {
      this.resultArr.push(el)
    }
    return this.getLastWordSpell(el) === 'wei'
  })
  if (lastOneIsWei) {
    // 如果是,那么就结束
    this.resultArr.push('为所欲为')
    this.result = this.resultArr.join(' - ')
  } else {
    // 如果不是,就在数组中随机找一个,然后递归
    const randomNum = this.getRandomNum(0, tempResArr.length)
    this.resultArr.push(tempResArr[randomNum])
    this.generator(this.getLastWordSpell(tempResArr[randomNum]))
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
// 生成从minNum到maxNum的随机数
getRandomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10)
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
    default:
      return 0
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 代码库
    wsyw-idiom-solitaire
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/878477
推荐阅读
相关标签
  

闽ICP备14008679号