vue实现走棋盘
Vue 实现走棋盘功能
走棋盘功能通常用于棋盘类游戏或路径规划演示,以下是基于 Vue 3 的实现方案:
核心代码结构
<template>
<div class="chessboard">
<div v-for="(row, rowIndex) in board" :key="rowIndex" class="row">
<div
v-for="(cell, colIndex) in row"
:key="colIndex"
class="cell"
:class="{
'active': isActive(rowIndex, colIndex),
'path': isInPath(rowIndex, colIndex)
}"
@click="moveTo(rowIndex, colIndex)"
>
{{ cell }}
</div>
</div>
</div>
</template>
数据初始化
<script setup>
import { ref } from 'vue'
const boardSize = 8
const board = ref(Array(boardSize).fill().map(() =>
Array(boardSize).fill(0)
))
const currentPosition = ref([0, 0])
const path = ref([])
// 初始化棋子位置
board.value[0][0] = '♟'
</script>
移动逻辑实现
const moveTo = (row, col) => {
// 清除旧位置
board.value[currentPosition.value[0]][currentPosition.value[1]] = 0
// 更新新位置
board.value[row][col] = '♟'
currentPosition.value = [row, col]
// 记录路径
path.value.push([row, col])
}
const isActive = (row, col) => {
return currentPosition.value[0] === row &&
currentPosition.value[1] === col
}
const isInPath = (row, col) => {
return path.value.some(pos => pos[0] === row && pos[1] === col)
}
样式设计
<style>
.chessboard {
display: inline-block;
border: 2px solid #333;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
background-color: #fff;
}
.cell:nth-child(odd) {
background-color: #f0d9b5;
}
.cell:nth-child(even) {
background-color: #b58863;
}
.active {
background-color: #ff0000 !important;
}
.path {
background-color: #aaffaa !important;
}
</style>
高级功能扩展
1. 移动限制
const isValidMove = (row, col) => {
const [currentRow, currentCol] = currentPosition.value
const rowDiff = Math.abs(row - currentRow)
const colDiff = Math.abs(col - currentCol)
// 例如只允许走日字形
return (rowDiff === 2 && colDiff === 1) ||
(rowDiff === 1 && colDiff === 2)
}
const moveTo = (row, col) => {
if (!isValidMove(row, col)) return
// ...原有移动逻辑
}
2. 动画效果
.cell {
transition: background-color 0.3s ease;
}
.move-animation {
animation: move 0.5s ease;
}
@keyframes move {
from { transform: scale(0.8); }
to { transform: scale(1); }
}
3. 键盘控制
onMounted(() => {
window.addEventListener('keydown', handleKeyPress)
})
onUnmounted(() => {
window.removeEventListener('keydown', handleKeyPress)
})
const handleKeyPress = (e) => {
const [row, col] = currentPosition.value
switch(e.key) {
case 'ArrowUp':
if(row > 0) moveTo(row - 1, col)
break
case 'ArrowDown':
if(row < boardSize - 1) moveTo(row + 1, col)
break
// 其他方向键处理...
}
}
完整组件示例
<template>
<div>
<div class="chessboard">
<!-- 棋盘渲染 -->
</div>
<div class="controls">
<button @click="reset">重置</button>
<span>当前位置: ({{ currentPosition[0] }}, {{ currentPosition[1] }})</span>
</div>
</div>
</template>
<script setup>
// 组合式API代码
const reset = () => {
board.value = Array(boardSize).fill().map(() =>
Array(boardSize).fill(0)
)
board.value[0][0] = '♟'
currentPosition.value = [0, 0]
path.value = []
}
</script>
以上实现可根据具体需求进行调整,如改变棋盘大小、棋子样式或移动规则等。对于更复杂的棋盘游戏,可以结合Vuex或Pinia进行状态管理。







