This commit is contained in:
hibiki
2021-08-04 15:19:45 +08:00
parent b62399e203
commit 910af434ae
22 changed files with 571 additions and 700 deletions
+107 -39
View File
@@ -1,7 +1,7 @@
from pathlib import Path
from configs.path_config import IMAGE_PATH, TXT_PATH
from utils.image_utils import CreateImg
from typing import Tuple
from typing import Tuple, List
from math import sqrt, pow
import random
@@ -28,6 +28,7 @@ class Map:
deviation: Tuple[int, int] = (25, 51),
padding: int = 100,
planning_route: bool = False,
ratio: float = 1,
):
"""
参数:
@@ -36,14 +37,21 @@ class Map:
:param deviation: 坐标误差
:param padding: 截图外边距
:param planning_route: 是否规划最佳线路
:param ratio: 压缩比率
"""
self.map = CreateImg(0, 0, background=map_path)
self.resource_name = resource_name
self.center_x = center_point[0]
self.center_y = center_point[1]
self.deviation = deviation
self.padding = padding
self.padding = int(padding * ratio)
self.planning_route = planning_route
self.ratio = ratio
self.deviation = (
int(self.deviation[0] * ratio),
int(self.deviation[1] * ratio),
)
data = json.load(open(resource_label_file, "r", encoding="utf8"))
# 资源 id
@@ -67,27 +75,27 @@ class Map:
# 资源坐标
data = json.load(open(resource_point_file, "r", encoding="utf8"))
self.resource_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.resource_id
]
# 传送锚点坐标
self.teleport_anchor_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_anchor_id
]
# 神像坐标
self.teleport_god_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_god_id
@@ -95,21 +103,23 @@ class Map:
# 将地图上生成资源图标
def generate_resource_icon_in_map(self) -> int:
x_list = [x[0] for x in self.resource_point]
y_list = [x[1] for x in self.resource_point]
x_list = [x.x for x in self.resource_point]
y_list = [x.y for x in self.resource_point]
min_width = min(x_list) - self.padding
max_width = max(x_list) + self.padding
min_height = min(y_list) - self.padding
max_height = max(y_list) + self.padding
self._generate_transfer_icon((min_width, min_height, max_width, max_height))
for res in self.resource_point:
icon = self._get_icon_image(self.resource_id)
self.map.paste(
icon, (res.x - self.deviation[0], res.y - self.deviation[1]), True
)
if self.planning_route:
self._generate_best_route()
self._generate_transfer_icon((min_width, min_height, max_width, max_height))
for x, y in self.resource_point:
icon = self._get_icon_image(self.resource_id)
self.map.paste(icon, (x - self.deviation[0], y - self.deviation[1]), True)
self.map.crop((min_width, min_height, max_width, max_height))
rand = random.randint(1, 10000)
self.map.save(f'{IMAGE_PATH}/temp/genshin_map_{rand}.png')
self.map.save(f"{IMAGE_PATH}/temp/genshin_map_{rand}.png")
return rand
# 资源数量
@@ -119,40 +129,98 @@ class Map:
# 生成传送锚点和神像
def _generate_transfer_icon(self, box: Tuple[int, int, int, int]):
min_width, min_height, max_width, max_height = box
for points in [self.teleport_anchor_point, self.teleport_god_point]:
for resources in [self.teleport_anchor_point, self.teleport_god_point]:
id_ = (
self.teleport_anchor_id
if points == self.teleport_anchor_point
if resources == self.teleport_anchor_point
else self.teleport_god_id
)
for x, y in points:
if min_width < x < max_width and min_height < y < max_height:
for res in resources:
if min_width < res.x < max_width and min_height < res.y < max_height:
icon = self._get_icon_image(id_)
self.map.paste(
icon, (x - self.deviation[0], y - self.deviation[1]), True
icon,
(res.x - self.deviation[0], res.y - self.deviation[1]),
True,
)
# 生成最优路线(说是最优其实就是直线最短)
def _generate_best_route(self):
for x, y in self.resource_point:
min_deviation = 999999
xy = None
for points in [
self.resource_point,
self.teleport_anchor_point,
self.teleport_god_point,
]:
for r_x, r_y in points:
distance = int(sqrt(pow(abs(r_x - x), 2) + pow(abs(r_y - y), 2)))
if distance < min_deviation and x != r_x and y != r_y:
min_deviation = distance
xy = (x, y, r_x, r_y)
resources_route = []
# 先连上最近的资源路径
for res in self.resource_point:
# 拿到最近的资源
current_res, _ = res.get_resource_distance(
self.resource_point
+ self.teleport_anchor_point
+ self.teleport_god_point
)
self.map.line(
(current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1
)
resources_route.append((current_res, res))
teleport_list = self.teleport_anchor_point + self.teleport_god_point
for res1, res2 in resources_route:
point_list = [x for x in resources_route if res1 in x or res2 in x]
if not list(set(point_list).intersection(set(teleport_list))):
if res1 not in teleport_list and res2 not in teleport_list:
# while True:
# tmp = [x for x in point_list]
# break
teleport1, distance1 = res1.get_resource_distance(teleport_list)
teleport2, distance2 = res2.get_resource_distance(teleport_list)
if distance1 > distance2:
self.map.line(
(teleport1.x, teleport1.y, res1.x, res1.y),
(255, 0, 0),
width=1,
)
else:
self.map.line(
(teleport2.x, teleport2.y, res2.x, res2.y),
(255, 0, 0),
width=1,
)
self.map.line(xy, (255, 0, 0), width=3)
# self.map.line(xy, (255, 0, 0), width=3)
# 获取资源图标
def _get_icon_image(self, id_: int) -> "CreateImg":
icon = icon_path / f"{id_}.png"
if icon.exists():
return CreateImg(50, 50, background=icon)
return CreateImg(50, 50, background=f"{icon_path}/box.png")
return CreateImg(
int(50 * self.ratio), int(50 * self.ratio), background=icon
)
return CreateImg(
int(50 * self.ratio),
int(50 * self.ratio),
background=f"{icon_path}/box.png",
)
# def _get_shortest_path(self, res: 'Resources', res_2: 'Resources'):
# 资源类
class Resources:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def get_distance(self, x: int, y: int):
return int(sqrt(pow(abs(self.x - x), 2) + pow(abs(self.y - y), 2)))
# 拿到资源在该列表中的最短路径
def get_resource_distance(self, resources: List["Resources"]) -> "Resources, int":
current_res = None
min_distance = 999999
for res in resources:
distance = self.get_distance(res.x, res.y)
if distance < min_distance and res != self:
current_res = res
min_distance = distance
return current_res, min_distance
@@ -16,6 +16,7 @@ import nonebot
import aiohttp
import aiofiles
import os
try:
import ujson as json
except ModuleNotFoundError:
@@ -38,20 +39,29 @@ CENTER_POINT: Optional[Tuple[int, int]] = None
resource_name_list: List[str] = []
MAP_RATIO = 0.5
# 查找资源
async def query_resource(resource_name: str) -> str:
global CENTER_POINT
planning_route: bool = False
if resource_name and resource_name[-2:] == "路径":
resource_name = resource_name[:-2].strip()
planning_route = True
if not resource_name or resource_name not in resource_name_list:
return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
map_ = Map(resource_name, CENTER_POINT, planning_route=planning_route)
map_ = Map(
resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO
)
count = map_.get_resource_count()
rand = await asyncio.get_event_loop().run_in_executor(None, map_.generate_resource_icon_in_map)
return f"{image(f'genshin_map_{rand}.png', 'temp')}" \
f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
rand = await asyncio.get_event_loop().run_in_executor(
None, map_.generate_resource_icon_in_map
)
return (
f"{image(f'genshin_map_{rand}.png', 'temp')}"
f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
)
# 原神资源列表
@@ -76,7 +86,7 @@ async def init(flag: bool = False):
global CENTER_POINT, resource_name_list
semaphore = asyncio.Semaphore(10)
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
await download_map_init(session, semaphore, flag)
await download_map_init(session, semaphore, MAP_RATIO, flag)
await download_resource_data(session, semaphore)
await download_resource_type(session)
if not CENTER_POINT:
@@ -137,42 +147,57 @@ async def download_resource_data(session: ClientSession, semaphore: Semaphore):
# 下载原神地图并拼图
async def download_map_init(session: ClientSession, semaphore: Semaphore, flag: bool = False):
global CENTER_POINT
async def download_map_init(
session: ClientSession, semaphore: Semaphore, ratio: float = 1, flag: bool = False
):
global CENTER_POINT, MAP_RATIO
map_path.mkdir(exist_ok=True, parents=True)
_map = map_path / "map.png"
if os.path.getsize(_map) > 1024 * 1024 * 30:
_map.unlink()
async with session.get(MAP_URL, timeout=5) as response:
if response.status == 200:
data = await response.json()
if data["message"] == "OK":
data = json.loads(data["data"]["info"]["detail"])
CENTER_POINT = (data["origin"][0], data["origin"][1])
# padding_w, padding_h = data['padding']
data = data["slices"]
idx = 0
for x in data:
idj = 0
for j in x:
await download_image(
j["url"],
f"{map_path}/{idx}_{idj}.png",
session,
semaphore,
force_flag=flag
)
idj += 1
idx += 1
map_width, map_height = CreateImg(
0, 0, background=f"{map_path}/0_0.png"
).size
lens = len([x for x in os.listdir(f"{map_path}") if x.startswith("0")])
background_image = CreateImg(
map_width * lens, map_height * lens, map_width, map_height
)
for i in range(idx):
for j in range(idj):
x = CreateImg(0, 0, background=f"{map_path}/{i}_{j}.png")
background_image.paste(x)
background_image.save(f"{map_path}/map.png")
if not _map.exists():
# padding_w, padding_h = data['padding']
data = data["slices"]
idx = 0
for x in data:
idj = 0
for j in x:
await download_image(
j["url"],
f"{map_path}/{idx}_{idj}.png",
session,
semaphore,
force_flag=flag,
)
idj += 1
idx += 1
map_width, map_height = CreateImg(
0, 0, background=f"{map_path}/0_0.png"
).size
map_width = map_width * MAP_RATIO
map_height = map_height * MAP_RATIO
lens = len(
[x for x in os.listdir(f"{map_path}") if x.startswith("0")]
)
background_image = CreateImg(
map_width * lens, map_height * lens, map_width, map_height
)
for i in range(idx):
for j in range(idj):
x = CreateImg(
0,
0,
background=f"{map_path}/{i}_{j}.png",
ratio=MAP_RATIO,
)
background_image.paste(x)
background_image.save(f"{map_path}/map.png")
else:
logger.warning(f'获取原神地图失败 msg: {data["message"]}')
else:
@@ -238,3 +263,8 @@ async def download_image(
logger.warning(f"原神图片打开错误..已删除,等待下次更新... file: {path}")
if os.path.exists(path):
os.remove(path)
#
# def _get_point_ratio():
#