Random numbers can be very useful in your Small Basic games.  They can be used to make the game play vary from one game to the next.

The Small Basic keyword to get a random number is Math.GetRandomNumber(maxNumber).  It will return a random integer between 1 and the input value maxNumber.

Here are a few ideas and tips:

Random Position and Speed

We can position sprites with random positions and velocities.

radius = 25
numSprite = 10
gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
For i = 1 To numSprite
  sprite[i] = Shapes.AddEllipse(2*radius,2*radius)
  spritePosX[i] = radius+Math.GetRandomNumber(gw-2*radius)
  spritePosY[i] = radius+Math.GetRandomNumber(gh-2*radius)
  spriteVelX[i] = Math.GetRandomNumber(11)-6
  spriteVelY[i] = Math.GetRandomNumber(11)-6
While "True"
  For i = 1 To numSprite
    spritePosX[i] = spritePosX[i]+spriteVelX[i]
    spritePosY[i] = spritePosY[i]+spriteVelY[i]
    If (spritePosX[i] < radius) Then
      spritePosX[i] = radius
      spriteVelX[i] = -spriteVelX[i]
    ElseIf (spritePosX[i] > gw-radius) Then
      spritePosX[i] = gw-radius
      spriteVelX[i] = -spriteVelX[i]
    If (spritePosY[i] < radius) Then
      spritePosY[i] = radius
      spriteVelY[i] = -spriteVelY[i]
    ElseIf (spritePosY[i] > gh-radius) Then
      spritePosY[i] = gh-radius
      spriteVelY[i] = -spriteVelY[i]

Random Branching

We can randomly do different things in the code,  perhaps equivalent to rolling a dice.

dice = Math.GetRandomNumber(6)
If (dice = 1) Then
  TextWindow.WriteLine("Do something for a dice roll of 1")
ElseIf (dice = 2) Then
  TextWindow.WriteLine("Do something for a dice roll of 2")
ElseIf (dice = 3) Then
  TextWindow.WriteLine("Do something for a dice roll of 3")
ElseIf (dice = 4) Then
  TextWindow.WriteLine("Do something for a dice roll of 4")
ElseIf (dice = 5) Then
  TextWindow.WriteLine("Do something for a dice roll of 5")
ElseIf (dice = 6) Then
  TextWindow.WriteLine("Do something for a dice roll of 6")

We could also only do something with a probability, say 1 in 10.

If (Math.GetRandomNumber(10) = 1) Then
  TextWindow.WriteLine("This is a 1 in 10 event!!!")
  TextWindow.WriteLine("A 10% probability event didn't happen")

Ranges and Intervals

If we want random numbers over a different range (not 1 to maxNumber) or with smaller intervals, for example 0.2, then we can use the following formula.

rand = min + (Math.GetRandomNumber(1+(max-min)/interval)-1)*interval

Here is an example using this to create random numbers between -5 and 3, with intervals of 0.2.

min = -5
max = 3
interval = 0.2
For i = 1 To 1000
Sub Random
  rand = min + (Math.GetRandomNumber(1+(max-min)/interval)-1)*interval