]> git.lizzy.rs Git - elidragon_v2.git/commitdiff
Add random API
authorElias Fleckenstein <eliasfleckenstein@web.de>
Fri, 19 Feb 2021 09:47:35 +0000 (10:47 +0100)
committerElias Fleckenstein <eliasfleckenstein@web.de>
Fri, 19 Feb 2021 09:47:35 +0000 (10:47 +0100)
mods/elidragon_random/init.lua [new file with mode: 0644]
mods/elidragon_random/mod.conf [new file with mode: 0644]

diff --git a/mods/elidragon_random/init.lua b/mods/elidragon_random/init.lua
new file mode 100644 (file)
index 0000000..98d54fc
--- /dev/null
@@ -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 (file)
index 0000000..7bcf69c
--- /dev/null
@@ -0,0 +1,4 @@
+name = elidragon_random
+author = Fleckenstein
+description = A random API for Elidragon v2
+depends = elidragon