文章配图:随机等级生成算法

页面预览

前言

在「猫猫大作战」中,新投放的猫咪需要随机生成等级,但不能全是低级猫也不能全是高级猫。我们使用加权随机算法控制各等级的出现概率。

一、加权随机

private randomLevel(): CatLevel {
  const rand = Math.random();
  if (rand < 0.5) return CatLevel.SMALL;    // 50%
  if (rand < 0.8) return CatLevel.MEDIUM;   // 30%
  if (rand < 0.95) return CatLevel.LARGE;   // 15%
  return CatLevel.XLARGE;                    // 5%
}

二、概率分布

等级 概率 区间 难度
SMALL (1) 50% [0, 0.5) 简单
MEDIUM (2) 30% [0.5, 0.8) 普通
LARGE (3) 15% [0.8, 0.95) 困难
XLARGE (4) 5% [0.95, 1.0) 稀有

三、随机列选择

private randomCol(): number {
  return Math.floor(Math.random() * GameConfig.BOARD_WIDTH);
}

// 带权重的列选择(中间列概率更高)
private randomColWeighted(): number {
  const weights = [0.15, 0.2, 0.3, 0.2, 0.15];
  const rand = Math.random();
  let sum = 0;
  for (let i = 0; i < weights.length; i++) {
    sum += weights[i];
    if (rand < sum) return i;
  }
  return 2; // 默认中间列
}

四、防重复策略

// 连续三次不出高级猫时,保证一次中高级
private forcedLevel: CatLevel | null = null;

private getNextLevel(): CatLevel {
  if (this.forcedLevel) {
    const level = this.forcedLevel;
    this.forcedLevel = null;
    return level;
  }
  return this.randomLevel();
}

private checkForce(): void {
  if (this.consecutiveLow >= 3) {
    this.forcedLevel = CatLevel.MEDIUM;
    this.consecutiveLow = 0;
  }
}

五、最佳实践

  1. Math.random() 生成 [0,1) 均匀分布
  2. if-else 链实现加权采样
  3. 保底机制:连续不出高级猫时强制提升
  4. 列权重:中间列概率略高,增加策略性

总结

加权随机算法通过 Math.random() 配合条件判断控制各等级的生成概率,保底机制保证游戏体验。核心要点:Math.random() 均匀分布、 条件判断加权采样、 保底机制防极端

如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!


相关资源:

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