完善部分功能,将资源文件进行迁移

This commit is contained in:
Art_Sakura 2025-03-17 18:07:25 +08:00
parent 599acc8a85
commit 0185e2cb44
28 changed files with 196 additions and 66 deletions

View File

@ -1,36 +1,38 @@
from nonebot.plugin import PluginMetadata
from nonebot import get_driver
from nonebot.plugin import PluginMetadata
from zhenxun.configs.utils import PluginExtraData
from zhenxun.services.plugin_init import PluginInit
from .gClass import(
g_pSqlManager,
g_pJsonManager
)
from .command import (
diuse_register
)
from .command import diuse_farm, diuse_register
from .globalClass import g_pJsonManager, g_pSqlManager
__plugin_meta = PluginMetadata(
name = "真寻的农场",
description = "快乐的农场时光",
usage = """
name="真寻的农场",
description="快乐的农场时光",
usage="""
农场快乐时光
""".strip(),
extra = PluginExtraData(
extra=PluginExtraData(
author="molanp",
version="1.0",
menu_type="群内小游戏",
).dict(),
)
#注册启动函数
driver = get_driver()
# 构造函数
@driver.on_startup
async def start():
#初始化数据库
# 初始化数据库
await g_pSqlManager.init()
# 初始化读取Json
await g_pJsonManager.init()
# 析构函数
@driver.on_shutdown
async def shutdown():
await g_pSqlManager.cleanup()

View File

@ -1,31 +1,119 @@
from nonebot.rule import to_me
from nonebot_plugin_alconna import (Alconna, AlconnaQuery, Args, Match, Option,
Query, Subcommand, on_alconna, store_true)
from nonebot_plugin_uninfo import Uninfo
from nonebot_plugin_alconna import Alconna, on_alconna, Text
from zhenxun.services.log import logger
from zhenxun.utils.message import MessageUtils
from .gClass import(
g_pSqlManager
)
from .globalClass import g_pDrawImage, g_pSqlManager
diuse_register = on_alconna(
Alconna("注册空间"),
priority = 5,
Alconna("开通农场"),
priority=5,
rule=to_me(),
block = True,
block=True,
)
@diuse_register.handle()
async def _(session: Uninfo):
uid = str(session.user.id)
user = await g_pSqlManager.getUserByUid(uid)
user = await g_pSqlManager.getUserInfoByUid(uid)
if user:
await diuse_register.send(Text("你已经有啦"), reply_to=True)
await MessageUtils.build_message("你已经有啦").send(reply_to=True)
else:
info = {'uid' : uid, 'name' : '测试', 'level' : 1, 'point' : 0}
info = {"uid": uid, "name": "测试", "level": 1, "point": 0}
aaa = await g_pSqlManager.appendUserByUserInfo(info)
await diuse_register.send(Text(str(aaa)), reply_to=True)
await MessageUtils.build_message(str(aaa)).send(reply_to=True)
diuse_farm = on_alconna(
Alconna(
"我的农场",
Option("--all", action=store_true),
Subcommand("my-point", help_text="我的农场币"),
Subcommand("plant-shop", help_text="种子商店"),
Subcommand("buy-plant", Args["name?", str]["num?", int], help_text="购买种子"),
Subcommand("my-plant", help_text="我的种子"),
Subcommand("my-props", help_text="我的农场道具"),
Subcommand("buy", Args["name?", str]["num?", int], help_text="购买道具"),
Subcommand("use", Args["name?", str]["num?", int], help_text="使用道具"),
Subcommand("gold-list", Args["num?", int], help_text="金币排行"),
),
priority=5,
rule=to_me(),
block=True,
)
@diuse_farm.assign("$main")
async def _(session: Uninfo):
uid = str(session.user.id)
image = await g_pDrawImage.drawMyFarm()
await MessageUtils.build_message(image).send()
diuse_farm.shortcut(
"我的农场币",
command="我的农场",
arguments=["my-point"],
prefix=True,
)
@diuse_farm.assign("my-point")
async def _(session: Uninfo):
uid = str(session.user.id)
point = await g_pSqlManager.getUserPointByUid(uid)
await MessageUtils.build_message(f"你的当前农场币为: {point}").send(reply_to=True)
diuse_farm.shortcut(
"种子商店",
command="我的农场",
arguments=["plant-shop"],
prefix=True,
)
@diuse_farm.assign("plant-shop")
async def _(session: Uninfo):
uid = str(session.user.id)
point = await g_pSqlManager.getUserPointByUid(uid)
await MessageUtils.build_message(f"你的当前农场币为: {point}").send(reply_to=True)
diuse_farm.shortcut(
"购买种子(?P<name>.*?)",
command="我的农场",
arguments=["buy-plant", "{name}"],
prefix=True,
)
@diuse_farm.assign("buy-plant")
async def _(session: Uninfo, name: Match[str], num: Query[int] = AlconnaQuery("num", 1),):
if not name.available:
await MessageUtils.build_message(
"请在指令后跟需要购买的种子名称"
).finish(reply_to=True)
uid = str(session.user.id)
point = await g_pSqlManager.getUserPointByUid(uid)
await MessageUtils.build_message(f"你的当前农场币为: {point}").send(reply_to=True)
diuse_farm.shortcut(
"种子商店",
command="我的农场",
arguments=["plant-shop"],
prefix=True,
)
@diuse_farm.assign("plant-shop")
async def _(session: Uninfo):
uid = str(session.user.id)
point = await g_pSqlManager.getUserPointByUid(uid)
await MessageUtils.build_message(f"你的当前农场币为: {point}").send(reply_to=True)

View File

@ -1,12 +1,15 @@
import json
from pathlib import Path
from zhenxun.configs.path_config import DATA_PATH
from zhenxun.services.log import logger
from zhenxun.configs.path_config import DATA_PATH, IMAGE_PATH, TEMPLATE_PATH
g_sDBPath = DATA_PATH / "farm_db"
g_sDBFilePath = DATA_PATH / "farm_db/farm.db"
g_sResourcePath = Path(__file__).resolve().parent / "resource"
class CJsonManager:
def __init__(self):
self.m_pItem = None
@ -27,12 +30,15 @@ class CJsonManager:
current_file_path = Path(__file__)
try:
with open(current_file_path.resolve().parent / "config/item.json", 'r', encoding='utf-8') as file:
with open(
current_file_path.resolve().parent / "config/item.json",
encoding="utf-8",
) as file:
cls.m_pItem = json.load(file)
return True
except FileNotFoundError:
logger.warning(f"item.json 打开失败: {e}")
logger.warning("item.json 打开失败")
return False
except json.JSONDecodeError as e:
logger.warning(f"item.json JSON格式错误: {e}")
@ -43,13 +49,16 @@ class CJsonManager:
current_file_path = Path(__file__)
try:
with open(current_file_path.resolve().parent / "config/plant.json", 'r', encoding='utf-8') as file:
with open(
current_file_path.resolve().parent / "config/plant.json",
encoding="utf-8",
) as file:
cls.m_pPlant = json.load(file)
return True
except FileNotFoundError:
logger.warning(f"plant.json 打开失败: {e}")
logger.warning("plant.json 打开失败")
return False
except json.JSONDecodeError as e:
logger.warning(f"plant.json JSON格式错误: {e}")
return False
return False

View File

@ -62,4 +62,4 @@
"sell": false
}
}
}
}

View File

@ -1,23 +1,21 @@
import os
import aiosqlite
import asyncio
from zhenxun.services.log import logger
from zhenxun.configs.path_config import DATA_PATH, IMAGE_PATH, TEMPLATE_PATH
from .config import (
g_sDBPath,
g_sDBFilePath
)
from .config import g_sDBFilePath, g_sDBPath
class CSqlManager:
def __init__(self):
g_sDBPath.mkdir(parents=True, exist_ok=True)
def __del__(self):
if self.m_pDB:
self.m_pDB.close()
self.m_pDB = None
@classmethod
async def cleanup(cls):
if cls.m_pDB:
await cls.m_pDB.close()
cls.m_pDB = None
@classmethod
async def init(cls) -> bool:
@ -26,7 +24,7 @@ class CSqlManager:
cls.m_pDB = await aiosqlite.connect(g_sDBFilePath)
if bIsExist == False:
#TODO 缺少判断创建失败事件
# TODO 缺少判断创建失败事件
await cls.createDB()
return True
@ -40,14 +38,14 @@ class CSqlManager:
"""
try:
await cls.m_pDB.execute('''
await cls.m_pDB.execute("""
CREATE TABLE user (
uid INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
level INTEGER DEFAULT 1,
point INTEGER DEFAULT 0
);
''')
""")
await cls.m_pDB.commit()
return True
except Exception as e:
@ -55,7 +53,7 @@ class CSqlManager:
return False
@classmethod
async def getUserByUid(cls, uid : str) -> list[dict]:
async def getUserInfoByUid(cls, uid: str) -> list[dict]:
"""根据用户Uid获取用户信息
Args:
@ -68,15 +66,17 @@ class CSqlManager:
return []
try:
async with cls.m_pDB.execute("SELECT * FROM user WHERE uid = ?", (uid,)) as cursor:
async with cls.m_pDB.execute(
"SELECT * FROM user WHERE uid = ?", (uid,)
) as cursor:
results = []
async for row in cursor:
user_dict = {
'uid': row[0],
'name': row[1],
'level': row[2],
'point': row[3]
"uid": row[0],
"name": row[1],
"level": row[2],
"point": row[3],
}
results.append(user_dict)
@ -86,7 +86,22 @@ class CSqlManager:
return []
@classmethod
async def appendUserByUserInfo(cls, info : list[dict]) -> bool:
async def getUserPointByUid(cls, uid: str) -> int:
if len(uid) <= 0:
return -1
try:
async with cls.m_pDB.execute(
"SELECT point FROM user WHERE uid = ?", (uid,)
) as cursor:
async for row in cursor:
return int(row[0])
except Exception as e:
logger.warning(f"查询失败: {e}")
return -1
@classmethod
async def appendUserByUserInfo(cls, info: list[dict]) -> bool:
"""添加用户信息
Args:
@ -97,12 +112,15 @@ class CSqlManager:
"""
try:
await cls.m_pDB.execute('''
await cls.m_pDB.execute(
"""
INSERT INTO user (uid, name, level, point) VALUES (?, ?, ?, ?)
''', (info['uid'], info['name'], info['level'], info['point']))
""",
(info["uid"], info["name"], info["level"], info["point"]),
)
await cls.m_pDB.commit()
return True
except Exception as e:
logger.warning(f"添加失败: {e}")
return False
return False

11
drawImage.py Normal file
View File

@ -0,0 +1,11 @@
from zhenxun.utils._build_image import BuildImage
from .config import g_sResourcePath
class CDrawImageManager:
@classmethod
async def drawMyFarm(cls) -> bytes:
img = BuildImage(background=g_sResourcePath / "background/background.jpg")
return img.pic2bytes()

0
farm/farm.py Normal file
View File

7
farm/shop.py Normal file
View File

@ -0,0 +1,7 @@
class CShopManager:
@classmethod
async def getPlantShopImage(cls) -> bytes:
return bytes()

View File

@ -1,6 +1,9 @@
from .config import CJsonManager
from .database import CSqlManager
from .drawImage import CDrawImageManager
g_pJsonManager = CJsonManager()
g_pSqlManager = CSqlManager()
g_pDrawImage = CDrawImageManager()

View File

@ -1,8 +0,0 @@
from nonebot_plugin_uninfo import Uninfo
from nonebot_plugin_alconna import Alconna, At, Image, Match, Text, UniMsg, on_alconna
import command
@diuse_register.handle()
async def _(session: Uninfo):
uid = str(session.user.id)

Binary file not shown.

After

Width:  |  Height:  |  Size: 912 KiB

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

View File

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

Before

Width:  |  Height:  |  Size: 7.9 KiB

After

Width:  |  Height:  |  Size: 7.9 KiB

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

View File

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.3 KiB

View File

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB