Skip to main content

GameStateMachine

Struct GameStateMachine 

Source
pub struct GameStateMachine { /* private fields */ }
Expand description

Game state machine for managing different phases of gameplay.

Implementations§

Source§

impl GameStateMachine

Source

pub fn new(initial_state: GameState) -> Self

Creates a new game state machine.

Examples found in repository?
examples/game_systems_demo.rs (line 213)
212fn demonstrate_game_state_machine() {
213  let mut state_machine = GameStateMachine::new(GameState::Initialize);
214  
215  println!("Starting game state machine...");
216  println!("Current state: {:?}", state_machine.current_state());
217
218  // Simulate game startup sequence
219  let state_transitions = [
220  (GameStateEvent::InitComplete, "Game initialized"),
221  (GameStateEvent::StartGame, "Starting new game"),
222  (GameStateEvent::StartGame, "Loading complete, entering gameplay"),
223  (GameStateEvent::EnterCombat, "Combat encounter!"),
224  (GameStateEvent::ExitCombat, "Combat resolved"),
225  (GameStateEvent::Pause, "Game paused"),
226  (GameStateEvent::Resume, "Game resumed"),
227  (GameStateEvent::OpenInventory, "Checking inventory"),
228  (GameStateEvent::CloseInventory, "Inventory closed"),
229  ];
230
231  for (event, description) in state_transitions {
232  if state_machine.process_event(event) {
233    println!("  {} → {:?} ({})", 
234      format!("{:?}", event), 
235      state_machine.current_state(), 
236      description);
237  } else {
238    println!("  {} → Failed (invalid transition from {:?})", 
239      format!("{:?}", event),
240      state_machine.current_state());
241  }
242  }
243
244  // Demonstrate state data
245  state_machine.set_state_data("player_name".to_string(), "Hero".to_string());
246  state_machine.set_state_data("level".to_string(), "forest_1".to_string());
247  
248  println!("\nState data:");
249  if let Some(name) = state_machine.get_state_data("player_name") {
250  println!("  Player name: {}", name);
251  }
252  if let Some(level) = state_machine.get_state_data("level") {
253  println!("  Current level: {}", level);
254  }
255
256  println!("Final state: {:?}", state_machine.current_state());
257}
258
259fn demonstrate_resource_management() {
260  let mut resource_manager = ResourceManager::new();
261
262  println!("Setting up entities with resources...");
263
264  // Create different entity types
265  resource_manager.add_entity(1, 100.0, 50.0);  // Player: 100 HP, 50 MP
266  resource_manager.add_entity(2, 80.0, 0.0);    // Warrior: 80 HP, 0 MP
267  resource_manager.add_entity(3, 60.0, 100.0);  // Mage: 60 HP, 100 MP
268  resource_manager.add_entity(4, 150.0, 25.0);  // Boss: 150 HP, 25 MP
269
270  // Configure regeneration
271  if let Some(resources) = resource_manager.get_resources_mut(1) {
272  resources.health.regeneration = 2.0; // Player regenerates 2 HP/sec
273  resources.mana.regeneration = 5.0;   // Player regenerates 5 MP/sec
274  }
275
276  if let Some(resources) = resource_manager.get_resources_mut(3) {
277  resources.mana.regeneration = 3.0;   // Mage regenerates 3 MP/sec
278  }
279
280  println!("\nInitial resources:");
281  for entity_id in [1, 2, 3, 4] {
282  if let Some(resources) = resource_manager.get_resources(entity_id) {
283    let entity_type = match entity_id {
284      1 => "Player",
285      2 => "Warrior", 
286      3 => "Mage",
287      4 => "Boss",
288      _ => "Unknown"
289    };
290    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP", 
291      entity_type,
292      resources.health.current, resources.health.maximum,
293      resources.mana.current, resources.mana.maximum);
294  }
295  }
296
297  println!("\nSimulating combat damage...");
298
299  // Player takes damage
300  resource_manager.modify_health(1, -25.0);
301  resource_manager.modify_mana(1, -15.0);
302  println!("  Player takes 25 damage, uses 15 mana");
303
304  // Warrior takes heavy damage
305  resource_manager.modify_health(2, -60.0);
306  println!("  Warrior takes 60 damage");
307
308  // Mage uses lots of mana
309  resource_manager.modify_mana(3, -80.0);
310  println!("  Mage uses 80 mana for powerful spell");
311
312  // Boss takes some damage
313  resource_manager.modify_health(4, -45.0);
314  println!("  Boss takes 45 damage from combined attacks");
315
316  println!("\nAfter combat:");
317  for entity_id in [1, 2, 3, 4] {
318  if let Some(resources) = resource_manager.get_resources(entity_id) {
319    let entity_type = match entity_id {
320      1 => "Player",
321      2 => "Warrior",
322      3 => "Mage", 
323      4 => "Boss",
324      _ => "Unknown"
325    };
326    println!("  {}: {:.0}/{:.0} HP ({:.0}%), {:.0}/{:.0} MP ({:.0}%)",
327      entity_type,
328      resources.health.current, resources.health.maximum,
329      resources.health.percentage() * 100.0,
330      resources.mana.current, resources.mana.maximum,
331      resources.mana.percentage() * 100.0);
332  }
333  }
334
335  println!("\nSimulating 3 seconds of regeneration...");
336  resource_manager.update_all(3.0);
337
338  println!("After regeneration:");
339  for entity_id in [1, 3] { // Only show entities with regen
340  if let Some(resources) = resource_manager.get_resources(entity_id) {
341    let entity_type = if entity_id == 1 { "Player" } else { "Mage" };
342    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP",
343      entity_type,
344      resources.health.current, resources.health.maximum,
345      resources.mana.current, resources.mana.maximum);
346  }
347  }
348
349  // Check for defeated entities
350  let defeated = resource_manager.get_defeated_entities();
351  if !defeated.is_empty() {
352  println!("\nDefeated entities: {:?}", defeated);
353  } else {
354  println!("\nNo entities defeated");
355  }
356}
357
358fn demonstrate_quest_system() {
359  let mut quest_manager = QuestManager::new();
360
361  println!("Setting up quest system...");
362
363  // Create a main quest
364  let main_quest = Quest {
365  id: "save_village".to_string(),
366  name: "Save the Village".to_string(),
367  description: "The village is under attack by orcs. Eliminate the threat!".to_string(),
368  status: QuestStatus::Available,
369  objectives: vec![
370    QuestObjective {
371      id: "kill_orcs".to_string(),
372      description: "Eliminate 5 orc raiders".to_string(),
373      completed: false,
374      objective_type: ObjectiveType::KillTargets {
375        target_type: "orc".to_string(),
376        count: 5,
377        current: 0,
378      },
379      optional: false,
380    },
381    QuestObjective {
382      id: "find_chief".to_string(),
383      description: "Find and defeat the orc chieftain".to_string(),
384      completed: false,
385      objective_type: ObjectiveType::KillTargets {
386        target_type: "orc_chief".to_string(),
387        count: 1,
388        current: 0,
389      },
390      optional: false,
391    },
392    QuestObjective {
393      id: "rescue_villagers".to_string(),
394      description: "Rescue captured villagers (Optional)".to_string(),
395      completed: false,
396      objective_type: ObjectiveType::Custom {
397        data: vec![("rescued".to_string(), "0".to_string())].into_iter().collect(),
398      },
399      optional: true,
400    },
401  ],
402  prerequisites: vec![],
403  rewards: vec![
404    QuestReward::Experience(500),
405    QuestReward::Currency(100),
406    QuestReward::Items("healing_potion".to_string(), 3),
407  ],
408  data: HashMap::new(),
409  };
410
411  // Create a side quest
412  let side_quest = Quest {
413  id: "gather_herbs".to_string(),
414  name: "Herb Gathering".to_string(),
415  description: "Collect medicinal herbs for the village healer".to_string(),
416  status: QuestStatus::Available,
417  objectives: vec![
418    QuestObjective {
419      id: "collect_herbs".to_string(),
420      description: "Collect 10 healing herbs".to_string(),
421      completed: false,
422      objective_type: ObjectiveType::CollectItems {
423        item_id: "healing_herb".to_string(),
424        count: 10,
425        current: 0,
426      },
427      optional: false,
428    },
429  ],
430  prerequisites: vec![],
431  rewards: vec![
432    QuestReward::Experience(100),
433    QuestReward::Currency(25),
434  ],
435  data: HashMap::new(),
436  };
437
438  quest_manager.add_quest(main_quest);
439  quest_manager.add_quest(side_quest);
440
441  // Start both quests
442  println!("\nStarting quests...");
443  quest_manager.start_quest("save_village", 1);
444  quest_manager.start_quest("gather_herbs", 1);
445
446  println!("Active quests: {}", quest_manager.active_quests().len());
447  for quest in quest_manager.active_quests() {
448  println!("  • {} - {}", quest.name, quest.description);
449  for objective in &quest.objectives {
450    let status = if objective.completed { "✓" } else { "○" };
451    let optional = if objective.optional { " (Optional)" } else { "" };
452    println!("    {} {}{}", status, objective.description, optional);
453  }
454  }
455
456  println!("\nSimulating quest progress...");
457
458  // Progress herb collection
459  quest_manager.update_objective("gather_herbs", "collect_herbs", 4);
460  println!("  Collected 4 herbs...");
461  
462  quest_manager.update_objective("gather_herbs", "collect_herbs", 6);
463  println!("  Collected 6 more herbs (10/10 complete)");
464
465  // Progress orc elimination
466  quest_manager.update_objective("save_village", "kill_orcs", 3);
467  println!("  Defeated 3 orcs...");
468
469  quest_manager.update_objective("save_village", "kill_orcs", 2);
470  println!("  Defeated 2 more orcs (5/5 complete)");
471
472  // Complete chieftain objective
473  quest_manager.update_objective("save_village", "find_chief", 1);
474  println!("  Defeated orc chieftain!");
475
476  println!("\nQuest completion status:");
477  println!("  Completed quests: {}", quest_manager.completed_quest_count());
478  for quest in quest_manager.completed_quests() {
479  println!("    ✓ {} - Completed!", quest.name);
480  println!("      Rewards:");
481  for reward in &quest.rewards {
482    match reward {
483      QuestReward::Experience(exp) => println!("        • {} Experience", exp),
484      QuestReward::Currency(gold) => println!("        • {} Gold", gold),
485      QuestReward::Items(item, count) => println!("        • {} x{}", item, count),
486      QuestReward::UnlockQuest(quest_id) => println!("        • Unlock Quest: {}", quest_id),
487      QuestReward::SetFlag(flag) => println!("        • Set Flag: {}", flag),
488    }
489  }
490  }
491
492  // Demonstrate flags
493  quest_manager.set_flag("village_saved".to_string(), true);
494  quest_manager.set_flag("hero_reputation".to_string(), true);
495  
496  println!("\nGlobal flags set:");
497  println!("  village_saved: {}", quest_manager.get_flag("village_saved"));
498  println!("  hero_reputation: {}", quest_manager.get_flag("hero_reputation"));
499}
500
501fn demonstrate_integrated_gameplay() {
502  println!("Setting up integrated tactical RPG session...");
503
504  // Initialize all systems
505  let mut turn_game = TurnBasedGame::new();
506  let mut resources = ResourceManager::new();
507  let mut state_machine = GameStateMachine::new(GameState::Playing);
508  let mut quest_manager = QuestManager::new();
509  let mut event_bus = EventBus::new();
510
511  // Set up event listeners for system integration
512  event_bus.subscribe(|event: &TurnStartedEvent| {
513  println!("🎯 Turn started for entity {} (Round {})", event.entity_id, event.round_number);
514  EventResult::Continue
515  });
516
517  event_bus.subscribe(|event: &ResourceChangedEvent| {
518  if event.resource_type == "health" && event.new_value <= 0.0 {
519    println!("💀 Entity {} has fallen!", event.entity_id);
520  }
521  EventResult::Continue
522  });
523
524  // Create a tactical scenario
525  println!("\n🗺️ Tactical Battle Setup");
526  println!("Party vs Orc Raiders");
527
528  // Add party members
529  turn_game.add_participant(1, 85);   // Player Fighter
530  turn_game.add_participant(2, 95);   // Player Mage
531  turn_game.add_participant(3, 75);   // Player Cleric
532
533  // Add enemies  
534  turn_game.add_participant(11, 80);  // Orc Warrior 1
535  turn_game.add_participant(12, 70);  // Orc Warrior 2
536  turn_game.add_participant(13, 90);  // Orc Shaman
537
538  // Initialize resources for all participants
539  resources.add_entity(1, 120.0, 30.0);   // Fighter: High HP, Low MP
540  resources.add_entity(2, 70.0, 100.0);   // Mage: Low HP, High MP
541  resources.add_entity(3, 90.0, 80.0);    // Cleric: Medium HP, High MP
542
543  resources.add_entity(11, 85.0, 10.0);   // Orc Warrior 1
544  resources.add_entity(12, 85.0, 10.0);   // Orc Warrior 2  
545  resources.add_entity(13, 65.0, 60.0);   // Orc Shaman
546
547  // Create quest for this battle
548  let battle_quest = Quest {
549  id: "orc_encounter".to_string(),
550  name: "Orc Encounter".to_string(),
551  description: "Defeat the orc raiding party".to_string(),
552  status: QuestStatus::Active,
553  objectives: vec![
554    QuestObjective {
555      id: "defeat_orcs".to_string(),
556      description: "Defeat all orc raiders".to_string(),
557      completed: false,
558      objective_type: ObjectiveType::KillTargets {
559        target_type: "orc".to_string(),
560        count: 3,
561        current: 0,
562      },
563      optional: false,
564    },
565  ],
566  prerequisites: vec![],
567  rewards: vec![QuestReward::Experience(200)],
568  data: HashMap::new(),
569  };
570
571  quest_manager.add_quest(battle_quest);
572
573  // Create a visual representation
574  let mut battle_grid = GridRenderer::new()
575  .with_size(12, 8)
576  .with_style(GridStyle::Square8);
577
578  // Position party members
579  battle_grid.add_colored_marker((2, 6), "F", "Fighter", DebugColor::Green, 10);
580  battle_grid.add_colored_marker((1, 5), "M", "Mage", DebugColor::Blue, 10);
581  battle_grid.add_colored_marker((3, 5), "C", "Cleric", DebugColor::Yellow, 10);
582
583  // Position enemies
584  battle_grid.add_colored_marker((9, 4), "O1", "Orc Warrior", DebugColor::Red, 10);
585  battle_grid.add_colored_marker((10, 6), "O2", "Orc Warrior", DebugColor::Red, 10);
586  battle_grid.add_colored_marker((8, 2), "S", "Orc Shaman", DebugColor::Purple, 10);
587
588  // Add environmental elements
589  battle_grid.add_colored_marker((5, 3), "T", "Tree", DebugColor::Green, 5);
590  battle_grid.add_colored_marker((6, 5), "R", "Rock", DebugColor::Gray, 5);
591
592  println!("\nBattlefield:");
593  println!("{}", battle_grid.render_ascii());
594
595  println!("Combat begins!");
596
597  // Simulate one round of combat
598  let mut actions_this_round = 0;
599  let start_round = turn_game.round_number();
600
601  while turn_game.round_number() == start_round && actions_this_round < 6 {
602  if let Some(current_entity) = turn_game.current_turn() {
603    let entity_name = match current_entity {
604      1 => "Fighter",
605      2 => "Mage", 
606      3 => "Cleric",
607      11 => "Orc Warrior 1",
608      12 => "Orc Warrior 2",
609      13 => "Orc Shaman",
610      _ => "Unknown"
611    };
612
613    // Publish turn started event
614    event_bus.publish(TurnStartedEvent {
615      entity_id: current_entity,
616      round_number: turn_game.round_number(),
617      action_points: turn_game.current_participant().unwrap().action_points,
618    });
619
620    // Simulate actions based on entity type and AI
621    match current_entity {
622      1 => { // Fighter
623        println!("  {} attacks Orc Warrior 1 with sword!", entity_name);
624        resources.modify_health(11, -25.0);
625        turn_game.spend_action_points(2);
626        
627        event_bus.publish(ResourceChangedEvent {
628          entity_id: 11,
629          resource_type: "health".to_string(),
630          old_value: 85.0,
631          new_value: resources.get_resources(11).unwrap().health.current,
632        });
633      },
634      2 => { // Mage
635        println!("  {} casts fireball at Orc Shaman!", entity_name);
636        resources.modify_health(13, -35.0);
637        resources.modify_mana(2, -20.0);
638        turn_game.spend_action_points(3);
639      },
640      3 => { // Cleric  
641        println!("  {} heals Fighter!", entity_name);
642        resources.modify_health(1, 15.0);
643        resources.modify_mana(3, -15.0);
644        turn_game.spend_action_points(2);
645      },
646      11 => { // Orc Warrior 1
647        if resources.get_resources(11).unwrap().health.current > 0.0 {
648          println!("  {} attacks Fighter with axe!", entity_name);
649          resources.modify_health(1, -20.0);
650          turn_game.spend_action_points(2);
651        }
652      },
653      12 => { // Orc Warrior 2
654        println!("  {} charges at Mage!", entity_name);
655        resources.modify_health(2, -18.0);
656        turn_game.spend_action_points(3);
657      },
658      13 => { // Orc Shaman
659        if resources.get_resources(13).unwrap().health.current > 0.0 {
660          println!("  {} casts dark bolt at Cleric!", entity_name);
661          resources.modify_health(3, -15.0);
662          resources.modify_mana(13, -10.0);
663          turn_game.spend_action_points(2);
664        }
665      },
666      _ => {}
667    }
668
669    turn_game.end_turn();
670    actions_this_round += 1;
671  }
672
673  event_bus.process_events();
674  }
675
676  println!("\n📊 End of Round Status:");
677  for entity_id in [1, 2, 3, 11, 12, 13] {
678  if let Some(res) = resources.get_resources(entity_id) {
679    let name = match entity_id {
680      1 => "Fighter",
681      2 => "Mage",
682      3 => "Cleric", 
683      11 => "Orc Warrior 1",
684      12 => "Orc Warrior 2",
685      13 => "Orc Shaman",
686      _ => "Unknown"
687    };
688    
689    let status = if res.health.current <= 0.0 { " [DEFEATED]" } else { "" };
690    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP{}",
691      name, res.health.current, res.health.maximum,
692      res.mana.current, res.mana.maximum, status);
693  }
694  }
695
696  // Check for defeated enemies and update quest progress
697  let mut orcs_defeated = 0;
698  for orc_id in [11, 12, 13] {
699  if let Some(res) = resources.get_resources(orc_id) {
700    if res.health.current <= 0.0 {
701      orcs_defeated += 1;
702    }
703  }
704  }
705
706  if orcs_defeated > 0 {
707  quest_manager.update_objective("orc_encounter", "defeat_orcs", orcs_defeated);
708  println!("\n📜 Quest Progress: {} orcs defeated", orcs_defeated);
709  }
710
711  // Check if battle is won
712  let party_alive = [1, 2, 3].iter().any(|&id| {
713  resources.get_resources(id).unwrap().health.current > 0.0
714  });
715  
716  let enemies_alive = [11, 12, 13].iter().any(|&id| {
717  resources.get_resources(id).unwrap().health.current > 0.0
718  });
719
720  if !enemies_alive && party_alive {
721  println!("\n🎉 Victory! All orcs defeated!");
722  state_machine.process_event(GameStateEvent::VictoryAchieved);
723  
724  if quest_manager.is_quest_completed("orc_encounter") {
725    event_bus.publish(QuestCompletedEvent {
726      quest_id: "orc_encounter".to_string(),
727      rewards: vec![QuestReward::Experience(200)],
728    });
729  }
730  } else if !party_alive {
731  println!("\n💀 Defeat! The party has fallen...");
732  state_machine.process_event(GameStateEvent::PlayerDefeated);
733  } else {
734  println!("\n⚔️ Battle continues! Both sides still fighting.");
735  }
736
737  println!("Final game state: {:?}", state_machine.current_state());
738  
739  event_bus.process_events();
740
741  println!("\n🎯 Integration Summary:");
742  println!("This demonstrated how all systems work together:");
743  println!("• Turn-based combat managed participant order and actions");
744  println!("• Resource system tracked health/mana for all entities");
745  println!("• Quest system monitored combat objectives");
746  println!("• Event system coordinated between systems");
747  println!("• State machine tracked overall game flow");
748  println!("• Debug visualization showed tactical positions");
749}
More examples
Hide additional examples
examples/beginner_tutorial.rs (line 472)
462fn tutorial_step_8_complete_game() {
463    println!("🎯 Step 8: Complete Mini-Game");
464    println!("-----------------------------");
465    println!("Let's put everything together into a working game!");
466    
467    // Game components
468    let mut world = World::new();
469    let mut turn_game = TurnBasedGame::new();
470    let mut resource_manager = ResourceManager::new();
471    let mut event_bus = EventBus::new();
472    let mut state_machine = GameStateMachine::new(GameState::Playing);
473    
474    // Game events
475    #[derive(Debug, Clone)]
476    struct PlayerMoved {
477        from: (i32, i32),
478        to: (i32, i32),
479    }
480    
481    #[derive(Debug, Clone)] 
482    struct EnemyDefeated {
483        enemy_type: String,
484        position: (i32, i32),
485    }
486    
487    #[derive(Debug, Clone)]
488    struct TreasureFound {
489        position: (i32, i32),
490        value: u32,
491    }
492    
493    // Events automatically implement Event trait via blanket impl
494    
495    // Set up event listeners
496    event_bus.subscribe(|event: &PlayerMoved| {
497        println!("📍 Player moved from ({}, {}) to ({}, {})", 
498            event.from.0, event.from.1, event.to.0, event.to.1);
499        EventResult::Continue
500    });
501    
502    event_bus.subscribe(|event: &EnemyDefeated| {
503        println!("💀 {} defeated at ({}, {})!", 
504            event.enemy_type, event.position.0, event.position.1);
505        EventResult::Continue
506    });
507    
508    event_bus.subscribe(|event: &TreasureFound| {
509        println!("💰 Found treasure worth {} gold at ({}, {})!", 
510            event.value, event.position.0, event.position.1);
511        EventResult::Continue
512    });
513    
514    // Create game entities
515    let player = world.spawn((
516        Position::new(SquareCoord::<FourConnected>::new(1, 1)),
517        Health::new(100),
518    ));
519    
520    let goblin = world.spawn((
521        Position::new(SquareCoord::<FourConnected>::new(4, 2)),
522        Health::new(25),
523    ));
524    
525    let _treasure = world.spawn((
526        Position::new(SquareCoord::<FourConnected>::new(6, 3)),
527    ));
528    
529    // Add to game systems
530    turn_game.add_participant(player.id() as u32, 100); // Player goes first
531    turn_game.add_participant(goblin.id() as u32, 80);  // Goblin second
532    
533    resource_manager.add_entity(player.id() as u32, 100.0, 30.0);
534    resource_manager.add_entity(goblin.id() as u32, 25.0, 0.0);
535    
536    println!("🎮 Mini Dungeon Explorer Started!");
537    println!("Player Goal: Defeat the goblin and find the treasure");
538    
539    // Game state tracking
540    let mut player_gold = 0;
541    let mut enemies_defeated = 0;
542    
543    // Simulate simple gameplay
544    println!("\n=== Game Simulation ===");
545    
546    // Player moves towards goblin
547    let player_start = SquareCoord::<FourConnected>::new(1, 1);
548    let goblin_pos = SquareCoord::<FourConnected>::new(4, 2);
549    
550    event_bus.publish(PlayerMoved { 
551        from: (player_start.x, player_start.y), 
552        to: (goblin_pos.x - 1, goblin_pos.y) 
553    });
554    
555    // Combat occurs
556    println!("⚔️ Player attacks goblin!");
557    resource_manager.modify_health(goblin.id() as u32, -25.0); // Defeat goblin
558    
559    event_bus.publish(EnemyDefeated {
560        enemy_type: "Goblin".to_string(),
561        position: (goblin_pos.x, goblin_pos.y),
562    });
563    enemies_defeated += 1;
564    
565    // Player finds treasure
566    let treasure_pos = SquareCoord::<FourConnected>::new(6, 3);
567    event_bus.publish(TreasureFound {
568        position: (treasure_pos.x, treasure_pos.y),
569        value: 100,
570    });
571    player_gold += 100;
572    
573    // Victory condition
574    state_machine.process_event(GameStateEvent::VictoryAchieved);
575    println!("🎉 Victory! Game completed!");
576    
577    event_bus.process_events();
578    
579    // Final game summary
580    println!("\n📋 Game Summary:");
581    println!("   Final State: {:?}", state_machine.current_state());
582    println!("   Player Gold: {}", player_gold);
583    println!("   Enemies Defeated: {}", enemies_defeated);
584    
585    if state_machine.current_state() == GameState::Victory {
586        println!("🏆 Congratulations! You've mastered the basics of tiles_tools!");
587    } else {
588        println!("⏰ Game ended - but you've learned the fundamentals!");
589    }
590    
591    println!("✅ You've built a complete tile-based game using tiles_tools!\n");
592}
Source

