本文将详细指导您如何使用 JavaScript、HTML 和 CSS 构建一个基础的网页版猜词游戏。您将学习如何随机选择一个词语、将其拆分成单个字符、用下划线初始化显示,并实现用户输入处理,支持猜测单个字母或整个词语,并根据猜测结果动态更新游戏界面。
1. 游戏概述与核心逻辑
本教程将创建一个类似于“字母盘”或“猜谜”的网页游戏。游戏的核心逻辑包括:
- 词语选择: 从预设的电影标题列表中随机选择一个作为谜底。
- 字符拆分: 将选定的谜底词语拆分成单个字符数组,便于逐个处理。
- 初始显示: 在页面上为每个字符显示一个下划线 _,代表待猜测的字母。
- 用户猜测: 允许用户输入单个字母或整个词语进行猜测。
- 结果判断: 根据用户的猜测,判断是否正确,并更新显示。
2. HTML 结构
首先,我们需要一个基本的 HTML 结构来承载游戏界面。这包括一个用于显示谜底的 div 容器,以及一个用于用户输入的文本框。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>猜词游戏</title> <link rel="stylesheet" href="https://www.php.cn/faq/style.css"> </head> <body> <div id="display"></div> <span>请猜一个字母或整个标题:</span> <input type="text" id="entry"> <script src="https://www.php.cn/faq/script.js"></script> </body> </html>
- div id=”display”:这个容器将动态插入
元素,每个
元素代表谜底的一个字母(或下划线)。
- input type=”text” id=”entry”:用户在此输入他们的猜测。
3. CSS 样式
为了让游戏界面看起来更清晰,我们添加一些基本的 CSS 样式。
p { float: left; /* 让字母块横向排列 */ margin: 10px; padding: 5px; /* 增加内边距 */ background-color: white; border: 1px solid #ccc; /* 添加边框 */ min-width: 30px; /* 确保每个字母块有最小宽度 */ text-align: center; /* 文本居中 */ font-size: 1.5em; /* 字体大小 */ font-weight: bold; } body { background-color: lightgray; margin-top: 100px; font-family: Arial, sans-serif; display: flex; /* 使用 flexbox 布局 */ flex-direction: column; /* 垂直排列 */ align-items: center; /* 水平居中 */ } #display { margin-bottom: 20px; display: flex; /* 让内部的 p 元素也使用 flex 布局 */ flex-wrap: wrap; /* 允许换行 */ justify-content: center; /* 居中显示字母块 */ } span { margin-right: 10px; font-size: 1.2em; } input { padding: 8px; font-size: 1.1em; border: 1px solid #aaa; border-radius: 5px; }
这些样式将使每个字母显示为独立的白色方块,并使整个页面居中显示。
4. JavaScript 实现
这是游戏的核心逻辑部分。我们将逐步构建它。
立即学习“Java免费学习笔记(深入)”;
4.1 初始化游戏数据
// 电影标题列表作为谜底 var movietitles = ['Iron Man', 'Jaws', 'Avengers', 'Evil Dead', 'It', 'Transformers', 'Little Mermaid', 'Mulan', 'Scooby Doo']; // 随机选择一个电影标题 const selection = movietitles[Math.floor(Math.random() * movietitles.length)]; // 将选定的标题拆分为字符数组 let text = selection; const game = text.split(""); // 用于跟踪已猜对的字母,初始全部为 false (未猜对) // 对于空格,我们默认它们是“猜对”的,因为它们不需要被用户猜 var correctGuesses = new Array(game.length).fill(false).map((val, index) => game[index] === ' ' ? true : false); // 获取用户输入框和显示区域的 DOM 元素 var userInput = document.getElementById('entry'); var displayContainer = document.getElementById("display");
- movietitles:存储所有可能的谜底。
- selection:通过 Math.random() 随机选出的当前谜底。
- game:将谜底字符串拆分为字符数组,例如 “Iron Man” 会变成 [‘I’, ‘r’, ‘o’, ‘n’, ‘ ‘, ‘M’, ‘a’, ‘n’]。
- correctGuesses:这是一个布尔数组,与 game 数组长度相同。correctGuesses[i] 为 true 表示 game[i] 处的字母已经被猜对并显示出来,否则显示下划线。我们初始化时,将空格对应的位置设为 true。
4.2 渲染初始显示
我们需要一个函数来根据 correctGuesses 数组的状态渲染或更新谜底的显示。
/** * 根据 correctGuesses 数组的状态更新显示。 * 未猜对的字母显示为下划线,已猜对的字母显示其本身。 */ function updateDisplay() { displayContainer.innerHTML = ''; // 清空当前显示 for (var i = 0; i < game.length; i++) { var newEl = document.createElement('p'); // 如果该位置的字母已猜对,则显示字母本身,否则显示下划线 var charToDisplay = correctGuesses[i] ? game[i] : "_"; var newNode = document.createTextNode(charToDisplay); newEl.appendChild(newNode); displayContainer.appendChild(newEl); } } // 首次加载时调用,显示所有下划线 updateDisplay();
updateDisplay() 函数负责根据 correctGuesses 数组的内容,在 displayContainer 中创建
元素来显示下划线或已猜对的字母。在游戏初始化时,我们会调用它一次。
4.3 处理用户猜测
现在,我们来处理用户在输入框中输入内容并按回车(change 事件触发)时的逻辑。
/** * 处理用户猜测的入口函数。 * 判断是字母猜测还是词语猜测。 * @param {string} guess 用户输入的猜测内容。 */ function handleGuess(guess) { if (!guess) { // 如果输入为空,则不处理 return; } // 将猜测转换为小写,便于不区分大小写比较 const normalizedGuess = guess.toLowerCase(); if (normalizedGuess.length === 1) { // 如果是单个字符,则认为是字母猜测 guessLetter(normalizedGuess); } else { // 否则认为是词语猜测 guessWord(normalizedGuess); } userInput.value = ''; // 清空输入框 checkGameStatus(); // 每次猜测后检查游戏状态 } /** * 处理单个字母猜测。 * @param {string} letter 用户猜测的字母。 */ function guessLetter(letter) { let found = false; for (let i = 0; i < game.length; i++) { // 不区分大小写比较 if (game[i].toLowerCase() === letter) { correctGuesses[i] = true; // 标记该位置的字母已猜对 found = true; } } if (found) { alert(`恭喜!字母 "${letter.toUpperCase()}" 猜对了!`); updateDisplay(); // 更新显示 } else { alert(`很遗憾,字母 "${letter.toUpperCase()}" 不在谜底中。`); } } /** * 处理整个词语猜测。 * @param {string} word 用户猜测的整个词语。 */ function guessWord(word) { // 将原始谜底也转换为小写,并移除空格进行比较,以应对用户可能不输入空格的情况 const normalizedSelection = selection.toLowerCase().replace(/\s/g, ''); const normalizedGuess = word.toLowerCase().replace(/\s/g, ''); if (normalizedSelection === normalizedGuess) { alert("恭喜!您猜对了整个电影标题!游戏胜利!"); // 猜对整个词语后,显示所有字母 correctGuesses.fill(true); updateDisplay(); userInput.disabled = true; // 禁用输入框 } else { alert("很遗憾,整个标题猜错了。请再试一次。"); } } /** * 检查游戏是否胜利(所有字母都已猜对)。 */ function checkGameStatus() { const allGuessed = correctGuesses.every(val => val === true); if (allGuessed) { alert("恭喜!您已猜出所有字母!游戏胜利!"); userInput.disabled = true; // 禁用输入框 } } // 监听用户输入框的 change 事件 userInput.addEventListener('change', function() { handleGuess(userInput.value); });
- handleGuess(guess):这是用户输入事件的统一处理函数。它会根据输入的长度判断是字母猜测还是词语猜测,并调用相应的处理函数。
- guessLetter(letter):遍历 game 数组,查找所有匹配的字母(不区分大小写),将 correctGuesses 中对应位置的布尔值设为 true,然后调用 updateDisplay() 更新界面。
- guessWord(word):将用户猜测的词语和原始谜底都转换为小写并移除空格,然后进行比较。如果完全匹配,则提示胜利,并禁用输入框。
- checkGameStatus():在每次猜测后调用,检查 correctGuesses 数组是否所有元素都为 true。如果是,则表示所有字母都已猜对,游戏胜利。
- userInput.addEventListener(‘change’, …):当用户在输入框中输入内容并按回车键或输入框失去焦点时,会触发 change 事件,从而调用 handleGuess 函数。
5. 完整代码示例
将上述 HTML、CSS 和 JavaScript 代码分别保存为 index.html、style.css 和 script.js,并确保它们在同一目录下。
index.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>猜词游戏</title> <link rel="stylesheet" href="https://www.php.cn/faq/style.css"> </head> <body> <div id="display"></div> <span>请猜一个字母或整个标题:</span> <input type="text" id="entry"> <script src="https://www.php.cn/faq/script.js"></script> </body> </html>
style.css
p { float: left; margin: 10px; padding: 5px; background-color: white; border: 1px solid #ccc; min-width: 30px; text-align: center; font-size: 1.5em; font-weight: bold; } body { background-color: lightgray; margin-top: 100px; font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; } #display { margin-bottom: 20px; display: flex; flex-wrap: wrap; justify-content: center; } span { margin-right: 10px; font-size: 1.2em; } input { padding: 8px; font-size: 1.1em; border: 1px solid #aaa; border-radius: 5px; }
script.js
var movietitles = ['Iron Man', 'Jaws', 'Avengers', 'Evil Dead', 'It', 'Transformers', 'Little Mermaid', 'Mulan', 'Scooby Doo']; const selection = movietitles[Math.floor(Math.random() * movietitles.length)]; let text = selection; const game = text.split(""); var correctGuesses = new Array(game.length).fill(false).map((val, index) => game[index] === ' ' ? true : false); var userInput = document.getElementById('entry'); var displayContainer = document.getElementById("display"); function updateDisplay() { displayContainer.innerHTML = ''; for (var i = 0; i < game.length; i++) { var newEl = document.createElement('p'); var charToDisplay = correctGuesses[i] ? game[i] : "_"; var newNode = document.createTextNode(charToDisplay); newEl.appendChild(newNode); displayContainer.appendChild(newEl); } } function handleGuess(guess) { if (!guess) { return; } const normalizedGuess = guess.toLowerCase(); if (normalizedGuess.length === 1) { guessLetter(normalizedGuess); } else { guessWord(normalizedGuess); } userInput.value = ''; checkGameStatus(); } function guessLetter(letter) { let found = false; for (let i = 0; i < game.length; i++) { if (game[i].toLowerCase() === letter) { correctGuesses[i] = true; found = true; } } if (found) { alert(`恭喜!字母 "${letter.toUpperCase()}" 猜对了!`); updateDisplay(); } else { alert(`很遗憾,字母 "${letter.toUpperCase()}" 不在谜底中。`); } } function guessWord(word) { const normalizedSelection = selection.toLowerCase().replace(/\s/g, ''); const normalizedGuess = word.toLowerCase().replace(/\s/g, ''); if (normalizedSelection === normalizedGuess) { alert("恭喜!您猜对了整个电影标题!游戏胜利!"); correctGuesses.fill(true); updateDisplay(); userInput.disabled = true; } else { alert("很遗憾,整个标题猜错了。请再试一次。"); } } function checkGameStatus() { const allGuessed = correctGuesses.every(val => val === true); if (allGuessed) { alert("恭喜!您已猜出所有字母!游戏胜利!"); userInput.disabled = true; } } userInput.addEventListener('change', function() { handleGuess(userInput.value); }); // 初始显示 updateDisplay();
6. 注意事项与功能扩展
- 大小写不敏感: 当前实现已经对字母和词语猜测进行了大小写不敏感处理,提高了用户体验。
- 空格处理: 谜底中的空格在初始化时就被视为已猜对并显示出来。
- 重复猜测: 当前版本未对重复猜测的字母进行特殊处理,用户可以反复猜测同一个字母。可以添加一个 guessedLetters 集合来存储已猜过的字母,避免重复提示。
- 错误计数与游戏失败: 可以引入一个错误计数器,当错误猜测达到一定次数时,游戏失败。
- 游戏重置: 添加一个“重新开始”按钮,允许玩家开始新一轮游戏。
- 用户界面反馈: 除了 alert 弹窗,可以考虑在页面上显示更友好的提示信息(例如,已猜过的字母列表,剩余猜测次数等)。
- 输入验证: 可以在 handleGuess 函数中增加输入验证,例如,只允许输入字母字符。
7. 总结
通过本教程,您已经学会了如何使用 HTML、CSS 和 JavaScript 构建一个基本的猜词游戏。这包括了随机选择谜底、动态渲染界面、处理用户输入(无论是单个字母还是整个词语),并根据猜测结果更新游戏状态。在此基础上,您可以根据“注意事项”中的建议,进一步扩展和完善您的游戏,使其功能更强大,用户体验更佳。
暂无评论内容