✨ 新增收获逻辑
✨ 新增播种逻辑 ✨ 新增绘制作物逻辑
This commit is contained in:
parent
b1788f42c2
commit
59bb2068df
@ -36,8 +36,7 @@ async def start():
|
|||||||
# 初始化读取Json
|
# 初始化读取Json
|
||||||
await g_pJsonManager.init()
|
await g_pJsonManager.init()
|
||||||
|
|
||||||
aaa = await g_pFarmManager.sowing("1754798088", "胡萝卜", 1)
|
# await g_pFarmManager.harvest("1754798088")
|
||||||
logger.info(aaa)
|
|
||||||
|
|
||||||
# 析构函数
|
# 析构函数
|
||||||
@driver.on_shutdown
|
@driver.on_shutdown
|
||||||
|
|||||||
112
command.py
112
command.py
@ -35,14 +35,12 @@ diuse_farm = on_alconna(
|
|||||||
"我的农场",
|
"我的农场",
|
||||||
Option("--all", action=store_true),
|
Option("--all", action=store_true),
|
||||||
Subcommand("my-point", help_text="我的农场币"),
|
Subcommand("my-point", help_text="我的农场币"),
|
||||||
Subcommand("plant-shop", help_text="种子商店"),
|
Subcommand("seed-shop", help_text="种子商店"),
|
||||||
Subcommand("buy-plant", Args["name?", str]["num?", int], help_text="购买种子"),
|
Subcommand("buy-seed", Args["name?", str]["num?", int], help_text="购买种子"),
|
||||||
Subcommand("my-plant", help_text="我的种子"),
|
Subcommand("my-seed", help_text="我的种子"),
|
||||||
Subcommand("my-props", help_text="我的农场道具"),
|
|
||||||
Subcommand("sowing", Args["name?", str]["num?", int], help_text="播种"),
|
Subcommand("sowing", Args["name?", str]["num?", int], help_text="播种"),
|
||||||
Subcommand("buy", Args["name?", str]["num?", int], help_text="购买道具"),
|
Subcommand("harvest", help_text="收获"),
|
||||||
Subcommand("use", Args["name?", str]["num?", int], help_text="使用道具"),
|
Subcommand("my-plant", help_text="我的作物")
|
||||||
Subcommand("gold-list", Args["num?", int], help_text="金币排行"),
|
|
||||||
),
|
),
|
||||||
priority=5,
|
priority=5,
|
||||||
rule=to_me(),
|
rule=to_me(),
|
||||||
@ -82,11 +80,11 @@ async def _(session: Uninfo):
|
|||||||
diuse_farm.shortcut(
|
diuse_farm.shortcut(
|
||||||
"种子商店",
|
"种子商店",
|
||||||
command="我的农场",
|
command="我的农场",
|
||||||
arguments=["plant-shop"],
|
arguments=["seed-shop"],
|
||||||
prefix=True,
|
prefix=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@diuse_farm.assign("plant-shop")
|
@diuse_farm.assign("seed-shop")
|
||||||
async def _(session: Uninfo):
|
async def _(session: Uninfo):
|
||||||
uid = str(session.user.id)
|
uid = str(session.user.id)
|
||||||
point = await g_pSqlManager.getUserPointByUid(uid)
|
point = await g_pSqlManager.getUserPointByUid(uid)
|
||||||
@ -95,17 +93,17 @@ async def _(session: Uninfo):
|
|||||||
await MessageUtils.build_message("尚未开通农场").send()
|
await MessageUtils.build_message("尚未开通农场").send()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
image = await g_pShopManager.getPlantShopImage()
|
image = await g_pShopManager.getSeedShopImage()
|
||||||
await MessageUtils.build_message(image).send()
|
await MessageUtils.build_message(image).send()
|
||||||
|
|
||||||
diuse_farm.shortcut(
|
diuse_farm.shortcut(
|
||||||
"购买种子(?P<name>.*?)",
|
"购买种子(?P<name>.*?)",
|
||||||
command="我的农场",
|
command="我的农场",
|
||||||
arguments=["buy-plant", "{name}"],
|
arguments=["buy-seed", "{name}"],
|
||||||
prefix=True,
|
prefix=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@diuse_farm.assign("buy-plant")
|
@diuse_farm.assign("buy-seed")
|
||||||
async def _(session: Uninfo, name: Match[str], num: Query[int] = AlconnaQuery("num", 1),):
|
async def _(session: Uninfo, name: Match[str], num: Query[int] = AlconnaQuery("num", 1),):
|
||||||
if not name.available:
|
if not name.available:
|
||||||
await MessageUtils.build_message(
|
await MessageUtils.build_message(
|
||||||
@ -119,12 +117,75 @@ async def _(session: Uninfo, name: Match[str], num: Query[int] = AlconnaQuery("n
|
|||||||
await MessageUtils.build_message("尚未开通农场").send()
|
await MessageUtils.build_message("尚未开通农场").send()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
result = await g_pShopManager.buyPlant(uid, name.result, num.result)
|
result = await g_pShopManager.buySeed(uid, name.result, num.result)
|
||||||
await MessageUtils.build_message(result).send(reply_to=True)
|
await MessageUtils.build_message(result).send(reply_to=True)
|
||||||
|
|
||||||
diuse_farm.shortcut(
|
diuse_farm.shortcut(
|
||||||
"我的种子",
|
"我的种子",
|
||||||
command="我的农场",
|
command="我的农场",
|
||||||
|
arguments=["my-seed"],
|
||||||
|
prefix=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
@diuse_farm.assign("my-seed")
|
||||||
|
async def _(session: Uninfo):
|
||||||
|
uid = str(session.user.id)
|
||||||
|
point = await g_pSqlManager.getUserPointByUid(uid)
|
||||||
|
|
||||||
|
if point < 0:
|
||||||
|
await MessageUtils.build_message("尚未开通农场").send()
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = await g_pFarmManager.getUserSeedByUid(uid)
|
||||||
|
await MessageUtils.build_message(result).send(reply_to=True)
|
||||||
|
|
||||||
|
diuse_farm.shortcut(
|
||||||
|
"播种(?P<name>.*?)",
|
||||||
|
command="我的农场",
|
||||||
|
arguments=["sowing", "{name}"],
|
||||||
|
prefix=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
@diuse_farm.assign("sowing")
|
||||||
|
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)
|
||||||
|
|
||||||
|
if point < 0:
|
||||||
|
await MessageUtils.build_message("尚未开通农场").send()
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = await g_pFarmManager.sowing(uid, name.result, num.result)
|
||||||
|
await MessageUtils.build_message(result).send(reply_to=True)
|
||||||
|
|
||||||
|
|
||||||
|
diuse_farm.shortcut(
|
||||||
|
"收获",
|
||||||
|
command="我的农场",
|
||||||
|
arguments=["harvest"],
|
||||||
|
prefix=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
@diuse_farm.assign("harvest")
|
||||||
|
async def _(session: Uninfo):
|
||||||
|
uid = str(session.user.id)
|
||||||
|
point = await g_pSqlManager.getUserPointByUid(uid)
|
||||||
|
|
||||||
|
if point < 0:
|
||||||
|
await MessageUtils.build_message("尚未开通农场").send()
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = await g_pFarmManager.harvest(uid)
|
||||||
|
await MessageUtils.build_message(result).send(reply_to=True)
|
||||||
|
|
||||||
|
diuse_farm.shortcut(
|
||||||
|
"我的作物",
|
||||||
|
command="我的农场",
|
||||||
arguments=["my-plant"],
|
arguments=["my-plant"],
|
||||||
prefix=True,
|
prefix=True,
|
||||||
)
|
)
|
||||||
@ -140,28 +201,3 @@ async def _(session: Uninfo):
|
|||||||
|
|
||||||
result = await g_pFarmManager.getUserPlantByUid(uid)
|
result = await g_pFarmManager.getUserPlantByUid(uid)
|
||||||
await MessageUtils.build_message(result).send(reply_to=True)
|
await MessageUtils.build_message(result).send(reply_to=True)
|
||||||
|
|
||||||
diuse_farm.shortcut(
|
|
||||||
"播种(?P<name>.*?)",
|
|
||||||
command="我的农场",
|
|
||||||
arguments=["sowing", "{name}"],
|
|
||||||
prefix=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
if point < 0:
|
|
||||||
await MessageUtils.build_message("尚未开通农场").send()
|
|
||||||
return None
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
# result = await g_pShopManager.buyPlant(uid, name.result, num.result)
|
|
||||||
# await MessageUtils.build_message(result).send(reply_to=True)
|
|
||||||
|
|||||||
122
database.py
122
database.py
@ -1,6 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
|
from math import e
|
||||||
from typing import Any, List, Optional
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
import aiosqlite
|
import aiosqlite
|
||||||
@ -55,7 +56,8 @@ class CSqlManager:
|
|||||||
CREATE TABLE storehouse (
|
CREATE TABLE storehouse (
|
||||||
uid INTEGER PRIMARY KEY AUTOINCREMENT,
|
uid INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
item TEXT DEFAULT '',
|
item TEXT DEFAULT '',
|
||||||
plant TEXT DEFAULT ''
|
plant TEXT DEFAULT '',
|
||||||
|
seed TEXT DEFAULT ''
|
||||||
);
|
);
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@ -106,31 +108,16 @@ class CSqlManager:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def executeDBCursor(cls, command: str) -> Optional[List[Any]]:
|
async def initUserInfoByUid(cls, uid: str, name: str = "", exp: int = 0, point: int = 100):
|
||||||
"""执行自定义SQL并返回查询结果
|
"""初始化用户信息
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
command (str): SQL查询语句
|
uid (str): 用户Uid
|
||||||
|
name (str): 农场名称
|
||||||
Returns:
|
exp (int): 农场经验
|
||||||
Optional[List[Any]]: 查询结果列表(成功时),None(失败时)
|
point (int): 农场币
|
||||||
"""
|
"""
|
||||||
if len(command) <= 0:
|
|
||||||
logger.warning("空数据库命令")
|
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
|
||||||
async with cls.m_pDB.execute(command) as cursor:
|
|
||||||
# 将Row对象转换为字典列表
|
|
||||||
results = [dict(row) for row in await cursor.fetchall()]
|
|
||||||
return results
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"数据库执行失败: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def initUserInfoByUid(cls,
|
|
||||||
uid: str, name: str = "", exp: int = 0, point: int = 100):
|
|
||||||
#用户信息
|
#用户信息
|
||||||
userInfo = f"""
|
userInfo = f"""
|
||||||
INSERT INTO user (uid, name, exp, point) VALUES ({uid}, '{name}', {str(exp)}, {str(point)})
|
INSERT INTO user (uid, name, exp, point) VALUES ({uid}, '{name}', {str(exp)}, {str(point)})
|
||||||
@ -141,6 +128,7 @@ class CSqlManager:
|
|||||||
INSERT INTO storehouse (uid) VALUES ({uid});
|
INSERT INTO storehouse (uid) VALUES ({uid});
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
#用户土地
|
||||||
userSoilInfo = f"""
|
userSoilInfo = f"""
|
||||||
INSERT INTO soil (uid) VALUES ({uid});
|
INSERT INTO soil (uid) VALUES ({uid});
|
||||||
"""
|
"""
|
||||||
@ -304,48 +292,62 @@ class CSqlManager:
|
|||||||
return soilNumber
|
return soilNumber
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def getUserSoilStatusBySoilID(cls, uid: str, soil: str) -> bool:
|
async def getUserSoilStatusBySoilID(cls, uid: str, soil: str) -> tuple[bool, str]:
|
||||||
"""根据土地块获取用户土地状态
|
"""根据土地块获取用户土地状态
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
uid (str): 用户Uid
|
uid (str): 用户Uid
|
||||||
soil (str): 土地块
|
soil (str): 土地id
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否可以播种
|
tuple[bool, str]: [是否可以播种,土地信息]
|
||||||
"""
|
"""
|
||||||
if len(uid) <= 0:
|
if len(uid) <= 0:
|
||||||
return False
|
return False, ""
|
||||||
|
|
||||||
async with cls.m_pDB.execute(f"SELECT {soil} FROM soil WHERE uid = '{uid}'") as cursor:
|
async with cls.m_pDB.execute(f"SELECT {soil} FROM soil WHERE uid = '{uid}'") as cursor:
|
||||||
async for row in cursor:
|
async for row in cursor:
|
||||||
if row[0] == None:
|
if row[0] == None or len(row[0]) <= 0:
|
||||||
return True
|
return True, ""
|
||||||
|
else:
|
||||||
|
return False, row[0]
|
||||||
|
|
||||||
return False
|
return False, ""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def updateUserSoilStatusBySowing(cls, uid: str, soil: str, plant: str) -> bool:
|
async def updateUserSoilStatusByPlantName(cls, uid: str, soil: str, plant: str = "", status: int = 0) -> bool:
|
||||||
|
"""根据种子名称使用户播种
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
soil (str): 土地id
|
||||||
|
plant (str): 种子名称
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 是否更新成功
|
||||||
|
"""
|
||||||
|
|
||||||
if len(uid) <= 0:
|
if len(uid) <= 0:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
if len(plant) <= 0:
|
||||||
|
s = f",,,{status}"
|
||||||
|
else:
|
||||||
#获取种子信息 这里能崩我吃
|
#获取种子信息 这里能崩我吃
|
||||||
plantInfo = g_pJsonManager.m_pPlant['plant'][plant] # type: ignore
|
plantInfo = g_pJsonManager.m_pPlant['plant'][plant] # type: ignore
|
||||||
|
|
||||||
|
|
||||||
currentTime = datetime.now()
|
currentTime = datetime.now()
|
||||||
newTime = currentTime + timedelta(minutes=int(plantInfo['time']))
|
newTime = currentTime + timedelta(minutes=int(plantInfo['time']))
|
||||||
|
|
||||||
#种子名称,当前阶段,预计长大/预计下个阶段,地状态:0:无 1:长草 2:生虫 3:缺水 4:枯萎状态
|
#种子名称,种下时间,预计成熟时间,地状态:0:无 1:长草 2:生虫 3:缺水 4:枯萎状态
|
||||||
status = f"{plant},1,{int(newTime.timestamp())},0"
|
s = f"{plant},{int(currentTime.timestamp())},{int(newTime.timestamp())},{status}"
|
||||||
|
|
||||||
sql = f"UPDATE soil SET {soil} = '{status}' WHERE uid = '{uid}'"
|
sql = f"UPDATE soil SET {soil} = '{s}' WHERE uid = '{uid}'"
|
||||||
|
|
||||||
return await cls.executeDB(sql)
|
return await cls.executeDB(sql)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def getUserPlantByUid(cls, uid: str) -> str:
|
async def getUserSeedByUid(cls, uid: str) -> str:
|
||||||
"""获取用户仓库种子信息
|
"""获取用户仓库种子信息
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@ -355,6 +357,49 @@ class CSqlManager:
|
|||||||
str: 仓库种子信息
|
str: 仓库种子信息
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if len(uid) <= 0:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with cls.m_pDB.execute(f"SELECT seed FROM storehouse WHERE uid = '{uid}'") as cursor:
|
||||||
|
async for row in cursor:
|
||||||
|
return row[0]
|
||||||
|
|
||||||
|
return ""
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"getUserSeedByUid查询失败: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def updateUserSeedByUid(cls, uid: str, seed: str) -> bool:
|
||||||
|
"""更新用户种子仓库
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
seed (str): 种子名称
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool:
|
||||||
|
"""
|
||||||
|
|
||||||
|
if len(uid) <= 0:
|
||||||
|
return False
|
||||||
|
|
||||||
|
sql = f"UPDATE storehouse SET seed = '{seed}' WHERE uid = '{uid}'"
|
||||||
|
|
||||||
|
return await cls.executeDB(sql)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def getUserPlantByUid(cls, uid: str) -> str:
|
||||||
|
"""获取用户仓库作物信息
|
||||||
|
|
||||||
|
Args:
|
||||||
|
info (list[dict]): 用户信息
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 仓库作物信息
|
||||||
|
"""
|
||||||
|
|
||||||
if len(uid) <= 0:
|
if len(uid) <= 0:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
@ -370,13 +415,14 @@ class CSqlManager:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def updateUserPlantByUid(cls, uid: str, plant: str) -> bool:
|
async def updateUserPlantByUid(cls, uid: str, plant: str) -> bool:
|
||||||
"""添加用户仓库种子信息
|
"""更新用户作物仓库
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
info (list[dict]): 种子信息
|
uid (str): 用户Uid
|
||||||
|
plant (str): 作物名称
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否添加成功
|
bool:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(uid) <= 0:
|
if len(uid) <= 0:
|
||||||
|
|||||||
333
farm/farm.py
333
farm/farm.py
@ -1,4 +1,8 @@
|
|||||||
from numpy import arange
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from io import StringIO
|
||||||
|
from typing import Dict, List, Tuple
|
||||||
|
|
||||||
from zhenxun.services.log import logger
|
from zhenxun.services.log import logger
|
||||||
from zhenxun.utils._build_image import BuildImage
|
from zhenxun.utils._build_image import BuildImage
|
||||||
@ -22,15 +26,15 @@ class CFarmManager:
|
|||||||
"""
|
"""
|
||||||
soilNumber = await g_pSqlManager.getUserLevelByUid(uid)
|
soilNumber = await g_pSqlManager.getUserLevelByUid(uid)
|
||||||
|
|
||||||
img = BuildImage(background=g_sResourcePath / "background/background.jpg")
|
img = BuildImage(background = g_sResourcePath / "background/background.jpg")
|
||||||
|
|
||||||
soilSize = g_pJsonManager.m_pSoil['size'] # type: ignore
|
soilSize = g_pJsonManager.m_pSoil['size'] # type: ignore
|
||||||
|
|
||||||
#TODO 缺少判断用户土地资源状况
|
#TODO 缺少判断用户土地资源状况
|
||||||
soil = BuildImage(background=g_sResourcePath / "soil/普通土地.png")
|
soil = BuildImage(background = g_sResourcePath / "soil/普通土地.png")
|
||||||
await soil.resize(0, soilSize[0], soilSize[1])
|
await soil.resize(0, soilSize[0], soilSize[1])
|
||||||
|
|
||||||
grass = BuildImage(background=g_sResourcePath / "soil/草土地.png")
|
grass = BuildImage(background = g_sResourcePath / "soil/草土地.png")
|
||||||
await grass.resize(0, soilSize[0], soilSize[1])
|
await grass.resize(0, soilSize[0], soilSize[1])
|
||||||
|
|
||||||
soilPos = g_pJsonManager.m_pSoil['soil'] # type: ignore
|
soilPos = g_pJsonManager.m_pSoil['soil'] # type: ignore
|
||||||
@ -38,7 +42,9 @@ class CFarmManager:
|
|||||||
|
|
||||||
x = 0
|
x = 0
|
||||||
y = 0
|
y = 0
|
||||||
isFirst = True
|
isFirstExpansion = True #首次添加扩建图片
|
||||||
|
isFirstRipe = True
|
||||||
|
plant = None
|
||||||
for index, level in enumerate(soilUnlock):
|
for index, level in enumerate(soilUnlock):
|
||||||
x = soilPos[str(index + 1)]['x']
|
x = soilPos[str(index + 1)]['x']
|
||||||
y = soilPos[str(index + 1)]['y']
|
y = soilPos[str(index + 1)]['y']
|
||||||
@ -47,25 +53,88 @@ class CFarmManager:
|
|||||||
if soilNumber >= int(level):
|
if soilNumber >= int(level):
|
||||||
await img.paste(soil, (x, y))
|
await img.paste(soil, (x, y))
|
||||||
|
|
||||||
#TODO 缺少判断土地上是否有农作物
|
isPlant, plant, isRipe= await cls.drawSoilPlant(uid, f"soil{str(index + 1)}")
|
||||||
plant = BuildImage(background=g_sResourcePath / "plant/basic/0.png")
|
|
||||||
await plant.resize(0, 35, 58)
|
if isPlant:
|
||||||
await img.paste(plant, (x + 100, y + 50))
|
await img.paste(plant, (x + soilSize[0] // 2 - plant.width // 2,
|
||||||
|
y + soilSize[1] // 2 - plant.height // 2))
|
||||||
|
|
||||||
|
#首次添加可收获图片
|
||||||
|
if isRipe and isFirstRipe:
|
||||||
|
ripe = BuildImage(background = g_sResourcePath / "background/ripe.png")
|
||||||
|
|
||||||
|
await img.paste(ripe, (x + soilSize[0] // 2 - ripe.width // 2,
|
||||||
|
y - ripe.height // 2))
|
||||||
|
|
||||||
|
isFirstRipe = False
|
||||||
else:
|
else:
|
||||||
await img.paste(grass, (x, y))
|
await img.paste(grass, (x, y))
|
||||||
|
|
||||||
if isFirst:
|
if isFirstExpansion:
|
||||||
isFirst = False
|
isFirstExpansion = False
|
||||||
|
|
||||||
#首次添加扩建图片
|
#首次添加扩建图片
|
||||||
expansion = BuildImage(background=g_sResourcePath / "background/expansion.png")
|
expansion = BuildImage(background = g_sResourcePath / "background/expansion.png")
|
||||||
await expansion.resize(0, 69, 69)
|
await expansion.resize(0, 69, 69)
|
||||||
await img.paste(expansion, (x + 85, y + 20))
|
await img.paste(expansion, (x + soilSize[0] // 2 - expansion.width // 2,
|
||||||
|
y + soilSize[1] // 2 - expansion.height))
|
||||||
|
|
||||||
|
await img.resize(0.6)
|
||||||
return img.pic2bytes()
|
return img.pic2bytes()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def getUserPlantByUid(cls, uid: str) -> bytes:
|
async def drawSoilPlant(cls, uid: str, soilid: str) -> tuple[bool, BuildImage, bool]:
|
||||||
|
"""绘制植物资源
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
soilid (str): 土地id
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[bool, BuildImage]: [绘制是否成功,资源图片, 是否成熟]
|
||||||
|
"""
|
||||||
|
|
||||||
|
plant = None
|
||||||
|
soilStatus, soilInfo = await g_pSqlManager.getUserSoilStatusBySoilID(uid, soilid)
|
||||||
|
|
||||||
|
if soilStatus == True:
|
||||||
|
return False, None, False
|
||||||
|
else:
|
||||||
|
soilInfo = soilInfo.split(',')
|
||||||
|
plantInfo = g_pJsonManager.m_pPlant['plant'][soilInfo[0]] # type: ignore
|
||||||
|
|
||||||
|
if int(soilInfo[3]) == 4:
|
||||||
|
plant = BuildImage(background = g_sResourcePath / f"plant/basic/9.png")
|
||||||
|
|
||||||
|
return True, plant, False
|
||||||
|
|
||||||
|
currentTime = datetime.now()
|
||||||
|
matureTime = datetime.fromtimestamp(int(soilInfo[2]))
|
||||||
|
|
||||||
|
if currentTime >= matureTime:
|
||||||
|
phase = int(plantInfo['phase'])
|
||||||
|
plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo[0]}/{phase - 1}.png")
|
||||||
|
|
||||||
|
return True, plant, True
|
||||||
|
else:
|
||||||
|
plantedTime = datetime.fromtimestamp(int(soilInfo[1]))
|
||||||
|
|
||||||
|
elapsedTime = currentTime - plantedTime
|
||||||
|
elapsedMinutes = elapsedTime.total_seconds() / 60
|
||||||
|
|
||||||
|
currentStage = int(elapsedMinutes / (plantInfo['time'] / (plantInfo['phase'] - 1)))
|
||||||
|
|
||||||
|
#TODO 缺少判断部分种子是否是通用0阶段图片
|
||||||
|
if currentStage <= 0:
|
||||||
|
plant = BuildImage(background = g_sResourcePath / f"plant/basic/0.png")
|
||||||
|
await plant.resize(0, 35, 58)
|
||||||
|
else:
|
||||||
|
plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo[0]}/{currentStage}.png")
|
||||||
|
|
||||||
|
return True, plant, False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def getUserSeedByUid(cls, uid: str) -> bytes:
|
||||||
"""获取用户种子仓库
|
"""获取用户种子仓库
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@ -88,12 +157,194 @@ class CFarmManager:
|
|||||||
"是否可以上架交易行"
|
"是否可以上架交易行"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
seed = await g_pSqlManager.getUserSeedByUid(uid)
|
||||||
|
|
||||||
|
if seed == None:
|
||||||
|
result = await ImageTemplate.table_page(
|
||||||
|
"种子仓库",
|
||||||
|
"播种示例:@小真寻 播种 大白菜 [数量]",
|
||||||
|
column_name,
|
||||||
|
data_list,
|
||||||
|
)
|
||||||
|
|
||||||
|
return result.pic2bytes()
|
||||||
|
|
||||||
|
sell = ""
|
||||||
|
for item in seed.split(','):
|
||||||
|
if '|' in item:
|
||||||
|
seedName, count = item.split('|', 1) # 分割一次,避免多竖线问题
|
||||||
|
try:
|
||||||
|
plantInfo = g_pJsonManager.m_pPlant['plant'][seedName] # type: ignore
|
||||||
|
|
||||||
|
icon = ""
|
||||||
|
icon_path = g_sResourcePath / f"plant/{seedName}/icon.png"
|
||||||
|
if icon_path.exists():
|
||||||
|
icon = (icon_path, 33, 33)
|
||||||
|
|
||||||
|
if plantInfo['again'] == True:
|
||||||
|
sell = "可以"
|
||||||
|
else:
|
||||||
|
sell = "不可以"
|
||||||
|
|
||||||
|
data_list.append(
|
||||||
|
[
|
||||||
|
icon,
|
||||||
|
seedName,
|
||||||
|
count,
|
||||||
|
plantInfo['experience'],
|
||||||
|
plantInfo['harvest'],
|
||||||
|
plantInfo['time'],
|
||||||
|
plantInfo['crop'],
|
||||||
|
plantInfo['again'],
|
||||||
|
sell
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
continue
|
||||||
|
|
||||||
|
result = await ImageTemplate.table_page(
|
||||||
|
"种子仓库",
|
||||||
|
"播种示例:@小真寻 播种 大白菜 [数量]",
|
||||||
|
column_name,
|
||||||
|
data_list,
|
||||||
|
)
|
||||||
|
|
||||||
|
return result.pic2bytes()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def sowing(cls, uid: str, name: str, num: int = -1) -> str:
|
||||||
|
"""播种
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
name (str): 播种种子名称
|
||||||
|
num (int, optional): 播种数量
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str:
|
||||||
|
"""
|
||||||
|
plant = await g_pSqlManager.getUserSeedByUid(uid)
|
||||||
|
|
||||||
|
if plant == None:
|
||||||
|
return "你的种子仓库是空的,快去买点吧!"
|
||||||
|
|
||||||
|
plantDict = {}
|
||||||
|
for item in plant.split(','):
|
||||||
|
if '|' in item:
|
||||||
|
seed_name, count = item.split('|', 1)
|
||||||
|
plantDict[seed_name] = int(count)
|
||||||
|
|
||||||
|
isAll = False
|
||||||
|
if num == -1:
|
||||||
|
isAll = True
|
||||||
|
|
||||||
|
soilNumber = await g_pSqlManager.getUserSoilByUid(uid)
|
||||||
|
|
||||||
|
for i in range(1, soilNumber + 1):
|
||||||
|
if plantDict[name] > 0:
|
||||||
|
if isAll or num > 0:
|
||||||
|
soilName = f"soil{i}"
|
||||||
|
success, message = await g_pSqlManager.getUserSoilStatusBySoilID(uid, soilName)
|
||||||
|
if success:
|
||||||
|
# 更新种子数量
|
||||||
|
num -= 1
|
||||||
|
plantDict[name] -= 1
|
||||||
|
if plantDict[name] == 0:
|
||||||
|
del plantDict[name]
|
||||||
|
|
||||||
|
# 更新数据库
|
||||||
|
await g_pSqlManager.updateUserSoilStatusByPlantName(uid, soilName, name)
|
||||||
|
|
||||||
|
await g_pSqlManager.updateUserSeedByUid(
|
||||||
|
uid,
|
||||||
|
','.join([f"{k}|{v}" for k, v in plantDict.items()])
|
||||||
|
)
|
||||||
|
|
||||||
|
if num > 0:
|
||||||
|
return f"播种数量超出解锁土地数量,已将可播种土地成功播种{name}!仓库还剩下{plantDict[name]}个种子"
|
||||||
|
else:
|
||||||
|
return f"播种{name}成功!仓库还剩下{plantDict[name]}个种子"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def harvest(cls, uid: str) -> str:
|
||||||
|
"""收获作物
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 返回
|
||||||
|
"""
|
||||||
|
|
||||||
|
soilNumber = await g_pSqlManager.getUserLevelByUid(uid)
|
||||||
|
soilUnlock = g_pJsonManager.m_pLevel['soil'] # type: ignore
|
||||||
|
|
||||||
|
plant = {}
|
||||||
|
|
||||||
|
soilNames = [f"soil{i + 1}" for i, level in enumerate(soilUnlock) if soilNumber >= level]
|
||||||
|
soilStatuses = await asyncio.gather(*[
|
||||||
|
g_pSqlManager.getUserSoilStatusBySoilID(uid, name)
|
||||||
|
for name in soilNames
|
||||||
|
])
|
||||||
|
|
||||||
|
plant: Dict[str, int] = {}
|
||||||
|
harvest_records: List[str] = []
|
||||||
|
|
||||||
|
for (soil_name, (status, info)) in zip(soilNames, soilStatuses):
|
||||||
|
if not status:
|
||||||
|
soil_info = info.split(',')
|
||||||
|
plant_id = soil_info[0]
|
||||||
|
plant_info = g_pJsonManager.m_pPlant['plant'][plant_id] # type: ignore
|
||||||
|
|
||||||
|
current_time = datetime.now()
|
||||||
|
mature_time = datetime.fromtimestamp(int(soil_info[2]))
|
||||||
|
|
||||||
|
if current_time >= mature_time:
|
||||||
|
plant[plant_id] = plant.get(plant_id, 0) + plant_info['harvest']
|
||||||
|
harvest_records.append(f"收获作物:{plant_id},数量为:{plant_info['harvest']}")
|
||||||
|
|
||||||
|
# 批量更新数据库操作
|
||||||
|
await g_pSqlManager.updateUserSoilStatusByPlantName(uid, soil_name, "", 4)
|
||||||
|
|
||||||
|
if not plant:
|
||||||
|
return "可收获作物为0哦~ 不要试图拔苗助长"
|
||||||
|
else:
|
||||||
|
# 批量更新用户作物数据
|
||||||
|
await g_pSqlManager.updateUserPlantByUid(
|
||||||
|
uid,
|
||||||
|
','.join([f"{k}|{v}" for k, v in plant.items()])
|
||||||
|
)
|
||||||
|
|
||||||
|
return "\n".join(harvest_records)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def getUserPlantByUid(cls, uid: str) -> bytes:
|
||||||
|
"""获取用户作物仓库
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bytes: 返回图片
|
||||||
|
"""
|
||||||
|
|
||||||
|
data_list = []
|
||||||
|
column_name = [
|
||||||
|
"-",
|
||||||
|
"作物名称",
|
||||||
|
"数量",
|
||||||
|
"单价",
|
||||||
|
"总价",
|
||||||
|
"是否可以上架交易行"
|
||||||
|
]
|
||||||
|
|
||||||
plant = await g_pSqlManager.getUserPlantByUid(uid)
|
plant = await g_pSqlManager.getUserPlantByUid(uid)
|
||||||
|
|
||||||
if plant == None:
|
if plant == None:
|
||||||
result = await ImageTemplate.table_page(
|
result = await ImageTemplate.table_page(
|
||||||
"种子仓库",
|
"作物仓库",
|
||||||
"播种示例:@小真寻 播种 大白菜",
|
"播种示例:@小真寻 出售作物 大白菜 [数量]",
|
||||||
column_name,
|
column_name,
|
||||||
data_list,
|
data_list,
|
||||||
)
|
)
|
||||||
@ -122,11 +373,8 @@ class CFarmManager:
|
|||||||
icon,
|
icon,
|
||||||
plantName,
|
plantName,
|
||||||
count,
|
count,
|
||||||
plantInfo['experience'],
|
plantInfo['price'],
|
||||||
plantInfo['harvest'],
|
count * int(plantInfo['price']),
|
||||||
plantInfo['time'],
|
|
||||||
plantInfo['crop'],
|
|
||||||
plantInfo['again'],
|
|
||||||
sell
|
sell
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@ -135,51 +383,12 @@ class CFarmManager:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
result = await ImageTemplate.table_page(
|
result = await ImageTemplate.table_page(
|
||||||
"种子商店",
|
"作物仓库",
|
||||||
"购买示例:@小真寻 购买种子 大白菜 5",
|
"播种示例:@小真寻 出售作物 大白菜 [数量]",
|
||||||
column_name,
|
column_name,
|
||||||
data_list,
|
data_list,
|
||||||
)
|
)
|
||||||
|
|
||||||
return result.pic2bytes()
|
return result.pic2bytes()
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def sowing(cls, uid: str, name: str, num: int = 1) -> str:
|
|
||||||
"""播种
|
|
||||||
|
|
||||||
Args:
|
|
||||||
uid (str): 用户Uid
|
|
||||||
name (str): 播种种子名称
|
|
||||||
num (int, optional): 播种数量
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str:
|
|
||||||
"""
|
|
||||||
plant = await g_pSqlManager.getUserPlantByUid(uid)
|
|
||||||
|
|
||||||
if plant == None:
|
|
||||||
return "你的种子仓库是空的,快去买点吧!"
|
|
||||||
|
|
||||||
for item in plant.split(','):
|
|
||||||
if '|' in item:
|
|
||||||
plantName, count = item.split('|', 1) # 分割一次,避免多竖线问题
|
|
||||||
|
|
||||||
#判断仓库是否有当前播种种子
|
|
||||||
if plantName == name:
|
|
||||||
count = int(count)
|
|
||||||
|
|
||||||
#获取用户解锁多少块地
|
|
||||||
soilName = ""
|
|
||||||
soilNumber = await g_pSqlManager.getUserSoilByUid(uid)
|
|
||||||
#遍历地块,查看地块是否可以播种
|
|
||||||
for i in arange(1, soilNumber + 1):
|
|
||||||
if count > 0:
|
|
||||||
soilName = f"soil{str(i)}"
|
|
||||||
#如果可以播种
|
|
||||||
if await g_pSqlManager.getUserSoilStatusBySoilID(uid, soilName):
|
|
||||||
count -= 1
|
|
||||||
await g_pSqlManager.updateUserSoilStatusBySowing(uid, soilName, plantName)
|
|
||||||
return f"播种{plantName}成功!"
|
|
||||||
return "播种失败"
|
|
||||||
|
|
||||||
g_pFarmManager = CFarmManager()
|
g_pFarmManager = CFarmManager()
|
||||||
|
|||||||
27
farm/shop.py
27
farm/shop.py
@ -9,11 +9,13 @@ from ..database import g_pSqlManager
|
|||||||
class CShopManager:
|
class CShopManager:
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def getPlantShopImage(cls) -> bytes:
|
async def getSeedShopImage(cls) -> bytes:
|
||||||
"""by ATTomato
|
"""获取商店页面
|
||||||
|
|
||||||
|
TODO: 缺少翻页功能
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bytes: _description_
|
bytes: 返回商店图片bytes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
data_list = []
|
data_list = []
|
||||||
@ -68,7 +70,18 @@ class CShopManager:
|
|||||||
return result.pic2bytes()
|
return result.pic2bytes()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def buyPlant(cls, uid: str, name: str, num: int = 1) -> str:
|
async def buySeed(cls, uid: str, name: str, num: int = 1) -> str:
|
||||||
|
"""购买种子
|
||||||
|
|
||||||
|
Args:
|
||||||
|
uid (str): 用户Uid
|
||||||
|
name (str): 植物名称
|
||||||
|
num (int, optional): 购买数量
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str:
|
||||||
|
"""
|
||||||
|
|
||||||
if num <= 0:
|
if num <= 0:
|
||||||
return "请输入购买数量!"
|
return "请输入购买数量!"
|
||||||
|
|
||||||
@ -89,7 +102,7 @@ class CShopManager:
|
|||||||
if point < total:
|
if point < total:
|
||||||
return "你的农场币不够哦~ 快速速氪金吧!"
|
return "你的农场币不够哦~ 快速速氪金吧!"
|
||||||
else:
|
else:
|
||||||
p = await g_pSqlManager.getUserPlantByUid(uid)
|
p = await g_pSqlManager.getUserSeedByUid(uid)
|
||||||
|
|
||||||
if not p == None:
|
if not p == None:
|
||||||
for item in p.split(','):
|
for item in p.split(','):
|
||||||
@ -102,10 +115,10 @@ class CShopManager:
|
|||||||
else:
|
else:
|
||||||
userPlants[name] = num
|
userPlants[name] = num
|
||||||
|
|
||||||
plant_list = [f"{k}|{v}" for k, v in userPlants.items()]
|
plantList = [f"{k}|{v}" for k, v in userPlants.items()]
|
||||||
|
|
||||||
await g_pSqlManager.updateUserPointByUid(uid, point - total)
|
await g_pSqlManager.updateUserPointByUid(uid, point - total)
|
||||||
await g_pSqlManager.updateUserPlantByUid(uid, ','.join(plant_list))
|
await g_pSqlManager.updateUserSeedByUid(uid, ','.join(plantList))
|
||||||
|
|
||||||
return f"成功购买{name},当前仓库数量为:{userPlants[name]},花费{total}农场币, 剩余{point - total}农场币"
|
return f"成功购买{name},当前仓库数量为:{userPlants[name]},花费{total}农场币, 剩余{point - total}农场币"
|
||||||
|
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 18 KiB |
Loading…
Reference in New Issue
Block a user