js翻牌小游戏
时间: 2023-07-23 12:06:05 浏览: 250
js记忆翻牌匹配小游戏代码.zip
这里是一个简单的JS翻牌小游戏的实现,它包括一个HTML文件和一个JS文件:
HTML文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>翻牌小游戏</title>
<style type="text/css">
.container {
display: flex;
flex-wrap: wrap;
width: 300px;
margin: 0 auto;
}
.card {
width: 100px;
height: 100px;
margin: 5px;
background-color: #ccc;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
color: #fff;
cursor: pointer;
transition: transform 0.3s ease-in-out;
}
.card:hover {
transform: scale(1.1);
}
</style>
</head>
<body>
<h1>翻牌小游戏</h1>
<div class="container"></div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
```
JS文件:
```javascript
const nums = [1, 2, 3, 4, 5, 6, 7, 8];
const cards = [...nums, ...nums]; // 生成16张牌
let firstCard = null; // 记录第一次翻牌
let secondCard = null; // 记录第二次翻牌
let isFlipping = false; // 防止连续翻牌
let matchedCards = []; // 记录已经匹配的牌
function shuffleCards(cards) {
return cards.sort(() => Math.random() - 0.5);
}
function createCard(num) {
const card = document.createElement('div');
card.classList.add('card');
card.dataset.num = num;
card.textContent = num;
card.addEventListener('click', handleCardClick);
return card;
}
function renderCards() {
const container = document.querySelector('.container');
container.innerHTML = '';
const shuffledCards = shuffleCards(cards);
shuffledCards.forEach(num => {
const card = createCard(num);
container.appendChild(card);
});
}
function handleCardClick() {
if (isFlipping || matchedCards.includes(this)) {
return;
}
this.classList.add('flipped');
if (!firstCard) {
firstCard = this;
} else if (!secondCard) {
secondCard = this;
isFlipping = true;
if (firstCard.dataset.num === secondCard.dataset.num) {
matchedCards.push(firstCard, secondCard);
firstCard = null;
secondCard = null;
isFlipping = false;
if (matchedCards.length === cards.length) {
setTimeout(() => {
alert('恭喜你,游戏胜利!');
renderCards();
}, 500);
}
} else {
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
firstCard = null;
secondCard = null;
isFlipping = false;
}, 1000);
}
}
}
renderCards();
```
这个游戏会生成16张牌,每张牌上有一个数字,你需要点击牌翻开它,然后再点击另一张牌翻开它,如果两张牌上的数字一样,那么它们就会保持翻开状态,否则会在1秒钟后自动翻回去。当所有的牌都匹配成功后,游戏就胜利了。
阅读全文