Udemy课程JavaScript骰子游戏计分错误问题排查求助
The Issue: Incorrect Dice Value Generation
Your score calculation bug stems from how you're generating the dice number. The line:
var dice = (Math.random() * Math.floor(6)) + 1;
produces a floating-point number (like 3.456 or 5.999) instead of an integer between 1 and 6. Here's why this breaks your game:
- When you add a non-integer value to
roundScore, you end up with cumulative errors that don't match the actual dice face shown. - Your dice image will also fail to load correctly (since filenames like
dice-3.456.pngdon't exist), which might confuse players about what roll actually counted. - In your specific case, if you accidentally clicked the roll button three times (thinking it was one), the floating-point values could add up to 9 even if you intended a single roll of 3.
The Fix
Replace the dice generation line with the standard method to get a random integer between 1 and 6:
var dice = Math.floor(Math.random() * 6) + 1;
Let's break this down step by step:
Math.random()creates a number between 0 (inclusive) and 1 (exclusive).- Multiplying by 6 expands this range to 0 (inclusive) to 6 (exclusive).
Math.floor()rounds down to the nearest integer, giving us values from 0 to 5.- Adding 1 shifts the range to 1-6, perfectly matching the faces on a standard die.
Quick Check
After applying this fix:
- Your dice rolls will always be integers between 1 and 6.
- The round score will correctly accumulate the exact value of each roll.
- Your dice images will load properly every time.
内容的提问来源于stack exchange,提问作者Franky Padilla
相关产品推荐
相关产品推荐

