tiles_tools 0.2.0

High-performance tile-based game development toolkit with comprehensive coordinate systems (hexagonal, square, triangular, isometric), pathfinding, ECS integration, and grid management.
Documentation
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
#![allow(dead_code)]
#![allow(clippy::needless_return)]
#![allow(clippy::implicit_return)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::items_after_statements)]
#![allow(clippy::unnecessary_cast)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::explicit_iter_loop)]
#![allow(clippy::format_in_format_args)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::wildcard_imports)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::std_instead_of_core)]
#![allow(clippy::similar_names)]
#![allow(clippy::duplicated_attributes)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::trivially_copy_pass_by_ref)]
#![allow(clippy::missing_inline_in_public_items)]
#![allow(clippy::useless_vec)]
#![allow(clippy::unnested_or_patterns)]
#![allow(clippy::else_if_without_else)]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::redundant_else)]
#![allow(clippy::map_unwrap_or)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::struct_field_names)]
//! Stealth Game example demonstrating field-of-view mechanics.
//!
//! This example showcases a stealth-based game using the tiles_tools
//! field-of-view system. Features include:
//!
//! - Guard patrol with line-of-sight detection
//! - Player stealth mechanics and hiding spots
//! - Dynamic lighting from torches and lamps
//! - Shadow-based visibility calculations
//! - Multi-layered security with overlapping vision cones
//! - Noise propagation and detection systems
//!
//! Run with: `cargo run --example stealth_game --features enabled`

#![allow(dead_code)]

use tiles_tools::{
  ecs::{World, Position, Health, Stats, Team, AI, Movable},
  coordinates::{
  Distance,
  square::{Coordinate as SquareCoord, EightConnected},
  },
  field_of_view::{FieldOfView, FOVAlgorithm, LightSource, LightingCalculator},
  pathfind::astar,
};

// =============================================================================
// Game-Specific Components
// =============================================================================

/// Stealth component for sneaking and detection.
#[derive(Debug, Clone, Copy)]
struct Stealth {
  /// Stealth skill level (higher = harder to detect)
  stealth_level: u32,
  /// Current stealth state (hiding, moving, etc.)
  state: StealthState,
  /// Noise level generated by current activity
  noise_level: u32,
  /// Whether currently hidden behind cover
  in_cover: bool,
}

impl Stealth {
  pub fn new(level: u32) -> Self {
  Self {
    stealth_level: level,
    state: StealthState::Hidden,
    noise_level: 1,
    in_cover: false,
  }
  }
  
  pub fn start_moving(&mut self) {
  self.state = StealthState::Moving;
  self.noise_level = if self.in_cover { 2 } else { 4 };
  }
  
  pub fn hide(&mut self) {
  self.state = StealthState::Hidden;
  self.noise_level = 0;
  }
  
  pub fn set_cover(&mut self, in_cover: bool) {
  self.in_cover = in_cover;
  if in_cover {
    self.noise_level = self.noise_level.saturating_sub(2);
  }
  }
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum StealthState {
  Hidden,      // Stationary and trying to avoid detection
  Moving,      // Moving but trying to be stealthy
  Exposed,     // Detected or making noise
  Distracted,  // Investigating something
}

/// Vision component for guards and NPCs.
#[derive(Debug, Clone)]
struct Vision {
  /// Base vision range in normal lighting
  base_range: u32,
  /// Field of view angle in degrees (360 = all directions)
  fov_angle: u32,
  /// Direction the entity is currently facing (0-360 degrees)
  facing_direction: u32,
  /// Detection threshold (lower = more sensitive)
  detection_threshold: u32,
  /// Alert level (0 = unaware, 10 = fully alert)
  alert_level: u32,
}

impl Vision {
  pub fn new(range: u32, angle: u32) -> Self {
  Self {
    base_range: range,
    fov_angle: angle,
    facing_direction: 0,
    detection_threshold: 5,
    alert_level: 0,
  }
  }
  
  pub fn face_direction(&mut self, direction: u32) {
  self.facing_direction = direction % 360;
  }
  
  pub fn increase_alert(&mut self, amount: u32) {
  self.alert_level = (self.alert_level + amount).min(10);
  }
  