pub fn current_state(&self) -> GameState

Gets the current state.

Examples found in repository?
examples/game_systems_demo.rs (line 216)
212fn demonstrate_game_state_machine() {
213  let mut state_machine = GameStateMachine::new(GameState::Initialize);
214  
215  println!("Starting game state machine...");
216  println!("Current state: {:?}", state_machine.current_state());
217
218  // Simulate game startup sequence
219  let state_transitions = [
220  (GameStateEvent::InitComplete, "Game initialized"),
221  (GameStateEvent::StartGame, "Starting new game"),
222  (GameStateEvent::StartGame, "Loading complete, entering gameplay"),
223  (GameStateEvent::EnterCombat, "Combat encounter!"),
224  (GameStateEvent::ExitCombat, "Combat resolved"),
225  (GameStateEvent::Pause, "Game paused"),
226  (GameStateEvent::Resume, "Game resumed"),
227  (GameStateEvent::OpenInventory, "Checking inventory"),
228  (GameStateEvent::CloseInventory, "Inventory closed"),
229  ];
230
231  for (event, description) in state_transitions {
232  if state_machine.process_event(event) {
233    println!("  {} → {:?} ({})", 
234      format!("{:?}", event), 
235      state_machine.current_state(), 
236      description);
237  } else {
238    println!("  {} → Failed (invalid transition from {:?})", 
239      format!("{:?}", event),
240      state_machine.current_state());
241  }
242  }
243
244  // Demonstrate state data
245  state_machine.set_state_data("player_name".to_string(), "Hero".to_string());
246  state_machine.set_state_data("level".to_string(), "forest_1".to_string());
247  
248  println!("\nState data:");
249  if let Some(name) = state_machine.get_state_data("player_name") {
250  println!("  Player name: {}", name);
251  }
252  if let Some(level) = state_machine.get_state_data("level") {
253  println!("  Current level: {}", level);
254  }
255
256  println!("Final state: {:?}", state_machine.current_state());
257}
258
259fn demonstrate_resource_management() {
260  let mut resource_manager = ResourceManager::new();
261
262  println!("Setting up entities with resources...");
263
264  // Create different entity types
265  resource_manager.add_entity(1, 100.0, 50.0);  // Player: 100 HP, 50 MP
266  resource_manager.add_entity(2, 80.0, 0.0);    // Warrior: 80 HP, 0 MP
267  resource_manager.add_entity(3, 60.0, 100.0);  // Mage: 60 HP, 100 MP
268  resource_manager.add_entity(4, 150.0, 25.0);  // Boss: 150 HP, 25 MP
269
270  // Configure regeneration
271  if let Some(resources) = resource_manager.get_resources_mut(1) {
272  resources.health.regeneration = 2.0; // Player regenerates 2 HP/sec
273  resources.mana.regeneration = 5.0;   // Player regenerates 5 MP/sec
274  }
275
276  if let Some(resources) = resource_manager.get_resources_mut(3) {
277  resources.mana.regeneration = 3.0;   // Mage regenerates 3 MP/sec
278  }
279
280  println!("\nInitial resources:");
281  for entity_id in [1, 2, 3, 4] {
282  if let Some(resources) = resource_manager.get_resources(entity_id) {
283    let entity_type = match entity_id {
284      1 => "Player",
285      2 => "Warrior", 
286      3 => "Mage",
287      4 => "Boss",
288      _ => "Unknown"
289    };
290    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP", 
291      entity_type,
292      resources.health.current, resources.health.maximum,
293      resources.mana.current, resources.mana.maximum);
294  }
295  }
296
297  println!("\nSimulating combat damage...");
298
299  // Player takes damage
300  resource_manager.modify_health(1, -25.0);
301  resource_manager.modify_mana(1, -15.0);
302  println!("  Player takes 25 damage, uses 15 mana");
303
304  // Warrior takes heavy damage
305  resource_manager.modify_health(2, -60.0);
306  println!("  Warrior takes 60 damage");
307
308  // Mage uses lots of mana
309  resource_manager.modify_mana(3, -80.0);
310  println!("  Mage uses 80 mana for powerful spell");
311
312  // Boss takes some damage
313  resource_manager.modify_health(4, -45.0);
314  println!("  Boss takes 45 damage from combined attacks");
315
316  println!("\nAfter combat:");
317  for entity_id in [1, 2, 3, 4] {
318  if let Some(resources) = resource_manager.get_resources(entity_id) {
319    let entity_type = match entity_id {
320      1 => "Player",
321      2 => "Warrior",
322      3 => "Mage", 
323      4 => "Boss",
324      _ => "Unknown"
325    };
326    println!("  {}: {:.0}/{:.0} HP ({:.0}%), {:.0}/{:.0} MP ({:.0}%)",
327      entity_type,
328      resources.health.current, resources.health.maximum,
329      resources.health.percentage() * 100.0,
330      resources.mana.current, resources.mana.maximum,
331      resources.mana.percentage() * 100.0);
332  }
333  }
334
335  println!("\nSimulating 3 seconds of regeneration...");
336  resource_manager.update_all(3.0);
337
338  println!("After regeneration:");
339  for entity_id in [1, 3] { // Only show entities with regen
340  if let Some(resources) = resource_manager.get_resources(entity_id) {
341    let entity_type = if entity_id == 1 { "Player" } else { "Mage" };
342    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP",
343      entity_type,
344      resources.health.current, resources.health.maximum,
345      resources.mana.current, resources.mana.maximum);
346  }
347  }
348
349  // Check for defeated entities
350  let defeated = resource_manager.get_defeated_entities();
351  if !defeated.is_empty() {
352  println!("\nDefeated entities: {:?}", defeated);
353  } else {
354  println!("\nNo entities defeated");
355  }
356}
357
358fn demonstrate_quest_system() {
359  let mut quest_manager = QuestManager::new();
360
361  println!("Setting up quest system...");
362
363  // Create a main quest
364  let main_quest = Quest {
365  id: "save_village".to_string(),
366  name: "Save the Village".to_string(),
367  description: "The village is under attack by orcs. Eliminate the threat!".to_string(),
368  status: QuestStatus::Available,
369  objectives: vec![
370    QuestObjective {
371      id: "kill_orcs".to_string(),
372      description: "Eliminate 5 orc raiders".to_string(),
373      completed: false,
374      objective_type: ObjectiveType::KillTargets {
375        target_type: "orc".to_string(),
376        count: 5,
377        current: 0,
378      },
379      optional: false,
380    },
381    QuestObjective {
382      id: "find_chief".to_string(),
383      description: "Find and defeat the orc chieftain".to_string(),
384      completed: false,
385      objective_type: ObjectiveType::KillTargets {
386        target_type: "orc_chief".to_string(),
387        count: 1,
388        current: 0,
389      },
390      optional: false,
391    },
392    QuestObjective {
393      id: "rescue_villagers".to_string(),
394      description: "Rescue captured villagers (Optional)".to_string(),
395      completed: false,
396      objective_type: ObjectiveType::Custom {
397        data: vec![("rescued".to_string(), "0".to_string())].into_iter().collect(),
398      },
399      optional: true,
400    },
401  ],
402  prerequisites: vec![],
403  rewards: vec![
404    QuestReward::Experience(500),
405    QuestReward::Currency(100),
406    QuestReward::Items("healing_potion".to_string(), 3),
407  ],
408  data: HashMap::new(),
409  };
410
411  // Create a side quest
412  let side_quest = Quest {
413  id: "gather_herbs".to_string(),
414  name: "Herb Gathering".to_string(),
415  description: "Collect medicinal herbs for the village healer".to_string(),
416  status: QuestStatus::Available,
417  objectives: vec![
418    QuestObjective {
419      id: "collect_herbs".to_string(),
420      description: "Collect 10 healing herbs".to_string(),
421      completed: false,
422      objective_type: ObjectiveType::CollectItems {
423        item_id: "healing_herb".to_string(),
424        count: 10,
425        current: 0,
426      },
427      optional: false,
428    },
429  ],
430  prerequisites: vec![],
431  rewards: vec![
432    QuestReward::Experience(100),
433    QuestReward::Currency(25),
434  ],
435  data: HashMap::new(),
436  };
437
438  quest_manager.add_quest(main_quest);
439  quest_manager.add_quest(side_quest);
440
441  // Start both quests
442  println!("\nStarting quests...");
443  quest_manager.start_quest("save_village", 1);
444  quest_manager.start_quest("gather_herbs", 1);
445
446  println!("Active quests: {}", quest_manager.active_quests().len());
447  for quest in quest_manager.active_quests() {
448  println!("  • {} - {}", quest.name, quest.description);
449  for objective in &quest.objectives {
450    let status = if objective.completed { "✓" } else { "○" };
451    let optional = if objective.optional { " (Optional)" } else { "" };
452    println!("    {} {}{}", status, objective.description, optional);
453  }
454  }
455
456  println!("\nSimulating quest progress...");
457
458  // Progress herb collection
459  quest_manager.update_objective("gather_herbs", "collect_herbs", 4);
460  println!("  Collected 4 herbs...");
461  
462  quest_manager.update_objective("gather_herbs", "collect_herbs", 6);
463  println!("  Collected 6 more herbs (10/10 complete)");
464
465  // Progress orc elimination
466  quest_manager.update_objective("save_village", "kill_orcs", 3);
467  println!("  Defeated 3 orcs...");
468
469  quest_manager.update_objective("save_village", "kill_orcs", 2);
470  println!("  Defeated 2 more orcs (5/5 complete)");
471
472  // Complete chieftain objective
473  quest_manager.update_objective("save_village", "find_chief", 1);
474  println!("  Defeated orc chieftain!");
475
476  println!("\nQuest completion status:");
477  println!("  Completed quests: {}", quest_manager.completed_quest_count());
478  for quest in quest_manager.completed_quests() {
479  println!("    ✓ {} - Completed!", quest.name);
480  println!("      Rewards:");
481  for reward in &quest.rewards {
482    match reward {
483      QuestReward::Experience(exp) => println!("        • {} Experience", exp),
484      QuestReward::Currency(gold) => println!("        • {} Gold", gold),
485      QuestReward::Items(item, count) => println!("        • {} x{}", item, count),
486      QuestReward::UnlockQuest(quest_id) => println!("        • Unlock Quest: {}", quest_id),
487      QuestReward::SetFlag(flag) => println!("        • Set Flag: {}", flag),
488    }
489  }
490  }
491
492  // Demonstrate flags
493  quest_manager.set_flag("village_saved".to_string(), true);
494  quest_manager.set_flag("hero_reputation".to_string(), true);
495  
496  println!("\nGlobal flags set:");
497  println!("  village_saved: {}", quest_manager.get_flag("village_saved"));
498  println!("  hero_reputation: {}", quest_manager.get_flag("hero_reputation"));
499}
500
501fn demonstrate_integrated_gameplay() {
502  println!("Setting up integrated tactical RPG session...");
503
504  // Initialize all systems
505  let mut turn_game = TurnBasedGame::new();
506  let mut resources = ResourceManager::new();
507  let mut state_machine = GameStateMachine::new(GameState::Playing);
508  let mut quest_manager = QuestManager::new();
509  let mut event_bus = EventBus::new();
510
511  // Set up event listeners for system integration
512  event_bus.subscribe(|event: &TurnStartedEvent| {
513  println!("🎯 Turn started for entity {} (Round {})", event.entity_id, event.round_number);
514  EventResult::Continue
515  });
516
517  event_bus.subscribe(|event: &ResourceChangedEvent| {
518  if event.resource_type == "health" && event.new_value <= 0.0 {
519    println!("💀 Entity {} has fallen!", event.entity_id);
520  }
521  EventResult::Continue
522  });
523
524  // Create a tactical scenario
525  println!("\n🗺️ Tactical Battle Setup");
526  println!("Party vs Orc Raiders");
527
528  // Add party members
529  turn_game.add_participant(1, 85);   // Player Fighter
530  turn_game.add_participant(2, 95);   // Player Mage
531  turn_game.add_participant(3, 75);   // Player Cleric
532
533  // Add enemies  
534  turn_game.add_participant(11, 80);  // Orc Warrior 1
535  turn_game.add_participant(12, 70);  // Orc Warrior 2
536  turn_game.add_participant(13, 90);  // Orc Shaman
537
538  // Initialize resources for all participants
539  resources.add_entity(1, 120.0, 30.0);   // Fighter: High HP, Low MP
540  resources.add_entity(2, 70.0, 100.0);   // Mage: Low HP, High MP
541  resources.add_entity(3, 90.0, 80.0);    // Cleric: Medium HP, High MP
542
543  resources.add_entity(11, 85.0, 10.0);   // Orc Warrior 1
544  resources.add_entity(12, 85.0, 10.0);   // Orc Warrior 2  
545  resources.add_entity(13, 65.0, 60.0);   // Orc Shaman
546
547  // Create quest for this battle
548  let battle_quest = Quest {
549  id: "orc_encounter".to_string(),
550  name: "Orc Encounter".to_string(),
551  description: "Defeat the orc raiding party".to_string(),
552  status: QuestStatus::Active,
553  objectives: vec![
554    QuestObjective {
555      id: "defeat_orcs".to_string(),
556      description: "Defeat all orc raiders".to_string(),
557      completed: false,
558      objective_type: ObjectiveType::KillTargets {
559        target_type: "orc".to_string(),
560        count: 3,
561        current: 0,
562      },
563      optional: false,
564    },
565  ],
566  prerequisites: vec![],
567  rewards: vec![QuestReward::Experience(200)],
568  data: HashMap::new(),
569  };
570
571  quest_manager.add_quest(battle_quest);
572
573  // Create a visual representation
574  let mut battle_grid = GridRenderer::new()
575  .with_size(12, 8)
576  .with_style(GridStyle::Square8);
577
578  // Position party members
579  battle_grid.add_colored_marker((2, 6), "F", "Fighter", DebugColor::Green, 10);
580  battle_grid.add_colored_marker((1, 5), "M", "Mage", DebugColor::Blue, 10);
581  battle_grid.add_colored_marker((3, 5), "C", "Cleric", DebugColor::Yellow, 10);
582
583  // Position enemies
584  battle_grid.add_colored_marker((9, 4), "O1", "Orc Warrior", DebugColor::Red, 10);
585  battle_grid.add_colored_marker((10, 6), "O2", "Orc Warrior", DebugColor::Red, 10);
586  battle_grid.add_colored_marker((8, 2), "S", "Orc Shaman", DebugColor::Purple, 10);
587
588  // Add environmental elements
589  battle_grid.add_colored_marker((5, 3), "T", "Tree", DebugColor::Green, 5);
590  battle_grid.add_colored_marker((6, 5), "R", "Rock", DebugColor::Gray, 5);
591
592  println!("\nBattlefield:");
593  println!("{}", battle_grid.render_ascii());
594
595  println!("Combat begins!");
596
597  // Simulate one round of combat
598  let mut actions_this_round = 0;
599  let start_round = turn_game.round_number();
600
601  while turn_game.round_number() == start_round && actions_this_round < 6 {
602  if let Some(current_entity) = turn_game.current_turn() {
603    let entity_name = match current_entity {
604      1 => "Fighter",
605      2 => "Mage", 
606      3 => "Cleric",
607      11 => "Orc Warrior 1",
608      12 => "Orc Warrior 2",
609      13 => "Orc Shaman",
610      _ => "Unknown"
611    };
612
613    // Publish turn started event
614    event_bus.publish(TurnStartedEvent {
615      entity_id: current_entity,
616      round_number: turn_game.round_number(),
617      action_points: turn_game.current_participant().unwrap().action_points,
618    });
619
620    // Simulate actions based on entity type and AI
621    match current_entity {
622      1 => { // Fighter
623        println!("  {} attacks Orc Warrior 1 with sword!", entity_name);
624        resources.modify_health(11, -25.0);
625        turn_game.spend_action_points(2);
626        
627        event_bus.publish(ResourceChangedEvent {
628          entity_id: 11,
629          resource_type: "health".to_string(),
630          old_value: 85.0,
631          new_value: resources.get_resources(11).unwrap().health.current,
632        });
633      },
634      2 => { // Mage
635        println!("  {} casts fireball at Orc Shaman!", entity_name);
636        resources.modify_health(13, -35.0);
637        resources.modify_mana(2, -20.0);
638        turn_game.spend_action_points(3);
639      },
640      3 => { // Cleric  
641        println!("  {} heals Fighter!", entity_name);
642        resources.modify_health(1, 15.0);
643        resources.modify_mana(3, -15.0);
644        turn_game.spend_action_points(2);
645      },
646      11 => { // Orc Warrior 1
647        if resources.get_resources(11).unwrap().health.current > 0.0 {
648          println!("  {} attacks Fighter with axe!", entity_name);
649          resources.modify_health(1, -20.0);
650          turn_game.spend_action_points(2);
651        }
652      },
653      12 => { // Orc Warrior 2
654        println!("  {} charges at Mage!", entity_name);
655        resources.modify_health(2, -18.0);
656        turn_game.spend_action_points(3);
657      },
658      13 => { // Orc Shaman
659        if resources.get_resources(13).unwrap().health.current > 0.0 {
660          println!("  {} casts dark bolt at Cleric!", entity_name);
661          resources.modify_health(3, -15.0);
662          resources.modify_mana(13, -10.0);
663          turn_game.spend_action_points(2);
664        }
665      },
666      _ => {}
667    }
668
669    turn_game.end_turn();
670    actions_this_round += 1;
671  }
672
673  event_bus.process_events();
674  }
675
676  println!("\n📊 End of Round Status:");
677  for entity_id in [1, 2, 3, 11, 12, 13] {
678  if let Some(res) = resources.get_resources(entity_id) {
679    let name = match entity_id {
680      1 => "Fighter",
681      2 => "Mage",
682      3 => "Cleric", 
683      11 => "Orc Warrior 1",
684      12 => "Orc Warrior 2",
685      13 => "Orc Shaman",
686      _ => "Unknown"
687    };
688    
689    let status = if res.health.current <= 0.0 { " [DEFEATED]" } else { "" };
690    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP{}",
691      name, res.health.current, res.health.maximum,
692      res.mana.current, res.mana.maximum, status);
693  }
694  }
695
696  // Check for defeated enemies and update quest progress
697  let mut orcs_defeated = 0;
698  for orc_id in [11, 12, 13] {
699  if let Some(res) = resources.get_resources(orc_id) {
700    if res.health.current <= 0.0 {
701      orcs_defeated += 1;
702    }
703  }
704  }
705
706  if orcs_defeated > 0 {
707  quest_manager.update_objective("orc_encounter", "defeat_orcs", orcs_defeated);
708  println!("\n📜 Quest Progress: {} orcs defeated", orcs_defeated);
709  }
710
711  // Check if battle is won
712  let party_alive = [1, 2, 3].iter().any(|&id| {
713  resources.get_resources(id).unwrap().health.current > 0.0
714  });
715  
716  let enemies_alive = [11, 12, 13].iter().any(|&id| {
717  resources.get_resources(id).unwrap().health.current > 0.0
718  });
719
720  if !enemies_alive && party_alive {
721  println!("\n🎉 Victory! All orcs defeated!");
722  state_machine.process_event(GameStateEvent::VictoryAchieved);
723  
724  if quest_manager.is_quest_completed("orc_encounter") {
725    event_bus.publish(QuestCompletedEvent {
726      quest_id: "orc_encounter".to_string(),
727      rewards: vec![QuestReward::Experience(200)],
728    });
729  }
730  } else if !party_alive {
731  println!("\n💀 Defeat! The party has fallen...");
732  state_machine.process_event(GameStateEvent::PlayerDefeated);
733  } else {
734  println!("\n⚔️ Battle continues! Both sides still fighting.");
735  }
736
737  println!("Final game state: {:?}", state_machine.current_state());
738  
739  event_bus.process_events();
740
741  println!("\n🎯 Integration Summary:");
742  println!("This demonstrated how all systems work together:");
743  println!("• Turn-based combat managed participant order and actions");
744  println!("• Resource system tracked health/mana for all entities");
745  println!("• Quest system monitored combat objectives");
746  println!("• Event system coordinated between systems");
747  println!("• State machine tracked overall game flow");
748  println!("• Debug visualization showed tactical positions");
749}
More examples
Hide additional examples
examples/beginner_tutorial.rs (line 581)
462fn tutorial_step_8_complete_game() {
463    println!("🎯 Step 8: Complete Mini-Game");
464    println!("-----------------------------");
465    println!("Let's put everything together into a working game!");
466    
467    // Game components
468    let mut world = World::new();
469    let mut turn_game = TurnBasedGame::new();
470    let mut resource_manager = ResourceManager::new();
471    let mut event_bus = EventBus::new();
472    let mut state_machine = GameStateMachine::new(GameState::Playing);
473    
474    // Game events
475    #[derive(Debug, Clone)]
476    struct PlayerMoved {
477        from: (i32, i32),
478        to: (i32, i32),
479    }
480    
481    #[derive(Debug, Clone)] 
482    struct EnemyDefeated {
483        enemy_type: String,
484        position: (i32, i32),
485    }
486    
487    #[derive(Debug, Clone)]
488    struct TreasureFound {
489        position: (i32, i32),
490        value: u32,
491    }
492    
493    // Events automatically implement Event trait via blanket impl
494    
495    // Set up event listeners
496    event_bus.subscribe(|event: &PlayerMoved| {
497        println!("📍 Player moved from ({}, {}) to ({}, {})", 
498            event.from.0, event.from.1, event.to.0, event.to.1);
499        EventResult::Continue
500    });
501    
502    event_bus.subscribe(|event: &EnemyDefeated| {
503        println!("💀 {} defeated at ({}, {})!", 
504            event.enemy_type, event.position.0, event.position.1);
505        EventResult::Continue
506    });
507    
508    event_bus.subscribe(|event: &TreasureFound| {
509        println!("💰 Found treasure worth {} gold at ({}, {})!", 
510            event.value, event.position.0, event.position.1);
511        EventResult::Continue
512    });
513    
514    // Create game entities
515    let player = world.spawn((
516        Position::new(SquareCoord::<FourConnected>::new(1, 1)),
517        Health::new(100),
518    ));
519    
520    let goblin = world.spawn((
521        Position::new(SquareCoord::<FourConnected>::new(4, 2)),
522        Health::new(25),
523    ));
524    
525    let _treasure = world.spawn((
526        Position::new(SquareCoord::<FourConnected>::new(6, 3)),
527    ));
528    
529    // Add to game systems
530    turn_game.add_participant(player.id() as u32, 100); // Player goes first
531    turn_game.add_participant(goblin.id() as u32, 80);  // Goblin second
532    
533    resource_manager.add_entity(player.id() as u32, 100.0, 30.0);
534    resource_manager.add_entity(goblin.id() as u32, 25.0, 0.0);
535    
536    println!("🎮 Mini Dungeon Explorer Started!");
537    println!("Player Goal: Defeat the goblin and find the treasure");
538    
539    // Game state tracking
540    let mut player_gold = 0;
541    let mut enemies_defeated = 0;
542    
543    // Simulate simple gameplay
544    println!("\n=== Game Simulation ===");
545    
546    // Player moves towards goblin
547    let player_start = SquareCoord::<FourConnected>::new(1, 1);
548    let goblin_pos = SquareCoord::<FourConnected>::new(4, 2);
549    
550    event_bus.publish(PlayerMoved { 
551        from: (player_start.x, player_start.y), 
552        to: (goblin_pos.x - 1, goblin_pos.y) 
553    });
554    
555    // Combat occurs
556    println!("⚔️ Player attacks goblin!");
557    resource_manager.modify_health(goblin.id() as u32, -25.0); // Defeat goblin
558    
559    event_bus.publish(EnemyDefeated {
560        enemy_type: "Goblin".to_string(),
561        position: (goblin_pos.x, goblin_pos.y),
562    });
563    enemies_defeated += 1;
564    
565    // Player finds treasure
566    let treasure_pos = SquareCoord::<FourConnected>::new(6, 3);
567    event_bus.publish(TreasureFound {
568        position: (treasure_pos.x, treasure_pos.y),
569        value: 100,
570    });
571    player_gold += 100;
572    
573    // Victory condition
574    state_machine.process_event(GameStateEvent::VictoryAchieved);
575    println!("🎉 Victory! Game completed!");
576    
577    event_bus.process_events();
578    
579    // Final game summary
580    println!("\n📋 Game Summary:");
581    println!("   Final State: {:?}", state_machine.current_state());
582    println!("   Player Gold: {}", player_gold);
583    println!("   Enemies Defeated: {}", enemies_defeated);
584    
585    if state_machine.current_state() == GameState::Victory {
586        println!("🏆 Congratulations! You've mastered the basics of tiles_tools!");
587    } else {
588        println!("⏰ Game ended - but you've learned the fundamentals!");
589    }
590    
591    println!("✅ You've built a complete tile-based game using tiles_tools!\n");
592}
Source

