summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--doc/api_misc.rst4
-rw-r--r--weatbag/tiles/e1.py5
-rw-r--r--weatbag/utils.py23
3 files changed, 29 insertions, 3 deletions
diff --git a/doc/api_misc.rst b/doc/api_misc.rst
index 4830e1c..674ab08 100644
--- a/doc/api_misc.rst
+++ b/doc/api_misc.rst
@@ -24,4 +24,8 @@ Understanding commands
.. automodule:: weatbag.words
+Utility functions
+-----------------
+
+.. autofunction:: weatbag.utils.transfer
diff --git a/weatbag/tiles/e1.py b/weatbag/tiles/e1.py
index 909f1b3..486a98f 100644
--- a/weatbag/tiles/e1.py
+++ b/weatbag/tiles/e1.py
@@ -1,4 +1,5 @@
from weatbag import words
+from weatbag.utils import transfer
class Tile:
def __init__(self):
@@ -17,9 +18,7 @@ class Tile:
print("Sorry, I don't understand.")
def take_berries(self, player):
- if self.contents['berries'] > 0:
- self.contents['berries'] -= 1
- player.give('berries')
+ if transfer('berries', self.contents, player.inventory):
print("Reaching up, you pick the berries.")
else:
print("There are no berries here.")
diff --git a/weatbag/utils.py b/weatbag/utils.py
new file mode 100644
index 0000000..0f73294
--- /dev/null
+++ b/weatbag/utils.py
@@ -0,0 +1,23 @@
+"""Utility functions for the game."""
+
+def transfer(item, from_collection, to_collection, n=1):
+ """Move an item from one dictionary of objects to another.
+
+ Returns True if the item was successfully transferred, False if it's not in
+ from_collection.
+
+ For example, to have the player pick up a pointy stick::
+
+ if transfer('pointy stick', tile.contents, player.inventory):
+ print("You take the stick.")
+ else:
+ print("There's no stick here.")
+ """
+ if from_collection.get(item, 0) < n:
+ return False
+ from_collection[item] -= n
+ if item in to_collection:
+ to_collection[item] += n
+ else:
+ to_collection[item] = n
+ return True