[英]shifumi : am I on the right path ? (coding js)
我想在没有教程的情况下尝试编码,所以我希望你能帮助我......所以我开始编写 javascript 并且我被困在这里,我在正确的道路上吗? 我无法显示消息,当我单击按钮时似乎没有发生任何事情(没有错误消息或任何东西)可能是语法问题? 无法解决问题,谢谢
我想做的事 :
脚本.js
const game = ["rock", "paper", "scissors"];
// faire apparaitre aléatoirement le rock paper scissors
const computer = (aiChoice) => {
aiChoice = (Math.random() * game.length) | 0;
const result = game[aiChoice];
console.log(result);
};
// création fonction player
function player(userChoice, aiChoice) {
document.getElementById("btn").click();
if (userChoice === "rock" && aiChoice === "rock") {
alert("Il y a égalité");
} else alert("ceci est un test");
}
指数
<h1>Shifumi</h1>
<div class="container">
<button id="btn">Pierre</button>
<button id="btn">Feuille</button>
<button id="btn">Ciseaux</button>
</div>
你的第一个问题是随机化。 看看下面的函数:
function getGame(game) { return game[parseInt(Math.random() * game.length)]; } const game = ["rock", "paper", "scissors"]; console.log(getGame(game));
基本上,当您运行Math.random()
时,您会得到一个介于 0 和 1 之间的数字。 将它与game.length
(游戏数)相乘会在 [0, game.length] 的区间内强制执行它。 获取该索引上的游戏将返回一个随机游戏。
您的第二个问题是将用户选择与随机选择进行比较:
const game = ["rock", "paper", "scrissors"]; // faire apparaitre aléatoirement le rock paper scissors const getAIChoice = (game) => { return parseInt(Math.random() * game.length); }; for (let btn of document.getElementsByClassName("btn")) { btn.addEventListener("click", function() { let choice = game.indexOf(this.innerText); let aiChoice = getAIChoice(game); console.log({player: game[choice], ai: game[aiChoice]}); if (((aiChoice + 1) % 3) === choice) alert("You win"); else if (aiChoice === choice) alert("Draw"); else alert("You lose"); }) }
<h1>Shifumi</h1> <div class="container"> <button class="btn">rock</button> <button class="btn">paper</button> <button class="btn">scrissors</button> </div>
现在,我已将您的id
属性更改为class
属性,因为对同一文档中的不同项目使用相同的id
是无效的,因为id
代表标识符并且对多个项目具有相同的标识符会破坏目的。 然后我为您的每个按钮添加了一个事件处理程序,该处理程序运行一个函数,该函数将这些按钮的内部文本作为值,找到它们在game
中的位置,然后将其与随机计算机移动进行比较。 我已经记录了结果以反映手头的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.