vue 井字棋游戏

- 对react示例拙略的模仿👉 教程

<template>
  <div class="body">

    <el-divider></el-divider>
    <h2 @click="reset" class="h2">{{ text }}: {{ isFork ? "❌" : "⭕" }}</h2>
    <div class="board">
      <div class="board-row" v-for="row of 3">
        <button v-for="index of 3" class="square" @click="handleChess(row+index*10,$event)"/>
      </div>
    </div>

  </div>
</template>
<script>
export default {
  data() {
    return {
      isFork: true,
      forkList: [],
      circleList: [],
      text: "下一步该",
      status: false,
    }
  },
  methods: {
    handleChess(index, event) {
      if (this.status || event.target.innerText!=="") return
      event.target.innerText = this.isFork ? "❌" : "⭕";
      this.isFork ? this.forkList.push(index) : this.circleList.push(index)
      if (this.calculateWinner()) {
        this.text = '🎉🎉🎉获胜者是'
        this.status = true
      } else {
        this.isFork = !this.isFork;
      }
    },

    // 11 21 31
    // 12 22 32
    // 13 23 33
    calculateWinner() {
      const lines = [
        [11, 21, 31],
        [12, 22, 32],
        [13, 23, 33],
        [11, 12, 13],
        [21, 22, 23],
        [31, 32, 33],
        [11, 22, 33],
        [13, 22, 31],
      ];
      let flag = false
      let forkList = this.forkList;
      let circleList = this.circleList;
      for (const e of lines) {
        const [a, b, c] = e
        if (forkList.includes(a) && forkList.includes(b) && forkList.includes(c)) {
          flag = true
        }
        if (circleList.includes(a) && circleList.includes(b) && circleList.includes(c)) {
          flag = true
        }
        if (flag) break
      }
      return flag
    },

    reset(){
      const reset = {
        isFork: true,
        forkList: [],
        circleList: [],
        text: "下一步该",
        status: false,
      }
      // 浅拷贝
      Object.assign(this.$data,reset)
      let squares = window.document.getElementsByClassName("square");
      Array.prototype.forEach.call(squares,e=>e.innerText = "")
    }
  }
}

</script>
<style scoped>
* {
  box-sizing: border-box;
}

h2 {
  margin-bottom: 20px;
}

code {
  font-size: 1.2em;
}

.body {
  font-family: sans-serif;
  margin: 20px 140px;
  padding: 0;
}

.square {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.board-row:after {
  clear: both;
  content: '';
  display: table;
}

.status {
  margin-bottom: 10px;
}

.game {
  display: flex;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值