  pub fn get_effective_range(&self) -> u32 {
  // Alert guards see farther
  self.base_range + (self.alert_level / 2)
  }
}

/// Patrol route component for guard movement.
#[derive(Debug, Clone)]
struct PatrolRoute {
  /// Waypoints in the patrol route
  waypoints: Vec<SquareCoord<EightConnected>>,
  /// Current waypoint index
  current_waypoint: usize,
  /// Time to wait at each waypoint
  wait_time: u32,
  /// Current wait timer
  current_wait: u32,
  /// Whether to reverse route when reaching end
  reverse_route: bool,
  /// Direction of travel (forward/backward)
  going_forward: bool,
}

impl PatrolRoute {
  pub fn new(waypoints: Vec<SquareCoord<EightConnected>>, wait_time: u32) -> Self {
  Self {
    waypoints,
    current_waypoint: 0,
    wait_time,
    current_wait: 0,
    reverse_route: true,
    going_forward: true,
  }
  }
  
  pub fn get_current_target(&self) -> Option<SquareCoord<EightConnected>> {
  self.waypoints.get(self.current_waypoint).copied()
  }
  
  pub fn advance_waypoint(&mut self) {
  if self.current_wait > 0 {
    self.current_wait = self.current_wait.saturating_sub(1);
    return;
  }
  
  if self.reverse_route {
    if self.going_forward {
      if self.current_waypoint + 1 >= self.waypoints.len() {
        self.going_forward = false;
        if self.current_waypoint > 0 {
          self.current_waypoint -= 1;
        }
      } else {
        self.current_waypoint += 1;
      }
    } else {
      if self.current_waypoint == 0 {
        self.going_forward = true;
        self.current_waypoint = 1;
      } else {
        self.current_waypoint -= 1;
      }
    }
  } else {
    self.current_waypoint = (self.current_waypoint + 1) % self.waypoints.len();
  }
  
  self.current_wait = self.wait_time;
  }
}

// =============================================================================
// Game State Management
// =============================================================================

/// Main stealth game state.
struct StealthGame {
  world: World,
  player_entity: hecs::Entity,
  guard_entities: Vec<hecs::Entity>,
  fov_calculator: FieldOfView,
  lighting_calculator: LightingCalculator<SquareCoord<EightConnected>>,
  level_map: LevelMap,
  turn_counter: u32,
  game_state: GameState,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum GameState {
  Stealth,        // Player is undetected
  Alert,          // Guards are searching
  Detected,       // Player has been spotted
  Victory,        // Player reached objective
  GameOver,       // Player was caught
}

/// Simple level map for obstacle and cover detection.
struct LevelMap {
  width: i32,
  height: i32,
  walls: std::collections::HashSet<SquareCoord<EightConnected>>,
  cover_spots: std::collections::HashSet<SquareCoord<EightConnected>>,
  light_sources: Vec<SquareCoord<EightConnected>>,
  objective: SquareCoord<EightConnected>,
}

impl LevelMap {
  pub fn new(width: i32, height: i32) -> Self {
  let mut map = Self {
    width,
    height,
    walls: std::collections::HashSet::new(),
    cover_spots: std::collections::HashSet::new(),
    light_sources: Vec::new(),
    objective: SquareCoord::<EightConnected>::new(width - 2, height - 2),
  };
  
  // Create a simple level layout
  map.generate_level_layout();
  map
  }
  