pub fn previous_state(&self) -> Option<GameState>

Gets the previous state.

Source

pub fn add_transition( &mut self, from: GameState, event: GameStateEvent, to: GameState, )

Adds a state transition rule.

Source

pub fn process_event(&mut self, event: GameStateEvent) -> bool

Processes a state event and potentially transitions to a new state.

Examples found in repository?
examples/game_systems_demo.rs (line 232)
212fn demonstrate_game_state_machine() {
213  let mut state_machine = GameStateMachine::new(GameState::Initialize);
214  
215  println!("Starting game state machine...");
216  println!("Current state: {:?}", state_machine.current_state());
217
218  // Simulate game startup sequence
219  let state_transitions = [
220  (GameStateEvent::InitComplete, "Game initialized"),
221  (GameStateEvent::StartGame, "Starting new game"),
222  (GameStateEvent::StartGame, "Loading complete, entering gameplay"),
223  (GameStateEvent::EnterCombat, "Combat encounter!"),
224  (GameStateEvent::ExitCombat, "Combat resolved"),
225  (GameStateEvent::Pause, "Game paused"),
226  (GameStateEvent::Resume, "Game resumed"),
227  (GameStateEvent::OpenInventory, "Checking inventory"),
228  (GameStateEvent::CloseInventory, "Inventory closed"),
229  ];
230
231  for (event, description) in state_transitions {
232  if state_machine.process_event(event) {
233    println!("  {} → {:?} ({})", 
234      format!("{:?}", event), 
235      state_machine.current_state(), 
236      description);
237  } else {
238    println!("  {} → Failed (invalid transition from {:?})", 
239      format!("{:?}", event),
240      state_machine.current_state());
241  }
242  }
243
244  // Demonstrate state data
245  state_machine.set_state_data("player_name".to_string(), "Hero".to_string());
246  state_machine.set_state_data("level".to_string(), "forest_1".to_string());
247  
248  println!("\nState data:");
249  if let Some(name) = state_machine.get_state_data("player_name") {
250  println!("  Player name: {}", name);
251  }
252  if let Some(level) = state_machine.get_state_data("level") {
253  println!("  Current level: {}", level);
254  }
255
256  println!("Final state: {:?}", state_machine.current_state());
257}
258
259fn demonstrate_resource_management() {
260  let mut resource_manager = ResourceManager::new();
261
262  println!("Setting up entities with resources...");
263
264  // Create different entity types
265  resource_manager.add_entity(1, 100.0, 50.0);  // Player: 100 HP, 50 MP
266  resource_manager.add_entity(2, 80.0, 0.0);    // Warrior: 80 HP, 0 MP
267  resource_manager.add_entity(3, 60.0, 100.0);  // Mage: 60 HP, 100 MP
268  resource_manager.add_entity(4, 150.0, 25.0);  // Boss: 150 HP, 25 MP
269
270  // Configure regeneration
271  if let Some(resources) = resource_manager.get_resources_mut(1) {
272  resources.health.regeneration = 2.0; // Player regenerates 2 HP/sec
273  resources.mana.regeneration = 5.0;   // Player regenerates 5 MP/sec
274  }
275
276  if let Some(resources) = resource_manager.get_resources_mut(3) {
277  resources.mana.regeneration = 3.0;   // Mage regenerates 3 MP/sec
278  }
279
280  println!("\nInitial resources:");
281  for entity_id in [1, 2, 3, 4] {
282  if let Some(resources) = resource_manager.get_resources(entity_id) {
283    let entity_type = match entity_id {
284      1 => "Player",
285      2 => "Warrior", 
286      3 => "Mage",
287      4 => "Boss",
288      _ => "Unknown"
289    };
290    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP", 
291      entity_type,
292      resources.health.current, resources.health.maximum,
293      resources.mana.current, resources.mana.maximum);
294  }
295  }
296
297  println!("\nSimulating combat damage...");
298
299  // Player takes damage
300  resource_manager.modify_health(1, -25.0);
301  resource_manager.modify_mana(1, -15.0);
302  println!("  Player takes 25 damage, uses 15 mana");
303
304  // Warrior takes heavy damage
305  resource_manager.modify_health(2, -60.0);
306  println!("  Warrior takes 60 damage");
307
308  // Mage uses lots of mana
309  resource_manager.modify_mana(3, -80.0);
310  println!("  Mage uses 80 mana for powerful spell");
311
312  // Boss takes some damage
313  resource_manager.modify_health(4, -45.0);
314  println!("  Boss takes 45 damage from combined attacks");
315
316  println!("\nAfter combat:");
317  for entity_id in [1, 2, 3, 4] {
318  if let Some(resources) = resource_manager.get_resources(entity_id) {
319    let entity_type = match entity_id {
320      1 => "Player",
321      2 => "Warrior",
322      3 => "Mage", 
323      4 => "Boss",
324      _ => "Unknown"
325    };
326    println!("  {}: {:.0}/{:.0} HP ({:.0}%), {:.0}/{:.0} MP ({:.0}%)",
327      entity_type,
328      resources.health.current, resources.health.maximum,
329      resources.health.percentage() * 100.0,
330      resources.mana.current, resources.mana.maximum,
331      resources.mana.percentage() * 100.0);
332  }
333  }
334
335  println!("\nSimulating 3 seconds of regeneration...");
336  resource_manager.update_all(3.0);
337
338  println!("After regeneration:");
339  for entity_id in [1, 3] { // Only show entities with regen
340  if let Some(resources) = resource_manager.get_resources(entity_id) {
341    let entity_type = if entity_id == 1 { "Player" } else { "Mage" };
342    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP",
343      entity_type,
344      resources.health.current, resources.health.maximum,
345      resources.mana.current, resources.mana.maximum);
346  }
347  }
348
349  // Check for defeated entities
350  let defeated = resource_manager.get_defeated_entities();
351  if !defeated.is_empty() {
352  println!("\nDefeated entities: {:?}", defeated);
353  } else {
354  println!("\nNo entities defeated");
355  }
356}
357
358fn demonstrate_quest_system() {
359  let mut quest_manager = QuestManager::new();
360
361  println!("Setting up quest system...");
362
363  // Create a main quest
364  let main_quest = Quest {
365  id: "save_village".to_string(),
366  name: "Save the Village".to_string(),
367  description: "The village is under attack by orcs. Eliminate the threat!".to_string(),
368  status: QuestStatus::Available,
369  objectives: vec![
370    QuestObjective {
371      id: "kill_orcs".to_string(),
372      description: "Eliminate 5 orc raiders".to_string(),
373      completed: false,
374      objective_type: ObjectiveType::KillTargets {
375        target_type: "orc".to_string(),
376        count: 5,
377        current: 0,
378      },
379      optional: false,
380    },
381    QuestObjective {
382      id: "find_chief".to_string(),
383      description: "Find and defeat the orc chieftain".to_string(),
384      completed: false,
385      objective_type: ObjectiveType::KillTargets {
386        target_type: "orc_chief".to_string(),
387        count: 1,
388        current: 0,
389      },
390      optional: false,
391    },
392    QuestObjective {
393      id: "rescue_villagers".to_string(),
394      description: "Rescue captured villagers (Optional)".to_string(),
395      completed: false,
396      objective_type: ObjectiveType::Custom {
397        data: vec![("rescued".to_string(), "0".to_string())].into_iter().collect(),
398      },
399      optional: true,
400    },
401  ],
402  prerequisites: vec![],
403  rewards: vec![
404    QuestReward::Experience(500),
405    QuestReward::Currency(100),
406    QuestReward::Items("healing_potion".to_string(), 3),
407  ],
408  data: HashMap::new(),
409  };
410
411  // Create a side quest
412  let side_quest = Quest {
413  id: "gather_herbs".to_string(),
414  name: "Herb Gathering".to_string(),
415  description: "Collect medicinal herbs for the village healer".to_string(),
416  status: QuestStatus::Available,
417  objectives: vec![
418    QuestObjective {
419      id: "collect_herbs".to_string(),
420      description: "Collect 10 healing herbs".to_string(),
421      completed: false,
422      objective_type: ObjectiveType::CollectItems {
423        item_id: "healing_herb".to_string(),
424        count: 10,
425        current: 0,
426      },
427      optional: false,
428    },
429  ],
430  prerequisites: vec![],
431  rewards: vec![
432    QuestReward::Experience(100),
433    QuestReward::Currency(25),
434  ],
435  data: HashMap::new(),
436  };
437
438  quest_manager.add_quest(main_quest);
439  quest_manager.add_quest(side_quest);
440
441  // Start both quests
442  println!("\nStarting quests...");
443  quest_manager.start_quest("save_village", 1);
444  quest_manager.start_quest("gather_herbs", 1);
445
446  println!("Active quests: {}", quest_manager.active_quests().len());
447  for quest in quest_manager.active_quests() {
448  println!("  • {} - {}", quest.name, quest.description);
449  for objective in &quest.objectives {
450    let status = if objective.completed { "✓" } else { "○" };
451    let optional = if objective.optional { " (Optional)" } else { "" };
452    println!("    {} {}{}", status, objective.description, optional);
453  }
454  }
455
456  println!("\nSimulating quest progress...");
457
458  // Progress herb collection
459  quest_manager.update_objective("gather_herbs", "collect_herbs", 4);
460  println!("  Collected 4 herbs...");
461  
462  quest_manager.update_objective("gather_herbs", "collect_herbs", 6);
463  println!("  Collected 6 more herbs (10/10 complete)");
464
465  // Progress orc elimination
466  quest_manager.update_objective("save_village", "kill_orcs", 3);
467  println!("  Defeated 3 orcs...");
468
469  quest_manager.update_objective("save_village", "kill_orcs", 2);
470  println!("  Defeated 2 more orcs (5/5 complete)");
471
472  // Complete chieftain objective
473  quest_manager.update_objective("save_village", "find_chief", 1);
474  println!("  Defeated orc chieftain!");
475
476  println!("\nQuest completion status:");
477  println!("  Completed quests: {}", quest_manager.completed_quest_count());
478  for quest in quest_manager.completed_quests() {
479  println!("    ✓ {} - Completed!", quest.name);
480  println!("      Rewards:");
481  for reward in &quest.rewards {
482    match reward {
483      QuestReward::Experience(exp) => println!("        • {} Experience", exp),
484      QuestReward::Currency(gold) => println!("        • {} Gold", gold),
485      QuestReward::Items(item, count) => println!("        • {} x{}", item, count),
486      QuestReward::UnlockQuest(quest_id) => println!("        • Unlock Quest: {}", quest_id),
487      QuestReward::SetFlag(flag) => println!("        • Set Flag: {}", flag),
488    }
489  }
490  }
491
492  // Demonstrate flags
493  quest_manager.set_flag("village_saved".to_string(), true);
494  quest_manager.set_flag("hero_reputation".to_string(), true);
495  
496  println!("\nGlobal flags set:");
497  println!("  village_saved: {}", quest_manager.get_flag("village_saved"));
498  println!("  hero_reputation: {}", quest_manager.get_flag("hero_reputation"));
499}
500
501fn demonstrate_integrated_gameplay() {
502  println!("Setting up integrated tactical RPG session...");
503
504  // Initialize all systems
505  let mut turn_game = TurnBasedGame::new();
506  let mut resources = ResourceManager::new();
507  let mut state_machine = GameStateMachine::new(GameState::Playing);
508  let mut quest_manager = QuestManager::new();
509  let mut event_bus = EventBus::new();
510
511  // Set up event listeners for system integration
512  event_bus.subscribe(|event: &TurnStartedEvent| {
513  println!("🎯 Turn started for entity {} (Round {})", event.entity_id, event.round_number);
514  EventResult::Continue
515  });
516
517  event_bus.subscribe(|event: &ResourceChangedEvent| {
518  if event.resource_type == "health" && event.new_value <= 0.0 {
519    println!("💀 Entity {} has fallen!", event.entity_id);
520  }
521  EventResult::Continue
522  });
523
524  // Create a tactical scenario
525  println!("\n🗺️ Tactical Battle Setup");
526  println!("Party vs Orc Raiders");
527
528  // Add party members
529  turn_game.add_participant(1, 85);   // Player Fighter
530  turn_game.add_participant(2, 95);   // Player Mage
531  turn_game.add_participant(3, 75);   // Player Cleric
532
533  // Add enemies  
534  turn_game.add_participant(11, 80);  // Orc Warrior 1
535  turn_game.add_participant(12, 70);  // Orc Warrior 2
536  turn_game.add_participant(13, 90);  // Orc Shaman
537
538  // Initialize resources for all participants
539  resources.add_entity(1, 120.0, 30.0);   // Fighter: High HP, Low MP
540  resources.add_entity(2, 70.0, 100.0);   // Mage: Low HP, High MP
541  resources.add_entity(3, 90.0, 80.0);    // Cleric: Medium HP, High MP
542
543  resources.add_entity(11, 85.0, 10.0);   // Orc Warrior 1
544  resources.add_entity(12, 85.0, 10.0);   // Orc Warrior 2  
545  resources.add_entity(13, 65.0, 60.0);   // Orc Shaman
546
547  // Create quest for this battle
548  let battle_quest = Quest {
549  id: "orc_encounter".to_string(),
550  name: "Orc Encounter".to_string(),
551  description: "Defeat the orc raiding party".to_string(),
552  status: QuestStatus::Active,
553  objectives: vec![
554    QuestObjective {
555      id: "defeat_orcs".to_string(),
556      description: "Defeat all orc raiders".to_string(),
557      completed: false,
558      objective_type: ObjectiveType::KillTargets {
559        target_type: "orc".to_string(),
560        count: 3,
561        current: 0,
562      },
563      optional: false,
564    },
565  ],
566  prerequisites: vec![],
567  rewards: vec![QuestReward::Experience(200)],
568  data: HashMap::new(),
569  };
570
571  quest_manager.add_quest(battle_quest);
572
573  // Create a visual representation
574  let mut battle_grid = GridRenderer::new()
575  .with_size(12, 8)
576  .with_style(GridStyle::Square8);
577
578  // Position party members
579  battle_grid.add_colored_marker((2, 6), "F", "Fighter", DebugColor::Green, 10);
580  battle_grid.add_colored_marker((1, 5), "M", "Mage", DebugColor::Blue, 10);
581  battle_grid.add_colored_marker((3, 5), "C", "Cleric", DebugColor::Yellow, 10);
582
583  // Position enemies
584  battle_grid.add_colored_marker((9, 4), "O1", "Orc Warrior", DebugColor::Red, 10);
585  battle_grid.add_colored_marker((10, 6), "O2", "Orc Warrior", DebugColor::Red, 10);
586  battle_grid.add_colored_marker((8, 2), "S", "Orc Shaman", DebugColor::Purple, 10);
587
588  // Add environmental elements
589  battle_grid.add_colored_marker((5, 3), "T", "Tree", DebugColor::Green, 5);
590  battle_grid.add_colored_marker((6, 5), "R", "Rock", DebugColor::Gray, 5);
591
592  println!("\nBattlefield:");
593  println!("{}", battle_grid.render_ascii());
594
595  println!("Combat begins!");
596
597  // Simulate one round of combat
598  let mut actions_this_round = 0;
599  let start_round = turn_game.round_number();
600
601  while turn_game.round_number() == start_round && actions_this_round < 6 {
602  if let Some(current_entity) = turn_game.current_turn() {
603    let entity_name = match current_entity {
604      1 => "Fighter",
605      2 => "Mage", 
606      3 => "Cleric",
607      11 => "Orc Warrior 1",
608      12 => "Orc Warrior 2",
609      13 => "Orc Shaman",
610      _ => "Unknown"
611    };
612
613    // Publish turn started event
614    event_bus.publish(TurnStartedEvent {
615      entity_id: current_entity,
616      round_number: turn_game.round_number(),
617      action_points: turn_game.current_participant().unwrap().action_points,
618    });
619
620    // Simulate actions based on entity type and AI
621    match current_entity {
622      1 => { // Fighter
623        println!("  {} attacks Orc Warrior 1 with sword!", entity_name);
624        resources.modify_health(11, -25.0);
625        turn_game.spend_action_points(2);
626        
627        event_bus.publish(ResourceChangedEvent {
628          entity_id: 11,
629          resource_type: "health".to_string(),
630          old_value: 85.0,
631          new_value: resources.get_resources(11).unwrap().health.current,
632        });
633      },
634      2 => { // Mage
635        println!("  {} casts fireball at Orc Shaman!", entity_name);
636        resources.modify_health(13, -35.0);
637        resources.modify_mana(2, -20.0);
638        turn_game.spend_action_points(3);
639      },
640      3 => { // Cleric  
641        println!("  {} heals Fighter!", entity_name);
642        resources.modify_health(1, 15.0);
643        resources.modify_mana(3, -15.0);
644        turn_game.spend_action_points(2);
645      },
646      11 => { // Orc Warrior 1
647        if resources.get_resources(11).unwrap().health.current > 0.0 {
648          println!("  {} attacks Fighter with axe!", entity_name);
649          resources.modify_health(1, -20.0);
650          turn_game.spend_action_points(2);
651        }
652      },
653      12 => { // Orc Warrior 2
654        println!("  {} charges at Mage!", entity_name);
655        resources.modify_health(2, -18.0);
656        turn_game.spend_action_points(3);
657      },
658      13 => { // Orc Shaman
659        if resources.get_resources(13).unwrap().health.current > 0.0 {
660          println!("  {} casts dark bolt at Cleric!", entity_name);
661          resources.modify_health(3, -15.0);
662          resources.modify_mana(13, -10.0);
663          turn_game.spend_action_points(2);
664        }
665      },
666      _ => {}
667    }
668
669    turn_game.end_turn();
670    actions_this_round += 1;
671  }
672
673  event_bus.process_events();
674  }
675
676  println!("\n📊 End of Round Status:");
677  for entity_id in [1, 2, 3, 11, 12, 13] {
678  if let Some(res) = resources.get_resources(entity_id) {
679    let name = match entity_id {
680      1 => "Fighter",
681      2 => "Mage",
682      3 => "Cleric", 
683      11 => "Orc Warrior 1",
684      12 => "Orc Warrior 2",
685      13 => "Orc Shaman",
686      _ => "Unknown"
687    };
688    
689    let status = if res.health.current <= 0.0 { " [DEFEATED]" } else { "" };
690    println!("  {}: {:.0}/{:.0} HP, {:.0}/{:.0} MP{}",
691      name, res.health.current, res.health.maximum,
692      res.mana.current, res.mana.maximum, status);
693  }
694  }
695
696  // Check for defeated enemies and update quest progress
697  let mut orcs_defeated = 0;
698  for orc_id in [11, 12, 13] {
699  if let Some(res) = resources.get_resources(orc_id) {
700    if res.health.current <= 0.0 {
701      orcs_defeated += 1;
702    }
703  }
704  }
705
706  if orcs_defeated > 0 {
707  quest_manager.update_objective("orc_encounter", "defeat_orcs", orcs_defeated);
708  println!("\n📜 Quest Progress: {} orcs defeated", orcs_defeated);
709  }
710
711  // Check if battle is won
712  let party_alive = [1, 2, 3].iter().any(|&id| {
713  resources.get_resources(id).unwrap().health.current > 0.0
714  });
715  
716  let enemies_alive = [11, 12, 13].iter().any(|&id| {
717  resources.get_resources(id).unwrap().health.current > 0.0
718  });
719
720  if !enemies_alive && party_alive {
721  println!("\n🎉 Victory! All orcs defeated!");
722  state_machine.process_event(GameStateEvent::VictoryAchieved);
723  
724  if quest_manager.is_quest_completed("orc_encounter") {
725    event_bus.publish(QuestCompletedEvent {
726      quest_id: "orc_encounter".to_string(),
727      rewards: vec![QuestReward::Experience(200)],
728    });
729  }
730  } else if !party_alive {
731  println!("\n💀 Defeat! The party has fallen...");
732  state_machine.process_event(GameStateEvent::PlayerDefeated);
733  } else {
734  println!("\n⚔️ Battle continues! Both sides still fighting.");
735  }
736
737  println!("Final game state: {:?}", state_machine.current_state());
738  
739  event_bus.process_events();
740
741  println!("\n🎯 Integration Summary:");
742  println!("This demonstrated how all systems work together:");
743  println!("• Turn-based combat managed participant order and actions");
744  println!("• Resource system tracked health/mana for all entities");
745  println!("• Quest system monitored combat objectives");
746  println!("• Event system coordinated between systems");
747  println!("• State machine tracked overall game flow");
748  println!("• Debug visualization showed tactical positions");
749}
More examples
Hide additional examples
examples/beginner_tutorial.rs (line 574)
462fn tutorial_step_8_complete_game() {
463    println!("🎯 Step 8: Complete Mini-Game");
464    println!("-----------------------------");
465    println!("Let's put everything together into a working game!");
466    
467    // Game components
468    let mut world = World::new();
469    let mut turn_game = TurnBasedGame::new();
470    let mut resource_manager = ResourceManager::new();
471    let mut event_bus = EventBus::new();
472    let mut state_machine = GameStateMachine::new(GameState::Playing);
473    
474    // Game events
475    #[derive(Debug, Clone)]
476    struct PlayerMoved {
477        from: (i32, i32),
478        to: (i32, i32),
479    }
480    
481    #[derive(Debug, Clone)] 
482    struct EnemyDefeated {
483        enemy_type: String,
484        position: (i32, i32),
485    }
486    
487    #[derive(Debug, Clone)]
488    struct TreasureFound {
489        position: (i32, i32),
490        value: u32,
491    }
492    
493    // Events automatically implement Event trait via blanket impl
494    
495    // Set up event listeners
496    event_bus.subscribe(|event: &PlayerMoved| {
497        println!("📍 Player moved from ({}, {}) to ({}, {})", 
498            event.from.0, event.from.1, event.to.0, event.to.1);
499        EventResult::Continue
500    });
501    
502    event_bus.subscribe(|event: &EnemyDefeated| {
503        println!("💀 {} defeated at ({}, {})!", 
504            event.enemy_type, event.position.0, event.position.1);
505        EventResult::Continue
506    });
507    
508    event_bus.subscribe(|event: &TreasureFound| {
509        println!("💰 Found treasure worth {} gold at ({}, {})!", 
510            event.value, event.position.0, event.position.1);
511        EventResult::Continue
512    });
513    
514    // Create game entities
515    let player = world.spawn((
516        Position::new(SquareCoord::<FourConnected>::new(1, 1)),
517        Health::new(100),
518    ));
519    
520    let goblin = world.spawn((
521        Position::new(SquareCoord::<FourConnected>::new(4, 2)),
522        Health::new(25),
523    ));
524    
525    let _treasure = world.spawn((
526        Position::new(SquareCoord::<FourConnected>::new(6, 3)),
527    ));
528    
529    // Add to game systems
530    turn_game.add_participant(player.id() as u32, 100); // Player goes first
531    turn_game.add_participant(goblin.id() as u32, 80);  // Goblin second
532    
533    resource_manager.add_entity(player.id() as u32, 100.0, 30.0);
534    resource_manager.add_entity(goblin.id() as u32, 25.0, 0.0);
535    
536    println!("🎮 Mini Dungeon Explorer Started!");
537    println!("Player Goal: Defeat the goblin and find the treasure");
538    
539    // Game state tracking
540    let mut player_gold = 0;
541    let mut enemies_defeated = 0;
542    
543    // Simulate simple gameplay
544    println!("\n=== Game Simulation ===");
545    
546    // Player moves towards goblin
547    let player_start = SquareCoord::<FourConnected>::new(1, 1);
548    let goblin_pos = SquareCoord::<FourConnected>::new(4, 2);
549    
550    event_bus.publish(PlayerMoved { 
551        from: (player_start.x, player_start.y), 
552        to: (goblin_pos.x - 1, goblin_pos.y) 
553    });
554    
555    // Combat occurs
556    println!("⚔️ Player attacks goblin!");
557    resource_manager.modify_health(goblin.id() as u32, -25.0); // Defeat goblin
558    
559    event_bus.publish(EnemyDefeated {
560        enemy_type: "Goblin".to_string(),
561        position: (goblin_pos.x, goblin_pos.y),
562    });
563    enemies_defeated += 1;
564    
565    // Player finds treasure
566    let treasure_pos = SquareCoord::<FourConnected>::new(6, 3);
567    event_bus.publish(TreasureFound {
568        position: (treasure_pos.x, treasure_pos.y),
569        value: 100,
570    });
571    player_gold += 100;
572    
573    // Victory condition
574    state_machine.process_event(GameStateEvent::VictoryAchieved);
575    println!("🎉 Victory! Game completed!");
576    
577    event_bus.process_events();
578    
579    // Final game summary
580    println!("\n📋 Game Summary:");
581    println!("   Final State: {:?}", state_machine.current_state());
582    println!("   Player Gold: {}", player_gold);
583    println!("   Enemies Defeated: {}", enemies_defeated);
584    
585    if state_machine.current_state() == GameState::Victory {
586        println!("🏆 Congratulations! You've mastered the basics of tiles_tools!");
587    } else {
588        println!("⏰ Game ended - but you've learned the fundamentals!");
589    }
590    
591    println!("✅ You've built a complete tile-based game using tiles_tools!\n");
592}
Source

