random_number_generation.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. Lastly, we'll take a look at
  10. cryptographically secure random number generation and how it differs from
  11. typical random number generation.
  12. .. note::
  13. Computers cannot generate "true" random numbers. Instead, they rely on
  14. `pseudorandom number generators
  15. <https://en.wikipedia.org/wiki/Pseudorandom_number_generator>`__ (PRNGs).
  16. Godot internally uses the `PCG Family <https://www.pcg-random.org/>`__
  17. of pseudorandom number generators.
  18. Global scope versus RandomNumberGenerator class
  19. -----------------------------------------------
  20. Godot exposes two ways to generate random numbers: via *global scope* methods or
  21. using the :ref:`class_RandomNumberGenerator` class.
  22. Global scope methods are easier to set up, but they don't offer as much control.
  23. RandomNumberGenerator requires more code to use, but allows creating
  24. multiple instances, each with their own seed and state.
  25. This tutorial uses global scope methods, except when the method only exists in
  26. the RandomNumberGenerator class.
  27. The randomize() method
  28. ----------------------
  29. .. note::
  30. Since Godot 4.0, the random seed is automatically set to a random value when
  31. the project starts. This means you don't need to call ``randomize()`` in
  32. ``_ready()`` anymore to ensure that results are random across project runs.
  33. However, you can still use ``randomize()`` if you want to use a specific
  34. seed number, or generate it using a different method.
  35. In global scope, you can find a :ref:`randomize()
  36. <class_@GlobalScope_method_randomize>` method. **This method should be called only
  37. once when your project starts to initialize the random seed.** Calling it
  38. multiple times is unnecessary and may impact performance negatively.
  39. Putting it in your main scene script's ``_ready()`` method is a good choice:
  40. .. tabs::
  41. .. code-tab:: gdscript GDScript
  42. func _ready():
  43. randomize()
  44. .. code-tab:: csharp
  45. public override void _Ready()
  46. {
  47. GD.Randomize();
  48. }
  49. You can also set a fixed random seed instead using :ref:`seed()
  50. <class_@GlobalScope_method_seed>`. Doing so will give you *deterministic* results
  51. across runs:
  52. .. tabs::
  53. .. code-tab:: gdscript GDScript
  54. func _ready():
  55. seed(12345)
  56. # To use a string as a seed, you can hash it to a number.
  57. seed("Hello world".hash())
  58. .. code-tab:: csharp
  59. public override void _Ready()
  60. {
  61. GD.Seed(12345);
  62. // To use a string as a seed, you can hash it to a number.
  63. GD.Seed("Hello world".Hash());
  64. }
  65. When using the RandomNumberGenerator class, you should call ``randomize()`` on
  66. the instance since it has its own seed:
  67. .. tabs::
  68. .. code-tab:: gdscript GDScript
  69. var random = RandomNumberGenerator.new()
  70. random.randomize()
  71. .. code-tab:: csharp
  72. var random = new RandomNumberGenerator();
  73. random.Randomize();
  74. Getting a random number
  75. -----------------------
  76. Let's look at some of the most commonly used functions and methods to generate
  77. random numbers in Godot.
  78. The function :ref:`randi() <class_@GlobalScope_method_randi>` returns a random
  79. number between ``0`` and ``2^32 - 1``. Since the maximum value is huge, you most
  80. likely want to use the modulo operator (``%``) to bound the result between 0 and
  81. the denominator:
  82. .. tabs::
  83. .. code-tab:: gdscript GDScript
  84. # Prints a random integer between 0 and 49.
  85. print(randi() % 50)
  86. # Prints a random integer between 10 and 60.
  87. print(randi() % 51 + 10)
  88. .. code-tab:: csharp
  89. // Prints a random integer between 0 and 49.
  90. GD.Print(GD.Randi() % 50);
  91. // Prints a random integer between 10 and 60.
  92. GD.Print(GD.Randi() % 51 + 10);
  93. :ref:`randf() <class_@GlobalScope_method_randf>` returns a random floating-point
  94. number between 0 and 1. This is useful to implement a
  95. :ref:`doc_random_number_generation_weighted_random_probability` system, among
  96. other things.
  97. :ref:`randfn() <class_@GlobalScope_method_randfn>` returns a random
  98. floating-point number following a `normal distribution
  99. <https://en.wikipedia.org/wiki/Normal_distribution>`__. This means the returned
  100. value is more likely to be around the mean (0.0 by default),
  101. varying by the deviation (1.0 by default):
  102. .. tabs::
  103. .. code-tab:: gdscript GDScript
  104. # Prints a random floating-point number from a normal distribution with a mean 0.0 and deviation 1.0.
  105. print(randfn())
  106. .. code-tab:: csharp
  107. // Prints a random floating-point number from a normal distribution with a mean of 0.0 and deviation of 1.0.
  108. GD.Print(GD.Randfn());
  109. :ref:`randf_range() <class_@GlobalScope_method_randf_range>` takes two arguments
  110. ``from`` and ``to``, and returns a random floating-point number between ``from``
  111. and ``to``:
  112. .. tabs::
  113. .. code-tab:: gdscript GDScript
  114. # Prints a random floating-point number between -4 and 6.5.
  115. print(randf_range(-4, 6.5))
  116. .. code-tab:: csharp
  117. // Prints a random floating-point number between -4 and 6.5.
  118. GD.Print(GD.RandfRange(-4, 6.5));
  119. :ref:`randi_range() <class_@GlobalScope_method_randi_range>` takes two arguments ``from``
  120. and ``to``, and returns a random integer between ``from`` and ``to``:
  121. .. tabs::
  122. .. code-tab:: gdscript GDScript
  123. # Prints a random integer between -10 and 10.
  124. print(randi_range(-10, 10))
  125. .. code-tab:: csharp
  126. // Prints a random integer between -10 and 10.
  127. GD.Print(GD.RandiRange(-10, 10));
  128. Get a random array element
  129. --------------------------
  130. We can use random integer generation to get a random element from an array,
  131. or use the :ref:`Array.pick_random<class_Array_method_pick_random>` method
  132. to do it for us:
  133. .. tabs::
  134. .. code-tab:: gdscript GDScript
  135. var _fruits = ["apple", "orange", "pear", "banana"]
  136. func _ready():
  137. for i in range(100):
  138. # Pick 100 fruits randomly.
  139. print(get_fruit())
  140. for i in range(100):
  141. # Pick 100 fruits randomly, this time using the `Array.pick_random()`
  142. # helper method. This has the same behavior as `get_fruit()`.
  143. print(_fruits.pick_random())
  144. func get_fruit():
  145. var random_fruit = _fruits[randi() % _fruits.size()]
  146. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  147. # We may get the same fruit multiple times in a row.
  148. return random_fruit
  149. .. code-tab:: csharp
  150. // Use Godot's Array type instead of a BCL type so we can use `PickRandom()` on it.
  151. private Godot.Collections.Array<string> _fruits = new Godot.Collections.Array<string> { "apple", "orange", "pear", "banana" };
  152. public override void _Ready()
  153. {
  154. for (int i = 0; i < 100; i++)
  155. {
  156. // Pick 100 fruits randomly.
  157. GD.Print(GetFruit());
  158. }
  159. for (int i = 0; i < 100; i++)
  160. {
  161. // Pick 100 fruits randomly, this time using the `Array.PickRandom()`
  162. // helper method. This has the same behavior as `GetFruit()`.
  163. GD.Print(_fruits.PickRandom());
  164. }
  165. }
  166. public string GetFruit()
  167. {
  168. string randomFruit = _fruits[GD.Randi() % _fruits.Size()];
  169. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  170. // We may get the same fruit multiple times in a row.
  171. return randomFruit;
  172. }
  173. To prevent the same fruit from being picked more than once in a row, we can add
  174. more logic to the above method. In this case, we can't use
  175. :ref:`Array.pick_random<class_Array_method_pick_random>` since it lacks a way to
  176. prevent repetition:
  177. .. tabs::
  178. .. code-tab:: gdscript GDScript
  179. var _fruits = ["apple", "orange", "pear", "banana"]
  180. var _last_fruit = ""
  181. func _ready():
  182. # Pick 100 fruits randomly.
  183. for i in range(100):
  184. print(get_fruit())
  185. func get_fruit():
  186. var random_fruit = _fruits[randi() % _fruits.size()]
  187. while random_fruit == _last_fruit:
  188. # The last fruit was picked. Try again until we get a different fruit.
  189. random_fruit = _fruits[randi() % _fruits.size()]
  190. # Note: if the random element to pick is passed by reference,
  191. # such as an array or dictionary,
  192. # use `_last_fruit = random_fruit.duplicate()` instead.
  193. _last_fruit = random_fruit
  194. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  195. # The function will never return the same fruit more than once in a row.
  196. return random_fruit
  197. .. code-tab:: csharp
  198. private string[] _fruits = { "apple", "orange", "pear", "banana" };
  199. private string _lastFruit = "";
  200. public override void _Ready()
  201. {
  202. for (int i = 0; i < 100; i++)
  203. {
  204. // Pick 100 fruits randomly.
  205. GD.Print(GetFruit());
  206. }
  207. }
  208. public string GetFruit()
  209. {
  210. string randomFruit = _fruits[GD.Randi() % _fruits.Length];
  211. while (randomFruit == _lastFruit)
  212. {
  213. // The last fruit was picked. Try again until we get a different fruit.
  214. randomFruit = _fruits[GD.Randi() % _fruits.Length];
  215. }
  216. _lastFruit = randomFruit;
  217. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  218. // The function will never return the same fruit more than once in a row.
  219. return randomFruit;
  220. }
  221. This approach can be useful to make random number generation feel less
  222. repetitive. Still, it doesn't prevent results from "ping-ponging" between a
  223. limited set of values. To prevent this, use the :ref:`shuffle bag
  224. <doc_random_number_generation_shuffle_bags>` pattern instead.
  225. Get a random dictionary value
  226. -----------------------------
  227. We can apply similar logic from arrays to dictionaries as well:
  228. .. tabs::
  229. .. code-tab:: gdscript GDScript
  230. var metals = {
  231. "copper": {"quantity": 50, "price": 50},
  232. "silver": {"quantity": 20, "price": 150},
  233. "gold": {"quantity": 3, "price": 500},
  234. }
  235. func _ready():
  236. for i in range(20):
  237. print(get_metal())
  238. func get_metal():
  239. var random_metal = metals.values()[randi() % metals.size()]
  240. # Returns a random metal value dictionary every time the code runs.
  241. # The same metal may be selected multiple times in succession.
  242. return random_metal
  243. .. _doc_random_number_generation_weighted_random_probability:
  244. Weighted random probability
  245. ---------------------------
  246. The :ref:`randf() <class_@GlobalScope_method_randf>` method returns a
  247. floating-point number between 0.0 and 1.0. We can use this to create a
  248. "weighted" probability where different outcomes have different likelihoods:
  249. .. tabs::
  250. .. code-tab:: gdscript GDScript
  251. func _ready():
  252. for i in range(100):
  253. print(get_item_rarity())
  254. func get_item_rarity():
  255. var random_float = randf()
  256. if random_float < 0.8:
  257. # 80% chance of being returned.
  258. return "Common"
  259. elif random_float < 0.95:
  260. # 15% chance of being returned.
  261. return "Uncommon"
  262. else:
  263. # 5% chance of being returned.
  264. return "Rare"
  265. .. code-tab:: csharp
  266. public override void _Ready()
  267. {
  268. for (int i = 0; i < 100; i++)
  269. {
  270. GD.Print(GetItemRarity());
  271. }
  272. }
  273. public string GetItemRarity()
  274. {
  275. float randomFloat = GD.Randf();
  276. if (randomFloat < 0.8f)
  277. {
  278. // 80% chance of being returned.
  279. return "Common";
  280. }
  281. else if (randomFloat < 0.95f)
  282. {
  283. // 15% chance of being returned.
  284. return "Uncommon";
  285. }
  286. else
  287. {
  288. // 5% chance of being returned.
  289. return "Rare";
  290. }
  291. }
  292. You can also get a weighted random *index* using the
  293. :ref:`rand_weighted() <class_RandomNumberGenerator_method_rand_weighted>` method
  294. on a RandomNumberGenerator instance. This returns a random integer
  295. between 0 and the size of the array that is passed as a parameter. Each value in the
  296. array is a floating-point number that represents the *relative* likelihood that it
  297. will be returned as an index. A higher value means the value is more likely to be
  298. returned as an index, while a value of ``0`` means it will never be returned as an index.
  299. For example, if ``[0.5, 1, 1, 2]`` is passed as a parameter, then the method is twice
  300. as likely to return ``3`` (the index of the value ``2``) and twice as unlikely to return
  301. ``0`` (the index of the value ``0.5``) compared to the indices ``1`` and ``2``.
  302. Since the returned value matches the array's size, it can be used as an index to
  303. get a value from another array as follows:
  304. .. tabs::
  305. .. code-tab:: gdscript GDScript
  306. # Prints a random element using the weighted index that is returned by `rand_weighted()`.
  307. # Here, "apple" will be returned twice as rarely as "orange" and "pear".
  308. # "banana" is twice as common as "orange" and "pear", and four times as common as "apple".
  309. var fruits = ["apple", "orange", "pear", "banana"]
  310. var probabilities = [0.5, 1, 1, 2];
  311. var random = RandomNumberGenerator.new()
  312. print(fruits[random.rand_weighted(probabilities)])
  313. .. code-tab:: csharp
  314. // Prints a random element using the weighted index that is returned by `RandWeighted()`.
  315. // Here, "apple" will be returned twice as rarely as "orange" and "pear".
  316. // "banana" is twice as common as "orange" and "pear", and four times as common as "apple".
  317. string[] fruits = { "apple", "orange", "pear", "banana" };
  318. float[] probabilities = { 0.5, 1, 1, 2 };
  319. var random = new RandomNumberGenerator();
  320. GD.Print(fruits[random.RandWeighted(probabilities)]);
  321. .. _doc_random_number_generation_shuffle_bags:
  322. "Better" randomness using shuffle bags
  323. --------------------------------------
  324. Taking the same example as above, we would like to pick fruits at random.
  325. However, relying on random number generation every time a fruit is selected can
  326. lead to a less *uniform* distribution. If the player is lucky (or unlucky), they
  327. could get the same fruit three or more times in a row.
  328. You can accomplish this using the *shuffle bag* pattern. It works by removing an
  329. element from the array after choosing it. After multiple selections, the array
  330. ends up empty. When that happens, you reinitialize it to its default value::
  331. var _fruits = ["apple", "orange", "pear", "banana"]
  332. # A copy of the fruits array so we can restore the original value into `fruits`.
  333. var _fruits_full = []
  334. func _ready():
  335. _fruits_full = _fruits.duplicate()
  336. _fruits.shuffle()
  337. for i in 100:
  338. print(get_fruit())
  339. func get_fruit():
  340. if _fruits.is_empty():
  341. # Fill the fruits array again and shuffle it.
  342. _fruits = _fruits_full.duplicate()
  343. _fruits.shuffle()
  344. # Get a random fruit, since we shuffled the array,
  345. # and remove it from the `_fruits` array.
  346. var random_fruit = _fruits.pop_front()
  347. # Prints "apple", "orange", "pear", or "banana" every time the code runs.
  348. return random_fruit
  349. When running the above code, there is a chance to get the same fruit twice in a
  350. row. Once we picked a fruit, it will no longer be a possible return value unless
  351. the array is now empty. When the array is empty, we reset it back to its default
  352. value, making it possible to have the same fruit again, but only once.
  353. Random noise
  354. ------------
  355. The random number generation shown above can show its limits when you need a
  356. value that *slowly* changes depending on the input. The input can be a position,
  357. time, or anything else.
  358. To achieve this, you can use random *noise* functions. Noise functions are
  359. especially popular in procedural generation to generate realistic-looking
  360. terrain. Godot provides :ref:`class_fastnoiselite` for this, which supports
  361. 1D, 2D and 3D noise. Here's an example with 1D noise:
  362. .. tabs::
  363. .. code-tab:: gdscript GDScript
  364. var _noise = FastNoiseLite.new()
  365. func _ready():
  366. # Configure the FastNoiseLite instance.
  367. _noise.noise_type = FastNoiseLite.NoiseType.TYPE_SIMPLEX_SMOOTH
  368. _noise.seed = randi()
  369. _noise.fractal_octaves = 4
  370. _noise.frequency = 1.0 / 20.0
  371. for i in 100:
  372. # Prints a slowly-changing series of floating-point numbers
  373. # between -1.0 and 1.0.
  374. print(_noise.get_noise_1d(i))
  375. .. code-tab:: csharp
  376. private FastNoiseLite _noise = new FastNoiseLite();
  377. public override void _Ready()
  378. {
  379. // Configure the FastNoiseLite instance.
  380. _noise.NoiseType = NoiseTypeEnum.SimplexSmooth;
  381. _noise.Seed = (int)GD.Randi();
  382. _noise.FractalOctaves = 4;
  383. _noise.Frequency = 1.0f / 20.0f;
  384. for (int i = 0; i < 100; i++)
  385. {
  386. GD.Print(_noise.GetNoise1D(i));
  387. }
  388. }
  389. Cryptographically secure pseudorandom number generation
  390. -------------------------------------------------------
  391. So far, the approaches mentioned above are **not** suitable for
  392. *cryptographically secure* pseudorandom number generation (CSPRNG). This is fine
  393. for games, but this is not sufficient for scenarios where encryption,
  394. authentication or signing is involved.
  395. Godot offers a :ref:`class_Crypto` class for this. This class can perform
  396. asymmetric key encryption/decryption, signing/verification, while also
  397. generating cryptographically secure random bytes, RSA keys, HMAC digests, and
  398. self-signed :ref:`class_X509Certificate`\ s.
  399. The downside of :abbr:`CSPRNG (Cryptographically secure pseudorandom number generation)`
  400. is that it's much slower than standard pseudorandom number generation. Its API
  401. is also less convenient to use. As a result,
  402. :abbr:`CSPRNG (Cryptographically secure pseudorandom number generation)`
  403. should be avoided for gameplay elements.
  404. Example of using the Crypto class to generate 2 random integers between ``0``
  405. and ``2^32 - 1`` (inclusive):
  406. ::
  407. var crypto := Crypto.new()
  408. # Request as many bytes as you need, but try to minimize the amount
  409. # of separate requests to improve performance.
  410. # Each 32-bit integer requires 4 bytes, so we request 8 bytes.
  411. var byte_array := crypto.generate_random_bytes(8)
  412. # Use the ``decode_u32()`` method from PackedByteArray to decode a 32-bit unsigned integer
  413. # from the beginning of `byte_array`. This method doesn't modify `byte_array`.
  414. var random_int_1 := byte_array.decode_u32(0)
  415. # Do the same as above, but with an offset of 4 bytes since we've already decoded
  416. # the first 4 bytes previously.
  417. var random_int_2 := byte_array.decode_u32(4)
  418. prints("Random integers:", random_int_1, random_int_2)
  419. .. seealso::
  420. See :ref:`class_PackedByteArray`'s documentation for other methods you can
  421. use to decode the generated bytes into various types of data, such as
  422. integers or floats.