-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_loading.rs
256 lines (231 loc) · 7.2 KB
/
game_loading.rs
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use std::{
io::{Cursor, ErrorKind, Read, Write},
mem::align_of,
};
use byteorder::{ReadBytesExt, WriteBytesExt, LE};
use contiguous_mem::*;
pub enum IndexOrPtr<T> {
Index(u32),
Ptr(*const T),
}
impl<T> IndexOrPtr<T> {
pub fn to_ref(&self, data: &[*const T]) -> IndexOrPtr<T> {
match self {
IndexOrPtr::Index(index) => IndexOrPtr::Ptr(data[*index as usize]),
IndexOrPtr::Ptr(ref ptr) => IndexOrPtr::Ptr(*ptr),
}
}
pub fn unwrap_ptr(&self) -> *const T {
match self {
IndexOrPtr::Index(_) => panic!("not a pointer"),
IndexOrPtr::Ptr(ptr) => *ptr,
}
}
pub fn unwrap_ref(&self) -> &'static mut T {
unsafe { &mut *(self.unwrap_ptr() as *mut T) }
}
}
pub trait Load {
unsafe fn load<R: Read>(data: R) -> Self;
}
pub trait Save {
fn save<W: Write>(&self, data: &mut W) -> Result<(), std::io::Error>;
}
pub struct Enemy {
pub max_health: u32,
pub health: u32,
pub speed: f32,
pub age: f32,
}
impl Enemy {
pub fn reset(&mut self) {
self.health = self.max_health;
self.age = 0.0;
}
}
impl Load for Enemy {
unsafe fn load<R: Read>(mut data: R) -> Enemy {
Enemy {
max_health: data.read_u32::<LE>().unwrap_unchecked(),
health: data.read_u32::<LE>().unwrap_unchecked(),
speed: data.read_f32::<LE>().unwrap_unchecked(),
age: data.read_f32::<LE>().unwrap_unchecked(),
}
}
}
impl Save for Enemy {
fn save<W: Write>(&self, data: &mut W) -> Result<(), std::io::Error> {
data.write_u32::<LE>(self.max_health)?;
data.write_u32::<LE>(self.health)?;
data.write_f32::<LE>(self.speed)?;
data.write_f32::<LE>(self.age)?;
Ok(())
}
}
pub struct Level {
pub enemies: Vec<IndexOrPtr<Enemy>>,
}
impl Load for Level {
unsafe fn load<R: Read>(mut data: R) -> Level {
let enemies_count = data.read_u32::<LE>().unwrap();
let enemies = (0..enemies_count).map(|_| {
let enemy_index = data.read_u32::<LE>().unwrap();
IndexOrPtr::Index(enemy_index)
});
Level {
enemies: enemies.collect(),
}
}
}
impl Save for Level {
fn save<W: Write>(&self, data: &mut W) -> Result<(), std::io::Error> {
data.write_u32::<LE>(self.enemies.len() as u32)?;
for enemy in self.enemies.iter() {
match enemy {
IndexOrPtr::Index(index) => data.write_u32::<LE>(*index)?,
IndexOrPtr::Ptr(_) => {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
"can't save level with references",
))
}
}
}
Ok(())
}
}
// this function emulates FS access for this example, ignore it
fn load_game_file<T: Load>(file_name: &'static str) -> T {
let mut data = Vec::with_capacity(24);
let mut data_cursor = Cursor::new(&mut data);
match file_name {
"enemy1.dat" => Enemy {
max_health: 200,
health: 200,
speed: 2.0,
age: 0.0,
}
.save(&mut data_cursor)
.unwrap(),
"enemy2.dat" => Enemy {
max_health: 200,
health: 200,
speed: 2.0,
age: 0.0,
}
.save(&mut data_cursor)
.unwrap(),
"enemy3.dat" => Enemy {
max_health: 200,
health: 200,
speed: 2.0,
age: 0.0,
}
.save(&mut data_cursor)
.unwrap(),
"enemy4.dat" => Enemy {
max_health: 200,
health: 200,
speed: 2.0,
age: 0.0,
}
.save(&mut data_cursor)
.unwrap(),
"level1.dat" => Level {
enemies: vec![
IndexOrPtr::Index(0),
IndexOrPtr::Index(1),
IndexOrPtr::Index(1),
IndexOrPtr::Index(2),
],
}
.save(&mut data_cursor)
.unwrap(),
"level2.dat" => Level {
enemies: vec![
IndexOrPtr::Index(1),
IndexOrPtr::Index(1),
IndexOrPtr::Index(1),
IndexOrPtr::Index(2),
IndexOrPtr::Index(2),
IndexOrPtr::Index(3),
IndexOrPtr::Index(3),
],
}
.save(&mut data_cursor)
.unwrap(),
_ => unreachable!(),
};
data_cursor.set_position(0);
unsafe { T::load(data_cursor) }
}
fn main() {
let mut data = UnsafeContiguousMemory::new_aligned(112, align_of::<Level>()).unwrap();
// Create enemy lookup list.
let enemies: &[*const Enemy] = unsafe {
&[
data.push(load_game_file("enemy1.dat")).unwrap_unchecked(),
data.push(load_game_file("enemy2.dat")).unwrap_unchecked(),
data.push(load_game_file("enemy3.dat")).unwrap_unchecked(),
data.push(load_game_file("enemy4.dat")).unwrap_unchecked(),
]
};
// Create level lookup list.
let levels: &[*mut Level] = unsafe {
&[
data.push(load_game_file("level1.dat")).unwrap_unchecked(),
data.push(load_game_file("level2.dat")).unwrap_unchecked(),
]
};
// data won't go out of scope while we're using it in this example, but in
// your use case it might. This is here for completeness.
data.forget();
// now we can assume all created pointers are 'static
// prepare levels for use
levels.iter().for_each(|level| {
let level = unsafe { &mut **level };
level.enemies = level
.enemies
.iter()
.map(|enemy| enemy.to_ref(enemies))
.collect();
});
let mut time = 0.0;
let mut current_level: usize = 0;
// Main game loop
while current_level < levels.len() {
// Simulate the passage of time (you can replace this with your game logic)
time += 1.0;
let mut all_enemies_killed = true;
let current_lvl = unsafe { &mut *levels[current_level] };
for enemy in current_lvl.enemies.iter_mut() {
let enemy_ref = enemy.unwrap_ref();
let health_reduction = ((5.0 + time * 0.25) as u32).min(enemy_ref.health);
enemy_ref.health -= health_reduction;
enemy_ref.age += 1.0;
// Check if the enemy is still alive
if enemy_ref.health > 0 {
all_enemies_killed = false;
}
}
// If all enemies in the current level are killed, reset them and progress to the next level
if all_enemies_killed {
println!(
"All enemies in level {} have been killed!",
current_level + 1
);
current_level += 1;
// Reset all enemies in the next level
if current_level < levels.len() {
let next_level = unsafe { &mut *levels[current_level] };
for enemy in next_level.enemies.iter_mut() {
enemy.unwrap_ref().reset();
}
}
}
}
println!(
"Congratulations! You've completed all levels in: {:.2}",
time
);
}