I'd like to try coding without tutorials so I hope you can help me... So I begin writing the javascript and I am stuck here, Am I in the right path ? I can't display the message, and when I click on the button nothing seems to happen (don't have an error message or anything) maybe it's a syntax issue ? I can't figure it out the issue, thanks
What I want to do :
script.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");
}
index
<h1>Shifumi</h1>
<div class="container">
<button id="btn">Pierre</button>
<button id="btn">Feuille</button>
<button id="btn">Ciseaux</button>
</div>
Your first problem is the randomizing. Take a look at the following function:
function getGame(game) {
return game[parseInt(Math.random() * game.length)];
}
const game = ["rock", "paper", "scissors"];
console.log(getGame(game));
Basically, you get a number between 0 and 1 when you run Math.random(). Multiplying it with game.length (the number of games) enforces it between the interval of [0, game.length]. Getting the game on this index will return a random game.
Your second problem is comparing the user choice with the randomized choice:
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>
Now, I have changed your id attributes to class attributes, because using the same id for different items in the same document is invalid, since the id stands for identifier and having the same identifier to several items defeats the purpose. Then I have added an event handler to each of your buttons which runs a function that takes the inner text of those buttons as value, finds their position in game and then compares it to a random computer move. I have logged the results to reflect the situation at hand.