🎨 将文本内容同一更新

🐛 修复偷菜无法正常计算的BUG
This commit is contained in:
2025-06-06 10:56:22 +08:00
parent ba2ecf19fc
commit ac13ab9280
20 changed files with 1284 additions and 699 deletions
+360 -253
View File
@@ -1,7 +1,5 @@
import asyncio
import math
import random
from typing import Dict, List, Tuple
from zhenxun.configs.config import Config
from zhenxun.models.user_console import UserConsole
@@ -11,7 +9,7 @@ from zhenxun.utils.enum import GoldHandle
from zhenxun.utils.image_utils import ImageTemplate
from zhenxun.utils.platform import PlatformUtils
from ..config import g_bIsDebug, g_sResourcePath
from ..config import g_bIsDebug, g_sResourcePath, g_sTranslation
from ..dbService import g_pDBService
from ..event.event import g_pEventManager
from ..json import g_pJsonManager
@@ -29,16 +27,20 @@ class CFarmManager:
pro = float(Config.get_config("zhenxun_plugin_farm", "兑换倍数"))
tax = float(Config.get_config("zhenxun_plugin_farm", "手续费"))
#计算手续费
# 计算手续费
fee = math.floor(num * tax)
#实际扣费金额
# 实际扣费金额
deduction = num + fee
if user.gold < deduction:
return f"你的金币不足或不足承担手续费。当前手续费为{fee}"
await UserConsole.reduce_gold(uid, num, GoldHandle.PLUGIN , 'zhenxun_plugin_farm') # type: ignore
await UserConsole.reduce_gold(uid, fee, GoldHandle.PLUGIN , 'zhenxun_plugin_farm') # type: ignore
await UserConsole.reduce_gold(
uid, num, GoldHandle.PLUGIN, "zhenxun_plugin_farm"
) # type: ignore
await UserConsole.reduce_gold(
uid, fee, GoldHandle.PLUGIN, "zhenxun_plugin_farm"
) # type: ignore
point = num * pro
@@ -59,48 +61,59 @@ class CFarmManager:
Returns:
bytes: 返回绘制结果
"""
img = BuildImage(background = g_sResourcePath / "background/background.jpg")
img = BuildImage(background=g_sResourcePath / "background/background.jpg")
soilSize = g_pJsonManager.m_pSoil['size']
soilSize = g_pJsonManager.m_pSoil["size"]
#TODO 缺少判断用户土地资源状况
soil = BuildImage(background = g_sResourcePath / "soil/普通土地.png")
# TODO 缺少判断用户土地资源状况
soil = BuildImage(background=g_sResourcePath / "soil/普通土地.png")
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])
soilPos = g_pJsonManager.m_pSoil['soil']
soilPos = g_pJsonManager.m_pSoil["soil"]
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
soilUnlock = int(userInfo['soil'])
soilUnlock = int(userInfo["soil"])
x = 0
y = 0
isFirstExpansion = True #首次添加扩建图片
isFirstExpansion = True # 首次添加扩建图片
isFirstRipe = True
plant = None
for index in range(0, 30):
x = soilPos[str(index + 1)]['x']
y = soilPos[str(index + 1)]['y']
x = soilPos[str(index + 1)]["x"]
y = soilPos[str(index + 1)]["y"]
#如果土地已经到达对应等级
# 如果土地已经到达对应等级
if index < soilUnlock:
await img.paste(soil, (x, y))
isPlant, plant, isRipe, offsetX, offsetY = await cls.drawSoilPlant(uid, index + 1)
isPlant, plant, isRipe, offsetX, offsetY = await cls.drawSoilPlant(
uid, index + 1
)
if isPlant:
await img.paste(plant, (x + soilSize[0] // 2 - plant.width // 2 + offsetX,
y + soilSize[1] // 2 - plant.height // 2 + offsetY))
await img.paste(
plant,
(
x + soilSize[0] // 2 - plant.width // 2 + offsetX,
y + soilSize[1] // 2 - plant.height // 2 + offsetY,
),
)
#1700 275
#首次添加可收获图片
# 1700 275
# 首次添加可收获图片
if isRipe and isFirstRipe:
ripe = BuildImage(background = g_sResourcePath / "background/ripe.png")
ripe = BuildImage(
background=g_sResourcePath / "background/ripe.png"
)
await img.paste(ripe, (x + soilSize[0] // 2 - ripe.width // 2,
y - ripe.height // 2))
await img.paste(
ripe,
(x + soilSize[0] // 2 - ripe.width // 2, y - ripe.height // 2),
)
isFirstRipe = False
else:
@@ -109,54 +122,71 @@ class CFarmManager:
if isFirstExpansion:
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 img.paste(expansion, (x + soilSize[0] // 2 - expansion.width // 2,
y + soilSize[1] // 2 - expansion.height))
await img.paste(
expansion,
(
x + soilSize[0] // 2 - expansion.width // 2,
y + soilSize[1] // 2 - expansion.height,
),
)
#左上角绘制用户信息
#头像
# 左上角绘制用户信息
# 头像
image = await PlatformUtils.get_user_avatar(uid, "qq")
if image:
avatar = BuildImage(background = image)
avatar = BuildImage(background=image)
await img.paste(avatar, (125, 85))
#头像框
frame = BuildImage(background = g_sResourcePath / "background/frame.png")
# 头像框
frame = BuildImage(background=g_sResourcePath / "background/frame.png")
await img.paste(frame, (75, 44))
#用户名
nameImg = await BuildImage.build_text_image(userInfo['name'], size = 24, font_color = (77, 35, 4))
# 用户名
nameImg = await BuildImage.build_text_image(
userInfo["name"], size=24, font_color=(77, 35, 4)
)
await img.paste(nameImg, (300, 92))
#经验值
# 经验值
level = await g_pDBService.user.getUserLevelByUid(uid)
beginX = 309
endX = 627
#绘制宽度计算公式为 (当前经验值 / 经验值上限) * 宽度
# 绘制宽度计算公式为 (当前经验值 / 经验值上限) * 宽度
width = int((level[2] / level[1]) * (endX - beginX))
await img.rectangle((beginX, 188, beginX + width, 222), (171, 194, 41))
expImg = await BuildImage.build_text_image(f"{level[2]} / {level[1]}", size = 24, font_color = (102, 120, 19))
expImg = await BuildImage.build_text_image(
f"{level[2]} / {level[1]}", size=24, font_color=(102, 120, 19)
)
await img.paste(expImg, (390, 193))
#等级
levelImg = await BuildImage.build_text_image(str(level[0]), size = 32, font_color = (214, 111, 1))
# 等级
levelImg = await BuildImage.build_text_image(
str(level[0]), size=32, font_color=(214, 111, 1)
)
await img.paste(levelImg, (660, 187))
#金币
pointImg = await BuildImage.build_text_image(str(userInfo['point']), size = 24, font_color = (253, 253, 253))
# 金币
pointImg = await BuildImage.build_text_image(
str(userInfo["point"]), size=24, font_color=(253, 253, 253)
)
await img.paste(pointImg, (330, 255))
#点券 TODO
bondsImg = await BuildImage.build_text_image("0", size = 24, font_color = (253, 253, 253))
# 点券 TODO
bondsImg = await BuildImage.build_text_image(
"0", size=24, font_color=(253, 253, 253)
)
await img.paste(bondsImg, (570, 255))
#清晰度
# 清晰度
definition = Config.get_config("zhenxun_plugin_farm", "绘制农场清晰度")
if definition == "medium":
await img.resize(0.6)
@@ -196,9 +226,9 @@ class CFarmManager:
if soilInfo:
if soilInfo["soilLevel"] == 1:
iconPath = g_sResourcePath / f"soil/TODO.png"
iconPath = g_sResourcePath / "soil/TODO.png"
else:
iconPath = g_sResourcePath / f"soil/普通土地.png"
iconPath = g_sResourcePath / "soil/普通土地.png"
if iconPath.exists():
icon = (iconPath, 33, 33)
@@ -211,27 +241,34 @@ class CFarmManager:
totalNumber = "-"
plantNumber = "-"
else:
matureTime = g_pToolManager.dateTime().fromtimestamp(int(soilInfo.get("matureTime", 0))).strftime("%Y-%m-%d %H:%M:%S")
matureTime = (
g_pToolManager.dateTime()
.fromtimestamp(int(soilInfo.get("matureTime", 0)))
.strftime("%Y-%m-%d %H:%M:%S")
)
soilStatus = await g_pDBService.userSoil.getUserSoilStatus(uid, i)
totalNumber = await g_pDBService.userSteal.getTotalStolenCount(uid, i)
totalNumber = await g_pDBService.userSteal.getTotalStolenCount(
uid, i
)
planInfo = await g_pDBService.plant.getPlantByName(plantName)
if not planInfo:
plantNumber = f"None"
plantNumber = "None"
else:
plantNumber = f"{planInfo['harvest'] - totalNumber}"
dataList.append(
[
icon,
i,
plantName,
matureTime,
soilStatus,
totalNumber,
plantNumber,
])
[
icon,
i,
plantName,
matureTime,
soilStatus,
totalNumber,
plantNumber,
]
)
if len(dataList) >= 15:
result = await ImageTemplate.table_page(
@@ -258,7 +295,9 @@ class CFarmManager:
return info
@classmethod
async def drawSoilPlant(cls, uid: str, soilIndex: int) -> tuple[bool, BuildImage, bool, int, int]:
async def drawSoilPlant(
cls, uid: str, soilIndex: int
) -> tuple[bool, BuildImage, bool, int, int]:
"""绘制植物资源
Args:
@@ -273,54 +312,64 @@ class CFarmManager:
soilInfo = await g_pDBService.userSoil.getUserSoil(uid, soilIndex)
if not soilInfo:
return False, None, False, 0, 0 #type: ignore
return False, None, False, 0, 0 # type: ignore
#是否枯萎
# 是否枯萎
if int(soilInfo.get("wiltStatus", 0)) == 1:
plant = BuildImage(background = g_sResourcePath / f"plant/basic/9.png")
plant = BuildImage(background=g_sResourcePath / "plant/basic/9.png")
await plant.resize(0, 150, 212)
return True, plant, False, 0, 0
#获取作物详细信息
plantInfo = await g_pDBService.plant.getPlantByName(soilInfo['plantName'])
# 获取作物详细信息
plantInfo = await g_pDBService.plant.getPlantByName(soilInfo["plantName"])
if not plantInfo:
logger.error(f"绘制植物资源失败: {soilInfo['plantName']}")
return False, None, False, 0, 0 #type: ignore
return False, None, False, 0, 0 # type: ignore
offsetX = plantInfo.get('officX', 0)
offsetY = plantInfo.get('officY', 0)
offsetW = plantInfo.get('officW', 0)
offsetH = plantInfo.get('officH', 0)
offsetX = plantInfo.get("officX", 0)
offsetY = plantInfo.get("officY", 0)
offsetW = plantInfo.get("officW", 0)
offsetH = plantInfo.get("officH", 0)
currentTime = g_pToolManager.dateTime().now().timestamp()
phaseList = await g_pDBService.plant.getPlantPhaseByName(soilInfo['plantName'])
phaseList = await g_pDBService.plant.getPlantPhaseByName(soilInfo["plantName"])
#如果当前时间大于成熟时间 说明作物成熟
if currentTime >= soilInfo['matureTime']:
plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo['plantName']}/{len(phaseList)}.png")
# 如果当前时间大于成熟时间 说明作物成熟
if currentTime >= soilInfo["matureTime"]:
plant = BuildImage(
background=g_sResourcePath
/ f"plant/{soilInfo['plantName']}/{len(phaseList)}.png"
)
return True, plant, True, offsetX, offsetY
else:
#如果是多阶段作物 且没有成熟 #早期思路 多阶段作物 直接是倒数第二阶段图片
# 如果是多阶段作物 且没有成熟 #早期思路 多阶段作物 直接是倒数第二阶段图片
# if soilInfo['harvestCount'] >= 1:
# plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo['plantName']}/{plantInfo['phase'] - 1s}.png")
# return True, plant, False, offsetX, offsetY
#如果没有成熟 则根据当前阶段进行绘制
elapsedTime = currentTime - soilInfo['plantTime']
currentStage = sum(1 for thr in phaseList if elapsedTime >= thr)
# 如果没有成熟 则根据当前阶段进行绘制
elapsedTime = currentTime - soilInfo["plantTime"]
currentStage = currentStage = sum(
1 for thr in phaseList if elapsedTime >= thr
)
if currentStage <= 0:
if plantInfo['general'] == False:
plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo['plantName']}/0.png")
if not plantInfo["general"]:
plant = BuildImage(
background=g_sResourcePath
/ f"plant/{soilInfo['plantName']}/0.png"
)
else:
plant = BuildImage(background = g_sResourcePath / f"plant/basic/0.png")
plant = BuildImage(background=g_sResourcePath / "plant/basic/0.png")
await plant.resize(0, 35 + offsetW, 58 + offsetH)
else:
plant = BuildImage(background = g_sResourcePath / f"plant/{soilInfo['plantName']}/{currentStage}.png")
plant = BuildImage(
background=g_sResourcePath
/ f"plant/{soilInfo['plantName']}/{currentStage}.png"
)
return True, plant, False, offsetX, offsetY
@@ -336,10 +385,10 @@ class CFarmManager:
"收获数量",
"成熟时间(小时)",
"收获次数",
"是否可以上架交易行"
"是否可以上架交易行",
]
#从数据库获取结构化数据
# 从数据库获取结构化数据
seedRecords = await g_pDBService.userSeed.getUserSeedByUid(uid) or {}
if not seedRecords:
@@ -359,18 +408,20 @@ class CFarmManager:
iconPath = g_sResourcePath / f"plant/{seedName}/icon.png"
icon = (iconPath, 33, 33) if iconPath.exists() else ""
sellable = "可以" if plantInfo['sell'] else "不可以"
sellable = "可以" if plantInfo["sell"] else "不可以"
dataList.append([
icon,
seedName,
count,
plantInfo['experience'],
plantInfo['harvest'],
plantInfo['time'],
plantInfo['crop'],
sellable
])
dataList.append(
[
icon,
seedName,
count,
plantInfo["experience"],
plantInfo["harvest"],
plantInfo["time"],
plantInfo["crop"],
sellable,
]
)
except KeyError:
continue
@@ -395,58 +446,61 @@ class CFarmManager:
str: 返回结果
"""
try:
#获取用户的种子数量
# 获取用户的种子数量
count = await g_pDBService.userSeed.getUserSeedByName(uid, name)
if count is None:
count = 0 #如果返回 None,则视为没有种子
count = 0 # 如果返回 None,则视为没有种子
if count <= 0:
return f"没有在你的仓库发现{name}种子,快去买点吧!"
return g_sTranslation["sowing"]["noSeed"].format(name=name)
#如果播种数量超过仓库种子数量
# 如果播种数量超过仓库种子数量
if count < num and num != -1:
return f"仓库中的{name}种子数量不足,当前剩余{count}个种子"
return g_sTranslation["sowing"]["noNum"].format(name=name, num=count)
#获取用户土地数量
# 获取用户土地数量
soilNumber = await g_pDBService.user.getUserSoilByUid(uid)
#如果播种数量为 -1,表示播种所有可播种的土地
# 如果播种数量为 -1,表示播种所有可播种的土地
if num == -1:
num = count
#发送播种前信号
# 发送播种前信号
await g_pEventManager.m_beforePlant.emit(uid=uid, name=name, num=num)
#记录是否成功播种
# 记录是否成功播种
successCount = 0
for i in range(1, soilNumber + 1):
if count > 0 and num > 0:
success = await g_pDBService.userSoil.sowingByPlantName(uid, i, name)
success = await g_pDBService.userSoil.sowingByPlantName(
uid, i, name
)
if success:
#更新种子数量
# 更新种子数量
num -= 1
count -= 1
#记录种子消耗数量
# 记录种子消耗数量
successCount += 1
#发送播种后信号
await g_pEventManager.m_afterPlant.emit(uid=uid, name=name, soilIndex=i)
# 发送播种后信号
await g_pEventManager.m_afterPlant.emit(
uid=uid, name=name, soilIndex=i
)
#确保用户仓库数量更新
# 确保用户仓库数量更新
if successCount > 0:
await g_pDBService.userSeed.updateUserSeedByName(uid, name, count)
#根据播种结果给出反馈
# 根据播种结果给出反馈
if num == 0:
return f"播种{name}成功!仓库剩余{count}个种子"
return g_sTranslation["sowing"]["success"].format(name=name, num=count)
else:
return f"播种数量超出开垦土地数量,已将可播种土地成功播种{name}!仓库剩余{count}个种子"
return g_sTranslation["sowing"]["success2"].format(name=name, num=count)
except Exception as e:
logger.warning(f"播种操作失败!", e=e)
return "播种失败,请稍后重试!"
logger.warning("播种操作失败!", e=e)
return g_sTranslation["sowing"]["error"]
@classmethod
async def harvest(cls, uid: str) -> str:
@@ -463,12 +517,12 @@ class CFarmManager:
soilNumber = await g_pDBService.user.getUserSoilByUid(uid)
harvestRecords = [] #收获日志记录
experience = 0 #总经验值
harvestCount = 0 #成功收获数量
harvestRecords = [] # 收获日志记录
experience = 0 # 总经验值
harvestCount = 0 # 成功收获数量
for i in range(1, soilNumber + 1):
#如果没有种植
# 如果没有种植
if not await g_pDBService.userSoil.isSoilPlanted(uid, i):
continue
@@ -476,21 +530,25 @@ class CFarmManager:
if not soilInfo:
continue
#如果是枯萎状态
# 如果是枯萎状态
if soilInfo.get("wiltStatus", 1) == 1:
continue
plantInfo = await g_pDBService.plant.getPlantByName(soilInfo['plantName'])
plantInfo = await g_pDBService.plant.getPlantByName(
soilInfo["plantName"]
)
if not plantInfo:
continue
currentTime = g_pToolManager.dateTime().now()
matureTime = g_pToolManager.dateTime().fromtimestamp(int(soilInfo['matureTime']))
matureTime = g_pToolManager.dateTime().fromtimestamp(
int(soilInfo["matureTime"])
)
if currentTime >= matureTime:
number = plantInfo['harvest']
number = plantInfo["harvest"]
#处理偷菜扣除数量
# 处理偷菜扣除数量
stealNum = await g_pDBService.userSteal.getTotalStolenCount(uid, i)
number -= stealNum
@@ -499,44 +557,67 @@ class CFarmManager:
continue
harvestCount += 1
experience += plantInfo['experience']
experience += plantInfo["experience"]
harvestRecords.append(f"收获作物:{soilInfo['plantName']},数量为:{number},经验为:{plantInfo['experience']}")
harvestRecords.append(
g_sTranslation["harvest"]["append"].format(
name=soilInfo["plantName"],
num=number,
exp=plantInfo["experience"],
)
)
await g_pDBService.userPlant.addUserPlantByUid(uid, soilInfo['plantName'], number)
await g_pDBService.userPlant.addUserPlantByUid(
uid, soilInfo["plantName"], number
)
#如果到达收获次数上限
if soilInfo['harvestCount'] + 1 >= plantInfo['crop']:
await g_pDBService.userSoil.updateUserSoil(uid, i, "wiltStatus", 1)
# 如果到达收获次数上限
if soilInfo["harvestCount"] + 1 >= plantInfo["crop"]:
await g_pDBService.userSoil.updateUserSoil(
uid, i, "wiltStatus", 1
)
else:
phase = await g_pDBService.plant.getPlantPhaseByName(soilInfo['plantName'])
ts, hc = int(currentTime.timestamp()), soilInfo["harvestCount"] + 1
p1, p2, *rest = phase
await g_pDBService.userSoil.updateUserSoilFields(uid, i,
{
"harvestCount": hc,
"plantTime": ts - p1 - p2,
"matureTime": ts + p2 + sum(rest),
}
phase = await g_pDBService.plant.getPlantPhaseByName(
soilInfo["plantName"]
)
await g_pEventManager.m_afterHarvest.emit(uid=uid, name=soilInfo['plantName'], num=number, soilIndex=i)
ts, hc = (
int(currentTime.timestamp()),
soilInfo["harvestCount"] + 1,
)
p1, p2, *rest = phase
await g_pDBService.userSoil.updateUserSoilFields(
uid,
i,
{
"harvestCount": hc,
"plantTime": ts - p1 - p2,
"matureTime": ts + p2 + sum(rest),
},
)
await g_pEventManager.m_afterHarvest.emit(
uid=uid, name=soilInfo["plantName"], num=number, soilIndex=i
)
if experience > 0:
exp = await g_pDBService.user.getUserExpByUid(uid)
await g_pDBService.user.updateUserExpByUid(uid, exp + experience)
harvestRecords.append(f"\t累计获得经验:{experience}")
harvestRecords.append(
g_sTranslation["harvest"]["exp"].format(
exp=experience,
)
)
if harvestCount <= 0:
return "没有可收获的作物哦~ 不要试图拔苗助长"
return g_sTranslation["harvest"]["no"]
else:
return "\n".join(harvestRecords)
except Exception as e:
logger.warning(f"收获操作失败!", e=e)
return "收获失败,请稍后重试!"
logger.warning("收获操作失败!", e=e)
return g_sTranslation["harvest"]["error"]
@classmethod
async def eradicate(cls, uid: str) -> str:
@@ -554,38 +635,38 @@ class CFarmManager:
experience = 0
for i in range(1, soilNumber + 1):
#如果没有种植
if not await g_pDBService.userSoil.isSoilPlanted(uid, i):
continue
# 如果没有种植
if not await g_pDBService.userSoil.isSoilPlanted(uid, i):
continue
soilInfo = await g_pDBService.userSoil.getUserSoil(uid, i)
if not soilInfo:
continue
soilInfo = await g_pDBService.userSoil.getUserSoil(uid, i)
if not soilInfo:
continue
#如果不是枯萎状态
if soilInfo.get("wiltStatus", 0) == 0:
continue
# 如果不是枯萎状态
if soilInfo.get("wiltStatus", 0) == 0:
continue
experience += 3
experience += 3
if g_bIsDebug:
experience += 999
if g_bIsDebug:
experience += 999
#批量更新数据库操作
await g_pDBService.userSoil.deleteUserSoil(uid, i)
# 批量更新数据库操作
await g_pDBService.userSoil.deleteUserSoil(uid, i)
#铲除作物会将偷菜记录清空
await g_pDBService.userSteal.deleteStealRecord(uid, i)
# 铲除作物会将偷菜记录清空
await g_pDBService.userSteal.deleteStealRecord(uid, i)
await g_pEventManager.m_afterEradicate.emit(uid=uid, soilIndex=i)
await g_pEventManager.m_afterEradicate.emit(uid=uid, soilIndex=i)
if experience > 0:
exp = await g_pDBService.user.getUserExpByUid(uid)
await g_pDBService.user.updateUserExpByUid(uid, exp + experience)
return f"成功铲除荒废作物,累计获得经验:{experience}"
return g_sTranslation["eradicate"]["success"].format(exp=experience)
else:
return "没有可以铲除的作物"
return g_sTranslation["eradicate"]["error"]
@classmethod
async def getUserPlantByUid(cls, uid: str) -> bytes:
@@ -598,14 +679,7 @@ class CFarmManager:
bytes: 返回图片
"""
data_list = []
column_name = [
"-",
"作物名称",
"数量",
"单价",
"总价",
"是否可以上架交易行"
]
column_name = ["-", "作物名称", "数量", "单价", "总价", "是否可以上架交易行"]
plant = await g_pDBService.userPlant.getUserPlantByUid(uid)
@@ -629,23 +703,14 @@ class CFarmManager:
if icon_path.exists():
icon = (icon_path, 33, 33)
if plantInfo['sell'] == True:
if plantInfo["sell"] == True:
sell = "可以"
else:
sell = "不可以"
number = int(count) * plantInfo['price']
number = int(count) * plantInfo["price"]
data_list.append(
[
icon,
name,
count,
plantInfo['price'],
number,
sell
]
)
data_list.append([icon, name, count, plantInfo["price"], number, sell])
result = await ImageTemplate.table_page(
"作物仓库",
@@ -667,30 +732,33 @@ class CFarmManager:
Returns:
str: 返回
"""
#用户信息
# 用户信息
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
stealTime = userInfo.get('stealTime', "")
stealCount = int(userInfo['stealCount'])
stealTime = userInfo.get("stealTime", "")
stealCount = int(userInfo["stealCount"])
if stealTime == "" or not stealTime:
stealTime = g_pToolManager.dateTime().date().today().strftime('%Y-%m-%d')
stealTime = g_pToolManager.dateTime().date().today().strftime("%Y-%m-%d")
stealCount = 5
elif g_pToolManager.dateTime().date().fromisoformat(stealTime) != g_pToolManager.dateTime().date().today():
stealTime = g_pToolManager.dateTime().date().today().strftime('%Y-%m-%d')
elif (
g_pToolManager.dateTime().date().fromisoformat(stealTime)
!= g_pToolManager.dateTime().date().today()
):
stealTime = g_pToolManager.dateTime().date().today().strftime("%Y-%m-%d")
stealCount = 5
if stealCount <= 0:
return "你今天可偷次数到达上限啦,手下留情吧"
return g_sTranslation["stealing"]["max"]
#获取用户解锁地块数量
# 获取用户解锁地块数量
soilNumber = await g_pDBService.user.getUserSoilByUid(target)
harvestRecords: List[str] = []
harvestRecords: list[str] = []
isStealingNumber = 0
isStealingPlant = 0
for i in range(1, soilNumber + 1):
#如果没有种植
# 如果没有种植
if not await g_pDBService.userSoil.isSoilPlanted(target, i):
continue
@@ -698,123 +766,162 @@ class CFarmManager:
if not soilInfo:
continue
#如果是枯萎状态
# 如果是枯萎状态
if soilInfo.get("wiltStatus", 1) == 1:
continue
#作物信息
plantInfo = await g_pDBService.plant.getPlantByName(soilInfo['plantName'])
# 作物信息
plantInfo = await g_pDBService.plant.getPlantByName(soilInfo["plantName"])
if not plantInfo:
continue
currentTime = g_pToolManager.dateTime().now()
matureTime = g_pToolManager.dateTime().fromtimestamp(int(soilInfo['matureTime']))
matureTime = g_pToolManager.dateTime().fromtimestamp(
int(soilInfo["matureTime"])
)
if currentTime >= matureTime:
#如果偷过,则跳过该土地
# 如果偷过,则跳过该土地
if await g_pDBService.userSteal.hasStealed(target, i, uid):
isStealingNumber += 1
continue
stealingNumber = plantInfo['harvest'] - await g_pDBService.userSteal.getTotalStolenCount(target, i)
stealingNumber = plantInfo[
"harvest"
] - await g_pDBService.userSteal.getTotalStolenCount(target, i)
randomNumber = random.choice([1, 2])
randomNumber = min(randomNumber, stealingNumber)
if randomNumber > 0:
await g_pDBService.userPlant.addUserPlantByUid(uid, soilInfo['plantName'], randomNumber)
await g_pDBService.userPlant.addUserPlantByUid(
uid, soilInfo["plantName"], randomNumber
)
harvestRecords.append(f"成功偷到作物:{soilInfo['plantName']},数量为:{randomNumber}")
harvestRecords.append(
g_sTranslation["stealing"]["info"].format(
name=soilInfo["plantName"], num=randomNumber
)
)
isStealingPlant += 1
#如果将作物偷完,就直接更新状态 并记录用户偷取过
if plantInfo['harvest'] - randomNumber + stealingNumber == 0:
#如果作物 是最后一阶段作物且偷完 则直接枯萎
if soilInfo['harvestCount'] + 1 >= plantInfo['crop']:
await g_pDBService.userSoil.updateUserSoil(target, i, "wiltStatus", 1)
# 如果将作物偷完,就直接更新状态 并记录用户偷取过
if plantInfo["harvest"] - randomNumber + stealingNumber == 0:
# 如果作物 是最后一阶段作物且偷完 则直接枯萎
if soilInfo["harvestCount"] + 1 >= plantInfo["crop"]:
await g_pDBService.userSoil.updateUserSoil(
target, i, "wiltStatus", 1
)
else:
phase = await g_pDBService.plant.getPlantPhaseByName(soilInfo['plantName'])
ts, hc = int(currentTime.timestamp()), soilInfo["harvestCount"] + 1
p1, p2, *rest = phase
await g_pDBService.userSoil.updateUserSoilFields(uid, i,
{
"harvestCount": hc,
"plantTime": ts - p1 - p2,
"matureTime": ts + p2 + sum(rest),
}
phase = await g_pDBService.plant.getPlantPhaseByName(
soilInfo["plantName"]
)
await g_pDBService.userSteal.addStealRecord(target, i, uid, randomNumber, int(g_pToolManager.dateTime().now().timestamp()))
ts, hc = (
int(currentTime.timestamp()),
soilInfo["harvestCount"] + 1,
)
p1, p2, *rest = phase
await g_pDBService.userSoil.updateUserSoilFields(
uid,
i,
{
"harvestCount": hc,
"plantTime": ts - p1 - p2,
"matureTime": ts + p2 + sum(rest),
},
)
await g_pDBService.userSteal.addStealRecord(
target,
i,
uid,
randomNumber,
int(g_pToolManager.dateTime().now().timestamp()),
)
else:
await g_pDBService.userSteal.addStealRecord(target, i, uid, randomNumber, int(g_pToolManager.dateTime().now().timestamp()))
await g_pDBService.userSteal.addStealRecord(
target,
i,
uid,
randomNumber,
int(g_pToolManager.dateTime().now().timestamp()),
)
if isStealingPlant <= 0 and isStealingNumber <= 0:
return "目标没有作物可以被偷"
return g_sTranslation["stealing"]["noPlant"]
elif isStealingPlant <= 0 and isStealingNumber > 0:
return "你已经偷过目标啦,请手下留情"
return g_sTranslation["stealing"]["repeat"]
else:
stealCount -= 1
await g_pDBService.user.updateStealCountByUid(uid, stealCount)
await g_pDBService.user.updateStealCountByUid(uid, stealTime, stealCount)
return "\n".join(harvestRecords)
@classmethod
async def reclamationCondition(cls, uid: str) -> str:
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
rec = g_pJsonManager.m_pLevel['reclamation']
rec = g_pJsonManager.m_pLevel["reclamation"]
try:
if userInfo['soil'] >= 30:
return "你已经开垦了全部土地"
if userInfo["soil"] >= 30:
return g_sTranslation["reclamation"]["perfect"]
rec = rec[f"{userInfo['soil'] + 1}"]
level = rec['level']
point = rec['point']
item = rec['item']
level = rec["level"]
point = rec["point"]
item = rec["item"]
str = ""
if len(item) == 0:
str = f"下次开垦所需条件:等级:{level},农场币:{point}"
str = g_sTranslation["reclamation"]["next"].format(
level=level, num=point
)
else:
str = f"下次开垦所需条件:等级:{level},农场币:{point},物品:{item}"
str = g_sTranslation["reclamation"]["next2"].format(
level=level, num=point, item=item
)
return str
except Exception as e:
return "获取开垦土地条件失败!"
except Exception:
return g_sTranslation["reclamation"]["error"]
@classmethod
async def reclamation(cls, uid: str) -> str:
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
level = await g_pDBService.user.getUserLevelByUid(uid)
rec = g_pJsonManager.m_pLevel['reclamation']
rec = g_pJsonManager.m_pLevel["reclamation"]
try:
if userInfo['soil'] >= 30:
return "你已经开垦了全部土地"
if userInfo["soil"] >= 30:
return g_sTranslation["reclamation"]["perfect"]
rec = rec[f"{userInfo['soil'] + 1}"]
levelFileter = rec['level']
point = rec['point']
item = rec['item']
levelFileter = rec["level"]
point = rec["point"]
item = rec["item"]
if level[0] < levelFileter:
return f"当前用户等级{level[0]},升级所需等级为{levelFileter}"
return g_sTranslation["reclamation"]["nextLevel"].format(
level=level[0], next=levelFileter
)
if userInfo['point'] < point:
return f"当前用户农场币不足,升级所需农场币为{point}"
if userInfo["point"] < point:
return g_sTranslation["reclamation"]["noNum"].format(num=point)
#TODO 缺少判断消耗的item
await g_pDBService.user.updateUserPointByUid(uid, userInfo['point'] - point)
await g_pDBService.user.updateUserSoilByUid(uid, userInfo['soil'] + 1)
# TODO 缺少判断消耗的item
await g_pDBService.user.updateUserPointByUid(uid, userInfo["point"] - point)
await g_pDBService.user.updateUserSoilByUid(uid, userInfo["soil"] + 1)
return g_sTranslation["reclamation"]["success"]
except Exception:
return g_sTranslation["reclamation"]["error1"]
return "开垦土地成功!"
except Exception as e:
return "执行开垦失败!"
g_pFarmManager = CFarmManager()
+50 -42
View File
@@ -1,19 +1,15 @@
import math
import plistlib
from itertools import islice
from zhenxun.services.log import logger
from zhenxun.utils._build_image import BuildImage
from zhenxun.utils.image_utils import ImageTemplate
from ..config import g_sResourcePath
from ..config import g_sResourcePath, g_sTranslation
from ..dbService import g_pDBService
from ..json import g_pJsonManager
class CShopManager:
@classmethod
async def getSeedShopImage(cls, filterKey: str|int = 1, num: int = 1) -> bytes:
async def getSeedShopImage(cls, filterKey: str | int = 1, num: int = 1) -> bytes:
"""获取商店页面
Args:
@@ -44,7 +40,7 @@ class CShopManager:
"收获数量",
"成熟时间(小时)",
"收获次数",
"是否可以上架交易行"
"是否可以上架交易行",
]
# 查询所有可购买作物,并根据筛选关键字过滤
@@ -52,10 +48,10 @@ class CShopManager:
filteredPlants = []
for plant in plants:
# 跳过未解锁购买的种子
if plant['isBuy'] == 0:
if plant["isBuy"] == 0:
continue
# 字符串筛选
if filterStr and filterStr not in plant['name']:
if filterStr and filterStr not in plant["name"]:
continue
filteredPlants.append(plant)
@@ -63,7 +59,7 @@ class CShopManager:
totalCount = len(filteredPlants)
pageCount = math.ceil(totalCount / 15) if totalCount else 1
startIndex = (page - 1) * 15
pageItems = filteredPlants[startIndex: startIndex + 15]
pageItems = filteredPlants[startIndex : startIndex + 15]
# 构建数据行
dataList = []
@@ -75,20 +71,22 @@ class CShopManager:
icon = (iconPath, 33, 33)
# 交易行标记
sell = "可以" if plant['sell'] else "不可以"
sell = "可以" if plant["sell"] else "不可以"
dataList.append([
icon,
plant['name'], # 种子名称
plant['buy'], # 种子单价
plant['level'], # 解锁等级
plant['price'], # 果实单价
plant['experience'], # 收获经验
plant['harvest'], # 收获数量
plant['time'], # 成熟时间(小时)
plant['crop'], # 收获次数
sell # 是否可上架交易行
])
dataList.append(
[
icon,
plant["name"], # 种子名称
plant["buy"], # 种子单价
plant["level"], # 解锁等级
plant["price"], # 果实单价
plant["experience"], # 收获经验
plant["harvest"], # 收获数量
plant["time"], # 成熟时间(小时)
plant["crop"], # 收获次数
sell, # 是否可上架交易行
]
)
# 页码标题
title = f"种子商店 页数: {page}/{pageCount}"
@@ -102,7 +100,6 @@ class CShopManager:
)
return result.pic2bytes()
@classmethod
async def buySeed(cls, uid: str, name: str, num: int = 1) -> str:
"""购买种子
@@ -117,31 +114,35 @@ class CShopManager:
"""
if num <= 0:
return "请输入购买数量!"
return g_sTranslation["buySeed"]["notNum"]
plantInfo = await g_pDBService.plant.getPlantByName(name)
if not plantInfo:
return "购买出错!请检查需购买的种子名称!"
return g_sTranslation["buySeed"]["error"]
level = await g_pDBService.user.getUserLevelByUid(uid)
if level[0] < int(plantInfo['level']):
return "你的等级不够哦,努努力吧"
if level[0] < int(plantInfo["level"]):
return g_sTranslation["buySeed"]["noLevel"]
point = await g_pDBService.user.getUserPointByUid(uid)
total = int(plantInfo['buy']) * num
total = int(plantInfo["buy"]) * num
logger.debug(f"用户:{uid}购买{name},数量为{num}。用户农场币为{point},购买需要{total}")
logger.debug(
f"用户:{uid}购买{name},数量为{num}。用户农场币为{point},购买需要{total}"
)
if point < total:
return "你的农场币不够哦~ 快速速氪金吧!"
return g_sTranslation["buySeed"]["noPoint"]
else:
await g_pDBService.user.updateUserPointByUid(uid, point - total)
if not await g_pDBService.userSeed.addUserSeedByUid(uid, name, num):
return "购买失败,执行数据库错误!"
return g_sTranslation["buySeed"]["errorSql"]
return f"成功购买{name},花费{total}农场币, 剩余{point - total}农场币"
return g_sTranslation["buySeed"]["success"].format(
name=name, total=total, point=point - total
)
@classmethod
async def sellPlantByUid(cls, uid: str, name: str = "", num: int = 1) -> str:
@@ -158,11 +159,11 @@ class CShopManager:
plant = await g_pDBService.userPlant.getUserPlantByUid(uid)
if not plant:
return "你仓库没有可以出售的作物"
return g_sTranslation["sellPlant"]["no"]
point = 0
totalSold = 0
isAll = (num == -1)
isAll = num == -1
if name == "":
for plantName, count in plant.items():
@@ -170,16 +171,18 @@ class CShopManager:
if not plantInfo:
continue
point += plantInfo['price'] * count
point += plantInfo["price"] * count
await g_pDBService.userPlant.updateUserPlantByName(uid, plantName, 0)
else:
if name not in plant:
return f"出售作物{name}出错:仓库中不存在该作物"
return g_sTranslation["sellPlant"]["error"].format(name=name)
available = plant[name]
sellAmount = available if isAll else min(available, num)
if sellAmount <= 0:
return f"出售作物{name}出错:数量不足"
await g_pDBService.userPlant.updateUserPlantByName(uid, name, available - sellAmount)
return g_sTranslation["sellPlant"]["error1"].format(name=name)
await g_pDBService.userPlant.updateUserPlantByName(
uid, name, available - sellAmount
)
totalSold = sellAmount
if name == "":
@@ -189,7 +192,7 @@ class CShopManager:
if not plantInfo:
price = 0
else:
price = plantInfo['price']
price = plantInfo["price"]
totalPoint = totalSold * price
@@ -197,8 +200,13 @@ class CShopManager:
await g_pDBService.user.updateUserPointByUid(uid, currentPoint + totalPoint)
if name == "":
return f"成功出售所有作物,获得农场币:{totalPoint},当前农场币:{currentPoint + totalPoint}"
return g_sTranslation["sellPlant"]["success"].format(
point=totalPoint, num=currentPoint + totalPoint
)
else:
return f"成功出售{name},获得农场币:{totalPoint},当前农场币:{currentPoint + totalPoint}"
return g_sTranslation["sellPlant"]["success1"].format(
name=name, point=totalPoint, num=currentPoint + totalPoint
)
g_pShopManager = CShopManager()