You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
110 lines
3.0 KiB
C#
110 lines
3.0 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace Game
|
|
{
|
|
public static class GameRandom
|
|
{
|
|
private static System.Random _random;
|
|
|
|
static GameRandom()
|
|
{
|
|
_random = new System.Random();
|
|
}
|
|
|
|
public static int Randint(int min, int max)
|
|
{
|
|
return _random.Next(min, max + 1);
|
|
}
|
|
|
|
public static float Random()
|
|
{
|
|
return Mathf.Abs((float)(_random.NextDouble())) % 1;
|
|
}
|
|
|
|
public static float Random(float min, float max)
|
|
{
|
|
return Random() * (max - min) + min;
|
|
}
|
|
|
|
public static float RandomRot(float rot, float angle)
|
|
{
|
|
var ret = rot - angle / 2 + GameRandom.Random(0, angle);
|
|
return ret;
|
|
}
|
|
|
|
public static Vector3 RandomDir(Vector3 dir, float rot, float forbidRot)
|
|
{
|
|
var rotHalf = rot * 0.5f;
|
|
var forbidRotHalf = forbidRot * 0.5f;
|
|
var vNew = dir;
|
|
if (rotHalf == 0) return vNew;
|
|
if (rotHalf <= forbidRotHalf)
|
|
forbidRotHalf = 0;
|
|
|
|
var rotAdd = Random(forbidRotHalf, rotHalf) * RollSymbol(0.5f);
|
|
vNew = Quaternion.AngleAxis(rotAdd, Vector3.up) * vNew;
|
|
return vNew;
|
|
}
|
|
|
|
public static Vector3 RandomVector3(float min, float max)
|
|
{
|
|
return new Vector3(Random(min, max), 0, Random(min, max));
|
|
}
|
|
|
|
public static Vector3 RandomVector3(Vector3 vec, float range)
|
|
{
|
|
return vec + RandomVector3(-range, range);
|
|
}
|
|
|
|
public static T Pick<T>(List<T> list)
|
|
{
|
|
return (list.Count > 0 ? list[Randint(0, list.Count - 1)] : default(T));
|
|
}
|
|
|
|
public static List<T> Sample<T>(List<T> list, int pickNum)
|
|
{
|
|
var listCount = list.Count;
|
|
if (listCount <= pickNum)
|
|
{
|
|
return list;
|
|
}
|
|
|
|
var ret = list.GetRange(0, pickNum);
|
|
for (int i = pickNum; i < listCount; i++)
|
|
{
|
|
if (i / listCount > Random())
|
|
{
|
|
ret[Randint(0, pickNum)] = list[i];
|
|
}
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
public static void Shuffle<T>(List<T> list)
|
|
{
|
|
var listCount = list.Count;
|
|
for (int i = 0; i < listCount; i++)
|
|
{
|
|
var targetIndex = Randint(0, listCount - 1);
|
|
(list[i], list[targetIndex]) = (list[targetIndex], list[i]);
|
|
}
|
|
}
|
|
|
|
public static T Pick<T>(HashSet<T> set)
|
|
{
|
|
return Pick<T>(new List<T>(set));
|
|
}
|
|
|
|
public static bool Roll(float chance)
|
|
{
|
|
return Random() < chance;
|
|
}
|
|
|
|
public static float RollSymbol(float chance)
|
|
{
|
|
return Random() < chance ? 1 : -1;
|
|
}
|
|
}
|
|
} |