-
Notifications
You must be signed in to change notification settings - Fork 16
/
action.rs
290 lines (249 loc) · 7.95 KB
/
action.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use std::io::prelude::*;
use std::path::{Path};
use std::fs::{self, File};
use rand::StdRng;
use rand::SeedableRng;
use std::iter::Filter;
use util::Dijkstra;
use entity::Entity;
use ecs::EntityIter;
use world;
use flags;
use dir6::Dir6;
use area::Area;
use location::Location;
use ecs::{ComponentAccess};
use msg;
/// Game update control.
#[derive(Copy, PartialEq)]
pub enum ControlState {
AwaitingInput,
ReadyToUpdate,
}
/// Player input action.
#[derive(Copy, Eq, PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Input {
/// Take a step in the given direction.
Step(Dir6),
/// Melee attack in the given direction.
Melee(Dir6),
/// Shoot in the given direction.
Shoot(Dir6),
/// Do nothing for a turn.
Pass,
}
/// Return the player entity if one exists.
pub fn player() -> Option<Entity> {
world::with(|w| w.flags.player)
}
/// Return true if the game has ended and the player can make no further
/// actions.
pub fn is_game_over() -> bool {
player().is_none()
}
/// Find the first entity that has a local (not inherited) Desc component with
/// the given name.
pub fn find_prototype(name: &str) -> Option<Entity> {
world::with(|w|
entities().find(|&e| {
if let Some(d) = w.descs().get_local(e) {
if d.name == name { return true; }
}
false
})
)
}
/// Spawn a specific type of entity
pub fn spawn_named(name: &str, loc: Location) {
find_prototype(name).expect(&format!("Spawn prototype '{}' not found", name)[..])
.clone_at(loc);
}
// World update state machine //////////////////////////////////////////
/// Get the current control state.
pub fn control_state() -> ControlState {
if world::with(|w| w.flags.player_acted) { return ControlState::ReadyToUpdate; }
match player() {
Some(p) if p.acts_this_frame() => ControlState::AwaitingInput,
_ => ControlState::ReadyToUpdate,
}
}
/// Top-level game state update function. Only valid to call if
/// control_state() returned ReadyToUpdate.
pub fn update() {
assert!(control_state() == ControlState::ReadyToUpdate);
ai_main();
world::with_mut(|w| {
w.flags.tick += 1;
w.flags.player_acted = false;
});
}
/// Give player input. Only valid to call if control_state() returned
/// AwaitingInput.
pub fn input(input: Input) {
assert!(control_state() == ControlState::AwaitingInput);
let p = player().expect("No player to receive input");
match input {
Input::Step(d) => {
p.step(d);
}
Input::Melee(d) => {
p.melee(d);
}
Input::Shoot(d) => {
p.shoot(d);
}
Input::Pass => {
}
}
world::with_mut(|w| w.flags.player_acted = true);
// Run one world update cycle right away, so that we don't get awkward
// single frames rendered where the player has acted and the rest of the
// world hasn't.
if control_state() == ControlState::ReadyToUpdate {
update();
}
}
// Entities ////////////////////////////////////////////////////////////
/// Return an iterator of all the world entities.
pub fn entities() -> EntityIter {
world::with(|w| w.ecs.iter())
}
/// Return an iterator of all the world mobs.
pub fn mobs() -> Filter<EntityIter, fn(&Entity) -> bool> {
fn is_mob(e: &Entity) -> bool { e.is_mob() }
entities().filter(is_mob as fn(&Entity) -> bool)
}
/// Run AI for all autonomous mobs.
fn ai_main() {
for entity in entities() {
entity.update();
}
}
// World logic /////////////////////////////////////////////////////////
/// Return the current floor depth. Greater depths mean more powerful monsters
/// and stranger terrain.
pub fn current_depth() -> i32 { world::with(|w| w.area.seed.spec.depth) }
pub fn start_level(depth: i32) {
let biome = match depth {
1 => ::Biome::Overland,
_ => ::Biome::Dungeon,
};
clear_nonplayers();
let seed = world::with(|w| w.flags.seed);
let new_area = Area::new(
seed,
::AreaSpec::new(biome, depth));
// XXX: How to move area into the closure without cloning?
world::with_mut(|w| {
w.area = new_area.clone();
});
let mut rng: StdRng = SeedableRng::from_seed(&[seed as usize + depth as usize][..]);
for (spawn, loc) in world::with(|w| w.area.get_spawns()).into_iter() {
spawn.spawn(&mut rng, loc);
}
let start_loc = world::with(|w| w.area.player_entrance());
// Either reuse the existing player or create a new one.
match player() {
Some(p) => {
p.forget_map();
p.place(start_loc);
}
None => {
let player = find_prototype("player").expect("No Player prototype found!")
.clone_at(start_loc);
world::with_mut(|w| w.flags.player = Some(player));
}
};
flags::set_camera(start_loc);
}
fn clear_nonplayers() {
let po = player();
for e in entities() {
// Don't destroy player or player's inventory.
if let Some(p) = po {
if e == p || p.contains(e) {
continue;
}
}
if e.location().is_some() {
e.delete();
}
}
}
/// Move the player to the next level.
pub fn next_level() {
// This is assuming a really simple, original Rogue style descent-only, no
// persistent maps style world.
start_level(current_depth() + 1);
caption!("Depth {}", current_depth() - 1);
}
// Effects /////////////////////////////////////////////////////////////
/// Create a projectile arc in dir from origin.
pub fn shoot(origin: Location, dir: Dir6, range: u32, power: i32) {
let mut loc = origin;
if range == 0 { return; }
for i in 1..(range + 1) {
loc = origin + dir.to_v2() * (i as i32);
if loc.terrain().blocks_shot() {
msg::push(::Msg::Sparks(loc));
break;
}
if let Some(e) = loc.mob_at() {
e.damage(power);
break;
}
}
msg::push(::Msg::Beam(origin, loc));
}
////////////////////////////////////////////////////////////////////////
/// Build a Dijkstra map towards the unexplored corners of the player's FOV.
///
/// Pathing_depth is the depth of the search map. Low pathing depths may not
/// reach distant unexplored cells, but high pathing depths take longer to
/// calculate.
pub fn autoexplore_map(pathing_depth: u32) -> Option<Dijkstra<Location>> {
let locs = world::with(|w| w.area.terrain.iter()
.map(|(&loc, _)| loc)
.filter(|loc| loc.fov_status().is_none())
.collect::<Vec<Location>>());
if locs.len() == 0 {
return None;
}
Some(Dijkstra::new(locs, |&loc| !loc.blocks_walk(), pathing_depth))
}
/// Look for targets to shoot in a direction.
pub fn find_target(shooter: Entity, dir: Dir6, range: usize) -> Option<Entity> {
let origin = shooter.location().unwrap();
for i in 1..(range + 1) {
let loc = origin + dir.to_v2() * (i as i32);
if loc.terrain().blocks_shot() {
break;
}
if let Some(e) = loc.mob_at() {
if shooter.is_hostile_to(e) { return Some(e); }
}
}
None
}
////////////////////////////////////////////////////////////////////////
pub fn save_game() {
// Only save if there's still a living player around.
if is_game_over() {
return;
}
let save_data = world::save();
File::create("magog_save.json").unwrap()
.write_all(&save_data.into_bytes()).unwrap();
}
pub fn load_game() {
let path = Path::new("magog_save.json");
if !path.exists() { return; }
let mut save_data = String::new();
File::open(&path).unwrap().read_to_string(&mut save_data).unwrap();
// TODO: Handle failed load nicely.
world::load(&save_data[..]).unwrap();
}
pub fn delete_save() {
fs::remove_file("magog_save.json").unwrap();
}
pub fn save_exists() -> bool { Path::new("magog_save.json").exists() }