random_number_generation.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. .. _doc_random_number_generation:
  2. Random number generation
  3. ========================
  4. Many games rely on randomness to implement core game mechanics. This page
  5. guides you through common types of randomness and how to implement them in
  6. Godot.
  7. After giving you a brief overview of useful functions that generate random
  8. numbers, you will learn how to get random elements from arrays, dictionaries,
  9. and how to use a noise generator in GDScript.
  10. .. note::
  11. Computers cannot generate "true" random numbers. Instead, they rely on
  12. `pseudorandom number generators
  13. <https://en.wikipedia.org/wiki/Pseudorandom_number_generator>`__ (PRNGs).
  14. Global scope versus RandomNumberGenerator class
  15. -----------------------------------------------
  16. Godot exposes two ways to generate random numbers: via *global scope* methods or
  17. using the :ref:`class_RandomNumberGenerator` class.
  18. Global scope methods are easier to set up, but they don't offer as much control.
  19. RandomNumberGenerator requires more code to use, but allows creating
  20. multiple instances, each with their own seed and state.
  21. This tutorial uses global scope methods, except when the method only exists in
  22. the RandomNumberGenerator class.
  23. The randomize() method
  24. ----------------------
  25. In global scope, you can find a :ref:`randomize()
  26. <class_@GlobalScope_method_randomize>` method. **This method should be called only
  27. once when your project starts to initialize the random seed.** Calling it
  28. multiple times is unnecessary and may impact performance negatively.
  29. Putting it in your main scene script's ``_ready()`` method is a good choice:
  30. .. tabs::
  31. .. code-tab:: gdscript GDScript
  32. func _ready():
  33. randomize()
  34. .. code-tab:: csharp
  35. public override void _Ready()
  36. {
  37. GD.Randomize();
  38. }
  39. You can also set a fixed random seed instead using :ref:`seed()
  40. <class_@GlobalScope_method_seed>`. Doing so will give you *deterministic* results
  41. across runs:
  42. .. tabs::
  43. .. code-tab:: gdscript GDScript
  44. func _ready():
  45. seed(12345)
  46. # To use a string as a seed, you can hash it to a number.
  47. seed("Hello world".hash())
  48. .. code-tab:: csharp
  49. public override void _Ready()
  50. {
  51. GD.Seed(12345);
  52. GD.Seed("Hello world".Hash());
  53. }
  54. When using the RandomNumberGenerator class, you should call ``randomize()`` on
  55. the instance since it has its own seed:
  56. .. tabs::
  57. .. code-tab:: gdscript GDScript
  58. var random = RandomNumberGenerator.new()
  59. random.randomize()
  60. .. code-tab:: csharp
  61. var random = new RandomNumberGenerator();
  62. random.Randomize();
  63. Getting a random number
  64. -----------------------
  65. Let's look at some of the most commonly used functions and methods to generate
  66. random numbers in Godot.
  67. The function :ref:`randi() <class_@GlobalScope_method_randi>` returns a random
  68. number between 0 and 2^32-1. Since the maximum value is huge, you most likely
  69. want to use the modulo operator (``%``) to bound the result between 0 and the
  70. denominator:
  71. .. tabs::
  72. .. code-tab:: gdscript GDScript
  73. # Prints a random integer between 0 and 49.
  74. print(randi() % 50)
  75. # Prints a random integer between 10 and 60.
  76. print(randi() % 51 + 10)
  77. .. code-tab:: csharp
  78. // Prints a random integer between 0 and 49.
  79. GD.Print(GD.Randi() % 50);
  80. // Prints a random integer between 10 and 60.
  81. GD.Print(GD.Randi() % 51 + 10);
  82. :ref:`randf() <class_@GlobalScope_method_randf>` returns a random floating-point
  83. number between 0 and 1. This is useful to implement a
  84. :ref:`doc_random_number_generation_weighted_random_probability` system, among
  85. other things.
  86. :ref:`randfn() <class_RandomNumberGenerator_method_randfn>` returns a random
  87. floating-point number following a `normal distribution
  88. <https://en.wikipedia.org/wiki/Normal_distribution>`__. This means the returned
  89. value is more likely to be around the mean (0.0 by default),
  90. varying by the deviation (1.0 by default):
  91. .. tabs::
  92. .. code-tab:: gdscript GDScript
  93. # Prints a random floating-point number from a normal distribution with a mean 0.0 and deviation 1.0.
  94. var random = RandomNumberGenerator.new()
  95. random.randomize()
  96. print(random.randfn())
  97. .. code-tab:: csharp
  98. // Prints a normally distributed floating-point number between 0.0 and 1.0.
  99. var random = new RandomNumberGenerator();
  100. random.Randomize();
  101. GD.Print(random.Randfn());
  102. :ref:`randf_range() <class_@GlobalScope_method_randf_range>` takes two arguments
  103. ``from`` and ``to``, and returns a random floating-point number between ``from``
  104. and ``to``:
  105. .. tabs::
  106. .. code-tab:: gdscript GDScript
  107. # Prints a random floating-point number between -4 and 6.5.
  108. print(randf_range(-4, 6.5))
  109. :ref:`RandomNumberGenerator.randi_range()
  110. <class_RandomNumberGenerator_method_randi_range>` takes two arguments ``from``
  111. and ``to``, and returns a random integer between ``from`` and ``to``:
  112. .. tabs::
  113. .. code-tab:: gdscript GDScript
  114. # Prints a random integer between -10 and 10.
  115. var random = RandomNumberGenerator.new()
  116. random.randomize()
  117. print(random.randi_range(-10, 10))
  118. .. code-tab:: csharp
  119. // Prints a random integer number between -10 and 10.
  120. random.Randomize();
  121. GD.Print(random.RandiRange(-10, 10));
  122. Get a random array element
  123. --------------------------
  124. We can use random integer generation to get a random element from an array:
  125. .. tabs::
  126. .. code-tab:: gdscript GDScript
  127. var _fruits = ["apple", "orange", "pear", "banana"]
  128. func _ready():
  129. randomize()
  130. for i in range(100):
  131. # Pick 100 fruits randomly.
  132. print(get_fruit())
  133. func get_fruit():
  134. var random_fruit = _fruits[randi() % _fruits.size()]
  135. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  136. # We may get the same fruit multiple times in a row.
  137. return random_fruit
  138. .. code-tab:: csharp
  139. private string[] _fruits = { "apple", "orange", "pear", "banana" };
  140. public override void _Ready()
  141. {
  142. GD.Randomize();
  143. for (int i = 0; i < 100; i++)
  144. {
  145. // Pick 100 fruits randomly.
  146. GD.Print(GetFruit());
  147. }
  148. }
  149. public string GetFruit()
  150. {
  151. string randomFruit = _fruits[GD.Randi() % _fruits.Length];
  152. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  153. // We may get the same fruit multiple times in a row.
  154. return randomFruit;
  155. }
  156. To prevent the same fruit from being picked more than once in a row, we can add
  157. more logic to this method:
  158. .. tabs::
  159. .. code-tab:: gdscript GDScript
  160. var _fruits = ["apple", "orange", "pear", "banana"]
  161. var _last_fruit = ""
  162. func _ready():
  163. randomize()
  164. # Pick 100 fruits randomly.
  165. for i in range(100):
  166. print(get_fruit())
  167. func get_fruit():
  168. var random_fruit = _fruits[randi() % _fruits.size()]
  169. while random_fruit == _last_fruit:
  170. # The last fruit was picked, try again until we get a different fruit.
  171. random_fruit = _fruits[randi() % _fruits.size()]
  172. # Note: if the random element to pick is passed by reference,
  173. # such as an array or dictionary,
  174. # use `_last_fruit = random_fruit.duplicate()` instead.
  175. _last_fruit = random_fruit
  176. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  177. # The function will never return the same fruit more than once in a row.
  178. return random_fruit
  179. .. code-tab:: csharp
  180. private string[] _fruits = { "apple", "orange", "pear", "banana" };
  181. private string _lastFruit = "";
  182. public override void _Ready()
  183. {
  184. GD.Randomize();
  185. for (int i = 0; i < 100; i++)
  186. {
  187. // Pick 100 fruits randomly.
  188. GD.Print(GetFruit());
  189. }
  190. }
  191. public string GetFruit()
  192. {
  193. string randomFruit = _fruits[GD.Randi() % _fruits.Length];
  194. while (randomFruit == _lastFruit)
  195. {
  196. // The last fruit was picked, try again until we get a different fruit.
  197. randomFruit = _fruits[GD.Randi() % _fruits.Length];
  198. }
  199. _lastFruit = randomFruit;
  200. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  201. // The function will never return the same fruit more than once in a row.
  202. return randomFruit;
  203. }
  204. This approach can be useful to make random number generation feel less
  205. repetitive. Still, it doesn't prevent results from "ping-ponging" between a
  206. limited set of values. To prevent this, use the :ref:`shuffle bag
  207. <doc_random_number_generation_shuffle_bags>` pattern instead.
  208. Get a random dictionary value
  209. -----------------------------
  210. We can apply similar logic from arrays to dictionaries as well:
  211. .. tabs::
  212. .. code-tab:: gdscript GDScript
  213. var metals = {
  214. "copper": {"quantity": 50, "price": 50},
  215. "silver": {"quantity": 20, "price": 150},
  216. "gold": {"quantity": 3, "price": 500},
  217. }
  218. func _ready():
  219. randomize()
  220. for i in range(20):
  221. print(get_metal())
  222. func get_metal():
  223. var random_metal = metals.values()[randi() % metals.size()]
  224. # Returns a random metal value dictionary every time the code runs.
  225. # The same metal may be selected multiple times in succession.
  226. return random_metal
  227. .. _doc_random_number_generation_weighted_random_probability:
  228. Weighted random probability
  229. ---------------------------
  230. The :ref:`randf() <class_@GlobalScope_method_randf>` method returns a
  231. floating-point number between 0.0 and 1.0. We can use this to create a
  232. "weighted" probability where different outcomes have different likelihoods:
  233. .. tabs::
  234. .. code-tab:: gdscript GDScript
  235. func _ready():
  236. randomize()
  237. for i in range(100):
  238. print(get_item_rarity())
  239. func get_item_rarity():
  240. var random_float = randf()
  241. if random_float < 0.8:
  242. # 80% chance of being returned.
  243. return "Common"
  244. elif random_float < 0.95:
  245. # 15% chance of being returned.
  246. return "Uncommon"
  247. else:
  248. # 5% chance of being returned.
  249. return "Rare"
  250. .. code-tab:: csharp
  251. public override void _Ready()
  252. {
  253. GD.Randomize();
  254. for (int i = 0; i < 100; i++)
  255. {
  256. GD.Print(GetItemRarity());
  257. }
  258. }
  259. public string GetItemRarity()
  260. {
  261. float randomFloat = GD.Randf();
  262. if (randomFloat < 0.8f)
  263. {
  264. // 80% chance of being returned.
  265. return "Common";
  266. }
  267. else if (randomFloat < 0.95f)
  268. {
  269. // 15% chance of being returned
  270. return "Uncommon";
  271. }
  272. else
  273. {
  274. // 5% chance of being returned.
  275. return "Rare";
  276. }
  277. }
  278. .. _doc_random_number_generation_shuffle_bags:
  279. "Better" randomness using shuffle bags
  280. --------------------------------------
  281. Taking the same example as above, we would like to pick fruits at random.
  282. However, relying on random number generation every time a fruit is selected can
  283. lead to a less *uniform* distribution. If the player is lucky (or unlucky), they
  284. could get the same fruit three or more times in a row.
  285. You can accomplish this using the *shuffle bag* pattern. It works by removing an
  286. element from the array after choosing it. After multiple selections, the array
  287. ends up empty. When that happens, you reinitialize it to its default value::
  288. var _fruits = ["apple", "orange", "pear", "banana"]
  289. # A copy of the fruits array so we can restore the original value into `fruits`.
  290. var _fruits_full = []
  291. func _ready():
  292. randomize()
  293. _fruits_full = _fruits.duplicate()
  294. _fruits.shuffle()
  295. for i in 100:
  296. print(get_fruit())
  297. func get_fruit():
  298. if _fruits.empty():
  299. # Fill the fruits array again and shuffle it.
  300. _fruits = _fruits_full.duplicate()
  301. _fruits.shuffle()
  302. # Get a random fruit, since we shuffled the array,
  303. # and remove it from the `_fruits` array.
  304. var random_fruit = _fruits.pop_front()
  305. # Prints "apple", "orange", "pear", or "banana" every time the code runs.
  306. return random_fruit
  307. When running the above code, there is a chance to get the same fruit twice in a
  308. row. Once we picked a fruit, it will no longer be a possible return value unless
  309. the array is now empty. When the array is empty, we reset it back to its default
  310. value, making it possible to have the same fruit again, but only once.
  311. Random noise
  312. ------------
  313. The random number generation shown above can show its limits when you need a
  314. value that *slowly* changes depending on the input. The input can be a position,
  315. time, or anything else.
  316. To achieve this, you can use random *noise* functions. Noise functions are
  317. especially popular in procedural generation to generate realistic-looking
  318. terrain. Godot provides :ref:`class_fastnoiselite` for this, which supports
  319. 1D, 2D and 3D noise. Here's an example with 1D noise:
  320. .. tabs::
  321. .. code-tab:: gdscript GDScript
  322. var _noise = FastNoiseLite.new()
  323. func _ready():
  324. randomize()
  325. # Configure the FastNoiseLite instance.
  326. _noise.noise_type = FastNoiseLite.NoiseType.TYPE_SIMPLEX_SMOOTH
  327. _noise.seed = randi()
  328. _noise.fractal_octaves = 4
  329. _noise.frequency = 1.0 / 20.0
  330. for i in 100:
  331. # Prints a slowly-changing series of floating-point numbers
  332. # between -1.0 and 1.0.
  333. print(_noise.get_noise_1d(i))
  334. .. code-tab:: csharp
  335. private FastNoiseLite _noise = new FastNoiseLite();
  336. public override void _Ready()
  337. {
  338. GD.Randomize();
  339. // Configure the FastNoiseLite instance.
  340. _noise.NoiseType = NoiseTypeEnum.SimplexSmooth;
  341. _noise.Seed = (int)GD.Randi();
  342. _noise.FractalOctaves = 4;
  343. _noise.Frequency = 1.0f / 20.0f;
  344. for (int i = 0; i < 100; i++)
  345. {
  346. GD.Print(_noise.GetNoise1D(i));
  347. }
  348. }