diff --git a/__init__.py b/__init__.py index de6bc7f..6d2b440 100644 --- a/__init__.py +++ b/__init__.py @@ -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() diff --git a/command.py b/command.py index 6399d9d..1f4a98b 100644 --- a/command.py +++ b/command.py @@ -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) \ No newline at end of file + + 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.*?)", + 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) diff --git a/config.py b/config.py index 91be6c8..9785eef 100644 --- a/config.py +++ b/config.py @@ -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 \ No newline at end of file + return False diff --git a/config/plant.json b/config/plant.json index b1d6e6b..2e25184 100644 --- a/config/plant.json +++ b/config/plant.json @@ -62,4 +62,4 @@ "sell": false } } -} \ No newline at end of file +} diff --git a/database.py b/database.py index e86a506..0c59f8a 100644 --- a/database.py +++ b/database.py @@ -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 \ No newline at end of file + return False diff --git a/drawImage.py b/drawImage.py new file mode 100644 index 0000000..5a1fa4c --- /dev/null +++ b/drawImage.py @@ -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() diff --git a/farm/farm.py b/farm/farm.py new file mode 100644 index 0000000..e69de29 diff --git a/farm/shop.py b/farm/shop.py new file mode 100644 index 0000000..a48f3b8 --- /dev/null +++ b/farm/shop.py @@ -0,0 +1,7 @@ + + +class CShopManager: + + @classmethod + async def getPlantShopImage(cls) -> bytes: + return bytes() diff --git a/gClass.py b/globalClass.py similarity index 62% rename from gClass.py rename to globalClass.py index 1167a8f..ee1c492 100644 --- a/gClass.py +++ b/globalClass.py @@ -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() diff --git a/initFarm.py b/initFarm.py deleted file mode 100644 index 503e889..0000000 --- a/initFarm.py +++ /dev/null @@ -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) \ No newline at end of file diff --git a/resource/background/background.jpg b/resource/background/background.jpg new file mode 100644 index 0000000..b2c5683 Binary files /dev/null and b/resource/background/background.jpg differ diff --git a/resource/basic/0.png b/resource/plant/basic/0.png similarity index 100% rename from resource/basic/0.png rename to resource/plant/basic/0.png diff --git a/resource/basic/9.png b/resource/plant/basic/9.png similarity index 100% rename from resource/basic/9.png rename to resource/plant/basic/9.png diff --git a/resource/plant/大白菜/Crop_59_6_f61172fd4300051dd60141736111df60.png b/resource/plant/大白菜/Crop_59_6_f61172fd4300051dd60141736111df60.png new file mode 100644 index 0000000..9245a8a Binary files /dev/null and b/resource/plant/大白菜/Crop_59_6_f61172fd4300051dd60141736111df60.png differ diff --git a/resource/大白菜/icon.png b/resource/plant/大白菜/icon.png similarity index 100% rename from resource/大白菜/icon.png rename to resource/plant/大白菜/icon.png diff --git a/resource/大蒜/icon.png b/resource/plant/大蒜/icon.png similarity index 100% rename from resource/大蒜/icon.png rename to resource/plant/大蒜/icon.png diff --git a/resource/小麦/icon.png b/resource/plant/小麦/icon.png similarity index 100% rename from resource/小麦/icon.png rename to resource/plant/小麦/icon.png diff --git a/resource/水稻/icon.png b/resource/plant/水稻/icon.png similarity index 100% rename from resource/水稻/icon.png rename to resource/plant/水稻/icon.png diff --git a/resource/油菜/icon.png b/resource/plant/油菜/icon.png similarity index 100% rename from resource/油菜/icon.png rename to resource/plant/油菜/icon.png diff --git a/resource/牧草/icon.png b/resource/plant/牧草/icon.png similarity index 100% rename from resource/牧草/icon.png rename to resource/plant/牧草/icon.png diff --git a/resource/玉米/icon.png b/resource/plant/玉米/icon.png similarity index 100% rename from resource/玉米/icon.png rename to resource/plant/玉米/icon.png diff --git a/resource/生菜/icon.png b/resource/plant/生菜/icon.png similarity index 100% rename from resource/生菜/icon.png rename to resource/plant/生菜/icon.png diff --git a/resource/白萝卜/icon.png b/resource/plant/白萝卜/icon.png similarity index 100% rename from resource/白萝卜/icon.png rename to resource/plant/白萝卜/icon.png diff --git a/resource/胡萝卜/1.png b/resource/plant/胡萝卜/1.png similarity index 100% rename from resource/胡萝卜/1.png rename to resource/plant/胡萝卜/1.png diff --git a/resource/胡萝卜/2.png b/resource/plant/胡萝卜/2.png similarity index 100% rename from resource/胡萝卜/2.png rename to resource/plant/胡萝卜/2.png diff --git a/resource/胡萝卜/3.png b/resource/plant/胡萝卜/3.png similarity index 100% rename from resource/胡萝卜/3.png rename to resource/plant/胡萝卜/3.png diff --git a/resource/胡萝卜/4.png b/resource/plant/胡萝卜/4.png similarity index 100% rename from resource/胡萝卜/4.png rename to resource/plant/胡萝卜/4.png diff --git a/resource/胡萝卜/icon.png b/resource/plant/胡萝卜/icon.png similarity index 100% rename from resource/胡萝卜/icon.png rename to resource/plant/胡萝卜/icon.png