简体   繁体   English

硬币翻转游戏 JS/HTML

[英]Coin Flip Game JS/HTML

I'm trying to create a coin flip game, with a button for both guessing heads and tails with appropriate outputs for the guess - you guessed x, and the answer is x, you're correct/you guessed x and the answer is y, you're incorrect.我正在尝试创建一个掷硬币游戏,带有一个用于猜测正面和反面的按钮,并带有适当的猜测输出 - 你猜对了 x,答案是 x,你是正确的/你猜对了 x,答案是 y ,你错了。 I'm new to JS, and I'm struggling to find out why I'm not having results for the game when buttons are clicked.我是 JS 的新手,我正在努力找出为什么单击按钮时我没有获得游戏结果。

 document.getElementById('flipHeads').onclick = click; var flipHeads = Math.round(Math.random()) + 1; function click(flipHeads) { if (coinFlip == 1) { var Result = "flipHeads"; } else { var Result = "flipTails"; } if (Result == flipHeads) { if (Result == "heads") { alert("The flip was heads and you chose heads...you win!"); } else { alert("The flip was tails and you chose heads...you lose!"); } } } document.getElementById('flipTails').onclick = click; function click(flipTails) { var flipTails = Math.round(Math.random()) + 1; if (Result == fliptails) { alert("The flip was heads and you chose tails...you lose!"); } else { alert("The flip was tails and you chose tails...you win!"); } } function flip(flipHeads) { document.getElementById("result").innerHTML = Heads; }; function flip(flipTails) { document.getElementById("result").innerHTML = Tails; };
 <div> <button id="flipHeads" type="button">Heads</button> <button id="flipTails" type="button">Tails</button> <div id="result"></div> </div>

I simplified your code and made it actually work.我简化了您的代码并使其真正起作用。 I will go step by step through the changes:我将逐步完成更改:

  1. I gave the containing div and ID (flip).我给出了包含的div和 ID(翻转)。 Then I changed the ID of the button to just Heads or Tails .然后我将按钮的 ID 更改为HeadsTails
  2. I used an eventListener that looks for a click event within the div id="flip"我使用了一个在div id="flip"中查找点击事件的eventListener
  3. this event looks if the element that was clicked on is a button and not the containing element itself.此事件查看被单击的元素是否是button而不是包含元素本身。
  4. The script stores the ID of the clicked element as variable which is either Heads or Tails该脚本将单击元素的 ID 存储为变量,即HeadsTails
  5. Then it randomly rolls from an array to get a result that is either Heads or Tails然后它从一个数组中随机滚动得到一个HeadsTails的结果
  6. Last but not least it compares the ID of the clicked button with the rolled "flip".最后但并非最不重要的一点是将点击按钮的 ID 与滚动的“翻转”进行比较。 Depending if both strings are identical it outputs a result.根据两个字符串是否相同,它会输出结果。 The "flip" as well as the "pick" are included as variables to shorten the code. “翻转”和“选择”作为变量包含在内以缩短代码。

 /* checks for a click event within the div id="flip" */ const onClick = (event) => { /* checks if a button was clicked */ if (event.target.nodeName === 'BUTTON') { /* gets the ID of the clicked button as string */ var choice = event.target.id; /* Array to roll between different strings over then a number */ var roll = [ 'Heads', 'Tails' ]; var flip = roll[Math.floor(Math.random() * roll.length)]; /* checks if the flip and the pick is the same */ if (choice == flip) { var result = ' ...you win!'; } else { var result = ' ...you lose!'; } /* outputs the result */ alert('The flip was ' + flip + ' and you chose ' + choice + result); } } document.querySelector('#flip').addEventListener('click', onClick);
 <div id="flip"> <button id="Heads" type="button">Heads</button> <button id="Tails" type="button">Tails</button> <div id="result"></div> </div>

