Below is my JS file for a rock, paper, scissors game activity we had to do in my web development class. I was able to get everything to work, however I do not like how long my if-else statements made my code and was wondering how can I make this more concise and have it in less lines of code.
const imagePath=[];
imagePath.push("img/paper.png");
imagePath.push("img/rock.png");
imagePath.push("img/scissors.png");
let counter=1;
let counter2=1;
let images=document.querySelector("#player");
let images2=document.querySelector("#computer");
function ImageChange()
{
images.src=imagePath[counter];
counter++;
if (counter == imagePath.length)
{
counter=0;
}
images2.src=imagePath[counter2];
counter2++;
if (counter2 == imagePath.length)
{
counter2=0;
}
}
let intervalObject=setInterval(ImageChange,500);
const playButton=document.querySelector("#play");
const div= document.querySelector("#message");
playButton.addEventListener("click",function(){
clearInterval(intervalObject);
let randomIndex=Math.floor(Math.random()*imagePath.length);
images.src=imagePath[randomIndex];
let randomIndex2=Math.floor(Math.random()*imagePath.length);
images2.src=imagePath[randomIndex2];
//paper=0,rock=1,scissors=2
if(randomIndex==randomIndex2)
{
div.innerHTML="<h1>Tie!</h1>";
}
else if(randomIndex==0)
{
if(randomIndex2==1)
{
div.innerHTML="<h1>Player Wins</h1>";
}
else
{
div.innerHTML="<h1>Computer Wins</h1>";
}
}
else if(randomIndex==1)
{
if(randomIndex2==2)
{
div.innerHTML="<h1>Player Wins</h1>";
}
else
{
div.innerHTML="<h1>Computer Wins</h1>";
}
}
else if(randomIndex==2)
{
if(randomIndex2==0)
{
div.innerHTML="<h1>Player Wins</h1>";
}
else
{
div.innerHTML="<h1>Computer Wins</h1>";
}
}
});
Like I said everything works and I have my html/css files. However, my concern is just with the if statements I have. Is there a better way I can write them?
Aucun commentaire:
Enregistrer un commentaire