Python3.9开发GW2配方计算工具替代递归解决深度报错方案
激战2制作成本计算工具兼容神秘熔炉配方解决方案
问题背景
我正在使用Python 3.9开发《激战2(Guild Wars 2,GW2)》的制作工具,期望实现类似gw2efficiency的功能:展示最便宜的制作路径,最终扣除用户已有材料后计算仍需花费的金币。
最初编写的递归实现函数始终触发递归深度错误,原本没有预料到配方树的规模会这么大,推测问题是配方中加入了*Mystic Forge(神秘熔炉)*配方,同一件物品可能存在多个配方,导致分支量级大幅增长,目前卡在该问题上。
已经实现了从.json文件读取所有可用配方的类,以及获取所有物品价格的类,等核心逻辑跑通后就可以接入。
现有实现代码如下:
import json """ Example of a recipe: { "type": "Refinement", "output_item_id": 46739, "output_item_count": 1, "min_rating": 450, "time_to_craft_ms": 5000, "disciplines": [ "Leatherworker", "Armorsmith", "Tailor", "Huntsman" ], "flags": [ "AutoLearned" ], "ingredients": [ {"item_id": 19733, "count": 20}, {"item_id": 19734, "count": 10}, {"item_id": 19736, "count": 20}, {"item_id": 46745, "count": 1} ], "id": 7307, "chat_link": "[&CYscAAA=]" } """ # https://gist.github.com/M6D6M6A/36cd6bfd87983ee60297f4ca8dc71451 (all_recipes.json) # with open("/path/to/your/all_recipes.json") as all_recipes_json: with open("C:/Users/reute/Documents/_Python/GW2/gw2crafting/Gw2Crafter/obj/all_recepies_data.json") as all_recipes_json: all_recipes = json.load(all_recipes_json) all_recipes = [v for _, v in all_recipes["ALL_RECEPIES_DICT"].items()] # you can try all_recipes["ALL_RECEPIES"].items() to ignore Mystic Froge recipes # all_recipes = [[v for _, v in r.items()][0] # for r in all_recipes["ALL_RECEPIES"]] class gw2_recipe: def __init__(self, item_id: int): self.item_id: int = item_id self.recipe: dict = self.get_recipe_by_id(item_id) self.tree = self.get_tree(self.recipe) def get_recipe_by_id(self, item_id: int): return [r for r in all_recipes if item_id == r["output_item_id"]] def get_tree(self, recipe): """ Funktion to get full recipe tree for given item_id Example: for index, ingredient in enumerate(recipe.get("ingredients")): recipe["ingredients"][index]["recipe"] = self.get_recipe_by_id( ingredient.get("item_id")) new_ingredients = recipe["ingredients"][index]["recipe"].get( "ingredients") if new_ingredient in ([], None): return recipe for new_ingredient in recipe["ingredients"][index]["recipe"][ "ingredients"]: self.get_tree(new_ingredient) """ pass if __name__ == "__main__": # Example: https://gw2efficiency.com/crafting/calculator/a~0!b~1!c~1!d~1-46739 item_46739 = gw2_recipe(46739) print(item_46739.tree) """ Desired output Example without Mystic Forge recipes: (Only neste 1x, the code should nest until "ingredients" == []. With Mystic Forge recipes it would be a list of recipes and not a single dict) { "type": "Refinement", "output_item_id": 46739, "output_item_count": 1, "min_rating": 450, "time_to_craft_ms": 5000, "disciplines": [ "Leatherworker", "Armorsmith", "Tailor", "Huntsman" ], "flags": [ "AutoLearned" ], "ingredients": [ {"item_id": 19733, "count": 20, "recipe": {'type': 'Refinement', 'output_item_id': 19733, 'output_item_count': 1, 'min_rating': 75, 'time_to_craft_ms': 1000, 'disciplines': ['Leatherworker', 'Armorsmith', 'Tailor', 'Artificer', 'Weaponsmith', 'Scribe', 'Huntsman'], 'flags': ['AutoLearned'], 'ingredients': [{'item_id': 19728, 'count': 2}], 'id': 24, 'chat_link': '[&CRgAAAA=]'}}, {"item_id": 19734, "count": 10, "recipe": {'type': 'Refinement', 'output_item_id': 19734, 'output_item_count': 1, 'min_rating': 150, 'time_to_craft_ms': 1000, 'disciplines': ['Leatherworker', 'Armorsmith', 'Tailor', 'Artificer', 'Weaponsmith', 'Scribe', 'Huntsman'], 'flags': ['AutoLearned'], 'ingredients': [{'item_id': 19730, 'count': 2}], 'id': 25, 'chat_link': '[&CRkAAAA=]'}}, {"item_id": 19736, "count": 20, "recipe": {'type': 'Refinement', 'output_item_id': 19736, 'output_item_count': 1, 'min_rating': 225, 'time_to_craft_ms': 1000, 'disciplines': ['Leatherworker', 'Armorsmith', 'Tailor', 'Artificer', 'Weaponsmith', 'Scribe', 'Huntsman'], 'flags': ['AutoLearned'], 'ingredients': [{'item_id': 19731, 'count': 2}], 'id': 26, 'chat_link': '[&CRoAAAA=]'}}, {"item_id": 46745, "count": 1, "recipe": {'type': 'RefinementEctoplasm', 'output_item_id': 46745, 'output_item_count': 1, 'min_rating': 450, 'time_to_craft_ms': 5000, 'disciplines': ['Leatherworker', 'Armorsmith', 'Tailor', 'Artificer', 'Weaponsmith', 'Huntsman'], 'flags': ['AutoLearned'], 'ingredients': [{'item_id': 19735, 'count': 50}, {'item_id': 19721, 'count': 1}, {'item_id': 46747, 'count': 10}], 'id': 7321, 'chat_link': '[&CZkcAAA=]'}} ], "id": 7307, "chat_link": "[&CYscAAA=]" } """
问题确认
现在可以确认问题来自引入的神秘熔炉配方:排除这类配方时,示例中4种素材有3种仅返回1条配方,引入后会返回5条。怀疑逻辑出现了无限循环,或者配方树膨胀速度过快超出了内存承载。
可行解决方案
- 优先处理无限循环问题:神秘熔炉存在大量循环配方(例如高阶材料反向合成低阶材料、同阶材料互相转化的配方),递归时必须新增
visited已访问物品ID集合,已经处理过的物品ID不再重复展开,仅返回预存的成本或配方信息,避免无限递归。 - 放弃全量配方树展开思路:你的核心需求是获取最低成本制作路径,而非全量配方结构,改用动态规划自底向上计算效率更高:
- 初始化所有物品的最低成本为交易行直接购买的价格
- 遍历所有配方,计算用该配方制作产出物的单位成本(所有原料的最低成本之和除以产出数量),如果该成本低于当前物品的最低成本,就更新物品的最低成本,同时绑定对应的最优配方
- 重复上述遍历过程,直到没有物品的最低成本被更新为止,循环配方因为成本必然高于直接获取路径,不会触发更新,天然被过滤
- 替换递归为迭代实现:如果确实需要生成配方树结构,用栈/队列的深度/广度优先迭代实现替代Python原生递归,不受Python默认1000层递归深度限制,同时每层遍历可以插入去重逻辑,避免重复计算。
- 多配方分支剪枝:同一个物品存在多个配方时,先预计算每个配方的成本,仅保留成本最低的1-2个配方展开,不需要保留全部分支,大幅降低配方树的膨胀速度。
内容的提问来源于stack exchange,提问作者MPB.RIP
相关产品推荐
相关产品推荐

