random_number_generation.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 exposes many methods not
  20. found in global scope such as :ref:`randi_range()
  21. <class_RandomNumberGenerator_method_randi_range>` and :ref:`randfn()
  22. <class_RandomNumberGenerator_method_randfn>`. On top of that, it allows creating
  23. multiple instances each with their own seed.
  24. This tutorial uses global scope methods, except when the method only exists in
  25. the RandomNumberGenerator class.
  26. The randomize() method
  27. ----------------------
  28. In global scope, you can find a :ref:`randomize()
  29. <class_@GDScript_method_randomize>` method. **This method should be called only
  30. once when your project starts to initialize the random seed.** Calling it
  31. multiple times is unnecessary and may impact performance negatively.
  32. Putting it in your main scene script's ``_ready()`` method is a good choice::
  33. func _ready():
  34. randomize()
  35. You can also set a fixed random seed instead using :ref:`seed()
  36. <class_@GDScript_method_seed>`. Doing so will give you *deterministic* results
  37. across runs::
  38. func _ready():
  39. seed(12345)
  40. # To use a string as a seed, you can hash it to a number.
  41. seed("Hello world".hash())
  42. When using the RandomNumberGenerator class, you should call ``randomize()`` on
  43. the instance since it has its own seed::
  44. var rng = RandomNumberGenerator.new()
  45. rng.randomize()
  46. Getting a random number
  47. -----------------------
  48. Let's look at some of the most commonly used functions and methods to generate
  49. random numbers in Godot.
  50. The function :ref:`randi() <class_@GDScript_method_randi>` returns a random
  51. number between 0 and 2^32-1. Since the maximum value is huge, you most likely
  52. want to use the modulo operator (``%``) to bound the result between 0 and the
  53. denominator::
  54. # Prints a random integer between 0 and 49.
  55. print(randi() % 50)
  56. # Prints a random integer between 10 and 60.
  57. print(randi() % 51 + 10)
  58. :ref:`randf() <class_@GDScript_method_randf>` returns a random floating-point
  59. number between 0 and 1. This is useful to implement a
  60. :ref:`doc_random_number_generation_weighted_random_probability` system, among
  61. other things.
  62. :ref:`randfn() <class_RandomNumberGenerator_method_randfn>` returns a random
  63. floating-point number following a `normal distribution
  64. <https://en.wikipedia.org/wiki/Normal_distribution>`__. This means the returned
  65. value is more likely to be around the mean (0.0 by default), varying by the deviation (1.0 by default)::
  66. # Prints a random floating-point number from a normal distribution with a mean 0.0 and deviation 1.0.
  67. var rng = RandomNumberGenerator.new()
  68. rng.randomize()
  69. print(rng.randfn())
  70. :ref:`rand_range() <class_@GDScript_method_rand_range>` takes two arguments
  71. ``from`` and ``to``, and returns a random floating-point number between ``from``
  72. and ``to``::
  73. # Prints a random floating-point number between -4 and 6.5.
  74. print(rand_range(-4, 6.5))
  75. :ref:`RandomNumberGenerator.randi_range()
  76. <class_RandomNumberGenerator_method_randi_range>` takes two arguments ``from``
  77. and ``to``, and returns a random integer between ``from`` and ``to``::
  78. # Prints a random integer between -10 and 10.
  79. var rng = RandomNumberGenerator.new()
  80. rng.randomize()
  81. print(rng.randi_range(-10, 10))
  82. Get a random array element
  83. --------------------------
  84. We can use random integer generation to get a random element from an array::
  85. var fruits = ["apple", "orange", "pear", "banana"]
  86. func _ready():
  87. randomize()
  88. for i in 100:
  89. # Pick 100 fruits randomly.
  90. # (``for i in 100`` is a faster shorthand for ``for i in range(100)``.)
  91. print(get_fruit())
  92. func get_fruit():
  93. var random_fruit = fruits[randi() % fruits.size()]
  94. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  95. # We may get the same fruit multiple times in a row.
  96. return random_fruit
  97. To prevent the same fruit from being picked more than once in a row, we can add
  98. more logic to this method::
  99. var fruits = ["apple", "orange", "pear", "banana"]
  100. var last_fruit = ""
  101. func _ready():
  102. randomize()
  103. # Pick 100 fruits randomly.
  104. # Note: ``for i in 100`` is a shorthand for ``for i in range(100)``.
  105. for i in 100:
  106. print(get_fruit())
  107. func get_fruit():
  108. var random_fruit = fruits[randi() % fruits.size()]
  109. while random_fruit == last_fruit:
  110. # The last fruit was picked, try again until we get a different fruit.
  111. random_fruit = fruits[randi() % fruits.size()]
  112. # Note: if the random element to pick is passed by reference,
  113. # such as an array or dictionary,
  114. # use `last_fruit = random_fruit.duplicate()` instead.
  115. last_fruit = random_fruit
  116. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  117. # The function will never return the same fruit more than once in a row.
  118. return random_fruit
  119. This approach can be useful to make random number generation feel less
  120. repetitive. Still, it doesn't prevent results from "ping-ponging" between a
  121. limited set of values. To prevent this, use the :ref:`shuffle bag
  122. <doc_random_number_generation_shuffle_bags>` pattern instead.
  123. Get a random dictionary value
  124. -----------------------------
  125. We can apply similar logic from arrays to dictionaries as well::
  126. var metals = {
  127. "copper": {"quantity": 50, "price": 50},
  128. "silver": {"quantity": 20, "price": 150},
  129. "gold": {"quantity": 3, "price": 500},
  130. }
  131. func _ready():
  132. randomize()
  133. for i in 20:
  134. print(get_metal())
  135. func get_metal():
  136. var random_metal = metals.values()[randi() % metals.size()]
  137. # Returns a random metal value dictionary every time the code runs.
  138. # The same metal may be selected multiple times in succession.
  139. return random_metal
  140. .. _doc_random_number_generation_weighted_random_probability:
  141. Weighted random probability
  142. ---------------------------
  143. The :ref:`randf() <class_@GDScript_method_randf>` method returns a
  144. floating-point number between 0.0 and 1.0. We can use this to create a
  145. "weighted" probability where different outcomes have different likelihoods::
  146. func _ready():
  147. randomize()
  148. for i in 100:
  149. print(get_item_rarity())
  150. func get_item_rarity():
  151. var random_float = randf()
  152. if random_float < 0.8:
  153. # 80% chance of being returned.
  154. return "Common"
  155. elif random_float < 0.95:
  156. # 15% chance of being returned.
  157. return "Uncommon"
  158. else:
  159. # 5% chance of being returned.
  160. return "Rare"
  161. .. _doc_random_number_generation_shuffle_bags:
  162. "Better" randomness using shuffle bags
  163. --------------------------------------
  164. Taking the same example as above, we would like to pick fruits at random.
  165. However, relying on random number generation every time a fruit is selected can
  166. lead to a less *uniform* distribution. If the player is lucky (or unlucky), they
  167. could get the same fruit three or more times in a row.
  168. You can accomplish this using the *shuffle bag* pattern. It works by removing an
  169. element from the array after choosing it. After multiple selections, the array
  170. ends up empty. When that happens, you reinitialize it to its default value::
  171. var fruits = ["apple", "orange", "pear", "banana"]
  172. # A copy of the fruits array so we can restore the original value into `fruits`.
  173. var fruits_full = []
  174. func _ready():
  175. randomize()
  176. fruits_full = fruits.duplicate()
  177. fruits.shuffle()
  178. for i in 100:
  179. print(get_fruit())
  180. func get_fruit():
  181. if fruits.empty():
  182. # Fill the fruits array again and shuffle it.
  183. fruits = fruits_full.duplicate()
  184. fruits.shuffle()
  185. # Get a random fruit, since we shuffled the array,
  186. # and remove it from the `fruits` array.
  187. var random_fruit = fruits.pop_front()
  188. # Prints "apple", "orange", "pear", or "banana" every time the code runs.
  189. return random_fruit
  190. When running the above code, there is a chance to get the same fruit twice in a
  191. row. Once we picked a fruit, it will no longer be a possible return value unless
  192. the array is now empty. When the array is empty, we reset it back to its default
  193. value, making it possible to have the same fruit again, but only once.
  194. Random noise
  195. ------------
  196. The random number generation shown above can show its limits when you need a
  197. value that *slowly* changes depending on the input. The input can be a position,
  198. time, or anything else.
  199. To achieve this, you can use random *noise* functions. Noise functions are
  200. especially popular in procedural generation to generate realistic-looking
  201. terrain. Godot provides :ref:`class_opensimplexnoise` for this, which supports
  202. 1D, 2D, 3D, and 4D noise. Here's an example with 1D noise::
  203. var noise = OpenSimplexNoise.new()
  204. func _ready():
  205. randomize()
  206. # Configure the OpenSimplexNoise instance.
  207. noise.seed = randi()
  208. noise.octaves = 4
  209. noise.period = 20.0
  210. noise.persistence = 0.8
  211. for i in 100:
  212. # Prints a slowly-changing series of floating-point numbers
  213. # between -1.0 and 1.0.
  214. print(noise.get_noise_1d(i))