pub fn transition_to(&mut self, new_state: GameState)

Forces a transition to a specific state.

Source

pub fn set_state_data(&mut self, key: String, value: String)

Sets data associated with the current state.

Examples found in repository?
examples/game_systems_demo.rs (line 245)
212fn demonstrate_game_state_machine() {
213  let mut state_machine = GameStateMachine::new(GameState::Initialize);
214  
215  println!("Starting game state machine...");
216  println!("Current state: {:?}", state_machine.current_state());
217
218  // Simulate game startup sequence
219  let state_transitions = [
220  (GameStateEvent::InitComplete, "Game initialized"),
221  (GameStateEvent::StartGame, "Starting new game"),
222  (GameStateEvent::StartGame, "Loading complete, entering gameplay"),
223  (GameStateEvent::EnterCombat, "Combat encounter!"),
224  (GameStateEvent::ExitCombat, "Combat resolved"),
225  (GameStateEvent::Pause, "Game paused"),
226  (GameStateEvent::Resume, "Game resumed"),
227  (GameStateEvent::OpenInventory, "Checking inventory"),
228  (GameStateEvent::CloseInventory, "Inventory closed"),
229  ];
230
231  for (event, description) in state_transitions {
232  if state_machine.process_event(event) {
233    println!("  {} → {:?} ({})", 
234      format!("{:?}", event), 
235      state_machine.current_state(), 
236      description);
237  } else {
238    println!("  {} → Failed (invalid transition from {:?})", 
239      format!("{:?}", event),
240      state_machine.current_state());
241  }
242  }
243
244  // Demonstrate state data
245  state_machine.set_state_data("player_name".to_string(), "Hero".to_string());
246  state_machine.set_state_data("level".to_string(), "forest_1".to_string());
247  
248  println!("\nState data:");
249  if let Some(name) = state_machine.get_state_data("player_name") {
250  println!("  Player name: {}", name);
251  }
252  if let Some(level) = state_machine.get_state_data("level") {
253  println!("  Current level: {}", level);
254  }
255
256  println!("Final state: {:?}", state_machine.current_state());
257}
Source

