home · contact · privacy
Better integration of eat cost vs. eat gain in all AI deliberations.
[plomrogue] / roguelike-server
index 258bae690579a9c0e2d1051c0fda2dc951c8e51f..bd3ab104da977ddadc359214b8e190def2d6cb23 100755 (executable)
@@ -12,6 +12,7 @@ import shlex
 import shutil
 import time
 import ctypes
+import math
 
 
 class RandomnessIO:
@@ -98,6 +99,11 @@ def cleanup_server_io():
         io_db["file_record"].close()
 
 
+def log(msg):
+    """Send "msg" to log."""
+    strong_write(io_db["file_out"], "LOG " + msg + "\n")
+
+
 def obey(command, prefix, replay=False, do_record=False):
     """Call function from commands_db mapped to command's first token.
 
@@ -468,6 +474,14 @@ def make_map():
     # This all-too-precise replica of the original C code misses iter_limit().
 
 
+def eat_vs_hunger_threshold(thingtype):
+    """Return satiation cost of eating for type. Good food for it must be >."""
+    hunger_unit = hunger_per_turn(thingtype)
+    actiontype = [id for id in world_db["ThingActions"]
+               if world_db["ThingActions"][id]["TA_NAME"] == "use"][0]
+    return world_db["ThingActions"][actiontype]["TA_EFFORT"] * hunger_unit
+
+
 def update_map_memory(t, age_map=True):
     """Update t's T_MEMMAP with what's in its FOV now,age its T_MEMMEPTHMAP."""
 
@@ -573,7 +587,7 @@ def build_fov_map(t):
 
 def log_help():
     """Send quick usage info to log."""
-    strong_write(io_db["file_out"], "LOG See README file for help.\n")
+    log("LOG See README file for help.")
 
 
 def decrement_lifepoints(t):
@@ -593,9 +607,8 @@ def decrement_lifepoints(t):
         t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
         if world_db["Things"][0] == t:
             t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
-            strong_write(io_db["file_out"], "LOG You die.\n")
-            strong_write(io_db["file_out"],
-                         "LOG See README on how to start over.\n")
+            log("You die.")
+            log("See README on how to start over.")
         else:
             t["fovmap"] = False
             t["T_MEMMAP"] = False
@@ -615,7 +628,7 @@ def mv_yx_in_dir_legal(dir, y, x):
 def actor_wait(t):
     """Make t do nothing (but loudly, if player avatar)."""
     if t == world_db["Things"][0]:
-        strong_write(io_db["file_out"], "LOG You wait.\n")
+        log("You wait")
 
 
 def actor_move(t):
@@ -635,12 +648,10 @@ def actor_move(t):
             if t == world_db["Things"][0]:
                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
-                strong_write(io_db["file_out"], "LOG You wound "
-                                                + hitted_name + ".\n")
+                log("You wound " + hitted_name + ".")
             elif 0 == hit_id:
                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
-                strong_write(io_db["file_out"], "LOG " + hitter_name +
-                                                " wounds you.\n")
+                log(hitter_name +" wounds you.")
             decrement_lifepoints(world_db["Things"][hit_id])
             return
         passable = "." == chr(world_db["MAP"][pos])
@@ -654,9 +665,9 @@ def actor_move(t):
             world_db["Things"][id]["T_POSX"] = move_result[2]
         build_fov_map(t)
         if t == world_db["Things"][0]:
-            strong_write(io_db["file_out"], "LOG You move " + dir + ".\n")
+            log("You move " + dir + ".")
     elif t == world_db["Things"][0]:
-        strong_write(io_db["file_out"], "LOG You fail to move " + dir + ".\n")
+        log("You fail to move " + dir + ".")
 
 
 def actor_pick_up(t):
@@ -678,10 +689,9 @@ def actor_pick_up(t):
         world_db["Things"][id]["carried"] = True
         t["T_CARRIES"].append(id)
         if t == world_db["Things"][0]:
-            strong_write(io_db["file_out"], "LOG You pick up an object.\n")
+                log("You pick up an object.")
     elif t == world_db["Things"][0]:
-        err = "You try to pick up an object, but there is none."
-        strong_write(io_db["file_out"], "LOG " + err + "\n")
+            log("You try to pick up an object, but there is none.")
 
 
 def actor_drop(t):
@@ -692,10 +702,9 @@ def actor_drop(t):
         t["T_CARRIES"].remove(id)
         world_db["Things"][id]["carried"] = False
         if t == world_db["Things"][0]:
-            strong_write(io_db["file_out"], "LOG You drop an object.\n")
+            log("You drop an object.")
     elif t == world_db["Things"][0]:
-        err = "You try to drop an object, but you own none."
-        strong_write(io_db["file_out"], "LOG " + err + "\n")
+       log("You try to drop an object, but you own none.")
 
 
 def actor_use(t):
@@ -709,14 +718,11 @@ def actor_use(t):
             del world_db["Things"][id]
             t["T_SATIATION"] += world_db["ThingTypes"][type]["TT_TOOLPOWER"]
             if t == world_db["Things"][0]:
-                strong_write(io_db["file_out"],
-                             "LOG You consume this object.\n")
+                log("You consume this object.")
         elif t == world_db["Things"][0]:
-            strong_write(io_db["file_out"],
-                         "LOG You try to use this object, but fail.\n")
+            log("You try to use this object, but fail.")
     elif t == world_db["Things"][0]:
-        strong_write(io_db["file_out"],
-                     "LOG You try to use an object, but you own none.\n")
+        log("You try to use an object, but you own none.")
 
 
 def thingproliferation(t, prol_map):
@@ -743,38 +749,34 @@ def thingproliferation(t, prol_map):
 
 
 def try_healing(t):
-    """Grow t's HP to a 1/32 chance if < HP max, satiation > 0, and waiting.
+    """If t's HP < max, increment them if well-nourished, maybe waiting."""
+    if t["T_LIFEPOINTS"] < \
+       world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]:
+        wait_id = [id for id in world_db["ThingActions"]
+                      if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
+        wait_divider = 8 if t["T_COMMAND"] == wait_id else 1
+        testval = int(abs(t["T_SATIATION"]) / wait_divider)
+        if (testval <= 1 or 1 == (rand.next() % testval)):
+            t["T_LIFEPOINTS"] += 1
+            if t == world_db["Things"][0]:
+                log("You heal.")
 
-    On success, decrease satiation score by 32.
-    """
-    if t["T_SATIATION"] > 0 \
-       and t["T_LIFEPOINTS"] < \
-        world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] \
-       and 0 == (rand.next() % 31) \
-       and t["T_COMMAND"] == [id for id in world_db["ThingActions"]
-                              if world_db["ThingActions"][id]["TA_NAME"] ==
-                              "wait"][0]:
-        t["T_LIFEPOINTS"] += 1
-        t["T_SATIATION"] -= 32
-        if t == world_db["Things"][0]:
-            strong_write(io_db["file_out"], "LOG You heal.\n")
+
+def hunger_per_turn(type_id):
+    """The amount of satiation score lost per turn for things of given type."""
+    return int(math.sqrt(world_db["ThingTypes"][type_id]["TT_LIFEPOINTS"]))
 
 
 def hunger(t):
     """Decrement t's satiation,dependent on it trigger lifepoint dec chance."""
     if t["T_SATIATION"] > -32768:
-        t["T_SATIATION"] -= 1
-    testbase = t["T_SATIATION"] if t["T_SATIATION"] >= 0 else -t["T_SATIATION"]
-    if not world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]:
-        raise RuntimeError("A thing that should not hunger is hungering.")
-    stomach = int(32767 / world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"])
-    if int(int(testbase / stomach) / ((rand.next() % stomach) + 1)):
+        t["T_SATIATION"] -= hunger_per_turn(t["T_TYPE"])
+    if 0 != t["T_SATIATION"] and 0 == int(rand.next() / abs(t["T_SATIATION"])):
         if t == world_db["Things"][0]:
             if t["T_SATIATION"] < 0:
-                strong_write(io_db["file_out"], "LOG You suffer from hunger.\n")
+                log("You suffer from hunger.")
             else:
-                strong_write(io_db["file_out"],
-                             "LOG You suffer from over-eating.\n")
+                log("You suffer from over-eating.")
         decrement_lifepoints(t)
 
 
@@ -834,10 +836,13 @@ def get_dir_to_target(t, filter):
                             t["T_LIFEPOINTS"]):
                         return True
         elif t["T_MEMMAP"] and "c" == filter:
