Skip to content

Instantly share code, notes, and snippets.

@ScottLilly
Last active April 22, 2019 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottLilly/e05a5f971c1fce7ea5fe to your computer and use it in GitHub Desktop.
Save ScottLilly/e05a5f971c1fce7ea5fe to your computer and use it in GitHub Desktop.
Lesson 15.1 - Getting random numbers for the game
using System;
using System.Security.Cryptography;
namespace Engine
{
// This is the more complex version
public static class RandomNumberGenerator
{
private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();
public static int NumberBetween(int minimumValue, int maximumValue)
{
byte[] randomNumber = new byte[1];
_generator.GetBytes(randomNumber);
double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]);
// We are using Math.Max, and substracting 0.00000000001,
// to ensure "multiplier" will always be between 0.0 and .99999999999
// Otherwise, it's possible for it to be "1", which causes problems in our rounding.
double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d);
// We need to add one to the range, to allow for the rounding done with Math.Floor
int range = maximumValue - minimumValue + 1;
double randomValueInRange = Math.Floor(multiplier * range);
return (int)(minimumValue + randomValueInRange);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine
{
public static class RandomNumberGenerator
{
private static Random _generator = new Random();
public static int NumberBetween(int minimumValue, int maximumValue)
{
return _generator.Next(minimumValue, maximumValue + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment