impls wealth updating

This commit is contained in:
2019-07-02 15:07:03 +02:00
parent 9acedd4119
commit 36c8f24fdc
5 changed files with 57 additions and 17 deletions

View File

@@ -1,3 +1,4 @@
use diesel::prelude::*;
use crate::schema::players;
use crate::DbConnection;
@@ -14,11 +15,31 @@ pub struct Player {
}
/// Wealth represented as a single fractionnal amount of gold pieces
#[derive(Identifiable, AsChangeset)]
/// Unpack a floating value in gold pieces to integer
/// values of copper, silver, gold and platinum pieces
///
/// # Note
///
/// The conversion is slightly different than standard rules :
/// ``` 1pp = 100gp = 1000sp = 10000 cp ```
///
fn unpack_gold_value(gold: f32) -> (i32, i32, i32, i32) {
let rest = (gold.fract() * 100.0).round() as i32;
let gold = gold.trunc() as i32;
let pp = gold / 100;
let gp = gold % 100;
let sp = rest / 10;
let cp = rest % 10;
(cp, sp, gp, pp)
}
/// Represent an update on a player's wealth
///
/// The values held here are the amount of pieces to add or
/// substract to player wealth.
#[derive(Queryable, AsChangeset, Debug)]
#[table_name="players"]
struct WealthUpdate {
id: i32,
pub struct WealthUpdate {
cp: i32,
sp: i32,
gp: i32,
@@ -27,10 +48,15 @@ struct WealthUpdate {
impl WealthUpdate{
/// Unpack individual pieces counts from gold value
fn from_gp(id: i32, gp: f32) -> Self {
// TODO: 0,01 pp = 1 gp = 10 sp = 100 cp
let (cp, sp, gp, pp) = (0,0,0,0);
Self { id, cp, sp, gp, pp }
pub fn from_gp(gp: f32) -> Self {
let (cp, sp, gp, pp) = unpack_gold_value(gp);
Self { cp, sp, gp, pp }
}
pub fn to_gp(&self) -> f32 {
let i = self.pp * 100 + self.gp;
let f = ( self.sp * 10 + self.cp ) as f32 / 100.0;
i as f32 + f
}
}