Compare commits

...

45 Commits

Author SHA1 Message Date
justuser31 bda4452390 Мелкие правки, добавление источников локализации и рецептов 2024-05-07 22:04:02 +03:00
justuser31 53d540c841 Добавлена функция получения предрасчётов 2024-05-07 20:37:54 +03:00
justuser31 320a7204e3 Обновление update_db и мелкие изменения 2024-05-04 18:53:45 +03:00
justuser31 0ef9fc1de9 Сохранение рецептов, изменение структуры класса reag__ 2024-05-04 14:20:09 +03:00
justuser31 5cce77aa10 Загрузка списком локализаций и рецептов 2024-05-04 14:00:31 +03:00
justuser31 0a98ef930b up 2024-05-04 13:20:24 +03:00
justuser31 45ec9a1157 Исправил баг, немного модифицировал. 2024-05-04 13:18:41 +03:00
justuser31 5deaa5823e up 2024-05-04 12:46:21 +03:00
justuser31 170dc0517a Оптимизация функции локализации 2024-05-03 18:08:26 +03:00
justuser31 63af9c4eaa Оптимизация функции локализации 2024-05-03 18:04:09 +03:00
wadehusky a54a1b3d61 Исправление табуляции 2024-05-03 17:58:37 +03:00
wadehusky 3d6074260a Добавление функции localize() в parse.py 2024-05-02 19:07:06 +03:00
justuser31 32527fe39e Домножение рецепта и мелкие доработки 2024-05-02 17:46:32 +03:00
justuser31 22b2a0ec27 Мелкие поправки, комментарии. 2024-05-01 15:14:33 +03:00
justuser31 eb13e945b9 Merge branch 'main' of github.com:Justuser3310/ss14_chemistry_site 2024-05-01 15:11:19 +03:00
justuser31 0d3bd86b2c Новый алгоритм, ура. 2024-05-01 15:07:43 +03:00
dttric 609c21245f + примерная реализация "получения рецепта" через POST
+ реформат таблицы для демо потому что удобно (я копировать буду👿👿)
2024-04-30 21:56:33 +07:00
dttric d7296528b2 Просто сделай 2 вкладки под это. 2024-04-30 20:52:52 +07:00
dttric 398796e892 justuser — Сегодня, в 20:45
Рецепт составляющего не нужен, много мороки будет.
2024-04-30 20:49:03 +07:00
dttric 21a77c1372 Совмещение изменений. 2024-04-30 20:44:53 +07:00
dttric ad8819dbd7 + demo.html
# показывает примерный вид сайта
2024-04-30 20:44:31 +07:00
justuser31 0afa599408 Пробелы на табы, мелкие поправки. 2024-04-30 16:09:46 +03:00
dttric ed661f01f1 - дропдауны
+ радиальные кнопки для количества
+ <select /> для реакций
2024-04-30 20:01:03 +07:00
wadehusky bdc90b42d0 Добавление функции load_recipe() в parse.py
Добавление функции get_all() для класса reag__
2024-04-30 15:34:26 +03:00
wadehusky fb9254844e Merge remote-tracking branch 'origin/main' 2024-04-30 15:31:13 +03:00
wadehusky e5c7c65816 Добавление функции load_recipe() в parse.py
Добавление функции get_all() для класса reag__
2024-04-30 15:29:00 +03:00
Justuser 2ad1536f77 Delete reworked/frontend/templates directory 2024-04-29 16:36:07 +00:00
Justuser 33ee933114 Delete reworked/frontend/main.py 2024-04-29 16:35:59 +00:00
justuser31 766549c649 Перенос файлов 2024-04-29 19:35:21 +03:00
justuser31 55da6a92cf del 2024-04-29 19:15:53 +03:00
Justuser d436f702e0 Delete reworked/frontend/index.html 2024-04-29 16:12:22 +00:00
justuser31 61fba86600 Исправление всех ошибок, запуск: flask --app main run 2024-04-29 19:10:53 +03:00
dttric bb182fed32 😴 2024-04-29 23:07:12 +07:00
dttric f0aa026ed1 просто запусти питонячий файл 2024-04-29 23:04:45 +07:00
dttric ef87f56239 пофиксил то что шаблон не работает
+ добавил ./ перед index.html

