Last active
December 31, 2019 09:12
-
-
Save ErnSur/3f11be8c7e357c3c9190c5eb04d373d4 to your computer and use it in GitHub Desktop.
Random number generator with modifiable chance for each value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Linq; | |
public abstract class Dice | |
{ | |
protected Side[] Sides { get; } | |
public Dice(Side[] sides) | |
{ | |
Sides = sides; | |
} | |
public int Roll() | |
{ | |
var winnerSide = Sides | |
.OrderByDescending(side => Random.Range(0, side.chance)) | |
.First(); | |
return winnerSide.value; | |
} | |
public struct Side | |
{ | |
public readonly int value; | |
public readonly float chance; | |
public Side(int value, float chance) | |
{ | |
this.value = value; | |
this.chance = chance; | |
} | |
} | |
} | |
public class GreedDice : Dice | |
{ | |
public GreedDice() : base(GetSides()) { } | |
private static Side[] GetSides() | |
{ | |
var sideCount = 6; | |
var sides = Enumerable.Range(1, sideCount).Select(sideValue => new Side(sideValue, GetChance(sideValue))).ToArray(); | |
return sides; | |
float GetChance(int sideValue) | |
{ | |
var standardSideChance = (float)1 / sideCount; | |
return sideValue == 1 || sideValue == sideCount ? standardSideChance * 2 : standardSideChance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment