More efficient choice comparison for Rock Paper Scissors

前端 未结 6 932
你的背包
你的背包 2021-01-07 23:54

This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an al

6条回答
  •  青春惊慌失措
    2021-01-08 00:35

    You can also use an array to check the winner. Order the array so that the winner is always on the right side. Then compare if the machine's choise is the one next to user's choise, like so:

    var weapons = ['paper', 'scissors', 'rock'],
      user = 'scissors',
      machine = 'paper',
      uIdx = weapons.indexOf(user),
      mIdx = weapons.indexOf(machine),
      winner;
    if (uIdx !== mIdx) {
      winner = (mIdx === (uIdx + 1) % 3) ? 'machine' : 'user';
    } else {
      winner = 'tie';
    }
    
    console.log(winner);

    A fiddle to play with.

    The modulo operator makes the magic at the end of the array. If user has chosen "rock", the next to it would be undefined, but the modulo operator of 3 % 3 returns 0, hence "paper" is compared to "rock".

提交回复
热议问题