There are several errors you've made in the code;您在代码中犯了几个错误; here are some of them that I could find, but there are more:以下是我能找到的一些,但还有更多:

  • document.getElementById( [element] ).onClick = click won't work - there should be parentheses after click ( click() ) document.getElementById( [element] ).onClick = click不起作用 - 点击后应该有括号( click click()
  • In if (Results == fliptails) , you misspelled the flipTails variable as fliptails .if (Results == fliptails)中,您将flipTails变量拼错为fliptails
  • The line document.getElementById("result").innerHTML = Heads tries to set the innerHTML of the results element to be equal to the variable Heads , which doesn't exist.document.getElementById("result").innerHTML = Heads尝试将结果元素的innerHTML设置为等于不存在的变量Heads You should wrap it in quotes (ie "Heads" ), to set the innerHTML to the string "Heads".您应该将它用引号括起来(即"Heads" ),以将 innerHTML 设置为字符串 "Heads"。 Likewise with [...] = Tails .同样与[...] = Tails

There's also quite a bit of confusion here, and in general the code is quite hard to salvage.这里也有相当多的混乱,通常代码很难挽救。 Thankfully however, there's a much more efficient way of accomplishing your goal.然而,值得庆幸的是,有一种更有效的方法可以实现您的目标。 Here's an example of functional, more efficient code for this - which I'll walk through:这是一个功能更有效的代码示例 - 我将逐步介绍:

 function flip(guess) { let sideLandedOn = Math.round(Math.random()) == 0 ? 'heads' : 'tails'; // "flip" coin document.getElementById("result").innerHTML = sideLandedOn; // set innerHTML of results element to side that coin landed on if (guess == sideLandedOn) { alert(`The coin landed on ${sideLandedOn} and you guessed ${guess}... you win!`); // alert user won } else { alert(`The coin landed on ${sideLandedOn} and you guessed ${guess}... you lose!`); // alert user lost } }
 <div> <button id="flipHeads" type="button" onclick="flip('heads');">Heads</button> <button id="flipTails" type="button" onclick="flip('tails');">Tails</button> <div id="result"></div> </div>

So, here's what's going on in the snippet:所以,这就是片段中发生的事情:

  • On the HTML side, when either button is clicked, it calls the flip() function, passing to it a parameter ( guess ) representing which side was guessed.在 HTML 端,当单击任一按钮时,它会调用flip()函数,向它传递一个参数 ( guess ),表示猜到了哪一侧。
  • On the JS side, after a button is clicked, the first line of code in the flip function ( let sideLandedOn = Math.round(Math.random()) == 0 ? 'heads' : 'tails' ) basically "flips" the coin by randomly generating a number that is either 0 or 1, and then deciding it is heads if it is 0, and tails if it is 1 via the conditional/ternary operator.在 JS 端,单击按钮后,翻转函数中的第一行代码( let sideLandedOn = Math.round(Math.random()) == 0 ? 'heads' : 'tails' )基本上“翻转”通过随机生成一个 0 或 1 的数字,然后通过条件/三元运算符确定如果为 0 则为正面,如果为 1 则为反面。 The line is effectively equivalent to this:该行实际上等效于:
let sideLandedOn;
if (Math.round(Math.random()) == 0) {
  sideLandedOn = 'heads';
} else {
  sideLandedOn = 'tails';
}
  • Then, we set the innerHTML of the result div to be equal to sideLandedOn.然后,我们将result div 的innerHTML设置为等于 sideLandedOn。
  • Then, we use a conditional to check if the user guessed correctly.然后,我们使用条件来检查用户是否猜对了。 An alert is generated displaying what side the coin landed on and what the user guessed, and whether they won or lost.会生成一个警报,显示硬币落在哪一边,用户猜到了什么,以及他们是赢了还是输了。

Note: the template literal注意:模板字面量

`The coin landed on ${sideLandedOn} and... `

is effectively equivalent to等效于

"The coin landed on " + sideLandedOn + " and..."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM