<script setup>
import { onMounted, reactive, ref } from "vue"
// 配置
const con = reactive({
  width: 20,
  height: 20
})
const lattices = ref([])
let nextPlay = 'isBlack' // isWhite
// 5 连珠的下标
let isWin = []

onMounted(confirm)

function confirm() {
  const { width, height } = con
  nextPlay = 'isBlack'
  isWin = []
  lattices.value = Array(height).fill([]).map(item => Array(width).fill(null))
}

function playChess(item, r_i, c_i) {
  if (isWin.length || item) return
  lattices.value[r_i][c_i] = nextPlay
  const test = checkWin(lattices.value, nextPlay)
  if (test) {
    console.log(test)
    isWin = test
    return
  }
  nextPlay = nextPlay === 'isBlack' ? 'isWhite' : 'isBlack'

}
// AI 生成代码
function checkFiveInARow(board, startX, startY, deltaX, deltaY) {
  const rows = board.length;
  const cols = board[0].length;
  const player = board[startX][startY];
  if (!player) {
    return null;
  }
  for (let i = 1; i <= 4; i++) {
    const row = startX + i * deltaX;
    const col = startY + i * deltaY;
    if (row < 0 || row >= rows || col < 0 || col >= cols || board[row][col] !== player) {
      return null;
    }
  }
  return [[startX, startY], [startX + deltaX, startY + deltaY], [startX + 2 * deltaX, startY + 2 * deltaY], [startX + 3 * deltaX, startY + 3 * deltaY], [startX + 4 * deltaX, startY + 4 * deltaY]];
}

function checkWin(board) {
  const rows = board.length;
  const cols = board[0].length;
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const positions =
        checkFiveInARow(board, row, col, 0, 1) ||
        checkFiveInARow(board, row, col, 1, 0) ||
        checkFiveInARow(board, row, col, 1, 1) ||
        checkFiveInARow(board, row, col, 1, -1);
      if (positions) {
        return positions;
      }
    }
  }
  return null;
}


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

<template>
  <div class="content flex-between">
    <p class="flex-between">
      <label>高：</label>
      <input v-model="con.height" type="number">
    </p>
    <p class="flex-between">
      <label>宽：</label>
      <input v-model="con.width" type="number">
    </p>
    <button @click="confirm">重新开始</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>

