一个基于html5+jquery实现的连连看小游戏
以下是一个简化版的连连看小游戏实现,仅包含核心功能:
<!DOCTYPE html>
<html>
<head>
<title>连连看游戏</title>
<style>
.card {
width: 80px;
height: 120px;
float: left;
margin: 10px;
cursor: pointer;
position: relative;
background-size: cover;
}
.card.matched {
opacity: 0.5;
}
</style>
</head>
<body>
<div id="game-board">
<!-- 卡片动态生成 -->
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var cards = ["1.jpg", "2.jpg", "3.jpg", ...]; // 所有卡片图片列表
var currentCard = null;
var matchedCards = [];
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function createCardsHTML() {
var html = '';
cards = shuffle(cards); // 洗牌
cards.forEach(function(card) {
html += '<div class="card" style="background-image: url(' + card + ');"></div>';
});
$('#game-board').html(html);
}
function resetGame() {
matchedCards = [];
currentCard = null;
$('.card').removeClass('matched');
}
createCardsHTML(); // 创建卡片HTML
$('.card').click(function() {
var $this = $(this);
if ($this.hasClass('matched')) return; // 已匹配的卡片不再响应点击
if (currentCard && $this[0] !== currentCard[0]) {
var card1 = currentCard.attr('style').match(/url\((.*)\)/)[1];
var card2 = $this.attr('style').match(/url\((.*)\)/)[1];
if (card1 === card2) { // 匹配卡片逻辑
currentCard.addClass('matched');
$this.addClass('matched');
matchedCards.push(currentCard);
matchedCards.push($this);
if (matchedCards.length === cards.length / 2) {
alert('恭喜你,游戏胜利!');
resetGame();
}
} else {
// 不匹配时的处理逻辑(例如:卡片翻转回原样)
setTimeout(function() {
评论已关闭