From a8c457414fe8450303e8b4acc4746c8669fe3434 Mon Sep 17 00:00:00 2001 From: Dino Date: Fri, 22 May 2026 14:24:46 -0400 Subject: [PATCH] Fix bug in city_turns_to_grow() RM #2040 --- common/city.c | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/common/city.c b/common/city.c index e8614be9e7..5007692af7 100644 --- a/common/city.c +++ b/common/city.c @@ -2050,15 +2050,29 @@ int city_turns_to_build(const struct city *pcity, **************************************************************************/ int city_turns_to_grow(const struct city *pcity) { - if (pcity->surplus[O_FOOD] > 0) { - return (city_granary_size(city_size_get(pcity)) - pcity->food_stock + - pcity->surplus[O_FOOD] - 1) / pcity->surplus[O_FOOD]; - } else if (pcity->surplus[O_FOOD] < 0) { + int food_stock = pcity->food_stock; + int surplus = pcity->surplus[O_FOOD]; + int granary_size = city_granary_size(city_size_get(pcity)); + + if (food_stock + surplus >= granary_size) { + if (city_can_grow_to(pcity, city_size_get(pcity) + 1)) { + return 1; + } else { + return 0; + } + } + if (surplus > 0) { + /* It was possible for the numerator in this calculation to be + * negative, e.g. the city just lost pop due to a disaster and now + * the granary_size is smaller than the food_stock. In that case, the + * returned value was wrong, so now we do that first test. */ + return (granary_size - food_stock + surplus - 1) / surplus; + } + if (surplus < 0) { /* Turns before famine loss */ - return -1 + (pcity->food_stock / pcity->surplus[O_FOOD]); - } else { - return FC_INFINITY; + return -1 + (food_stock / surplus); } + return FC_INFINITY; } /**********************************************************************//** -- 2.31.0