🐛 将获取用户基本信息的地方全部转交给Player类

This commit is contained in:
Shu-Ying 2025-10-22 21:58:58 +08:00
parent 1be91147c1
commit 5c043bc0c8
7 changed files with 91 additions and 126 deletions

View File

@ -762,8 +762,10 @@ diuse_farm.shortcut(
@diuse_farm.assign("vipSeed-shop")
async def _(session: Uninfo, res: Match[tuple[str, ...]]):
uid = str(session.user.id)
player = await g_pToolManager.getPlayerByUid(uid)
if not await g_pToolManager.isRegisteredByUid(uid):
if player is None or await player.isRegistered():
await g_pToolManager.repeat()
return
if res.result is inspect._empty:

View File

@ -175,29 +175,25 @@ class CUserDB(CSqlManager):
return level, totalExpNextLevel, currentExp
async def getUserSoilByUid(self, uid: str) -> int:
"""获取用户解锁土地数量
async def updateStealCountByUid(
self, uid: str, stealTime: str, stealCount: int
) -> bool:
"""根据用户Uid更新剩余偷菜次数
Args:
uid (str): 用户Uid
stealTime (str): 偷菜日期
stealCount (int): 新剩余偷菜次数
Returns:
int: 解锁土地数量失败返回-1
bool: 是否更新成功
"""
if not uid:
return -1
if not uid or stealCount < 0:
return False
records = await self.select("user", where={"uid": uid}, columns=["soil"])
if not records:
return -1
try:
soil = int(records[0].get("soil", 3))
except Exception:
soil = 3
return soil
return await self.update(
"user", {"stealTime": stealTime, "stealCount": stealCount}, {"uid": uid}
)
async def updateFieldByUid(self, uid: str, field: str, value) -> bool:
"""更新单字段信息

View File

@ -124,6 +124,10 @@ class CUserSignDB(CSqlManager):
bool: 0: 签到失败 1: 签到成功 2: 重复签到
"""
try:
player = await g_pToolManager.getPlayerByUid(uid)
if not player:
return 0
if not signDate:
signDate = g_pToolManager.dateTime().date().today().strftime("%Y-%m-%d")
@ -233,17 +237,11 @@ class CUserSignDB(CSqlManager):
exp += 9999
# 向数据库更新
currentExp = await g_pDBService.user.getUserExpByUid(uid)
await g_pDBService.user.updateUserExpByUid(uid, currentExp + exp)
currentPoint = await g_pDBService.user.getUserPointByUid(uid)
await g_pDBService.user.updateUserPointByUid(uid, currentPoint + point)
await player.addExp(exp)
await player.addPoint("point", point)
if vipPoint > 0:
currentVipPoint = await g_pDBService.user.getUserVipPointByUid(uid)
await g_pDBService.user.updateUserVipPointByUid(
uid, currentVipPoint + vipPoint
)
await player.addPoint("vipPoint", vipPoint)
return 1
except Exception as e:

View File

@ -2,9 +2,9 @@ import math
from zhenxun.services.log import logger
from ...utils.config import g_bIsDebug
from ...utils.tool import g_pToolManager
from ..dbService import g_pDBService
from ..utils.config import g_bIsDebug
from ..utils.tool import g_pToolManager
from .database import CSqlManager
@ -117,56 +117,6 @@ class CUserSoilDB(CSqlManager):
columns = [description[0] for description in cursor.description]
return dict(zip(columns, row))
@classmethod
async def migrateOldFarmData(cls) -> bool:
"""迁移旧土地数据到新表 userSoil 并删除旧表
Returns:
bool: 如果旧表不存在则返回 False否则迁移并删除后返回 True
"""
# 检查旧表是否存在
cursor = await cls.m_pDB.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='soil'"
)
if not await cursor.fetchone():
return False
async with cls._transaction():
users = await g_pDBService.user.getAllUsers()
for uid in users:
farmInfo = await cls.getUserFarmByUid(uid)
for i in range(1, 31):
key = f"soil{i}"
data = farmInfo.get(key)
if not data:
continue
if data == ",,,4,":
continue
parts = data.split(",")
if len(parts) < 3:
continue
name = parts[0]
pt = int(parts[1])
mt = int(parts[2])
await cls.m_pDB.execute(
"""
INSERT INTO userSoil
(uid,soilIndex,plantName,plantTime,matureTime,harvestCount)
VALUES (?,?,?,?,?,?)
""",
(uid, i, name, pt, mt, 0),
)
await cls.m_pDB.execute("DROP TABLE soil")
logger.info("数据库迁移完毕!")
return True
@classmethod
async def insertUserSoil(cls, soilInfo: dict):
"""插入一条新的 userSoil 记录

View File

@ -33,9 +33,6 @@ class CDBService:
self.userSign = CUserSignDB()
await self.userSign.initDB()
# 迁移旧数据库
await self.userSoil.migrateOldFarmData()
async def cleanup(self):
await self.plant.cleanup()

View File

@ -53,10 +53,9 @@ class CFarmManager:
if not player:
return g_sTranslation["basic"]["error"]
p = player.user.get("point", 0)
await player.addPoint("point", point + p)
await player.addPoint("point", int(point))
return f"充值{point}农场币成功,手续费{tax}金币,当前农场币:{point + p}"
return f"充值{point}农场币成功,手续费{tax}金币,当前农场币:{player.user.get('point', 0)}"
@classmethod
async def drawFarmByUid(cls, uid: str) -> bytes:
@ -869,7 +868,7 @@ class CFarmManager:
return g_sTranslation["stealing"]["max"]
# 获取用户解锁地块数量
soilNumber = await g_pDBService.user.getUserSoilByUid(target)
soilNumber = player.user.get("soil", 3)
harvestRecords: list[str] = []
isStealingNumber = 0
isStealingPlant = 0
@ -974,7 +973,7 @@ class CFarmManager:
else:
stealCount -= 1
await g_pDBService.user.updateStealCountByUid(uid, stealTime, stealCount)
await player.updateStealCountByUid(uid, stealTime, stealCount)
return "\n".join(harvestRecords)
@ -988,14 +987,16 @@ class CFarmManager:
Returns:
str: 返回条件文本信息
"""
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
rec = g_pJsonManager.m_pLevel["reclamation"]
player = await g_pToolManager.getPlayerByUid(uid)
if not player:
return g_sTranslation["basic"]["error"]
try:
if userInfo["soil"] >= 30:
if player.user["soil"] >= 30:
return g_sTranslation["reclamation"]["perfect"]
rec = rec[f"{userInfo['soil'] + 1}"]
rec = rec[f"{player.user['soil'] + 1}"]
level = rec["level"]
point = rec["point"]
@ -1025,16 +1026,18 @@ class CFarmManager:
Returns:
str: _description_
"""
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
level = await g_pDBService.user.getUserLevelByUid(uid)
player = await g_pToolManager.getPlayerByUid(uid)
if not player:
return g_sTranslation["basic"]["error"]
level = await player.getUserLevel()
rec = g_pJsonManager.m_pLevel["reclamation"]
try:
if userInfo["soil"] >= 30:
if player.user["soil"] >= 30:
return g_sTranslation["reclamation"]["perfect"]
rec = rec[f"{userInfo['soil'] + 1}"]
rec = rec[f"{player.user['soil'] + 1}"]
levelFileter = rec["level"]
point = rec["point"]
@ -1045,12 +1048,12 @@ class CFarmManager:
level=level[0], next=levelFileter
)
if userInfo["point"] < point:
if player.user["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)
await player.subPoint("point", point)
await player.updateField("soil", player.user["soil"] + 1)
return g_sTranslation["reclamation"]["success"]
except Exception:
@ -1116,9 +1119,11 @@ class CFarmManager:
Returns:
str:
"""
userInfo = await g_pDBService.user.getUserInfoByUid(uid)
soilInfo = await g_pDBService.userSoil.getUserSoil(uid, soilIndex)
player = await g_pToolManager.getPlayerByUid(uid)
if not player:
return g_sTranslation["basic"]["error"]
soilInfo = await g_pDBService.userSoil.getUserSoil(uid, soilIndex)
if not soilInfo:
return g_sTranslation["soilInfo"]["error"]
@ -1132,9 +1137,9 @@ class CFarmManager:
fileter = g_pJsonManager.m_pSoil["upgrade"][soilLevelText][countSoil]
getters = {
"level": (await g_pDBService.user.getUserLevelByUid(uid))[0],
"point": userInfo.get("point", 0),
"vipPoint": userInfo.get("vipPoint", 0),
"level": (await player.getUserLevel())[0],
"point": player.user.get("point", 0),
"vipPoint": player.user.get("vipPoint", 0),
}
requirements = {
@ -1159,11 +1164,8 @@ class CFarmManager:
await g_pDBService.userSoil.matureNow(uid, soilIndex)
# 更新数据库字段
point = userInfo.get("point", 0) - fileter.get("point", 0)
await g_pDBService.user.updateUserPointByUid(uid, point)
vipPoint = userInfo.get("vipPoint", 0) - fileter.get("vipPoint", 0)
await g_pDBService.user.updateUserVipPointByUid(uid, vipPoint)
await player.subPoint("point", fileter.get("point", 0))
await player.subPoint("vipPoint", fileter.get("vipPoint", 0))
return g_sTranslation["soilInfo"]["success"].format(
name=await g_pDBService.userSoil.getSoilLevelText(soilLevel),
@ -1173,21 +1175,21 @@ class CFarmManager:
@classmethod
async def pointToVipPointByUid(cls, uid: str, num: int) -> str:
"""点券兑换
num:用户传参,即将兑换的点券
pro:兑换倍数;兑换倍数乘以num即为需要消耗的农场币
Args:
uid (str): 用户Uid
num (int): 兑换点券数量
Returns:
str: 返回结果
兑换比例在配置文件中配置
目前配置文件中默认是20倍
100点券需要20000农场币
赠送点券规则
小于2000点券0
2000-5000点券100
5000-50000点券280
大于50000点券3000
兑换比例在配置文件中配置
目前配置文件中默认是20倍
100点券需要20000农场币
赠送点券规则
小于2000点券0
2000-5000点券100
5000-50000点券280
大于50000点券3000
"""
if num < 100:
return "点券兑换数量必须大于等于100"
@ -1195,12 +1197,14 @@ class CFarmManager:
pro = int(Config.get_config("zhenxun_plugin_farm", "点券兑换倍数"))
pro *= num
point = await g_pDBService.user.getUserPointByUid(uid)
player = await g_pToolManager.getPlayerByUid(uid)
if not player:
return g_sTranslation["basic"]["error"]
point = player.user.get("point", 0)
if point < pro:
return f"你的农场币不足,当前农场币为{point},兑换还需要{pro - point}农场币"
p = await g_pDBService.user.getUserVipPointByUid(uid)
giftPoints: int
if num < 2000:
giftPoints = 0
@ -1211,11 +1215,9 @@ class CFarmManager:
else:
giftPoints = 3000
number = num + p + giftPoints
await g_pDBService.user.updateUserVipPointByUid(uid, int(number))
point -= pro
await g_pDBService.user.updateUserPointByUid(uid, int(point))
number = num + giftPoints
await player.addPoint("vipPoint", number)
await player.subPoint("point", pro)
return f"兑换{num}点券成功,当前点券:{number},赠送点券:{giftPoints},当前农场币:{point}"

View File

@ -185,7 +185,27 @@ class CPlayer:
return await g_pDBService.user.getUserLevelByUid(uid)
async def updateField(self, field: str) -> bool:
async def updateStealCountByUid(
self, uid: str, stealTime: str, stealCount: int
) -> bool:
"""根据用户Uid更新剩余偷菜次数
Args:
uid (str): 用户Uid
stealTime (str): 偷菜日期
stealCount (int): 新剩余偷菜次数
Returns:
bool: 是否更新成功
"""
uid = self.user.get("uid", "")
if uid == "":
return False
return await g_pDBService.user.updateStealCountByUid(uid, stealTime, stealCount)
async def updateField(self, field: str, value) -> bool:
"""更新单字段信息
Returns:
@ -196,4 +216,4 @@ class CPlayer:
if uid == "":
return False
return await g_pDBService.farm.updateFarmFieldByUid(uid)
return await g_pDBService.user.updateFieldByUid(uid, field, value)