пишу с мобильного гитхаба (на сегодня точно все)
2024-04-29 23:01:10 +07:00
dttric 2592688a74 Merge branch 'main' of https://github.com/Justuser3310/ss14_chemistry_site 2024-04-29 21:19:17 +07:00
dttric a24ef738b4 намеки на фронтенд 2024-04-29 21:15:59 +07:00
justuser31 fda71ff7f3 up 2024-04-29 16:47:40 +03:00
justuser31 9f09fd67f4 up 2024-04-28 21:37:34 +03:00
justuser31 6b80c415ff Добавление парсинга ftl 2024-04-28 21:14:47 +03:00
justuser31 5c6917e40e Тесты парсера 2024-04-28 21:02:09 +03:00
none 2fa9b57ce3 Начинаем переработку всего... 2024-04-01 19:37:33 +03:00
none 88571e318a up 2024-04-01 18:44:10 +03:00
none c7987e6fd1 Добавлен нагрев 2024-03-01 23:36:26 +03:00
none 864e7ed15b Исправление рецептов с плазмой, теперь они смешаны в 1 кучу 2024-03-01 21:44:32 +03:00
17 changed files with 745 additions and 96 deletions
+165 -91
View File
@@ -1,6 +1,10 @@
from db import * from db import *
from math import floor from math import floor
# DEBUG
from icecream import ic
ic.disable()
db = read_db() db = read_db()
# Составные # Составные
@@ -8,121 +12,191 @@ recipe = {}
''' '''
def sround(num, parts): def sround(num, parts):
acc = [1,2,3,4,5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] acc = [1,2,3,4,5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
amount = num*parts amount = num*parts
# Ловим частые повторения # Ловим частые повторения
tries = 0 tries = 0
# Пока не вывели хорошее число # Пока не вывели хорошее число
good = False good = False
while not good: while not good:
num = floor(num) num = floor(num)
print(good, ' ', num) ic(good, ' ', num)
st = 1 ; good = True st = 1 ; good = True
# Перебираем различное количество частей # Перебираем различное количество частей
while st < parts: while st < parts:
# Если в допустимых значениях # Если в допустимых значениях
if num*st in acc: if num*st in acc:
st += 1 st += 1
continue continue
good = False good = False
# Перебираем допустимые значения # Перебираем допустимые значения
for i in acc: for i in acc:
if abs(i - num*st) <= 2: if abs(i - num*st) <= 2:
num = i num = i
break break
st += 1 st += 1
# Ловим частые повторения # Ловим частые повторения
tries += 1 tries += 1
if tries > 500: if tries > 500:
return sround1(num, parts) return sround1(num, parts)
if num*parts > amount: if num*parts > amount:
return sround1(num, parts) return sround1(num, parts)
return num return num
''' '''
def sround(num, parts): def sround(num, parts):
acc = [1,2,3,4,5] acc = [1,2,3,4,5]
num = floor(num) num = floor(num)
if num == 0: if num == 0:
return 1 return 1
if num in acc: if num in acc:
return num return num
elif num%5 == 0: elif num%5 == 0:
return num return num
while num%5 != 0: while num%5 != 0:
num -= 1 num -= 1
return num return num
# Поиск элемента в списке рецепта
def ll_find(ll, pat):
find = False
for i in range(len(ll)):
if ll[i][0] == pat:
return i
return None
def calc(el, amount, main = False): def calc(el, amount, main = False):
global db, recipe global db, recipe
if main: if main:
recipe = {} recipe = []
comps = db[el][2:] # Получаем составные comps = db[el][3:] # Получаем составные
out = db[el][0] #Количество на выходе heat = db[el][2]
out = db[el][0] #Количество на выходе
# Считаем количество частей # Считаем количество частей
parts = 0 parts = 0
for i in comps: for i in comps:
parts += i[1] parts += i[1]
# Делаем поправку на выход # Делаем поправку на выход
while out < parts: while out < parts:
# Предварительная часть # Предварительная часть
part = sround(amount/parts, parts) part = sround(amount/parts, parts)
#print(el, ': ',out,' < ', parts) # Если итоговый объём <= входного объёма
# Если итоговый объём <= входного объёма if (parts+1)*part <= amount:
if (parts+1)*part <= amount: parts += 1
parts += 1 else:
else: break
break
# parts = out # Считаем 1 часть
part = sround(amount/parts, parts)
# Считаем 1 часть # Динамический объём
part = sround(amount/parts, parts) # Нужен когда у вещества вход 20 а выход 10
#part_vol =
# Перебираем составные и делаем рекурсию
for i in comps:
if i[0] in db:
lpart = calc(i[0], part*i[1])
# lpart - количество составного в итоге
# 50/3, часть = 16, ИТОГ: 16*3=48 <
try:
if lpart < part:
print("LPART: ",lpart)
part = lpart
except:
pass
# Перебираем элементарные вещества # Перебираем составные и делаем рекурсию
for i in comps: for i in comps:
if i[0] not in db: ic(i)
if i[0] == 'Плазма': if i[0] in db:
recipe[i[0]] = 1 lpart = calc(i[0], part*i[1])
else: # Если наша часть больше чем составная
if i[0] not in recipe: if lpart < part:
recipe[i[0]] = part*i[1] part = lpart
else: # lpart - количество составного в итоге
recipe[i[0]] += part*i[1] # 50/3, часть = 16, ИТОГ: 16*3=48 <
if main:
print('PART: ', part) if heat and not main:
return [recipe, out*part] recipe = [['heat']] + recipe
else: if heat and main:
print('PART: ', part) recipe.append(['heat'])
return part*parts
# Перебираем элементарные вещества
for i in comps:
if i[0] not in db:
if i[0] == 'Плазма':
if ll_find(recipe, 'Плазма') == None:
recipe = [[i[0], 1]] + recipe
else:
if heat:
recipe = [[i[0], part*i[1]]] + recipe
else:
recipe.append([i[0], part*i[1]])
# Если нету плазмы и нагрева - соединяем вещества
if main:
if ll_find(recipe, 'Плазма') == None and ll_find(recipe, 'heat') == None:
ic('START: ', recipe)
new_recipe = []
while recipe != []:
ic("ORIG:", recipe)
el = recipe[0]
new_recipe.append(el)
del recipe[0]
# Текущий id
id = ll_find(new_recipe, el[0])
# Если есть ещё такой элемент
while ll_find(recipe, el[0]):
# Если это отметка для нагрева
if el[0] == 'heat':
break
same_id = ll_find(recipe, el[0])
ic('OLD: ', new_recipe[id][1])
new_recipe[id][1] += recipe[same_id][1]
ic('NEW: ', new_recipe[id][1] + recipe[same_id][1])
# Удаляем этот элемент
del recipe[same_id]
ic("NEW:", new_recipe)
recipe = new_recipe
if main:
ic(part)
return [recipe, out*part]
else:
ic(recipe)
ic(el)
ic('PART: ', part)
# >>>>>>>>>>>>>>> Возможен баг <<<<<<<<<<<<
#return part*parts
# Возвращаем объём=часть*выход
return part*out
#print( calc("Лексорин", 100, True)) #print( calc("Лексорин", 100, True))
#print( calc("Бикаридин", 100, True)) #print( calc("Бикаридин", 100, True))
#print( calc("Диловен", 100, True)) #print( calc("Диловен", 100, True))
#print( calc("Эфедрин", 100, True)) #print( calc("Эфедрин", 100, True))
#print( calc("Криоксадон", 100, True) )
#print( calc("Гидроксид", 100, True) )
#print( calc("Пунктураз", 100, True) )
#print( calc("Эпинефрин", 100, True) )
#print( calc("Гидроксид", 100, True) )
#print( calc("Ацетон", 50, True) )
#print( calc("Фенол", 50, True) )
#print(calc("Бензол", 50, True))
#OK print( calc("Гидроксид", 50, True) )
#print( calc("", 100, True) )
#print( calc("", 100, True) )
#print( calc("", 100, True) )
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

+67
View File
@@ -0,0 +1,67 @@
from precalc__ import precalc__
from db import load
global expanded
def expand_recipe(recipe, recipes, main = False):
global expanded
if main:
expanded = {}
ok = False
part = 1 # Одна часть
while not ok:
ok = True
vol_in = 0 # Объём мин. рецепта (вход)
# Перебираем элементы
for el in recipe:
# Если составное
if el in recipes:
# Одна часть должна делиться без остатка!
if part % recipes[el].out != 0:
ok = False
part += 1
expanded = {}
break
else:
vol_in += expand_recipe(recipes[el].comps, recipes)
else:
if el in expanded:
expanded[el] += recipe[el]*part
else:
expanded[el] = recipe[el]*part
vol_in += recipe[el]*part
if main:
return expanded, vol_in, part
else:
return vol_in
def calc(element, amount, recipes):
# Получаем характеристику элемента
recipe, vol_out = recipes[element].comps, recipes[element].out
# Расчитываем минимальный рецепт
expanded, vol_in, part = expand_recipe(recipe, recipes, True)
need = amount//vol_in
for i in expanded:
expanded[i] = expanded[i]*need
vol_in *= need
vol_out *= part*need
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
def precalc(element, amount):
try:
# Загружаем рецепты с нужным количеством
recipes = load(f'{amount}_calc.json', 'precalc')
except:
return 'Нету такого файла или вещества'
return recipes[element]
+48
View File
@@ -0,0 +1,48 @@
import os
import json
from reag__ import reag__
from precalc__ import precalc__
if not os.path.exists('precalc.json'):
db = {}
js = json.dumps(db, indent=2)
with open('precalc.json', 'w') as outfile:
outfile.write(js)
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):
with open(file, 'r', encoding='utf-8') as openfile:
db = json.load(openfile)
return db
def write_db(db, file):
js = json.dumps(db, indent=2, ensure_ascii=False)
with open(file, 'w', encoding='utf-8') as outfile:
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
+88
View File
@@ -0,0 +1,88 @@
<!doctype html>
<html lang="ru" data-bs-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SS14Tools</title>
<link rel="icon" type="image/x-icon" href="./assets/favicon.ico">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
<style>
.mx-10 {
margin-left: 10rem;
margin-right: 10rem;
}
.gxr-- {
margin-right: 18rem;
}
.gxl-- {
margin-left: 18rem;
}
</style>
<nav class="navbar bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#"><i class="bi bi-tools"></i> SS14Tools</a>
<div class="btn-group" role="group" aria-label="Простой пример">
<button type="button" class="btn btn-primary"><i class="bi bi-discord"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-telegram"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-github"></i></button>
</div>
</div>
</nav>
<center>
<div class="container">
<div class="row py-5">
<div class="col-xl-9">
<select class="form-select" aria-label="Реакция">
<option selected><p class="gx-5">💊 Дермалин</p></option>
</select>
</div>
<div class="container-fluid col">
<div class="btn-group" role="group" aria-label="Базовая группа переключателей радио">
<input type="radio" class="btn-check" name="btnradio" id="30" autocomplete="off">
<label class="btn btn-outline-primary" for="30">30</label>
<input type="radio" class="btn-check" name="btnradio" id="50" autocomplete="off">
<label class="btn btn-outline-primary" for="50">50</label>
<input type="radio" class="btn-check" name="btnradio" id="100" autocomplete="off" checked>
<label class="btn btn-outline-primary" for="100">100</label>
<input type="radio" class="btn-check" name="btnradio" id="300" autocomplete="off">
<label class="btn btn-outline-primary" for="300">300</label>
<input type="radio" class="btn-check" name="btnradio" id="1000" autocomplete="off">
<label class="btn btn-outline-primary" for="1000">1000</label>
</div>
</div>
</div>
<div class="row">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Рецепт</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Эффекты и дебафы</a>
</li>
</ul>
<table class="table">
<thead>
<tr>
<th scope="col">Составляющее</th>
<th scope="col">Количество</th>
</tr>
</thead>
<tbody>
<tr><td>Кислород</td><td>100</td></tr>
<tr><td>Фосфор</td><td>100</td></tr>
<tr><td>Келотан</td><td>100</td></tr>
</tbody>
</table>
</div>
</div>
</center>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
+83
View File
@@ -0,0 +1,83 @@
from requests import get
from yaml import load, SafeLoader
from reag__ import reag__
from tqdm import tqdm
#### Локализация ####
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')
locales = {}
for i in raw.splitlines():
if 'name' in i:
splitted = i.split()
name = splitted[0][13:]
locale = splitted[2]
locales[name] = locale
return locales
def load_locales(locales_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 = {}
for el in tqdm(recipes_url):
yml = parse_yml(el, prefix)
for element in yml:
if 'products' not in element or 'reactants' not in element:
continue
product = element['id']
comps = {}
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
#### Локализируем ####
def localize(recipes, locale):
loc_recipes = {}
# Итерируем элементы
for element in recipes:
# Итерируем составные
el = recipes[element]
# Локализованные составные
loc_comps = {}
for comp in el.comps:
# Ищем перевод
if comp.lower() in locale:
loc = locale[comp.lower()].capitalize()
loc_comps[loc] = el.comps[comp]
else:
loc_comps[comp] = el.comps[comp]
# Заменяем на локализованное
el.comps = loc_comps
# Локализуем ключ
if element.lower() in locale:
loc = locale[element.lower()].capitalize()
loc_recipes[loc] = recipes[element]
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]
+11
View File
@@ -0,0 +1,11 @@
class reag__:
def __init__(self, comps, out, category = '-'):
# {'инапровалин': 1, 'углерод': 1}
self.comps = comps
# 2
self.out = out
# medicine
self.category = category
def get_all(self):
return [self.comps, self.out, self.category]
+1
View File
@@ -0,0 +1 @@
flask
+76
View File
@@ -0,0 +1,76 @@
<mxfile host="app.diagrams.net" modified="2024-04-29T13:47:17.196Z" agent="Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0" etag="XnVek72uMfAQe9lHc6O7" version="24.2.8" type="device">
<diagram name="Page-1" id="jgGGHY6DT18EdGNQ9F9V">
<mxGraphModel dx="600" dy="322" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="18loy90T9bJApvsHHXn6-5" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="307.5" y="330" width="245" height="110" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-1" value="&lt;div&gt;Рецепты: parse_yml(url)&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-5">
<mxGeometry x="10" width="220" height="20" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-2" value="&lt;div&gt;[ {&#39;type&#39;: &#39;reaction&#39;, &#39;id&#39;: &#39;Dylovene&#39;, &#39;reactants&#39;: {&#39;Silicon&#39;: {&#39;amount&#39;: 1}, &#39;Nitrogen&#39;: {&#39;amount&#39;: 1}, &#39;Potassium&#39;: {&#39;amount&#39;: 1}}, &#39;products&#39;: {&#39;Dylovene&#39;: 3}}, ...]&lt;/div&gt;" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-5">
<mxGeometry y="20" width="245" height="90" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-10" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="345.5" y="495" width="170" height="70" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-8" value="load_recipe(recipes)" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-10">
<mxGeometry x="20" width="130" height="20" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-9" value="{&quot;Dylovene&quot;: reag__.*, ...}" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-10">
<mxGeometry y="20" width="170" height="50" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-11" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-2" target="18loy90T9bJApvsHHXn6-8">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-15" value="&lt;div align=&quot;left&quot;&gt;reag__(&lt;br&gt;category = &#39;medicine&#39;, comps = {&#39;silicon&#39;: 1, &#39;nitrogen&#39;: 1, &#39;potassium&#39;: 1}, &lt;br&gt;out = 3&lt;br&gt;)&lt;/div&gt;" style="shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;align=left;" vertex="1" parent="1">
<mxGeometry x="128" y="490" width="180" height="100" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-16" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-9" target="18loy90T9bJApvsHHXn6-15">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-20" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-18" target="18loy90T9bJApvsHHXn6-19">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-19" value="&lt;div align=&quot;left&quot;&gt;reag__(&lt;br&gt;category = &#39;medicine&#39;, comps = {&#39;кремний&#39;: 1, &#39;азот&#39;: 1, &#39;калий&#39;: 1}, &lt;br&gt;out = 3&lt;br&gt;)&lt;/div&gt;" style="shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;align=left;" vertex="1" parent="1">
<mxGeometry x="128" y="620" width="180" height="100" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-21" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="340.5" y="625" width="180" height="70" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-17" value="&lt;span class=&quot;HwtZe&quot; lang=&quot;en&quot;&gt;&lt;span class=&quot;jCAhz ChMk0b&quot;&gt;&lt;span class=&quot;ryNqvb&quot;&gt;localize&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;(recipes)" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-21">
<mxGeometry x="17" width="147" height="20" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-18" value="{&quot;Диловен&quot;: reag__.*, ...}" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-21">
<mxGeometry y="20" width="180" height="50" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-22" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="560.495" y="495" width="161.875" height="70" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-3" value="{&#39;dylovene&#39;: &#39;диловен&#39;, ...}" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-22">
<mxGeometry y="20" width="161.875" height="50" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-4" value="Локализация: parse_ftl(url)" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="18loy90T9bJApvsHHXn6-22">
<mxGeometry x="4.375" width="148.75" height="20" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-23" value="{&#39;dylovene&#39;: &#39;диловен&#39;, ...}" style="shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;" vertex="1" parent="1">
<mxGeometry x="576.43" y="647.5" width="130" height="45" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-24" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-3" target="18loy90T9bJApvsHHXn6-23">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-25" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-18" target="18loy90T9bJApvsHHXn6-23">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-27" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="18loy90T9bJApvsHHXn6-9" target="18loy90T9bJApvsHHXn6-17">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="18loy90T9bJApvsHHXn6-28" value="parse.py" style="swimlane;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="92.37" y="290" width="647.63" height="450" as="geometry" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
+51
View File
@@ -0,0 +1,51 @@
<mxfile host="app.diagrams.net" modified="2024-04-01T16:29:26.277Z" agent="Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0" etag="2Je_fr_wu3mHw-hys32a" version="24.2.0" type="device">
<diagram name="Page-1" id="Rpvc9EjizXgK4u0YfwZ1">
<mxGraphModel dx="768" dy="414" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="9GxXwJ9rFdMoL2Du00uo-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="9GxXwJ9rFdMoL2Du00uo-1" target="9GxXwJ9rFdMoL2Du00uo-5">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-1" value="Парсер" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="170" y="420" width="100" height="50" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-2" value="github.com/SerbiaStrong-220" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="370" y="415" width="250" height="80" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.07;entryY=0.4;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="9GxXwJ9rFdMoL2Du00uo-1" target="9GxXwJ9rFdMoL2Du00uo-2">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-4" value="Запрос данных" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];" vertex="1" connectable="0" parent="9GxXwJ9rFdMoL2Du00uo-3">
<mxGeometry x="-0.1787" y="-1" relative="1" as="geometry">
<mxPoint as="offset" />
</mxGeometry>
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-10" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="9GxXwJ9rFdMoL2Du00uo-5" target="9GxXwJ9rFdMoL2Du00uo-7">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-5" value="recipes.json" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;" vertex="1" parent="1">
<mxGeometry x="175" y="340" width="90" height="50" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="9GxXwJ9rFdMoL2Du00uo-7" target="9GxXwJ9rFdMoL2Du00uo-11">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-7" value="calc.py" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="170" y="240" width="110" height="50" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-8" value="Получение рецептов и т.п." style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry y="430" width="170" height="30" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-9" value="Составление рецепта вещества" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry y="250" width="170" height="30" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-11" value="site.py" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="390" y="242.5" width="100" height="45" as="geometry" />
</mxCell>
<mxCell id="9GxXwJ9rFdMoL2Du00uo-13" value="Отображение самого рецепта в виде компонентов" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="490" y="250" width="220" height="30" as="geometry" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+14
View File
@@ -0,0 +1,14 @@
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=False, port = 5001)
@app.route("/submit", methods=['POST'])
def calculate():
selectedval = request.form["getrecept"]
return f"{selectedval}"
+71
View File
@@ -0,0 +1,71 @@
<!doctype html>
<html lang="ru" data-bs-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SS14Tools</title>
<link rel="icon" type="image/x-icon" href="../assets/favicon.ico">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
<style>
.mx-10 {
margin-left: 10rem;
margin-right: 10rem;
}
.gxr-- {
margin-right: 18rem;
}
.gxl-- {
margin-left: 18rem;
}
</style>
<nav class="navbar bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#"><i class="bi bi-tools"></i> SS14Tools</a>
<div class="btn-group" role="group" aria-label="Простой пример">
<button type="button" class="btn btn-primary"><i class="bi bi-discord"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-telegram"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-github"></i></button>
</div>
</div>
</nav>
<center>
<div class="container">
<div class="row py-5">
<div class="col-xl-9">
<form action="/submit" method="post">
<select class="form-select" name="getrecept" aria-label="Реакция">
<option selected><p class="gx-5">Выберите (бля а что мы конкретно выбираем)</p></option>
<option value="1">Пример 1</option>
<option value="2">Пример 2</option>
<option value="3">Пример 3</option>
</select>
<input type="submit" value="Submit">
</form>
</div>
<div class="container-fluid col">
<div class="btn-group" role="group" aria-label="Базовая группа переключателей радио">
<input type="radio" class="btn-check" name="btnradio" id="30" autocomplete="off">
<label class="btn btn-outline-primary" for="30">30</label>
<input type="radio" class="btn-check" name="btnradio" id="50" autocomplete="off">
<label class="btn btn-outline-primary" for="50">50</label>
<input type="radio" class="btn-check" name="btnradio" id="100" autocomplete="off" checked>
<label class="btn btn-outline-primary" for="100">100</label>
<input type="radio" class="btn-check" name="btnradio" id="300" autocomplete="off">
<label class="btn btn-outline-primary" for="300">300</label>
<input type="radio" class="btn-check" name="btnradio" id="1000" autocomplete="off">
<label class="btn btn-outline-primary" for="1000">1000</label>
</div>
</div>
</div>
</div>
</center>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
+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("ГОТОВО.")
+6 -3
View File
@@ -7,7 +7,6 @@ els = list(db.keys())
from dash import Dash, dcc, html, Input, Output,callback from dash import Dash, dcc, html, Input, Output,callback
app = Dash(__name__, title="SS14 Tools", update_title=None) app = Dash(__name__, title="SS14 Tools", update_title=None)
#### ФОРМАТ СТРАНИЦЫ #### #### ФОРМАТ СТРАНИЦЫ ####
app.index_string = ''' app.index_string = '''
@@ -143,7 +142,11 @@ def update_output(reaction, amount):
# Форматирование для HTML # Форматирование для HTML
result = [] result = []
for i in comps: for i in comps:
result.append( html.Div(i + ': ' + str(comps[i]) if i[0] == 'heat':
result.append( html.Div('Нагреть!'
, style={'background-color': 'rgb(115, 62, 157)', 'color': '#ffffff', 'margin-top': 10, 'border-radius': 10, 'padding': 15, 'font-family': '"Source Sans Pro", sans-serif', 'font-size': '120%'}) )
else:
result.append( html.Div(i[0] + ': ' + str(i[1])
, style={'background-color': 'rgb(213, 193, 86)', 'color': '#ffffff', 'margin-top': 10, 'border-radius': 10, 'padding': 15, 'font-family': '"Source Sans Pro", sans-serif', 'font-size': '120%'}) ) , style={'background-color': 'rgb(213, 193, 86)', 'color': '#ffffff', 'margin-top': 10, 'border-radius': 10, 'padding': 15, 'font-family': '"Source Sans Pro", sans-serif', 'font-size': '120%'}) )
# Выходное вещество # Выходное вещество
@@ -160,4 +163,4 @@ def update_output(reaction, amount):
if __name__ == '__main__': if __name__ == '__main__':
# app.run(debug=True) # app.run(debug=True)
app.run(debug=False) app.run(debug=False, port = 9000)
+10 -2
View File
@@ -71,7 +71,7 @@ class Reagent:
self.__category = init_data.get("category") self.__category = init_data.get("category")
# raw значения которые обработаны # raw значения которые обработаны
self.heat: bool = init_data.get("heat") self.__heat: bool = init_data.get("heat")
@property @property
def name(self): def name(self):
@@ -95,6 +95,9 @@ class Reagent:
print(self.__category) print(self.__category)
result.append(self.__category) result.append(self.__category)
# Добавляем нужен ли нагрев
result.append(self.__heat)
if not self.__recipe: if not self.__recipe:
return None return None
for item in self.__recipe: for item in self.__recipe:
@@ -171,7 +174,12 @@ def load_recipes(url,name):
# print(item["id"]) # print(item["id"])
if item["id"] not in content: if item["id"] not in content:
continue continue
content[item["id"]]["heat"] = "minTemp" in item if "minTemp" in item:
content[item["id"]]["heat"] = True
else:
content[item["id"]]["heat"] = False
# if "minTemp" in item:
# print(item["minTemp"])
content[item["id"]]["reactants"] = { content[item["id"]]["reactants"] = {
element: {"amount": item["reactants"][element]["amount"], "reagent": element in content} for element in element: {"amount": item["reactants"][element]["amount"], "reagent": element in content} for element in
item["reactants"]} item["reactants"]}