消消乐uniapp完整代码
时间: 2023-08-20 16:08:07 浏览: 238
以下是一个使用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" :class="{ selected: isSelected(rowIndex, colIndex) }" @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 < 6; i++) {
const row = [];
for (let j = 0; j < 6; j++) {
const randomIndex = Math.floor(Math.random() * colors.length);
row.push(colors[randomIndex]);
}
this.board.push(row);
}
},
// 点击方块
clickCell(rowIndex, colIndex) {
const clickedCell = this.board[rowIndex][colIndex];
if (this.selectedCell) {
if (this.checkAdjacent(rowIndex, colIndex)) {
if (this.checkMatch(this.selectedCell, clickedCell)) {
this.removeCells(rowIndex, colIndex);
}
}
this.selectedCell = null;
} else {
this.selectedCell = clickedCell;
}
},
// 检查方块是否相邻
checkAdjacent(rowIndex, colIndex) {
const selectedRowIndex = this.board.findIndex(row => row.includes(this.selectedCell));
const selectedColIndex = this.board[selectedRowIndex].indexOf(this.selectedCell);
return (
(rowIndex === selectedRowIndex && Math.abs(colIndex - selectedColIndex) === 1) ||
(colIndex === selectedColIndex && Math.abs(rowIndex - selectedRowIndex) === 1)
);
},
// 检查方块是否匹配
checkMatch(cell1, cell2) {
return cell1 === cell2;
},
// 移除相匹配的方块
removeCells(rowIndex, colIndex) {
this.board[rowIndex].splice(colIndex, 1);
},
// 判断方块是否被选中
isSelected(rowIndex, colIndex) {
return this.selectedCell === this.board[rowIndex][colIndex];
},
},
};
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.board {
display: flex;
flex-direction: column;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
margin: 5px;
background-color: lightgray;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.selected {
background-color: orange;
}
</style>
```
这个示例代码实现了一个简单的消消乐游戏,通过点击方块来进行消除。你可以根据需求自定义样式和添加更多的游戏逻辑。
阅读全文