<template>
<div class="container">
<h1>五子棋</h1>
<div class="board">
<div class="row"
v-for="(row, rowIndex) in board"
:key="rowIndex">
<div class="cell"
v-for="(cell, cellIndex) in row"
:key="cellIndex"
@click="placePiece(rowIndex, cellIndex)">
<div class="piece"
:class="{'black': cell == 1, 'white': cell == 2}">
</div>
</div>
</div>
</div>
<button @click="resetBoard">重新开始</button>
</div>
</template>
<script>
export default {
data () {
return {
board: [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
currentPlayer: 1,//选手 1/2
gameOver: false
}
},
methods: {
placePiece (row, col) {
if (this.gameOver) return;
if (this.board[row][col] !== 0) return;
this.$set(this.board[row], [col], this.currentPlayer)//
// this.board[row][col] = this.currentPlayer;二维数组深层监听,这样的写法不行,页面不做渲染
if (this.checkWin(row, col)) {
this.gameOver = true;
alert(`Player ${this.currentPlayer} wins!`);
} else {
this.currentPlayer = this.currentPlayer === 1 ? 2 : 1;//切换选择
}
},
resetBoard () {
this.board = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
this.currentPlayer = 1;
this.gameOver = false;
},
//判读输赢的逻辑
checkWin (row, col) {
const directions = [
[0, 1],
[1, 0],
[1, 1],
[-1, 1]
];
for (let i = 0; i < directions.length; i ) {
const [x, y] = directions[i];
let count = 1;
let r = row x;
let c = col y;
while (r >= 0 && r < 10 && c >= 0 && c < 10 && this.board[r][c] === this.currentPlayer) {
count ;
r = x;
c = y;
}
r = row - x;
c = col - y;
while (r >= 0 && r < 10 && c >= 0 && c < 10 && this.board[r][c] === this.currentPlayer) {
count ;
r -= x;
c -= y;
}
if (count >= 5) {
return true;
}
}
return false;
}
}
}
</script>
<style scoped>
.board {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 20px;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid #000;
position: relative;
}
.piece {
width: 40px;
height: 40px;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
}
.black {
background-color: #000;
}
.white {
background-color: #fff;
border: 1px solid #000;
}
</style>
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved