-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy patharmy.rs
324 lines (288 loc) · 8.79 KB
/
army.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::path::Path;
use bevy::prelude::*;
use bevy_ecs::entity::{EntityMapper, MapEntities};
use moonshine_save::prelude::*;
const SAVE_PATH: &str = "army.ron";
const HELP_TEXT: &str =
"Use the buttons to spawn a new soldier with either a melee or a ranged weapon.
The text displays the army composition by grouping soldiers based on their equipped weapon.
The state of this army can be saved into and loaded from disk.";
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Army".to_string(),
resolution: (700., 200.).into(),
..default()
}),
..default()
}))
// Save and Load plugins are independant.
// Usually, both are needed:
.add_plugins((SavePlugin, LoadPlugin))
// Register game types for de/serialization
.register_type::<Soldier>()
.register_type::<SoldierWeapon>()
.register_type::<Option<Entity>>()
.register_type::<WeaponKind>()
// Add gameplay systems:
.add_systems(Startup, setup)
.add_systems(Update, (update_text, update_buttons))
.add_systems(
Update,
(
add_melee_button_clicked,
add_ranged_button_clicked,
load_button_clicked,
save_button_clicked,
),
)
// Add save/load pipelines:
.add_systems(
PreUpdate,
save_default().into(file_from_resource::<SaveRequest>()),
)
.add_systems(PreUpdate, load(file_from_resource::<LoadRequest>()))
.run();
}
/// Represents a soldier entity within the army.
#[derive(Bundle)]
struct SoldierBundle {
// Marker
soldier: Soldier,
// Currently equipped weapon entity
weapon: SoldierWeapon,
// Soldiers should be saved
save: Save,
}
impl SoldierBundle {
fn new(weapon: Entity) -> Self {
Self {
soldier: Soldier,
weapon: SoldierWeapon(Some(weapon)),
save: Save,
}
}
}
#[derive(Component, Default, Reflect)]
#[reflect(Component)]
struct Soldier;
#[derive(Component, Default, Reflect)]
#[reflect(Component, MapEntities)]
struct SoldierWeapon(Option<Entity>);
impl MapEntities for SoldierWeapon {
fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
if let Some(weapon) = self.0.as_mut() {
*weapon = entity_mapper.map_entity(*weapon);
}
}
}
/// Represents a weapon entity which may be equipped by a soldier.
#[derive(Bundle)]
struct WeaponBundle {
// Type of weapon determines whether its owner is ranged or melee
kind: WeaponKind,
// Weapons should be saved
save: Save,
}
impl WeaponBundle {
fn new(kind: WeaponKind) -> Self {
Self { kind, save: Save }
}
}
#[derive(Component, Default, Reflect)]
#[reflect(Component)]
enum WeaponKind {
#[default]
Melee,
Ranged,
}
use WeaponKind::*;
#[derive(Component)]
struct Army;
#[derive(Component)]
struct AddMeleeButton;
#[derive(Component)]
struct AddRangedButton;
#[derive(Component)]
struct SaveButton;
#[derive(Component)]
struct LoadButton;
fn setup(mut commands: Commands) {
// Spawn camera
commands.spawn(Camera2d);
// Spawn army text
// Spawn buttons
commands
.spawn(Node {
width: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
padding: UiRect::all(Val::Px(20.)),
..default()
})
.with_children(|root| {
root.spawn((
Node {
margin: UiRect::bottom(Val::Px(20.)),
..default()
},
Text::new(HELP_TEXT),
TextFont {
font_size: 14.0,
..default()
},
TextColor(Color::WHITE),
));
root.spawn((
Army,
Node {
margin: UiRect::bottom(Val::Px(20.)),
..default()
},
Text::new(""),
TextFont {
font_size: 30.0,
..default()
},
TextColor(Color::WHITE),
));
// Buttons Row
root.spawn(Node {
flex_direction: FlexDirection::Row,
..default()
})
.with_children(|parent| {
spawn_button(parent, "SPAWN MELEE", AddMeleeButton);
spawn_button(parent, "SPAWN RANGED", AddRangedButton);
spawn_space(parent, Val::Px(20.), Val::Auto);
spawn_button(parent, "SAVE", SaveButton);
spawn_button(parent, "LOAD", LoadButton);
});
});
}
fn spawn_button(parent: &mut ChildBuilder, value: impl Into<String>, bundle: impl Bundle) {
parent
.spawn((
bundle,
(
Node {
margin: UiRect::all(Val::Px(5.)),
padding: UiRect::new(Val::Px(10.), Val::Px(10.), Val::Px(5.), Val::Px(5.)),
..default()
},
Button,
),
BackgroundColor(bevy::color::palettes::css::DARK_GRAY.into()),
))
.with_children(|fly_button| {
fly_button.spawn((
Node { ..default() },
Text::new(value.into()),
TextFont {
font_size: 20.,
..default()
},
TextColor(Color::WHITE),
));
});
}
fn spawn_space(parent: &mut ChildBuilder, width: Val, height: Val) {
parent.spawn(Node {
width,
height,
..default()
});
}
/// Groups soldiers by the kind of their equipped weapons and displays the results in text.
fn update_text(
soldiers: Query<&SoldierWeapon, With<Soldier>>,
weapon_query: Query<&WeaponKind>,
mut army_query: Query<&mut Text, With<Army>>,
) {
let melee_count = soldiers
.iter()
.filter_map(|SoldierWeapon(entity)| {
entity.and_then(|weapon_entity| weapon_query.get(weapon_entity).ok())
})
.filter(|weapon_kind| matches!(weapon_kind, Melee))
.count();
let ranged_count = soldiers
.iter()
.filter_map(|SoldierWeapon(entity)| {
entity.and_then(|weapon_entity| weapon_query.get(weapon_entity).ok())
})
.filter(|weapon_kind| matches!(weapon_kind, Ranged))
.count();
army_query.single_mut().0 = format!("Soldiers: {melee_count} Melee, {ranged_count} Ranged");
}
const DEFAULT_BUTTON_COLOR: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON_COLOR: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON_COLOR: Color = Color::srgb(0.35, 0.75, 0.35);
/// Handle color feedback for buttons.
fn update_buttons(
mut interaction_query: Query<(&Interaction, &mut BackgroundColor), Changed<Interaction>>,
) {
for (interaction, mut color) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
*color = PRESSED_BUTTON_COLOR.into();
}
Interaction::Hovered => {
*color = HOVERED_BUTTON_COLOR.into();
}
Interaction::None => {
*color = DEFAULT_BUTTON_COLOR.into();
}
}
}
}
fn add_ranged_button_clicked(
query: Query<&Interaction, (With<AddRangedButton>, Changed<Interaction>)>,
mut commands: Commands,
) {
if let Ok(Interaction::Pressed) = query.get_single() {
let weapon = commands.spawn(WeaponBundle::new(Ranged)).id();
commands.spawn(SoldierBundle::new(weapon));
}
}
fn add_melee_button_clicked(
query: Query<&Interaction, (With<AddMeleeButton>, Changed<Interaction>)>,
mut commands: Commands,
) {
if let Ok(Interaction::Pressed) = query.get_single() {
let weapon = commands.spawn(WeaponBundle::new(Melee)).id();
commands.spawn(SoldierBundle::new(weapon));
}
}
fn save_button_clicked(
query: Query<&Interaction, (With<SaveButton>, Changed<Interaction>)>,
mut commands: Commands,
) {
if let Ok(Interaction::Pressed) = query.get_single() {
commands.insert_resource(SaveRequest);
}
}
fn load_button_clicked(
query: Query<&Interaction, (With<LoadButton>, Changed<Interaction>)>,
mut commands: Commands,
) {
if let Ok(Interaction::Pressed) = query.get_single() {
commands.insert_resource(LoadRequest);
}
}
/// A resource which is used to invoke the save system.
#[derive(Resource)]
struct SaveRequest;
impl GetFilePath for SaveRequest {
fn path(&self) -> &Path {
SAVE_PATH.as_ref()
}
}
/// A resource which is used to invoke the load system.
#[derive(Resource)]
struct LoadRequest;
impl GetFilePath for LoadRequest {
fn path(&self) -> &Path {
SAVE_PATH.as_ref()
}
}