简体   繁体   English

如何为我的石头剪刀布游戏编写一套更简洁的代码?

[英]How can I write a neater set of code for my rock paper scissors game?

Below is my JS file for a rock, paper, scissors game activity we had to do in my web development class.下面是我的 JS 文件,用于我们在 web 开发 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.我能够让一切正常工作,但是我不喜欢我的 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>";
  }
}


});

Like I said everything works and I have my html/css files.就像我说的一切正常,我有我的 html/css 文件。 However, my concern is just with the if statements I have.但是,我关心的只是我拥有的 if 语句。 Is there a better way I can write them?有没有更好的方法可以写它们?

I'd think something more like this would save you a lot of lines of code:我认为更像这样的东西会为你节省很多代码行:

 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>" }

Edit: (Here's a quick rewrite using the mod (%) suggestion below, see Megaptera novaeangliae)编辑:(这里使用下面的 mod (%) 建议快速重写,请参阅 Megaptera 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>"; } });

If you look at your logic for randomIndex and randomIndex2 , you'll realize that all you need in the if condition is this:如果您查看randomIndexrandomIndex2的逻辑,您会意识到if条件中您需要的只是:

if(randomIndex2 === (randomIndex + 1) % 3)

Have a look here:看看这里:

 let a = 0, b = 1; console.log(b === (a + 1) % 3); a = 1, b = 2; console.log(b === (a + 1) % 3); a = 2, b = 0; console.log(b === (a + 1) % 3);

So, all those conditions could be shortened to:因此,所有这些条件都可以缩短为:

if (randomIndex == randomIndex2) {
  div.innerHTML = "<h1>Tie!</h1>";
} else if if (randomIndex2 === (randomIndex + 1) % 3) {
  div.innerHTML = "<h1>Player Wins</h1>";
} else {
  div.innerHTML = "<h1>Computer Wins</h1>";
}

This might be a personal preference, but I find things much neater when there is space between operators and operands.这可能是个人喜好,但是当运算符和操作数之间有空间时,我发现事情会更整洁。 And I also properly despise the我也适当地鄙视

else
{
...
}

Formatting scheme.格式化方案。 I would recommend, for neatness purposes, use出于整洁的目的,我建议使用

else { 
    ... 
}

Most people will also tell you not to, but I find it helps with neatness further: on single statement conditions or clauses, you can omit braces.大多数人也会告诉你不要这样做,但我发现它进一步有助于整洁:在单个语句条件或子句中,你可以省略大括号。

else 
    console.log("Else Clause")
console.log("Outside of Else");

I would also suggest using switch statements as these make code far more readable, although they have their own quirks, they are fantastic for making code readable.我还建议使用 switch 语句,因为它们使代码更具可读性,尽管它们有自己的怪癖,但它们对于使代码可读性非常好。 Further, I would also suggest to avoid one-liners.此外,我还建议避免单行。 I fell into that habit for a while and it hit me hard.我有一段时间养成了这个习惯,这对我打击很大。 You haven't really done that in this case, but I'm just adding it for future references.在这种情况下,您并没有真正做到这一点,但我只是将其添加以供将来参考。

Another thing you might find useful is grouping variables of similar usage/purpose.您可能会发现有用的另一件事是将具有相似用途/目的的变量分组。 So don't put newlines between them.所以不要在它们之间放置换行符。

Again, another personal preference is using 4-space indentation.同样,另一个个人偏好是使用 4 空格缩进。 Makes it more visible where the indents start and end.使缩进开始和结束的位置更加明显。

So in summary:总而言之:

  • Leave enough space between tokens在标记之间留出足够的空间
  • Place braces on the same line将大括号放在同一行
  • Blocks (Except try / catch ) with only one statement can omit their braces只有一个语句的块(除了try / catch )可以省略大括号
  • Use a switch statement使用switch语句
  • Group variables组变量
  • Use four spaces (spaces, not tabs)使用四个空格(空格,而不是制表符)

Hope that helps希望有帮助

To put the entire game logic into a simple script:要将整个游戏逻辑放入一个简单的脚本中:

Rock, Paper, Scissors to indexes: 0, 1, 2 Rock, Paper, Scissors to index: 0, 1, 2

result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1;
//                   |                         |   |
// 0 = PL wins --------------------------------┘   |
// 1 = AI wins ------------------------------------┘
// 2 = draw    ------┘

Having those three indexes in place you can now easily retrieve the respective played figure-names and the needed won/draw message from Arrays :有了这三个索引,您现在可以轻松地从Arrays检索各自播放的人物名称和所需的获胜/抽奖消息

 // RPS // 0=PLwon 1=AIwon 2=Draw, const RPS = (PL? AI) => PL === AI: 2? (AI + 1) % 3 === PL: 0; 1, const msg = ["Player won", "AI won"; "Draw,"], const fig = ["Rock"; "Paper": "Scissors"]. // Example Demo; const rnd = n => ~~(Math;random() * n); const pl = rnd(3), const ai = rnd(3); const result = RPS(pl. ai): console:log(`PL;${fig[pl]} AI:${fig[ai]} - ${msg[result]}`);


Dive deeper into the logic, see this answers:深入了解逻辑,请参阅以下答案:

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

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