
本教程将创建一个类似于“字母盘”或“猜谜”的网页游戏。游戏的核心逻辑包括:
首先,我们需要一个基本的 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="style.css">
</head>
<body>
<div id="display"></div>
<span>请猜一个字母或整个标题:</span>
<input type="text" id="entry">
<script src="script.js"></script>
</body>
</html>为了让游戏界面看起来更清晰,我们添加一些基本的 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;
}这些样式将使每个字母显示为独立的白色方块,并使整个页面居中显示。
这是游戏的核心逻辑部分。我们将逐步构建它。
立即学习“Java免费学习笔记(深入)”;
// 电影标题列表作为谜底
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");我们需要一个函数来根据 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 中创建 <p> 元素来显示下划线或已猜对的字母。在游戏初始化时,我们会调用它一次。
现在,我们来处理用户在输入框中输入内容并按回车(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);
});将上述 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="style.css">
</head>
<body>
<div id="display"></div>
<span>请猜一个字母或整个标题:</span>
<input type="text" id="entry">
<script src="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();通过本教程,您已经学会了如何使用 HTML、CSS 和 JavaScript 构建一个基本的猜词游戏。这包括了随机选择谜底、动态渲染界面、处理用户输入(无论是单个字母还是整个词语),并根据猜测结果更新游戏状态。在此基础上,您可以根据“注意事项”中的建议,进一步扩展和完善您的游戏,使其功能更强大,用户体验更佳。
以上就是使用 JavaScript 构建交互式猜词游戏:从随机选择到字母/单词猜测的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号