消消乐uniapp代码
时间: 2023-08-21 16:07:17 浏览: 197
以下是一个使用uni-app框架实现的简单消消乐游戏的代码示例:
```vue
<template>
<view class="container">
<view class="board">
<view v-for="(row, rowIndex) in board" :key="rowIndex" class="row">
<view v-for="(col, colIndex) in row" :key="colIndex" class="cell" @click="clickCell(rowIndex, colIndex)">
{{ col }}
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
board: [], // 棋盘数组
selectedCell: null, // 当前选中的方块
};
},
mounted() {
this.initBoard();
},
methods: {
// 初始化棋盘
initBoard() {
const colors = ['red', 'blue', 'green', 'yellow', 'purple'];
for (let i = 0; i < 5; i++) {
const row = [];
for (let j = 0; j < 5; j++) {
row.push(colors[Math.floor(Math.random() * colors.length)]);
}
this.board.push(row);
}
},
// 点击方块时的操作
clickCell(row, col) {
if (!this.selectedCell) {
this.selectedCell = { row, col };
} else {
const { row: prevRow, col: prevCol } = this.selectedCell;
if (this.canSwap(prevRow, prevCol, row, col)) {
this.swapCells(prevRow, prevCol, row, col);
if (this.checkMatches()) {
this.removeMatches();
} else {
this.swapCells(prevRow, prevCol, row, col); // 无法消除,交换回来
}
}
this.selectedCell = null;
}
},
// 判断两个方块是否可以交换
canSwap(row1, col1, row2, col2) {
return Math.abs(row1 - row2) + Math.abs(col1 - col2) === 1;
},
// 交换两个方块的位置
swapCells(row1, col1, row2, col2) {
const temp = this.board[row1][col1];
this.board[row1][col1] = this.board[row2][col2];
this.board[row2][col2] = temp;
},
// 检查是否有可以消除的方块
checkMatches() {
const matches = new Set();
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 5; col++) {
if (this.isMatch(row, col)) {
matches.add(`${row}-${col}`);
}
}
}
return matches.size > 0;
},
// 判断某个方块是否可以消除
isMatch(row, col) {
const color = this.board[row][col];
let count = 0;
// 横向判断
for (let i = col + 1; i < 5; i++) {
if (this.board[row][i] === color) {
count++;
} else {
break;
}
}
for (let i = col
阅读全文