Home Blog Gaming

GDScript Random Numbers

Godot Tutorials > GDScript Random Numbers

Game development often includes random events. Even when games are largely based on skill, there is still usually some element of chance. Random numbers are one way to program randomly occuring events and outcomes. In this lesson we will learn to generate random numbers with GDScript.

randomize ( )

There are several GDScript pre-defined functions for generating randomness. We learned one, shuffle, in the array functions lesson. These functions actually generate pseudo-randomness. Because the outcome is generated using an algorithm, the outcome is not truely random. If you know the algorithm, you can predict its outcome. However, the algoriths use a seed. A seed is a parameter passed into the algorithm. In order to simulate randomness we use randomize to generate a time based seed. Just as we used randomize to shuffle an array, we will use it to generate pseudo-random numbers.


Random Floats

randf() is used to generate a random float between 0 and 1. Let's look at an example where we generate 3 random floats then print the results.

func _ready():
  # generate seed
  randomize()
  # generate 3 random floats
  var rand_float_1 = randf()
  var rand_float_2 = randf()
  var rand_float_3 = randf()
  # Print Random Floats
  print ("Random Number 1: ", rand_float_1)
  print ("Random Number 2: ", rand_float_2)
  print ("Random Number 3: ", rand_float_3)

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
Random Number 1: 0.817816
Random Number 2: 0.685592
Random Number 3: 0.12154
** Debug Process Stopped **

Now let's run the same code a second time.

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
Random Number 1: 0.195899
Random Number 2: 0.841726
Random Number 3: 0.999226
** Debug Process Stopped **

Each time we run the code, the output should be different. When you run the code at home, your results will be different then mine.

You might not want to generate a random float between 0 and 1. If you want to provide your own range use randf_range

extends Node

# Declare new random number generator
var rand_generate = RandomNumberGenerator.new()

func _ready():
    # randomize seed
    rand_generate.randomize()
    # generate a random float between -1 and 0
    var rand_float = rand_generate.randf_range(-1.0, 1.0)
    # print random number
    print (rand_float)

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
0.984032
** Debug Process Stopped **

Let's run the same code again.

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
-0.707864
** Debug Process Stopped **

Random Integer

We can use randi() to generate a random number between 0 and 4,294,967,295.

func _ready():
  randomize()
  var rand_int = randi()
  print (rand_int)
  

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
809093518
** Debug Process Stopped **

But we probably want to specifiy a range...

extends Node

# Declare new random number generator
var rand_generate = RandomNumberGenerator.new()

func _ready():
    # randomize seed
    rand_generate.randomize()
    # generate a random integer between 1 and 10
    var rand_int = rand_generate.randi_range(1,10)
    # print random number
    print (rand_int)

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
5
** Debug Process Stopped **

Let's run the same code again...

Output

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
1
** Debug Process Stopped **

Homework

Use GDScript code to solve the following problems:
  1. Generate a random float between -1 and 0.
  2. Create a function the simulates fliping a coin. The function will take in two names as parameters. These are the two players. Each will flip the coin. The player who gets heads wins. If both players get heads, it is a tie. If no one gets heads, they both flip again until someone wins or it is a tie. Print the results.
  3. You are creating a quiz game. There are three levels of question difficulty: easy, medium, and hard. About 20% of the time you want an easy question. About 20% of the time you want a hard question. Using these percentages write code that randomly outputs a question. You may use dictionaries or arrays to store your questions. You must have an equal number of questions for each difficulty level.

Want Commander Candy to Grade Your Homework?

Donate

Linux Gaming Blog - Coding Commanders
Palm Beach Techie - Diverisity in Tech
Linux Gaming King Hatnix on Twitch
murks - Linux Game Dev
Women in Tech - Milly Berst
Women in Tech - Robyn Silber
Women in Tech - she_who_codes
jookia - DOS Bots
Twitch: daisychaincosplay Live Coding!!!
Learn PHP on Linux with Commander Candy
Coding Commanders YouTube
Coding Commanders Twitter
Previous Lesson | Next Lesson