pub fn get_state_data(&self, key: &str) -> Option<&String>

Gets data associated with the current state.

Examples found in repository?
examples/game_systems_demo.rs (line 249)
212fn demonstrate_game_state_machine() {
213  let mut state_machine = GameStateMachine::new(GameState::Initialize);
214  
215  println!("Starting game state machine...");
216  println!("Current state: {:?}", state_machine.current_state());
217
218  // Simulate game startup sequence
219  let state_transitions = [
220  (GameStateEvent::InitComplete, "Game initialized"),
221  (GameStateEvent::StartGame, "Starting new game"),
222  (GameStateEvent::StartGame, "Loading complete, entering gameplay"),
223  (GameStateEvent::EnterCombat, "Combat encounter!"),
224  (GameStateEvent::ExitCombat, "Combat resolved"),
225  (GameStateEvent::Pause, "Game paused"),
226  (GameStateEvent::Resume, "Game resumed"),
227  (GameStateEvent::OpenInventory, "Checking inventory"),
228  (GameStateEvent::CloseInventory, "Inventory closed"),
229  ];
230
231  for (event, description) in state_transitions {
232  if state_machine.process_event(event) {
233    println!("  {} → {:?} ({})", 
234      format!("{:?}", event), 
235      state_machine.current_state(), 
236      description);
237  } else {
238    println!("  {} → Failed (invalid transition from {:?})", 
239      format!("{:?}", event),
240      state_machine.current_state());
241  }
242  }
243
244  // Demonstrate state data
245  state_machine.set_state_data("player_name".to_string(), "Hero".to_string());
246  state_machine.set_state_data("level".to_string(), "forest_1".to_string());
247  
248  println!("\nState data:");
249  if let Some(name) = state_machine.get_state_data("player_name") {
250  println!("  Player name: {}", name);
251  }
252  if let Some(level) = state_machine.get_state_data("level") {
253  println!("  Current level: {}", level);
254  }
255
256  println!("Final state: {:?}", state_machine.current_state());
257}
Source

pub fn can_transition(&self, event: GameStateEvent) -> bool

Checks if the machine can transition on the given event.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T, All> From1<(T,)> for All
where All: From1<T>,

Source§

fn from1(arg: (T,)) -> All

Constructor with a single arguments.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<All, F> Into1<F> for All
where F: From1<All>,

Source§

fn to(self) -> F

Converts this type into the (usually inferred) input type.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoResult<T> for T

Source§

impl<T> ToRef<T> for T
where T: ?Sized,

Source§

fn to_ref(&self) -> &T

Converts the implementing type to an immutable reference. Read more
Source§

impl<T> ToValue<T> for T

Source§

fn to_value(self) -> T

Obtains the value from the implementing type. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.