1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
use std::cell::RefCell;
use std::time::Duration;
use std::{fmt::Display, string};
use std::error::Error;
use crate::GameState;
pub type Second = u64;
pub const MINUTE: Second = 60;
pub const HOUR: Second = MINUTE * 60;
pub const DAY: Second = HOUR * 24;
pub const YEAR: Second = DAY * 365;
pub const SYSTEM_TICK_INTERVAL: Second = 1 * DAY;
pub struct TimeMan
{
time: Second,
last_time: Second,
pub auto_tick: Option<Second>
}
impl TimeMan
{
pub fn new(time: Second)
-> Self {
Self {
time,
last_time: time,
auto_tick: None
}
}
pub fn seconds(&self)
-> Second {
self.time
}
pub fn advance(
&mut self,
by: Second)
{
self.time += by;
}
pub fn update(
&mut self)
-> Vec<Second>
{
match self.auto_tick {
Some(advance) => { self.time += advance; },
None => {}
}
let time_diff = self.time - self.last_time;
let tick_diff = self.time / SYSTEM_TICK_INTERVAL -
self.last_time / SYSTEM_TICK_INTERVAL;
if time_diff == 0 || tick_diff == 0 {
self.last_time = self.time;
return vec![];
}
let time_start = self.last_time - (self.last_time % SYSTEM_TICK_INTERVAL);
let time_end = self.time - (self.time % SYSTEM_TICK_INTERVAL);
let tick_start = time_start / SYSTEM_TICK_INTERVAL;
let tick_end = time_end / SYSTEM_TICK_INTERVAL;
self.last_time = self.time;
(tick_start..tick_end).map(|v| {
v * SYSTEM_TICK_INTERVAL
}).collect::<Vec<_>>()
}
pub fn format_duration(time: Second) -> String
{
let seconds = time % 60;
let minutes = (time / 60) % 60;
let hours = (time / (60 * 60)) % 24;
let days = (time / (60 * 60 * 24)) % 365;
let years = time / (60 * 60 * 24 * 365);
if time == 0 {
return "0s".to_string();
}
format!("{}{}{}{}{}",
if years > 0 { format!("{}y", years) } else { format!("") },
if days > 0 { format!("{}d", days) } else { format!("") },
if hours > 0 { format!("{}h", hours) } else { format!("") },
if minutes > 0 { format!("{}m", minutes) } else { format!("") },
if seconds > 0 { format!("{}s", seconds) } else { format!("") })
}
} //impl TimeMan
|