API Reference › Random › Random.chance
method

Random.chance

Random.chance(percent) -> bool

Returns true roughly percent times out of a hundred, and false otherwise — a convenient shorthand for "this happens X% of the time". Use it to gate random events such as spawning an enemy on a given frame, dropping loot, or triggering a rare animation. Passing 0 never fires and 100 always fires. Like the rest of the Random namespace it is driven by the seeded generator, so seed it with Random.seed for reproducible behavior.

Parameters

percentthe probability of returning true, from 0 to 100

Example

program SpawnWave {
  property Position { column: int = 0, row: int = 0 }
  model Enemy { Position }

  const GRID_WIDTH: int = 20
  const TILE_SIZE: int = 16

  handler SeedRandom phase Start {
    Random.seed(value: 3)
  }

  handler MaybeSpawn phase Update {
    if Random.chance(percent: 10) {
      spawn Enemy {
        Position { column: Random.range(low: 0, high: GRID_WIDTH - 1), row: 0 }
      }
    }
  }

  handler DrawWorld phase Render {
    Screen.clear(Color.MidnightBlue)
    for (Position) in query [Position, {Enemy}] {
      Screen.fill_rectangle(
        x: Position.column * TILE_SIZE,
        y: Position.row * TILE_SIZE,
        width: TILE_SIZE,
        height: TILE_SIZE,
        color: Color.Crimson)
    }
    Screen.show()
  }
}
← All symbols