use crate::{
AmbleWorld, Item, ItemHolder, ItemId, Location, NpcId, View, ViewItem, WorldObject,
entity_search::{
EntityId, SearchError, SearchScope, WorldEntity, entity_not_found, find_entity_match, find_item_match,
},
helpers::{name_from_id, symbol_or_unknown},
item::{ItemAbility, ItemInteractionType, Movability},
spinners::CoreSpinnerType,
style::GameStyle,
trigger::{TriggerCondition, check_triggers},
};
use anyhow::{Result, anyhow, bail};
use colored::Colorize;
use log::{error, info, warn};
pub fn drop_handler(world: &mut AmbleWorld, view: &mut View, thing: &str) -> Result<bool> {
let room_id = world.player_room_id();
let item_id = match find_item_match(world, thing, SearchScope::Inventory) {
Ok(item_id) => item_id,
Err(SearchError::NoMatchingName(input)) => {
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
let item = world.items.get_mut(&item_id).expect("item_id already validated");
if matches!(item.movability, Movability::Free) {
if let Some(dropped) = world.items.get_mut(&item_id) {
dropped.set_location_room(room_id.clone());
dropped.visibility = crate::item::ItemVisibility::Listed;
if let Some(room) = world.rooms.get_mut(&room_id) {
room.add_item(dropped.id.clone());
info!(
"{} dropped {} ({}) in {} ({})",
world.player.name(),
dropped.name(),
dropped.symbol(),
room.name(),
room.symbol()
);
}
world.player.remove_item(item_id.clone());
view.push(ViewItem::ActionSuccess(format!(
"You dropped the {}.",
dropped.name().item_style()
)));
check_triggers(world, view, &[TriggerCondition::Drop(item_id.clone())])?;
}
} else {
let reason = match &item.movability {
Movability::Fixed { reason } | Movability::Restricted { reason } => reason,
Movability::Free => "",
};
view.push(ViewItem::ActionFailure(format!(
"You can't drop the {}. {reason}",
item.name().item_style()
)));
return Ok(true);
}
Ok(true)
}
pub fn take_handler(world: &mut AmbleWorld, view: &mut View, thing: &str) -> Result<bool> {
let take_verb = world.spin_core(CoreSpinnerType::TakeVerb, "take");
let room_id = world.player_room_id();
let entity_id = match find_entity_match(world, thing, SearchScope::AllTouchable(room_id.clone())) {
Ok(id) => id,
Err(SearchError::NoMatchingName(input)) => {
if let Some(room) = world.rooms.get(&room_id)
&& let Some(entry) = room.find_scenery(&input)
{
view.push(ViewItem::ActionFailure(format!(
"You can't {take_verb} the {}. It's part of the scenery.",
entry.name.error_style()
)));
info!(
"{} tried to take scenery \"{}\" in room {}",
world.player.name(),
entry.name,
room.symbol()
);
return Ok(false);
}
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
let consumed_turn = match entity_id {
EntityId::Item(item_id) => {
let item = world.items.get(&item_id).expect("known OK from entity match");
if let Some(ability) = item.requires_capability_for(ItemInteractionType::Handle) {
report_handling_requirement(view, item, &ability);
return Ok(true);
}
if matches!(item.movability, Movability::Free) {
let loot_id = item.id.clone();
let orig_loc = item.location.clone();
if let Some(moved_item) = world.items.get_mut(&loot_id) {
moved_item.set_location_inventory();
world.player.add_item(moved_item.id.clone());
view.push(ViewItem::ActionSuccess(format!(
"You {take_verb} the {}.",
moved_item.name().item_style()
)));
info!("player took the {} ({})", moved_item.name(), moved_item.symbol());
}
match orig_loc {
Location::Item(container_id) => {
if let Some(container) = world.items.get_mut(&container_id) {
container.remove_item(loot_id.clone());
check_triggers(
world,
view,
&[
TriggerCondition::Take(loot_id.clone()),
TriggerCondition::TakeFromItem { loot_id, container_id },
],
)?;
} else {
bail!("container ({container_id}) not found during Take({loot_id})");
}
},
Location::Room(room_id) => {
if let Some(room) = world.rooms.get_mut(&room_id) {
room.remove_item(loot_id.clone());
check_triggers(world, view, &[TriggerCondition::Take(loot_id)])?;
} else {
bail!("room ({room_id}) not found during Take({loot_id})");
}
},
_ => {
warn!("'take' matched an item at {orig_loc:?}: shouldn't be in scope");
},
}
} else {
report_immovable_item(world, view, &take_verb, item);
}
true
},
EntityId::Npc(npc_id) => {
let npc = world.npcs.get(&npc_id).expect("known ok from entity match");
view.push(ViewItem::ActionFailure(format!(
"You can't {take_verb} {}. That would be kidnapping!",
npc.name().npc_style()
)));
info!(
"{} tried to take {} ({})",
world.player.name(),
npc.name(),
npc.symbol()
);
false
},
};
Ok(consumed_turn)
}
fn report_immovable_item(world: &AmbleWorld, view: &mut View, take_verb: &str, item: &Item) {
let reason = match &item.movability {
Movability::Fixed { reason } | Movability::Restricted { reason } => reason,
Movability::Free => "",
};
view.push(ViewItem::ActionFailure(format!(
"You can't {take_verb} the {}. {}",
item.name().error_style(),
reason.italic()
)));
info!(
"{} denied ({reason}) item {} ({})",
world.player.name(),
item.name(),
item.symbol()
);
}
fn report_handling_requirement(view: &mut View, item: &Item, ability: &ItemAbility) {
view.push(ViewItem::ActionFailure(format!(
"{}",
format!(
"You can't take the {} without using something to {} it.",
item.name().item_style(),
ability.to_string().bold()
)
.denied_style()
)));
info!(
"Blocked attempt to take {} ({}) without item that can \"{ability}\"",
item.name(),
item.symbol()
);
}
#[derive(Debug, Copy, Clone, Default)]
pub enum VesselType {
#[default]
Item,
Npc,
}
pub fn take_from_handler(
world: &mut AmbleWorld,
view: &mut View,
item_pattern: &str,
vessel_pattern: &str,
) -> Result<bool> {
let current_room = world.player_room_id();
let vessel_id = match find_entity_match(world, vessel_pattern, SearchScope::NearbyVessels(current_room)) {
Ok(id) => id,
Err(SearchError::NoMatchingName(input)) => {
view.push(ViewItem::ActionFailure(format!(
"You don't see a \"{}\" here that you can loot.",
input.error_style()
)));
return Ok(false);
},
Err(e) => bail!(e),
};
match vessel_id {
EntityId::Item(vessel_uuid) => {
if let Some(vessel) = world.items.get(&vessel_uuid)
&& let Some(reason) = vessel.access_denied_reason()
{
view.push(ViewItem::ActionFailure(format!(
"{reason} You can't take anything from it."
)));
return Ok(false);
}
validate_and_transfer_from_item(world, view, item_pattern, &vessel_uuid)?;
},
EntityId::Npc(npc_id) => {
validate_and_transfer_from_npc(world, view, item_pattern, &npc_id)?;
},
}
Ok(true)
}
#[derive(Debug, Clone, Default)]
pub(crate) struct TransferData {
vessel_type: VesselType,
vessel_id: String,
vessel_name: String,
loot_id: ItemId,
loot_name: String,
}
pub(crate) fn validate_and_transfer_from_npc(
world: &mut AmbleWorld,
view: &mut View,
item_pattern: &str,
npc_id: &NpcId,
) -> Result<(), anyhow::Error> {
let mut tx_data = TransferData {
vessel_id: npc_id.to_string(),
vessel_type: VesselType::Npc,
..Default::default()
};
let npc = world
.npcs
.get(npc_id)
.ok_or(anyhow!("container {npc_id} lookup failed"))?;
tx_data.vessel_name = npc.name.clone();
match find_item_match(world, item_pattern, SearchScope::NpcInventory(npc_id.clone())) {
Ok(loot_id) => {
tx_data.loot_id.clone_from(&loot_id);
let loot = world.items.get(&loot_id).expect("loot_id already validated");
tx_data.loot_name = loot.name.clone();
if let Some(reason) = loot.take_denied_reason() {
view.push(ViewItem::ActionFailure(reason.clone()));
return Ok(());
}
},
Err(SearchError::NoMatchingName(input)) => {
view.push(ViewItem::ActionFailure(format!(
"{} has no \"{}\" for you to take.",
tx_data.vessel_name.npc_style(),
input.error_style()
)));
return Ok(());
},
Err(e) => bail!(e),
}
transfer_to_player(world, view, &tx_data);
check_triggers(
world,
view,
&[
TriggerCondition::Take(tx_data.loot_id.clone()),
TriggerCondition::TakeFromNpc {
item_id: tx_data.loot_id.clone(),
npc_id: npc_id.clone(),
},
],
)?;
Ok(())
}
pub(crate) fn validate_and_transfer_from_item(
world: &mut AmbleWorld,
view: &mut View,
item_pattern: &str,
vessel_id: &ItemId,
) -> Result<(), anyhow::Error> {
let mut tx_data = TransferData {
vessel_type: VesselType::Item,
vessel_id: vessel_id.to_string(),
vessel_name: name_from_id(&world.items, vessel_id)
.expect("vessel validated by (take_from()) caller")
.to_owned(),
..Default::default()
};
match find_item_match(world, item_pattern, SearchScope::ItemContents(vessel_id.clone())) {
Ok(id) => {
tx_data.loot_id.clone_from(&id);
tx_data.loot_name = world.items.get(&id).expect("id must be present").name().to_owned();
},
Err(SearchError::NoMatchingName(input)) => {
view.push(ViewItem::ActionFailure(format!(
"You don't see any \"{}\" in the {} to take.",
input.error_style(),
tx_data.vessel_name.item_style()
)));
return Ok(());
},
Err(e) => bail!(e),
}
if let Some(loot) = world.items.get(&tx_data.loot_id)
&& let Some(reason) = loot.take_denied_reason()
{
view.push(ViewItem::ActionFailure(reason));
return Ok(());
}
transfer_to_player(world, view, &tx_data);
check_triggers(
world,
view,
&[
TriggerCondition::Take(tx_data.loot_id.clone()),
TriggerCondition::TakeFromItem {
loot_id: tx_data.loot_id.clone(),
container_id: vessel_id.clone(),
},
],
)?;
Ok(())
}
pub(crate) fn transfer_to_player(world: &mut AmbleWorld, view: &mut View, tx_data: &TransferData) {
if let Some(moving_item) = world.get_item_mut(&tx_data.loot_id) {
moving_item.set_location_inventory();
}
match tx_data.vessel_type {
VesselType::Item => {
if let Some(vessel) = world.items.get_mut(tx_data.vessel_id.as_str()) {
vessel.remove_item(tx_data.loot_id.clone());
}
},
VesselType::Npc => {
if let Some(vessel) = world.npcs.get_mut(&tx_data.vessel_id) {
vessel.pause_movement(world.turn_count, 4);
vessel.remove_item(tx_data.loot_id.clone());
}
},
}
world.player.add_item(tx_data.loot_id.clone());
let take_verb = world.spin_core(CoreSpinnerType::TakeVerb, "take");
view.push(ViewItem::ActionSuccess(format!(
"You {take_verb} the {}.",
tx_data.loot_name.item_style()
)));
info!(
"player took {} ({}) from {} ({})",
tx_data.loot_name, tx_data.loot_id, tx_data.vessel_name, tx_data.vessel_id
);
}
pub fn put_in_handler(world: &mut AmbleWorld, view: &mut View, item: &str, container: &str) -> Result<bool> {
let (item_id, item_name) = match find_item_match(world, item, SearchScope::Inventory) {
Ok(item_id) => {
let item = world.items.get(&item_id).expect("id known valid here");
if let Some(reason) = item.take_denied_reason() {
view.push(ViewItem::ActionFailure(reason));
return Ok(true);
}
let name = name_from_id(&world.items, &item_id)
.expect("item_id must be valid")
.to_owned();
(item_id, name)
},
Err(SearchError::NoMatchingName(input)) => {
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
let room_id = world.player_room_id();
let (vessel_id, vessel_name) = match find_item_match(world, container, SearchScope::NearbyVessels(room_id)) {
Ok(vessel_id) => {
let vessel = world.items.get(&vessel_id).expect("vessel_id must be valid");
if let Some(reason) = vessel.access_denied_reason() {
view.push(ViewItem::ActionFailure(format!(
"{reason} You can't put anything in it."
)));
return Ok(true);
}
let name = name_from_id(&world.items, &vessel_id)
.expect("vessel_id must be valid")
.to_owned();
(vessel_id, name)
},
Err(SearchError::NoMatchingName(input)) => {
entity_not_found(world, view, input.as_str());
return Ok(false);
},
Err(e) => bail!(e),
};
if let Some(moved_item) = world.items.get_mut(&item_id) {
moved_item.set_location_item(vessel_id.clone());
}
if let Some(vessel) = world.items.get_mut(&vessel_id) {
vessel.add_item(item_id.clone());
}
world.player.inventory.remove(&item_id);
view.push(ViewItem::ActionSuccess(format!(
"You put the {} in the {}.",
item_name.item_style(),
vessel_name.item_style()
)));
info!(
"{} put {} ({}) into {} ({})",
world.player.name(),
item_name,
symbol_or_unknown(&world.items, &item_id),
vessel_name,
symbol_or_unknown(&world.items, &vessel_id)
);
check_triggers(
world,
view,
&[
TriggerCondition::Insert {
item: item_id.clone(),
container: vessel_id.clone(),
},
TriggerCondition::Drop(item_id.clone()),
],
)?;
Ok(true)
}
pub fn unexpected_entity(entity: WorldEntity, view: &mut View, denial_msg: &str) {
let (entity_name, entity_sym, entity_loc) = match entity {
WorldEntity::Item(item) => (item.name(), item.symbol(), item.location()),
WorldEntity::Npc(npc) => (npc.name(), npc.symbol(), npc.location()),
};
view.push(ViewItem::Error(denial_msg.to_string()));
error!("entity '{entity_name}' ({entity_sym}) found in unexpected location {entity_loc:?}");
}
#[cfg(test)]
mod tests {
use super::*;
use crate::RoomId;
use crate::{
ItemHolder,
health::HealthState,
item::{ContainerState, Item},
npc::{Npc, NpcState},
room::Room,
};
use std::collections::{HashMap, HashSet};
struct TestWorld {
world: AmbleWorld,
view: View,
room_id: RoomId,
inv_item_id: ItemId,
room_item_id: ItemId,
chest_id: ItemId,
gem_id: ItemId,
npc_id: NpcId,
npc_item_id: ItemId,
restr_chest_item_id: ItemId,
restr_npc_item_id: ItemId,
}
#[allow(clippy::too_many_lines)]
fn build_world() -> TestWorld {
let mut world = AmbleWorld::new_empty();
let room_id = crate::idgen::new_room_id();
let room = Room {
id: room_id.clone(),
symbol: "room".into(),
name: "Test Room".into(),
base_description: String::new(),
overlays: vec![],
scenery: Vec::new(),
scenery_default: None,
location: Location::Nowhere,
visited: false,
exits: HashMap::new(),
contents: HashSet::new(),
npcs: HashSet::new(),
};
world.rooms.insert(room_id.clone(), room);
world.player.location = Location::Room(room_id.clone());
let inv_item_id: ItemId = crate::idgen::new_id().into();
let inv_item = Item {
id: inv_item_id.clone(),
symbol: "apple".into(),
name: "Apple".into(),
description: String::new(),
location: Location::Inventory,
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
world.items.insert(inv_item_id.clone(), inv_item);
world.player.inventory.insert(inv_item_id.clone());
let room_item_id: ItemId = crate::idgen::new_id().into();
let room_item = Item {
id: room_item_id.clone(),
symbol: "rock".into(),
name: "Rock".into(),
description: String::new(),
location: Location::Room(room_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
world.items.insert(room_item_id.clone(), room_item);
world.rooms.get_mut(&room_id).unwrap().add_item(room_item_id.clone());
let chest_id: ItemId = crate::idgen::new_id().into();
let mut chest = Item {
id: chest_id.clone(),
symbol: "chest".into(),
name: "Chest".into(),
description: String::new(),
location: Location::Room(room_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: Some(ContainerState::Open),
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
let gem_id: ItemId = crate::idgen::new_id().into();
let gem = Item {
id: gem_id.clone(),
symbol: "gem".into(),
name: "Gem".into(),
description: String::new(),
location: Location::Item(chest_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
let restricted_chest_item_id: ItemId = crate::idgen::new_id().into();
let restricted_chest_item = Item {
id: restricted_chest_item_id.clone(),
symbol: "rci".into(),
name: "Restricted Chest Item".into(),
description: String::new(),
location: Location::Item(chest_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Restricted {
reason: "restricted because... reasons".to_string(),
},
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
chest.add_item(gem_id.clone());
chest.add_item(restricted_chest_item_id.clone());
world.items.insert(gem_id.clone(), gem);
world.items.insert(chest_id.clone(), chest);
world
.items
.insert(restricted_chest_item_id.clone(), restricted_chest_item);
world.rooms.get_mut(&room_id).unwrap().add_item(chest_id.clone());
let npc_id: NpcId = crate::idgen::new_id().into();
let mut npc = Npc {
id: npc_id.clone(),
symbol: "bob".into(),
name: "Bob".into(),
description: String::new(),
location: Location::Room(room_id.clone()),
inventory: HashSet::new(),
dialogue: HashMap::new(),
state: NpcState::Normal,
movement: None,
health: HealthState::new_at_max(10),
};
let npc_item_id: ItemId = crate::idgen::new_id().into();
let npc_item = Item {
id: npc_item_id.clone(),
symbol: "coin".into(),
name: "Coin".into(),
description: String::new(),
location: Location::Npc(npc_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
let restricted_npc_item_id: ItemId = crate::idgen::new_id().into();
let restricted_npc_item = Item {
id: restricted_npc_item_id.clone(),
symbol: "key".into(),
name: "Restricted NPC Item".into(),
description: String::new(),
location: Location::Npc(npc_id.clone()),
container_state: None,
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Restricted {
reason: "reasons".to_string(),
},
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
npc.add_item(npc_item_id.clone());
npc.add_item(restricted_npc_item_id.clone());
world.items.insert(npc_item_id.clone(), npc_item);
world.items.insert(restricted_npc_item_id.clone(), restricted_npc_item);
world.npcs.insert(npc_id.clone(), npc);
world.rooms.get_mut(&room_id).unwrap().npcs.insert(npc_id.clone());
let view = View::new();
TestWorld {
world,
view,
room_id,
inv_item_id,
room_item_id,
chest_id,
gem_id,
npc_id,
npc_item_id,
restr_chest_item_id: restricted_chest_item_id,
restr_npc_item_id: restricted_npc_item_id,
}
}
#[test]
fn drop_handler_drops_item_into_room() {
let mut tw = build_world();
let item_id = tw.inv_item_id;
let room_id = tw.room_id;
drop_handler(&mut tw.world, &mut tw.view, "apple").unwrap();
assert!(!tw.world.player.inventory.contains(&item_id));
assert!(tw.world.rooms.get(&room_id).unwrap().contents.contains(&item_id));
assert_eq!(
tw.world.items.get(&item_id).unwrap().location(),
&Location::Room(room_id)
);
}
#[test]
fn take_handler_moves_item_to_inventory() {
let mut tw = build_world();
let item_id = tw.room_item_id;
let room_id = tw.room_id;
take_handler(&mut tw.world, &mut tw.view, "rock").unwrap();
assert!(tw.world.player.inventory.contains(&item_id));
assert!(!tw.world.rooms.get(&room_id).unwrap().contents.contains(&item_id));
assert_eq!(tw.world.items.get(&item_id).unwrap().location(), &Location::Inventory);
}
#[test]
fn take_from_handler_from_item() {
let mut tw = build_world();
let chest_id = tw.chest_id;
let gem_id = tw.gem_id;
take_from_handler(&mut tw.world, &mut tw.view, "gem", "chest").unwrap();
assert!(tw.world.player.inventory.contains(&gem_id));
assert!(!tw.world.items.get(&chest_id).unwrap().contents.contains(&gem_id));
assert_eq!(tw.world.items.get(&gem_id).unwrap().location(), &Location::Inventory);
}
#[test]
fn take_restricted_item_from_item_blocked() {
let mut tw = build_world();
let chest_id = tw.chest_id;
let item_id = tw.restr_chest_item_id;
take_from_handler(&mut tw.world, &mut tw.view, "restricted", "chest").unwrap();
assert!(!tw.world.player.inventory.contains(&item_id));
assert!(tw.world.items.get(&chest_id).unwrap().contents.contains(&item_id));
assert_eq!(
tw.world.items.get(&item_id).unwrap().location(),
&Location::Item(chest_id)
);
}
#[test]
fn take_from_handler_prefers_selected_container_contents() {
let mut tw = build_world();
let floor_gem_id: ItemId = crate::idgen::new_id().into();
let floor_gem = Item {
id: floor_gem_id.clone(),
symbol: "floor-gem".into(),
name: "Gem".into(),
description: String::new(),
location: Location::Room(tw.room_id.clone()),
visibility: crate::item::ItemVisibility::Listed,
visible_when: None,
aliases: Vec::new(),
movability: Movability::Free,
container_state: None,
contents: HashSet::new(),
abilities: HashSet::new(),
interaction_requires: HashMap::new(),
text: None,
consumable: None,
};
tw.world.items.insert(floor_gem_id.clone(), floor_gem);
tw.world
.rooms
.get_mut(&tw.room_id)
.unwrap()
.add_item(floor_gem_id.clone());
take_from_handler(&mut tw.world, &mut tw.view, "gem", "chest").unwrap();
assert!(tw.world.player.inventory.contains(&tw.gem_id));
assert!(!tw.world.player.inventory.contains(&floor_gem_id));
assert!(!tw.world.items.get(&tw.chest_id).unwrap().contents.contains(&tw.gem_id));
assert!(
tw.world
.rooms
.get(&tw.room_id)
.unwrap()
.contents
.contains(&floor_gem_id)
);
assert_eq!(
tw.world.items.get(&floor_gem_id).unwrap().location(),
&Location::Room(tw.room_id)
);
}
#[test]
fn take_from_handler_from_npc() {
let mut tw = build_world();
let npc_id = tw.npc_id;
let coin_id = tw.npc_item_id;
take_from_handler(&mut tw.world, &mut tw.view, "coin", "bob").unwrap();
assert!(tw.world.player.inventory.contains(&coin_id));
assert!(!tw.world.npcs.get(&npc_id).unwrap().inventory.contains(&coin_id));
assert_eq!(tw.world.items.get(&coin_id).unwrap().location(), &Location::Inventory);
}
#[test]
fn take_restricted_item_from_npc_blocked() {
let mut tw = build_world();
let npc_id = tw.npc_id;
let item_id = tw.restr_npc_item_id;
take_from_handler(&mut tw.world, &mut tw.view, "restricted", "bob").unwrap();
assert!(!tw.world.player.inventory.contains(&item_id));
assert!(tw.world.npcs.get(&npc_id).unwrap().inventory.contains(&item_id));
assert_eq!(tw.world.items.get(&item_id).unwrap().location(), &Location::Npc(npc_id));
}
#[test]
fn validate_and_transfer_from_item_moves_loot() {
let mut tw = build_world();
let chest_id = tw.chest_id.clone();
let gem_id = tw.gem_id.clone();
validate_and_transfer_from_item(&mut tw.world, &mut tw.view, "gem", &chest_id).unwrap();
assert!(tw.world.player.inventory.contains(&gem_id));
assert!(!tw.world.items.get(&chest_id).unwrap().contents.contains(&gem_id));
assert_eq!(tw.world.items.get(&gem_id).unwrap().location(), &Location::Inventory);
}
#[test]
fn validate_and_transfer_from_npc_moves_loot() {
let mut tw = build_world();
let npc_id = tw.npc_id.clone();
let coin_id = tw.npc_item_id.clone();
validate_and_transfer_from_npc(&mut tw.world, &mut tw.view, "coin", &npc_id).unwrap();
assert!(tw.world.player.inventory.contains(&coin_id));
assert!(!tw.world.npcs.get(&npc_id).unwrap().inventory.contains(&coin_id));
assert_eq!(tw.world.items.get(&coin_id).unwrap().location(), &Location::Inventory);
}
#[test]
fn transfer_to_player_updates_world_from_item() {
let mut tw = build_world();
let tx_data = TransferData {
vessel_id: tw.chest_id.to_string(),
loot_id: tw.gem_id.clone(),
vessel_type: VesselType::Item,
vessel_name: "Vessel".to_string(),
loot_name: "Loot".to_string(),
};
transfer_to_player(&mut tw.world, &mut tw.view, &tx_data);
assert!(tw.world.player.inventory.contains(&tx_data.loot_id));
assert_eq!(
tw.world.items.get(&tx_data.loot_id).unwrap().location(),
&Location::Inventory
);
assert!(
!tw.world
.items
.get(&tx_data.vessel_id)
.unwrap()
.contents
.contains(&tx_data.loot_id)
);
}
#[test]
fn transfer_to_player_updates_world_from_npc() {
let mut tw = build_world();
let tx_data = TransferData {
vessel_type: VesselType::Npc,
vessel_id: tw.npc_id.to_string(),
vessel_name: "Some NPC".to_string(),
loot_id: tw.npc_item_id.clone(),
loot_name: "Loot".to_string(),
};
transfer_to_player(&mut tw.world, &mut tw.view, &tx_data);
assert!(tw.world.player.inventory.contains(&tx_data.loot_id));
assert_eq!(
tw.world.items.get(&tx_data.loot_id).unwrap().location(),
&Location::Inventory
);
assert!(
!tw.world
.npcs
.get(&tx_data.vessel_id)
.unwrap()
.inventory
.contains(&tx_data.loot_id)
);
}
#[test]
fn put_in_handler_moves_item_into_container() {
let mut tw = build_world();
let inv_item_id = tw.inv_item_id.clone();
let chest_id = tw.chest_id.clone();
put_in_handler(&mut tw.world, &mut tw.view, "apple", "chest").unwrap();
assert!(!tw.world.player.inventory.contains(&inv_item_id));
assert!(tw.world.items.get(&chest_id).unwrap().contents.contains(&inv_item_id));
assert_eq!(
tw.world.items.get(&inv_item_id).unwrap().location(),
&Location::Item(chest_id)
);
}
#[test]
fn unexpected_entity_does_not_change_world() {
let mut tw = build_world();
let before = tw.world.npcs.get(&tw.npc_id).unwrap().location().clone();
{
let npc_ref = tw.world.npcs.get(&tw.npc_id).unwrap();
unexpected_entity(WorldEntity::Npc(npc_ref), &mut tw.view, "nope");
}
let after = tw.world.npcs.get(&tw.npc_id).unwrap().location().clone();
assert_eq!(before, after);
}
}