mirror of
https://gitlab.com/veloren/veloren.git
synced 2024-08-30 18:12:32 +00:00
Implemented a lottery system
This commit is contained in:
parent
e05c9267a7
commit
d101d7f132
5
assets/common/items/loot_table.ron
Normal file
5
assets/common/items/loot_table.ron
Normal file
@ -0,0 +1,5 @@
|
||||
Lottery(
|
||||
items : Vec(
|
||||
// All loot rates go here
|
||||
)
|
||||
)
|
44
common/src/comp/inventory/item/lottery.rs
Normal file
44
common/src/comp/inventory/item/lottery.rs
Normal file
@ -0,0 +1,44 @@
|
||||
use crate::{
|
||||
assets::{self, Asset},
|
||||
};
|
||||
use rand::prelude::*;
|
||||
use std::{fs::File, io::BufReader};
|
||||
|
||||
// Generate a random float between 0 and 1
|
||||
pub fn rand() -> f32 {
|
||||
let mut rng = rand::thread_rng();
|
||||
rng.gen()
|
||||
}
|
||||
|
||||
pub struct Lottery<T> {
|
||||
items: Vec<f32, T>,
|
||||
total: f32,
|
||||
}
|
||||
|
||||
impl Asset for Lottery<&str> {
|
||||
const ENDINGS: &'static [&'static str] = &["ron"];
|
||||
|
||||
fn parse(buf_reader: BufReader<File>) -> Result<Self, assets::Error> {
|
||||
ron::de::from_reader(buf_reader).map_err(assets::Error::parse_error)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Lottery<T> {
|
||||
pub fn from_rates(items: impl Iterator<Item=(f32, T)>) -> Self {
|
||||
let mut total = 0.0;
|
||||
let items = items
|
||||
.map(|(rate, item| {
|
||||
total += rate;
|
||||
(total - rate, item)
|
||||
})
|
||||
.collect();
|
||||
Self { items, total }
|
||||
}
|
||||
|
||||
pub fn choose(&self) -> &T {
|
||||
let x = rand() * self.total;
|
||||
&self.items[self.items
|
||||
.binary_search_by(|(y, _)|, y.partial_cmp(&x).unwrap())
|
||||
.unwrap_or_else(|i| i.saturating_sub(1))].1
|
||||
}
|
||||
}
|
@ -181,6 +181,7 @@ impl Item {
|
||||
BlockKind::Coconut => Some(assets::load_expect_cloned("common.items.coconut")),
|
||||
BlockKind::Chest => Some(assets::load_expect_cloned(
|
||||
[
|
||||
// TODO: Throw it all out and replace with the loot table (common/items/loot_table.ron)
|
||||
//miscellaneous
|
||||
"common.items.velorite",
|
||||
"common.items.veloritefrag",
|
||||
|
Loading…
Reference in New Issue
Block a user