summaryrefslogtreecommitdiff
path: root/src/exchange.rs
diff options
context:
space:
mode:
authortroido <troido@protonmail.com>2020-04-05 23:22:36 +0200
committertroido <troido@protonmail.com>2020-04-05 23:22:36 +0200
commitff457701ff56072914acb8a7160cd02c2a07095a (patch)
treea9f7c9130ce274887924ee140824dc15af061b73 /src/exchange.rs
parent48c24ec8b011d081550dc78329cbe61de67b30e9 (diff)
trading now works
Diffstat (limited to 'src/exchange.rs')
-rw-r--r--src/exchange.rs45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/exchange.rs b/src/exchange.rs
new file mode 100644
index 0000000..5e87ef2
--- /dev/null
+++ b/src/exchange.rs
@@ -0,0 +1,45 @@
+
+use crate::{
+ components::Inventory,
+ ItemId,
+ Encyclopedia
+};
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Exchange {
+ pub cost: Vec<ItemId>,
+ pub offer: Vec<ItemId>
+}
+
+impl Exchange {
+ pub fn show(&self) -> String {
+ format!(
+ "offer: [{}], price: [{}]",
+ self.offer.iter().map(|i| i.0.clone()).collect::<Vec<String>>().join(", "),
+ self.cost.iter().map(|i| i.0.clone()).collect::<Vec<String>>().join(", ")
+ )
+ }
+
+ pub fn can_trade(&self, inventory: &Inventory) -> bool {
+ if self.offer.len() as isize - self.cost.len() as isize > inventory.capacity as isize - inventory.items.len() as isize{
+ return false;
+ }
+ let mut costs = self.cost.clone();
+ for entry in inventory.items.iter() {
+ if let Some(pos) = costs.iter().position(|x| *x == entry.itemid){
+ costs.remove(pos);
+ }
+ }
+ costs.is_empty()
+ }
+
+ pub fn trade(&self, inventory: &mut Inventory, enc: &Encyclopedia) {
+ for item in self.cost.iter() {
+ let pos = inventory.items.iter().position(|entry| entry.itemid == item.clone()).unwrap();
+ inventory.items.remove(pos);
+ }
+ for item in self.offer.iter() {
+ inventory.add_item(item.clone(), enc);
+ }
+ }
+}