考验你的记忆力

168 阅读2分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!


说明

一共有9张卡片,由三个图案(工资狗🐕,可爱猫🐱,耶耶鹅🦆),三种背景颜色(黄,绿,蓝)随机组合。

刚开始,会给你 9s 的时间记忆这 9 张卡片在九宫格的位置,9s 后,9 张卡片顺序打乱,你需要根据你的记忆将9张卡片放回原位,选中你想放置的卡片,再点击你想放置的位置即可。

错误后可以重新放置,但是错误数量会被记录。

快打开代码块测试一下你的记忆力吧!

最终效果:

image.png

代码块

代码说明

  1. 创建【开始记忆】按钮,点击该按钮随机生成9张卡片
<button @click="startMemory">开始记忆</button> 

startMemory() {
  this.initCards();
},
initCards() {
  let cards = [];
  this.imgs.forEach((img) => {
    this.colors.forEach((color) => {
      cards.push({ img: img, color: color, default: false }); // default用来控制X的显示
    });
  });

  this.allCards = [...cards]; // 保存所有的卡片

  this.cards = cards.sort(() => Math.random() - 0.5); // 卡片乱序

  // 9s倒计时
  let time = setInterval(() => {
    this.second--;
    if (!this.second) {
      clearInterval(time);
      this.saveCards = this.cards;
      this.cards = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
    }
  }, 1000);
},
  1. 绘制9个卡片槽
<div class="card_ul">
  <div
    class="card_li"
    :class="item.img ? 'card' : 'ka_cao'"
    :style="{ backgroundColor: item.color }"
    v-for="(item, index) in cards"
    :key="index"
    @click="clickKacao(item, index)"
  >
    <img :src="item.img" alt="" srcset="" width="80%" height="auto" />
    <div class="default" v-show="item.default">X</div>
  </div>
</div>
  1. 绘制下方选择卡片
<div class="all_cards" v-show="second === 0">
  <div
    class="ca_li"
    v-for="(item, index) in allCards"
    :key="index"
    :style="{ backgroundColor: item.color }"
    @click="clickCard(item, index)"
    :class="{ ca_li_active: curCardIdx === index }"
  >
    <img :src="item.img" alt="" srcset="" width="80%" height="auto" />
  </div>
</div>
  1. 选中卡片,然后点击卡槽匹配代码:
// 选中卡片
clickCard(item, index) {
  this.curCardIdx = index; // 选中卡片的index
  this.curCard = item; // 选中卡片的内容
},
// 点击卡槽匹配
clickKacao(item, index) {
  // 如果有选中卡片才进行匹配
  if (this.curCard) {
    let card = this.saveCards[index]; // 选中的卡槽的内容
    // 如果卡槽内容和选中卡片内容一样,则匹配成功
    if (
      this.curCard.color === card.color &&
      this.curCard.img === card.img
    ) {
      this.cards[index] = card; // 当前卡槽内容变为匹配成功的卡片内容
      this.curCard = null;
      this.allCards.splice(this.curCardIdx, 1); // 删除匹配成功的卡片
      this.curCardIdx = null;

      // 如果所有卡片都匹配成功,则可以重新开始游戏
      if (this.allCards.length === 0) {
        this.second = 9;
      }
    } else {
      // 匹配不成功则错误数量+1
      this.defaultNum++;
      this.$set(item, "default", true); // 并且显示X
      setTimeout(() => {
        this.$set(item, "default", false); // 0.8s后X隐藏
      }, 800);
    }
  }
},

写在最后

以上就是所有的代码说明。