剪刀石头布游戏
这个例子展示了一个web应用程序的代码,石头剪刀布游戏与图形界面实现使用HTML和JavaScript。 让我们把它一块一块地拆开.
HTML结构
代码以标准HTML标记开头。:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Камень-ножницы-бумага</title>
样式(CSS)
在该部分 <style> 定义了几种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 {
opacity: 0.5;
cursor: not-allowed;
}
这些样式添加:
*悬停时重置按钮缩放的动画;
*悬停时选择按钮的放大倍数动画(如果它们未被禁用);
*禁用选择按钮的样式(半透明,光标为"不允许")。
页面的基本结构
文档的主体包含一个包含游戏的容器:
<div style="background: #f0f0f0; font-family: Arial, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px; border-radius: 20px; position: relative;">
里面有几个部分。
- 分数计数器:
<div style="display: flex; justify-content: center; align-items: center; gap: 20px; margin-bottom: 10px;">
<div style="background: white; padding: 15px; border-radius: 10px; text-align: center; font-size: 18px; flex-grow: 1;">
<div style="display: flex; justify-content: space-around; align-items: center;">
<div style="display: flex; align-items: center; gap: 5px;">
<div style="font-weight: bold;">ВЫ:</div>
<div id="player-score" style="font-size: 24px;">0️⃣</div>
</div>
<div style="font-weight: bold; font-size: 20px;">VS</div>
<div style="display: flex; align-items: center; gap: 5px;">
<div style="font-weight: bold;">Робот:</div>
<div id="computer-score" style="font-size: 24px;">0️⃣</div>
</div>
</div>
<div id="result-text"></div>
</div>
<button onclick="resetGame()" id="reset-btn" style="background: none; border: none; cursor: pointer; font-size: 24px; margin-left: 10px;">🔄</button>
</div>
- 播放器和电脑选择区:
<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>
- 选择按钮:
<div style="text-align: center; margin-bottom: 15px;">
<h3 style="margin-bottom: 10px; color: #444;">Ваш выбор:</h3>
<div style="display: flex; justify-content: center; gap: 10px; margin-bottom: 15px;">
<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逻辑
初始化变量
let playerScore = 0;
let computerScore = 0;
let gameActive = true;
const choices = ['✊', '✋', '✌️'];
const beats = {
'✊': '✌️',
'✋': '✊',
'✌️': '✋'
};
辅助功能
updateScoreEmoji使用emojis更新帐户:
function updateScoreEmoji(scoreElement, score) {
const emojiScores = ['0️⃣', '1️⃣', '2️⃣', '3️⃣'];
scoreElement.textContent = emojiScores[score] || score;
}
animateComputerChoice动画计算机选择:
function animateComputerChoice(finalChoice, callback) {
let iterations = 0;
const animationInterval = setInterval(() => {
document.getElementById('computer-choice').textContent = choices[iterations % 3];
iterations++;
if (iterations > 10) {
clearInterval(animationInterval);
document.getElementById('computer-choice').textContent = '🤖';
document.getElementById('computer-mini-choice').textContent = finalChoice;
if (callback) callback();
}
}, 100);
}
游戏的主要功能
makeChoice-玩家选择处理程序:
function makeChoice(choiceIdx) {
if (!gameActive) {
alert('Игра окончена. Нажмите 🔄 для новой.');
return;
}
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 ? '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);
// Показываем результат
let resultText = '';
if (!gameActive) {
if (playerScore === 3) {
resultText = '🏆 Победил игрок!';
} else {
resultText = '🤖 Победил робот!';
}
} else {
if (winner === 'draw') {
resultText = 'Ничья!';
} else if (winner === 'player') {
resultText = 'Вы выиграли этот раунд!';
} else {
resultText = 'Робот выиграл в этом раунде!';
}
}
document.getElementById('result-text').textContent = resultText;
// Включаем/выключаем кнопки в зависимости от состояния игры
document.querySelectorAll('.choice-btn').forEach(btn => {
btn.disabled = !gameActive;
});
});
}
resetGame-重置游戏:
function resetGame() {
playerScore = 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。 最简单的选择是直接在中调用并显示HTML文件。ngscript。
In [ ]:
@time display(MIME("text/html"), read("$(@__DIR__)/GUI.html", String))
或者,我们可以通过调用应用程序来使用GenieFramework提升服务器。jl文件。
using GenieFramework
route("/") do
html(read(joinpath(@__DIR__, "GUI.html"), String))
end
In [ ]:
Pkg.add("GenieFramework")
using GenieFramework
In [ ]:
# 启动应用程序并获取URL
app_url = string(engee.genie.start(string(@__DIR__,"/App.jl")))
# 使用正则表达式提取URL
url_match = match(r"'(https?://[^']+)'", app_url)
url = url_match[1] # 从第一个捕获组获取URL
Out[0]:
根据服务器启动的结果,我们可以通过URL连接到服务器,并在iframe中显示应用程序,而无需离开Engee。
iframe(内联框架)是一个HTML元素,允许您在当前页面内嵌入另一个HTML文档或网页。 这会在页面内创建一个"窗口",可以在其中显示独立内容。
html_content = """<iframe src="$url" width="750" height="500" style="border: none;"></iframe>"""
display(MIME("text/html"), html_content)
结论
石头剪刀布游戏的代码是一个完整的web应用程序。 分析调用方法及其特性,可以进行以下观察。
-
直接HTML输出:
没有后端的简单演示;
在本地环境下工作工程师;
*与其他组件的集成有限。 -
通过GenieFramework:
*运行完整的web服务器,
*允许您在iframe中嵌入游戏,
*适合整合到更大的项目中,
*需要更多的启动时间,
*提供执行上下文的隔离。