+            eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
             for mt in t["T_MEMTHING"]:
                 if ' ' != chr(t["T_MEMMAP"][(mt[1] * world_db["MAP_LENGTH"])
                                             + mt[2]]) \
-                   and world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food":
+                   and world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food" \
+                   and world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"] \
+                       > eat_cost:
                     return True
         return False
 
@@ -885,11 +890,14 @@ def get_dir_to_target(t, filter):
                    world_db["ThingTypes"][Thing["T_TYPE"]]["TT_LIFEPOINTS"]:
                     set_map_score(pos, 0)
         elif "c" == filter:
+            eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
             for mt in [mt for mt in t["T_MEMTHING"]
                        if ord_blank != t["T_MEMMAP"][mt[1]
                                                      * world_db["MAP_LENGTH"]
                                                      + mt[2]]
-                       if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"]:
+                       if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
+                       if world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"]
+                           > eat_cost]:
                 set_map_score(mt[1] * world_db["MAP_LENGTH"] + mt[2], 0)
         elif "s" == filter:
             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
@@ -976,27 +984,36 @@ def get_dir_to_target(t, filter):
 
 
 def standing_on_food(t):
-    """Return True/False whether t is standing on a consumable."""
+    """Return True/False whether t is standing on healthy consumable."""
+    eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
     for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
+               if not world_db["Things"][id]["carried"]
                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]
                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
-                          ["TT_TOOL"] == "food"]:
+                  ["TT_TOOL"] == "food"
+               if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
+                  ["TT_TOOLPOWER"] > eat_cost]:
         return True
     return False
 
 
 def get_inventory_slot_to_consume(t):
-    """Return slot Id of strongest consumable in t's inventory, else -1."""
-    cmp_food = 0
+    """Return invent. slot of healthiest consumable(if any healthy),else -1."""
+    cmp_food = -1
     selection = -1
     i = 0
+    eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
     for id in t["T_CARRIES"]:
         type = world_db["Things"][id]["T_TYPE"]
         if world_db["ThingTypes"][type]["TT_TOOL"] == "food" \
-           and world_db["ThingTypes"][type]["TT_TOOLPOWER"] > cmp_food:
-            cmp_food = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
-            selection = i
+           and world_db["ThingTypes"][type]["TT_TOOLPOWER"]:
+            nutvalue = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
+            tmp_cmp = abs(t["T_SATIATION"] + nutvalue - eat_cost)
+            if (cmp_food < 0 and tmp_cmp < abs(t["T_SATIATION"])) \
+            or tmp_cmp < cmp_food:
+                cmp_food = tmp_cmp
+                selection = i
         i += 1
     return selection