Hey,
I realized I've never written a basic item drop code including loot tables, which is all about random choices, so here goes:
// Project: Loot Table
// Created: 2018-06-09
#option_explicit
SetErrorMode ( 2 )
SetWindowTitle ( "Loot Table" )
SetWindowSize ( 1024, 768, 0 )
SetVirtualResolution ( 1024, 768 )
SetRandomSeed ( GetUnixTime() )
type LootTableType
weight as integer // types are sorted by their first field, so weight is on top ( weight is basically the drop probability )
item as string // item description
rangeL as integer // drop range - LOW value
rangeH as integer // drop range - HIGH value
endtype
global loot as LootTableType[0]
global drop as integer = -1
// let's add some stuff to the loot table in random order
// the first parameter is the item description, the second parameter the drop probability
// the drop probability for each item is the item weight / total weight * 100
// total weight = 15 + 25 + 5 + 45 + 10 + 100 = 200
// drop probability of the Looter's Backpack: 5 / 200 * 100 = 2.5%
// Silver Coins drop 5 times as often as Looter's Backpacks, and NO DROPs appear 10 times as often as Scroll drops
// using this system makes it pretty easy to adjust drop probabilities
AddItem ( "Bastard Sword", 15 )
Additem ( "Silver Coin", 25 )
AddItem ( "Looter's Backpack", 5 )
AddItem ( "Empty Flask", 45 )
AddItem ( "Scroll", 10 )
AddItem ( "NO DROP :(", 100 )
do
if GetRawKeyReleased ( 32 )
drop = ItemDrop()
endif
if drop <> -1
print ( loot[drop].item )
endif
print ( "Press SPACE to loot" )
Sync()
loop
// adds an item to the loot table
function AddItem ( item as string, weight as integer )
local i as integer
local l as integer
local h as integer
loot.length = loot.length + 1 // increase size of loot table by 1
loot[loot.length].item = item // add item description
loot[loot.length].weight = weight // add item weight
loot.sort() // sort the loot table, beginning with the rarest item
for i=1 to loot.length // determine drop ranges of all items in the loot table ( low and high values )
l = l + loot[i-1].weight
h = h + loot[i].weight
loot[i].rangeL = l
loot[i].rangeH = h
next i
endfunction
// drops an item ( or not )
function ItemDrop()
local i as integer
local r as integer
local w as integer
// calculate total weight
for i= 1 to loot.length
inc w, loot[i].weight
next i
r = random ( 1, w )
// run through the loot table and find the item that fits in the weight range
for i=1 to loot.length
if r >= loot[i].rangeL AND r <= loot[i].rangeH
message ( "Roll: " + str ( r ) )
exitfunction i
endif
next i
endfunction -1
It basically uses this approach which is quite the standard:
http://www.lostgarden.com/2014/12/loot-drop-tables.html
I heavily commented it, so it's pretty self-explanatory.
Maybe you can use it...
Cheers,
PSY