用uniapp写一个黑白棋游戏
时间: 2023-05-20 09:01:19 浏览: 89
好的,以下是一个简单的黑白棋游戏的Uniapp代码:
<template>
<div class="container">
<div class="board">
<div v-for="(row, rowIndex) in board" :key="rowIndex" class="row">
<div v-for="(cell, cellIndex) in row" :key="cellIndex" class="cell" :class="{'black': cell === 1, 'white': cell === 2}" @click="play(rowIndex, cellIndex)">
</div>
</div>
</div>
<div class="info">
<div class="turn">{{ turn === 1 ? '黑方' : '白方' }}回合</div>
<div class="score">黑方 {{ score[0] }} : {{ score[1] }} 白方</div>
</div>
</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, 2, 1, 0, 0, 0],
[0, 0, 0, 1, 2, 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]
],
turn: 1,
score: [2, 2]
}
},
methods: {
play(row, col) {
if (this.board[row][col] !== 0) {
return
}
let directions = [
[-1, -1], [-1, 0], [-1, 1],
[0, -1], [0, 1],
[1, -1], [1, 0], [1, 1]
]
let flipped = []
for (let d of directions) {
let r = row + d[0]
let c = col + d[1]
let temp = []
while (r >= 0 && r < 8 && c >= 0 && c < 8 && this.board[r][c] !== 0 && this.board[r][c] !== this.turn) {
temp.push([r, c])
r += d[0]
c += d[1]
}
if (r >= 0 && r < 8 && c >= 0 && c < 8 && this.board[r][c] === this.turn) {
flipped.push(...temp)
}
}
if (flipped.length === 0) {
return
}
this.board[row][col] = this.turn
for (let [r, c] of flipped) {
this.board[r][c] = this.turn
}
this.score[this.turn - 1] += flipped.length + 1
this.score[2 - this.turn] -= flipped.length
this.turn = 3 - this.turn
}
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.board {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
border: 2px solid black;
}
.row {
display: flex;
flex-wrap: wrap;
width: 100%;
height: 12.5%;
}
.cell {
width: 12.5%;
height: 100%;
border: 1px solid black;
}
.black {
background-color: black;
}
.white {
background-color: white;
}
.info {
margin-top: 20px;
font-size: 24px;
text-align: center;
}
</style>