首页 > 解决方案 > 我的硬币游戏代码,但似乎无法弄清楚这部分

问题描述

<!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。

标签: javascripthtml

解决方案


代码中有几个小的逻辑问题。

  1. 当玩家输入正面或反面时,可以在代码中将其转换为 1 或 2,以便与随机生成的值进行比较。
  2. 如果玩家输入垃圾值,则应进行处理。
  3. 我不确定我是否理解显示结果的代码是做什么的,所以只是将其更改为显示获胜或失败的警报。

这是一个显示此操作的工作片段:

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);
  }
}


推荐阅读