为何我的骰子游戏条件判断代码失效,朋友的却正常运行?
Hey there! Let's walk through why your dice game code isn't behaving as expected, even though it looks similar to your friend's working version. There are a few key logic and syntax issues throwing things off:
1. 核心条件判断逻辑错误(非1的判断)
Your code uses:
if (dice !== 1 || diceTwo !== 1) {
This condition means "if either die is NOT 1" — which will still trigger the scoring branch even if one die IS 1 (e.g., dice=1, diceTwo=2 would pass this check). But according to your rules, we should only enter the scoring branch if neither die is 1. You need to use && instead of || here:
if (dice !== 1 && diceTwo !== 1) {
2. 连续6的判断不完整
Your code checks for consecutive sixes with:
if (doubleSix === 6 && dice === 6) {
This only looks at the first die (dice) being 6, but your rule applies if either die is 6 on the second roll. You need to include diceTwo here, matching your friend's logic:
if (doubleSix === 6 && (dice === 6 || diceTwo === 6)) {
3. 分数清空范围错误
You're resetting the entire score variable to 0 with:
score = 0;
But this should only reset the active player's score, not all players' scores. Use the same approach as your friend:
score[activePlayer] = 0;
4. 语法错误(无效的else if)
Your code has a broken else if with no condition:
} else if {
This is invalid syntax — since you've already checked the consecutive sixes condition, the remaining case is just normal scoring, so you should use a plain else instead.
修正后的完整代码
Here's your code with all the fixes applied, which should match your friend's working logic:
if (dice !== 1 && diceTwo !== 1) { // Add score if (doubleSix === 6 && (dice === 6 || diceTwo === 6)) { roundScore = 0; score[activePlayer] = 0; nextPlayer(); } else { roundScore += (dice + diceTwo); document.querySelector('#current-' + activePlayer).textContent = roundScore; doubleSix = dice; } } else { // Next Player nextPlayer(); }
Let's confirm the logic now matches your rules:
- If either die rolls a 1: switch players immediately
- If neither die is 1, but we had a 6 on the last roll and now roll a 6 on either die: reset current and player scores, then switch players
- Otherwise: add the dice total to the round score, update the display, and save the current die value for checking consecutive sixes next round
内容的提问来源于stack exchange,提问作者LiamOakley

