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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
pub mod entities;
pub mod map;
use std::collections::HashMap;
use std::error::Error;
use std::fs::{self, File};
use std::io::Read;
use std::io::Write;
use super::geometry::Point;
use crate::bincode::{deserialize, serialize};
use entities::GameEntity;
use map::{GameMap, DEFAULT_MAP, DEFAULT_MAP_DIMENSIONS, DEFAULT_MAP_NAME};
#[derive(Debug)]
enum GameMessage {
Interact {
source: GameEntity,
target: GameEntity,
},
TriggerAbility {
target: GameEntity,
},
Move {
target: GameEntity,
destination: Point,
},
}
#[derive(Debug)]
pub struct GameState {
entities: Vec<GameEntity>,
}
#[derive(Debug)]
pub struct ActiveGame {
pub map: GameMap,
pub state: GameState,
pub started_time: u32,
}
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
{
calculation: T,
values: HashMap<U, V>,
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: std::cmp::Eq + std::hash::Hash + std::cmp::PartialEq + Copy,
V: std::cmp::Eq + Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
Some(v) => *v,
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, v);
v
}
}
}
}
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v1, 1);
assert_eq!(v2, 2);
}
#[test]
fn call_with_different_types() {
let mut c = Cacher::new(|_a| "some_str");
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v1, v2);
assert_eq!(v1, "some_str");
let mut c = Cacher::new(|_a| 1);
let v1 = c.value("foo");
let v2 = c.value("bar");
assert_eq!(v1, v2);
assert_eq!(v1, 1);
}
pub fn recreate_default_map() -> Result<GameMap, Box<dyn Error>> {
println!("Recreating default map");
let mut file = File::create(DEFAULT_MAP)?;
let map_struct = GameMap {
dimensions: DEFAULT_MAP_DIMENSIONS,
name: DEFAULT_MAP_NAME.to_string(),
};
let encoded: Vec<u8> = serialize(&map_struct).unwrap();
file.write_all(&encoded)?;
Ok(map_struct)
}
pub fn get_default_map() -> Result<GameMap, Box<dyn Error>> {
let mut map_file = match File::open(DEFAULT_MAP) {
Ok(f) => f,
Err(_error) => return recreate_default_map(),
};
let mut map_data = Vec::<u8>::new();
map_file.read_to_end(&mut map_data)?;
match deserialize(&map_data) {
Ok(map_struct) => Ok(map_struct),
Err(_error) => recreate_default_map(),
}
}
pub fn start_game(map: GameMap) -> ActiveGame {
ActiveGame {
map,
state: GameState {
entities: Vec::new(),
},
started_time: 0,
}
}