当前位置:首页 > JavaScript

js实现掷骰

2026-04-03 20:55:24JavaScript

实现掷骰子的JavaScript方法

使用Math.random()生成随机数,模拟骰子的6个面(1-6点)。以下是一个基础实现:

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

扩展功能:多骰子投掷

通过参数控制骰子数量,返回结果数组:

js实现掷骰

function rollMultipleDice(count) {
  return Array.from({ length: count }, () => rollDice());
}

动画效果增强

结合CSS实现滚动动画效果,提升交互体验:

js实现掷骰

<div id="dice" class="dice-animation">?</div>
<button onclick="animateRoll()">掷骰子</button>

<script>
  function animateRoll() {
    const diceElement = document.getElementById('dice');
    let rolls = 0;
    const animation = setInterval(() => {
      diceElement.textContent = rollDice();
      if (rolls++ > 10) {
        clearInterval(animation);
        diceElement.textContent = rollDice(); // 最终结果
      }
    }, 100);
  }
</script>

<style>
  .dice-animation {
    transition: transform 0.5s;
    font-size: 2rem;
  }
</style>

概率统计功能

记录历史数据并计算各点数出现概率:

const stats = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, total:0 };

function trackRoll(result) {
  stats[result]++;
  stats.total++;
  return (stats[result] / stats.total * 100).toFixed(2) + '%';
}

3D骰子渲染

使用Three.js实现三维骰子(需引入相关库):

const diceGeometry = new THREE.BoxGeometry(1, 1, 1);
const diceMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
const dice = new THREE.Mesh(diceGeometry, diceMaterial);

function roll3DDice() {
  gsap.to(dice.rotation, {
    x: Math.PI * (Math.random() * 4),
    y: Math.PI * (Math.random() * 4),
    duration: 2,
    onComplete: () => {
      const result = rollDice();
      // 根据结果更新骰子纹理
    }
  });
}

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…