我们将创建一个简单但完整的 “猜数字” 游戏,以此来展示如何使用 Bootstrap 来构建游戏界面。
最终效果预览
这个模板将包含三个主要界面,通过 Bootstrap 的模态框和 JavaScript 来切换:
- 开始界面: 欢迎玩家,显示游戏标题和“开始游戏”按钮。
- 游戏主界面: 显示游戏标题、提示信息、一个输入框让玩家猜数字,以及一个提交按钮。
- 游戏结束界面: 显示玩家是赢了还是输了,并给出“再玩一次”的选项。
第一步:准备工作
你需要一个开发环境,最简单的方式是:
- 创建一个项目文件夹,
bootstrap-game-template。 - 在该文件夹下创建三个文件:
index.htmlstyle.cssscript.js
第二步:HTML 结构 (index.html)
这是整个游戏的骨架,我们将使用 Bootstrap 的网格系统、组件和模态框来构建界面。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">Bootstrap 游戏模板</title>
<!-- 1. 引入 Bootstrap 的 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. 引入自定义的 CSS -->
<link rel="stylesheet" href="style.css">
</head>
<body class="bg-dark text-white">
<!-- 游戏主容器 -->
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6 text-center">
<!-- 游戏标题 -->
<h1 class="display-4 mb-4">猜数字游戏</h1>
<!-- 游戏状态提示信息 -->
<p id="game-message" class="lead">点击下方按钮开始游戏!</p>
<!-- 游戏内容区域 -->
<div id="game-content">
<!-- 初始时,这里可以放一些占位内容,或者为空 -->
<p>游戏即将开始...</p>
</div>
<!-- 控制按钮区域 -->
<div class="mt-4">
<button id="start-game-btn" class="btn btn-primary btn-lg">开始游戏</button>
</div>
</div>
</div>
</div>
<!-- 游戏结束模态框 -->
<div class="modal fade" id="gameOverModal" tabindex="-1" aria-labelledby="gameOverModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content bg-dark text-white border-secondary">
<div class="modal-header">
<h5 class="modal-title" id="gameOverModalLabel">游戏结束</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="game-result-message"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
<button type="button" id="play-again-btn" class="btn btn-primary">再玩一次</button>
</div>
</div>
</div>
</div>
<!-- 3. 引入 Bootstrap 的 JS (依赖 Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- 4. 引入自定义的 JS -->
<script src="script.js"></script>
</body>
</html>
HTML 解析:
- Bootstrap CDN: 我们通过 CDN 引入了 Bootstrap 的 CSS 和 JS,无需本地下载。
.container,.row,.col-md-6: 这是 Bootstrap 的经典响应式布局,将内容居中并限制在中等屏幕宽度内。#game-message: 一个<p>标签,用于动态显示游戏提示(如“猜大一点”、“猜小一点”)。#game-content: 一个<div>容器,我们将用 JavaScript 动态地在这里插入游戏界面(输入框等)。#start-game-btn: “开始游戏”按钮。#gameOverModal: Bootstrap 的模态框组件,用于显示游戏结束信息。modal-dialog-centered使其居中显示,我们自定义了其深色主题。
第三步:CSS 样式 (style.css)
这里我们添加一些自定义样式,让游戏看起来更有趣。
/* style.css */
body {
/* 使用背景图片增加游戏感 */
background-image: url('https://images.unsplash.com/photo-1533799834267-4be84414b7be?q=80&w=2070&auto=format&fit=crop');
background-size: cover;
background-position: center;
background-attachment: fixed;
font-family: 'Arial', sans-serif;
}
/* 半透明的遮罩层,让文字更清晰 */
body::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
z-index: -1;
}
#game-message {
min-height: 2rem; /* 保持高度稳定,防止布局跳动 */
}
/* 为输入框添加游戏风格 */
#guess-input {
background-color: rgba(255, 255, 255, 0.1);
border: 2px solid #6c757d;
color: white;
text-align: center;
font-size: 1.2rem;
}
#guess-input:focus {
background-color: rgba(255, 255, 255, 0.2);
border-color: #0d6efd;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
color: white;
}
#guess-input::placeholder {
color: #adb5bd;
}
/* 按钮悬停效果 */
.btn-primary {
background-color: #0d6efd;
border-color: #0d6efd;
transition: all 0.3s ease;
}
.btn-primary:hover {
background-color: #0b5ed7;
border-color: #0a58ca;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}
第四步:JavaScript 游戏逻辑 (script.js)
这是游戏的核心,负责处理用户交互和游戏状态。
// script.js
document.addEventListener('DOMContentLoaded', () => {
// --- DOM 元素 ---
const startGameBtn = document.getElementById('start-game-btn');
const gameContent = document.getElementById('game-content');
const gameMessage = document.getElementById('game-message');
const gameOverModal = new bootstrap.Modal(document.getElementById('gameOverModal'));
const gameResultMessage = document.getElementById('game-result-message');
const playAgainBtn = document.getElementById('play-again-btn');
// --- 游戏状态 ---
let targetNumber;
let attempts;
// --- 事件监听器 ---
startGameBtn.addEventListener('click', initGame);
playAgainBtn.addEventListener('click', () => {
gameOverModal.hide();
initGame();
});
// --- 游戏函数 ---
/**
* 初始化游戏
*/
function initGame() {
// 1. 生成目标数字 (1-100)
targetNumber = Math.floor(Math.random() * 100) + 1;
attempts = 0;
console.log('目标数字是:', targetNumber); // 方便调试
// 2. 更新UI
gameMessage.textContent = '我已经想好了一个 1 到 100 之间的数字,开始猜吧!';
// 3. 渲染游戏输入界面
renderGameInput();
}
/**
* 渲染游戏输入界面
*/
function renderGameInput() {
gameContent.innerHTML = `
<div class="input-group input-group-lg mb-3">
<input type="number" id="guess-input" class="form-control" placeholder="输入你的猜测" min="1" max="100">
<button class="btn btn-primary" type="button" id="submit-guess-btn">提交</button>
</div>
<p class="text-muted">尝试次数: <span id="attempts-count">0</span></p>
`;
// 为新创建的按钮添加事件监听
const submitGuessBtn = document.getElementById('submit-guess-btn');
const guessInput = document.getElementById('guess-input');
submitGuessBtn.addEventListener('click', handleGuess);
guessInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleGuess();
}
});
// 聚焦到输入框,提升用户体验
guessInput.focus();
}
/**
* 处理玩家的猜测
*/
function handleGuess() {
const guessInput = document.getElementById('guess-input');
const guess = parseInt(guessInput.value);
const attemptsCountSpan = document.getElementById('attempts-count');
// 输入验证
if (isNaN(guess) || guess < 1 || guess > 100) {
gameMessage.textContent = '请输入一个 1 到 100 之间的有效数字!';
return;
}
attempts++;
attemptsCountSpan.textContent = attempts;
// 判断猜测结果
if (guess === targetNumber) {
// 猜对了!
gameResultMessage.innerHTML = `
<h4>🎉 恭喜你赢了!🎉</h4>
<p>你猜对了数字 <strong>${targetNumber}</strong>!</p>
<p>你总共用了 <strong>${attempts}</strong> 次尝试。</p>
`;
gameOverModal.show();
} else if (guess < targetNumber) {
// 猜小了
gameMessage.textContent = '猜小了!再大一点试试。';
guessInput.value = ''; // 清空输入框
guessInput.focus();
} else {
// 猜大了
gameMessage.textContent = '猜大了!再小一点试试。';
guessInput.value = ''; // 清空输入框
guessInput.focus();
}
}
});
JavaScript 解析:
DOMContentLoaded: 确保整个 HTML 文档加载完毕后再执行 JS 代码。- 状态管理: 使用
targetNumber和attempts变量来追踪游戏核心状态。 - 事件委托: 我们为
startGameBtn和playAgainBtn添加了监听器。 initGame():- 生成一个 1-100 的随机数。
- 重置尝试次数。
- 更新提示信息。
- 调用
renderGameInput()来显示游戏界面。
renderGameInput():- 使用
gameContent.innerHTML动态创建输入框和提交按钮。 - 关键点: 为新创建的按钮和输入框添加事件监听器,同时支持点击按钮和按回车键提交。
guessInput.focus()让玩家可以直接开始输入,非常友好。
- 使用
handleGuess():- 获取玩家输入的值并转换为数字。
- 进行输入验证(是否为数字、是否在范围内)。
- 更新尝试次数。
- 核心逻辑:比较
guess和targetNumber,给出“大了”、“小了”或“正确”的反馈。 - 如果猜对,则填充模态框的内容并
show()出来。 - 如果猜错,清空输入框并重新聚焦,方便玩家连续猜测。
如何运行和使用这个模板?
- 将上面的代码分别复制到
index.html,style.css, 和script.js文件中。 - 将这三个文件放在同一个文件夹下。
- 用任何现代浏览器(如 Chrome, Firefox, Edge)打开
index.html文件。 - 你就可以开始玩游戏了!
如何扩展这个模板?
这个模板是一个绝佳的起点,你可以基于它构建更复杂的游戏:
- 增加更多界面: 为游戏的不同阶段(如设置难度、暂停菜单、排行榜)创建更多的模态框或隐藏的
div,然后通过 JS 来控制它们的显示和隐藏。 - 添加动画: 使用 Bootstrap 的
.fade,.show类结合 JavaScript,或者引入 AOS (Animate On Scroll) 等库,为游戏添加入场/退场动画。 - 美化界面: 更换
style.css中的背景图片、颜色主题和字体,打造独特的游戏风格。 - 功能扩展:
- 在猜数字游戏中增加“最高分记录”(最少尝试次数)功能,并使用
localStorage保存。 - 创建一个简单的点击游戏或记忆翻牌游戏,只需要修改
renderGameInput()和handleGuess()中的逻辑即可。 - 添加音效和背景音乐。
- 在猜数字游戏中增加“最高分记录”(最少尝试次数)功能,并使用
这个模板为你提供了一个清晰、可维护且响应式的游戏开发基础,祝你游戏开发愉快!
