You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. When you add a non-integer value to roundScore, you end up with cumulative errors that don't match the actual dice face shown.
  2. Your dice image will also fail to load correctly (since filenames like dice-3.456.png don't exist), which might confuse players about what roll actually counted.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:03:16