写一个消消乐
时间: 2023-09-20 17:12:21 浏览: 167
以下是一个简单的消消乐HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>消消乐</title>
<style>
body {
background-color: #ddd;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-size: 2rem;
}
.container {
display: flex;
flex-wrap: wrap;
width: 500px;
height: 500px;
background-color: #fff;
padding: 10px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.tile {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;
background-color: #eee;
margin: 5px;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s;
}
.tile:hover {
transform: scale(1.1);
}
.selected {
background-color: #ff0;
}
.matched {
background-color: #f00;
color: #fff;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
const colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple'];
const container = document.querySelector('.container');
const tiles = [];
let selected = [];
// 创建随机颜色的方块
function createTile() {
const color = colors[Math.floor(Math.random() * colors.length)];
const tile = document.createElement('div');
tile.classList.add('tile');
tile.dataset.color = color;
tile.innerText = color;
tile.addEventListener('click', () => {
if (selected.length < 2 && !tile.classList.contains('selected')) {
tile.classList.add('selected');
selected.push(tile);
if (selected.length === 2) {
if (selected[0].dataset.color === selected[1].dataset.color) {
selected.forEach(tile => {
tile.classList.remove('selected');
tile.classList.add('matched');
tile.removeEventListener('click', () => {});
});
} else {
setTimeout(() => {
selected.forEach(tile => {
tile.classList.remove('selected');
});
}, 1000);
}
selected = [];
}
}
});
return tile;
}
// 创建九宫格
for (let i = 0; i < 9; i++) {
const tile = createTile();
tiles.push(tile);
container.appendChild(tile);
}
</script>
</body>
</html>
```
这个代码会在页面中创建一个九宫格的消消乐游戏。每个方块会随机出现为六种颜色之一,玩家需要通过点击方块来消除相同颜色的方块。点击两个不同颜色的方块,它们会在1秒后翻转回去,如果点击了两个相同颜色的方块,它们就会消失并变为红色,表示已经匹配成功。游戏会持续进行,直到所有方块都匹配成功。
阅读全文