From: Elias Fleckenstein Date: Fri, 19 Feb 2021 09:47:35 +0000 (+0100) Subject: Add random API X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=ea8a19bce6e5ef596a5d868c7a56f1acc7ab7032;p=elidragon_v2.git Add random API --- diff --git a/mods/elidragon_random/init.lua b/mods/elidragon_random/init.lua new file mode 100644 index 0000000..98d54fc --- /dev/null +++ b/mods/elidragon_random/init.lua @@ -0,0 +1,42 @@ +local random = { + choices = {}, + probabilities = {}, + csum = {}, + sum = 0 +} + +random.__index = random + +function random:new(o) + o = o or {} + setmetatable(o, self) + o.choices = {} + o.probabilities = {} + o.csum = {} + o.sum = 0 + return o +end + +function random:calc_csum() + self.sum = 0 + for i, choice in ipairs(self.choices) do + self.sum = self.sum + self.probabilities[choice] + self.csum[choice] = self.sum + end +end + +function random:choose() + local r = math.random() + math.random(0, self.sum - 1) + for i, choice in pairs(self.choices) do + if r < self.csum[choice] then + return choice + end + end +end + +function random:add_choice(choice, probability) + table.insert(self.choices, choice) + self.probabilities[choice] = probability +end + +elidragon.random = random diff --git a/mods/elidragon_random/mod.conf b/mods/elidragon_random/mod.conf new file mode 100644 index 0000000..7bcf69c --- /dev/null +++ b/mods/elidragon_random/mod.conf @@ -0,0 +1,4 @@ +name = elidragon_random +author = Fleckenstein +description = A random API for Elidragon v2 +depends = elidragon