<script setup>
import { onMounted, ref } from "vue"
import { is_empty, checkWin, is_black, is_white } from "./utils"
import { robotPlay } from './utils/api'
// 配置
const size = ref(20)
const win_size = ref(5)
const lattices = ref([])
// 5 连珠的下标
let isWin = []

onMounted(confirm)

function confirm() {
  isWin = []
  lattices.value = Array(size.value).fill([]).map(() => Array(size.value).fill(is_empty))
}
// 玩家下棋
async function playChess(item, row, col) {
  if (isWin.length || item !== is_empty) return
  lattices.value[row][col] = is_black
  const test = checkWin({ row, col, board: lattices.value, player: is_black, win_size: win_size.value })
  if (test) {
    isWin = test
    return
  } else {
    const [x, y] = await robotPlay(lattices.value, is_white, win_size.value)
    lattices.value[x][y] = is_white
  }
}


function getStyle(item, row, col) {
  if (isWin.length) {
    return isWin.map(([r, c]) => `${r}_${c}`).includes(`${row}_${col}`) ? 'isWin' : item
  }
  return item
}
</script>

<template>
  <div class="content flex-start">
    <p class="flex-between mr-6px">
      <label for="size" class="space-nowrap">棋盘大小：</label>
      <input v-model="size" id="size" type="number">
    </p>
    <p class="flex-between mr-6px">
      <label for="win_size" class="space-nowrap">胜利棋数：</label>
      <input v-model="win_size" id="win_size" type="number">
    </p>
    <button @click="confirm" class="space-nowrap">重新开始</button>
  </div>
  <div class="content border-top content-lattice">
    <p class="row" v-for="(lattice, r_i) in lattices" :key="r_i">
    <p class="col" :class="getStyle(item, r_i, c_i)" v-for="(item, c_i) in lattice" :key="`${r_i}-${c_i}`"
      @click="playChess(item, r_i, c_i)">
    </p>
    </p>
  </div>
</template>

