MathUtils.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. namespace FL
  4. {
  5. public static class MathUtils
  6. {
  7. /// <summary>
  8. /// 传递一个概率值(1-10000),返回随机结果是否在概率内
  9. /// </summary>
  10. /// <param name="probability">1-10000</param>
  11. /// <param name="maxExclusive">最大值</param>
  12. /// <returns></returns>
  13. public static bool Random(int probability, int maxExclusive = 10000)
  14. {
  15. //零固定返回false
  16. if (probability <= 0) return false;
  17. if (probability < maxExclusive)
  18. {
  19. var random = UnityEngine.Random.Range(0, maxExclusive);
  20. return random < probability;
  21. }
  22. return true;
  23. }
  24. /// <summary>
  25. /// 传递一个权重数组,返回随机结果对应的索引
  26. /// </summary>
  27. /// <param name="weights"></param>
  28. /// <returns></returns>
  29. public static int Random(IList<int> weights)
  30. {
  31. var total = 0;
  32. foreach (var weight in weights)
  33. {
  34. total += weight;
  35. }
  36. if (total <= 0)
  37. {
  38. return 0;
  39. }
  40. var random = UnityEngine.Random.Range(0, total);
  41. var temp = 0;
  42. for (var i = 0; i < weights.Count; i++)
  43. {
  44. temp += weights[i];
  45. if (random < temp)
  46. {
  47. return i;
  48. }
  49. }
  50. XGame.Log.Error($"随机数错误。total:{total} total:{random}");
  51. return 0;
  52. }
  53. /// <summary>
  54. /// 毫秒转指定格式的时间字符串
  55. /// </summary>
  56. /// <param name="milliseconds"></param>
  57. /// <param name="format">字符串格式, 例: @"mm\:ss"</param>
  58. /// <returns></returns>
  59. public static string ToTimeString(this long milliseconds, string format)
  60. {
  61. var timeData = TimeSpan.FromMilliseconds(milliseconds);
  62. return timeData.ToString(format);
  63. }
  64. }
  65. }