为什么我的分数没有第一次更新? (剪刀石头布)

时间:2019-09-11 23:06:07

标签: javascript events template-literals

const div=document.querySelector('div');
const buttons=document.querySelector('.buttons')
let score=[0,0]


buttons.addEventListener('click', (e)=> {
  if (e.target.tagName==="BUTTON") {
    let playerRes=e.target.innerHTML
    let compRes=rockPaper()
    let number=compareValues(playerRes, compRes)
    console.log(number)
    if (number===0) {
      div.innerHTML=`
      <p>Player[${score[0]}] Computer[${score[1]}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>It's a tie!</p>
      `
    } else if (number>0) {
      div.innerHTML=`
      <p>Player[${score[0]++}] Computer[${score[1]}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>Player wins!</p>
      `
    } else if (number<0) {
      div.innerHTML=`
      <p>Player[${score[0]}] Computer[${score[1]++}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>Computer wins!</p>
      `
    }
  }
  
});


const rockPaper=()=> {
  const items=["Rock", "Paper", "Scissors"]
  let item = items[Math.floor(Math.random()*items.length)];
  return item
}

const compareValues=(player,comp)=> {
  if (player==="Rock" && comp==="Scissors" || player==="Scissors" && comp==="Paper"|| player==="Paper" && comp==="Rock" ) {
    return 1
  } else if (player===comp) {
    return 0
  } else {
    return -1
  }
}
<div></div>
<div class="buttons">
  <button>Rock</button>
  <button>Paper</button>
  <button>Scissors</button>
</div>

这是我的JS代码:

const div=document.querySelector('div');
const buttons=document.querySelector('.buttons')
let score=[0,0]


buttons.addEventListener('click', (e)=> {
  if (e.target.tagName==="BUTTON") {
    let playerRes=e.target.innerHTML
    let compRes=rockPaper()
    let number=compareValues(playerRes, compRes)
    console.log(number)
    if (number===0) {
      div.innerHTML=`
      <p>Player[${score[0]}] Computer[${score[1]}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>It's a tie!</p>
      `
    } else if (number>0) {
      div.innerHTML=`
      <p>Player[${score[0]++}] Computer[${score[1]}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>Player wins!</p>
      `
    } else if (number<0) {
      div.innerHTML=`
      <p>Player[${score[0]}] Computer[${score[1]++}]</p>
      <p>${playerRes} vs ${compRes}</p>
      <p>Computer wins!</p>
      `
    }
  }

});


const rockPaper=()=> {
  const items=["Rock", "Paper", "Scissors"]
  let item = items[Math.floor(Math.random()*items.length)];
  return item
}

const compareValues=(player,comp)=> {
  if (player==="Rock" && comp==="Scissors" || player==="Scissors" && comp==="Paper"|| player==="Paper" && comp==="Rock" ) {
    return 1
  } else if (player===comp) {
    return 0
  } else {
    return -1
  }
}

这是我的JS小提琴的链接:https://jsfiddle.net/apasric4/b1Lgr5xu/

两个玩家的分数只有在第一次单击三个按钮之一后才能正确更新吗?为什么会这样呢?即使第一次赢得玩家或计算机的胜利,两个分数都保持在0。条件条件以及compareValues函数似乎是正确的。我不知道怎么了。

0 个答案:

没有答案