Just a simple, and painful to use calculator for the game Factorio written in Python
Revision | a34e66bbcad3e13452d20b1bc4fc5f587feb5ad7 (tree) |
---|---|
Time | 2017-10-03 11:56:13 |
Author | Eric Hopper <hopper@omni...> |
Commiter | Eric Hopper |
Implement a way to save itemdb (but not yet load) as XML.
@@ -4,6 +4,8 @@ | ||
4 | 4 | from fractions import Fraction as _F |
5 | 5 | import sys |
6 | 6 | from collections import namedtuple |
7 | +import re | |
8 | + | |
7 | 9 | |
8 | 10 | class ProductionItem: |
9 | 11 | __slots__ = ('_name', '_time', '_ingredients', '_produced', '__weakref__') |
@@ -75,6 +77,42 @@ | ||
75 | 77 | return item |
76 | 78 | raise KeyError(name) |
77 | 79 | |
80 | + @staticmethod | |
81 | + def _itemId(item): | |
82 | + idstr = item._name.lower() | |
83 | + idstr = re.sub(r'\s+', '_', idstr) | |
84 | + return idstr | |
85 | + | |
86 | + @staticmethod | |
87 | + def _itemAsXML(item, item_idmap): | |
88 | + if item not in item_idmap: | |
89 | + cur_id = ItemSet._itemId(item) | |
90 | + item_idmap[item] = (cur_id, False) | |
91 | + for _, ingredient in item._ingredients: | |
92 | + yield from ItemSet._itemAsXML(ingredient, item_idmap) | |
93 | + if item._produced is not None: | |
94 | + yield f' <item id="{cur_id}" name="{item._name}" ' \ | |
95 | + f'time="{item._time}" ' \ | |
96 | + f'produced="{item._produced}">\n' | |
97 | + for count, ingredient in item._ingredients: | |
98 | + ingredient_id = item_idmap[ingredient][0] | |
99 | + yield f' <ingredient idref="{ingredient_id}" ' \ | |
100 | + f'count="{count}" />\n' | |
101 | + yield ' </item>\n' | |
102 | + else: | |
103 | + yield f' <item id="{cur_id}" name="{item._name}" />\n' | |
104 | + item_idmap[item] = (cur_id, True) | |
105 | + elif not item_idmap[item][1]: | |
106 | + raise RuntimeError(f"Circular reference detected '{item._name}'") | |
107 | + | |
108 | + def asXML(self): | |
109 | + yield '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n' | |
110 | + yield '<factorio_calc_item_db>\n' | |
111 | + item_idmap = {} | |
112 | + for item in self: | |
113 | + yield from self._itemAsXML(item, item_idmap) | |
114 | + yield '</factorio_calc_item_db>\n' | |
115 | + | |
78 | 116 | _mod_dir = _osp.dirname(__file__) |
79 | 117 | db_fname = _osp.join(_mod_dir, 'item-db.pickle') |
80 | 118 |