  fn generate_level_layout(&mut self) {
  // Create perimeter walls
  for x in 0..self.width {
    self.walls.insert(SquareCoord::<EightConnected>::new(x, 0));
    self.walls.insert(SquareCoord::<EightConnected>::new(x, self.height - 1));
  }
  for y in 0..self.height {
    self.walls.insert(SquareCoord::<EightConnected>::new(0, y));
    self.walls.insert(SquareCoord::<EightConnected>::new(self.width - 1, y));
  }
  
  // Add some interior obstacles
  let obstacles = [
    (5, 3), (5, 4), (5, 5),   // Wall section
    (8, 7), (9, 7), (10, 7),  // Another wall
    (12, 4), (13, 4),         // Small wall
  ];
  
  for &(x, y) in &obstacles {
    if x < self.width && y < self.height {
      self.walls.insert(SquareCoord::<EightConnected>::new(x, y));
    }
  }
  
  // Add cover spots (bushes, crates, etc.)
  let cover_locations = [
    (3, 6), (7, 2), (11, 8), (6, 9), (14, 5)
  ];
  
  for &(x, y) in &cover_locations {
    if x < self.width && y < self.height && !self.walls.contains(&SquareCoord::new(x, y)) {
      self.cover_spots.insert(SquareCoord::<EightConnected>::new(x, y));
    }
  }
  
  // Add light sources (torches)
  self.light_sources = vec![
    SquareCoord::<EightConnected>::new(4, 4),
    SquareCoord::<EightConnected>::new(10, 6),
    SquareCoord::<EightConnected>::new(7, 9),
  ];
  }
  
  pub fn is_wall(&self, coord: &SquareCoord<EightConnected>) -> bool {
  self.walls.contains(coord)
  }
  
  pub fn has_cover(&self, coord: &SquareCoord<EightConnected>) -> bool {
  self.cover_spots.contains(coord)
  }
  
  pub fn blocks_sight(&self, coord: &SquareCoord<EightConnected>) -> bool {
  self.is_wall(coord)
  }
  
  pub fn is_passable(&self, coord: &SquareCoord<EightConnected>) -> bool {
  !self.is_wall(coord) &&
  coord.x >= 0 && coord.x < self.width &&
  coord.y >= 0 && coord.y < self.height
  }
}

impl StealthGame {
  /// Creates a new stealth game.
  pub fn new() -> Self {
  let mut world = World::new();
  let level_map = LevelMap::new(20, 15);
  
  // Create player
  let player_team = Team::new(0);
  let player_entity = world.spawn((
    Position::new(SquareCoord::<EightConnected>::new(2, 2)),
    Health::new(100),
    Stats::new(10, 8, 15, 1), // High speed for stealth
    player_team,
    Movable::new(3),
    Stealth::new(7), // High stealth skill
  ));
  
  // Create guards
  let guard_team = Team::hostile(1);
  let mut guard_entities = Vec::new();
  
  // Guard 1: Patrolling the upper area
  let guard1 = world.spawn((
    Position::new(SquareCoord::<EightConnected>::new(8, 3)),
    Health::new(80),
    Stats::new(12, 10, 8, 1),
    guard_team,
    Movable::new(2),
    AI::new(1.0),
    Vision::new(6, 120), // 120-degree vision cone
    PatrolRoute::new(vec![
      SquareCoord::<EightConnected>::new(8, 3),
      SquareCoord::<EightConnected>::new(12, 3),
      SquareCoord::<EightConnected>::new(12, 6),
      SquareCoord::<EightConnected>::new(8, 6),
    ], 2),
  ));
  guard_entities.push(guard1);
  
  // Guard 2: Stationary guard watching the objective
  let guard2 = world.spawn((
    Position::new(SquareCoord::<EightConnected>::new(16, 11)),
    Health::new(90),
    Stats::new(14, 12, 6, 1),
    guard_team,
    AI::new(1.5),
    Vision::new(8, 180), // Wide field of view
    PatrolRoute::new(vec![
      SquareCoord::<EightConnected>::new(16, 11),
      SquareCoord::<EightConnected>::new(15, 13),
    ], 3),
  ));
  guard_entities.push(guard2);
  
  // Create lighting system
  let mut lighting_calculator = LightingCalculator::new();
  
  // Add torches
  for torch_pos in &level_map.light_sources {
    let torch_light = LightSource::new(torch_pos.clone(), 4, 0.7)
      .with_color(1.0, 0.8, 0.3); // Warm torch light
    lighting_calculator.add_light_source(torch_light);
  }
  
  Self {
    world,
    player_entity,
    guard_entities,
    fov_calculator: FieldOfView::with_algorithm(FOVAlgorithm::Shadowcasting),
    lighting_calculator,
    level_map,
    turn_counter: 0,
    game_state: GameState::Stealth,
  }
  }
  
