🐛 将获取用户基本信息的地方全部转交给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") @diuse_farm.assign("vipSeed-shop")
async def _(session: Uninfo, res: Match[tuple[str, ...]]): async def _(session: Uninfo, res: Match[tuple[str, ...]]):
uid = str(session.user.id) 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 return
if res.result is inspect._empty: if res.result is inspect._empty:

View File

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

View File

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

View File

@ -2,9 +2,9 @@ import math
from zhenxun.services.log import logger from zhenxun.services.log import logger
from ...utils.config import g_bIsDebug
from ...utils.tool import g_pToolManager
from ..dbService import g_pDBService from ..dbService import g_pDBService
from ..utils.config import g_bIsDebug
from ..utils.tool import g_pToolManager
from .database import CSqlManager from .database import CSqlManager
@ -117,56 +117,6 @@ class CUserSoilDB(CSqlManager):
columns = [description[0] for description in cursor.description] columns = [description[0] for description in cursor.description]
return dict(zip(columns, row)) 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 @classmethod
async def insertUserSoil(cls, soilInfo: dict): async def insertUserSoil(cls, soilInfo: dict):
"""插入一条新的 userSoil 记录 """插入一条新的 userSoil 记录

View File

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

View File

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

View File

@ -185,7 +185,27 @@ class CPlayer:
return await g_pDBService.user.getUserLevelByUid(uid) 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: Returns:
@ -196,4 +216,4 @@ class CPlayer:
if uid == "": if uid == "":
return False return False
return await g_pDBService.farm.updateFarmFieldByUid(uid) return await g_pDBService.user.updateFieldByUid(uid, field, value)