2 回答

TA貢獻1880條經驗 獲得超4個贊
你能試試這樣的嗎
function App() {
const cpuWeapon = ["paper", "rock", "scissor"];
const [playerOne,setPlayerOne]=useState(0)
const [playerTwo,setPlayerTwo]=useState(0)
const { playerOne, playerTwo } = playerChoice;
const selectWeapon = weapon => {
const player1 = weapon;
const player2 = cpuWeapon[Math.floor(Math.random() * 3)];
getScore(player1, player2)
};
const getScore = (pl1, pl2) => {
if (pl1 === "paper") {
if (pl2 === "scissor") {
setPlayerTwo(playerTwo+1)
} else if (pl2 === "rock") {
setPlayerOne(playerOne+1)
}
}
};
}

TA貢獻1806條經驗 獲得超5個贊
難怪您會為兩個分數獲得相同的更新,因為您設置了相同的值:getScore(player1, player2)
我建議您將getScore功能替換為:
const getWinner = (pl1, pl2) => {
// Compare pl1 and pl2 and return:
// * 0 in case of tie,
// * 1 if player one wins,
// * 2 if player two wins
};
然后,在您的selectWeapon函數中,添加:
...
const winner = getWinner(player1, player2);
setPlayerChoice({
playerOne: {
choice: player1,
score: playerOne.score + (winner === 1 ? 1 : 0)
},
playerTwo: {
choice: player2,
score: playerTwo.score + (winner === 2 ? 1 : 0)
}
});
添加回答
舉報