下面是我在 Web 开发课程中必须进行的石头剪刀布游戏活动的 JS 文件。我能够让一切正常工作,但是我不喜欢 if-else 语句使我的代码花费了多长时间,并且想知道如何使其更加简洁并以更少的代码行数实现。
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>";
}
}
});
就像我说的,一切正常,我有我的 html/css 文件。然而,我关心的只是我的 if 语句。我有更好的方法来编写它们吗?
我认为类似这样的东西会节省你很多代码行:
if(randomIndex==randomIndex2) {
div.innerHTML="<h1>Tie!</h1>";
}
else {
var playerWins = (randomIndex==0 && randomIndex2==1) || (randomIndex==1 && randomIndex2==2) || (randomIndex==2 && randomIndex2==0)
div.innerHTML = playerWins ? "<h1>Player Wins</h1>" : "<h1>Computer Wins</h1>"
}
编辑:
(这是使用下面的 mod (%) 建议进行的快速重写,请参阅 Megaaptera novaeangliae)
const imagePath = ["img/paper.png", "img/rock.png", "img/scissors.png"];
const playButton = document.querySelector("#play");
const playerImage = document.querySelector("#player");
const computerImage = document.querySelector("#computer");
const div = document.querySelector("#message");
let computerChoice, playerChoice;
function randomChoice() {
return Math.floor(Math.random() * imagePath.length);
}
function randomize() {
playerChoice = randomChoice();
computerChoice = randomChoice();
playerImage.src = imagePath[playerChoice];
computerImage.src = imagePath[computerChoice];
}
let intervalObject = setTimeout(randomize, 500);
playButton.addEventListener("click", function() {
clearInterval(intervalObject);
// paper=0, rock=1, scissors=2
if (playerChoice == computerChoice) {
div.innerHTML = "<h1>Tie!</h1>";
} else if (playerChoice == (computerChoice + 1) % imagePath.length) {
div.innerHTML = "<h1>Player Wins</h1>";
} else {
div.innerHTML = "<h1>Computer Wins</h1>";
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)