src/selection.rs 23.3 K · 735 lines · raw · history

1 use bevy::{prelude::*, transform::TransformSystems, window::PrimaryWindow};
2
3 use crate::{
4 actions::Action,
5 animals::Animal,
6 building::Blueprints,
7 camera::CameraController,
8 colonist::{Colonist, Path},
9 food::Hunger,
10 items::{Carrying, Item, ItemKind, stock},
11 jobs::{ColonyGoals, CurrentJob, EXPAND_WORK, Job, Order, Task, WorkKind},
12 light::daylight,
13 needs::Rest,
14 sim::{SimSpeed, SimTick, TICKS_PER_HOUR, format_clock, hour_of_day},
15 structures::{Fuel, Structure, StructureKind},
16 ui::{HideableUi, PointerOverUi},
17 world::{TILE_SIZE, TilePos, WorldMap},
18 worldgen::{WorldGenerated, WorldSeed},
19 zones::{ZoneTool, Zones},
20 };
21
22 pub struct SelectionPlugin;
23
24 impl Plugin for SelectionPlugin {
25 fn build(&self, app: &mut App) {
26 app.init_resource::<Cursor>()
27 .init_resource::<Selection>()
28 .add_systems(Startup, spawn_tile_info)
29 .add_systems(Update, clear_selection.run_if(on_message::<WorldGenerated>))
30 .add_systems(
31 PostUpdate,
32 (
33 update_cursor,
34 update_selection.run_if(|tool: Res<ZoneTool>| !tool.active),
35 issue_move_orders,
36 draw_highlights,
37 update_tile_info,
38 )
39 .chain()
40 .after(TransformSystems::Propagate),
41 );
42 }
43 }
44
45 #[derive(Resource, Default, Debug, PartialEq)]
46 pub struct Cursor {
47 pub screen: Option<Vec2>,
48 pub world: Option<Vec2>,
49 pub tile: Option<UVec2>,
50 }
51
52 #[derive(Resource, Default, Debug, PartialEq, Clone, Copy)]
53 pub enum Selection {
54 #[default]
55 None,
56 Tile(UVec2),
57 Colonist(Entity),
58 }
59
60 #[derive(Component)]
61 struct TileInfoText;
62
63 const HOVER_COLOR: Color = Color::srgba(1.0, 1.0, 1.0, 0.6);
64 const SELECT_COLOR: Color = Color::srgb(1.0, 0.85, 0.2);
65 const PROGRESS_COLOR: Color = Color::srgb(0.4, 0.9, 0.4);
66 const PROGRESS_BACK_COLOR: Color = Color::srgba(0.0, 0.0, 0.0, 0.6);
67 const PATH_COLOR: Color = Color::srgba(1.0, 0.85, 0.2, 0.7);
68 const PICK_RADIUS: f32 = TILE_SIZE * 0.6;
69 const CLICK_SLOP_PX: f32 = 4.0;
70
71 pub fn update_cursor(
72 map: Res<WorldMap>,
73 window: Single<&Window, With<PrimaryWindow>>,
74 camera: Single<(&Camera, &GlobalTransform), With<CameraController>>,
75 over_ui: Res<PointerOverUi>,
76 mut cursor: ResMut<Cursor>,
77 ) {
78 let (camera, global) = *camera;
79 let screen = window.cursor_position();
80 let world = screen
81 .filter(|_| !over_ui.0)
82 .and_then(|s| camera.viewport_to_world_2d(global, s).ok());
83 let tile = world.and_then(|w| map.tile_at(w));
84 cursor.set_if_neq(Cursor {
85 screen,
86 world,
87 tile,
88 });
89 }
90
91 fn clear_selection(mut selection: ResMut<Selection>) {
92 *selection = Selection::None;
93 }
94
95 fn update_selection(
96 mut actions: MessageReader<Action>,
97 buttons: Res<ButtonInput<MouseButton>>,
98 over_ui: Res<PointerOverUi>,
99 cursor: Res<Cursor>,
100 colonists: Query<(Entity, &Transform), With<Colonist>>,
101 mut selection: ResMut<Selection>,
102 ) {
103 if actions.read().any(|a| *a == Action::Cancel) {
104 selection.set_if_neq(Selection::None);
105 } else if buttons.just_pressed(MouseButton::Left) && !over_ui.0 {
106 let picked = cursor.world.and_then(|world| {
107 pick_nearest(
108 world,
109 colonists.iter().map(|(e, t)| (e, t.translation.truncate())),
110 )
111 });
112 let new = match (picked, cursor.tile) {
113 (Some(entity), _) => Selection::Colonist(entity),
114 (None, Some(tile)) => Selection::Tile(tile),
115 (None, None) => Selection::None,
116 };
117 selection.set_if_neq(new);
118 }
119 }
120
121 pub fn pick_nearest(
122 point: Vec2,
123 candidates: impl Iterator<Item = (Entity, Vec2)>,
124 ) -> Option<Entity> {
125 candidates
126 .map(|(e, pos)| (e, pos.distance(point)))
127 .filter(|&(_, d)| d <= PICK_RADIUS)
128 .min_by(|a, b| a.1.total_cmp(&b.1))
129 .map(|(e, _)| e)
130 }
131
132 fn issue_move_orders(
133 buttons: Res<ButtonInput<MouseButton>>,
134 cursor: Res<Cursor>,
135 selection: Res<Selection>,
136 over_ui: Res<PointerOverUi>,
137 mut orders: MessageWriter<Order>,
138 mut pressed_at: Local<Option<Vec2>>,
139 ) {
140 if buttons.just_pressed(MouseButton::Right) {
141 *pressed_at = cursor.screen.filter(|_| !over_ui.0);
142 }
143 if !buttons.just_released(MouseButton::Right) {
144 return;
145 }
146 let (Some(press), Some(release)) = (pressed_at.take(), cursor.screen) else {
147 return;
148 };
149 if let (true, Selection::Colonist(colonist), Some(tile)) =
150 (is_click(press, release), *selection, cursor.tile)
151 {
152 orders.write(Order { colonist, tile });
153 }
154 }
155
156 pub fn is_click(press: Vec2, release: Vec2) -> bool {
157 press.distance(release) <= CLICK_SLOP_PX
158 }
159
160 fn draw_highlights(
161 mut gizmos: Gizmos,
162 cursor: Res<Cursor>,
163 selection: Res<Selection>,
164 colonists: Query<(Entity, &Transform, &Path, &CurrentJob), With<Colonist>>,
165 ) {
166 for (_, transform, _, job) in &colonists {
167 if let Some(fraction) = job.0.and_then(|j| progress_fraction(j.task))
168 && fraction > 0.0
169 {
170 let left =
171 transform.translation.truncate() + Vec2::new(-TILE_SIZE * 0.4, TILE_SIZE * 0.6);
172 let full = TILE_SIZE * 0.8;
173 let done = full * fraction;
174 gizmos.line_2d(left, left + Vec2::X * full, PROGRESS_BACK_COLOR);
175 gizmos.line_2d(left, left + Vec2::X * done, PROGRESS_COLOR);
176 }
177 }
178 if let Some(tile) = cursor.tile {
179 gizmos.rect_2d(
180 WorldMap::tile_center(tile),
181 Vec2::splat(TILE_SIZE),
182 HOVER_COLOR,
183 );
184 }
185 match *selection {
186 Selection::None => {}
187 Selection::Tile(tile) => {
188 gizmos.rect_2d(
189 WorldMap::tile_center(tile),
190 Vec2::splat(TILE_SIZE),
191 SELECT_COLOR,
192 );
193 }
194 Selection::Colonist(entity) => {
195 let Ok((_, transform, path, job)) = colonists.get(entity) else {
196 return;
197 };
198 if let Some(Job {
199 task:
200 Task::Work { site, .. }
201 | Task::ExpandStockpile { site, .. }
202 | Task::Build { site, .. },
203 ..
204 }) = job.0
205 {
206 gizmos.rect_2d(
207 WorldMap::tile_center(site),
208 Vec2::splat(TILE_SIZE),
209 PATH_COLOR,
210 );
211 }
212 let pos = transform.translation.truncate();
213 gizmos.circle_2d(pos, TILE_SIZE * 0.5, SELECT_COLOR);
214 let points = path.0.iter().map(|&t| WorldMap::tile_center(t));
215 gizmos.linestrip_2d(std::iter::once(pos).chain(points), PATH_COLOR);
216 }
217 }
218 }
219
220 fn spawn_tile_info(mut commands: Commands) {
221 commands.spawn((
222 TileInfoText,
223 HideableUi,
224 Text::default(),
225 TextFont::from_font_size(14.0),
226 Node {
227 position_type: PositionType::Absolute,
228 top: px(8),
229 left: px(8),
230 padding: UiRect::all(px(6)),
231 ..default()
232 },
233 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.5)),
234 ));
235 }
236
237 fn update_tile_info(
238 map: Res<WorldMap>,
239 cursor: Res<Cursor>,
240 selection: Res<Selection>,
241 colonists: Query<(
242 &Colonist,
243 &TilePos,
244 &Path,
245 &CurrentJob,
246 &Carrying,
247 &Rest,
248 &Hunger,
249 )>,
250 items: Query<(&Item, &TilePos)>,
251 structures: Query<(&Structure, &TilePos, Option<&Fuel>)>,
252 animals: Query<(&Animal, &TilePos)>,
253 blueprints: Res<Blueprints>,
254 goals: Res<ColonyGoals>,
255 zones: Res<Zones>,
256 tool: Res<ZoneTool>,
257 time: Res<Time<Virtual>>,
258 tick: Res<SimTick>,
259 speed: Res<SimSpeed>,
260 seed: Res<WorldSeed>,
261 mut text: Single<&mut Text, With<TileInfoText>>,
262 ) {
263 let selected = match *selection {
264 Selection::None => "-".to_string(),
265 Selection::Tile(tile) => describe_tile(&map, Some(tile)),
266 Selection::Colonist(entity) => colonists
267 .get(entity)
268 .map(|(colonist, tile, path, job, carrying, rest, hunger)| {
269 describe_colonist(&ColonistView {
270 name: &colonist.name,
271 tile: tile.0,
272 job: job.0,
273 steps_left: path.0.len(),
274 carrying: carrying.0,
275 rest: rest.0,
276 fed: hunger.0,
277 })
278 })
279 .unwrap_or_else(|_| "-".into()),
280 };
281 let clock = format!(
282 "{} ({})",
283 format_clock(*tick),
284 time_of_day(hour_of_day(*tick))
285 );
286 let speed = describe_speed(*speed, time.is_paused());
287 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.4.0).collect();
288 let stock_line = |food: bool| {
289 ItemKind::ALL
290 .iter()
291 .filter(|kind| kind.is_food() == food)
292 .map(|&kind| {
293 let have = stock(
294 items.iter().map(|(item, _)| item).chain(carried.iter()),
295 kind,
296 );
297 format!("{kind:?} {have}/{}", goals.goal(kind))
298 })
299 .collect::<Vec<_>>()
300 .join(" ")
301 };
302 let materials = format!("{}\n{}", stock_line(false), stock_line(true));
303 let hovered_zone = match cursor.tile {
304 Some(tile) if zones.is_stockpile(tile) => ", Stockpile",
305 _ => "",
306 };
307 let hovered_items: String = items
308 .iter()
309 .filter(|(_, pos)| Some(pos.0) == cursor.tile)
310 .map(|(item, _)| format!(", {:?} x{}", item.kind, item.count))
311 .collect();
312 let hovered_structure: String = structures
313 .iter()
314 .filter(|(_, pos, _)| Some(pos.0) == cursor.tile)
315 .map(|(structure, _, fuel)| describe_structure(structure.kind, fuel.map(|f| f.0)))
316 .chain(
317 cursor
318 .tile
319 .and_then(|t| blueprints.get(t))
320 .map(|kind| format!(", planned {}", kind.name())),
321 )
322 .chain(
323 animals
324 .iter()
325 .filter(|(_, pos)| Some(pos.0) == cursor.tile)
326 .map(|(animal, _)| format!(", {}", animal.kind.name())),
327 )
328 .collect();
329 let tool_hint = if tool.active {
330 "\nSTOCKPILE TOOL: drag to add, shift-drag to remove"
331 } else {
332 ""
333 };
334 let info = format!(
335 "{clock} {speed}\nSeed: {}\n{materials}{tool_hint}\nHover: {}{hovered_zone}{hovered_items}{hovered_structure}\nSelected: {selected}",
336 seed.0,
337 describe_tile(&map, cursor.tile)
338 );
339 if text.0 != info {
340 text.0 = info;
341 }
342 }
343
344 pub fn describe_tile(map: &WorldMap, tile: Option<UVec2>) -> String {
345 let Some((t, terrain)) = tile.and_then(|t| map.get(t.as_ivec2()).map(|terrain| (t, terrain)))
346 else {
347 return "-".into();
348 };
349 let p = t.as_ivec2();
350 let roof = if map.is_roofed(p) { ", Roofed" } else { "" };
351 let plant = map
352 .plant(p)
353 .map(|plant| match plant.ripening_ticks() {
354 None => format!(", {plant:?}"),
355 Some(_) if plant.is_ripe(map.growth(p)) => format!(", {plant:?} (ripe)"),
356 Some(_) => format!(", {plant:?} ({:.0}% grown)", map.growth(p) * 100.0),
357 })
358 .unwrap_or_default();
359 let height = map.height(p).unwrap_or(0.0);
360 format!("({}, {}) {terrain:?}{plant}{roof}, {height:.0} m", t.x, t.y)
361 }
362
363 pub fn describe_speed(speed: SimSpeed, paused: bool) -> String {
364 if paused {
365 "PAUSED".into()
366 } else {
367 format!("{}x", speed.multiplier())
368 }
369 }
370
371 pub fn time_of_day(hour: f32) -> &'static str {
372 match daylight(hour) {
373 1.0 => "day",
374 0.0 => "night",
375 _ if hour < 12.0 => "dawn",
376 _ => "dusk",
377 }
378 }
379
380 pub fn describe_structure(kind: StructureKind, fuel: Option<u32>) -> String {
381 match fuel {
382 Some(fuel) => {
383 let hours = fuel as f32 / TICKS_PER_HOUR as f32;
384 format!(", {:?} ({hours:.1}h of fuel)", kind)
385 }
386 None => format!(", {kind:?}"),
387 }
388 }
389
390 pub fn progress_fraction(task: Task) -> Option<f32> {
391 match task {
392 Task::Work { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
393 Task::ExpandStockpile { progress, .. } => Some(progress as f32 / EXPAND_WORK as f32),
394 Task::Build { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
395 Task::Hunt { kind, progress, .. } => Some(progress as f32 / kind.hunt_work() as f32),
396 _ => None,
397 }
398 }
399
400 fn percent(task: Task) -> u32 {
401 (progress_fraction(task).unwrap_or(0.0) * 100.0).round() as u32
402 }
403
404 pub struct ColonistView<'a> {
405 pub name: &'a str,
406 pub tile: UVec2,
407 pub job: Option<Job>,
408 pub steps_left: usize,
409 pub carrying: Option<Item>,
410 pub rest: f32,
411 pub fed: f32,
412 }
413
414 pub fn describe_colonist(view: &ColonistView) -> String {
415 let (tile, job, carrying) = (view.tile, view.job, view.carrying);
416 let activity = match (job.map(|j| j.task), view.steps_left) {
417 (None, 0) => "idle".to_string(),
418 (None, _) => "wandering".to_string(),
419 (Some(Task::MoveTo(_)), n) => format!("moving, {n} steps left"),
420 (
421 Some(Task::Work {
422 kind: WorkKind::Chop,
423 ..
424 }),
425 n,
426 ) if n > 0 => "walking to a tree".to_string(),
427 (
428 Some(Task::Work {
429 kind: WorkKind::Mine,
430 ..
431 }),
432 n,
433 ) if n > 0 => "walking to rock".to_string(),
434 (
435 Some(Task::Work {
436 kind: WorkKind::Harvest,
437 ..
438 }),
439 n,
440 ) if n > 0 => "walking to a plant".to_string(),
441 (Some(task @ Task::Work { kind, .. }), _) => {
442 let verb = match kind {
443 WorkKind::Chop => "chopping a tree",
444 WorkKind::Mine => "mining",
445 WorkKind::Harvest => "harvesting",
446 };
447 format!("{verb}, {}%", percent(task))
448 }
449 (Some(Task::ExpandStockpile { .. }), n) if n > 0 => {
450 "going to expand the stockpile".to_string()
451 }
452 (Some(task @ Task::ExpandStockpile { .. }), _) => {
453 format!("expanding the stockpile, {}%", percent(task))
454 }
455 (
456 Some(Task::Haul {
457 pickup: Some(_), ..
458 }),
459 _,
460 ) => "fetching items to haul".to_string(),
461 (Some(Task::Haul { pickup: None, .. }), _) => "hauling to the stockpile".to_string(),
462 (
463 Some(Task::Build {
464 kind,
465 pickup: Some(_),
466 ..
467 }),
468 _,
469 ) => format!("fetching {:?} for a {}", kind.cost().0, kind.name()).to_lowercase(),
470 (Some(Task::Build { kind, .. }), n) if n > 0 => {
471 format!("carrying {:?} to build a {}", kind.cost().0, kind.name()).to_lowercase()
472 }
473 (Some(Task::Sleep { .. }), n) if n > 0 => "going to sleep".to_string(),
474 (Some(Task::Sleep { .. }), _) => "sleeping".to_string(),
475 (
476 Some(Task::Eat {
477 pickup: Some(_), ..
478 }),
479 _,
480 ) => "fetching food".to_string(),
481 (Some(Task::Eat { .. }), _) => "eating".to_string(),
482 (Some(task @ Task::Hunt { kind, progress, .. }), _) if progress > 0 => {
483 format!("hunting a {}, {}%", kind.name(), percent(task))
484 }
485 (Some(Task::Hunt { kind, .. }), _) => format!("stalking a {}", kind.name()),
486 (Some(task @ Task::Build { kind, .. }), _) => {
487 format!("building a {}, {}%", kind.name(), percent(task))
488 }
489 };
490 let load = carrying
491 .map(|item| format!(", carrying {} {:?}", item.count, item.kind))
492 .unwrap_or_default();
493 let ordered = if job.is_some_and(|j| j.ordered) {
494 " (ordered)"
495 } else {
496 ""
497 };
498 format!(
499 "{} at ({}, {}), {activity}{ordered}{load}, rest {:.0}%, food {:.0}%",
500 view.name,
501 tile.x,
502 tile.y,
503 view.rest * 100.0,
504 view.fed * 100.0
505 )
506 }
507
508 #[cfg(test)]
509 mod tests {
510 use super::*;
511 use crate::world::Terrain;
512
513 fn selection_app(cursor: Cursor, selection: Selection) -> App {
514 let mut app = App::new();
515 app.init_resource::<ButtonInput<MouseButton>>()
516 .init_resource::<PointerOverUi>()
517 .insert_resource(cursor)
518 .insert_resource(selection)
519 .add_message::<Order>()
520 .add_message::<Action>()
521 .add_systems(Update, (update_selection, issue_move_orders));
522 app
523 }
524
525 fn cursor_on_tile(tile: UVec2) -> Cursor {
526 Cursor {
527 screen: Some(Vec2::new(50.0, 50.0)),
528 world: Some(WorldMap::tile_center(tile)),
529 tile: Some(tile),
530 }
531 }
532
533 fn press(app: &mut App, button: MouseButton) {
534 app.world_mut()
535 .resource_mut::<ButtonInput<MouseButton>>()
536 .press(button);
537 app.update();
538 }
539
540 fn release(app: &mut App, button: MouseButton) {
541 let mut input = app.world_mut().resource_mut::<ButtonInput<MouseButton>>();
542 input.clear();
543 input.release(button);
544 app.update();
545 }
546
547 fn selection(app: &App) -> Selection {
548 *app.world().resource::<Selection>()
549 }
550
551 fn sent_orders(app: &mut App) -> Vec<(Entity, UVec2)> {
552 app.world_mut()
553 .resource_mut::<Messages<Order>>()
554 .drain()
555 .map(|o| (o.colonist, o.tile))
556 .collect()
557 }
558
559 #[test]
560 fn clicking_selects_the_hovered_tile() {
561 let mut app = selection_app(cursor_on_tile(UVec2::new(3, 4)), Selection::None);
562 press(&mut app, MouseButton::Left);
563 assert_eq!(selection(&app), Selection::Tile(UVec2::new(3, 4)));
564 }
565
566 #[test]
567 fn clicking_a_colonist_selects_it_instead_of_its_tile() {
568 let tile = UVec2::new(3, 4);
569 let mut app = selection_app(cursor_on_tile(tile), Selection::None);
570 let colonist = app
571 .world_mut()
572 .spawn((
573 Colonist { name: "Ada".into() },
574 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
575 ))
576 .id();
577 press(&mut app, MouseButton::Left);
578 assert_eq!(selection(&app), Selection::Colonist(colonist));
579 }
580
581 #[test]
582 fn clicking_outside_the_world_clears_the_selection() {
583 let mut app = selection_app(Cursor::default(), Selection::Tile(UVec2::new(3, 4)));
584 press(&mut app, MouseButton::Left);
585 assert_eq!(selection(&app), Selection::None);
586 }
587
588 #[test]
589 fn cancel_clears_the_selection() {
590 let mut app = selection_app(
591 cursor_on_tile(UVec2::ONE),
592 Selection::Tile(UVec2::new(3, 4)),
593 );
594 app.world_mut().write_message(Action::Cancel);
595 app.update();
596 assert_eq!(selection(&app), Selection::None);
597 }
598
599 #[test]
600 fn clicks_on_the_ui_do_not_reach_the_map() {
601 let colonist = Entity::from_raw_u32(7).unwrap();
602 let mut app = selection_app(
603 cursor_on_tile(UVec2::new(5, 6)),
604 Selection::Colonist(colonist),
605 );
606 app.insert_resource(PointerOverUi(true));
607 press(&mut app, MouseButton::Left);
608 assert_eq!(selection(&app), Selection::Colonist(colonist));
609 press(&mut app, MouseButton::Right);
610 release(&mut app, MouseButton::Right);
611 assert!(sent_orders(&mut app).is_empty());
612 }
613
614 #[test]
615 fn right_click_orders_selected_colonist_to_hovered_tile() {
616 let colonist = Entity::from_raw_u32(7).unwrap();
617 let mut app = selection_app(
618 cursor_on_tile(UVec2::new(5, 6)),
619 Selection::Colonist(colonist),
620 );
621 press(&mut app, MouseButton::Right);
622 release(&mut app, MouseButton::Right);
623 assert_eq!(sent_orders(&mut app), vec![(colonist, UVec2::new(5, 6))]);
624 }
625
626 #[test]
627 fn right_drag_does_not_order_because_it_pans_the_camera() {
628 let colonist = Entity::from_raw_u32(7).unwrap();
629 let mut app = selection_app(
630 cursor_on_tile(UVec2::new(5, 6)),
631 Selection::Colonist(colonist),
632 );
633 press(&mut app, MouseButton::Right);
634 app.world_mut().resource_mut::<Cursor>().screen = Some(Vec2::new(200.0, 50.0));
635 release(&mut app, MouseButton::Right);
636 assert!(sent_orders(&mut app).is_empty());
637 }
638
639 #[test]
640 fn pick_nearest_ignores_far_candidates() {
641 let a = Entity::from_raw_u32(1).unwrap();
642 let b = Entity::from_raw_u32(2).unwrap();
643 let candidates = [(a, Vec2::new(5.0, 0.0)), (b, Vec2::new(2.0, 0.0))];
644 assert_eq!(pick_nearest(Vec2::ZERO, candidates.into_iter()), Some(b));
645 assert_eq!(
646 pick_nearest(Vec2::new(100.0, 0.0), candidates.into_iter()),
647 None
648 );
649 }
650
651 #[test]
652 fn describe_tile_shows_coordinates_terrain_plant_and_height() {
653 let mut map = WorldMap::filled(UVec2::new(4, 4), Terrain::Sand);
654 map.set_height(UVec2::new(1, 2), 12.4);
655 assert_eq!(
656 describe_tile(&map, Some(UVec2::new(1, 2))),
657 "(1, 2) Sand, 12 m"
658 );
659 map.set_plant(UVec2::new(1, 2), Some(crate::world::Plant::Tree));
660 assert_eq!(
661 describe_tile(&map, Some(UVec2::new(1, 2))),
662 "(1, 2) Sand, Tree, 12 m"
663 );
664 assert_eq!(describe_tile(&map, None), "-");
665 }
666
667 #[test]
668 fn time_of_day_labels() {
669 assert_eq!(time_of_day(12.0), "day");
670 assert_eq!(time_of_day(6.0), "dawn");
671 assert_eq!(time_of_day(19.0), "dusk");
672 assert_eq!(time_of_day(1.0), "night");
673 }
674
675 #[test]
676 fn describe_speed_shows_multiplier_or_paused() {
677 assert_eq!(describe_speed(SimSpeed::Fastest, false), "6x");
678 assert_eq!(describe_speed(SimSpeed::Fast, true), "PAUSED");
679 }
680
681 fn view(job: Option<Job>, steps_left: usize, carrying: Option<Item>) -> ColonistView<'static> {
682 ColonistView {
683 name: "Ada",
684 tile: UVec2::new(1, 2),
685 job,
686 steps_left,
687 carrying,
688 rest: 1.0,
689 fed: 0.5,
690 }
691 }
692
693 #[test]
694 fn describe_colonist_shows_activity_and_needs() {
695 assert_eq!(
696 describe_colonist(&view(None, 0, None)),
697 "Ada at (1, 2), idle, rest 100%, food 50%"
698 );
699 let ordered_move = Job {
700 task: Task::MoveTo(UVec2::ZERO),
701 ordered: true,
702 };
703 assert_eq!(
704 describe_colonist(&view(Some(ordered_move), 3, None)),
705 "Ada at (1, 2), moving, 3 steps left (ordered), rest 100%, food 50%"
706 );
707 let chop = Job {
708 task: Task::Work {
709 site: UVec2::ZERO,
710 kind: WorkKind::Chop,
711 progress: WorkKind::Chop.work() / 2,
712 },
713 ordered: false,
714 };
715 assert_eq!(
716 describe_colonist(&view(Some(chop), 0, None)),
717 "Ada at (1, 2), chopping a tree, 50%, rest 100%, food 50%"
718 );
719 let eat = Job {
720 task: Task::Eat {
721 pickup: None,
722 progress: 0,
723 },
724 ordered: false,
725 };
726 let meal = Item {
727 kind: ItemKind::Meal,
728 count: 1,
729 };
730 assert_eq!(
731 describe_colonist(&view(Some(eat), 0, Some(meal))),
732 "Ada at (1, 2), eating, carrying 1 Meal, rest 100%, food 50%"
733 );
734 }
735 }