Compare commits

...

11 Commits

6 changed files with 188 additions and 66 deletions
+30 -15
View File
@@ -1,12 +1,17 @@
global expanded ; expanded = {} from precalc__ import precalc__
from db import load
global expanded
def expand_recipe(recipe, recipes, main = False): def expand_recipe(recipe, recipes, main = False):
global expanded global expanded
if main:
expanded = {}
ok = False ok = False
part = 1 # Одна часть part = 1 # Одна часть
while not ok: while not ok:
ok = True ok = True
min_vol = 0 # Объём мин. рецепта (вход) vol_in = 0 # Объём мин. рецепта (вход)
# Перебираем элементы # Перебираем элементы
for el in recipe: for el in recipe:
# Если составное # Если составное
@@ -18,35 +23,45 @@ def expand_recipe(recipe, recipes, main = False):
expanded = {} expanded = {}
break break
else: else:
min_vol += expand_recipe(recipes[el].comps, recipes) vol_in += expand_recipe(recipes[el].comps, recipes)
else: else:
if el in expanded: if el in expanded:
expanded[el] += recipe[el]*part expanded[el] += recipe[el]*part
else: else:
expanded[el] = recipe[el]*part expanded[el] = recipe[el]*part
min_vol += recipe[el]*part vol_in += recipe[el]*part
if main: if main:
return expanded, min_vol, part return expanded, vol_in, part
else: else:
return min_vol return vol_in
def calc(element, amount, recipes): def calc(element, amount, recipes):
# Получаем характеристику элемента # Получаем характеристику элемента
recipe, out = recipes[element].comps, recipes[element].out recipe, vol_out = recipes[element].comps, recipes[element].out
# Расчитываем минимальный рецепт # Расчитываем минимальный рецепт
expanded, vol, part = expand_recipe(recipe, recipes, True) expanded, vol_in, part = expand_recipe(recipe, recipes, True)
# Домнажаем на сколько нужно need = amount//vol_in
need = amount//vol
for i in expanded: for i in expanded:
expanded[i] = expanded[i]*need expanded[i] = expanded[i]*need
out = part*out*need vol_in *= need
vol_out *= part*need
return expanded, out return expanded, vol_in, vol_out
def calc_all(recipes, amount):
precalc = {}
for el in recipes:
precalc[el] = precalc__(calc(el, amount, recipes))
return precalc
from parse import * def precalc(element, amount):
#print( load_recipes() ) try:
print( calc('Leporazine', 100, load_recipes()) ) # Загружаем рецепты с нужным количеством
recipes = load(f'{amount}_calc.json', 'precalc')
except:
return 'Нету такого файла или вещества'
return recipes[element]
+35 -7
View File
@@ -1,20 +1,48 @@
import os import os
import json import json
from reag__ import reag__
from precalc__ import precalc__
if not os.path.exists('db.json'): if not os.path.exists('precalc.json'):
db = {} db = {}
js = json.dumps(db, indent=2) js = json.dumps(db, indent=2)
with open("db.json", "w") as outfile: with open('precalc.json', 'w') as outfile:
outfile.write(js) outfile.write(js)
print('Created new db.json') print('Created new precalc.json')
if not os.path.exists('raw_db.json'):
db = {}
js = json.dumps(db, indent=2)
with open('raw_db.json', 'w') as outfile:
outfile.write(js)
print('Created new raw_db.json')
def read_db(file = 'db.json'): def read_db(file):
with open(file, "r", encoding="utf-8") as openfile: with open(file, 'r', encoding='utf-8') as openfile:
db = json.load(openfile) db = json.load(openfile)
return db return db
def write_db(db, file = 'db.json'): def write_db(db, file):
js = json.dumps(db, indent=2, ensure_ascii=False) js = json.dumps(db, indent=2, ensure_ascii=False)
with open(file, "w", encoding="utf-8") as outfile: with open(file, 'w', encoding='utf-8') as outfile:
outfile.write(js) outfile.write(js)
def save(db, file):
raw = {}
for el in db:
class_data = db[el].get_all()
raw[el] = class_data
write_db(raw, file)
def load(file, type = 'raw'):
raw = read_db(file)
db = {}
if type == 'raw':
for el in raw:
db[el] = reag__(raw[el][0], raw[el][1], raw[el][2])
elif type == 'precalc':
for el in raw:
db[el] = precalc__(raw[el])
return db
+65 -40
View File
@@ -1,12 +1,14 @@
from requests import get from requests import get
from yaml import load, SafeLoader from yaml import load, SafeLoader
from reag__ import reag__ from reag__ import reag__
from tqdm import tqdm
def parse_yml(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions/medicine.yml'): #### Локализация ####
yml = load(get(url).content.decode('utf-8'), Loader=SafeLoader)
return yml
def parse_ftl(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Locale/ru-RU/reagents/meta/medicine.ftl'): def parse_ftl(el, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Locale/ru-RU/reagents/meta'):
if '.ftl' not in el:
el += '.ftl'
url = f'{prefix}/{el}'
raw = get(url).content.decode('utf-8') raw = get(url).content.decode('utf-8')
locales = {} locales = {}
for i in raw.splitlines(): for i in raw.splitlines():
@@ -17,42 +19,65 @@ def parse_ftl(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-st
locales[name] = locale locales[name] = locale
return locales return locales
def load_recipes(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions/medicine.yml', category = '-'): def load_locales(locales_url):
yml = parse_yml(url) locales = {}
for el in tqdm(locales_url):
locales = locales | parse_ftl(el)
return locales
#### Рецепты ####
SafeLoader.add_multi_constructor('', lambda loader, tag_suffix, node: None)
def parse_yml(el, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions'):
if '.yml' not in el:
el += '.yml'
url = f'{prefix}/{el}'
yml = load(get(url).content.decode('utf-8'), Loader=SafeLoader)
return yml
def load_recipes(recipes_url, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions'):
recipes = {} recipes = {}
for element in yml: for el in tqdm(recipes_url):
product = element["id"] yml = parse_yml(el, prefix)
comps = {} for element in yml:
for elem in element["reactants"]: if 'products' not in element or 'reactants' not in element:
comps[elem] = element["reactants"][elem]["amount"] continue
for id, value in element["products"].items(): product = element['id']
out = value comps = {}
recipes[product] = reag__(category=category, comps=comps, out=out) for elem in element['reactants']:
comps[elem] = element['reactants'][elem]['amount']
for id, value in element['products'].items():
out = value
recipes[product] = reag__(comps=comps, out=out, category=el)
return recipes return recipes
def localize(ftl = parse_ftl()):
recipes = load_recipes() #### Локализируем ####
for k, v in list(recipes.items()):
for word in ftl: def localize(recipes, locale):
if k.lower() == word: loc_recipes = {}
new_key = ftl[word].capitalize() # Итерируем элементы
recipes[new_key] = recipes.pop(k) for element in recipes:
for k1, v1 in list(recipes[new_key].comps.items()): # Итерируем составные
for word1 in ftl: el = recipes[element]
if k1.lower() == word1: # Локализованные составные
new_key1 = ftl[word1] loc_comps = {}
recipes[new_key].comps[new_key1] = recipes[new_key].comps.pop(k1) for comp in el.comps:
else: # Ищем перевод
try: if comp.lower() in locale:
for k1, v1 in list(recipes[k].comps.items()): loc = locale[comp.lower()].capitalize()
for word1 in ftl: loc_comps[loc] = el.comps[comp]
if k1.lower() == word1: else:
new_key1 = ftl[word1].capitalize() loc_comps[comp] = el.comps[comp]
recipes[k].comps[new_key1] = recipes[k].comps.pop(k1) # Заменяем на локализованное
except: el.comps = loc_comps
for k1, v1 in list(recipes[new_key].comps.items()):
for word1 in ftl: # Локализуем ключ
if k1.lower() == word1: if element.lower() in locale:
new_key1 = ftl[word1].capitalize() loc = locale[element.lower()].capitalize()
recipes[new_key].comps[new_key1] = recipes[new_key].comps.pop(k1) loc_recipes[loc] = recipes[element]
return recipes else:
loc_recipes[element] = recipes[element]
return loc_recipes
+7
View File
@@ -0,0 +1,7 @@
class precalc__:
def __init__(self, els):
self.recipe = els[0]
self.vol_in = els[1]
self.vol_out = els[2]
def get_all(self):
return [self.recipe, self.vol_in, self.vol_out]
+4 -4
View File
@@ -1,11 +1,11 @@
class reag__: class reag__:
def __init__(self, category: str = '-', comps = {}, out: int = 0): def __init__(self, comps, out, category = '-'):
# medicine
self.category = category
# {'инапровалин': 1, 'углерод': 1} # {'инапровалин': 1, 'углерод': 1}
self.comps = comps self.comps = comps
# 2 # 2
self.out = out self.out = out
# medicine
self.category = category
def get_all(self): def get_all(self):
return [self.category, self.comps, self.out] return [self.comps, self.out, self.category]
+47
View File
@@ -0,0 +1,47 @@
from parse import *
from calc import *
from db import *
print('''1. Обновить всё.
2. Пересчитать рецепты.
''')
inp = input(">> ")
print('\n')
vols = [30, 50, 100]
if inp == '1':
print('Парсим и обрабатываем данные...')
# Загружаем локализацию
locales_url = ['biological', 'botany', 'chemicals', 'cleaning', 'elements', 'fun',
'gases', 'medicine', 'narcotics', 'physical-desc', 'pyrotechnic', 'toxins',
'consumable/drink/alcohol', 'consumable/drink/drinks', 'consumable/drink/juice', 'consumable/drink/soda',
'consumable/food/condiments', 'consumable/food/food', 'consumable/food/ingredients']
locales = load_locales(locales_url)
# Загружаем сырые рецепты
recipes_url = ['biological', 'botany', 'chemicals', 'cleaning', 'drinks', 'food',
'fun', 'gas', 'medicine', 'pyrotechnic']
raw_recipes = load_recipes(recipes_url)
# Локализируем
recipes = localize(raw_recipes, locales)
save(recipes, 'raw_db.json')
print('Сохранены минимальные рецепты в raw_db.json')
print('Выполняем предрасчёты...')
for i in vols:
precalc = calc_all(recipes, i)
save(precalc, f'{i}_calc.json')
print(f'Данные сохранены в {i}_calc.json')
elif inp == '2':
print('Выполняем расчёты...')
recipes = load('raw_db.json')
for i in vols:
precalc = calc_all(recipes, i)
save(precalc, f'{i}_calc.json')
print(f'Данные сохранены в {i}_calc.json')
else:
exit()
print("ГОТОВО.")