Abolition of bloated switches, #1 in a series
authorMartin Read <mpread@chiark.greenend.org.uk>
Mon, 10 Mar 2014 15:35:56 +0000 (15:35 +0000)
committerMartin Read <mpread@chiark.greenend.org.uk>
Mon, 10 Mar 2014 15:35:56 +0000 (15:35 +0000)
Potion effects are now applied by searching a function table instead of
having an enormous switch.

objects.cc

index 35aa86f..73d7181 100644 (file)
@@ -200,45 +200,73 @@ Action_cost eat_food(Obj_handle obj)
     return Cost_std;
 }
 
+/*! \brief Effect of quaffing a body potion */
+static void body_potion_quaff(void)
+{
+    gain_body(1);
+}
+
+/*! \brief Effect of quaffing a agility potion */
+static void agility_potion_quaff(void)
+{
+    gain_agility(1);
+}
+
+/*! \brief Effect of quaffing a healing potion */
+static void healing_potion_quaff(void)
+{
+    int healpercent = inc_flat(30, 50);
+    int healamount = (healpercent * ((u.hpmax > 60) ? u.hpmax : 60)) / 100;
+    heal_u(healamount, 1, 1);
+}
+
+/*! \brief Effect of quaffing a restoration potion */
+static void restoration_potion_quaff(void)
+{
+    notify_quaff_potion_restoration();
+    if (u.bdam && ((!u.adam) || zero_die(2)))
+    {
+       u.bdam = 0;
+       notify_body_restore();
+    }
+    else if (u.adam)
+    {
+       u.adam = 0;
+       notify_agility_restore();
+    }
+}
+
+struct Potion_table_entry
+{
+    int pobj;
+    void (*quaff_func)(void);
+};
+
+static Quaff_table_entry quaff_table[] =
+{
+    { PO_BODY_POTION, body_potion_quaff },
+    { PO_AGILITY_POTION, agility_potion_quaff },
+    { PO_HEALING_POTION, healing_potion_quaff },
+    { PO_RESTORATION_POTION, restoration_potion_quaff },
+    { NO_POBJ, nullptr },
+};
+
 /*! \brief Consume a potion */
 Action_cost quaff_potion(Obj_handle obj)
 {
     Obj *optr = obj_snapv(obj);
-    switch (optr->po_ref)
+    int i;
+    for (i = 0; quaff_table[i].pobj != NO_POBJ; ++i)
     {
-    case PO_BODY_POTION:
-        gain_body(1);
-        break;
-    case PO_AGILITY_POTION:
-        gain_agility(1);
-        break;
-    case PO_HEALING_POTION:
-        {
-            int healpercent = inc_flat(30, 50);
-            int healamount = (healpercent * ((u.hpmax > 60) ? u.hpmax : 60)) / 100;
-            heal_u(healamount, 1, 1);
-        }
-        break;
-    case PO_RESTORATION_POTION:
-        notify_quaff_potion_restoration();
-        if (u.bdam && ((!u.adam) || zero_die(2)))
-        {
-            u.bdam = 0;
-            notify_body_restore();
-        }
-        else if (u.adam)
-        {
-            u.adam = 0;
-            notify_agility_restore();
-        }
-        break;
-    default:
-        debug_quaff_non_potion();
-        return Cost_none;
+       if (quaff_table[i].pobj == optr->po_ref)
+       {
+           quaff_table[i].quaff_func();
+           consume_obj(obj);
+           return Cost_std;
+       }
     }
-    consume_obj(obj);
-    return Cost_std;
-
+    debug_quaff_non_potion();
+    return Cost_none;
 }
 
 void flavours_init(void)