1
Fork 0
mirror of https://github.com/Steffo99/hella-farm.git synced 2024-11-22 08:04:23 +00:00
hella-farm/behaviours/sampler_weighted.gd

31 lines
634 B
GDScript3
Raw Normal View History

2024-04-16 03:08:25 +00:00
extends Sampler
class_name SamplerWeighted
## Sample a random reference from the array, considering the given weights.
@export var possibilities: Array = []
@export var weights: Array[int] = []
func sample() -> Object:
var total = compute_total_weight()
if total == 0:
return null
var sampled = Random.rng.randi_range(0, total - 1)
var idx = -1
while sampled >= 0:
idx += 1
sampled -= weights[idx]
return possibilities[idx]
func compute_total_weight() -> int:
var total = 0
for weight in weights:
if weight < 0:
Log.e(self, "Weight with negative value detected.")
return 0
total += weight
return total