jQuery字母消除游戏
以下是一个简单的jQuery字母消除游戏的实现示例。这个示例使用了一个简单的游戏逻辑,其中玩家需要点击连续相同字母的方块,使其消失,每消除一行或一列所有方块,玩家将得分。
HTML 部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Letter Elimination Game</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="game-container">
<div class="grid-container">
<!-- 动态生成游戏方块 -->
</div>
<div id="score">Score: 0</div>
</div>
</body>
</html>
CSS 部分(style.css):
.game-container {
width: 500px;
margin: auto;
text-align: center;
}
.grid-container {
width: 500px;
margin: 20px auto;
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 5px;
}
.grid-item {
background-color: #f0f0f0;
border: 1px solid #ccc;
cursor: pointer;
}
#score {
margin-top: 20px;
}
jQuery 部分(script.js):
$(document).ready(function() {
var score = 0;
var letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
function generateGrid() {
var gridHtml = '';
for (var i = 0; i < 10; i++) {
gridHtml += '<div class="grid-row">';
for (var j = 0; j < 7; j++) {
var randomLetter = letters[Math.floor(Math.random() * letters.length)];
gridHtml += '<div class="grid-item" data-letter="' + randomLetter + '">' + randomLetter + '</div>';
}
gridHtml += '</div>';
}
$('.grid-container').html(gridHtml);
}
generateGrid();
$('.grid-item').on('click', function() {
var $this = $(this);
var letter = $this.data('letter');
var $row = $this.parent();
var $column = $this.siblings();
var clearedRow = true;
var clearedColumn = true;
// 检查行
$row.find('.grid-item').each(function() {
if ($(this).data('letter') !== letter) {
clearedRow = false;
return false; // 停止循环
}
});
// 检查列
$('.grid-container').find('.grid-item').each(function() {
if ($(this).data('letter') !== letter) {
clearedColumn = false;
return false; // 停止循环
}
});
// 如果是连续相同的字母,则清除
if (clearedRow || clearedColumn) {
$row.
评论已关闭