use std::collections::HashMap;
use crate::{
AmbleWorld, ItemHolder, ItemId, Location, NpcId, View, ViewItem, WorldObject,
entity_search::{self, SearchError, SearchScope, entity_not_found},
health::{LifeState, LivingEntity},
helpers::symbol_or_unknown,
item::Movability,
npc::Npc,
spinners::CoreSpinnerType,
style::GameStyle,
trigger::{Trigger, TriggerAction, TriggerCondition, check_triggers, triggers_contain_condition},
};
use anyhow::{Context, Result, bail};
use log::info;
fn select_npc<'a>(location: &Location, world_npcs: &'a HashMap<NpcId, Npc>, query: &str) -> Option<&'a Npc> {
let npcs_in_room = world_npcs
.values()
.filter(|npc| npc.location() == location)
.collect::<Vec<_>>();
let query = query.to_lowercase();
npcs_in_room
.into_iter()
.find(|&npc| npc.name().to_lowercase().contains(&query))
}
pub fn talk_to_handler(world: &mut AmbleWorld, view: &mut View, npc_name: &str) -> Result<bool> {
let sent_id = if let Some(npc) = select_npc(world.player.location(), &world.npcs, npc_name) {
if matches!(npc.life_state(), LifeState::Dead) {
info!("talking to dead NPC {} disallowed", npc.symbol());
view.push(ViewItem::ActionFailure(format!(
"Sorry - {} is dead and there is no Ouija board in sight.",
npc.name().npc_style()
)));
return Ok(false);
}
npc.id.clone()
} else {
entity_not_found(world, view, npc_name);
return Ok(false);
};
if let Some(npc) = world.npcs.get_mut(&sent_id) {
npc.pause_movement(world.turn_count, 4);
}
let fired_triggers = check_triggers(world, view, &[TriggerCondition::TalkToNpc(sent_id.clone())])?;
let dialogue_fired = triggers_contain_condition(&fired_triggers, |cond| match cond {
TriggerCondition::TalkToNpc(npc_id) => sent_id == *npc_id,
_ => false,
});
if !dialogue_fired
&& let Some(npc) = world.npcs.get(&sent_id)
&& let Some(ignore_spinner) = world
.spinners
.get(&crate::spinners::SpinnerType::Core(CoreSpinnerType::NpcIgnore))
{
let dialogue = npc.random_dialogue(ignore_spinner);
view.push(ViewItem::NpcSpeech {
speaker: npc.name.clone(),
quote: dialogue.clone(),
});
info!("NPC \"{}\" ({}) said \"{}\"", npc.name(), npc.symbol(), dialogue);
}
Ok(true)
}
pub fn give_to_npc_handler(
world: &mut AmbleWorld,
view: &mut View,
item_pattern: &str,
npc_pattern: &str,
) -> Result<bool> {
let room_id = world.player_room_id();
let npc_id = match entity_search::find_npc_match(world, npc_pattern, SearchScope::TouchableNpcs(room_id)) {
Ok(id) => {
if let Some(npc) = world.npcs.get(&id)
&& npc.life_state() == LifeState::Dead
{
info!("gift to dead npc {} disallowed", npc.symbol());
view.push(ViewItem::ActionFailure(format!(
"Sorry -- {} is dead, and cannot accept your gift.",
npc.name().npc_style()
)));
return Ok(false);
}
id
},
Err(SearchError::NoMatchingName(input)) => {
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
if let Some(npc) = world.npcs.get_mut(&npc_id) {
npc.pause_movement(world.turn_count, 4);
}
let item_id = match entity_search::find_item_match(world, item_pattern, SearchScope::Inventory) {
Ok(id) => {
let item = world.items.get(&id).expect("validated in find_item_match()");
if let Movability::Fixed { reason } = &item.movability {
info!("player tried to move fixed item {} ({})", item.name(), item.symbol());
view.push(ViewItem::ActionFailure(format!(
"Sorry, the {} isn't transferrable. {reason}",
item.name().error_style()
)));
return Ok(false);
}
id
},
Err(SearchError::NoMatchingName(input)) => {
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
let fired_triggers = check_triggers(
world,
view,
&[TriggerCondition::GiveToNpc {
item_id: item_id.clone(),
npc_id: npc_id.clone(),
}],
)?;
let gift_response = check_fired_and_refused(&fired_triggers);
if gift_response.trigger_fired && !gift_response.npc_refused {
transfer_if_not_despawned(world, &npc_id, item_id.clone())?;
check_triggers(world, view, &[TriggerCondition::Drop(item_id.clone())])?;
show_npc_acceptance(world, view, npc_id.clone(), item_id.clone())?;
} else if !gift_response.trigger_fired {
show_npc_refusal(world, view, npc_id.clone(), item_id.clone())?;
}
Ok(true)
}
fn show_npc_refusal(world: &AmbleWorld, view: &mut View, npc_id: NpcId, item_id: ItemId) -> Result<()> {
let npc = world
.npcs
.get(&npc_id)
.with_context(|| format!("missing npc id: {npc_id}"))?;
let item = world
.items
.get(&item_id)
.with_context(|| format!("missing item id: {item_id}"))?;
view.push(ViewItem::ActionFailure(format!(
"{} has no use for {}, and won't hold it for you.",
npc.name(),
item.name()
)));
info!(
"{} ({}) refused a gift of {} ({})",
npc.name(),
symbol_or_unknown(&world.npcs, npc_id),
item.name(),
symbol_or_unknown(&world.items, item_id)
);
Ok(())
}
fn show_npc_acceptance(world: &AmbleWorld, view: &mut View, npc_id: NpcId, item_id: ItemId) -> Result<()> {
let npc = world
.npcs
.get(&npc_id)
.with_context(|| format!("missing npc id: {npc_id}"))?;
let item = world
.items
.get(&item_id)
.with_context(|| format!("missing item id: {item_id}"))?;
view.push(ViewItem::ActionSuccess(format!(
"{} accepted the {}.",
npc.name(),
item.name()
)));
info!(
"'{}' ({}) accepted '{}' ({}) from '{}'",
npc.name(),
symbol_or_unknown(&world.npcs, npc_id),
item.name(),
symbol_or_unknown(&world.items, item_id),
world.player.name()
);
Ok(())
}
struct GiftResponse {
trigger_fired: bool,
npc_refused: bool,
}
fn check_fired_and_refused(all_fired: &Vec<&Trigger>) -> GiftResponse {
let trigger_fired = all_fired.iter().any(|&trigger| {
trigger
.conditions
.any_trigger(|cond| matches!(cond, TriggerCondition::GiveToNpc { .. }))
});
let npc_refused = all_fired.iter().any(|t| {
t.actions
.iter()
.any(|a| matches!(&a.action, TriggerAction::NpcRefuseItem { .. }))
});
GiftResponse {
trigger_fired,
npc_refused,
}
}
fn transfer_if_not_despawned(world: &mut AmbleWorld, npc_id: &NpcId, item_id: ItemId) -> Result<()> {
if world
.items
.get(&item_id)
.with_context(|| format!("looking up item {item_id}"))?
.location
.is_not_nowhere()
{
world
.get_item_mut(&item_id)
.with_context(|| format!("looking up item {item_id}"))?
.set_location_npc(npc_id.clone());
world
.npcs
.get_mut(npc_id)
.with_context(|| format!("looking up NPC {npc_id}"))?
.add_item(item_id.clone());
world.player.remove_item(item_id);
}
Ok(())
}