javascript - 我的硬币游戏代码,但似乎无法弄清楚这部分
问题描述
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
alert("Welcome to the coin flip game ! Enter either heads or tails..");
var person = prompt("Please enter either heads or tails");
if (person == heads) {
alert()
}
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
alert("The computer generated heads!");
} else {
alert("The computer generated tails!");
}
var lost =
alert("You've lost");
var won =
alert("You've won!");
if (person != random) {
document.getElementById("demo").innerHTML =
(lost);
} else {
(won);
}
</script>
</body>
</html>
我当前的代码^^
目标:介绍游戏并解释如何玩。接收用户的输入,特别是他们对硬币是正面还是反面的猜测。生成一个介于 1 或 2 之间的随机数,然后将其与正面或反面匹配。(即 1 = 正面,2 = 反面)检查他们的猜测是否与随机数匹配。如果他们猜对了,告诉他们他们赢了。如果猜错了,告诉他们他们输了。
我似乎无法弄清楚如何将随机数生成器的 1 和 2 轮分配给正面或反面。这是我的大问题。
这是html javascript。
解决方案
代码中有几个小的逻辑问题。
- 当玩家输入正面或反面时,可以在代码中将其转换为 1 或 2,以便与随机生成的值进行比较。
- 如果玩家输入垃圾值,则应进行处理。
- 我不确定我是否理解显示结果的代码是做什么的,所以只是将其更改为显示获胜或失败的警报。
这是一个显示此操作的工作片段:
alert("Welcome to the coin flip game ! Enter either heads or tails..");
var person = prompt("Please enter either heads or tails");
var personChoice = 0;
if (person == 'heads') {
personChoice = 1;
} else if (person == 'tails') {
personChoice = 2;
} else {
alert('The player entered rubbish!');
}
if (personChoice > 0) {
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
alert("The computer generated heads!");
} else {
alert("The computer generated tails!");
}
var lost = "You've lost";
var won = "You've won";
if (personChoice != random) {
alert(lost); //document.getElementById("demo").innerHTML = (lost);
} else {
alert(won);
//(won);
}
}
推荐阅读
- laravel - 使用 Laravel Sanctum 进行 Magic Link 登录
- jquery - 将通用 css 应用于 body 的所有子元素的文本
- python - 为什么我的缺失值被与我想要的不同的东西所取代?Python
- html - 如何在带有隐藏滚动条的div中显示div上的水平滚动条
- python - Python Beautifulsoup 循环一个标签 ( ) 并获取它的所有兄弟 (a href)
- reactjs - 如何为 MUI DataGrid 中的每一行添加一个按钮
- java - android studio 在后台使用摄像头
- xml - 基于元素值类型的 xml 的 XSLT 转换
- c# - C# 8.0 基于输入类型的 switch 表达式
- javascript - 如何显示highchart coloraxis min max value?