random_number_generation.rst 17 KB

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