mvbg

VM_RAND

VM_RAND is a GBVM instruction used to generate a pseudo-random number within a specified range and store it into a GBVM variable.

Purpose: Randomness is a cornerstone of dynamic and engaging game experiences. VM_RAND allows you to introduce unpredictability into your game logic, which is essential for:

It generates a number between MIN (inclusive) and MIN + LIMIT (exclusive). For example, if MIN is 0 and LIMIT is 10, the random number will be between 0 and 9.

Syntax:

VM_RAND IDX, MIN, LIMIT

Usage Example: Random Enemy Movement Direction

Imagine an enemy that moves randomly in one of four directions (Up, Down, Left, Right). You can assign numerical values to these directions (e.g., 0=Up, 1=Down, 2=Left, 3=Right) and use VM_RAND to pick one.

; In your enemy AI script:

; Variable to store the randomly chosen direction
VAR_ENEMY_MOVE_DIR:
  .R_INT8 0

; Generate a random number between 0 and 3 (inclusive)
VM_RAND VAR_ENEMY_MOVE_DIR, 0, 4
; IDX: VAR_ENEMY_MOVE_DIR
; MIN: 0
; LIMIT: 4 (generates 0, 1, 2, or 3)

; Now, VAR_ENEMY_MOVE_DIR holds a random direction.
; Use conditional logic to apply the movement:
VM_IF_CONST .EQ, VAR_ENEMY_MOVE_DIR, 0, MOVE_UP, 0
VM_IF_CONST .EQ, VAR_ENEMY_MOVE_DIR, 1, MOVE_DOWN, 0
VM_IF_CONST .EQ, VAR_ENEMY_MOVE_DIR, 2, MOVE_LEFT, 0
VM_IF_CONST .EQ, VAR_ENEMY_MOVE_DIR, 3, MOVE_RIGHT, 0

MOVE_UP:
  VM_ACTOR_SET_DIR ENEMY_ACTOR, DIR_UP
  VM_ACTOR_MOVE_TO ENEMY_ACTOR, ENEMY_X, ENEMY_Y - 16, 16
  VM_JUMP END_ENEMY_MOVE

MOVE_DOWN:
  VM_ACTOR_SET_DIR ENEMY_ACTOR, DIR_DOWN
  VM_ACTOR_MOVE_TO ENEMY_ACTOR, ENEMY_X, ENEMY_Y + 16, 16
  VM_JUMP END_ENEMY_MOVE

MOVE_LEFT:
  VM_ACTOR_SET_DIR ENEMY_ACTOR, DIR_LEFT
  VM_ACTOR_MOVE_TO ENEMY_ACTOR, ENEMY_X - 16, ENEMY_Y, 16
  VM_JUMP END_ENEMY_MOVE

MOVE_RIGHT:
  VM_ACTOR_SET_DIR ENEMY_ACTOR, DIR_RIGHT
  VM_ACTOR_MOVE_TO ENEMY_ACTOR, ENEMY_X + 16, ENEMY_Y, 16
  VM_JUMP END_ENEMY_MOVE

END_ENEMY_MOVE:
  ; ... continue enemy AI ...

In this example, VM_RAND generates a random number between 0 and 3, which is then used to determine the enemy’s movement direction. This makes the enemy’s behavior less predictable and more dynamic.

Important Note on Seeding: Remember that VM_RAND is a pseudo-random number generator. For truly varied sequences across game sessions, you should seed the PRNG using VM_INIT_RNG (with a dynamic seed like the Real-Time Clock) or VM_RANDOMIZE at the start of your game or at appropriate points.

Analogy to other programming languages: This is analogous to generating a random integer within a range in other programming languages:

It provides the core functionality for introducing controlled randomness into your game logic.