  /// Processes one turn of the game.
  pub fn process_turn(&mut self) {
  self.turn_counter += 1;
  
  match self.game_state {
    GameState::Stealth => {
      self.process_stealth_turn();
    }
    GameState::Alert => {
      self.process_alert_turn();
    }
    GameState::Detected => {
      self.process_detected_turn();
    }
    _ => {
      // Game over states
      return;
    }
  }
  
  // Check victory condition
  if let Ok(player_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(self.player_entity) {
    if player_pos.coord.distance(&self.level_map.objective) <= 1 {
      self.game_state = GameState::Victory;
    }
  }
  }
  
  /// Processes a turn in stealth mode.
  fn process_stealth_turn(&mut self) {
  // Update guard patrols
  let guard_entities = self.guard_entities.clone();
  for guard in guard_entities {
    self.update_guard_patrol(guard);
  }
  
  // Check for player detection
  if self.check_player_detection() {
    self.game_state = GameState::Alert;
    println!("🚨 Alert! Guards are searching...");
  }
  
  // Simulate player movement (in a real game, this would be input-driven)
  self.simulate_player_movement();
  }
  
  /// Processes a turn in alert mode.
  fn process_alert_turn(&mut self) {
  // Guards move toward last known player position
  if self.check_player_detection() {
    self.game_state = GameState::Detected;
    println!("🎯 Player detected! Game over!");
  }
  
  // Gradually reduce alert level
  if self.turn_counter % 5 == 0 {
    let mut alert_decreased = true;
    for &guard in &self.guard_entities {
      if let Ok(mut vision) = self.world.get_mut::<Vision>(guard) {
        if vision.alert_level > 0 {
          vision.alert_level -= 1;
          alert_decreased = false;
        }
      }
    }
    
    if alert_decreased {
      self.game_state = GameState::Stealth;
      println!("😌 Guards have stopped searching.");
    }
  }
  }
  
  /// Processes a turn when player is detected.
  fn process_detected_turn(&mut self) {
  // Game over - guards converge on player
  self.game_state = GameState::GameOver;
  }
  
  /// Updates a guard's patrol behavior.
  fn update_guard_patrol(&mut self, guard: hecs::Entity) {
  // First get position without any mutable borrows
  let current_pos = {
    if let Ok(pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
      pos.coord
    } else {
      return;
    }
  };
  
  // Then get and modify patrol data
  let target_to_move = {
    if let Ok(mut patrol) = self.world.get_mut::<PatrolRoute>(guard) {
      if let Some(target) = patrol.get_current_target() {
        // Check if we've reached the target
        if current_pos.distance(&target) <= 1 {
          patrol.advance_waypoint();
          None
        } else {
          // Need to move toward target
          Some(target)
        }
      } else {
        return;
      }
    } else {
      return;
    }
  };
  
  if let Some(target) = target_to_move {
    self.move_guard_toward(guard, &target);
  }
  }
  
  /// Moves a guard toward a target position.
  fn move_guard_toward(&mut self, guard: hecs::Entity, target: &SquareCoord<EightConnected>) {
  if let Ok(pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
    if let Ok(movable) = self.world.get::<Movable>(guard) {
      // Use pathfinding to move toward target
      let path_result = astar(
        &pos.coord,
        target,
        |coord| self.level_map.is_passable(coord),
        |_| 1,
      );
      
      if let Some((path, _cost)) = path_result {
        let move_distance = movable.range.min(path.len() as u32 - 1);
        if move_distance > 0 {
          let new_pos = path[move_distance as usize];
          println!("🚶 Guard moving from ({}, {}) to ({}, {})", 
                   pos.coord.x, pos.coord.y, new_pos.x, new_pos.y);
        }
      }
    }
  }
  }
  
  /// Checks if any guard can detect the player.
  fn check_player_detection(&mut self) -> bool {
  let (player_coord, player_stealth_state, player_light_level) = {
    if let Ok(player_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(self.player_entity) {
      if let Ok(player_stealth) = self.world.get::<Stealth>(self.player_entity) {
        
        // Calculate lighting at player position
        let lighting = self.lighting_calculator.calculate_lighting(|coord| {
          self.level_map.blocks_sight(coord)
        });
        
        let player_light_level = lighting.get(&player_pos.coord).unwrap_or(&0.0);
        (player_pos.coord, *player_stealth, *player_light_level)
      } else {
        return false;
      }
    } else {
      return false;
    }
  };
  
  // Check each guard's detection ability
  let guard_entities = self.guard_entities.clone();
  for guard in guard_entities {
    let guard_coord = {
      if let Ok(guard_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
        guard_pos.coord
      } else {
        continue;
      }
    };
    
    if let Ok(mut vision) = self.world.get_mut::<Vision>(guard) {
            
      let distance = guard_coord.distance(&player_coord);
      let effective_range = vision.get_effective_range();
      
      if distance <= effective_range {
        // Check line of sight
        let has_los = self.fov_calculator.line_of_sight(
          &guard_coord,
          &player_coord,
          |coord| self.level_map.blocks_sight(coord)
        );
        
        if has_los {
          // Calculate detection chance
          let base_detection = 10 - player_stealth_state.stealth_level;
          let light_modifier = (player_light_level * 5.0) as u32;
          let distance_modifier = (effective_range - distance) / 2;
          let cover_modifier = if player_stealth_state.in_cover { 0 } else { 3 };
          let noise_modifier = player_stealth_state.noise_level;
          
          let detection_score = base_detection + light_modifier + 
                              distance_modifier + cover_modifier + noise_modifier;
          
          if detection_score >= vision.detection_threshold {
            vision.increase_alert(3);
            if vision.alert_level >= 7 {
              return true; // Player detected!
            }
          }
        }
      }
    }
  }
  false
  }
  
  /// Simulates player movement for demonstration.
  fn simulate_player_movement(&mut self) {
  let (current_pos, objective) = {
    if let Ok(player_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(self.player_entity) {
      (player_pos.coord, self.level_map.objective)
    } else {
      return;
    }
  };
  
  // Find path to objective
  if let Some((path, _cost)) = astar(
    &current_pos,
    &objective,
    |coord| self.level_map.is_passable(coord),
    |_| 1,
  ) {
    if path.len() > 1 {
      let next_pos = path[1];
      
      // Check if it's safe to move there
      if self.is_position_safe_for_player(&next_pos) {
        println!("🚶 Player moving from ({}, {}) to ({}, {})",
                 current_pos.x, current_pos.y, next_pos.x, next_pos.y);
        
        // Update stealth state
        if let Ok(mut stealth) = self.world.get_mut::<Stealth>(self.player_entity) {
          stealth.start_moving();
          stealth.set_cover(self.level_map.has_cover(&next_pos));
        }
      } else {
        // Wait and hide
        if let Ok(mut stealth) = self.world.get_mut::<Stealth>(self.player_entity) {
          stealth.hide();
        }
        println!("🕵️ Player waiting for guards to pass...");
      }
    }
  }
  }
  
  /// Checks if a position is safe for the player to move to.
  fn is_position_safe_for_player(&self, pos: &SquareCoord<EightConnected>) -> bool {
  // Check if any guard can see this position
  for &guard in &self.guard_entities {
    if let Ok(guard_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
      if let Ok(vision) = self.world.get::<Vision>(guard) {
        let distance = guard_pos.coord.distance(pos);
        if distance <= vision.get_effective_range() {
          let has_los = self.fov_calculator.line_of_sight(
            &guard_pos.coord,
            pos,
            |coord| self.level_map.blocks_sight(coord)
          );
          
          if has_los {
            return false; // Position is visible to guard
          }
        }
      }
    }
  }
  true
  }
  
  /// Prints the current game state.
  pub fn print_game_state(&self) {
  println!("\n=== Turn {} ===", self.turn_counter);
  println!("Game State: {:?}", self.game_state);
  
  // Print level with entities
  self.print_level_map();
  
  // Print player status
  if let Ok(player_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(self.player_entity) {
    if let Ok(stealth) = self.world.get::<Stealth>(self.player_entity) {
      println!("🕵️ Player at ({}, {}): {:?}, Noise: {}, Cover: {}", 
               player_pos.coord.x, player_pos.coord.y,
               stealth.state, stealth.noise_level, stealth.in_cover);
    }
  }
  
  // Print guard status
  for (i, &guard) in self.guard_entities.iter().enumerate() {
    if let Ok(guard_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
      if let Ok(vision) = self.world.get::<Vision>(guard) {
        println!("👮 Guard {} at ({}, {}): Alert Level {}/10", 
                 i + 1, guard_pos.coord.x, guard_pos.coord.y, vision.alert_level);
      }
    }
  }
  }
  
  /// Prints the level map with entities and lighting.
  fn print_level_map(&self) {
  let lighting = self.lighting_calculator.calculate_lighting(|coord| {
    self.level_map.blocks_sight(coord)
  });
  
  println!("\n📍 Level Map:");
  println!("🕵️ = Player, 👮 = Guard, 🏆 = Objective, ⬛ = Wall");
  println!("🌿 = Cover, 🕯️ = Torch, ░ = Dark, ▓ = Dim, ▀ = Lit");
  
  for y in 0..self.level_map.height {
    for x in 0..self.level_map.width {
      let coord = SquareCoord::<EightConnected>::new(x, y);
      
      // Check for entities first
      let mut symbol = None;
      
      // Check for player
      if let Ok(player_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(self.player_entity) {
        if player_pos.coord == coord {
          symbol = Some("🕵️");
        }
      }
      
      // Check for guards
      if symbol.is_none() {
        for &guard in &self.guard_entities {
          if let Ok(guard_pos) = self.world.get::<Position<SquareCoord<EightConnected>>>(guard) {
            if guard_pos.coord == coord {
              symbol = Some("👮");
              break;
            }
          }
        }
      }
      
      // Check for objective
      if symbol.is_none() && coord == self.level_map.objective {
        symbol = Some("🏆");
      }
      
      // Check for light sources
      if symbol.is_none() && self.level_map.light_sources.contains(&coord) {
        symbol = Some("🕯️");
      }
      
      // Check for terrain
      if symbol.is_none() {
        if self.level_map.is_wall(&coord) {
          symbol = Some("");
        } else if self.level_map.has_cover(&coord) {
          symbol = Some("🌿");
        } else {
          // Show lighting level
          let light_level = lighting.get(&coord).unwrap_or(&0.0);
          if *light_level >= 0.7 {
            symbol = Some(""); // Bright
          } else if *light_level >= 0.3 {
            symbol = Some(""); // Dim
          } else {
            symbol = Some(""); // Dark
          }
        }
      }
      
      print!("{}", symbol.unwrap_or(" "));
    }
    println!();
  }
  }
  
  /// Runs the complete stealth game simulation.
  pub fn run_simulation(&mut self) {
  println!("🎯 Stealth Game Simulation");
  println!("=========================");
  println!("Objective: Reach the 🏆 without being detected!");
  println!("Use cover (🌿) and darkness to avoid guards (👮)");
  
  self.print_game_state();
  
  // Run game loop
  for turn in 1..=30 {
    self.process_turn();
    self.print_game_state();
    
    match self.game_state {
      GameState::Victory => {
        println!("🏆 VICTORY! You reached the objective undetected!");
        break;
      }
      GameState::GameOver => {
        println!("💀 GAME OVER! You were caught by the guards!");
        break;
      }
      _ => {
        if turn >= 30 {
          println!("⏰ Simulation ended - mission continues...");
          break;
        }
      }
    }
    
    std::thread::sleep(std::time::Duration::from_millis(1500));
  }
  }
}

/// Main entry point for the stealth game demo.
fn main() {
  let mut game = StealthGame::new();
  game.run_simulation();
  
  println!("\n✨ Stealth Game Demo Complete!");
  println!("This example showcases:");
  println!("• Field-of-view calculations for line-of-sight");
  println!("• Multi-source dynamic lighting systems");
  println!("• Stealth mechanics with detection algorithms");
  println!("• Guard AI with patrol routes and alertness");
  println!("• Environmental factors (cover, lighting, noise)");
}