石头剪刀布游戏¶
本示例显示了一个带有图形界面的 "石头剪刀布 "游戏网络应用程序的代码,该程序使用 HTML 和 JavaScript 实现。让我们来逐条分析。
样式(CSS)¶
<style>
部分定义了几种 CSS 规则:
``CSS
reset-btn:hover {¶
transform: scale(1.2);
transition: transform 0.2s;
} .choice-btn:hover:not(:disabled) { transform: scale(1.1); transition: transform 0.2s; } .choice-btn:disabled { 不透明度:0.5; cursor: not-allowed; }
这些样式添加了
* 悬停时重置按钮放大的动画;
* 悬停时放大选择按钮的动画(如果未禁用);
* 禁用选择按钮的样式(带有 "不允许 "光标的半透明)。
基本页面结构¶
文档正文包含游戏容器:
<div style="background: #f0f0f0f0; font-family: Arial, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px; border-radius: 20px; position: relative;">
其中有几个部分。
1.分数计数器: ``html.
<div style="display: flex; justify-content: space-between; margin-bottom: 20px; height: 100px; align-items: center;">
<div style="text-align: center; width: 50%; position: relative;">
<div style="position: relative; display: inline-block; vertical-align: middle; line-height: 0;">
<div id="player-choice" style="font-size: 80px;">🤠</div>
<div id="player-mini-choice" style="..."></div>
</div
</div
<div style="text-align: center; width: 50%; position: relative;">
<div style="position: relative; display: inline-block; vertical-align: middle; line-height: 0;">
<div id="computer-choice" style="font-size: 80px;">🤖</div>
<div id="computer-mini-choice" style="..."></div>
</div
</div
</div
3.选择按钮:
<div style="text-align: center; margin-bottom: 15px;">
<h3 style="margin-bottom: 10px; color: #444;">您的选择:</h3>
<div style="display: flex; justify-content: center; margin: 10px; margin-bottom: 15px;"> <br
<button onclick="makeChoice(0)" class="choice-btn" style="...">✊</button> <button onclick="makeChoice(0)" class="choice-btn" style="...">✊</button>
<button onclick="makeChoice(1)" class="choice-btn" style="...">✋</button>
<button onclick="makeChoice(2)" class="choice-btn" style="...">✌️</button>
</div
</div
JavaScript 逻辑¶
变量初始化¶
``javascript 让 playerScore = 0; let computerScore = 0; let gameActive = true;
const choices = ['✊', '✋', '✌️']; const beats = { '✊': '✌️', '✋': '✊', '✌️': '✋' };
辅助功能¶
1.updateScoreEmoji
用表情符号更新账户:
``javascript
函数 updateScoreEmoji(scoreElement, score) {
const emojiScores = [' 0️⃣', ' 1️⃣', ' 2️⃣', ' 3️⃣'];
scoreElement.textContent = emojiScores[score] || score;
}
2.`animateComputerChoice` 动画显示计算机选择:
``javascript
function animateComputerChoice(finalChoice, callback) {
let iterations = 0;
const animationInterval = setInterval(() => {
document.getElementById('computer-choice').textContent = choices[iterations % 3];
迭代++;
if (iterations > 10) {
clearInterval(animationInterval);
document.getElementById('computer-choice').textContent = '🤖';
document.getElementById('computer-mini-choice').textContent = finalChoice;
if (callback) callback();
}
}, 100);
}
游戏的主要功能是¶
makeChoice
- 玩家选择处理程序: ``javascript function makeChoice(choiceIdx) { if (!gameActive) { alert('Game is over. Press 🔄 for a new one.'); 返回; } const playerEmoji = choices[choiceIdx]; const computerEmoji = choices[Math.floor(Math.random() * 3)];// 更新界面 document.getElementById('player-mini-choice').textContent = playerEmoji; document.getElementById('player-choice').textContent = '🤠'; document.querySelectorAll('.choice-btn').forEach(btn => btn.disabled = true); // 确定获胜者 function getWinner(player, computer) { if (player === computer) return 'draw'; return beats[player] === computer ?玩家' : '电脑 } const winner = getWinner(playerEmoji, computerEmoji);
// 更新分数 if (winner === 'player') { playerScore++; } else if (winner === 'computer') { computerScore++; } // 检查游戏结束 if (playerScore === 3 || computerScore === 3) { gameActive = false; }
// 制作电脑选择动画并更新界面 animateComputerChoice(computerEmoji, () => { updateScoreEmoji(document.getElementById('player-score'), playerScore); updateScoreEmoji(document.getElementById('computer-score'), computerScore);
// 显示结果 让 resultText = ''; if (!gameActive) { if (playerScore === 3) { resultText = '🏆玩家获胜!' } else { 否则 } else { resultText = '🤖机器人获胜!' } else { } } else { if (winner === 'draw') { resultText = '平局!' } else if (winner === 'player') { } else if (winner === 'player') { resultText = '你赢了这一轮!'; } else { resultText = '机器人赢了这一轮!' } else { resultText = 'You win this round! } } document.getElementById('result-text').textContent = resultText; // 根据游戏状态开关按钮 document.querySelectorAll('.choice-btn').forEach(btn => { btn.disabled = !gameActive; });
}); }
2. `resetGame` - 游戏重置:
``javascript
函数 resetGame() {
玩家分数 = 0;
computerScore = 0;
gameActive = true;
updateScoreEmoji(document.getElementById('player-score'), playerScore);
updateScoreEmoji(document.getElementById('computer-score'), computerScore);
document.getElementById('player-choice').textContent = '🤠';
document.getElementById('computer-choice').textContent = '🤖';
document.getElementById('player-mini-choice').textContent = '';
document.getElementById('computer-mini-choice').textContent = '';
document.getElementById('result-text').textContent = '';
document.querySelectorAll('.choice-btn').forEach(btn => btn.disabled = false);
}
该代码是一个完整的应用程序,具有 "石头-剪子-布 "游戏的界面和所有必要功能。
现在,让我们将应用程序连接到 Engee。最简单的方法是直接在 .ngscript 中调用并显示 HTML 文件。
@time display(MIME("text/html"), read("$(@__DIR__)/GUI.html", String))
或者,我们也可以使用 GenieFramework 调用 App.jl 文件来调用服务器
使用 GenieFramework
route("/") do
html(read(joinpath(@__DIR__, "GUI.html")), String))
结束
Pkg.add("GenieFramework")
using GenieFramework
# Запускаем приложение и получаем URL
app_url = string(engee.genie.start(string(@__DIR__,"/App.jl")))
# Извлекаем URL с помощью регулярного выражения
url_match = match(r"'(https?://[^']+)'", app_url)
url = url_match[1] # Получаем URL из первой группы захвата
根据运行服务器的结果,我们可以连接到URL的服务器,并在iframe中显示应用程序,而无需离开Engee。
iframe(内联框架)是一种 HTML 元素,可让您在当前页面中嵌入另一个 HTML 文档或网页。这样就在页面中创建了一个 "窗口",可以显示独立的内容。
``朱莉娅 htmll_content = """"""""""
display(MIME("text/html"), html_content)
输出¶
"石头-剪子-布 "游戏的代码是一个完整的网络应用程序。通过分析调用方法及其特点,可以得出以下结论。
1.直接 HTML 输出:
- 简单的无服务器演示;
- 在本地环境中运行 *Engee;
- 与其他组件的集成有限。
2.通过 GenieFramework:
- 运行完整的网络服务器、
- 允许在 iframe 中嵌入游戏、
- 适合集成到大型项目中、
- 运行需要更多时间、
- 提供运行时上下文隔离。