diff --git a/.gitignore b/.gitignore index fa8902370..0bc31adac 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ QWEN.md Client/.claude/ dev-ab-svr/debugconfig.json /Client/.uloop/ +/Client/.codex/ +/CodexOutput/ + diff --git a/CodexOutput/upserver/101真实玩法与迁移档恢复业务包-待评审-2026-09-28.md b/CodexOutput/upserver/101真实玩法与迁移档恢复业务包-待评审-2026-09-28.md deleted file mode 100644 index d5b99ae96..000000000 --- a/CodexOutput/upserver/101真实玩法与迁移档恢复业务包-待评审-2026-09-28.md +++ /dev/null @@ -1,67 +0,0 @@ -# 101真实玩法与迁移档恢复:完整业务包方案 - -2026-09-28,主会话;状态:待一次完整独立方案评审。**目标:101已导入的历史档能真实登录,完成一次普通抛竿、拉杆收鱼、收下奖励,保存并在新Unity进程恢复。** 本方案默认生产代码零改动,复用已关闭4C2的运行入口。不能把102已成功视为101也已通过。 - -## 1. 范围与执行方式 - -- 一个业务包包含准备、登录、玩法、保存、正常退出、重启恢复及对账;不再把备份、许可、运行准备各自拆成独立评审阶段。 -- 完整方案评审后由主会话核相关hash、逐条裁决;取得本包一次运行授权后连续执行。一次授权覆盖下述备份、两个游戏进程和最多一次付费抛竿,不逐步重新申请。需用户手动操作或启动CLI时只请求必要协作。 -- 内部检查点写开发日志。完成后一次汇总交付复核;发现明确超出本方案的业务改动,才提交针对性补充方案。 -- 固定 `http://s101.local:18080/`,仅Unity CLI Loop,不用UnitySkills、不打包。游戏只用101,102仅现有备份工具附带登录/Get,不在游戏使用或写102。 -- 不重导、不合并、不补发、不更改引导/活动/随机鱼/装备以绕过门。生产源码、配置、场景、预制体均不改;允许在本业务证据目录保存只读采样脚本、命令结果、许可归档和对账结果,不新增通用框架。 - -## 2. 已知事实和前提 - -导入已由 [D5裁决](P2AlphaImport101/D5-执行复核裁决与关闭.md) 限定关闭。历史参考是 `P2AlphaImport101/runs/20260928T073630Z-345b3ee1f47a419abf876bf5b5506d89/after.json`,55键逐值等于固定PF源。该文件只用于对比,不直接作为游戏permit的backupPath:现有许可要求备份位于 `KVGameplayLoopTests` 下。 - -同run/account.json证明NewlyCreated=false、InternalId=2、CreateTimeUtc=2026-09-16T12:58:05.860603Z;不能当成刚创建的新玩家。历史主档等级62、金币36550472、体力7275、装备20001、地图102、倍率索引3;实际倍率、活动和玩法资格必须在运行时读取,不能根据旧档推定。FishingChallengeData历史值为字符串null;两类历史空态兼容已经通过独立复核。 - -`KVGameplayLoopSetup`已有101/102许可支持;v3负责一次钓鱼,v1负责恢复登录。游戏登录仍先执行PF身份登录,再执行s101登录和KV加载,存在PF域名解析依赖;不能宣称本包游戏完全不访问PF。PF存档写入不在本包授权范围,发现即停止并调查。恢复登录可能产生既有登录保存/跨日写,不能称整个恢复进程只读。 - -## 3. 备份、许可与数据边界 - -复用锁定的 `P2AlphaImport101/D1-bin/Preflight.dll --backup-101-102`,从项目根运行。DLL SHA256=`AAA1276630E8633C131072DDF638639B92F60134A0425E17616A4A5A2A436607`,355328字节。禁止调用任何import分支。每轮备份为101/102各1登录+1Get,无KV Set/Delete;登录自身仍有账号元数据副作用。 - -计划四轮完整备份:S0游戏前、S1登录稳定且尚未抛竿、S2收下并正常退出后、S3新进程恢复并正常退出后。成功路径合计8登录+8Get用于备份,另计两次游戏登录、游戏加载Get和所有实际保存Set;分开记录,不能把工具计数当游戏总请求数。失败只补必要的一轮状态取证,不自动重复业务动作。 - -S0必须55键与D导入after原值一致,身份/关键档/配置匹配且解码有效;不一致则保留现状,说明差异后停止本次既定运行,不覆盖历史进度。保存S0原件、hash、键表。v3许可使用S0下101.json和它的55键集合;这是允许现有登录链访问/保存已备份键的上限,不是允许点击55种业务。新键写入保持原拒绝规则。 - -允许的游戏动作只有登录、一次普通付费钓鱼、收下、退出。钓鱼期间保留现有更严格写门:NewPlayerDataDic、实际地图鱼档Map_5_{area}、BattlePassRecordTask、MiniBPKeyNew、EventLuckGameRecord、EventLuckMagicPlayfabData,且必须在S0键集中。S0→S1的登录规范化/跨日差异单列来源,不混为钓鱼奖励;出现无法解释的键变化或写入则停止,不扩大白名单。未知/未消费键应原样保持。 - -用户运行确认时需保持101其他客户端停用直至本包结束;不沿用已结束的导入15分钟窗口。102不要求停用,其附带快照只报告观测值,不能把其他客户端可能产生的变化归于本次101游戏。 - -## 4. 连续执行步骤(内部检查点,不是五次评审) - -| 检查点 | 连续执行内容 | 通过证据 | -|---|---|---| -| 0 开始 | 裁决方案、记录本包授权;核焦点hash、实际API、Unity空闲/无活动permit;保存旧claims清单;读取S0。使用无旧本包claim的新进程,必要时正常关闭旧进程再启动。 | 批准范围、S0、进程身份、原claims、CLI状态齐全。 | -| 1 首次登录 | PrepareFishingRewardPermit(101,S0,55键);一次Play,等待登录/受控加载/首页稳定。禁止先操作签到或抛竿。采样游戏状态、准入环境、保存状态,读取S1并完成登录差异归因。 | Ready=true/Error为空、加载成功;登录保存确认;S1与运行时主档相符。 | -| 2 一次玩法 | 主会话完成动作前采样后才通知用户:手动抛竿→拉杆→收鱼,成功停在奖励界面;失败不重试。记录实际鱼/装备/地图/倍率、扣费和奖励票据、奖励画面/数据后,再协作点击收下返回首页。 | 仅一次付费动作;原扣费票据确认;fishing-reward-confirmed先于presented;收下回首页;原票据与最终值可关联。 | -| 3 保存退出 | 等既有保存确认,经QuitStage正常退出并确认closed/drained;归档v3许可,保留claim。取得S2并对账,再正常关闭Unity、确认旧进程已退出。 | 不靠强制Stop/杀进程模拟退出;未确认票据为0或有明确失败终态;S1→S2业务差异可解释。 | -| 4 重启恢复 | 新进程、S2的101备份建立v1许可,登录且不操作玩法/领奖/装备;核对恢复值,再正常退出,取得S3、归档许可和证据,汇总交付。 | 恢复金币/体力/鱼档/任务进度与S2一致;登录附带变化单独归因,最终无活动permit、旧新claims保留。 | - -进程退出有场景保存对话框时请用户处理,不强杀;CLI未连接时请用户Start Server,不无限轮询。这些是执行协作,不追加方案轮次。游戏失败后的安全退出也走已有保存/drain;不能为了凑齐闭环重建许可重扣一次费用。 - -## 5. 必须保留的准入与失败处理 - -复用 `UserService.KVFishingReward.cs` 的全部实际门:普通付费鱼、非免费/重试/决斗/固定列表/活动类型,无特殊鱼技能;无冲突引导、巡游/收集目标/存钱罐/砍价/进行中挑战,频次与倍率/刺鱼解锁合格;事件配置和Guidance投影匹配。自然鱼只在动作中选择,事先不能保证抽中合格鱼;拦截照常停止,不能修改随机结果。 - -PF解析失败、账号不符、加载失败、配置漂移、准入拒绝、并发迹象、Set失败/Unknown或写门拒绝:保存现有日志和快照,停止后续玩法。扣费已确认而奖励失败则如实记账,不自动补发/重试。服务器结果不明不重放Set。快照也失败则明确证据缺口,不当作没写入。恢复失败不把S0重新导入。 - -本方案不授权任意故障修复代码。若查明必须改业务逻辑,集中记录实际阻塞及最小差异,完整评审补充后再改;一般CLI参数、证据采样或日志路径修正按原范围处理并记日志,不单独开方案。 - -## 6. 验收和交付 - -1. 101实际加载既有55键档,关键运行时数据与S1一致;历史null不再抛异常;未回退空档/PF旧进度。 -2. S1是在动作前冻结;S1→S2核对体力/消费累计、金币、鱼数量/重量、钓鱼次数和实际任务变化,关联扣费/奖励票据与服务器结果。获取到公式输入才做独立重算;缺项如实列明,不能用同一结果自证公式正确。 -3. 奖励确认后显示,收下真实回首页;S2保存成立,新进程恢复成立,S3差异有归因。登录跨日变化不能掩盖玩法未保存。 -4. 无第二次付费、无导入/覆盖102、无放宽门/删claim/打包;所有非预期业务操作(如误点签到)记录,不能标成纯净单动作验证。 -5. 一份交付记录汇总实际命令、进程、4快照、票据/日志/关键截图、逐键对账、授权与边界、缺口;一次独立执行复核后主会话关闭。本包最多证明101这条真实链,不代表26模块外键、全活动、热换号、完整4B3B/C或G4完成。 - -证据放在 `CodexOutput/upserver/Gameplay101Validation/`,运行产生的原有permit/run/backup沿用现有目录并在交付索引引用,不复制庞大历史材料。受审hash仅冻结本方案、直接依赖及历史参考,见同目录 `review-hashes.json`;共享状态/日志不纳入冻结清单,更新检查点无需滚动重封全部项目。 - -## 7. 交给评审AI的提示词 - -请独立审查本完整业务包,先核 `Gameplay101Validation/review-hashes.json`,再核对涉及源码与4C2既有闭环。重点检查:101既有账号与55键备份;v3/v1边界;PF身份依赖;登录写和钓鱼写的区别;动作前S1;一次扣费与奖励/退出确认;新进程恢复;备份工具附带102只读;失败后不重导/重放/绕过准入。 - -给出通过/有条件通过/不通过,逐条问题、严重级别、依据与最小修订。只将真实阻断项作为开工条件,不因文档样式或内部检查点另设实施前复核阶段。只读审查,不运行Unity或正式接口,不修改主会话共享文档。请只落盘 `Gameplay101Validation/完整业务包独立方案审查.md`。此次没有新生产代码,方案批准后直接连续运行并统一复核;不得假设未知运行结果已经成立。 diff --git a/CodexOutput/upserver/3C补修复终审裁决与4A准入-2026-09-23.md b/CodexOutput/upserver/3C补修复终审裁决与4A准入-2026-09-23.md deleted file mode 100644 index ea7836cd0..000000000 --- a/CodexOutput/upserver/3C补修复终审裁决与4A准入-2026-09-23.md +++ /dev/null @@ -1,44 +0,0 @@ -# 3C补修复终审裁决与4A准入 - -日期:2026-09-23。主会话裁决。用户指令:“复核完成,继续下一步”。 - -## 1. 3C正式结论 - -**接受用户指定外部AI的实施复核,R1–R5关闭,3C通过,阶段3(G3)恢复关闭。** - -依据:[阶段3C补修复独立实施复核](阶段3C补修复独立实施复核-2026-09-23.md),报告SHA256为D39DAE878C48F9987C7BE6F1788927491B010D9CBCF4B188D25CF4ADD7668C19。 - -本轮重新计算了repair-final-source-hashes.json内全部10项:测试宿主Program、csproj及8份生产源码均匹配。Program完整SHA256为66C41B8B0A8E0CD4FF13A3BED8212B3F61BF95E4707F5C6373B235E21B20492A。报告首行缩写hash有笔误,以同格完整hash及本轮实际重算为准,不修改外部报告原文。 - -| 项目 | 裁决 | -|---|---| -| R1 实际收尾和自动清理门 | 关闭:linked CTS、等待body/Close、不确定原运行禁止自动cleanup;失败后不等未结束票据挡住Close | -| R2 manifest与路径边界 | 关闭:严格schema/重复字段、固定账号/精确key/run绑定、拒绝路径和链接、登录前验证 | -| R3 原始结果不可升级/覆盖 | 关闭:持久化原判、CreateNew原产物、补清理独立结果 | -| R4 值隔离/Owner重建/Delete实测 | 关闭:精确值、新Cookie/Owner、102后读101、删除前存在 | -| R5 组合故障与诊断缺项 | 关闭:真实C子进程Get、Unknown不重发、主档异常策略和真实状态诊断 | -| F2 外部实施复核 | 完成:外部复核接受、无新P1/P2、逐项矩阵确认,并独立复跑8/8与42/86/29 | - -接受外部复核关于Unity证据仍有效的裁决:最终变化仅在Unity工程外测试宿主,8份生产源码未变;外部已对最终版本独立复跑生产回归。正式run已清理,无需为了本次文档裁决重复访问正式服。 - -三项P3按非阻塞观察保留: - -1. Latest-*.log是可覆盖指针,per-run结果才是不可变证据。 -2. runs含故意损坏的离线负例,通用扫描必须区分,不能把解析错误当正式遗留。 -3. Confirm只在成功Flush后等待已终结票据;后续改动不得破坏此前提。 - -## 2. 4A准入结果 - -**3C前置门已满足;4A原设计审查继续有效。开工检查新发现构建文件白名单遗漏,先做最小差异评审,尚不修改代码。** - -已审设计要求新增独立PlayerKVLocalReadResult.cs,并让PlayerKVSessionOwner引用它。现有3个链接Owner的独立csproj使用显式Compile清单,没有该新增依赖。按原白名单只改生产Owner后,这些测试项目无法解析新结果类型,A12回归不能完成。 - -静态证据:[4A开工依赖核对](阶段4A开工依赖核对-2026-09-23.json)。尚未修改源码或制造编译失败;这是构建依赖推导,不是现有3C缺陷,不撤销3C通过。 - -任务书明确规定:“发现接口缺口先落盘差异方案并评审,不能临时扩展文件白名单。”本次需要增加3个csproj白名单,故不把用户“继续”解释为免除其规定的设计差异审查。 - -下一步只评审 [4A构建依赖最小差异方案](阶段4A构建依赖最小差异方案-2026-09-23.md)。通过并裁决后,本会话直接按4A检查点实施,不重做整套设计评审。 - -## 3. 仍然保持的范围 - -4A只做会话桥接和Owner安全只读接口,合成传输验证A1–A12;不接UserService/PlayFabMgr/玩法、不改服务器/包、不删SDK、不访问正式业务KV、不打包。正式API仍为http://s101.local:18080/。游戏真实存档迁移仍须4B/4C及后续验收。 \ No newline at end of file diff --git a/CodexOutput/upserver/3C补验收与4A方案审查裁决-2026-09-23.md b/CodexOutput/upserver/3C补验收与4A方案审查裁决-2026-09-23.md deleted file mode 100644 index 93be99acf..000000000 --- a/CodexOutput/upserver/3C补验收与4A方案审查裁决-2026-09-23.md +++ /dev/null @@ -1,49 +0,0 @@ -# 3C补验收与4A方案审查裁决 - -日期:2026-09-23。裁决者:主会话。依据:《3C补验收与4A方案独立审查-2026-09-23.md》。本轮确认审查并同步文档,未修改代码、未执行测试或访问正式服。 - -## 1. 审查版本核对 - -在修改方案文档前核验以下SHA256,与独立审查记录全部一致: - -| 对象 | SHA256 | -|---|---| -| 3C复核更正与补验收 | `20CEA4BA6B274BBD108E7B931DAE5FCEDF457D0A803A0343622A33D274DFBFD5` | -| 阶段4分期与4A方案 | `4A04700D9CA97992C6E0D25B2614DFA7AF6EECD99EFC4C3756FC134704C28D06` | -| 4A待审任务书 | `AF2E5217FE1DA1DFFCBC89CF707BE37EFCCEA89358C61768C824976673686F8E` | -| 3C Program.cs | `3C89DA087AA3841ADBA79A11BB2BAC724FD8F5F429D2124F826185EBBDDA64DA` | - -本文裁决后的方案修订会改变文档hash,不影响上述已审版本的追溯。独立审查原文保持不变。 - -## 2. 双裁决 - -- **A:3C修复设计通过,批准按限定范围实施修复。** R1/P1、R2/P1、R3/P2、R4/P2、R5/P2全部确认成立,目前仍未修复,不恢复3C/G3通过。 -- **B:4A设计通过,编码暂不放行。** 设计无新增P1/P2,必须先完成3C修复、逐行补验收和用户指定外部AI复核,再完成主会话裁决并批准4A任务书。 -- 原运行、回归和Unity历史证据保留,不等于修复后复验结果;当前无正式数据损坏的实测证据。 - -## 3. 六项P3逐条裁决 - -| 编号 | 裁决 | 实施说明 | -|---|---|---| -| A-S1 | 采纳 | 正式编排建立linked CTS,传递到登录/Owner/直接传输,超时后停止接收后续变更、请求取消并等待全部操作与Close真正收尾。取消是请求,不能假设忽略取消的Handler已结束;测试用闸门证明顺序。超时/Unknown的原运行仍禁止自动cleanup,即使本地传输已收尾;只有后续显式cleanup可尝试补救。 | -| A-S2 | 采纳 | manifest持久保存原运行断言状态、最终结果和不确定状态;尚未完成也不得按成功处理。原result/log不可覆写。补cleanup生成独立产物,只更新清理事实,不把原失败或未完成运行升级为通过。 | -| A-S3 | 采纳 | 用拒绝重复JSON属性的JObject严格解析,再逐字段白名单/类型映射;读取前验证路径,登录前完成全部schema/key/路径校验。合法cleanup输出待删key的SHA256清单,不回显明文,不额外增加用户确认步骤。 | -| B-S1 | 采纳 | 在A2/A3增加初始Get/Create失败后重开验证:失败owner完成收尾后清空桥接活动位;后续合法Open可用。若Close失败,保留关闭失败状态,不能无条件清空并继续Open。 | -| B-S2 | 采纳 | A8增加ReadLocalSnapshot与在途Flush并发:验证baseline→pending→localOnly合并视图,且读取不改变在途批次或发送次数。 | -| B-S3 | 采纳 | 同时存在归属失效/关闭与非Ready时,`StaleOrClosing`优先于`NotReady`;读取前、读取后及处理NotReady时均按该优先级检查。 | - -以上是现有方案澄清,不扩展架构或修改范围;无需为了这些已裁决P3单独再开一轮设计审查。修复实施后的独立复核仍是强制门。 - -## 4. 优先级和边界 - -R3严重度保留P2,但执行优先级按P1处理,与R1/R2同为正式服重跑前的阻塞项。实施顺序保持R2→R1/R3→R4/R5→离线验证和限定源码审查→新正式正常路径→回归/Unity/逐行证据→外部复核。 - -3C仅允许修改`CodexOutput/upserver/KVStage3CTests/Program.cs`、必要时其csproj、新增该目录证据,主会话维护实施记录和入口文档。不得修改生产代码、既有42/86/29测试、服务器、游戏入口或Unity项目配置。旧run证据只读保留。 - -正式API固定`http://s101.local:18080/`,账号101/102仅使用本次manifest登记fixture;离线安全门通过后才能显式执行新正式run,正式服不制造故障。 - -4A文件白名单仍由其任务书约束,本裁决不提前允许修改Owner或新增生产桥接类。 - -## 5. 下一步 - -下一步由主会话实施3C R2及R1/R3安全修复,逐个检查点保存开发日志;在补验收和外部复核完成前,状态保持“3C修复进行/待验收,4A设计已通过待前置”。 diff --git a/CodexOutput/upserver/3C补验收与4A方案独立审查-2026-09-23.md b/CodexOutput/upserver/3C补验收与4A方案独立审查-2026-09-23.md deleted file mode 100644 index 1ab7fc415..000000000 --- a/CodexOutput/upserver/3C补验收与4A方案独立审查-2026-09-23.md +++ /dev/null @@ -1,75 +0,0 @@ -# 3C补验收与4A方案独立审查 - -日期:2026-09-23。审查者:用户指定的独立审查AI(ZCode会话)。性质:只读审查,仅新增本文件;未修改代码、共享入口文档,未访问正式服,未使用子Agent。 - -## 审查对象SHA256 - -| 文件 | SHA256 | -|---|---| -| `阶段3C复核更正与补验收-2026-09-23.md` | `20CEA4BA6B274BBD108E7B931DAE5FCEDF457D0A803A0343622A33D274DFBFD5` | -| `阶段4存档接线分期与4A方案-2026-09-23.md` | `4A04700D9CA97992C6E0D25B2614DFA7AF6EECD99EFC4C3756FC134704C28D06` | -| `阶段4A实施任务书-待评审-2026-09-23.md` | `AF2E5217FE1DA1DFFCBC89CF707BE37EFCCEA89358C61768C824976673686F8E` | -| `KVStage3CTests/Program.cs` | `3C89DA087AA3841ADBA79A11BB2BAC724FD8F5F429D2124F826185EBBDDA64DA`(与更正文档记录一致,即上一轮终验所验收版本) | - -## 双裁决摘要 - -- **裁决A(3C复核更正与修复设计):通过。** R1–R5五项发现全部有源码依据,严重度评定恰当;修复任务书方向足够,附3项P3补充(A-S1~A-S3)。补验收完成前3C不得恢复"通过"。 -- **裁决B(4A方案可实施性):通过。** 接口租约、桥接所有权、Close屏障、旧句柄失效、取消语义均正确且在现有生产接口内可实现;A1–A12覆盖充分,附3项P3补充(B-S1~B-S3)。**4A编码批准仍被3C补验收前置门阻塞**(任务书前置门已正确列出)。 - -无新发现的P1/P2(R1–R5系对既有代码的确认,非本审查新增缺陷)。 - -## A:3C复核与补验收——R1–R5逐条确认 - -**R1/P1:确认成立。** 源码:`Program.cs:533` `action().WaitAsync(TimeSpan.FromSeconds(20))`仅取消等待不终止任务;`Live()`的L1/L2经`Run`包装(行283/287);`LiveAccount`内`CreateAsync(..., default, ...)`(行310)无生命周期token,无外部取消通路;超时后孤儿任务继续在途变更,而`finally`的`CleanupCore`(行296–301)与其并发;`HadUnknownWrite`由孤儿路径置位(行319–320)可能晚于`WriteArtifacts`。触发:正式网络慢于20s的组合步骤。影响:清理与迟到写重叠、结果文件失真。P1恰当。 - -**R2/P1:确认成立。** 源码:`ValidateManifest`(行516–523)——`!k.StartsWith(m.Prefix)`在Prefix为空串时恒真;Prefix无格式约束(任意前缀+以其开头的任意≤128键均可过);keys无唯一性与精确后缀校验;`RunDirectory/CacheRoot`仅要求`InsideRuns`未绑定与manifest同一run;`InsideRuns`(行525–529)不拒绝重解析点/链接;`JsonConvert.DeserializeObject`不拒绝重复JSON属性与未知字段。触发:被篡改/损坏的manifest+操作者运行`--cleanup`。影响:可授权删除非fixture key(含业务key)。P1恰当。 - -**R3/P2:确认成立。** 源码:`CleanupCore`行363 `Completed = !HadUnknownWrite && CleanedAccounts==2`,不依据断言失败;`Cleanup`(行332–341)独立进程以`failed=0`起点重跑并`WriteArtifacts`(行340→554–556)**覆盖原result.json与log**。影响:失败运行可被表现为成功且原始失败证据被销毁。P2成立;鉴于证据覆写后果,建议主会话将其修复按P1优先级排序(不改变分级)。 - -**R4/P2:确认成立。** 源码:`LiveAccount`行328–329只断言`Count==2`与键存在,不核对值;L2后不重读101;verify用`DirectGet`(裸Client)而非新登录+新Owner重开同缓存(矩阵L4缺失);删除目标`Keys[2]`从未先确认存在(碰撞预检全缺失⇒live删除的是从未写入的键,删除路径未被真实行使)。P2恰当。 - -**R5/P2:确认成立。** 源码:`OfflineChild`c分支(行145–150)仅Open+Inspect,无Get/Ready断言(重开未Get状态必为NotLoaded);`ConservativeUnknown`重开Owner使用新RecordingHandler(行230–231)无计数,行233`mutationCount==1`只覆盖首只handler,重开后不重发未证实;`CorruptionPolicy`缺"主档缺失+bak/tmp遗留→RecoveryRequired";live编排Unknown退出替身(矩阵L7)不存在;行102诊断`SnapshotDto("101", d, PlayerKVSyncStatus.Ready)`硬编码Ready,live诊断缺state/ticket/epoch真实字段。P2恰当。 - -### 修复设计的三点补充(P3,建议随裁决采纳) - -- **A-S1(R1)**:修复应把owner生命周期token接到编排级linked CTS,使孤儿传输被确定性Cancel并经Close drain收尾,而非仅等待其自行结束;替身用例须用闸门同步证明"超时→停止→传输收尾完成→才允许清理"的顺序(不使用Sleep)。 -- **A-S2(R3)**:原运行的断言状态须持久进manifest(当前manifest无该字段,补清理无法据原运行判定Completed);补清理只生成独立补救产物,原result/log保持只读。 -- **A-S3(R2)**:"未知字段/重复属性拒绝"需显式严格解析(JObject白名单字段映射;JsonConvert默认行为不满足);建议`--cleanup`在登录前完成全部校验,并输出将删除key的SHA256清单(不回显明文)供操作者核对。 - -## B:4A方案可实施性 - -| 审查点 | 结论 | -|---|---| -| Owner只读接口租约 | 正确。复用Owner准入门(含closing/closed/归属校验);`State.ReadLocal`自带原子状态检查并返回独立拷贝(3A实现已核);读后复查归属;不新建第二State、不改3A状态机 | -| 桥接重复拥有session | 无。明确"持有引用不拥有、不Dispose、登录控制器在Close完成后销毁";单一所有权成立 | -| Close挡住新Open | 成立。桥接串行屏障+3A文件租约(Busy)双保险;A4覆盖"忽略取消传输"等待场景 | -| 旧句柄写新账号 | 被阻止。固定句柄+逐操作验证OwnerInstanceId/epoch(A6);"仅全局epoch不足"判断正确——延后回调必须持固定句柄 | -| 取消等待误取消收尾 | 无。Open排队取消仅取消该等待者;Close异常保留失败状态并拒绝后续Open,锁未释放不被误作可重用 | -| 文件白名单 | 足够。`internal CreateAsync(handlerFactory)`注入点已存在(3B验证过同程序集编译),无需新增公共传输入口;修改`PlayerKVSessionOwner.cs`属已验收文件最小增量,A12要求3B回归保持通过且未允许文件hash不变 | -| 生产现状断言抽查 | 全部属实:`UserService.cs:306`HexNumber、`SurveyService.cs:56`、`FriendService.cs:375`、`FishingBehaviorB.cs:770`(async void)、`FishingTurntablePanel.cs:517/585`无条件`isDataSynced=true`、`DataCenter.PlayerData.cs`LoadPlayerData/NewPlayerDataDic、Coordinator tickets只增不清退 | -| 4B/4C约束反噬4A接口 | 未发现。固定句柄、空KV阻塞策略、票据语义均可由现有+4A新增接口承载 | - -### 三点补充(P3) - -- **B-S1**:建议A2/A3扩展——`CreateAsync`失败(如初始Get失败)后桥接活动位必须清空,后续Open不被卡死。 -- **B-S2**:建议增加"句柄ReadLocalSnapshot与在途Flush并发"用例:读应得到baseline→pending→localOnly合并视图且不干扰在途批次。 -- **B-S3**:`ReadLocalSnapshot`错误分类中`StaleOrClosing`与`NotReady`并存时的优先级建议明确(建议StaleOrClosing优先,避免旧句柄被误报为数据未就绪)。 - -## 证据类型区分 - -- **历史运行证据**(保留为执行事实):offline 7/7、live 3/3、42/86/29、Unity编译——不证明矩阵逐项满足;更正文档对此的定性正确。 -- **静态推导**:R1–R5全部为源码级推导(本审查逐行确认);均为"源码可达风险与覆盖缺口",不是已发生的数据事故;未观察到正式服数据损坏。 -- **尚未实测**:R1迟到写与清理重叠(合成复现方法:受闸门控制的延迟handler使L1超过20s,断言清理开始前传输已收尾——按更正文档§3.2在修复后执行);L7替身;修复后的全部矩阵与新的正式正常路径run。 - -## 需主会话确认的事项 - -1. 采纳A-S1~A-S3、B-S1~B-S3为实施说明。 -2. R3修复优先级建议按P1对待(证据覆写后果)。 -3. 重申:3C补验收(含修复、逐行矩阵、外部复核)完成前,不得以4A设计通过为由批准编码;4A任务书前置门已正确列出该条件。 -4. 更正文档§4关于"八文件历史基线"的自我更正(S101AccountSession仅本阶段hash)属实,无需再动。 - -## 结论 - -- **A:通过**(R1–R5确认,修复设计足够+3项P3补充;3C恢复"通过"须待补验收闭环)。 -- **B:通过**(4A方案可实施+3项P3补充;编码批准以3C补验收闭环为前置)。 -- 本审查无新增P1/P2。 diff --git a/CodexOutput/upserver/B3BatchMigration/B01-design-hashes.json b/CodexOutput/upserver/B3BatchMigration/B01-design-hashes.json deleted file mode 100644 index 137a43367..000000000 --- a/CodexOutput/upserver/B3BatchMigration/B01-design-hashes.json +++ /dev/null @@ -1,162 +0,0 @@ -{ - "createdUtc": "2026-09-28T10:08:57.6522702Z", - "purpose": "B01完整方案独立审查;项目根相对路径;共享状态和可更新执行TODO不冻结;清单不代表修改授权", - "count": 30, - "items": [ - { - "path": "CodexOutput/upserver/B3BatchMigration/B01-通知提示与已读状态批级方案-待评审.md", - "sha256": "3F9B1DAAE6D81546CD8B36ECD5DA1DF359BD27842B91A51F290504179812F2E0", - "bytes": 15840 - }, - { - "path": "CodexOutput/upserver/B3BatchMigration/B01-独立方案审查提示词.md", - "sha256": "3B689024ACD52A4733AD9CCC0E17D6C4D14E8FA471938227874A90563E59C0B1", - "bytes": 1719 - }, - { - "path": "CodexOutput/upserver/B3BatchMigration/调用分类与现状映射.json", - "sha256": "4537878A379D010104CD8C5A66997794095B02279D9F532BBB0433335EEFE768", - "bytes": 155605 - }, - { - "path": "CodexOutput/upserver/B3BatchMigration/分类统计.json", - "sha256": "8E142B41D4A1CB92EF09DFC267777053B97DF9ADCFE2F1741CA651ECFAC848F7", - "bytes": 836 - }, - { - "path": "CodexOutput/upserver/B3BatchMigration/current-scan/calls.json", - "sha256": "BA3720B8C802E2B85FB7F7FA1C8DE1D527B3E1C81D48EB068073DD905880C51E", - "bytes": 917099 - }, - { - "path": "CodexOutput/upserver/B3BatchMigration/current-scan/source-hashes.json", - "sha256": "C1D533D806AEF33537AAE58BD9A5F850C810891C48F056C49D9499F0E45AD02E", - "bytes": 276004 - }, - { - "path": "CodexOutput/upserver/B3DesignAudit/calls.json", - "sha256": "12588092ECE71E12FDFD829B0A65F23EFA53241F49C527067B0ADDE423E47C61", - "bytes": 913483 - }, - { - "path": "CodexOutput/upserver/B3DesignAudit/Program.cs", - "sha256": "542C2A6EE08EBC88E71A61C423587FEB9335DF16232FC134F4F22328B4BE865E", - "bytes": 5303 - }, - { - "path": "CodexOutput/upserver/B3DesignAudit/bin/Debug/net9.0/B3DesignAudit.dll", - "sha256": "B01AC846E3DD015A36744597872E46861981C4950E7D955C76324EF486D99722", - "bytes": 17408 - }, - { - "path": "CodexOutput/upserver/流程修正主会话意见-审查侧裁决-2026-09-28.md", - "sha256": "F77EC297607BEF1D9687F0B5778EC6585D9B083C87D148655ECA722726B0390F", - "bytes": 5436 - }, - { - "path": "CodexOutput/upserver/流程修正主会话意见-待审查裁决-2026-09-28.md", - "sha256": "21F7F1F1B853E18B598F4B5817EC051FC92FBC5A06B58D4E25E4EFC7930A61D8", - "bytes": 9195 - }, - { - "path": "CodexOutput/upserver/阶段4B3分期与4B3A固定存档入口方案-待评审-2026-09-24.md", - "sha256": "FA5EB445C77C9F11E3EEE71BEE8007A5A25AB76761DD4F75EFF93B23360B7022", - "bytes": 21798 - }, - { - "path": "Client/Assets/Scripts/Services/SettingService.cs", - "sha256": "5D139BE63E13A3D3248D866C46A2D07F9D0917F624E0073D9CF7FE5E05C561D8", - "bytes": 5337 - }, - { - "path": "Client/Assets/Scripts/Services/ILocalNotificationService.cs", - "sha256": "B5763A9CCB4A0C079916345F7D41371A4B9E73B706D5B45468C18345D7EBFEE5", - "bytes": 6672 - }, - { - "path": "Client/Assets/Scripts/Services/ClubService.cs", - "sha256": "DC94626E1F386F17FCCA3D3C12D357FE95CEE8E5F50A943E73770399F3B2CD42", - "bytes": 43338 - }, - { - "path": "Client/Assets/Scripts/UI/Setting/SettingNotificationsGradePopupPanel.cs", - "sha256": "177E9F1F6B680CF76A8C0C94653A4C02DAB23DDB56D4A85CEA525C3F01A3F1E0", - "bytes": 672 - }, - { - "path": "Client/Assets/Scripts/UI/Setting/SettingNotificationsPopupPanel.cs", - "sha256": "783F3973B240BB8BC6C0EAB6449610079C9B59B0666E73A1D101465DEC75E3E1", - "bytes": 634 - }, - { - "path": "Client/Assets/Scripts/UI/Setting/SettingPopupPanel.cs", - "sha256": "AF64C5E1CADAD9C543E98A8406F92576A76574F35B8556BBB295EF5A6429D8CF", - "bytes": 8854 - }, - { - "path": "Client/Assets/Scripts/UI/Shop/GiftNoticePanel.cs", - "sha256": "A1737674CAEBDD91F4EA2F18C488CDC62F186D948D3D49B4EA316E459C2D86CC", - "bytes": 2440 - }, - { - "path": "Client/Assets/Scripts/UI/Social/FishingSocialPanel.cs", - "sha256": "1E33FBD3CF6EF76C20CF76FA7EF12028A31EE062EF4C1EA26EB2A701AC85DD6E", - "bytes": 7122 - }, - { - "path": "Client/Assets/Scripts/DebugFunc.cs", - "sha256": "F7968007D44382D6DF17E1239FDA9FBA37BAEA40F5FD608D9412561BC0368107", - "bytes": 36052 - }, - { - "path": "Client/Assets/Scripts/DataCenter/DataCenter.PlayerData.cs", - "sha256": "768C2935FA702ACAA7E6F20FA9E82A883E3863B3104ACFD519DFFEBA3A890C83", - "bytes": 65923 - }, - { - "path": "Client/Assets/Scripts/Core/PlayFabMgr.cs", - "sha256": "E75C8BEDE21878286EF4E247BB3BE24CE81B81BFD1EEB3106E7B10468FFA9195", - "bytes": 15712 - }, - { - "path": "Client/Assets/Scripts/SubBoostrap.cs", - "sha256": "B62354B0761DCCD445A19C25D7379ACB71FFF2FD47D07BEB2101E5A79889D381", - "bytes": 18341 - }, - { - "path": "Client/Assets/Scripts/Stages/LoginStage.cs", - "sha256": "D95641EEB076B75D86F57855F71B4F83894519CC6F3890F1919490FB2FF45C45", - "bytes": 6152 - }, - { - "path": "Client/Assets/Scripts/Services/UserService.KVLoad.cs", - "sha256": "45300AA455CF43C07286A442E7A2C8534B3654C4AEB8316CA5EB3A20593AEA0D", - "bytes": 6963 - }, - { - "path": "Client/Assets/Scripts/Services/PlayerData/PlayerKVGameSessionBridge.cs", - "sha256": "DD888351BFA4BBA03E953F39E11362AF8EA9F76FB56AC1CB77D9053C81227363", - "bytes": 13612 - }, - { - "path": "Client/Assets/Scripts/Services/PlayerData/PlayerKVKeyReadResult.cs", - "sha256": "C9C76A16F61CBC3CC748A0F44B581508B4178E7F322C43C8F05E2FC8707345DC", - "bytes": 1471 - }, - { - "path": "Client/Assets/Scripts/Services/PlayerData/PlayerKVSaveSchema.cs", - "sha256": "FBDB253D3415E35D7D30F867DA057A84E91EAA7DE2FE74094707C517CB8B51A1", - "bytes": 76183 - }, - { - "path": "Client/Assets/Scripts/Services/PlayerData/PlayerKVGameplayBindings.cs", - "sha256": "710A0050277BE07AC781F976945D8D2DDF7704EA616D0BF83797ABA2FA6530EA", - "bytes": 6874 - } - ], - "expectedAbsent": [ - "Client/Assets/Editor/KVPromptStateValidation.cs", - "Client/Assets/Editor/KVPromptStateValidation.cs.meta", - "CodexOutput/upserver/B3BatchMigration/B01Tests" - ] -} diff --git a/CodexOutput/upserver/B3BatchMigration/B01-封板核验.json b/CodexOutput/upserver/B3BatchMigration/B01-封板核验.json deleted file mode 100644 index 5fd47f482..000000000 --- a/CodexOutput/upserver/B3BatchMigration/B01-封板核验.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "verifiedUtc": "2026-09-28T10:08:58.0972395Z", - "manifestCount": 30, - "hashMismatches": 0, - "absentCount": 3, - "classified": 224, - "uniqueStableIds": 224, - "sourceFilesChecked": 2108, - "sourceFilesChangedSinceScan": [], - "selectedStableIds": [ - "B3-C170", - "B3-C177", - "B3-C178" - ] -} diff --git a/CodexOutput/upserver/B3BatchMigration/B01-独立方案审查提示词.md b/CodexOutput/upserver/B3BatchMigration/B01-独立方案审查提示词.md deleted file mode 100644 index 7db92435b..000000000 --- a/CodexOutput/upserver/B3BatchMigration/B01-独立方案审查提示词.md +++ /dev/null @@ -1,9 +0,0 @@ -# B01独立批级方案审查 - -请只读审查C:\projects\ft的4B3B首批“通知提示与俱乐部已读状态”。先读上级《流程修正主会话意见-审查侧裁决-2026-09-28.md》,本目录《执行TodoList.md》《B01-通知提示与已读状态批级方案-待评审.md》及《调用分类与现状映射.json》《分类统计.json》。以《B01-design-hashes.json》独立核SHA256和长度;当前源码快照在current-scan,旧calls.json不得覆盖。 - -这是正式业务代码准备方案,不是新Editor单次许可,不启用正式KV;B→C门保持。本批3处存档调用须连同通知异步及多个UI上游审查,不以“少于30处”判不通过,也不能因末端一行保存就认定简单。8运行文件、1固定Editor测试入口及本批独立测试目录为候选白名单,尚未批准编码。 - -重点:固定实例/固定Owner、不在回调后Resolve新服务;合法缺键与拒读区别;普通本地Accepted及可能提交错误;授权await、异常finally、旧UI/红点副作用;B2同实例Reset/Replace;设备通知与账号提示的分工;C未来绑定是否可行;整个升级/社交/奖励链仍未开放,不能越界宣称完成。检查方案§6全部验收能否实现且不靠测试替代实现;对原有非Editor编译问题区分新增回归。 - -输出总裁决、hash结果、逐条问题和最小修订、是否可实施及批准边界。只落盘报告到本目录《B01-独立方案审查.md》,不改共享入口/方案/代码,不运行Unity/真实API/测试账号,不生成许可或打包。主会话随后核hash并逐条裁决。流程内实现错误修复无需逐调用补审,合同/范围变化才补审。 diff --git a/CodexOutput/upserver/B3BatchMigration/B01-通知提示与已读状态批级方案-待评审.md b/CodexOutput/upserver/B3BatchMigration/B01-通知提示与已读状态批级方案-待评审.md deleted file mode 100644 index 8266ac011..000000000 --- a/CodexOutput/upserver/B3BatchMigration/B01-通知提示与已读状态批级方案-待评审.md +++ /dev/null @@ -1,119 +0,0 @@ -# B01:通知提示与俱乐部已读状态批级方案 - -2026-09-28,主会话;待完整独立方案审查,未批准编码。本批属于4B3B的业务接线准备,**不是4B3C正式启用**。按F01–F12统一流程,一份方案、一轮方案审查、连续实施、一轮批末实施复核。 - -## 1. 当前分类与选批 - -复用既有B3DesignAudit扫描器,不修改扫描源码,在独立目录current-scan生成当前快照。旧223处全部可映射:B3-C050原PlayerData.SavePlayerData的写已提取到SerializeAndSavePlayerData,源调用保持;新增B3-N001是PlayFabMgr.StartKVGameplayLoopSync中的内部计时调用,源于之前Editor验证接线。本轮没有新增生产调用。 - -| 分类 | 当前数量 | 含义 | -|---|---:|---| -| 首批候选 | 3 | B3-C170、C177、C178,本方案详审 | -| 待迁移分类 | 200 | 按业务/读取/生命周期/交易等分派,未完成各自上游完整审计 | -| 已有限定处理、正式仍待 | 4 | 复用已有R1/4C/Editor证据,不能宣称正式路径全部完成 | -| 保留PF待专项 | 13 | 旧PF兼容/身份/SDK/公共资料,不改成本人KV | -| 本次排除 | 4 | GM路径,后续单列,不等于永久允许不迁移 | - -逐项见《调用分类与现状映射.json》,旧ID保持稳定,当前扫描ID另列。方法名候选不是语义调用关系;当前224处也不是全部可机械替换的任务。扫描仍不涵盖所有反射/UnityEvent绑定和新的显式KV调用,不能以数字清零关闭B。 - -三个选择比较: - -- 本批选择**通知提示/已读标记**:非消费、固定键;覆盖合法缺键、内存提交顺序、异步系统授权和多个UI入口,适合复用固定句柄的第一组业务合同。 -- 不按“前30个Update”选:足迹涉及高位保持与社交奖励,问卷涉及网络响应与奖励,不能因末端一行保存就混入低风险批。 -- 不先做定时器/加载发布:属于C,依赖B操作归属;不绕过原B→C门。 - -本批不改通知系统权限含义、经济公式、奖励、身份、俱乐部网络API或其他红点。ShowNotice仍是“已展示/处理过提示”而不是“操作系统已授权”;IsOpenClubRed写"1"仍表示已读,内存IsOpenClubRed=false。 - -## 2. B/C边界与固定归属 - -本批只实现固定Owner下的业务方法和调用者持有原服务的规则。**不修改SubBoostrap/LoginStage/UserService注册,不开放SaveBackend=kv,不获取4B1私有handle,不从PlayerKVGameplayLoop取句柄,不生成v4许可。** B验收使用既有合成session/Bridge;默认PF构造与已有受控Editor玩法保持。 - -复用PlayerKVGameSessionHandle与PlayFabMgr.ReadKV/WriteKV,不再造会话管理器/通用Registry/动态当前账号路由。为DefaultSettingService、ClubService提供internal固定KV构造入口:参数是非null、当前可读的既有handle,存于readonly字段;原无参构造继续表示PF。KV构造失败不能退回PF。LocalNotificationService的KV构造接收该次固定DefaultSettingService及配置依赖,不能在授权回调恢复后重新Resolve当前账号服务。 - -这些是生产可用的业务实现,不限UNITY_EDITOR;测试入口必须Editor或独立合成宿主。正式C尚未接入,不能因此宣称玩家现在已能使用此新KV路径。C未来必须为每次登录创建新的这些绑定实例,重新发布到游戏容器;同一实例不允许改绑新handle。旧实例仍只指向旧Owner,旧回调即使持有同一账号ID也失效。C还须撤销/退订旧实例及通知订阅;本批不把设备级通知服务生命周期重构提前完成。 - -B2受控加载的无参对象Reset/Replace继续照旧。固定KV实例不参与跨账号原地改绑;即便测试人为对旧实例Reset/Replace成新数据,旧Owner失效后也必须在写业务字段前拒绝。不得以ReferenceEquals(service)或账号ID相同代替Owner有效性检查。 - -本批不放行任何真实社交界面,也不声称整个ClubService已迁移。其捐赠、签到、网络回调及身份另批处理;C不得仅因SetOpenClubRed完成就启用所有俱乐部功能。 - -## 3. 每调用规则表 - -| 稳定ID/当前成员 | 上游与首次副作用 | 固定归属及处理 | 失败/验证 | -|---|---|---|---| -| B3-C177 DefaultSettingService.ShowNotice getter | CheckRequestPermission、通知面板;原首次修改为_showNotice缓存赋值 | 每次先ReadKV(构造捕获的Owner,"ShowNotice"),即使缓存已有也不可跳过有效性检查。成功且Found=false才返回false;Found=true严格沿用原值=="1"规则,其余原字符串为false,不规范化写回 | Stale/NotReady/LoadGuardActive拒绝,不能返回false冒充未提示;不赋缓存、不调用旧PF | -| B3-C178 ShowNotice setter | CheckRequestPermission;等级通知弹窗DestroyUI;LocalNotificationService.OpenSettings授权完成。原首次修改为_showNotice=value | KV先检查Owner有效、计算目标"1"/"0",以固定Owner写;本地Accepted后再改_showNotice。同值只有当前有效快照已是目标值时才可不写,不能只看旧内存缓存 | Validation/Blocked/StorageError不改提示状态,不自动重试;可能提交保留原结果,不清pending、不回写旧值;失败不继续关闭界面/触发后续动作 | -| B3-C170 ClubService.SetOpenClubRed | FishingSocialPanel.Start;原先IsOpenClubRed=false及SetClubRed发生在保存前 | KV先用固定Owner核有效并读取该键,按M14既有语义得到当前OpenRed(键缺失=true;键存在且值为任意非null字符串,包括空字符串/"0",均为false;不能改为仅"1"才已读);需要写时先WriteKV("IsOpenClubRed","1"),Accepted后再改字段并执行原SetClubRed。若有效快照已读则同步内存为false,不再次写 | 失败不改IsOpenClubRed、不发红点更新;旧服务在新Owner后不能改共享内存或红点。不能把此结果称远端Confirmed | - -普通状态采用本地Accepted语义,随后由原会话同步器保存,不给这两个标记新增每点击必Flush或票据等待。原票据留在既有系统,不伪造远端已确认。Owner在写已接受后被撤销:保留A已接受的事实;再次检查有效性后才发布UI副作用,若失效停止显示更新,不回滚/重放写入。 - -结果表达沿用原PlayerKVKeyReadResult/PlayerKVEditResult,不新增另一套通用错误模型。现有bool属性/void入口在KV拒绝时抛出带错误分类的InvalidOperationException;UI和async void边界捕获、记录并停止本次动作,不能冒充false/成功。原提交不确定时在该绑定服务内记录故障阻断后续修改,保留原EditResult供限定诊断;不实现人工解冻。PF分支业务语义保持。 - -## 4. 完整通知上游与UI边界 - -存档调用少不等于只改保存方法。本批包括以下必要上游,统一在一份方案中处理: - -| 入口 | 现状 | 本批合同 | -|---|---|---| -| LocalNotificationService.OpenSettings | initing先置true;await Init后重新Resolve ISettingService写ShowNotice;异常可能不复位initing | 启动前捕获原服务并验证其KV归属;使用async Task内部实现,由原void入口统一观察异常;finally只复位本实例initing。await后核原服务再写,不能Resolve新服务;无效时不安排后续账号相关通知/订阅 | -| LocalNotificationService.Init | 非Editor系统授权await后调度通知并订阅EventRankData | KV模式捕获本次设置服务,在请求前及await后核原Owner;过期则不调度/订阅或设置isInit。系统已弹出的权限结果不能撤销,必须明确不代表可写新账号。PF原分支保留 | -| SettingNotificationsGradePopupPanel | 点同意先调用DestroyUI(写ShowNotice),再打开系统设置;取消也写已提示 | 初始化时捕获设置和通知服务;回调先校验旧实例/原Owner,提示写被拒则停止,不关闭别人的UI、不打开设置。同意/取消的原业务含义保持;同一处理中的重复点击不重复请求 | -| SettingNotificationsPopupPanel | 同意关闭后Resolve通知服务 | 初始化时捕获通知服务;点击前校验,先拒绝陈旧入口,再执行原流程;不在延迟操作中重新取当前服务 | -| SettingPopupPanel.OnToggleNotification | 开启时Resolve通知服务;关闭时ShowUI弹窗 | 沿用已有settingService引用,初始化时捕获配套通知服务;点击前核归属,不由旧界面启动新账号操作。新弹窗创建归属由未来C UI生命周期统一保证,本批不声称修复所有UI加载回流 | -| GiftNoticePanel.OnClickYES | 关闭后Resolve通知服务 | 仅通知按钮同上;不改礼包展示/领取,也不开放该奖励业务。原OnClickNO的设备PlayerPrefs不迁移 | -| DebugFunc.NotifySettingTest | 同步Resolve到局部service再调用 | 原代码已捕获局部引用,不新增存档;保持不改,LocalNotificationService统一校验。不以GM作为真实验收入口 | -| PlayerData.LevelChange→CheckRequestPermission | 调用前已有升级、地图和事件副作用 | 本批仅保证CheckRequestPermission内部提示读写拒绝不会变成false或写新Owner;**整个LevelChange的上游归属未完成**,留核心进度批,C前不得用本批声明升级全链安全 | -| FishingSocialPanel.Awake/Start→SetOpenClubRed | Awake已捕获ClubService,Start先执行社交UI/API行为,再标记已读 | 固定KV模式在对应UI入口开始处核已捕获ClubService的有效性,至少在本批红点修改前核原Owner;不Resolve替代服务。调用失败记录并停止该段后续,整个社交API链另批,不扩大本批验收 | - -无需修改ISettingService/ILocalNotificationService的公开签名。内部可用具体服务的受限检查方法供同程序集UI使用;无参PF服务检查保持原行为,不检查当前全局SaveBackend来切路。UI原有无关按钮、格式和资产不动。失效旧UI只停止旧回调,不能用类型名销毁可能属于新会话的同名窗口。 - -错误日志只记键名、Owner标识和错误类别,不记Cookie或完整存档。系统权限已经改变与游戏提示标记保存失败分别记录;不以存档失败反向重复请求系统权限。 - -## 5. 白名单与明确不做 - -运行源码限8个既有文件(均在Client/Assets/Scripts下): - -1. Services/SettingService.cs:固定KV构造、ShowNotice读写、检查/错误边界;其他本地设置不改。 -2. Services/ILocalNotificationService.cs:固定依赖构造、原实例捕获、OpenSettings/Init的恢复校验和finally;调度公式不改。 -3. Services/ClubService.cs:固定KV构造、已读标记读取/提交/检查;不改捐赠/签到/身份/API实现。 -4. UI/Setting/SettingNotificationsGradePopupPanel.cs:原服务捕获、点击检查及失败中止。 -5. UI/Setting/SettingNotificationsPopupPanel.cs:同上。 -6. UI/Setting/SettingPopupPanel.cs:只处理通知入口。 -7. UI/Shop/GiftNoticePanel.cs:只处理通知入口,不涉及礼包奖励。 -8. UI/Social/FishingSocialPanel.cs:固定ClubService的本批提示状态入口校验和错误边界。 - -测试允许新增 `CodexOutput/upserver/B3BatchMigration/B01Tests/` 下独立宿主;如需真实Unity对象验证,新增 `Client/Assets/Editor/KVPromptStateValidation.cs` 及其meta,仅暴露固定B01用例入口、空闲Editor运行,使用fake transport。禁止任意反射方法执行器/真实API降级,不改原测试以掩盖回归。 - -测试优先编译/调用实际源文件并用最小必要平台shim;Unity验证实际服务/面板,不以重新手写一套算法替代生产入口。平台权限在离线shim或Editor分支模拟,不触发用户系统权限弹窗/推送。若必须新增其他生产文件或改公开接口/注册逻辑,先具体补审,不能借白名单延伸为通用框架。 - -不改Core/PlayFabMgr、Owner/Bridge、B2加载器与31模块合同、UserService/注册、通知包、数据格式、PF SDK。这里的默认PF兼容不授权KV失败回落PF。历史Editor KV Loop仍是已关闭验证链,未因此扩展或重新运行。 - -## 6. 验收矩阵 - -| 项 | 必须验证 | -|---|---| -| P01 正常读/缺键 | ShowNotice缺键false、"1"true、"0"/空字符串按旧规则false;只有成功快照的缺键才缺省,不自动写 | -| P02 拒读 | Stale/Closing/NotReady/加载guard活跃时不赋缓存,不当false,不转PF,即使_showNotice已有值也拒绝 | -| P03 普通提交 | 首次写正确原字符串/固定Owner,Accepted后才改内存/红点;同值不重复写;记录原票据但不声称已远端确认 | -| P04 故障 | Validation/Blocked/StorageError以及LocalCommitMayHaveSucceeded:不继续UI/系统副作用,不回滚、不自动重试;故障阻断后续修改 | -| P05 旧回调 | A通知授权挂起→撤销A→B创建→完成A;B缓存、ShowNotice、红点、网络请求均不变,A不重新Resolve B;同账号新epoch也覆盖 | -| P06 同对象污染 | 人为让旧Club实例Reset/Replace装入另一组数据后再触发旧操作,原Owner检查必须在字段/红点变化前拒绝;不以对象引用相等过关 | -| P07 权限时序 | 重复点击/授权失败/异常均观察并finally清initing;过期后不设置isInit、不新增通知订阅;系统授权与存档标记语义分离 | -| P08 UI入口 | 四个通知UI入口和Social标记调用捕获原服务;旧实例回调不销毁新同名UI,不触发新账号系统/存档操作;失败停止后续段 | -| P09 非消费范围 | 礼包展示、领取/捐赠/签到/升级经济数据不改;原无参PF入口及设备本地设置语义保持 | -| P10 回归与编译 | 既有42/86/29等适用基础回归、4B3A固定入口、B2 M14/31模块受影响回归;Unity Editor编译及适用SERVICE_HOST构建。平台分支做编译验证,已记录默认非Editor错误单列,不掩盖新增错误 | - -fake transport必须固定.invalid地址且绝不转发。关闭原合成Owner并排空后释放临时缓存。旧样本/真实101、102/permit/claim不变。B01不要求真实账号写入或再钓鱼;真实正式路径和连续操作属于后续C/4D集成范围。 - -## 7. 检查点与交付 - -0. 方案完整审查、主会话核hash和逐项裁决,批准8文件及固定测试范围。 -1. 批内实现固定绑定与两键规则、所有列明通知上游;相应故障/迟到场景先建有效失败用例,再修正。每检查点更新日志,不逐调用停下。 -2. 跑专项与适用回归、Unity编译;合同内失败修复并回归继续,保留首败;合同/范围/架构变化才补审。 -3. 原文件diff/范围核对,封存源码、原始测试输出、hash,形成一份实施交付与独立复核提示词。 -4. 一次独立实施复核,主会话裁决关闭B01;3处从“首批候选”改为“B业务实现关闭,待C正式接线”,不声称整个4B3B/C或两条完整用户玩法已启用。 - -## 8. 自审与需独立裁定的重点 - -作者自审:不按调用数量凑批;所有存档点与实际通知入口列明;复用原Owner而无全局动态句柄;无真实数据操作;B→C门未松动;未称整个升级/社交/礼包链已安全。首批是可单独实现和验证的非消费业务能力,后续正式发布仍须完整B/C依赖。 - -请独立审查重点判断:固定实例构造作为B准备是否足够且最小;C创建新实例的前置是否与现有受控加载可衔接;普通Accepted后的内存/红点时序是否正确;通知系统权限是设备级但提示标记是账号级,两者的失效处理是否有遗漏;当前8文件是否遗漏必要上游。若此边界不能成立,指出具体调用链和最小修订,不直接扩大到全部服务或免除批级方案门。 diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d-封存与核证.py.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d-封存与核证.py.txt deleted file mode 100644 index 00e8bed8c..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d-封存与核证.py.txt +++ /dev/null @@ -1,35 +0,0 @@ -import json,hashlib,re -from pathlib import Path -from datetime import datetime -m=Path('CodexOutput/upserver/B3BatchMigration/M2') -def read(p):return json.loads(p.read_text(encoding='utf-8-sig')) -def item(p): - p=Path(p);raw=p.read_bytes();return {'path':p.as_posix(),'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest().upper()} -original={x['path']:x for x in read(m/'M2-合批正式受审基线.json')['items']} -c=read(m/'M2-合批-C2c检查点与交付hash.json');prior=dict(original);prior.update({x['path']:x for x in c['items']}) -current=[item(p) for p in sorted(prior)] -changed=[x for x in current if x['path'] not in original or x['sha256']!=original[x['path']]['sha256']] -delta=[x['path'] for x in current if x['sha256']!=prior[x['path']]['sha256']] -allowed={x['path'] for x in read(m/'M2-合批正式候选白名单.json')['files']}|{'AGENTS.md','Client/Assets/Scripts/Services/UserService.KVFishingValidation.cs','Client/Assets/Scripts/Services/UserService.KVFishingRewardValidation.cs'} -unexpected=[x['path'] for x in changed if x['path'] not in allowed and x['path'].endswith(('.cs','.meta','.asmdef','.csproj'))];assert not unexpected,unexpected -assert item('Client/Assets/Scripts/UI/Home/HomePanel.cs')['sha256']==original['Client/Assets/Scripts/UI/Home/HomePanel.cs']['sha256'] -assert item(m/'M2-合批正式受审基线.json')['sha256']=='DBC965EDBF48FADA4C1508F2662562F4FD72C01711D8E2FE2022AC4956896EF3' -assert item(m/'M2-合批正式独立方案审查-2026-09-29.md')['sha256']=='BB02441CFFE72AF18CF3B0D78F8E581FC39549C3F77E45257B5ED16CADCF2937' -compile=read(m/'M2-C2d-final-compile.json');assert compile['Success'] and compile['ErrorCount']==0 -results={} -for name in ['consume','reward']: - d=read(m/f'M2-C2d-final-{name}.json');r=json.loads(d['Result']);assert d['Success'] and r['success'] and r['formalRequests']==0 - results[name]={k:r[k] for k in ['groups','assertions','formalRequests']} -d=read(m/'M2-C2d-final-modules.json');assert d['Success'];r=d['Result'] -a=json.loads(re.search(r'pureResult = (\{.*?\}), moduleResult',r)[1]);b=json.loads(re.search(r'moduleResult = (\{.*?\}), playing',r)[1]);assert a['success'] and b['success'] and b['restored'] and b['realModules']==31 -state=json.loads(read(m/'M2-C2d-final-state.json')['Result']);assert not any(state[k] for k in ['playing','enabled','ready','permitExists']) -for name in ['NON_ANDROID','ANDROID_AGG']: - assert 'groups=18 assertions=254 formalRequests=0' in (m/f'M2-C2d-final-ServiceHost-{name}.log').read_text(encoding='utf-8-sig') -recovered=[] -for p in [Path('CodexOutput/upserver/KVGameplayLoopTests/fishing-fixed-runs/20260930T032500_c51bfd787cac474983d7863461e379e8/result.json'),Path('CodexOutput/upserver/KVGameplayLoopTests/reward-fixed-runs/20260930T032547_cae307d3ed07409a8a3c363c460357fa/result.json')]: - assert read(p)['success'];recovered.append(item(p)) -(m/'M2-C2d-合并CLI超时核对.json').write_text(json.dumps({'cliSucceeded':False,'cliError':'Request timed out after 180000ms','underlyingResults':recovered,'followup':'Final individual CLI outputs are authoritative.'},ensure_ascii=False,indent=2),encoding='utf-8') -evidencePaths=list(m.glob('M2-C2d-*.json'))+list(m.glob('M2-C2d-*.log'))+list(m.glob('C2d-*.py.txt'))+[m/'C2d修改前快照/index.json',m/'M2-纯平移用户审查确认与C2d实施边界-2026-09-30.json',m/'M2-纯平移主会话裁决与C2d实施记录-2026-09-30.md'] -report={'date':datetime.now().astimezone().isoformat(),'stage':'C2d 纯平移核减与旧验证宿主注入完成;C3真实集成未验','reviewBasis':'用户明确审核完毕并继续,详见用户确认JSON;未声称收到新独立报告','originalReviewReportSha256':item(m/'M2-合批正式独立方案审查-2026-09-29.md')['sha256'],'originalManifestSha256':item(m/'M2-合批正式受审基线.json')['sha256'],'priorCheckpointSha256':item(m/'M2-合批-C2c检查点与交付hash.json')['sha256'],'combinedItemCount':len(current),'changedSinceC2c':delta,'outsideCodeWhitelist':unexpected,'unchangedOriginal':sum(x['path'] in original and x['sha256']==original[x['path']]['sha256'] for x in current),'items':changed,'homePanelUnchanged':True,'compile':{k:compile[k] for k in ['Success','ErrorCount','WarningCount']},'offlineResults':results,'modules':{'M08-M23':a,'B2-20':b},'serviceHost':{'NON_ANDROID':{'groups':18,'assertions':254},'ANDROID+AGG':{'groups':18,'assertions':254}},'evidence':[item(p) for p in sorted(set(evidencePaths)) if p.stat().st_size>0],'runtimeVerified':False,'formalRequests':0} -out=m/'M2-合批-C2d检查点与交付hash.json';out.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') -print(json.dumps({'combined':len(current),'cumulativeChanged':len(changed),'unchangedOriginal':report['unchangedOriginal'],'changedSinceC2c':len(delta),'outsideCodeWhitelist':unexpected,'checkpointSha256':item(out)['sha256']})) diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d-按核证基线核减.py.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d-按核证基线核减.py.txt deleted file mode 100644 index 7d32e3c3e..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d-按核证基线核减.py.txt +++ /dev/null @@ -1,93 +0,0 @@ -import hashlib, json, subprocess -from pathlib import Path -root=Path('Client/Assets/Scripts') -m=Path('CodexOutput/upserver/B3BatchMigration/M2') -baseline={x['path']:x for x in json.loads((m/'M2-合批正式受审基线.json').read_text(encoding='utf-8-sig'))['items']} -def original(suffix, require_match=True): - path=root/suffix - raw=subprocess.run(['git','show','HEAD:'+path.as_posix()],capture_output=True,check=True).stdout - s=raw.decode('utf-8-sig').replace('\r\n','\n') - variants=[s.encode('utf-8'),s.encode('utf-8-sig'),s.replace('\n','\r\n').encode('utf-8'),s.replace('\n','\r\n').encode('utf-8-sig')] - if require_match: - assert any(hashlib.sha256(b).hexdigest().upper()==baseline[path.as_posix()]['sha256'] for b in variants),suffix - return s -def write(suffix,s): - path=root/suffix; raw=path.read_bytes() - text=s.replace('\r\n','\n') - if b'\r\n' in raw: text=text.replace('\n','\r\n') - path.write_bytes(text.encode('utf-8-sig' if raw.startswith(b'\xef\xbb\xbf') else 'utf-8')) -def calls(s,old,new,tail): - pos=0 - while True: - start=s.find(old+'(',pos) - if start<0:return s - if s[s.rfind('\n',0,start)+1:start].lstrip().startswith('//'): - pos=start+len(old);continue - i=start+len(old);depth=0;quote=None;esc=False - while i boundSaveStore; - set { CouponData.BindSaveStore(value); boundSaveStore = value; } - } -''' -s=s.replace(' public partial class PlayerShopData : IDisposable\n {',' public partial class PlayerShopData : IDisposable\n {\n'+binding,1) -write('DataCenter/DataCenter.PlayerShopData.cs',storage(s,'SaveStore')) -s=original('UI/Turntable/FishingTurntablePanel.cs') -s=s.replace(' Tables _tables;',' game.PlayerDataStorage.IPlayerSaveStore saveStore;\n Tables _tables;',1) -s=s.replace(' void Awake()\n {',' void Awake()\n {\n saveStore = GContext.container.Resolve();',1) -s=calls(s,'await PlayFabMgr.Instance.SyncDataImmidiate','(await saveStore.WriteAndConfirmAsync',').Confirmed') -write('UI/Turntable/FishingTurntablePanel.cs',s) - -# Preserve all pre-existing uncommitted KV-loop/prompt work: replace only the inspected business methods. -f='GampPlay/FishingB/FishingBehaviorB.cs';s=(root/f).read_text(encoding='utf-8-sig');old=original(f,False) -start=old.index(' private void DoConsumeBait()');end=old.index(' void LoadFish()',start) -body=calls(old[start:end],'await PlayFabMgr.Instance.SyncDataImmidiate','(await saveStore.WriteAndConfirmAsync',').Confirmed') -start=s.index(' private async void DoConsumeBait()');end=s.index(' void LoadFish()',start) -s=s[:start]+body+s[end:] -for line in [' game.IUserService loginUser;\n',' bool consumptionPending;\n',' bool SaveSessionCurrent => this != null && isActiveAndEnabled && saveStore != null && saveStore.IsCurrent && !loginUser.LoginLifetime.IsCancellationRequested;\n',' loginUser = GContext.container.Resolve();\n']: - assert line in s,line;s=s.replace(line,'',1) -write(f,s) -f='Services/ClubService.cs';s=(root/f).read_text(encoding='utf-8-sig');old=original(f,False) -start=old.index(' private int? signingSession;');end=old.index(' public void SendSystemMessage2',start) -body=storage(old[start:end],'SaveStore') -start=s.index(' private int? signingSession;');end=s.index(' public void SendSystemMessage2',start) -write(f,s[:start]+body+s[end:]) -# This present wrapper was introduced only by C2c; retain the surrounding original deferred reward queue. -f='Services/DeferredRewardStashService.cs';s=(root/f).read_text(encoding='utf-8-sig') -s=s.replace('game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData()));','GContext.Publish(new ShowData());') -s=s.replace('PlayerSaveAction.Present(() => GContext.Publish(new ShowData()));','GContext.Publish(new ShowData());') -write(f,s) -print('Verified baseline + minimum storage/identity substitutions applied; historical partial-file work retained.') diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d-活动原流程核减.py.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d-活动原流程核减.py.txt deleted file mode 100644 index ea49a2137..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d-活动原流程核减.py.txt +++ /dev/null @@ -1,52 +0,0 @@ -from pathlib import Path -m=Path('CodexOutput/upserver/B3BatchMigration/M2') -# Reuse only the previously audited helper definitions, never replay prior edits. -exec((m/'C2d-按核证基线核减.py.txt').read_text(encoding='utf-8-sig').split('# All ten source bodies')[0]) -def read(f):return (root/f).read_text(encoding='utf-8-sig') -def replace(f,a,b): - s=read(f); assert s.count(a)==1,(f,a); write(f,s.replace(a,b,1)) -for f,klass in [('Activity/Data/EventDataRepository.cs','EventDataRepository'),('Activity/Services/EventTokenService.cs','EventTokenService')]: - s=original(f) - start=s.index('\n {',s.index('public class '+klass))+len('\n {') - s=s[:start]+'\n private readonly game.PlayerDataStorage.IPlayerSaveStore store;\n public '+klass+'(game.PlayerDataStorage.IPlayerSaveStore store)\n { this.store = store ?? throw new ArgumentNullException(nameof(store)); }\n'+s[start:] - s=s.replace('PlayFabMgr.Instance?.GetLocalData','PlayFabMgr.Instance.GetLocalData').replace('PlayFabMgr.Instance?.UpdateUserDataValue','PlayFabMgr.Instance.UpdateUserDataValue') - write(f,storage(s,'store')) -# Retain current store bindings and session checks. Restore only original parsing behavior. -for f in ['DataCenter/TotalRechargeManager.cs','MatchGame/MatchGameManager.cs','MiniBP/MiniBattlePassDataProvider.cs','EventLuckGame/EventLuckyGameModel.cs','EventWelcomeBack/EventWelcomeBackManager.cs','UI/AdWheel/AdWheelManager.cs','UI/OfferSweep/OfferSweepManager.cs','UI/JigsawPuzzle/JigsawPuzzleManager.cs']: - old=original(f); current=read(f) - # These files have only storage wiring + the inspected parsing changes; keep the current binding. - binding=' readonly game.PlayerDataStorage.IPlayerSaveStore saveStore = GContext.container.Resolve();\n\n' - assert current.count(binding)==1,f - prefix=current.split(binding)[0] - # Locate class opening in original without relying on line endings/BOM. - anchor='\n'.join(prefix.splitlines()[-2:])+'\n' - at=old.index(anchor)+len(anchor) - s=old[:at]+binding+old[at:] - s=storage(s,'saveStore') - if f=='MiniBP/MiniBattlePassDataProvider.cs': - s=s.replace(' public MiniBattlePassRecord GetMiniBattlePassRecord(string key)\n {',' public MiniBattlePassRecord GetMiniBattlePassRecord(string key)\n {\n if (!saveStore.IsCurrent) throw new System.InvalidOperationException("Expired battle pass session.");') - write(f,s) -f='Event/AEventDataManager.cs' -old=original(f);s=read(f) -a=s.index(' var read = SaveStore.Read(typeof(T).Name);') -b=s.index('\n }',a) -oa=old.index(' var dataStr = PlayFabMgr.Instance.GetLocalData(typeof(T).Name);') -ob=old.index('\n }',oa) -write(f,s[:a]+storage(old[oa:ob],'SaveStore')+s[b:]) -# Exact original archive branches, including the old null behavior; retain async session checks. -for f in ['DataCenter/FishingEventData_OneOne.cs','DataCenter/FishingEventData_OneTwo.cs']: - write(f,storage(original(f),'playerSaveStore')) -f='DataCenter/FishingEvent_PVPData.cs';s=read(f);old=original(f) -for method in ['public void SoloCheckClaimReward()','public void InitSoloData(FishingEvent t)']: - a=s.index(method);b=s.index('\n public ',a+len(method)) - oa=old.index(method);ob=old.index('\n public ',oa+len(method)) - s=s[:a]+storage(old[oa:ob],'playerSaveStore')+s[b:] -write(f,s) -f='DataCenter/DataCenter.FishingEventData.cs';s=read(f) -a=s.index(' T ReadEventArchive');b=s.index(' private cfg.Tables _tables;',a) -s=s[:a]+s[b:] -for line in [' List errors = null;\n',' (errors ??= new List()).Add(e);\n',' if (errors != null) throw new AggregateException("Activity refresh did not complete.", errors);\n']: - assert s.count(line)==1,line - s=s.replace(line,'',1) -write(f,s) -print('Restored original activity flows; retained store wiring and existing session isolation.') diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/000-EventDataRepository.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/000-EventDataRepository.cs.txt deleted file mode 100644 index 97e25f886..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/000-EventDataRepository.cs.txt +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using Newtonsoft.Json; -using UnityEngine; - -namespace Activity.Data -{ - /// - /// 使用本次登录绑定的存档提供方,保留活动类型名作为存档键。 - /// - public class EventDataRepository : IEventDataRepository - { - readonly game.PlayerDataStorage.IPlayerSaveStore store; - public EventDataRepository(game.PlayerDataStorage.IPlayerSaveStore store) - { this.store = store ?? throw new ArgumentNullException(nameof(store)); } - public void Save(T data) where T : IEventData - { - if (data == null) - { - Debug.LogWarning($"[EventDataRepository] Cannot save null data for {typeof(T).Name}"); - return; - } - - try - { - var json = JsonConvert.SerializeObject(data); -#if UNITY_EDITOR - Debug.Log($"[EventDataRepository] Saving {typeof(T).Name}: {json}"); -#endif - store.Write(typeof(T).Name, json).RequireAccepted(); - } - catch (Exception e) - { - Debug.LogError($"[EventDataRepository] Failed to save {typeof(T).Name}: {e.Message}\n{e.StackTrace}"); - throw; - } - } - - public T Load() where T : IEventData, new() - { - try - { - var read = store.Read(typeof(T).Name); - var dataStr = read.ValueOrThrow(); - if (read.Found == false) return new T(); - if (string.IsNullOrWhiteSpace(dataStr) || dataStr.Trim() == "null") - throw new JsonSerializationException("Stored activity data cannot be empty or null."); -// #if UNITY_EDITOR -// Debug.Log($"[EventDataRepository] Load {typeof(T).Name}: {dataStr}"); -// #endif - var data = JsonConvert.DeserializeObject(dataStr); - if (data == null) throw new JsonSerializationException("Stored activity data cannot be null."); - return data; - } - catch (Exception e) - { - Debug.LogError($"[EventDataRepository] Failed to load {typeof(T).Name}: {e.Message}\n{e.StackTrace}"); - throw; - } - } - - public bool Exists() where T : IEventData - { - var read = store.Read(typeof(T).Name); - read.ValueOrThrow(); - return read.Found.Value; - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/001-EventTokenService.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/001-EventTokenService.cs.txt deleted file mode 100644 index d6e456d2f..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/001-EventTokenService.cs.txt +++ /dev/null @@ -1,329 +0,0 @@ -using System; -using System.Collections.Generic; -using asap.core; -using UnityEngine; - -namespace Activity -{ - /// - /// 入账/扣账成功后由 发布, - /// 供各活动自行判断是否刷新入口合并红点等(避免订阅者与具体玩法耦合)。 - /// - public readonly struct ActivityEventTokenBalanceChanged - { - public int EventId { get; } - - public ActivityEventTokenBalanceChanged(int eventId) - { - EventId = eventId; - } - } -} - -namespace Activity.Services -{ - /// - /// 活动代币服务实现 - /// 负责管理所有活动的代币数据,提供统一的存储接口 - /// - public class EventTokenService : IEventTokenService - { - #region 常量与字段 - - private const string TransitionDataKey = "TransitionData"; - - private Dictionary _tokenData = new Dictionary(); - private readonly object _lock = new object(); - private bool _isInitialized; - private readonly game.PlayerDataStorage.IPlayerSaveStore store; - public EventTokenService(game.PlayerDataStorage.IPlayerSaveStore store) - { this.store = store ?? throw new ArgumentNullException(nameof(store)); } - #endregion - - #region 初始化 - - public void Initialize() - { - lock (_lock) - { - if (!store.IsCurrent) throw new InvalidOperationException("Activity token session is no longer current."); - if (_isInitialized) return; - var read = store.Read(TransitionDataKey); - var value = read.ValueOrThrow(); - Dictionary loaded; - if (read.Found == false) loaded = new Dictionary(); - else - { - if (string.IsNullOrWhiteSpace(value)) - throw new Newtonsoft.Json.JsonSerializationException("Stored activity tokens cannot be empty."); - loaded = Newtonsoft.Json.JsonConvert.DeserializeObject>(value); - if (loaded == null) throw new Newtonsoft.Json.JsonSerializationException("Stored activity tokens cannot be null."); - } - _tokenData = loaded; - _isInitialized = true; - } - } - - // Publish the candidate balance only after the current store accepts its exact JSON. - // Acceptance remains distinct from cloud confirmation, which belongs to the enclosing action. - private void SaveTokens(Dictionary candidate) - { - store.Write(TransitionDataKey, Newtonsoft.Json.JsonConvert.SerializeObject(candidate)).RequireAccepted(); - _tokenData = candidate; - } - - #endregion - - #region 基础操作 - - public void AddToken(int eventId, int count) - { - if (eventId <= 0) - { - Debug.LogWarning($"[EventTokenService] Invalid eventId: {eventId}"); - return; - } - - if (count == 0) - return; - - lock (_lock) - { - try - { - EnsureInitialized(); - var currentCount = GetTokenCount(eventId); - var candidate = new Dictionary(_tokenData); - candidate[eventId] = currentCount + count; - SaveTokens(candidate); - -#if UNITY_EDITOR - Debug.Log($"[EventTokenService] Added {count} tokens to event {eventId}, new total: {_tokenData[eventId]}"); -#endif - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] AddToken failed for event {eventId}: {e.Message}"); - throw; - } - } - - PublishActivityEventTokenBalanceChanged(eventId); - } - - public int RemoveToken(int eventId, int count) - { - if (eventId <= 0) - { - Debug.LogWarning($"[EventTokenService] Invalid eventId: {eventId}"); - return 0; - } - - int actualRemoved = 0; - lock (_lock) - { - try - { - EnsureInitialized(); - var currentCount = GetTokenCount(eventId); - actualRemoved = Mathf.Min(count, currentCount); - var newCount = currentCount - actualRemoved; - - var candidate = new Dictionary(_tokenData); - if (newCount <= 0) - { - candidate.Remove(eventId); - } - else - { - candidate[eventId] = newCount; - } - - SaveTokens(candidate); - -#if UNITY_EDITOR - Debug.Log($"[EventTokenService] Removed {actualRemoved} tokens from event {eventId}, remaining: {newCount}"); -#endif - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] RemoveToken failed for event {eventId}: {e.Message}"); - throw; - } - } - - PublishActivityEventTokenBalanceChanged(eventId); - - return actualRemoved; - } - - public int GetTokenCount(int eventId) - { - if (eventId <= 0) return 0; - - lock (_lock) - { - try - { - EnsureInitialized(); - return _tokenData.GetValueOrDefault(eventId, 0); - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] GetTokenCount failed for event {eventId}: {e.Message}"); - throw; - } - } - } - - public void SetToken(int eventId, int count) - { - if (eventId <= 0) - { - Debug.LogWarning($"[EventTokenService] Invalid eventId: {eventId}"); - return; - } - - lock (_lock) - { - try - { - EnsureInitialized(); - var candidate = new Dictionary(_tokenData); - candidate[eventId] = count; - SaveTokens(candidate); - -#if UNITY_EDITOR - Debug.Log($"[EventTokenService] Set event {eventId} token count to {count}"); -#endif - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] SetToken failed for event {eventId}: {e.Message}"); - throw; - } - } - } - - public void ClearToken(int eventId) - { - if (eventId <= 0) return; - - lock (_lock) - { - try - { - EnsureInitialized(); - var candidate = new Dictionary(_tokenData); - if (candidate.Remove(eventId)) - { - SaveTokens(candidate); - } - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] ClearToken failed for event {eventId}: {e.Message}"); - throw; - } - } - } - - #endregion - - #region 批量操作 - - public Dictionary GetAllTokens() - { - lock (_lock) - { - EnsureInitialized(); - return new Dictionary(_tokenData); - } - } - - public void SetTokens(Dictionary tokens) - { - if (tokens == null) return; - - lock (_lock) - { - try - { - EnsureInitialized(); - var candidate = new Dictionary(); - foreach (var kvp in tokens) - { - if (kvp.Key > 0) - { - candidate[kvp.Key] = kvp.Value; - } - } - SaveTokens(candidate); - -#if UNITY_EDITOR - Debug.Log($"[EventTokenService] Set {tokens.Count} token entries"); -#endif - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] SetTokens failed: {e.Message}"); - throw; - } - } - } - - public void ClearTokens(IEnumerable eventIds) - { - if (eventIds == null) return; - - lock (_lock) - { - try - { - EnsureInitialized(); - var candidate = new Dictionary(_tokenData); - bool changed = false; - foreach (var eventId in eventIds) - { - if (candidate.Remove(eventId)) - { - changed = true; - } - } - if (changed) - { - SaveTokens(candidate); - } - } - catch (Exception e) - { - Debug.LogError($"[EventTokenService] ClearTokens failed: {e.Message}"); - throw; - } - } - } - - #endregion - - #region 私有辅助方法 - - private void EnsureInitialized() - { - Initialize(); - } - - private static void PublishActivityEventTokenBalanceChanged(int eventId) - { - try - { - GContext.Publish(new Activity.ActivityEventTokenBalanceChanged(eventId)); - } - catch - { - // GContext 未就绪等 - } - } - - #endregion - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/002-AquariumManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/002-AquariumManager.cs.txt deleted file mode 100644 index 22fde5497..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/002-AquariumManager.cs.txt +++ /dev/null @@ -1,700 +0,0 @@ -using asap.core; -using cfg; -using game; -using GameCore; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using UnityEngine; - -public class AquariumManager -{ - public const string AquariumEventDataNewKey = "AquariumEventDataNewKey"; - readonly game.PlayerDataStorage.IPlayerSaveStore saveStore; - readonly IUserService loginUser; - private cfg.Tables _tables; - private ICustomServerMgr customServerMgr; - public AquariumManagerData data { get; private set; } - public int MapId => data.mapId; - public int Slot => data.slot; - public List eggNames; - public List sellList; - public AquariumManager() - { - saveStore = GContext.container.Resolve(); - loginUser = GContext.container.Resolve(); - _tables = GContext.container.Resolve(); - customServerMgr = GContext.container.Resolve(); - } - public static AquariumManagerData GetAquariumManagerData(game.PlayerDataStorage.IPlayerSaveStore store = null) - { - var source = store ?? GContext.container.Resolve(); - string dataStr = source.Read(AquariumEventDataNewKey).ValueOrThrow(); - if (!string.IsNullOrEmpty(dataStr)) - { - try - { - return AquariumManagerData.Deserialize(dataStr); - } - catch (Exception e) - { - Debug.LogError($"GetAquariumManagerData Deserialize Error:{e}"); - throw; - } - } - return null; - } - public async Task Synchrodata() - { - //从服务器拿数据 - if (!saveStore.IsCurrent) throw new OperationCanceledException(); - var dataSever = GetAquariumManagerData(saveStore); - if (dataSever == null) - { - //新数据 - data = new AquariumManagerData(); - data.startTime = ZZTimeHelper.UtcNow().AddDays(-2); - data.refreshCount = 0; - data.adCount = 0; - data.refreshDay = ZZTimeHelper.UtcNow().UtcNowOffset().Date.DayOfYear; - - data.slot = GContext.container.Resolve().benefitsAquariumLimit; - } - else - { - data = dataSever; - if (data.slotDatas == null || data.slotDatas.Count < data.slot) - { - return; - } - GetAquariumDataRequest request = new GetAquariumDataRequest(); - request.playFabId = loginUser.UserId; - string result = await customServerMgr.CustomServerPost("aquarium/GetAquariumData", Newtonsoft.Json.JsonConvert.SerializeObject(request)); - if (!saveStore.IsCurrent) throw new OperationCanceledException(); - AquariumServerData serverData = null; - if (result != null) - { - var resp = JsonConvert.DeserializeObject(result); - if (resp.code == 0) - { - serverData = resp.data; - } - else if (resp.code == 1) - { - Debug.LogWarning("GetAquariumDataRequest Null"); - } - else - { - Debug.LogError("GetAquariumDataRequest Null"); - } - } - if (serverData != null) - { - data.aquariumHurtDatas = serverData.aquariumHurtDatas ?? new List(); - int count = data.slot - data.aquariumHurtDatas.Count; - if (count > 0) - { - for (int i = 0; i < count; i++) - { - AquariumHurtData aquariumHurtData = new AquariumHurtData(); - data.aquariumHurtDatas.Add(aquariumHurtData); - } - } - data.aquariumResultDatas = serverData.aquariumResultDatas ?? new List(); - count = data.slot - data.aquariumResultDatas.Count; - if (count > 0) - { - for (int i = 0; i < count; i++) - { - AquariumResultData aquariumResultData = new AquariumResultData(); - data.aquariumResultDatas.Add(aquariumResultData); - } - } - } - - SetJury(); - //保存 数据 - SaveData(serverData == null); - } - } - void SetJury() - { - var dateTime = ZZTimeHelper.UtcNow(); - AquariumFish aquariumFish = null; - for (int i = 0; i < data.slot; i++) - { - AquariumSlotData slotData = data.slotDatas[i]; - slotData.index = i; - AquariumHurtData aquariumHurtData = data.aquariumHurtDatas[i]; - //没有受新伤 - if (aquariumHurtData.injuryTime < slotData.allRecoveryTime + 0.0001f) - { - continue; - } - - var HatchTime = slotData.FishHatchTime(); - //还没孵化 - if (HatchTime > dateTime) - { - continue; - } - //检查是否受伤 - //正常的成长时间 自然时间+加速成长-总恢复时间 - float normalH = (float)(dateTime - HatchTime).TotalHours + slotData.accelerationGrowth - slotData.allRecoveryTime; - //受伤时的成长时间 受伤时的时间+加速成长-受伤时的总恢复时间 - float injuryH = slotData.injuryGrowthTime; - - aquariumFish = _tables.TbAquariumFish.GetOrDefault(slotData.aquariumFishID); - //受伤时的成长进度大于正常的成长进度=还没恢复 - if (injuryH > normalH) - { - var recoveryTime = UnityEngine.Random.Range(aquariumFish.RecoveryTime[0], aquariumFish.RecoveryTime[1]); - slotData.recoveryTime = recoveryTime; - recoveryTime -= injuryH - normalH; - //处于受伤状态刷新时间 - if (recoveryTime > 0) - { - slotData.allRecoveryTime += recoveryTime; - } - } - else - { - //不处于受伤状态添加受伤时间 - //当前正常的成长进度 自然时间+加速成长 - 全部恢复时间 - //受伤时的成长时间 受伤时的时间+加速成长-受伤时的总恢复时间 - - slotData.injuryGrowthTime = (float)(dateTime - HatchTime).TotalHours + slotData.accelerationGrowth - slotData.allRecoveryTime; - slotData.recoveryTime = UnityEngine.Random.Range(aquariumFish.RecoveryTime[0], aquariumFish.RecoveryTime[1]); - slotData.allRecoveryTime += slotData.recoveryTime; - } - - } - } - public void GetRandmMap() - { - PlayerData playerData = GContext.container.Resolve(); - PlayerFishData playerFishData = GContext.container.Resolve(); - - data.startTime = ZZTimeHelper.UtcNow(); - data.slot = playerData.benefitsAquariumLimit; - List inits = _tables.TbAquariumInit.DataList; - if (data.startCount < inits.Count) - { - NewSlotInitData(inits[data.startCount]); - } - else - { - NewSlotData(); - } - data.refreshCount++; - data.isHome = false; - data.startCount++; - //保存 数据 - SaveData(true); - GContext.container.Resolve().RefreshTriggerPackData(4000201, data.mapId); - -#if AGG - int fishcard_totallevel = playerFishData.GetFishLevelByMap(data.mapId); - string egg_quality_list = data.slotDatas[0].eggId.ToString(); - for (int i = 1; i < data.slotDatas.Count; i++) - { - egg_quality_list = $"{egg_quality_list},{data.slotDatas[i].eggId}"; - } - using (var e = GEvent.GameEvent("aquarium_start")) - { - e.AddContent("map_id", data.mapId) - .AddContent("total_eggpots", data.slot) - .AddContent("fishcard_totallevel", fishcard_totallevel) - .AddContent("egg_quality_list", egg_quality_list); - } -#endif - } - void NewSlotInitData(AquariumInit init) - { - data.mapId = init.MapID; - List slotDatas = new List(); - List aquariumHurtDatas = new List(); - List aquariumResultDatas = new List(); - DateTime dateTime = ZZTimeHelper.UtcNow(); - - List TankEggList = _tables.TbAquariumEgg.DataList; - eggNames = new List(); - for (int i = 0; i < TankEggList.Count; i++) - { - eggNames.Add(TankEggList[i].Icon); - } - - List Egglist = init.Egglist; - List FishQualitylist = init.FishQualitylist; - List FishList = init.Fishlist; - List FishQuatitylist = init.FishQuatitylist; - List FishMutantlist = init.FishMutantlist; - - - for (int i = 0; i < data.slot; i++) - { - AquariumSlotData aquariumSlotData = new AquariumSlotData(); - aquariumSlotData.eggId = Egglist[i]; - aquariumSlotData.aquariumFishID = FishQualitylist[i]; - aquariumSlotData.fishMQ = FishQuatitylist[i]; - aquariumSlotData.fishItemID = FishList[i]; - - var tankEgg = _tables.TbAquariumEgg.GetOrDefault(Egglist[i]); - - aquariumSlotData.startTime = dateTime; - aquariumSlotData.hatchTime = UnityEngine.Random.Range(tankEgg.HatchTime[0], tankEgg.HatchTime[1]); - - AquariumFish aquariumFish = _tables.TbAquariumFish.GetOrDefault(FishQualitylist[i]); - - float allCash = SetRewardCount(aquariumFish.SoldReward); - float soldRewardRand = UnityEngine.Random.Range(0, aquariumFish.SoldRewardRand) - aquariumFish.SoldRewardRand * 0.5f; - aquariumSlotData.allCash = allCash * (1 + soldRewardRand); - - aquariumSlotData.growthTime = UnityEngine.Random.Range(aquariumFish.GrowthTime[0], aquariumFish.GrowthTime[1]); - aquariumSlotData.mutants = FishMutantlist[i]; - aquariumSlotData.index = i; - slotDatas.Add(aquariumSlotData); - - AquariumHurtData aquariumHurtData = new AquariumHurtData(); - aquariumHurtDatas.Add(aquariumHurtData); - - AquariumResultData aquariumResultData = new AquariumResultData(); - aquariumResultDatas.Add(aquariumResultData); - } - data.slotDatas = slotDatas; - data.aquariumHurtDatas = aquariumHurtDatas; - data.aquariumResultDatas = aquariumResultDatas; - } - - void SetAquariumFish(MapData mapData, AquariumSlotData aquariumSlotData, AquariumEgg tankEgg) - { - List fishList = mapData.DropFishList; - - //权重取鱼 - int allProb = tankEgg.HatchFishQualityProb.Sum(); - int prob = UnityEngine.Random.Range(0, allProb); - int curProb = 0; - int fishQuality = tankEgg.HatchFishQuality[^1]; - for (int k = 0; k < tankEgg.HatchFishQuality.Count; k++) - { - curProb += tankEgg.HatchFishQualityProb[k]; - if (curProb > prob) - { - fishQuality = tankEgg.HatchFishQuality[k]; - break; - } - } - //品质大于6??? - if (6 > fishQuality) - { - List FishIDList = fishList[fishQuality - 1].FishIDList; - aquariumSlotData.fishItemID = FishIDList[UnityEngine.Random.Range(0, FishIDList.Count)]; - } - else - { - List FishIDList = _tables.TbAquariumConfig.AquariumSpFishList; - aquariumSlotData.fishItemID = FishIDList[UnityEngine.Random.Range(0, FishIDList.Count)]; - } - aquariumSlotData.aquariumFishID = fishQuality; - //取鱼的数量 - allProb = tankEgg.HatchFishQuantityProb.Sum(); - prob = UnityEngine.Random.Range(0, allProb); - curProb = 0; - int fishCount = tankEgg.HatchFishQuantity[0]; - for (int k = 0; k < tankEgg.HatchFishQuantity.Count; k++) - { - curProb += tankEgg.HatchFishQuantityProb[k]; - if (curProb > prob) - { - fishCount = tankEgg.HatchFishQuantity[k]; - break; - } - } - aquariumSlotData.fishMQ = fishCount; - } - - void SetTime(AquariumSlotData aquariumSlotData, AquariumEgg tankEgg) - { - aquariumSlotData.hatchTime = UnityEngine.Random.Range(tankEgg.HatchTime[0], tankEgg.HatchTime[1]); - - AquariumFish aquariumFish = _tables.TbAquariumFish.GetOrDefault(aquariumSlotData.aquariumFishID); - - float allCash = SetRewardCount(aquariumFish.SoldReward); - float soldRewardRand = UnityEngine.Random.Range(0, aquariumFish.SoldRewardRand) - aquariumFish.SoldRewardRand * 0.5f; - aquariumSlotData.allCash = allCash * (1 + soldRewardRand); - - aquariumSlotData.growthTime = UnityEngine.Random.Range(aquariumFish.GrowthTime[0], aquariumFish.GrowthTime[1]); - aquariumSlotData.mutants = 0; - for (int j = 0; j < aquariumSlotData.fishMQ; j++) - { - if (UnityEngine.Random.Range(0, 1f) < aquariumFish.MutantProb) - { - aquariumSlotData.mutants++; - } - } - } - void NewSlotData() - { - int curMapId = MapId; - - var mapDatas = _tables.TbMapData.DataList; - var maxMapID = GContext.container.Resolve().lastMapId; - - //非当前地图 - var mapIDs = new List(); - for (int i = 0; i < mapDatas.Count; i++) - { - if (mapDatas[i].ID <= maxMapID) - { - if (mapDatas[i].ID != curMapId) - { - mapIDs.Add(mapDatas[i].ID); - } - } - else - { - break; - } - } - if (mapIDs.Count == 0) - { - data.mapId = maxMapID; - } - else - { - data.mapId = mapIDs[UnityEngine.Random.Range(0, mapIDs.Count)]; - } - - List slotDatas = new List(); - List aquariumHurtDatas = new List(); - List aquariumResultDatas = new List(); - - DateTime dateTime = ZZTimeHelper.UtcNow(); - MapData mapData = _tables.TbMapData.GetOrDefault(data.mapId); - List TankEggList = _tables.TbAquariumEgg.DataList; - float eggAllWeight = -0.0001f; - eggNames = new List(); - for (int i = 0; i < TankEggList.Count; i++) - { - eggNames.Add(TankEggList[i].Icon); - eggAllWeight += TankEggList[i].Weight; - } - for (int i = 0; i < data.slot; i++) - { - AquariumSlotData aquariumSlotData = new AquariumSlotData(); - //权重取蛋 - float eggWeight = UnityEngine.Random.Range(0, eggAllWeight); - float curEggWeight = 0; - AquariumEgg tankEgg = TankEggList[0]; - foreach (var item in TankEggList) - { - curEggWeight += item.Weight; - if (curEggWeight > eggWeight) - { - tankEgg = item; - break; - } - } - aquariumSlotData.eggId = tankEgg.ID; - SetAquariumFish(mapData, aquariumSlotData, tankEgg); - aquariumSlotData.startTime = dateTime; - SetTime(aquariumSlotData, tankEgg); - aquariumSlotData.index = i; - slotDatas.Add(aquariumSlotData); - - AquariumHurtData aquariumHurtData = new AquariumHurtData(); - aquariumHurtDatas.Add(aquariumHurtData); - - AquariumResultData aquariumResultData = new AquariumResultData(); - aquariumResultDatas.Add(aquariumResultData); - } - data.slotDatas = slotDatas; - data.aquariumHurtDatas = aquariumHurtDatas; - data.aquariumResultDatas = aquariumResultDatas; - } - - public void Speedup(bool isGuide) - { - var dateTime = ZZTimeHelper.UtcNow(); - float AdAccelerate = _tables.TbAquariumConfig.AdAccelerate; - if (isGuide) - { - AdAccelerate = _tables.TbAquariumConfig.AdAccelerateFirst; - } - List slotDataList = data.slotDatas; - List aquariumReportDatas = data.aquariumResultDatas; - for (int i = 0; i < slotDataList.Count; i++) - { - var slotData = slotDataList[i]; - - //售卖或者丢失 - if (slotData.IsResult() || aquariumReportDatas[slotData.index].IsResult()) - { continue; } - var HatchTime = slotData.FishHatchTime(); - if (HatchTime <= dateTime) - { - //鱼加速 - slotData.accelerationGrowth += AdAccelerate; - } - else - { - float s = (float)(HatchTime - dateTime).TotalHours; - if (s <= 0) - { - slotData.accelerationGrowth += AdAccelerate; - } - else if (AdAccelerate > s) - { - slotData.accelerationHatch += s; - slotData.accelerationGrowth += AdAccelerate - s; - } - else - { - slotData.accelerationHatch += AdAccelerate; - } - } - } - data.adCount++; - SaveData(); - } - - public void SellFish(List slotDataList) - { - sellList = new List(); - var dateTime = ZZTimeHelper.UtcNow(); - PlayerData playerData = GContext.container.Resolve(); - var weight = GetWeightMag(); - AquariumFish aquariumFish; - FishData fishData; - DateTime startTime; - float injuryH; - float weightIncEvent; - List itemDatas = new List(); - PlayerFishData playerFishData = GContext.container.Resolve(); - float CashMag = (1 + playerData.benefitsCashMag) * (1 + playerData.benefitsAquariumCashMag); - for (int i = 0; i < slotDataList.Count; i++) - { - var slotData = slotDataList[i]; - sellList.Add(slotData); - if (slotData.allCash == 0) - { - slotData.allCash = 1; - } - //奖励 - aquariumFish = _tables.TbAquariumFish.GetOrDefault(slotData.aquariumFishID); - startTime = slotData.FishHatchTime(); - injuryH = slotData.injuryGrowthTime; - weightIncEvent = (1 + weight[slotData.aquariumFishID - 1]) * CashMag; - - float normalH = (float)(dateTime - startTime).TotalHours + slotData.accelerationGrowth - slotData.allRecoveryTime; - - float rewardProgress = normalH / slotData.growthTime; - - if (injuryH > normalH && injuryH > slotData.growthTime) - { - rewardProgress = 1 - ((injuryH - normalH) / slotData.growthTime); - } - - if (rewardProgress > 1) - { - rewardProgress = 1; - } - - //金币显示 - ItemData itemData = new ItemData(); - - int fishQ = slotData.fishMQ; - bool is_injured = false; - if (injuryH > normalH) - { - fishQ -= data.aquariumHurtDatas[slotData.index].fishLQ; - is_injured = true; - if (fishQ <= 0) - { - fishQ = 1; - } - } - if (rewardProgress < 0) - { - rewardProgress = 0; - } - for (int j = 0; j < fishQ; j++) - { - if (j < slotData.mutants) - { - itemData.count += (int)(slotData.allCash * (1 + aquariumFish.MutantGrowthExtraSoldReward * rewardProgress) * (1 + aquariumFish.MutantExtraSoldReward) * weightIncEvent); - } - else - { - itemData.count += (int)(slotData.allCash * (1 + aquariumFish.GrowthExtraSoldReward * rewardProgress) * weightIncEvent); - } - } - itemData.id = 1002; - - itemDatas.Add(itemData); - slotData.cash = itemData.count; - - //重量 - Item item = _tables.TbItem.GetOrDefault(slotData.fishItemID); - fishData = _tables.TbFishData.GetOrDefault(item.RedirectID); - //float weightCount = fishData.BaseWeight * (1 + aquariumFish.GrowthExtraSoldReward * rewardProgress) * weightIncEvent; - //playerFishData.SetWeight(fishData.ID, weightCount, false); -#if AGG - int cardLevel = playerFishData.GetDataLevel(fishData.ID); - using (var e = GEvent.GameEvent("aquarium_sell")) - { - e.AddContent("map_id", data.mapId) - .AddContent("total_eggpots", data.slot) - .AddContent("fish_eggs_quality", slotData.eggId) - .AddContent("mature_percent", rewardProgress) - .AddContent("fish_id", fishData.ID) - .AddContent("fishcard_level", cardLevel) - .AddContent("fish_quality", slotData.aquariumFishID) - .AddContent("mutant_count", slotData.mutants) - .AddContent("is_injured", is_injured) - .AddContent("fish_count", slotData.fishMQ) - .AddContent("is_dead", false) - .AddContent("reward_cash", slotData.cash); - } -#endif - } - //GContext.Publish(new ShowData(itemDatas)); - GContext.container.Resolve().AddItem(itemDatas, null); - //GContext.Publish(new ShowData()); - CheckInHome(); - SaveData(); - } - - public float SetRewardCount(int dropID) - { - DropPackageList dropPackageList = _tables.TbDrop[dropID].DropList; - return dropPackageList.DropCountList[0]; - } - - public void CheckInHome() - { - data.isHome = true; - List aquariumResultDatas = data.aquariumResultDatas; - var slotDatas = data.slotDatas; - for (int i = 0; i < data.slot; i++) - { - if (!slotDatas[i].IsResult() && !aquariumResultDatas[i].IsResult()) - { - data.isHome = false; - } - } - if (data.isHome) - { -#if AGG - PlayerFishData playerFishData = GContext.container.Resolve(); - for (int i = 0; i < data.slot; i++) - { - if (!slotDatas[i].IsResult() && aquariumResultDatas[i].IsResult()) - { - var fishItem = _tables.TbItem.GetOrDefault(slotDatas[i].fishItemID); - int cardLevel = playerFishData.GetDataLevel(fishItem.RedirectID); - using (var e = GEvent.GameEvent("aquarium_sell")) - { - e.AddContent("map_id", data.mapId) - .AddContent("total_eggpots", data.slot) - .AddContent("fish_eggs_quality", slotDatas[i].eggId) - .AddContent("mature_percent", 0) - .AddContent("fish_id", fishItem.RedirectID) - .AddContent("fishcard_level", cardLevel) - .AddContent("fish_quality", slotDatas[i].aquariumFishID) - .AddContent("mutant_count", slotDatas[i].mutants) - .AddContent("is_injured", true) - .AddContent("is_dead", true) - .AddContent("fish_count", 0) - .AddContent("reward_cash", 0); - } - } - } -#endif - UpdateUserData(); - //_ = UIManager.Instance.ShowUI(UITypes.AquariumReportPopupPanel); - } - } - void UpdateUserData() - { - saveStore.Write(AquariumEventDataNewKey, data.Serialize()).RequireAccepted(); - } - void SaveData(bool all = false) - { - List slotDatas = data.slotDatas; - //鱼卡等级 - PlayerFishData playerFishData = GContext.container.Resolve(); - List cardLv = new List(); - for (int i = 0; i < slotDatas.Count; i++) - { - var fishItem = _tables.TbItem.GetOrDefault(slotDatas[i].fishItemID); - if (fishItem.Quality < 6) - { - int level = playerFishData.GetDataLevel(fishItem.RedirectID); - cardLv.Add(level); - } - else - { - int level = GContext.container.Resolve().benefitsLevel[4]; - cardLv.Add(level); - } - } - - if (all) - { - UpdateAquariumAllDataRequest request = new UpdateAquariumAllDataRequest(); - request.playFabId = loginUser.UserId; - request.data = new AquariumServerData() - { - startTime = data.startTime, - mapId = data.mapId, - slot = data.slot, - slotDatas = data.slotDatas, - cardLv = string.Join(',', cardLv), - aquariumResultDatas = data.aquariumResultDatas, - aquariumHurtDatas = data.aquariumHurtDatas, - }; - customServerMgr.CustomServerPost("aquarium/UpdateAquariumData", Newtonsoft.Json.JsonConvert.SerializeObject(request)); - } - else - { - UpdateSlotDatasRequest request = new UpdateSlotDatasRequest(); - request.playFabId = loginUser.UserId; - request.slotDatas = data.slotDatas; - request.cardLv = string.Join(',', cardLv); - customServerMgr.CustomServerPost("aquarium/UpdateSlotData", Newtonsoft.Json.JsonConvert.SerializeObject(request)); - } - UpdateUserData(); - } - - public List GetWeightMag() - { - PlayerFishData playerFishData = GContext.container.Resolve(); - PlayerData playerData = GContext.container.Resolve(); - List weight = new List() { 0, 0, 0, 0, 0, 0 }; - List fishCount = new List() { 0, 0, 0, 0, 0, 0 }; - MapData mapData = _tables.TbMapData.GetOrDefault(data.mapId); - var fishList = mapData.FishList; - for (int j = 0; j < fishList.Count; j++) - { - var data = _tables.TbFishData.GetOrDefault(fishList[j]); - fishCount[data.Quality - 1]++; - int level = playerFishData.GetDataLevel(fishList[j]); - if (level > 0) - { - FishCard fishCard = _tables.TbFishCard.GetOrDefault(data.FishCardID); - weight[data.Quality - 1] += fishCard.WeightMagList[level - 1]; - } - } - for (int i = 0; i < weight.Count; i++) - { - weight[i] /= fishCount[i]; - } - weight[5] = playerData.benefitsEventFishCashMag; - - return weight; - } -} - diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/003-CampDataMM.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/003-CampDataMM.cs.txt deleted file mode 100644 index 6f1bc3082..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/003-CampDataMM.cs.txt +++ /dev/null @@ -1,790 +0,0 @@ -using asap.core; -using cfg; -using game; -using GameCore; -using LitJson; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -public class CampDataMM -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - private cfg.Tables _tables; - MMTService _MMService; - public CampDataMM(cfg.Tables tables, MMTService mmService) - { - this._tables = tables; - _MMService = mmService; - } - - #region SERVER_DATA - int _id = 101; - public int PreID; - public int Id - { - set { _id = value; } - get - { - return _id; - } - } - public int AreaIndex { get; private set; } = 0; - public int AreaStep { get; private set; } = 0; - Dictionary CampDataDic = new Dictionary(); - #endregion - - public int AreaId { get; private set; } = 0; - public int AreaStepCount { get; private set; } - public int TimelineId { get; private set; } - public string Name { get { return GetMMTString(_tables.TbConstruction.DataMap[Id].Name_l10n_key); } } - - public string AreaIcon { get; private set; } - public string BasePrefab => GetBasePrefab(Id); - public List AllPrefabs - { - get - { - List AreaList = _tables.TbConstruction.DataMap[Id].AreaList; - return AreaList.Select(stepid => GetArea(stepid).BuildingPrefeb).Distinct().ToList(); - } - } - - - public string CurrentPrefab - { - get - { - int index = AreaIndex; - if (index >= AreaList.Count) - index = AreaList.Count - 1; - - return GetArea(AreaList[index]).BuildingPrefeb; - } - } - - - public Area GetAreaByIndex(int index) - { - if (index >= AreaList.Count) - index = AreaList.Count - 1; - return GetArea(AreaList[index]); - } - - - public string BGM { get { return _tables.TbConstruction.DataMap[Id].BGM; } } - public int NextMapID { get { return _tables.TbConstruction.DataMap[Id].NextID; } } - public Area constructionArea { get; private set; } - public Step StepInfo { get; private set; } - public List AreaList - { - get - { - return _tables.TbConstruction.DataMap[Id].AreaList; - } - } - - public List AreaStepList { get; private set; } - - public bool IsUpdataArea = false; - string _isOpenSkyscraper = "0"; - public bool IsOpenSkyscraper => _isOpenSkyscraper == "1" || IsCanSkyscraper; - public bool IsCanSkyscraper - { - get - { - var dataMap = _tables.TbMapData.DataList[^1]; - return GContext.container.Resolve().lv >= dataMap.LevelRequired; - } - } - //public int curQRewardCount = 0; - //是否需要修复 - public bool IsFix => _isFix && AreaIndex < AreaList.Count; - bool _isFix; - - internal static game.PlayerDataStorage.PlayerKVCampState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeCamp(raw,errors); - internal void ResetForKVLoad() - { - CampDataDic=new Dictionary(StringComparer.Ordinal); - _isFix=false; _isOpenSkyscraper="0"; _id=101; - PreID=AreaIndex=AreaStep=AreaId=AreaStepCount=TimelineId=0; - AreaIcon=null; constructionArea=null; StepInfo=null; AreaStepList=null; IsUpdataArea=false; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVCampState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - CampDataDic=state.Values.ToDictionary(p=>p.Key,p=>p.Value,StringComparer.Ordinal); - _isFix=state.IsFix; _isOpenSkyscraper=state.Skyscraper; - } - internal game.PlayerDataStorage.PlayerKVCampState SnapshotForKVValidation() => - new game.PlayerDataStorage.PlayerKVCampState(_isFix,_isOpenSkyscraper,CampDataDic); - public void InitData(Dictionary userData) - { - string value; - - if (userData.TryGetValue("IsFix", out value)) - { - SetIsFix(bool.Parse(value), false); - } - if (userData.TryGetValue("IsOpenSkyscraper", out value)) - { - _isOpenSkyscraper = value; - } - - if (userData.TryGetValue("CampDataDic", out value)) - { - CampDataDic = JsonMapper.ToObject>(value); - } - } - public void SetIsFix(bool isFix, bool isSave = true) - { - _isFix = isFix; - if (isSave) - { - SaveStore.Write("IsFix", _isFix.ToString()).RequireAccepted(); - } - } - - public void SetCampAreaIndex(string id_string) - { - AreaIndex = GlobalUtils.TryParseInt(id_string); - } - - public void SetCampAreaStep(string step_string) - { - AreaStep = GlobalUtils.TryParseInt(step_string); - } - void SetCampByLevel() - { - List _dataList = _tables.TbConstruction.DataList; - if (!_tables.TbConstruction.DataMap.ContainsKey(Id)) - { - Debug.LogError($"[CampData]UpdateCurrentData: Not found data of id({Id})!"); - Id = _dataList[^1].ID; - } - int level = GContext.container.Resolve().lv; - int id = _dataList[0].ID; - for (int i = _dataList.Count - 1; i >= 0; i--) - { - if (_dataList[i].InitialLevel <= level) - { - id = _dataList[i].ID; - level -= _dataList[i].InitialLevel; - break; - } - } - - AreaIndex = AreaList.Count; - var _area = GetArea(AreaList[^1]); - int StepCount = _area.StepCount; - AreaStep = StepCount; - if (id % 1000 <= Id % 1000) - { - Id = id; - AreaIndex = AreaList.Count; - for (int i = 0; i < AreaList.Count; i++) - { - _area = GetArea(AreaList[i]); - StepCount = _area.StepCount; - if (StepCount > level) - { - AreaIndex = i; - AreaStep = level; - break; - } - level -= StepCount; - } - } - } - public void Init() - { - if (CampDataDic.Count > 0) - { - Id = CampDataDic["CampId"]; - } - SetCampByLevel(); - PreID = Id; - if (_tables.TbConstruction.DataMap.ContainsKey(Id)) - { - if (AreaIndex >= AreaList.Count) - { - CompleteInit(); - } - else - { - UpdateCurrentData(); - } - } - else - { - Debug.LogError($"[CampData]UpdateCurrentData: Not found data of id({Id})!"); - } - } - - public void ChangeNextCampID() - { - OnChangeCamp(NextMapID); - } - public void ChangeCampId(int id) - { - OnChangeCamp(id); - } - - void OnChangeCamp(int id) - { - if (_tables.TbConstruction.DataMap.TryGetValue(id, out var camp_data)) - { - constructionArea = null; - Id = id; - PreID = Id; - SetCampByLevel(); - if (AreaIndex >= AreaList.Count) - { - CompleteInit(); - } - else - { - UpdateCurrentData(); - } - CampDataDic["CampId"] = Id; - SaveStore.Write("CampDataDic", JsonMapper.ToJson(CampDataDic)).RequireAccepted(); ; - } - else - { - Debug.LogError($"[CampData]UpdateCurrentData: Not found data of id({id})!"); - } - } - - public void ShowReward() - { - int lv = GContext.container.Resolve().lv; - if (_tables.TbGlobalConfig.AutoClaimUnlock > 0 && lv > _tables.TbGlobalConfig.AutoClaimUnlock) - GContext.Publish(new ShowData(RewardType.AutoOpen)); - else - GContext.Publish(new ShowData()); - - } - - - public void UpdateCurrentData() - { - if (AreaList != null) - { - if (AreaIndex < 0 || AreaIndex >= AreaList.Count) - { - if (NextMapID == -1 || !_tables.TbConstruction.DataMap.ContainsKey(NextMapID)) - { - _isOpenSkyscraper = "1"; - SaveStore.Write("IsOpenSkyscraper", _isOpenSkyscraper).RequireAccepted(); - return; - } - Debug.LogError( - $"[CampData]UpdateCurrentData: AreaIndex({AreaIndex}) is out of range[0-{AreaList.Count}]! Will reset to 0"); - AreaIndex = 0; - } - - IsUpdataArea = AreaId != AreaList[AreaIndex]; - if (IsUpdataArea) - { - AreaId = AreaList[AreaIndex]; - SetArea(); - } - - if (AreaStepList != null) - { - if (AreaStep < 0 || AreaStep >= AreaStepList.Count) - { - AreaStep = 0; - Debug.LogError( - $"[CampData]UpdateCurrentData: AreaStep({AreaStep}) is out of range[0-{AreaStepList.Count}]! Reset it to 0."); - } - - var step_id = AreaStepList[AreaStep]; - SetAreaStep(step_id); - } - else - { - Debug.LogError($"[CampData]UpdateCurrentData: AreaStepList is empty!"); - } - } - else - { - Debug.LogError($"[CampData]UpdateCurrentData: AreaList is empty!"); - } - } - - void SetArea() - { - constructionArea = GetArea(AreaId); - if (constructionArea == null) - { - Debug.LogError($"[CampData]UpdateCurrentData: Not found data of area id({AreaId})!"); - } - AreaIcon = constructionArea.Icon; - TimelineId = constructionArea.TimelineID; - - AreaStepCount = constructionArea.StepCount; - AreaStepList = constructionArea.StepList; - } - void SetAreaStep(int step_id) - { - StepInfo = GetStep(step_id); - - if (StepInfo == null) - { - Debug.LogError($"[CampData]UpdateCurrentData: Not found step data of id({step_id})!"); - } - } - void CompleteInit() - { - if (AreaList != null) - { - int curAreaIndex = AreaList.Count - 1; - AreaId = AreaList[curAreaIndex]; - - SetArea(); - - if (AreaStepList != null) - { - var step_id = AreaStepList[^1]; - SetAreaStep(step_id); - } - if (NextMapID == -1 || !_tables.TbConstruction.DataMap.ContainsKey(NextMapID)) - { - _isOpenSkyscraper = "1"; - SaveStore.Write("IsOpenSkyscraper", _isOpenSkyscraper).RequireAccepted(); - } - } - } - void SetHome_Skyscraper() - { - if (IsOpenSkyscraper) - { - if (IsCanSkyscraper) - { - ulong curGold = GContext.container.Resolve().gold; - ulong basePrice = - (ulong)GContext.container.Resolve().TbMapData.DataList[^1].ConstrutionCost; - var multiplierTable = GContext.container.Resolve().TbConstructionInfiniteConfig.CashMagList; - var ibData = new InfiniteBuildingData(); - ibData.Deserialize(GContext.container.Resolve().InfiniteBuildingData); - int step = ibData.Step; - ulong price = (ulong)(basePrice * multiplierTable[step]); - int count = 0; - while (curGold >= price) - { - curGold -= price; - step++; - step %= multiplierTable.Count; - price = (ulong)(basePrice * multiplierTable[step]); - count++; - if (count >= 99) - break; - } - - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Skyscraper, count > 0, (int)count); - } - else - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Skyscraper, false); - } - } - } - - public bool GoBuilding() - { - if (AreaStep >= AreaStepList.Count) - { - return false; - } - long gold = (long)(ulong)GContext.container.Resolve().gold; - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isConstructionCost = buffTimeData != null; - long _upgradeCost; - var step_id = AreaStepList[AreaStep]; - var camp_data = _tables.TbConstruction.DataMap[Id]; - List _areaStepList = AreaStepList; - int start; - int endIndex; - List _areaList; - _areaList = camp_data.AreaList; - start = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[step_id]); - _areaStepList = GetArea(_areaList[^1]).StepList; - endIndex = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[_areaStepList[^1]]); - List DataList = _tables.TbConstructionStep.DataList; - for (int i = start; i <= endIndex; i++) - { - if (isConstructionCost) - { - _upgradeCost = (long)(DataList[i].BuildRequired * (1 - buffTimeData.Param)); - } - else - { - _upgradeCost = DataList[i].BuildRequired; - } - gold -= _upgradeCost; - if (gold < 0) - { - return false; - } - } - return true; - } - public bool GoBuilding02(int endId) - { - if (AreaStep >= AreaStepList.Count) - { - return false; - } - var step_id = AreaStepList[AreaStep]; - if (step_id < 101003 || step_id >= endId) - { - return false; - } - long gold = (long)(ulong)GContext.container.Resolve().gold; - long _upgradeCost; - - int start = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[step_id]); - int endIndex = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[endId]); - List DataList = _tables.TbConstructionStep.DataList; - for (int i = start; i < endIndex; i++) - { - _upgradeCost = DataList[i].BuildRequired; - gold -= _upgradeCost; - if (gold < 0) - { - return false; - } - } - return true; - } - - /// - /// 从当前 起,用给定金币连续扣款,返回能支付多少步;含 ConstructionCost buff,与建造红点累计逻辑一致。全程 ,避免金币超出 long.MaxValue 时强转失真。 - /// - int CountAffordableConstructionSteps(ulong gold) - { - if (AreaStepList == null || AreaStep >= AreaStepList.Count) - { - return 0; - } - - var step_id = AreaStepList[AreaStep]; - int nextId = NextMapID; - var camp_data = _tables.TbConstruction.DataMap[Id]; - while (_tables.TbConstruction.DataMap.TryGetValue(nextId, out var _camp_data)) - { - camp_data = _camp_data; - nextId = camp_data.NextID; - } - - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isConstructionCost = buffTimeData != null; - - List _areaList = camp_data.AreaList; - int start = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[step_id]); - List _areaStepList = GetArea(_areaList[^1]).StepList; - int endIndex = _tables.TbConstructionStep.DataList.IndexOf(_tables.TbConstructionStep.DataMap[_areaStepList[^1]]); - int length = Math.Min(start + 100, endIndex + 1); - List DataList = _tables.TbConstructionStep.DataList; - - int count = 0; - for (int i = start; i < length; i++) - { - ulong stepCost = isConstructionCost - ? (ulong)(DataList[i].BuildRequired * (1 - buffTimeData.Param)) - : (ulong)DataList[i].BuildRequired; - if (gold < stepCost) - { - break; - } - - gold -= stepCost; - count++; - } - - return count; - } - - public void SetRedPoint() - { - SetHome_Skyscraper(); - int count = 0; - bool redPoint = false; - var playerData = GContext.container.Resolve(); - - if (GContext.container.Resolve().GetIsFinish(_tables.TbGlobalConfig.BuildRedPointUnlock) - && playerData.gold >= (ulong)StepInfo.BuildRequired) - { - if (AreaStepList == null || AreaStep >= AreaStepList.Count) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Build, redPoint, count); - return; - } - - count = CountAffordableConstructionSteps(playerData.gold); - redPoint = true; - } - - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Build, redPoint, count); - } - - - public int GetNextStepRequired(int allStep) - { - int price = 0; - if (!IsOpenSkyscraper || !IsCanSkyscraper) - { - if (AreaStep < AreaStepList.Count) - { - var step_id = AreaStepList[AreaStep]; - List BuildRequired = new List(); - List DataList = _tables.TbConstructionStep.DataList; - int start = DataList.IndexOf(_tables.TbConstructionStep.DataMap[step_id]); - int length = start + allStep; - - length = Math.Min(length, DataList.Count); - for (int i = start; i < length; i++) - { - allStep--; - price += DataList[i].BuildRequired; - } - } - } - if (allStep > 0) - { - int basePrice = GContext.container.Resolve().TbMapData.DataList[^1].ConstrutionCost; - var multiplierTable = GContext.container.Resolve().TbConstructionInfiniteConfig.CashMagList; - var ibData = new InfiniteBuildingData(); - ibData.Deserialize(GContext.container.Resolve().InfiniteBuildingData); - int step = ibData.Step; - for (int i = 0; i < allStep; i++) - { - price += (int)(basePrice * multiplierTable[step]); - step++; - step %= multiplierTable.Count; - } - } - return price; - } - public int GetStepRequired(int allStep) - { - int price = 0; - var start_id = AreaStepList[AreaStep]; - var lastAreaStepList = GetArea(_tables.TbConstruction.DataMap[Id].AreaList[^1]).StepList; - var end_id = lastAreaStepList[^1]; - if (end_id - start_id < allStep) - { - return -1; - } - List DataList = _tables.TbConstructionStep.DataList; - int start = DataList.IndexOf(_tables.TbConstructionStep.DataMap[start_id]); - int length = start + allStep; - for (int i = start; i < length; i++) - { - price += DataList[i].BuildRequired; - } - return price; - } - - public void NextStep() - { - if (AreaStepList != null) - { - AreaStep++; - - if (AreaStep < AreaStepList.Count) - { - UpdateCurrentData(); - } - else - { - AreaIndex++; - if (AreaIndex < AreaList.Count) - { - AreaStep = 0; - UpdateCurrentData(); - } - else - { - AreaIndex = AreaList.Count; - AreaStep = AreaStepList.Count; - - } - } - } - else - { - GameDebug.LogError($"[CampData]NextStep: AreaStepList is empty!"); - } - } - public Area GetArea(int id) - { - // if (id < 102000) - // { - // if (_MMService.MMBuilding) - // { - // ConstructionMMTArea areaMM = _tables.TbConstructionMMTArea.GetOrDefault(id); - // if (areaMM != null) - // { - // return new Area(areaMM); - // } - // } - // } - ConstructionArea area = _tables.TbConstructionArea.GetOrDefault(id); - if (area != null) - return new Area(area); - return null; - } - public Step GetStep(int id) - { - // if (id < 102000) - // { - // if (_MMService.MMBuilding) - // { - // ConstructionMMTStep stepMM = _tables.TbConstructionMMTStep.GetOrDefault(id); - // if (stepMM != null) - // { - // return new Step(stepMM); - // } - // } - // } - ConstructionStep step = _tables.TbConstructionStep.GetOrDefault(id); - if (step != null) - return new Step(step); - return null; - } - public string GetBasePrefab(int id) - { - List AreaList = _tables.TbConstruction.DataMap[id].AreaList; - return GetArea(AreaList[0]).BuildingPrefeb; - } - - public string GetMMTString(string oldValue) - { - // if (_MMService.MMBuilding) - // { - // var mmt = _tables.TbMMTStringData.GetOrDefault(oldValue); - // if (mmt != null) - // { - // return mmt.NewString; - // } - // } - return oldValue; - } -} -public class Area -{ - public int ID { get; private set; } - /// - /// Building脚本中的序号,从0开始 - /// - public int TimelineID { get; private set; } - public int StepCount { get; private set; } - public string BuildingPrefeb { get; private set; } - /// - /// 不同prefeb转换的时候,上一个timeline播放时间 - /// - public float TimelinePlaytime { get; private set; } - /// - /// 多语言key + 中文 - /// - public string Name { get; private set; } - public string Name_l10n_key { get; } - /// - /// 多语言key + 中文 - /// - public string NameIndex { get; private set; } - public string NameIndex_l10n_key { get; } - public string Icon { get; private set; } - /// - /// 对应Drop表主键 - /// - public int Reward { get; private set; } - public System.Collections.Generic.List StepList { get; private set; } - /// - /// 用于室内关闭lookfar和looknear功能
1 关闭 - ///
- public int TurnOffFreeLook { get; private set; } - /// - /// 用于室内关闭加速功能
1 关闭 - ///
- public int TurnOffTimeScale { get; private set; } - public Area(ConstructionArea area) - { - this.ID = area.ID; - this.TimelineID = area.TimelineID; - this.StepCount = area.StepCount; - this.BuildingPrefeb = area.BuildingPrefeb; - this.TimelinePlaytime = area.TimelinePlaytime; - this.Name = area.Name; - this.Name_l10n_key = area.Name_l10n_key; - this.NameIndex = area.NameIndex; - this.NameIndex_l10n_key = area.NameIndex_l10n_key; - this.Icon = area.Icon; - this.Reward = area.Reward; - this.StepList = area.StepList; - this.TurnOffFreeLook = area.TurnOffFreeLook; - this.TurnOffTimeScale = area.TurnOffTimeScale; - - } - public Area(ConstructionMMTArea area) - { - this.ID = area.ID; - this.TimelineID = area.TimelineID; - this.StepCount = area.StepCount; - this.BuildingPrefeb = area.BuildingPrefeb; - this.TimelinePlaytime = area.TimelinePlaytime; - this.Name = area.Name; - this.Name_l10n_key = area.Name_l10n_key; - this.NameIndex = area.NameIndex; - this.NameIndex_l10n_key = area.NameIndex_l10n_key; - this.Icon = area.Icon; - this.Reward = area.Reward; - this.StepList = area.StepList; - this.TurnOffFreeLook = area.TurnOffFreeLook; - this.TurnOffTimeScale = area.TurnOffTimeScale; - } -} - -public class Step -{ - public int ID { get; private set; } - /// - /// timeline中时间 - /// - public float StartTime { get; private set; } - /// - /// 动画播放时间 - /// - public float PlayTime { get; private set; } - /// - /// 建造所需钞票 - /// - public int BuildRequired { get; private set; } - /// - /// 修复所需钞票 - /// - public int FixRequired { get; private set; } - - public Step(ConstructionStep step) - { - this.ID = step.ID; - this.StartTime = step.StartTime; - this.PlayTime = step.PlayTime; - this.BuildRequired = step.BuildRequired; - this.FixRequired = step.FixRequired; - } - public Step(ConstructionMMTStep step) - { - this.ID = step.ID; - this.StartTime = step.StartTime; - this.PlayTime = step.PlayTime; - this.BuildRequired = step.BuildRequired; - this.FixRequired = step.FixRequired; - } -} - diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/004-PlayFabMgr.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/004-PlayFabMgr.cs.txt deleted file mode 100644 index faf13a402..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/004-PlayFabMgr.cs.txt +++ /dev/null @@ -1,358 +0,0 @@ -using asap.core; -using PlayFab; -using PlayFab.ClientModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using UnityEngine; -using game.PlayerDataStorage; - -public class PlayFabMgr : MonoBehaviour -{ - const int USER_DATA_UPDATE_INTERVAL = 40; - const int Buffer_Count = 5; - const string Last_Update_Time_Key_Prefix = "LastUpdateTime"; - const string Local_Data_Key_prefix = "LocalData"; - private string Last_Update_Time_Key; - private string Local_Data_Key; - - private LinkedList> dataBuffer; - private Dictionary swapData; - private Dictionary lastUpdateTime; - private Dictionary localData; - - private CancellationTokenSource tokenSource; - - static PlayFabMgr _instance = null; - // An inactive, never-awakened component proves that no timer or PF send has ever been started. - internal bool IsUnstartedForKVLoad => tokenSource==null && dataBuffer==null && swapData==null && localData==null && lastUpdateTime==null && _instance!=this; - internal static bool HasLiveInstanceForKVLoad => _instance!=null; - - public static PlayFabMgr Instance - { - get - { - if (_instance == null) - { - GameDebug.LogError("PlayFabMgr Instance doesn't exist yet!"); - } - - return _instance; - } - } - - public Dictionary CompareDatas(Dictionary remoteDatas, string userId) - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) throw PlayerKVGameplayLoop.Stop("PF archive comparison is disabled in KV loop."); -#endif - PlayerKVGameLoadGuard.RequireLegacyAllowed(PlayerKVGuardPoint.Compare); - Last_Update_Time_Key = $"{Last_Update_Time_Key_Prefix}_{userId}"; - Local_Data_Key = $"{Local_Data_Key_prefix}_{userId}"; - var lastUpdateTimeStr = PlayerPrefs.GetString(Last_Update_Time_Key, string.Empty); - var now = ZZTimeHelper.UtcNow().Ticks; - localData = new Dictionary(); - lastUpdateTime = new Dictionary(); - - if (string.IsNullOrEmpty(lastUpdateTimeStr)) - { - if (remoteDatas != null && remoteDatas.Count > 0) - { - lastUpdateTime = remoteDatas.ToDictionary(x => x.Key, x => x.Value.LastUpdated.Ticks); - localData = remoteDatas.ToDictionary(x => x.Key, x => x.Value.Value); - } - } - else - { - var tempLastUpdateTime = Newtonsoft.Json.JsonConvert.DeserializeObject>(lastUpdateTimeStr); - var localDataStr = PlayerPrefs.GetString(Local_Data_Key); - var tempLocalData = Newtonsoft.Json.JsonConvert.DeserializeObject>(localDataStr); - var allKeys = tempLocalData.Keys.Concat(remoteDatas.Keys).Distinct(); - foreach (var key in allKeys) - { - var localValue = tempLocalData.ContainsKey(key) ? tempLocalData[key] : null; - var remoteValue = remoteDatas.ContainsKey(key) ? remoteDatas[key].Value : null; - var localTime = tempLastUpdateTime.ContainsKey(key) ? tempLastUpdateTime[key] : 0; - var remoteTime = remoteDatas.ContainsKey(key) ? remoteDatas[key].LastUpdated.Ticks : 0; - - if (localValue == null) - { - localData[key] = remoteValue; - lastUpdateTime[key] = remoteTime; - continue; - } - - if (remoteValue == null) - { - UpdateUserDataValue(key, localValue); - lastUpdateTime[key] = now; - localData[key] = localValue; - continue; - } - - var timeDelta = localTime - remoteTime; - if (Math.Abs(timeDelta) > TimeSpan.TicksPerSecond * 60) - { - if (localTime > remoteTime) - { - UpdateUserDataValue(key, localValue); - lastUpdateTime[key] = now; - localData[key] = localValue; - } - else - { - lastUpdateTime[key] = remoteTime; - localData[key] = remoteValue; - } - } - else - { - lastUpdateTime[key] = localTime; - localData[key] = localValue; - } - } - } - - PlayerPrefs.SetString(Last_Update_Time_Key, LitJson.JsonMapper.ToJson(lastUpdateTime)); - PlayerPrefs.SetString(Local_Data_Key, LitJson.JsonMapper.ToJson(localData)); - return localData; - } - - void Awake() - { - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Lifecycle)) return; - _instance = this; -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) return; -#endif - InitBuffer(); - tokenSource = new CancellationTokenSource(); - UpdateUserDataValue(tokenSource.Token); - } - -#if UNITY_EDITOR && !SERVICE_HOST - internal void StartKVGameplayLoopSync() - { - if(!PlayerKVGameplayLoop.Ready || tokenSource!=null) return; - tokenSource=new CancellationTokenSource(); - UpdateUserDataValue(tokenSource.Token); - } - internal void StopKVGameplayLoopSync() - { tokenSource?.Cancel(); tokenSource?.Dispose(); tokenSource=null; } -#endif - void InitBuffer() - { - dataBuffer = new LinkedList>(); - for (int i = 0; i < Buffer_Count; i++) - { - dataBuffer.AddLast(new Dictionary()); - } - swapData = new Dictionary(); - } - - void OnApplicationPause(bool is_pause) - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) - { - if(is_pause) { StopKVGameplayLoopSync(); _=PlayerKVGameplayLoop.FlushObservedAsync(); } - else StartKVGameplayLoopSync(); - return; - } -#endif - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Lifecycle)) return; - if (is_pause) - { - tokenSource.Cancel(); - tokenSource = null; - SyncData(); - } - else - { - tokenSource = new CancellationTokenSource(); - UpdateUserDataValue(tokenSource.Token); - } - } - - void OnApplicationQuit() - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) { StopKVGameplayLoopSync(); _=PlayerKVGameplayLoop.CloseAsync(); return; } -#endif - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Lifecycle)) return; - tokenSource.Cancel(); - tokenSource = null; - SyncData(); - } - - void OnDestroy() - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) { StopKVGameplayLoopSync(); _=PlayerKVGameplayLoop.CloseAsync(); return; } -#endif - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Lifecycle)) return; - tokenSource?.Cancel(); - tokenSource = null; - if(!PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.PrefsSave)) PlayerPrefs.Save(); - SyncData(); - } - - private async void UpdateUserDataValue(CancellationToken token) - { - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Lifecycle)) return; - try - { - while (!token.IsCancellationRequested) - { - SyncData(); - await Task.Delay(USER_DATA_UPDATE_INTERVAL * 1000); - } - } - catch (System.Exception) { } - } - - public void UpdateUserDataValue(string key, string data, bool remoteStore = true) - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) { PlayerKVGameplayLoop.Write(key,data,remoteStore); return; } -#endif - PlayerKVGameLoadGuard.RequireLegacyAllowed(PlayerKVGuardPoint.Update); - if (remoteStore) - { - var cbuff = dataBuffer.First; - while (cbuff != null) - { - var datas = cbuff.Value; - if (!datas.ContainsKey(key) && datas.Count >= 10) - { - cbuff = cbuff.Next; - continue; - } - cbuff.Value[key] = data; - break; - } - } - - localData[key] = data; - lastUpdateTime[key] = ZZTimeHelper.UtcNow().Ticks; - //Debug.Log($"[PlayFabMgr]UpdateUserDataValue key:{key} data:{data}"); - PlayerPrefs.SetString(Last_Update_Time_Key, LitJson.JsonMapper.ToJson(lastUpdateTime)); - PlayerPrefs.SetString(Local_Data_Key, LitJson.JsonMapper.ToJson(localData)); - } - /// - /// 没有数据返回 null 一定一定一定判空!!! - /// - /// - /// - public string GetLocalData(string key) - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) return PlayerKVGameplayLoop.Read(key); -#endif - PlayerKVGameLoadGuard.RequireLegacyAllowed(PlayerKVGuardPoint.ReadLocal); - if (localData.ContainsKey(key)) - { - return localData[key]; - } - else - { - return null; - } - } - - private void SyncData() - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) { _=PlayerKVGameplayLoop.FlushObservedAsync(); return; } -#endif - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Sync)) return; - // Logout clears credentials before RootCtx is destroyed. Keep pending data local. - if (!PlayFabClientAPI.IsClientLoggedIn()) return; - var buf = dataBuffer.First; - if (buf.Value.Count == 0) - return; - - var datas = buf.Value; - swapData.Clear(); - buf.Value = swapData; - swapData = datas; - - dataBuffer.RemoveFirst(); - dataBuffer.AddLast(buf); - - var request = new UpdateUserDataRequest() - { - Data = swapData, - Permission = UserDataPermission.Public - }; - - PlayFabClientAPI.UpdateUserData(request, null, UpdateFaild); -#if UNITY_EDITOR - //IConfig config = GContext.container.Resolve(); - //if (config != null && config.Get("DBUG", string.Empty) == "1") - //{ - try - { - //写入本地文件记录 key 和时间 - string persistentPath = Application.persistentDataPath; - // 拼接文件名,这里使用txt文件记录数据 - string filePath = System.IO.Path.Combine(persistentPath, "syncData.csv"); - string currentTime = ZZTimeHelper.UtcNow().ToString("yyyy-MM-dd HH:mm:ss"); - string dataLine = $"{currentTime},{string.Join(',', swapData.Keys)}"; - // 使用追加模式写入文件,每次写入一行数据 - using (System.IO.StreamWriter writer = System.IO.File.AppendText(filePath)) - { - writer.WriteLine(dataLine); - } - } - catch (Exception e) - { - Debug.LogError($"记录数据时出错: {e.Message}"); - } - //} -#endif - } - - private void UpdateFaild(PlayFabError error) - { - GameDebug.LogError("[PlayFabMgr]UpdateUserData Error: {0}", error.ToString()); - } - - internal void FlushBufferedData() => SyncData(); - - public async Task SyncDataImmidiate(string key, string data) - { -#if UNITY_EDITOR && !SERVICE_HOST - if(PlayerKVGameplayLoop.Enabled) throw PlayerKVGameplayLoop.Stop("Immediate/consuming saves are outside the equipment loop."); -#endif - if(PlayerKVGameLoadGuard.Reject(PlayerKVGuardPoint.Immediate)) return false; - foreach (var buff in dataBuffer) - { - if (buff.ContainsKey(key)) - { - buff.Remove(key); - } - } - - var taskSource = new TaskCompletionSource(); - - var request = new UpdateUserDataRequest() - { - Data = new Dictionary() { { key, data } }, - Permission = UserDataPermission.Public - }; - - PlayFabClientAPI.UpdateUserData(request, - (r) => { taskSource.SetResult(true); }, - (e) => - { - taskSource.SetResult(false); - UnityEngine.Debug.LogError($"[PlayFabMgr]UpdateUserData Error: {e.ToString()}"); - } - ); - return await taskSource.Task; - } - -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/005-BargainPackData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/005-BargainPackData.cs.txt deleted file mode 100644 index 8f6d049e3..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/005-BargainPackData.cs.txt +++ /dev/null @@ -1,321 +0,0 @@ -using asap.core; -using cfg; -using GameCore; -using UnityEngine; -using System; -using game; -using System.Collections.Generic; - -public class BargainPackData -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - private readonly Tables _tables = GContext.container.Resolve(); - private readonly TbEventPackManager _epm = GContext.container.Resolve().TbEventPackManager; - private readonly TbSpecialPack _spp = GContext.container.Resolve().TbSpecialPack; - private GeneralEventPackData _data; - - private bool _kvLoadPresent; -#if UNITY_EDITOR - internal bool SelectionsAreIndependentForKVValidation() - { - var source = new List { 7, 9 }; - var state = new game.PlayerDataStorage.PlayerKVBargainState(true,0,_data.redirectID,0,0,0,0,0,0,0,0,0,false,false,0,source); - ReplaceFromKVDecoded(state); - source.Clear(); - if (_data.selections.Count != 2 || ReferenceEquals(_data.selections, source) || ReferenceEquals(_data.selections, state.selections)) return false; - var previous = _data.selections; - _data.selections[0] = 10; - if (state.selections[0] != 7) return false; - ResetForKVLoad(); - return _data.selections.Count == 0 && !ReferenceEquals(previous, _data.selections) && !_kvLoadPresent; - } -#endif - internal bool KVLoadPresent => _kvLoadPresent; - internal static game.PlayerDataStorage.PlayerKVBargainState DecodeForKVLoad( - IReadOnlyDictionary raw, game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeBargain(raw, snapshot, errors); - - internal void ResetForKVLoad() - { - _kvLoadPresent = false; - _data = default(GeneralEventPackData); - _data.selections = new List(); - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVBargainState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - if (!state.IsPresent) { ResetForKVLoad(); return; } - var replacement = new GeneralEventPackData - { - currentEventID = state.currentEventID, - redirectID = state.redirectID, - VIPLvlWhenEventActivate = state.VIPLvlWhenEventActivate, - purchaseCount = state.purchaseCount, - savingProgress = state.savingProgress, - discountLvl = state.discountLvl, - visualProgress = state.visualProgress, - visualDiscountLvl = state.visualDiscountLvl, - rodID = state.rodID, - lastPackIDBought = state.lastPackIDBought, - packID = state.packID, - doNeedTrigger = state.doNeedTrigger, - isTriggered = state.isTriggered, - inflation = state.inflation, - selections = state.selections == null ? null : new List(state.selections), - }; - _data = replacement; - _kvLoadPresent = true; - } - internal game.PlayerDataStorage.PlayerKVBargainState SnapshotForKVValidation() => - new game.PlayerDataStorage.PlayerKVBargainState(_kvLoadPresent, _data.currentEventID, _data.redirectID, _data.VIPLvlWhenEventActivate, _data.purchaseCount, _data.savingProgress, _data.discountLvl, _data.visualProgress, _data.visualDiscountLvl, _data.rodID, _data.lastPackIDBought, _data.packID, _data.doNeedTrigger, _data.isTriggered, _data.inflation, _data.selections); - - public int CurrentEventID => _data.currentEventID; - - public FishingEvent CurrentEvent => _tables.TbFishingEvent[_data.currentEventID]; - - public TimeSpan RemainingTime => - DateTime.Parse((_tables.TbFishingEvent[_data.currentEventID].TimeDefinition as LimitedTime).EndTime) - - ZZTimeHelper.UtcNow(); - - public bool IsWithinEventTime - { - get - { - var fishingEvent = _tables.TbFishingEvent.GetOrDefault(CurrentEventID); - if (!(fishingEvent?.TimeDefinition is LimitedTime time)) return false; - - var et = DateTime.Parse(time.EndTime); - var st = DateTime.Parse(time.StartTime); - return ZZTimeHelper.UtcNow() >= st && ZZTimeHelper.UtcNow() < et; - } - } - - public bool IsPackActivated - { - get - { - bool res = _tables.TbFishingEvent.DataMap.ContainsKey(_data.currentEventID) - && _epm.DataMap.ContainsKey(_data.redirectID) - && _epm[_data.redirectID].PackType == 3 - && IsWithinEventTime - && _data.isTriggered - && _data.purchaseCount < _epm[_data.redirectID].MaxCount; - //Debug.Log(_tables.TbFishingEvent.DataMap.ContainsKey(_data.currentEventID)); - //Debug.Log(_epm.DataMap.ContainsKey(_data.redirectID)); - //Debug.Log(_epm[_data.redirectID].PackType == 3); - //Debug.Log(IsWithinEventTime); - //Debug.Log(_data.isTriggered); - //Debug.Log(_data.purchaseCount < _epm[_data.redirectID].MaxCount); - return res; - } - } - - public int RedirectID => _data.redirectID; - public bool DoNeedTrigger => _data.doNeedTrigger; - public int PackID => _epm[_data.redirectID].VIPPackList[_data.VIPLvlWhenEventActivate][0]; - public int DiscountLvlCount => _spp[PackID].IAPID.Count; - public int DiscountLvl => _data.discountLvl; - public int PurchaseCount => _data.purchaseCount; - public int Progress => _data.savingProgress; - public int VIPLvlWhenEventActivated => _data.VIPLvlWhenEventActivate; - public int ActivateItemId => _spp[PackID].ActivateItemId; - public string ActiveItemImg => _spp[PackID].ActiveItemImg; - public int EventItemId => IsPackActivated ? _spp[PackID].EventItemId : 0; - public int RewardDropID => _spp[PackID].DropID[0]; - public int MaxCount => _epm[_data.redirectID].MaxCount; - public float Inflation => _data.inflation; - - public int NextTarget - { - get - { - int lvl = _data.discountLvl >= DiscountLvlCount - 1 ? DiscountLvlCount - 1 : _data.discountLvl + 1; - int count = _spp[PackID].EventItemRequire[lvl]; - PlayerItemData playerItemData = GContext.container.Resolve(); - count = playerItemData.IntInflation(count, _data.inflation); - return count; - } - } - - public bool IsFull => _data.discountLvl >= DiscountLvlCount - 1 && _data.savingProgress >= NextTarget; - public int IAPID => _spp[PackID].IAPID[DiscountLvl]; - public List FishingScoreList => _spp[PackID].EventItemGet; - public int NextDiscount - { - get - { - int lvl = _data.discountLvl >= DiscountLvlCount - 1 ? DiscountLvlCount - 1 : _data.discountLvl + 1; - return _spp[PackID].DiscountList[lvl]; - } - } - public int VisualProgress => _data.visualProgress; - public int VisualDiscountLvl => _data.visualDiscountLvl; - public int NextVisualTarget - { - get - { - int lvl = _data.visualDiscountLvl >= DiscountLvlCount - 1 - ? DiscountLvlCount - 1 - : _data.visualDiscountLvl + 1; - int EventItemRequire = _spp[PackID].EventItemRequire[lvl]; - PlayerItemData playerItemData = GContext.container.Resolve(); - EventItemRequire = playerItemData.IntInflation(EventItemRequire, _data.inflation); - return EventItemRequire; - } - } - - public int NextVisualDiscount - { - get - { - int lvl = _data.visualDiscountLvl >= DiscountLvlCount - 1 - ? DiscountLvlCount - 1 - : _data.visualDiscountLvl + 1; - return _spp[PackID].DiscountList[lvl]; - } - } - - public void SaveData() - { - //Debug.LogError("Testing, data not saved for debug purpose."); - SaveStore.Write("GeneralEventPackData", - Newtonsoft.Json.JsonConvert.SerializeObject(_data)).RequireAccepted(); - } - - public void LoadData(GeneralEventPackData data) - { - _data = data; - if (IsPackActivated && IsFull) - { - GContext.container.Resolve().AddGiftFaceUIForce(_data.currentEventID, UITypes.GiftBargainPopupPanel); - } - } - - public void UpdateData(FishingEvent e) - { - if (_epm[_tables.TbFishingEvent[e.ID].RedirectID].PackType != 3) - { - Debug.LogError($"Fishing event ID {e.ID} is not a Bargain back event"); - return; - } - - if (_data.currentEventID != e.ID) - { - _data = new GeneralEventPackData( - eventID: e.ID, - vip: GContext.container.Resolve().PriceLv, - redirectID: e.RedirectID, - savingProgress: 0, - discountLvl: 0, - isTriggered: false, - doNeedTrigger: true, - visualProgress: 0, - visualDiscountLvl: 0, - purchaseCount: 0, - inflation: GContext.container.Resolve().InflationRate); - } - - SaveData(); - } - - public void TriggerPack() - { - _data.doNeedTrigger = false; - _data.isTriggered = true; - int EventItemCountFirst = _spp[PackID].EventItemCountFirst; - PlayerItemData playerItemData = GContext.container.Resolve(); - EventItemCountFirst = playerItemData.IntInflation(EventItemCountFirst, _data.inflation); - AddProgress(EventItemCountFirst); - SaveData(); - } - - public void AddProgress(int progress) - { - if (progress <= 0 || IsFull) - return; - _data.savingProgress += progress; - while (_data.savingProgress >= NextTarget) - { - //DoUICut = true; - _data.savingProgress -= NextTarget; - _data.discountLvl++; - if (_data.discountLvl >= DiscountLvlCount - 1) - { - _data.savingProgress = NextTarget; - break; - } - } - - SaveData(); - return; - } - - public void AddProgress(int fishTier, int magnification) - { - if (!IsPackActivated || fishTier < 1 || fishTier > 5) - { - //Debug.LogError($"Fish Tier {fishTier} not defined in TbSpedialPack"); - return; - } - - int progress = _spp[PackID].EventItemGet[fishTier - 1] * magnification; - if (progress <= 0 || IsFull) - return; - - int curProgress = _data.savingProgress; - _data.savingProgress += progress; - GContext.Publish(new TargetAddData(EventItemId, curProgress, progress)); - while (_data.savingProgress >= NextTarget) - { - //DoUICut = true; - _data.savingProgress -= NextTarget; - _data.discountLvl++; - if (_data.discountLvl >= DiscountLvlCount - 1) - { - GContext.container.Resolve() - .AddGiftFaceUIForce(CurrentEventID, UITypes.GiftBargainPopupPanel); - _data.savingProgress = NextTarget; - break; - } - } - - SaveData(); - return; - } - - public void AddPurchase() - { - _data.purchaseCount++; - SaveData(); - } - - public void RefreshVisualData() - { - _data.visualDiscountLvl = _data.discountLvl; - _data.visualProgress = _data.savingProgress; - SaveData(); - } - - public int GetNextDiscountTarget(int l) - { - int lvl = l >= DiscountLvlCount - 1 ? DiscountLvlCount - 1 : l + 1; - int count = _spp[PackID].EventItemRequire[lvl]; - PlayerItemData playerItemData = GContext.container.Resolve(); - count = playerItemData.IntInflation(count, _data.inflation); - return count; - } - - public int GetNextDiscount(int l) - { - int lvl = l >= DiscountLvlCount - 1 ? DiscountLvlCount - 1 : l + 1; - return _spp[PackID].DiscountList[lvl]; - } -} - -public class BargainPackProgressEvent -{ - public int type; //0: 初始化 1:增加动画 - public int addProgress; -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/006-BattlePassData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/006-BattlePassData.cs.txt deleted file mode 100644 index 35de19450..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/006-BattlePassData.cs.txt +++ /dev/null @@ -1,923 +0,0 @@ -using asap.core; -using cfg; -using game; -using GameCore; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using tysdk; -using UniRx; -using UnityEngine; - -public class GetBattlePassRewardEvent -{ - public int NormalLevel; - public int VipLevel; -} - -public struct GetAllBPRewards -{ - -} - -public struct BpGetExp -{ - -} - -public struct BpVipUnlock -{ - -} - -public class BattlePassData -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - public BattlePassRecord BattlePassRecord; - public BattleTask BattleTask; - - internal static game.PlayerDataStorage.PlayerKVBattlePassState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeBattlePass(raw,snapshot,errors); - internal void ResetForKVLoad() - { - BattlePassRecord=new BattlePassRecord(); - BattleTask=new BattleTask(); - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVBattlePassState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - var record=new BattlePassRecord { - ID=state.Record.ID,Level=state.Record.Level,Exp=state.Record.Exp,BuyVipToastIndex=state.Record.BuyVipToastIndex, - IsUnlockVip=state.Record.IsUnlockVip,NormalRewardGet=new List(state.Record.Normal),VipRewardGet=new List(state.Record.Vip), - LastDropIDs=new List(state.Record.LastDrops),InflationRate=state.Record.Inflation - }; - var task=new BattleTask { - dic_dailyTasks=state.Task.Daily.ToDictionary(p=>p.Key,p=>p.Value),dic_weeklyTasks=state.Task.Weekly.ToDictionary(p=>p.Key,p=>p.Value), - loginDays=new List(state.Task.LoginDays),DailyTaskEndTime=state.Task.DailyEnd,WeeklyTaskEndTime=state.Task.WeeklyEnd - }; - BattlePassRecord=record; BattleTask=task; - } - - private Tables _tables; - - - public BattlePassData(Tables tables) - { - if (BattlePassRecord == null) - BattlePassRecord = new BattlePassRecord(); - if (BattleTask == null) - BattleTask = new BattleTask(); - - _tables = tables; - } - - #region Load&Save - public void InitData(Dictionary userDatas = null) - { - if (userDatas.TryGetValue("BattlePassRecordTask", out string battlePassRecordTask)) - { - - LoadBattlePassRecordTask(battlePassRecordTask); - } - else - { - //旧数据兼容 - if (userDatas.TryGetValue("BattlePassRecord", out string data_value)) - { - LoadBattlePassRecord(data_value); - } - if (userDatas.TryGetValue("BattleTask", out data_value)) - { - LoadBattleTask(data_value); - } - } - } - public void LoadBattlePassRecordTask(string data) - { - string[] values = data.Split('#'); - BattlePassRecord = new BattlePassRecord(); - BattlePassRecord.DeserializeObject(values[0]); - - BattleTask = new BattleTask(); - BattleTask.DeserializeObject(values[1]); - } - public void LoadBattlePassRecord(string data) - { - BattlePassRecord = JsonConvert.DeserializeObject(data); - } - public void LoadBattleTask(string data) - { - BattleTask = JsonConvert.DeserializeObject(data); - } - void SaveBattlePassRecordTask() - { - string battlePassRecord = BattlePassRecord.SerializeObject(); - string battleTask = BattleTask.SerializeObject(); - playerSaveStore.Write("BattlePassRecordTask", battlePassRecord + "#" + battleTask).RequireAccepted(); - } - public void SaveBattlePassRecord() - { - GContext.container.Resolve().SetRedPoint(); - SaveBattlePassRecordTask(); - //PlayFabMgr.Instance.UpdateUserDataValue("BattlePassRecord", JsonConvert.SerializeObject(BattlePassRecord)); - } - - public void SaveBattleTask() - { - GContext.container.Resolve().SetRedPoint(); - SaveBattlePassRecordTask(); - //PlayFabMgr.Instance.UpdateUserDataValue("BattleTask", JsonConvert.SerializeObject(BattleTask)); - } - #endregion - - #region BattlePass - - public void RefreshBattlePassRecord(FishingEvent t = null) - { - //没有开启的战令 - if (t == null) - { - GContext.container.Resolve().RecordLastBPUnGetDropIDs(); - BattlePassRecord.ID = 0; - SaveBattlePassRecord(); - return; - } - if (t.ID != BattlePassRecord.ID) - { - GContext.container.Resolve().RecordLastBPUnGetDropIDs(); - BattlePassRecord.Init(t.ID); - RefreshDaiyTask(); - RefreshWeeklyTask(); - SaveBattlePassRecord(); - } - } - - #endregion - - #region Task - - public void RefreshDaiyTask() - { - var fishingEvent = _tables.TbFishingEvent.GetOrDefault(BattlePassRecord.ID); - if (fishingEvent == null) return; - var bpMain = _tables.TbBattlePassMain.GetOrDefault(fishingEvent.RedirectID); - if (bpMain == null) return; - BattleTask.DailyTaskEndTime = ConvertTools.GetDateTimeYMD(ZZTimeHelper.UtcNow().UtcNowOffset()).AddDays(1); - var dailyTasks = bpMain.DailyTaskList; - BattleTask.dic_dailyTasks.Clear(); - foreach (var task in dailyTasks) - { - BattleTask.dic_dailyTasks.Add(task, 0); - } - GContext.Publish(new ConditionTypeEvent { type = ConditionType.LoginDays, count = 1 }); - SaveBattleTask(); - } - - public void RefreshWeeklyTask() - { - var fishingEvent = _tables.TbFishingEvent.GetOrDefault(BattlePassRecord.ID); - if (fishingEvent == null) return; - var bpMain = _tables.TbBattlePassMain.GetOrDefault(fishingEvent.RedirectID); - if (bpMain == null) return; - var weeklyTasks = bpMain.WeeklyTaskList; - BattleTask.dic_weeklyTasks.Clear(); - foreach (var task in weeklyTasks) - { - BattleTask.dic_weeklyTasks.Add(task, 0); - } - BattleTask.WeeklyTaskEndTime = ConvertTools.GetDateTimeSunDay(ZZTimeHelper.UtcNow().UtcNowOffset()).AddDays(1); - BattlePassRecord.InflationRate = GContext.container.Resolve().InflationRate; - - GContext.Publish(new ConditionTypeEvent { type = ConditionType.LoginDays, count = 1 }); - BattleTask.loginDays.Clear(); - SaveBattleTask(); - } - - #endregion - -} - -public class BattlePassDataProvider : IDisposable -{ - #region Fields - - public BattlePassData Data; - private PlayerItemData _itemData; - - public int LockTipID; - - public int DefaultBuyLevel - { - get - { - return curPassMain.BuyLevel; - } - } - - - - private Tables _tables; - private Dictionary dic_BPLevel; - - public bool IsActivating => Data.BattlePassRecord.ID != 0 && curPassMain != null; - public bool UILockVip = false; - public bool IsUnlockVip => Data.BattlePassRecord.IsUnlockVip == 1; - - CompositeDisposable disposables = new CompositeDisposable(); - - public BattlePassMain curPassMain - { - get - { - var fishingEvent = _tables.TbFishingEvent.GetOrDefault(Data.BattlePassRecord.ID); - if (fishingEvent == null) { return null; } - - return _tables.TbBattlePassMain.GetOrDefault(fishingEvent.RedirectID); - } - } - public BattlePassLevel curPassLevel - { - get - { - if (curPassMain != null) - return dic_BPLevel.GetValueOrDefault(curPassMain.LevelList[Data.BattlePassRecord.Level - 1]); - return null; - } - } - - - public BattlePassDataProvider(Tables tables, BattlePassData data, PlayerItemData itemData) - { - _tables = tables; - Data = data; - dic_BPLevel = tables.TbBattlePassLevel.DataMap; - _itemData = itemData; - GContext.OnEvent().Subscribe(UpdateTaskData).AddTo(disposables); - } - - #endregion - - #region Check Func - - public void CheckIfRefreshBattblePass() - { - if (!IsActivating) return; - DateTime endTime = GContext.container.Resolve().GetEventEndTime(Data.BattlePassRecord.ID); - - if (ZZTimeHelper.UtcNow().UtcNowOffset() >= endTime && IsActivating) - { - RecordLastBPUnGetDropIDs(); - Data.RefreshBattlePassRecord(); - //GContext.container.Resolve().GetEventAndInit(3, 7); - } - } - - public void CheckIfRefreshDailyTask() - { - if (ZZTimeHelper.UtcNow().UtcNowOffset() >= Data.BattleTask.DailyTaskEndTime && IsActivating) - { - Data.RefreshDaiyTask(); - } - } - - public void CheckIfRefreshWeekTask() - { - - if (ZZTimeHelper.UtcNow().UtcNowOffset() >= Data.BattleTask.WeeklyTaskEndTime && IsActivating) - { - Data.RefreshWeeklyTask(); - } - } - - public bool CheckIfPopBuyVipPanel() - { - if (Data.BattlePassRecord.BuyVipToastIndex >= curPassMain.RemindLevel.Count) - { - return false; - } - - return Data.BattlePassRecord.Level >= curPassMain.RemindLevel[Data.BattlePassRecord.BuyVipToastIndex] && Data.BattlePassRecord.IsUnlockVip == 0; - } - - public bool CheckIfGetLastBpRewards() - { - if (LastBpDropIds.Count != 0) - { - var playerData = GContext.container.Resolve(); - ChangeSource changeSource = new ChangeSource(Data.BattlePassRecord.ID, "BattlePass", "BattlePass_Normal28Day", "ExpiredReward"); - - var itemDatas = playerData.AddItemByDropListLureInflation(null, LastBpDropIds.GetRange(1, LastBpDropIds.Count - 1), changeSource); -#if AGG - using (var e = GEvent.GameEvent("bp_level_reward")) - { - e.AddContent("bp_level", GetBPCurLevel) - .AddContent("drop_id_list", JsonConvert.SerializeObject(LastBpDropIds.GetRange(1, LastBpDropIds.Count - 1))); - if (itemDatas != null && itemDatas.Count > 0) - { - int reward_hook = 0; - int hook_origin = 0; - int reward_cash = 0; - for (int i = 0; i < itemDatas.Count; i++) - { - if (itemDatas[i].id == 1001) - { - reward_hook += itemDatas[i].count; - hook_origin += itemDatas[i].origin; - } - else if (itemDatas[i].id == 1002) - { - reward_cash += itemDatas[i].count; - } - } - e.AddContent("reward_hook", reward_hook) - .AddContent("hook_origin", hook_origin) - .AddContent("reward_cash", reward_cash); - } - } -#endif - if (LastBpDropIds[0] > 0) - { -#if AGG - using (var e = GEvent.GameEvent("bp_cash_reward")) - { - e.AddContent("bp_level", GetBPCurLevel) - .AddContent("cash_num", LastBpDropIds[0]); - } -#endif - - var cash = new ItemData { id = 1002, count = LastBpDropIds[0] }; - ChangeSource changeSource1 = new ChangeSource(Data.BattlePassRecord.ID, "BattlePass", "BattlePass_Normal28Day", "OverflowReward"); - - playerData.AddItem(cash, changeSource1); - GContext.Publish(new ShowData(cash)); - } - GContext.Publish(new ShowData(textValue: LocalizationMgr.GetText("UI_BattlePassPanel_25"))); - LastBpDropIds.Clear(); - Data.SaveBattlePassRecord(); - return true; - } - return false; - } - #endregion - - #region Get Func - - public TimeSpan GetDailyTaskDuration() - { - return Data.BattleTask.DailyTaskEndTime - ZZTimeHelper.UtcNow().UtcNowOffset(); - } - - public TimeSpan GetWeeklyTaskDuration() - { - return Data.BattleTask.WeeklyTaskEndTime - ZZTimeHelper.UtcNow().UtcNowOffset(); - } - - public int GetBPCurLevel => Data.BattlePassRecord.Level; - public int GetBPNextLevel => Mathf.Clamp(Data.BattlePassRecord.Level + 1, 1, BPMaxLevel); - - public int BPMaxLevel => curPassMain.LevelList.Count; - public List LastBpDropIds => Data.BattlePassRecord.LastDropIDs; - - public BattlePassLevel GetBPLevel(int level) => dic_BPLevel[curPassMain.LevelList[level - 1]]; - - public int GetBPCurExp() => Data.BattlePassRecord.Exp; - - public int GetNeedExpToLevelUp(int upLevel) - { - var curLevel = Data.BattlePassRecord.Level; - return GetTotalExpFromLevelRange(curLevel, curLevel + upLevel) - Data.BattlePassRecord.Exp; - } - - public int GetCashBoxCount() - { - var count = 0; - if (GetBPCurLevel == BPMaxLevel) - count = GetBPCurExp() / 100 * curPassMain.ExpToCash; - return count; - } - - /// - /// Level Up From StartLevel To EndLevel - /// - /// - /// - /// - public int GetTotalExpFromLevelRange(int startLevel, int endLevel) - { - var expNeed = 0; - endLevel = endLevel > BPMaxLevel ? BPMaxLevel : endLevel; - for (int i = startLevel; i < endLevel; i++) - { - expNeed += dic_BPLevel[curPassMain.LevelList[i - 1]].Exp; - } - return expNeed; - } - - public BPRewardSlot.ESlotState GetSlotState(int level, bool isNormalReward) - { - // if ( !IsUnlockVip&&!isNormalReward ) - // return BPRewardSlot.ESlotState.VipLock; - if (Data.BattlePassRecord.Level < level || (!isNormalReward && !IsUnlockVip)) - { - return BPRewardSlot.ESlotState.LevelLock; - } - if (isNormalReward) - { - if (Data.BattlePassRecord.NormalRewardGet.Contains(level)) - return BPRewardSlot.ESlotState.HasGotReward; - } - else if (Data.BattlePassRecord.VipRewardGet.Contains(level)) - return BPRewardSlot.ESlotState.HasGotReward; - return BPRewardSlot.ESlotState.CanGetReward; - } - - public void GetAllBpRewards() - { - var playItemData = GContext.container.Resolve(); - var dropIds = new List(); - var dropIds1 = new List(); - var dropIds2 = new List(); - List itemDatas = new List(); - List itemDatas1 = new List(); - List itemDatas2 = new List(); - for (int i = 1; i <= Data.BattlePassRecord.Level; i++) - { - if (GetSlotState(i, true) == BPRewardSlot.ESlotState.CanGetReward) - { - dropIds1.Add(GetSlotDropID(i, true)); - SetLevelRewardGet(i, true); - } - } - if (dropIds1.Count > 0) - { - dropIds.AddRange(dropIds1); - ChangeSource changeSource = new ChangeSource(Data.BattlePassRecord.ID, "BattlePass", "BattlePass_Normal28Day", "FreeLevelReward"); - itemDatas1 = playItemData.GetItemByDropListLureInflation(null, dropIds1); - for (int i = 0; i < itemDatas1.Count; i++) - { - itemDatas1[i].changeSource = changeSource; - } - itemDatas.AddRange(itemDatas1); - } - if (IsUnlockVip) - { - for (int i = 1; i <= Data.BattlePassRecord.Level; i++) - { - if (GetSlotState(i, false) == BPRewardSlot.ESlotState.CanGetReward) - { - dropIds2.Add(GetSlotDropID(i, false)); - SetLevelRewardGet(i, false); - } - } - if (dropIds2.Count > 0) - { - dropIds.AddRange(dropIds2); - ChangeSource changeSource = new ChangeSource(Data.BattlePassRecord.ID, "BattlePass", "BattlePass_Normal28Day", "PrimeLevelReward"); - itemDatas2 = playItemData.GetItemByDropListLureInflation(null, dropIds2); - for (int i = 0; i < itemDatas2.Count; i++) - { - itemDatas2[i].changeSource = changeSource; - } - itemDatas.AddRange(itemDatas2); - } - } - Data.SaveBattlePassRecord(); - GContext.Publish(new ShowData(itemDatas)); - playItemData.AddItem(itemDatas, null); -#if AGG - using (var e = GEvent.GameEvent("bp_level_reward")) - { - e.AddContent("bp_level", GContext.container.Resolve().GetBPCurLevel) - .AddContent("drop_id_list", JsonConvert.SerializeObject(dropIds)); - if (itemDatas != null && itemDatas.Count > 0) - { - int reward_hook = 0; - int hook_origin = 0; - int reward_cash = 0; - for (int i = 0; i < itemDatas.Count; i++) - { - if (itemDatas[i].id == 1001) - { - reward_hook += itemDatas[i].count; - hook_origin += itemDatas[i].origin; - } - else if (itemDatas[i].id == 1002) - { - reward_cash += itemDatas[i].count; - } - } - e.AddContent("reward_hook", reward_hook) - .AddContent("hook_origin", hook_origin) - .AddContent("reward_cash", reward_cash); - } - } -#endif - } - - public int GetAllToGetRewardCount() - { - var count = 0; - for (int i = 1; i <= Data.BattlePassRecord.Level; i++) - { - if (GetSlotState(i, true) == BPRewardSlot.ESlotState.CanGetReward) - { - count++; - } - } - if (IsUnlockVip) - { - for (int i = 1; i <= Data.BattlePassRecord.Level; i++) - { - if (GetSlotState(i, false) == BPRewardSlot.ESlotState.CanGetReward) - { - count++; - } - } - } - return count; - } - - public int GetSlotDropID(int level, bool isNormalReward) - { - if (isNormalReward) - { - return curPassMain.FreeRewardList[level - 1]; - } - return curPassMain.PrimeRewardList[level - 1]; - } - public ItemData GetSlotDropItem(int level, bool isNormalReward) - { - if (isNormalReward) - { - return _itemData.GetItemDataOneLureInflation(null, curPassMain.FreeRewardList[level - 1]); - } - return _itemData.GetItemDataOneLureInflation(null, curPassMain.PrimeRewardList[level - 1]); - } - - public int GetDiamondCostByUpLevel(int upLevel) - { - var needExp = GetNeedExpToLevelUp(upLevel); - if (needExp % 100 > 0) - { - needExp = (needExp / 100 + 1) * 100; - } - return needExp / 100 * curPassMain.ExpPrice; - } - - public List GetRewardsByUpLevel(int upLevel, bool isNormal) - { - return GetRewardsByLevelRange(GetBPCurLevel + 1, GetBPCurLevel + upLevel, isNormal); - } - - public List GetRewardsByLevelRange(int startLevel, int endLevel, bool isNormal) - { - - var curLevel = startLevel; - var maxLevel = BPMaxLevel; - var curPass = curPassMain; - - Dictionary dic_allRewards = new(); - - var dic_items = GContext.container.Resolve().TbItem.DataMap; - var playerItemData = GContext.container.Resolve(); - var rewardList = isNormal ? curPass.FreeRewardList : curPass.PrimeRewardList; - - for (int i = curLevel - 1; i < endLevel && i < maxLevel; i++) - { - var curItemData = playerItemData.GetItemDataOneLureInflation(null, rewardList[i]); - if (dic_allRewards.ContainsKey(curItemData.id)) - { - dic_allRewards[curItemData.id] += curItemData.count; - } - else - dic_allRewards.Add(curItemData.id, curItemData.count); - } - - var rewards = dic_allRewards.OrderByDescending(x => dic_items[x.Key].Quality).Select(x => new ItemData { id = x.Key, count = x.Value }).ToList(); - return rewards; - } - - public int GetBarsDefaultPos() - { - for (int i = 1; i <= GetBPCurLevel; i++) - { - if (GetSlotState(i, true) == BPRewardSlot.ESlotState.CanGetReward) - return Mathf.Clamp(i - 1, 1, BPMaxLevel - 3); - - if (GetSlotState(i, false) == BPRewardSlot.ESlotState.CanGetReward) - return Mathf.Clamp(i - 1, 1, BPMaxLevel - 3); - } - return Mathf.Clamp(GetBPCurLevel - 1, 1, BPMaxLevel - 3); - } - - - #endregion - - #region Set Func - public void RecordLastBPUnGetDropIDs() - { - if (curPassMain == null) - return; - var drops = Data.BattlePassRecord.LastDropIDs; - if (Data.BattlePassRecord.ID == 0 || drops.Count > 0) - return; - drops.Add(GContext.container.Resolve().GetExtraCoinMag(GetCashBoxCount())); - for (int i = 1; i <= GetBPCurLevel; i++) - { - if (GetSlotState(i, true) == BPRewardSlot.ESlotState.CanGetReward) - drops.Add(curPassMain.FreeRewardList[i - 1]); - - if (GetSlotState(i, false) == BPRewardSlot.ESlotState.CanGetReward) - drops.Add(curPassMain.PrimeRewardList[i - 1]); - } - - } - public void SetRedPoint() - { - var flag = 0; - for (int i = 1; i <= GetBPCurLevel; i++) - { - if (GetSlotState(i, false) == BPRewardSlot.ESlotState.CanGetReward || GetSlotState(i, true) == BPRewardSlot.ESlotState.CanGetReward) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_BattlePass_Reward, true); - flag = 1; - break; - } - } - if (flag == 0) - RedPointManager.Instance.SetRedPointState(RedPointName.Home_BattlePass_Reward, false); - - foreach (var taskInfo in Data.BattleTask.dic_dailyTasks) - { - var task = _tables.TbBattlePassTask.Get(taskInfo.Key); - int requiredCount = int.Parse(task.Param[0]); - if (task.Type == ConditionType.ConsumeEnergy) - { - requiredCount = GContext.container.Resolve().IntInflation(requiredCount, Data.BattlePassRecord.InflationRate); - } - if (taskInfo.Value >= requiredCount) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_BattlePass_Task, true); - return; - } - } - foreach (var taskInfo in Data.BattleTask.dic_weeklyTasks) - { - var task = _tables.TbBattlePassTask.Get(taskInfo.Key); - int requiredCount = int.Parse(task.Param[0]); - if (task.Type == ConditionType.ConsumeEnergy) - { - requiredCount = GContext.container.Resolve().IntInflation(requiredCount, Data.BattlePassRecord.InflationRate); - } - if (taskInfo.Value >= requiredCount) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_BattlePass_Task, true); - return; - } - } - RedPointManager.Instance.SetRedPointState(RedPointName.Home_BattlePass_Task, false); - } - - public void SetVipUnlock() - { - Data.BattlePassRecord.IsUnlockVip = 1; - Data.SaveBattlePassRecord(); - } - - public void SetLevelRewardGet(int level, bool isNormal) - { - if (isNormal) - { - if (Data.BattlePassRecord.NormalRewardGet.Contains(level)) - { - Debug.LogError("Has Get Reward" + level); - return; - } - Data.BattlePassRecord.NormalRewardGet.Add(level); - } - else - { - if (Data.BattlePassRecord.VipRewardGet.Contains(level)) - { - Debug.LogError("Has Get Reward" + level); - return; - } - Data.BattlePassRecord.VipRewardGet.Add(level); - } - } - - public void SetBPExp(int exp) - { - var curExp = Data.BattlePassRecord.Exp + exp; - //Debug.Log("StartExp:" + Data.BattlePassRecord.Exp); - var upLevel = 0; - var curLevel = GetBPCurLevel; - while (curExp - GetTotalExpFromLevelRange(curLevel, curLevel + upLevel + 1) >= 0 && curLevel + upLevel < BPMaxLevel) - { - upLevel++; - } - - Data.BattlePassRecord.Exp = curExp - GetTotalExpFromLevelRange(curLevel, curLevel + upLevel); - Data.BattlePassRecord.Level = curLevel + upLevel; - //Debug.Log("EndExp:" + Data.BattlePassRecord.Exp + "Get:" + exp + " Level" + Data.BattlePassRecord.Level); - Data.SaveBattlePassRecord(); - SetRedPoint(); - } - - public void UpdateVipToastLevel() - { - Data.BattlePassRecord.BuyVipToastIndex++; - Data.SaveBattlePassRecord(); - } - - void UpdateTaskData(ConditionTypeEvent conditionTypeEvent) - { - if (!IsActivating) - return; - bool isUpdata = false; - var tasks = _tables.TbBattlePassTask; - var curTasks = Data.BattleTask.dic_dailyTasks; - var curTasksId = Data.BattleTask.dic_dailyTasks.Keys.ToList(); - //每日任务 - foreach (var taskId in curTasksId) - { - var task = tasks.GetOrDefault(taskId); - if (task == null) - continue; - if (task.Type == conditionTypeEvent.type) - { - int requiredCount = int.Parse(task.Param[0]); - if (task.Type == ConditionType.ConsumeEnergy) - { - requiredCount = GContext.container.Resolve().IntInflation(requiredCount, Data.BattlePassRecord.InflationRate); - } - if (curTasks[taskId] == requiredCount || curTasks[taskId] == -1) - { - continue; - } - if (task.Type == ConditionType.LoginDays && Data.BattleTask.loginDays.Contains((int)ZZTimeHelper.UtcNow().UtcNowOffset().DayOfWeek)) - { - continue; - } - - curTasks[taskId] += conditionTypeEvent.count; - if (curTasks[taskId] >= requiredCount) - { - curTasks[taskId] = requiredCount; - } - - isUpdata = true; - } - } - curTasks = Data.BattleTask.dic_weeklyTasks; - curTasksId = Data.BattleTask.dic_weeklyTasks.Keys.ToList(); - //每周任务 - foreach (var taskId in curTasksId) - { - var task = tasks.GetOrDefault(taskId); - if (task == null) - continue; - if (task.Type == conditionTypeEvent.type) - { - int requiredCount = int.Parse(task.Param[0]); - if (task.Type == ConditionType.ConsumeEnergy) - { - requiredCount = GContext.container.Resolve().IntInflation(requiredCount, Data.BattlePassRecord.InflationRate); - } - if (curTasks[taskId] == requiredCount || curTasks[taskId] == -1) - { - continue; - } - - if (task.Type == ConditionType.LoginDays && Data.BattleTask.loginDays.Contains((int)ZZTimeHelper.UtcNow().UtcNowOffset().DayOfWeek)) - { - continue; - } - - curTasks[taskId] += conditionTypeEvent.count; - if (curTasks[taskId] >= requiredCount) - { - curTasks[taskId] = requiredCount; - } - - isUpdata = true; - } - } - if (isUpdata) - { - if (conditionTypeEvent.type == ConditionType.LoginDays && Data.BattleTask.loginDays.Contains((int)ZZTimeHelper.UtcNow().UtcNowOffset().DayOfWeek)) - { - Data.BattleTask.loginDays.Add((int)ZZTimeHelper.UtcNow().UtcNowOffset().DayOfWeek); - } - Data.SaveBattleTask(); - } - - - } - - public void SetTaskDone(int taskID, bool isDailyTask) - { - var tasks = isDailyTask ? Data.BattleTask.dic_dailyTasks : Data.BattleTask.dic_weeklyTasks; - tasks[taskID] = -1; - Data.SaveBattleTask(); - } - #endregion - public void Dispose() - { - disposables?.Dispose(); - disposables = null; - } - -} - -public class BattlePassRecord -{ - public int ID; - public int Level; - public int Exp; - //0:Lock,1:Unlock - public int IsUnlockVip; - public int BuyVipToastIndex; - public List NormalRewardGet; - public List VipRewardGet; - public List LastDropIDs; - public float InflationRate; - - public BattlePassRecord() - { - ID = 0; - BuyVipToastIndex = 0; - Level = 1; - NormalRewardGet = new List(); - VipRewardGet = new List(); - LastDropIDs = new(); - } - public void Init(int id) - { - ID = id; - Level = 1; - Exp = 0; - BuyVipToastIndex = 0; - IsUnlockVip = 0; - NormalRewardGet.Clear(); - VipRewardGet.Clear(); - } - public string SerializeObject() - { - return $"{ID}|{Level}|{Exp}|{BuyVipToastIndex}|{IsUnlockVip}|{string.Join(',', NormalRewardGet)}|{string.Join(',', VipRewardGet)}"; - } - public void DeserializeObject(string data) - { - var arr = data.Split('|'); - ID = int.Parse(arr[0]); - Level = int.Parse(arr[1]); - Exp = int.Parse(arr[2]); - BuyVipToastIndex = int.Parse(arr[3]); - IsUnlockVip = int.Parse(arr[4]); - NormalRewardGet = arr[5].Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => int.Parse(x)).ToList(); - VipRewardGet = arr[6].Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => int.Parse(x)).ToList(); - } -} -public class BattleTask -{ - public Dictionary dic_dailyTasks; - public Dictionary dic_weeklyTasks; - public List loginDays; - public DateTime DailyTaskEndTime; - public DateTime WeeklyTaskEndTime; - public BattleTask() - { - dic_dailyTasks = new Dictionary(); - dic_weeklyTasks = new Dictionary(); - loginDays = new List(); - } - public string SerializeObject() - { - string dailyTasksStr = string.Join(',', dic_dailyTasks.Select(x => $"{x.Key}:{x.Value}")); - string weeklyTasksStr = string.Join(',', dic_weeklyTasks.Select(x => $"{x.Key}:{x.Value}")); - string loginDaysStr = string.Join(',', loginDays); - return $"{dailyTasksStr}|{weeklyTasksStr}|{loginDaysStr}|{DailyTaskEndTime.Ticks}|{WeeklyTaskEndTime.Ticks}"; - } - public void DeserializeObject(string data) - { - var arr = data.Split('|'); - dic_dailyTasks = arr[0].Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => - { - var kv = x.Split(':'); - return new KeyValuePair(int.Parse(kv[0]), int.Parse(kv[1])); - }).ToDictionary(x => x.Key, x => x.Value); - dic_weeklyTasks = arr[1].Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => - { - var kv = x.Split(':'); - return new KeyValuePair(int.Parse(kv[0]), int.Parse(kv[1])); - }).ToDictionary(x => x.Key, x => x.Value); - loginDays = arr[2].Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => int.Parse(x)).ToList(); - DailyTaskEndTime = new DateTime(long.Parse(arr[3])); - WeeklyTaskEndTime = new DateTime(long.Parse(arr[4])); - } -} - - - diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/007-BuffDataCenter.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/007-BuffDataCenter.cs.txt deleted file mode 100644 index d8947dd18..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/007-BuffDataCenter.cs.txt +++ /dev/null @@ -1,596 +0,0 @@ -using asap.core; -using cfg; -using GameCore; -using System; -using System.Collections.Generic; - -public class BuffDataCenter -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - private cfg.Tables _tables; - public BuffDataCenter(cfg.Tables tables) - { - this._tables = tables; - } - Dictionary mapBuffDataList = new Dictionary(); - List targetBuffDataList = new List(); - Dictionary globalBuffDataList = new Dictionary(); - FishBuffTimeData fishDailyBuff = null; - public List showFishBuffIds = new List(); - - internal static game.PlayerDataStorage.PlayerKVBuffState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeBuffs(raw,snapshot,errors); - internal void ResetForKVLoad() - { - mapBuffDataList=new Dictionary(); - targetBuffDataList=new List(); - globalBuffDataList=new Dictionary(); - showFishBuffIds=new List(); fishDailyBuff=null; - } - static FishBuffTimeData MaterializeKVBuff(game.PlayerDataStorage.PlayerKVBuffValue value) => value==null ? null : new FishBuffTimeData - { SortID=value.SortID,sourceID=value.sourceID,buffID=value.buffID,isEnd=value.isEnd,buffEndTime=value.buffEndTime,isNew=false,addDown=0 }; - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVBuffState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - var map=new Dictionary(); var global=new Dictionary(); var target=new List(); - foreach(var item in state.Map) map.Add(item.Key,MaterializeKVBuff(item.Value)); - foreach(var item in state.Global) global.Add(item.Key,MaterializeKVBuff(item.Value)); - foreach(var item in state.Target) target.Add(MaterializeKVBuff(item)); - mapBuffDataList=map; globalBuffDataList=global; targetBuffDataList=target; fishDailyBuff=MaterializeKVBuff(state.Daily); - } -#if UNITY_EDITOR - internal FishBuffTimeData BuffForKVValidation(int kind,int key) - { - if(kind==0) return mapBuffDataList.TryGetValue(key,out var value) ? value : null; - if(kind==1) return targetBuffDataList.Count>key ? targetBuffDataList[key] : null; - if(kind==2) return fishDailyBuff; - return globalBuffDataList.TryGetValue(key,out var global) ? global : null; - } - internal bool IsEmptyForKVValidation => mapBuffDataList.Count==0 && targetBuffDataList.Count==0 && - globalBuffDataList.Count==0 && showFishBuffIds.Count==0 && fishDailyBuff==null; -#endif - public void InitData(Dictionary userDatas) - { - if (userDatas.TryGetValue("BuffDataList", out string buffDataStr)) - { - InitBuffData(buffDataStr); - } - if (userDatas.TryGetValue("TargetBuffDataList", out string targetBuffDataStr)) - { - InitTargetBuffData(targetBuffDataStr); - } - if (userDatas.TryGetValue("FishDailyBuff", out string dailyBuffDataStr)) - { - InitDailyBuffData(dailyBuffDataStr); - } - if (userDatas.TryGetValue("GlobalBuffDataList", out string globalBuffDataStr)) - { - InitGlobalBuffData(globalBuffDataStr); - } - - } - void InitBuffData(string dataStr) - { - mapBuffDataList = Newtonsoft.Json.JsonConvert.DeserializeObject>(dataStr); - } - void InitTargetBuffData(string dataStr) - { - targetBuffDataList = Newtonsoft.Json.JsonConvert.DeserializeObject>(dataStr); - } - void InitDailyBuffData(string dataStr) - { - fishDailyBuff = Newtonsoft.Json.JsonConvert.DeserializeObject(dataStr); - } - void InitGlobalBuffData(string dataStr) - { - globalBuffDataList = Newtonsoft.Json.JsonConvert.DeserializeObject>(dataStr); - } - #region 地图Buff或目标奖励Buff - public FishBuff IsMapBuff(int mapId) - { - if (mapBuffDataList.TryGetValue(mapId, out FishBuffTimeData mapBuffData) && !mapBuffData.isEnd && mapBuffData.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - FishBuff buff = _tables.TbFishBuff.GetOrDefault(mapBuffData.buffID); - return buff; - } - foreach (var item in targetBuffDataList) - { - if (!item.isEnd && item.sourceID == mapId && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - - FishBuff buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - return buff; - } - } - return null; - } - public bool IsDarkness(int mapId) - { - if (mapBuffDataList.TryGetValue(mapId, out FishBuffTimeData mapBuffData) && !mapBuffData.isEnd && mapBuffData.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - var buff = _tables.TbFishBuff.GetOrDefault(mapBuffData.buffID); - if (buff.IsDarkness) - { - return true; - } - } - foreach (var item in targetBuffDataList) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (!item.isEnd && (item.sourceID == mapId || item.sourceID == 0) && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - if (buff.IsDarkness) - { - return true; - } - } - } - return false; - } - public string GetSceneFx(int mapId) - { - if (mapBuffDataList.TryGetValue(mapId, out FishBuffTimeData mapBuffData) && !mapBuffData.isEnd && mapBuffData.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - var buff = _tables.TbFishBuff.GetOrDefault(mapBuffData.buffID); - if (!string.IsNullOrEmpty(buff.SceneFx)) - { - return buff.SceneFx; - } - } - foreach (var item in targetBuffDataList) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (!item.isEnd && (item.sourceID == mapId || item.sourceID == 0) && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - if (!string.IsNullOrEmpty(buff.SceneFx)) - { - return buff.SceneFx; - } - } - } - return ""; - } - //获取某种Buff - public FishBuffTimeData GetBuffData() where T : FishBuffType - { - int curMapId = GContext.container.Resolve().currentMapId; - foreach (var item in targetBuffDataList) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (buff.BuffParam is T && !item.isEnd && (item.sourceID == curMapId || item.sourceID == 0) && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - return item; - } - } - return null; - } - //排行榜活动特殊地图额外积分 - public float GetSpMapExtraPointBuffValue() - { - float extraPointValue = 0; - foreach (var item in targetBuffDataList) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (buff.BuffParam is SpMapExtraPoint && !item.isEnd && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - SpMapExtraPoint extraPoint = buff.BuffParam as SpMapExtraPoint; - extraPointValue += extraPoint.Param; - } - } - return extraPointValue; - } - - #endregion - - #region 地图Buff - public bool CheckMapBuff(int mapID) - { - if (mapID != GContext.container.Resolve().lastMapId) - { - return false; - } - if (!mapBuffDataList.ContainsKey(mapID)) - { - var mapdata = _tables.TbMapData.GetOrDefault(mapID); - if (mapdata != null && mapdata.FishBuff > 0) - { - var buffData = _tables.TbFishBuff.GetOrDefault(mapdata.FishBuff); - var mapBuffData = new FishBuffTimeData(); - mapBuffData.SortID = buffData.SortID; - mapBuffData.sourceID = mapID; - mapBuffData.buffID = mapdata.FishBuff; - DateTime now = ZZTimeHelper.UtcNow().UtcNowOffset(); - mapBuffData.buffEndTime = now.AddSeconds(buffData.CountDown); - mapBuffDataList.Add(mapID, mapBuffData); - SaveStore.Write("BuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(mapBuffDataList)).RequireAccepted(); - return true; - } - } - return false; - } - //当前地图的Buff - public FishBuffTimeData GetMapBuffTimeData(int mapId) - { - if (mapBuffDataList.TryGetValue(mapId, out FishBuffTimeData mapBuffData) && !mapBuffData.isEnd && mapBuffData.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - return mapBuffData; - } - return null; - } - //钓鱼金币加成 - public float GetExtraGoldBuffValue(int mapId, int fishQuality) - { - float extraGoldValue = 0; - - if (mapBuffDataList.TryGetValue(mapId, out FishBuffTimeData mapBuffData) && !mapBuffData.isEnd && mapBuffData.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - var buff = _tables.TbFishBuff.GetOrDefault(mapBuffData.buffID); - if (buff.BuffParam is ExtraGold) - { - ExtraGold extraGold = buff.BuffParam as ExtraGold; - extraGoldValue += extraGold.Param; - } - } - MoreFishingCash moreFishingCash = GetWeelyBuffTimeData(); - if (moreFishingCash != null) - { - for (int i = 0; i < moreFishingCash.Quality.Count; i++) - { - if (fishQuality == moreFishingCash.Quality[i]) - { - extraGoldValue += moreFishingCash.Param[i]; - } - } - } - return extraGoldValue; - } - #endregion - #region 目标奖励活动Buff - public void CheckTargetBuff() - { - FishingEventData fishingEventData = GContext.container.Resolve(); - var collectingTargetInit = fishingEventData.collectingTargetInit; - if (collectingTargetInit != null) - { - EventTargetExtraDrop eventTargetExtraDrop = collectingTargetInit.FishingExtraDrop; - ETKeepsake eTKeepsake = null; - if (eventTargetExtraDrop is ETKeepsake) - { - eTKeepsake = eventTargetExtraDrop as ETKeepsake; - } - else - { - return; - } - - int buffID = eTKeepsake.FishbuffID; - FishBuff fishBuff = _tables.TbFishBuff.GetOrDefault(buffID); - if (fishBuff != null) - { - FishBuffTimeData fishBuffTimeData = new FishBuffTimeData(); - if (fishBuff.IsMapBuff) - { - fishBuffTimeData.sourceID = GContext.container.Resolve().currentMapId; - } - else - { - fishBuffTimeData.sourceID = 0; - } - fishBuffTimeData.SortID = fishBuff.SortID; - fishBuffTimeData.buffID = fishBuff.ID; - if (fishBuff.CountDown > 0) - { - fishBuffTimeData.buffEndTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(fishBuff.CountDown); - } - else - { - fishBuffTimeData.buffEndTime = fishingEventData.GetCollectingTargetEndTime(); - } - for (int i = 0; i < targetBuffDataList.Count; i++) - { - if (targetBuffDataList[i].buffID == fishBuffTimeData.buffID && targetBuffDataList[i].sourceID == fishBuffTimeData.sourceID) - { - targetBuffDataList[i] = fishBuffTimeData; - SaveStore.Write("TargetBuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(targetBuffDataList)).RequireAccepted(); - return; - } - } - targetBuffDataList.Add(fishBuffTimeData); - SaveStore.Write("TargetBuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(targetBuffDataList)).RequireAccepted(); - } - } - else - { - ClearTargetBuff(); - } - } - public void ClearTargetBuff() - { - targetBuffDataList.Clear(); - SaveStore.Write("TargetBuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(targetBuffDataList)).RequireAccepted(); - } - /// - /// CollectionTargetWeight的特殊处理 - /// - /// - public void EndCollectionTargetWeight(int fishItemId) - { - CollectingTargetInit collectingTargetInit = GContext.container.Resolve().collectingTargetInit; - if (collectingTargetInit == null) - { - return; - } - EventTargetExtraDrop eventTargetExtraDrop = collectingTargetInit.FishingExtraDrop; - ETKeepsake eTKeepsake = null; - if (eventTargetExtraDrop is ETKeepsake) - { - eTKeepsake = eventTargetExtraDrop as ETKeepsake; - } - else - { - return; - } - FishBuff fishBuff; - int curMapId = GContext.container.Resolve().currentMapId; - foreach (var item in targetBuffDataList) - { - fishBuff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (!item.isEnd && (item.sourceID == curMapId || item.sourceID == 0) && fishBuff.BuffParam is CollectionTargetWeight) - { - CollectionTargetWeight collectionTargetWeight = fishBuff.BuffParam as CollectionTargetWeight; - if (collectionTargetWeight.TargetFishIndex < 1 || collectionTargetWeight.TargetFishIndex > eTKeepsake.FishIDList.Count) - { - continue; - } - else if (fishItemId == eTKeepsake.FishIDList[collectionTargetWeight.TargetFishIndex - 1]) - { - item.isEnd = true; - SaveStore.Write("TargetBuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(targetBuffDataList)).RequireAccepted(); - break; - } - } - } - } - //目标奖励活动额外积分 - public float GetCollectionTargetExtraPointBuffValue(int mapId) - { - float extraPointValue = 0; - foreach (var item in targetBuffDataList) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.buffID); - if (buff.BuffParam is CollectionTargetExtraPoint && !item.isEnd && (item.sourceID == mapId || item.sourceID == 0) && item.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - CollectionTargetExtraPoint extraPoint = buff.BuffParam as CollectionTargetExtraPoint; - extraPointValue += extraPoint.Param; - } - } - return extraPointValue; - } - #endregion - #region 全局Buff Item投放 - - public void SetGlobalBucffNew(int buffID, bool isNew = true) - { - var buff = _tables.TbFishBuff.GetOrDefault(buffID); - if (buff != null) - { - if (globalBuffDataList.TryGetValue(buff.GroupId, out FishBuffTimeData fishBuffTimeData)) - { - if (fishBuffTimeData.isNew != isNew) - { - fishBuffTimeData.isNew = isNew; - - if (isNew) - { - showFishBuffIds.Add(fishBuffTimeData); - } - else - { - showFishBuffIds.Remove(fishBuffTimeData); - } - } - } - } - } - - public void AddGlobalBuff(int buffID) - { - var buff = _tables.TbFishBuff.GetOrDefault(buffID); - if (buff != null) - { - var UtcNow = ZZTimeHelper.UtcNow().UtcNowOffset(); - bool isNewBuff = true; - if (globalBuffDataList.TryGetValue(buff.GroupId, out FishBuffTimeData fishBuffTimeData)) - { - var oldBuff = _tables.TbFishBuff.GetOrDefault(fishBuffTimeData.buffID); - if (oldBuff.GroupId != buff.GroupId) - { - globalBuffDataList.Remove(buff.GroupId); - } - else - { - isNewBuff = false; - if (fishBuffTimeData.buffEndTime.Ticks > UtcNow.Ticks) - { - fishBuffTimeData.buffEndTime = fishBuffTimeData.buffEndTime.AddSeconds(buff.CountDown); - if (buff.SortID > fishBuffTimeData.SortID) - { - fishBuffTimeData.SortID = buff.SortID; - } - } - else - { - fishBuffTimeData.buffEndTime = UtcNow.AddSeconds(buff.CountDown); - fishBuffTimeData.SortID = buff.SortID; - fishBuffTimeData.isNew = true; - } - fishBuffTimeData.isEnd = false; - showFishBuffIds.Add(fishBuffTimeData); - fishBuffTimeData.addDown = buff.CountDown; - } - } - if (isNewBuff) - { - fishBuffTimeData = new FishBuffTimeData(); - if (buff.IsMapBuff) - { - fishBuffTimeData.sourceID = GContext.container.Resolve().currentMapId; - } - else - { - fishBuffTimeData.sourceID = 0; - } - fishBuffTimeData.buffID = buffID; - if (buff.CountDown > 0) - { - fishBuffTimeData.buffEndTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(buff.CountDown); - } - else - { - fishBuffTimeData.buffEndTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddDays(1); - } - globalBuffDataList[buff.GroupId] = fishBuffTimeData; - fishBuffTimeData.SortID = buff.SortID; - fishBuffTimeData.isNew = true; - fishBuffTimeData.addDown = buff.CountDown; - showFishBuffIds.Add(fishBuffTimeData); - } - SaveStore.Write("GlobalBuffDataList", Newtonsoft.Json.JsonConvert.SerializeObject(globalBuffDataList)).RequireAccepted(); - GContext.Publish(new AddGlobalBuffEvent(buffID)); - } - } - - //GetBuffGroupTimeData - public T GetWeelyBuffTimeData(bool isEnd = false) where T : FishBuffType - { - GetWeelyBuff(); - foreach (var item in globalBuffDataList) - { - if (!item.Value.isEnd && item.Value.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - FishBuff buff = _tables.TbFishBuff.GetOrDefault(item.Value.buffID); - if (buff != null && buff.BuffParam is T) - { - //if (isEnd) - //{ - // item.Value.isEnd = true; - //} - return buff.BuffParam as T; - } - } - } - return null; - } - public FishBuffTimeData GetBuffTimeDataByType() where T : FishBuffType - { - GetWeelyBuff(); - foreach (var item in globalBuffDataList) - { - if (!item.Value.isEnd && item.Value.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - FishBuff buff = _tables.TbFishBuff.GetOrDefault(item.Value.buffID); - if (buff.BuffParam.GetType() == typeof(T)) - { - return item.Value; - } - } - } - return null; - } - public List GetGroupBuff() - { - GetWeelyBuff(); - List buffList = new List(); - foreach (var item in globalBuffDataList) - { - if (!item.Value.isEnd && item.Value.buffEndTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks) - { - buffList.Add(item.Value); - } - } - return buffList; - } - #endregion - #region 每日周期Buff - - FishBuffTimeData GetWeelyBuff() - { - DateTime now = ZZTimeHelper.UtcNow().UtcNowOffset(); - int week = (int)now.DayOfWeek; - var weelyBuff = _tables.TbWeelyBuffInit.GetOrDefault(week); - if (weelyBuff != null) - { - List dailyBuffList = weelyBuff.DailyBuffList; - int day = now.DayOfYear; - if (fishDailyBuff != null && fishDailyBuff.buffEndTime > now/* && fishDailyBuff.buffEndTime.DayOfYear == day*/) - { - //旧的每日Buff还未结束 - return fishDailyBuff; - } - for (int i = 0; i < dailyBuffList.Count; i++) - { - var buff = _tables.TbDailyBuffTrigger.GetOrDefault(dailyBuffList[i]); - if (buff != null) - { - DateTime startTime = now.Date.AddSeconds(buff.StartTime); - DateTime endTime = now.Date.AddSeconds(buff.EndTime); - if (now >= startTime && now <= endTime) - { - //开启新的每日Buff - if (buff.LevelRequired > GContext.container.Resolve().lv) - { - return null; - } - if (fishDailyBuff == null) - { - fishDailyBuff = new FishBuffTimeData(); - } - if (fishDailyBuff.sourceID == buff.Day/* && fishDailyBuff.buffEndTime.DayOfYear == day*/) - { - return null; - } - FishBuff fishBuff = _tables.TbFishBuff.GetOrDefault(buff.BuffID); - fishDailyBuff.buffID = buff.BuffID; - fishDailyBuff.sourceID = buff.Day; - fishDailyBuff.buffEndTime = endTime; - if (fishBuff.CountDown > 0) - { - fishDailyBuff.buffEndTime = now.AddSeconds(fishBuff.CountDown); - } - AddGlobalBuff(buff.BuffID); - fishDailyBuff.isEnd = false; - SaveStore.Write("FishDailyBuff", Newtonsoft.Json.JsonConvert.SerializeObject(fishDailyBuff)).RequireAccepted(); - return fishDailyBuff; - } - } - } - - } - - return null; - } - #endregion -} -public class FishBuffTimeData -{ - public int SortID; - public int sourceID; - public int buffID; - public bool isEnd = false; - [NonSerialized] - public bool isNew = false; - [NonSerialized] - public int addDown; - public DateTime buffEndTime; -} -public class AddGlobalBuffEvent -{ - - public int buffID; - public AddGlobalBuffEvent(int buffID) - { - this.buffID = buffID; - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/008-DataCenter.FishingEventData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/008-DataCenter.FishingEventData.cs.txt deleted file mode 100644 index 747b13f89..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/008-DataCenter.FishingEventData.cs.txt +++ /dev/null @@ -1,2771 +0,0 @@ -using Activity.Services; -using asap.core; -using Assets.Scripts.UI.SocialRush; -using cfg; -using DataCenter; -using game; -using LitJson; -using Script.RuntimeScript; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using UniRx; -using UnityEngine; - -public class LimitedTimeEvent -{ - public int id; - - //持续时间分钟 - public double duration; - - //开始时间 - public string startTime; -} -public class FixedTimeEvent -{ - public int id; - //结束时间 - public string endTime; -} - -public struct TargetEvent -{ - public TargetEvent(int id, int type, int subType) - { - this.id = id; - this.type = type; - this.subType = subType; - } - public int id; - public int type; - public int subType; -} -public struct ConditionTypeEvent -{ - public ConditionTypeEvent(ConditionType conditionType, int count) - { - this.type = conditionType; - this.count = count; - } - public ConditionType type; - public int count; -} -namespace GameCore -{ - public partial class FishingEventData : IDisposable - { - game.PlayerDataStorage.IPlayerSaveStore boundSaveStore; - [Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore - { - get => boundSaveStore; - set - { - ThanksGivingPackData.BindSaveStore(value); - ChainPackWithProgressMigrationData.BindSaveStore(value); - boundSaveStore = value; - } - } - T ReadEventArchive(string key) where T : class - { - var read = playerSaveStore.Read(key); - var json = read.ValueOrThrow(); - if (read.Found == false) return null; - if (string.IsNullOrWhiteSpace(json)) - throw new Newtonsoft.Json.JsonSerializationException("Stored event archive cannot be empty: " + key); - return Newtonsoft.Json.JsonConvert.DeserializeObject(json) ?? - throw new Newtonsoft.Json.JsonSerializationException("Stored event archive cannot be null: " + key); - } - private cfg.Tables _tables; - private MMTService _mmtService; - private IEventTokenService _eventTokenService; - private IEventTokenService TokenService => - _eventTokenService ??= GContext.container?.Resolve(); - - public FishingEventData(cfg.Tables tables) - { - this._tables = tables; - _mmtService = GContext.container.Resolve(); - } - Dictionary limitedTimeEventDic = new Dictionary(); - - //固定时间开启事件的过期时间 - Dictionary fixedTimeEventDic = new Dictionary(); - public Dictionary FixedTimeEventDic => fixedTimeEventDic; - private int collectingTargetEventID = -1; - private int virtualCollectingTargetEventID = -1; - private DateTime NewPlayerEvent = DateTime.MinValue; - - public CollectingTargetInit collectingTargetInit = null; - public int collectingTargetInitTokenID; - public int collectingTargetInitTaskID; - public bool IsJoinUsPanelOpen = false; - public bool collectingTargetResoure = true; - public bool IsAquariumOpen = false; - public bool IsOpenDrop = false; - public int OpenAquariumID; - - public static string NextQueueKey = "CollectingTargetNextQueueKey"; - - List TargetList; - public CollectingTargetReward collectingTarget = null; - - public Queue preCollectingTarget = null; - public List targetItemDatas = null; - public List preRankTarget = null; - public List rankItemDatas = null; - /// - /// 0:rankEventID -1:isRankSendNotification -4 当前体力膨胀倍率(InflationRate*100) - /// - public Dictionary RankTargetCount = new Dictionary(); - private FishingEvent rankEvent = null; - public RankInit rankInit = null; - public RankTargets rankTarget = null; - /// - ///-5 当前任务Index - ///-4 当前体力膨胀倍率(InflationRate*100) - ///-3:新手活动过期时间 - ///-1:礼包购买数量 - ///0:rankEventID - ///1:新手引导数量 FishID :X 倍率 数量 ItemID: 钓鱼数量 TokenID:任务目标ID - /// - Dictionary ETDropAfterDropDic = new Dictionary(); - bool _isTargetGuidance = true; - private FishingEvent turntableEvent; - public WheelInit wheelInit = null; - public WheelLevel wheelLevel = null; - /// - /// Exp of each lvl. Key "-1" has expire time count. - /// Key "-2" counts the purchase time in "lack of ticket" panel. - /// LYNB. - /// - public Dictionary WheelLevelCount = new Dictionary(); - public int TurntableCoupon { get; private set; } - public int WheelOperateCount; - public int AllWheelOperateCount; - //public Dictionary WheelOperateCountDic = new Dictionary(); - public int freecount; - Dictionary SystemOpen = new Dictionary(); - HashSet _unlocked = new HashSet(); - //待释放 - IDisposable disposable; - - internal static game.PlayerDataStorage.PlayerKVEventBaseState DecodeForKVLoad(IReadOnlyDictionary raw, - IReadOnlyDictionary modern,game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) - => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeEventBase(raw,modern,snapshot,errors); - internal void ResetForKVLoad() - { - limitedTimeEventDic=new Dictionary(); fixedTimeEventDic=new Dictionary(); - ETDropAfterDropDic=new Dictionary(); RankTargetCount=new Dictionary(); WheelLevelCount=new Dictionary(); - TurntableCoupon=_tables.TbGlobalConfig.InitWheelTicket; WheelOperateCount=0; AllWheelOperateCount=0; freecount=0; PVPToken=0; - collectingTargetEventID=-1; virtualCollectingTargetEventID=-1; NewPlayerEvent=default; - collectingTargetInit=null; collectingTargetInitTokenID=0; collectingTargetInitTaskID=0; - TargetList=null; collectingTarget=null; preCollectingTarget=null; targetItemDatas=null; preRankTarget=null; rankItemDatas=null; - rankEvent=null; rankInit=null; rankTarget=null; turntableEvent=null; wheelInit=null; wheelLevel=null; - SystemOpen=new Dictionary(); _unlocked=new HashSet(); _isTargetGuidance=true; - IsJoinUsPanelOpen=false; collectingTargetResoure=true; IsAquariumOpen=false; IsOpenDrop=false; OpenAquariumID=0; - requiredCount=0; requiredRankCount=0; curActivateItemId=0; - duelData=null; rankTierChangeState=0; curSolomain=null; Pack1A1Data=null; Pack1A2Data=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVEventBaseState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - limitedTimeEventDic=state.Limited.ToDictionary(p=>p.Key,p=>new LimitedTimeEvent { id=p.Value.Id,duration=p.Value.Duration,startTime=p.Value.StartTime }); - fixedTimeEventDic=state.Fixed.ToDictionary(p=>p.Key,p=>new FixedTimeEvent { id=p.Value.id,endTime=p.Value.endTime }); - ETDropAfterDropDic=state.Target.ToDictionary(p=>p.Key,p=>p.Value); RankTargetCount=state.Rank.ToDictionary(p=>p.Key,p=>p.Value); - WheelLevelCount=state.Wheel.ToDictionary(p=>p.Key,p=>p.Value); TurntableCoupon=state.Coupon; - WheelOperateCount=state.Operate; AllWheelOperateCount=state.AllOperate; freecount=state.Free; PVPToken=state.PvpToken; - } -#if UNITY_EDITOR - internal game.PlayerDataStorage.PlayerKVEventBaseState SnapshotForKVValidation() => new game.PlayerDataStorage.PlayerKVEventBaseState( - limitedTimeEventDic.ToDictionary(p=>p.Key,p=>new game.PlayerDataStorage.PlayerKVLimitedValue(p.Value.id,p.Value.duration,p.Value.startTime)), - fixedTimeEventDic.ToDictionary(p=>p.Key,p=>new game.PlayerDataStorage.PlayerKVFixedTimeValue(p.Value.id,p.Value.endTime)), - ETDropAfterDropDic,RankTargetCount,WheelLevelCount,TurntableCoupon,WheelOperateCount,AllWheelOperateCount,freecount,PVPToken); - internal void MutateCollectionsForKVValidation() - { limitedTimeEventDic.Values.First().duration=99; fixedTimeEventDic.Values.First().id=99; ETDropAfterDropDic.Clear(); RankTargetCount.Clear(); WheelLevelCount.Clear(); } - internal bool IsInactiveForKVValidation => collectingTargetEventID==-1 && virtualCollectingTargetEventID==-1 && NewPlayerEvent==default && - collectingTargetInit==null && collectingTargetInitTokenID==0 && collectingTargetInitTaskID==0 && TargetList==null && collectingTarget==null && - preCollectingTarget==null && targetItemDatas==null && preRankTarget==null && rankItemDatas==null && rankEvent==null && rankInit==null && rankTarget==null && - turntableEvent==null && wheelInit==null && wheelLevel==null && SystemOpen.Count==0 && _unlocked.Count==0 && duelData==null && curSolomain==null && - Pack1A1Data==null && Pack1A2Data==null && !IsJoinUsPanelOpen && !IsAquariumOpen && !IsOpenDrop && OpenAquariumID==0 && requiredCount==0 && requiredRankCount==0 && curActivateItemId==0; -#endif - - public void InitData(Dictionary userDatas) - { - InitTurntableRoll(_tables.TbGlobalConfig.InitWheelTicket); - - string data_value; - try - { - - if (userDatas.TryGetValue("LimitedTimeEventDic", out data_value)) - { - var limitedTimeEventDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - SetLimitedTimeEventDic(limitedTimeEventDic); - } - } - catch (Exception e) - { - Debug.LogError(e); - } - - if (userDatas.TryGetValue("FixedTimeEventDic", out data_value)) - { - fixedTimeEventDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("ETDropAfterDropDic", out data_value)) - { - ETDropAfterDropDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("RankTargetCount", out data_value)) - { - RankTargetCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("TurntableRoll", out data_value)) - { - InitTurntableRoll(GlobalUtils.TryParseInt(data_value)); - } - - if (userDatas.TryGetValue("WheelLevelCount", out data_value)) - { - WheelLevelCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("WheelOperateCount", out data_value)) - { - WheelOperateCount = GlobalUtils.TryParseInt(data_value); - } - - if (userDatas.TryGetValue("AllWheelOperateCount", out data_value)) - { - AllWheelOperateCount = GlobalUtils.TryParseInt(data_value); - } - - if (userDatas.TryGetValue("WheelLevelFreeCount", out data_value)) - { - freecount = GlobalUtils.TryParseInt(data_value); - } - - // TransitionData 已统一由 EventTokenService 管理,不再本地加载 - if (userDatas.TryGetValue("PVPToken", out data_value)) - { - PVPToken = GlobalUtils.TryParseInt(data_value); - } - } - - public void SetLimitedTimeEventDic(Dictionary _limitedTimeEventDic) - { - limitedTimeEventDic.Clear(); - var timer = ZZTimeHelper.UtcNow().UtcNowOffset(); - foreach (var limitedTimeEvent in _limitedTimeEventDic) - { - if ((timer - GlobalUtils.TryParseDateTime(limitedTimeEvent.Value.startTime, timer)).TotalMinutes < limitedTimeEvent.Value.duration) - { - limitedTimeEventDic.Add(limitedTimeEvent.Key, limitedTimeEvent.Value); - } - } - } - - public void Init() - { - List _dataList = _tables.TbFishingEvent.DataList; - foreach (var t in _dataList) - { - switch (t.Type) - { - case 1: - switch (t.SubType) - { - case 3: - GContext.container.Resolve().vipTipforUnlocked = t.ID; - break; - case 4: - GContext.container.Resolve().shopTipforUnlocked = t.ID; - break; - case 5: - GContext.container.Resolve().socialTipforUnlocked = t.ID; - break; - case 6: - GContext.container.Resolve().MapTipforUnlocked = t.ID; - break; - - case 17: - GContext.container.Resolve().LockTipID = t.ID; - break; - case 18: - GContext.container.Resolve().OpenGradeID = t.ID; - break; - case 20: - OpenAquariumID = t.ID; - break; - //case 7: - // //杆 - // break; - } - break; - //case 2: - // switch (t.SubType) - // { - // case 1: - // break; - // case 2: - // break; - // } - // break; - //case 3: - // switch (t.SubType) - // { - // //case 1: - // // GContext.container.Resolve().TipforUnlocked = t.ID; - // // break; - // //case 2: - // // break; - // //case 3: - // // break; - // case 4: - // break; - // } - // break; - } - - SetEvent(t); - } - - foreach (var limitedTimeEvent in limitedTimeEventDic) - { - FishingEvent fishingEvent = - _tables.TbFishingEvent.GetOrDefault(limitedTimeEvent.Key); - if (fishingEvent != null) - { - SetEvent(fishingEvent, false); - } - } - if (disposable == null) - { - disposable = GContext.OnEvent().Subscribe(OnEventDataChange); - } - InitTransitionDataDic(); - } - public string GetTipforUnlocked(int id) - { - var t = _tables.TbFishingEvent.GetOrDefault(id); - if (t != null) - { - int conditionCount = t.ConditionList.Count; - if (conditionCount > 1) - { - for (int i = 0; i < conditionCount; i++) - { - if (!GetEventCondition(t.ConditionList[i])) - { - return GetEventConditionString(t.ConditionList[i]); - } - } - } - else - { - return GetEventConditionString(t.ConditionList[0]); - } - } - return ""; - } - string GetEventConditionString(EventCondition eventCondition) - { - switch (eventCondition.Condition) - { - case ConditionType.GetFishCount: - int count = int.Parse(eventCondition.Param[0]) - GContext.container.Resolve().GetAnglingCount(); - if (count < 0) - { - count = 0; - } - return LocalizationMgr.GetFormatTextValue(eventCondition.TipforUnlocked_l10n_key, count); - case ConditionType.AccountLevel: - return LocalizationMgr.GetFormatTextValue(eventCondition.TipforUnlocked_l10n_key, eventCondition.Param[0]); - default: - return ""; - } - } - void OnEventDataChange(ConditionTypeEvent conditionTypeEvent) - { - OnEventDataChange(conditionTypeEvent.type, conditionTypeEvent.count); - } - //事件数据改变 - void OnEventDataChange(ConditionType type, int count) - { - List _dataList = _tables.TbFishingEvent.DataList; - foreach (var t in _dataList) - { - List ConditionList = t.ConditionList; - for (int i = 0; i < ConditionList.Count; i++) - { - if (ConditionList[i].Condition == type) - { - SetEvent(t); - break; - } - } - } - } - /// - /// 时间跨天刷新 - /// - public void AllRefresh() - { - List _dataList = _tables.TbFishingEvent.DataList; - List systemOpen = new List(); - List errors = null; - foreach (var t in _dataList) - { - int open = RedirectType(t.Type, t.SubType); - if (t.Type > 1 && !systemOpen.Contains(open)) - { - try - { - if (SetEvent(t)) - { - systemOpen.Add(open); - } - } - catch (Exception e) - { - Debug.LogError(e); - (errors ??= new List()).Add(e); - } - } - } - if (errors != null) throw new AggregateException("Activity refresh did not complete.", errors); - RefreshEvent(); - } - - public void RefreshEvent() - { - new EventMatchGameManager().CheckEventData(); - - } - /// - /// 检查某一类型活动是否开启,并初始化,用于活动到期检查刷新 - /// - /// - /// - public int GetEventAndInit(int type, int subType) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type, subType); - foreach (var t in _dataList) - { - if (SetEvent(t)) - { - return t.ID; - } - } - return -1; - } - /// - /// 检查某一类型活动是否开启,不初始化 - /// - /// - /// - /// - public int GetEvent(int type, int subType) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type, subType); - foreach (var t in _dataList) - { - if (Condition(t)) - { - return t.ID; - } - } - return -1; - } - /// - /// 检查某一类型活动是否开启,不初始化 - /// - /// - /// - /// - /// - public int GetEventRedirectID(int type, int subType) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type, subType); - foreach (var t in _dataList) - { - if (Condition(t)) - { - return t.RedirectID; - } - } - return -1; - } - /// - /// 检查某一类型活动是否开启,不初始化 - /// - /// - /// - /// - /// - public FishingEvent GetEventByTypeAndSubType(int type, int subType, bool isCheckCondition = true) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type, subType); - foreach (var t in _dataList) - { - if (Condition(t) || !isCheckCondition) - { - return t; - } - } - return null; - } - /// - /// 检查某一类型活动是否开启,不初始化 - /// - /// - /// - /// - public FishingEvent GetEventeByTimType(int type, int subType) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type, subType); - foreach (var t in _dataList) - { - bool isOpen = true; - if (t.TimeDefinition is UserRegistration) - { - UserRegistration userRegistrationEvent = (UserRegistration)t.TimeDefinition; - double time = GContext.container.Resolve().CreateTotalSeconds(); - isOpen = userRegistrationEvent.StartTime <= time && time < userRegistrationEvent.EndTime; - } - else if (t.TimeDefinition is FixedTime) - { - isOpen = FixedTimeEventExpired(t.ID); - } - else if (t.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)t.TimeDefinition; - isOpen = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()) <= ZZTimeHelper.UtcNow() && ZZTimeHelper.UtcNow() < GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - } - if (isOpen) - { - return t; - } - } - return null; - } - /// - /// 获取type开启活动数据,并确保活动初始化,用于活动代币转换 - /// - /// - /// - public FishingEvent GetEventTable(int type) - { - List _dataList = _tables.TbFishingEvent.GetAllDataByType(type); - foreach (var t in _dataList) - { - if (Condition(t)) - { - if (!_unlocked.Contains(t.ID)) - { - Debug.Log($"Event {t.ID} unlocked"); - SetEvent(t, false); - _unlocked.Add(t.ID); - } - return t; - } - } - return null; - } - /// - /// 刷新活动 条件发生改变持续广播当前条件能开启哪些活动 - /// 最好记一下活动ID t.ID,只要ID不同就初始化 - /// - /// - /// - /// - bool SetEvent(FishingEvent t, bool condition = true) - { - //Assert.IsTrue(t.ID != 30801002); - //bool b = Condition(t); - //if (t.Type == 3) - // Debug.Log($"condition of id: {t.ID} {t.Type} {t.SubType}: {b}"); - if (!condition || Condition(t)) - { - if (t.TimeDefinition is FixedTime) - { - if (!fixedTimeEventDic.ContainsKey(t.ID)) - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - fixedTimeEventDic[t.ID] = new FixedTimeEvent() - { - id = t.ID, - endTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(fixedTime.StartTime).ToString(), - }; - playerSaveStore.Write("FixedTimeEventDic", JsonMapper.ToJson(fixedTimeEventDic)).RequireAccepted(); - } - } - switch (t.Type) - { - case 1: - SetEvent1(t); - break; - case 2: - SetEvent2(t); - break; - case 3: - SetEvent3(t); - break; - case 4: - if (t.SubType == 1) //沙滩寻宝 - { - GContext.container.Resolve().DataModel.ActivityOpen(t); - } - else if (t.SubType == 3) //鱼缸建造 - { - var data = GContext.container.Resolve(); - Debug.Log($"[EventPartner]Event On, Try load data"); - data.LoadData(t); - } - else if (t.SubType == 5) // 魔药 - { - GContext.container.Resolve().ActivateEvent(t); - } - else if (t.SubType == 6) // 弹珠 - { - GContext.container.Resolve().ActivateEvent(t); - } - else if (t.SubType == 7) - { - var bingoModel = GContext.container.Resolve(); - var pfData = EventBingoPlayfabData.Load(); - var ppData = EventBingoPlayerPreferenceData.Load(); - if (bingoModel == null) - { - GContext.container.Register().AsSingleton(); - bingoModel = GContext.container.Resolve(); - if (pfData == null || pfData.EventId != t.ID) - { - // Debug.Log("[EventBingo] Reset bingo."); - bingoModel.Init(t); - bingoModel.ToPlayfabData().Save(); - bingoModel.ToPlayerPreferenceData().Save(); - GContext.container.Resolve().EventRefresh(t, bingoModel.Ctx.GetBattlePassId()); - } - else - { - // Debug.Log("[EventBingo] Load bingo."); - bingoModel.Load(pfData, ppData, t); - GContext.container.Resolve().EventRefresh(t, bingoModel.Ctx.GetBattlePassId()); - } - } - else if (bingoModel.EventId != t.ID) - { - bingoModel.Init(t); - bingoModel.ToPlayfabData().Save(); - bingoModel.ToPlayerPreferenceData().Save(); - GContext.container.Resolve().EventRefresh(t, bingoModel.Ctx.GetBattlePassId()); - } - else if (pfData == null) - { - Debug.LogWarning("[EventBingo] Playfab data empty but model exists."); - } - else if (bingoModel.EventId == t.ID && pfData.EventId == t.ID) - { - Debug.Log("[EventBingo] Redundant call. Skip."); - } - else - { - Debug.LogWarning($"[EventBingo] EventId mismatch! event: {t.ID}, pf: {pfData.EventId}, model: {bingoModel.EventId}"); - } - } - // else if (t.SubType == 8) - // { - // InitPartnerGatherData(t); - // } - else if (t.SubType == 11 || t.SubType == 16) - { - InitCubeMeltData(t); - } - else if (t.SubType == 12) - { - EventBossFight.EventBossFightManager.Register(); - } - else if (t.SubType == 14) - { - PinballUncountable.Manager.InitEvent(t); - } - break; - case 5: - if (t.SubType == 1) - { - InitSoloData(t); - } - break; - case 6: - SetEvent6(t); - break; - case 7: - SetEvent7(t); - break; - case 8: - SetEvent8(t); - break; - case 9: - SetEvent9(t); - break; - case 10: - SetEvent10(t); - break; - case 11: - SetEvent11(t); - break; - case 15: - SetEvent15(t); - break; - } - SystemOpen[RedirectType(t.Type, t.SubType)] = true; - - GContext.Publish(new TargetEvent(t.ID, t.Type, t.SubType)); - return true; - } - return false; - } - public bool FixedTimeEventExpired(int eventId) - { - if (fixedTimeEventDic.TryGetValue(eventId, out FixedTimeEvent fixedTimeEvent)) - { - var endTime = GlobalUtils.TryParseDateTime(fixedTimeEvent.endTime, ZZTimeHelper.UtcNow().UtcNowOffset()); - return endTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks; - } - return true; - } - - public bool Condition(FishingEvent fishingEvent) - { - if (fishingEvent == null) - { - return false; - } - bool isOpen = true; - if (fishingEvent.TimeDefinition is UserRegistration) - { - UserRegistration userRegistrationEvent = (UserRegistration)fishingEvent.TimeDefinition; - double time = GContext.container.Resolve().CreateTotalSeconds(); - isOpen = userRegistrationEvent.StartTime <= time && time < userRegistrationEvent.EndTime; - } - else if (fishingEvent.TimeDefinition is FixedTime) - { - isOpen = FixedTimeEventExpired(fishingEvent.ID); - } - else if (fishingEvent.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)fishingEvent.TimeDefinition; - isOpen = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()) <= ZZTimeHelper.UtcNow() && ZZTimeHelper.UtcNow() < GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - } - - if (!isOpen) - { - if (fishingEvent.Type == 3 && fishingEvent.SubType == 3 && fishingEvent.TimeDefinition is LimitedTime) - { - if (GetOpenByConditionList(fishingEvent.ConditionList, fishingEvent.ConditionRelation)) - { - LimitedTime limitedTime = (LimitedTime)fishingEvent.TimeDefinition; - RankInit rankInit = _tables.TbRankInit.GetOrDefault(fishingEvent.RedirectID); - if (rankInit != null) - { - DateTime endTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow().AddMonths(-1)).AddSeconds(rankInit.HoldTime); - if (endTime > ZZTimeHelper.UtcNow()) - { - GContext.container.Resolve().lastEventRank = rankInit; - GContext.container.Resolve().fishingEvent = fishingEvent; - } - } - } - } - return false; - } - //ab测试影响 开启时间不一致 走单独逻辑 - if (fishingEvent.Type == 2 && fishingEvent.SubType == 4) - { - var ad = GContext.container.Resolve(); - return ad.IsOpen(this, fishingEvent, GetEventCondition, Condition_NoRechargeSeconds); - } - - return GetOpenByConditionList(fishingEvent.ConditionList, fishingEvent.ConditionRelation); - } - bool GetOpenByConditionList(List ConditionList, int ConditionRelation) - { - bool isOpen = false; - int conditionCount = ConditionList.Count; - if (conditionCount > 1) - { - if (ConditionRelation == 0) - { - isOpen = false; - //或 - for (int i = 0; i < conditionCount; i++) - { - if (GetEventCondition(ConditionList[i])) - { - isOpen = true; - break; - } - } - } - else - { - isOpen = true; - // 1与 - for (int i = 0; i < conditionCount; i++) - { - if (!GetEventCondition(ConditionList[i])) - { - isOpen = false; - break; - } - } - } - } - else - { - isOpen = GetEventCondition(ConditionList[0]); - } - return isOpen; - } - bool GetEventCondition(EventCondition eventCondition) - { - bool isOpen = false; - switch (eventCondition.Condition) - { - case ConditionType.AccountLevel: - isOpen = GContext.container.Resolve().lv >= int.Parse(eventCondition.Param[0]); - break; - case ConditionType.GetFishCount: - isOpen = GContext.container.Resolve().GetAnglingCount() >= int.Parse(eventCondition.Param[0]); - break; - - case ConditionType.RoleCreateTime: - //isOpen = true; - double time = GContext.container.Resolve().CreateTotalSeconds(); - isOpen = (time >= int.Parse(eventCondition.Param[0]) * 3600); - break; - case ConditionType.RoleCreateTimeLessThan: - //isOpen = true; - double time1 = GContext.container.Resolve().CreateTotalSeconds(); - isOpen = (time1 < int.Parse(eventCondition.Param[0]) * 3600); - break; - case ConditionType.AccountLevelAfterNoEnergy: - isOpen = GContext.container.Resolve().lv > int.Parse(eventCondition.Param[0]); - break; - case ConditionType.NoRechargeSeconds: - isOpen = Condition_NoRechargeSeconds(int.Parse(eventCondition.Param[0])); - break; - default: - Debug.LogWarning($"Event {eventCondition.Condition} not registered."); - break; - } - return isOpen; - } - - private bool Condition_NoRechargeSeconds(int timeSeconds) - { - var lastPaymentStr = playerSaveStore.Read("LastPaymentTime").ValueOrThrow(); - DateTime curTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - DateTime endTime = curTime; - if (string.IsNullOrEmpty(lastPaymentStr) || !lastPaymentStr.Contains("__")) - endTime = GContext.container.Resolve().CreateTime.UtcNowOffset(); - //else - //{ - // var lastPaymentTimeStr = lastPaymentStr.Split('_')?.FirstOrDefault(); - // if (string.IsNullOrEmpty(lastPaymentTimeStr)) return false; - - // endTime = GlobalUtils.TryParseDateTime(lastPaymentTimeStr, curTime); - //} - var curTimeSceond = new DateTimeOffset(curTime).ToUnixTimeSeconds(); - var endTimeSceond = new DateTimeOffset(endTime).ToUnixTimeSeconds(); - if (curTimeSceond - endTimeSceond >= timeSeconds) - return true; - return false; - } - public static bool Condition_NoRechargeDay(int timeDay = 7) - { - var store = GContext.container.Resolve().playerSaveStore; - var lastPaymentStr = store.Read("LastPaymentTime").ValueOrThrow(); - if (!string.IsNullOrEmpty(lastPaymentStr) && lastPaymentStr.Contains("__")) - return false; - DateTime curTime = ZZTimeHelper.UtcNow(); - DateTime endTime = GContext.container.Resolve().CreateTime; - if ((curTime - endTime).Days < timeDay) - return false; - return true; - } - void SetEvent1(FishingEvent t) - { - switch (t.SubType) - { - case 2: - GContext.container.Resolve().IsOpenMagnification = true; - break; - case 3: - GContext.container.Resolve().IsVIPOpen = true; - break; - case 4: - GContext.container.Resolve().IsShopOpen = true; - GContext.Publish(new SUnlockDiamondShopEvent { }); - break; - case 5: - GContext.container.Resolve().IsOpenClubJoined = true; - break; - case 6: - GContext.container.Resolve().IsOpenMap = true; - break; - case 7: - GContext.container.Resolve().IsOpenRod = true; - break; - //case 8: - // GContext.container.Resolve().IsOpenAutoFish = true; - // break; - case 9: - GContext.container.Resolve().IsShopTopOpen = true; - break; - case 10: - GContext.container.Resolve().OpenAdPack(); - break; - case 11: - var dataProvider1 = GContext.container.Resolve(); - dataProvider1.IsUnclocked = true; - //var boxCount = dataProvider1.Data.GetBoxTotalCount(); - //RedPointManager.Instance.SetRedPointState("Home.FishingBox", boxCount > 0, boxCount); - break; - case 13: - GContext.container.Resolve().IsOpenPiercing = true; - break; - case 14: - GContext.container.Resolve().IsUnlock = true; - break; - //case 15: - // //GContext.container.Resolve().IsUnlock = true; - // break; - //case 17: - // //GContext.container.Resolve().IsUnlock = true; - // break; - case 18: - GContext.container.Resolve().OpenGrade = true; - break; - case 19: - IsJoinUsPanelOpen = true; - // Debug.Log("IsJoinUsPanelOpen True!!!!!!!!!!!"); - break; - case 20: - IsAquariumOpen = true; - break; - case 21: - GContext.container.Resolve().IsOpenleaderboard = true; - break; - case 22: - IsOpenDrop = true; - break; - } - } - public bool GetSystemOpen(int id) - { - FishingEvent fishingEvent = _tables.TbFishingEvent.GetOrDefault(id); - if (fishingEvent == null) - { - return false; - } - id = RedirectType(fishingEvent.Type, fishingEvent.SubType); - return SystemOpen.TryGetValue(id, out bool isOpen) ? isOpen : false; - } - void SetEvent2(FishingEvent t) - { - switch (t.SubType) - { - case 1: - //七日签到礼包 - GContext.container.Resolve().SetDailySignEvent(t); - break; - case 2: - //周任务 - //GContext.container.Resolve().SetTaskToWeeklyEvent(t); - break; - case 3: - //GContext.container.Resolve().SetEventSignEvent(t); - // GContext.container.Resolve().IsOpen = true; - break; - } - } - - void SetEvent3(FishingEvent t) - { - switch (t.SubType) - { - //case 1: - // GContext.container.Resolve().SetAlbumEvent(t); - // GContext.container.Resolve().AlbumEventID = t.ID; - // break; - case 2: - SetCollectingTargetEvent(t); - break; - case 3: - SetRankEvent(t); - break; - case 4: - //转盘 - SetTurntable(t); - break; - - case 7: - GContext.container.Resolve().RefreshBattlePassRecord(t); - break; - case 8: - case 11: - SetEventPackData(t); - break; - case 9: - // Debug.Log("Black Friday update data!!"); - var d = GContext.container.Resolve().CouponData; - d.UpdateData(t); - if (d.IsActive && d.DoesPop) - { - GContext.container.Resolve() - .AddGiftFaceUIForce(t.ID, UITypes.BlackFridayPopupPanel); - d.DoesPop = false; - } - break; - case 10: - GContext.container.Resolve().AddChainPack(t); - break; - } - } - void SetEvent6(FishingEvent t) - { - switch (t.SubType) - { - case 1: - SetPack1A2(t); - break; - case 2: - // Debug.Log($"Event Triggered Thanks Giving!"); - var data = GContext.container.Resolve().ThanksGivingPackData; - if (t.ID != data.EventId) - data.UpdateData(t); - break; - } - } - - private void SetEvent7(FishingEvent e) - { - switch (e.SubType) - { - case 1: - var data = GContext.container.Resolve(); - if (data == null) - { - GContext.container.Register().AsSingleton(); - data = GContext.container.Resolve(); - } - data.UpdateData(e); - UITypes.EventWinterShootingPanel.SetType(data.MainPanelUrl); - UITypes.ShootingChainPackPanel.SetType(data.ChainPackPanelUrl); - UITypes.ShootingRangeFinalRewardPopup.SetType(data.RewardPanelUrl); - UITypes.ShootingRangeInfoPanel.SetType(data.InfoPanelUrl); - UITypes.ShootingNormalPackPanel.SetType(data.PackPanelUrl); - UITypes.ShootingRangeTransitionPanel.SetType(data.TransitionPanelUrl); - break; - case 2: - // Debug.Log($"[EventBreak] Id {e.ID} activated."); - EventBreakAct.Ctx = EventBreakTableContext.ReadTables(e.ID, GContext.container.Resolve()); - var playfabData = EventBreakPfData.Deserialize(playerSaveStore.Read(EventBreakPfData.PfKey).ValueOrThrow()); - var eventBreakModel = GContext.container.Resolve(); - if (eventBreakModel == null) - { - GContext.container.Register().AsSingleton(); - eventBreakModel = GContext.container.Resolve(); - } - if (eventBreakModel != null && eventBreakModel.EventId == e.ID) - return; - eventBreakModel.Update(e.ID, playfabData); - var uiData = EventBreakAct.Ctx.GetUIData(); - UITypes.EventBreakPanel.SetType(uiData.MainPanelUrl); - UITypes.EventBreakInfoPanel.SetType(uiData.InfoPanelUrl); - UITypes.EventBreakChainPackPanel.SetType(uiData.ChainPackPanelUrl); - UITypes.EventBreakNormalPackPanel.SetType(uiData.NormalPackPanelUrl); - UITypes.EventBreakRewardPopupPanel.SetType(uiData.RewardPanelUrl); - break; - case 3: // 刮刮乐 - GContext.container.Resolve().ActivateEvent(e); - break; - case 4: - var canModel = GContext.container.Resolve(); - var ecPlayfabString = playerSaveStore.Read(EventCanPlayfabData.PlayFabKey).ValueOrThrow(); - var ecPpString = PlayerPrefs.GetString(EventCanPlayerPreferenceData.PlayerPrefsKey); - var ecPlayfabData = EventCanPlayfabData.Deserialize(ecPlayfabString); - var ecPlayerPrefsData = EventCanPlayerPreferenceData.Deserialize(ecPpString); - var tableContext = GContext.container.Resolve(); - if (tableContext == null) - { - GContext.container.Register().AsSingleton(); - tableContext = GContext.container.Resolve(); - } - tableContext.ReadTables(e.ID); - if (canModel == null || canModel.EventId != e.ID) - { - if (canModel == null) - { - tableContext.ReadTables(e.ID); - GContext.container.Register().AsSingleton(); - canModel = GContext.container.Resolve(); - } - canModel.InitializeModel(e.ID, ecPlayfabData, ecPlayerPrefsData); - } - var chainPackData = GContext.container.Resolve(); - if (chainPackData == null) - { - GContext.container.Register().AsSingleton(); - chainPackData = GContext.container.Resolve(); - } - chainPackData.Init( - GContext.container.Resolve().GetPackData(canModel.ChainPackID), - e.ID, ref canModel.ChainPackProgress); - break; - case 5: - EventGatherCoreAct.Ctx = EventGatherCoreTableContext.ReadTables(e.ID); - var gatherCoreData = GContext.container.Resolve(); - var egcPfData = EventGatherCorePlayfabData.Load(); - if (gatherCoreData == null) - { - GContext.container.Register().AsSingleton(); - gatherCoreData = GContext.container.Resolve(); - } - if (gatherCoreData != null && gatherCoreData.EventId == e.ID) - return; - if (egcPfData != null && egcPfData.EventId == e.ID) - gatherCoreData.LoadData(egcPfData); - else - gatherCoreData.InitNew(e.ID); - var gatherCoreUiData = EventGatherCoreAct.Ctx.GetUiData(); - UITypes.EventGatherCorePanel.SetType(gatherCoreUiData.MainPanelUrl); - UITypes.EventGatherCoreInfoPanel.SetType(gatherCoreUiData.InfoPanelUrl); - UITypes.EventGatherCoreChainPackPanel.SetType(gatherCoreUiData.ChainPackPanelUrl); - UITypes.EventGatherCoreNormalPackPanel.SetType(gatherCoreUiData.NormalPackPanelUrl); - UITypes.EventGatherCoreRewardPopupPanel.SetType(gatherCoreUiData.RewardPopupPanelUrl); - break; - case 6: - EventMowForTreasure.EventMowForTreasureManager.Register(); - break; - case 10: // 砸罐子 - { - var smashMain = _tables.TbEventSmashMain.GetOrDefault(e.RedirectID); - if (smashMain != null && smashMain.BattlePassId > 0) - { - GContext.container.Resolve().EventRefresh(e, smashMain.BattlePassId); - } - } - break; - } - } - - void SetEvent8(FishingEvent t) - { - switch (t.SubType) - { - case 2: - SetTurntable(t); - break; - case 3: - var pfString = playerSaveStore.Read(EventLuckMagicPlayfabData.Key).ValueOrThrow(); - var pfData = EventLuckMagicPlayfabData.Deserialize(pfString); - var ppString = PlayerPrefs.GetString(EventLuckMagicPlayerPreferenceData.Key); - var ppData = EventLuckMagicPlayerPreferenceData.Deserialize(ppString); - - EventLuckMagicAct.TableContext = EventLuckMagicTableContext.ReadTables(t.ID); - var eventLuckMagicModel = GContext.container.Resolve(); - if (eventLuckMagicModel == null) - { - GContext.container.Register().AsSingleton(); - eventLuckMagicModel = GContext.container.Resolve(); - if (pfData == null || pfData.EventId != t.ID) - eventLuckMagicModel.InitNew(t.ID); - else - eventLuckMagicModel.Load(pfData, ppData); - } - else if (eventLuckMagicModel.EventId != t.ID) - { - // Here, I'll assume that playfab data is consistent with the model in memory. - eventLuckMagicModel.InitNew(t.ID); - } - else - { - //In this situation, this is a redundant call. - } - EventLuckMagicAct.System = new EventLuckMagicSystem(); - var uiUrls = EventLuckMagicAct.TableContext.GetUiPanelUrls(); - UITypes.EventLuckMagicTriplePackPanel.SetType(uiUrls.TriplePackPanelUrl); - break; - case 4: - EventLuckyGameModel.Get().OnEvent(t); - break; - } - } - /// - /// 9-1 小战令 - /// 9-5 offer journey - /// 9-6 小马礼包 - /// - /// - void SetEvent9(FishingEvent t) - { - if (t.SubType == 4) - { - GContext.container.Resolve().UpdateEventData(t); - } - else if (t.SubType == 5) - { - var offerJourneyData = GContext.container.Resolve(); - var playerData = GContext.container.Resolve(); - var eventOfferJourneyLvlTriggerTableContext = new EventOfferJourneyLvlTriggerTableContext(); - var pfData = EventOfferJourneyLvlTriggerPlayfabData.Load(); - if (eventOfferJourneyLvlTriggerTableContext.IsEventActive && - (pfData == null || pfData.RoundCount < eventOfferJourneyLvlTriggerTableContext.MaxRoundCount)) - { - Debug.Log("[EventOfferJourney] Normal event suppressed. TriggerPack On the way."); - return; - } - else if (offerJourneyData == null) - { - GContext.container.Register().AsSingleton(); - offerJourneyData = GContext.container.Resolve(); - if (!offerJourneyData.LoadDataFromPlayfab() || offerJourneyData.EventId != t.ID) - { - (offerJourneyData as EventOfferJourneyData).Init(t.ID, playerData.PriceLv); - } - GContext.container.Resolve().AddGiftFaceUI(t.ID, UITypes.EventOfferJourneyPanel, 0); - } - else if (offerJourneyData.EventId != t.ID) - { - if (offerJourneyData is EventOfferJourneyData offerJourneyDataActual) - offerJourneyDataActual.Init(t.ID, playerData.PriceLv); - else - { - GContext.container.Unregister(); - GContext.container.Register().AsSingleton(); - (GContext.container.Resolve() as EventOfferJourneyData).Init(t.ID, playerData.PriceLv); - } - GContext.container.Resolve().AddGiftFaceUI(t.ID, UITypes.EventOfferJourneyPanel, 0); - } - else - { - Debug.Log("[EventOfferJourney] Redundant call, ignore."); - } - var uiData = offerJourneyData.GetUiData(); - UITypes.EventOfferJourneyPanel.SetType(uiData.PanelUrl); - UITypes.EventOfferJourneyInfoPanel.SetType(uiData.InfoPanelUrl); - } - else if (t.SubType == 6) - { - GContext.container.Resolve().GetFreshPinataPackData(); - } - else if (t.SubType == 7) - { - GContext.container.Resolve().UpdateEventData(t); - } - else if (t.SubType == 8) - { - UI.HookWheel.HookWheelManager.Register(); - } - else if (t.SubType == 11) - { - OfferTreasureAscent.Manager.InitEvent(t); - } - else if (t.SubType == 1 || t.SubType == 2 || t.SubType == 3) - { - GContext.container.Resolve().EventRefresh(t, t.RedirectID); - } - else if (t.SubType == 9) - { - OfferStoryChain.Manager.InitEvent(t); - } - } - - void SetEvent10(FishingEvent t) - { - // GContext.container.Resolve().IsOpen = true; - GContext.container.Resolve().SetupEventData(t); - } - void SetEvent11(FishingEvent t) - { - switch (t.SubType) - { - case 1: - SocialRushArchitecture.Load(t); - break; - } - } - - private void InitPartnerGatherData(FishingEvent fishingEvent) - { - var manager = GContext.container.Resolve(); - manager.UpdateEventData(fishingEvent); - EventPartnerGatherManager.EnsureTokenExchangeContextRegistered(manager); - EventPartnerStatueTokenExchangeData.Load(fishingEvent); - } - public void InitCubeMeltData(FishingEvent fishingEvent) - { - GContext.container.Resolve().UpdateEventData(fishingEvent); - } - - - - - - public void SetRankEvent(FishingEvent t) - { - rankEvent = t; - if (!RankTargetCount.ContainsKey(0)) - { - RankTargetCount[0] = 0; - } - if (rankInit == null || RankTargetCount[0] != rankEvent.ID) - { - rankInit = _tables.TbRankInit.GetOrDefault(rankEvent.RedirectID); - InitRankTarget(); - //GContext.Publish(new TargetEvent(rankInit.ID, 3, 3)); - } - } - void SetTurntable(FishingEvent t) - { - turntableEvent = t; - if (!WheelLevelCount.ContainsKey(0)) - { - WheelLevelCount[0] = 0; - } - if (wheelInit == null || WheelLevelCount[0] != t.ID) - { - wheelInit = _tables.TbWheelInit.GetOrDefault(t.RedirectID); - - InitWheelLevel(); - } - //GContext.Publish(new TargetEvent(wheelInit.ID, 3, 4)); - } - - public void InitTurntableRoll(int value) - { - TurntableCoupon = value; - } - - - public void AddTurntableCoupon(int value) - { - TurntableCoupon = TurntableCoupon + value; - if (turntableEvent != null) - { - SaveTransitionData(turntableEvent.ID, TurntableCoupon); - } - TurntableRed(); - playerSaveStore.Write("TurntableRoll", TurntableCoupon.ToString()).RequireAccepted(); - } - public void RewardTurntableRoll(int value, bool remote = true) - { - GContext.Publish(new ConditionTypeEvent { type = ConditionType.ConusumeTicketCount, count = value }); - //Debug.Log($"Consume {value}"); - TurntableCoupon = TurntableCoupon - value; - if (turntableEvent != null) - SaveTransitionData(turntableEvent.ID, TurntableCoupon); - TurntableRed(); - -#if AGG - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", 1004) - .AddContent("state_info", "cost") - .AddContent("change_num", value); - } -#endif - playerSaveStore.Write("TurntableRoll", TurntableCoupon.ToString(), remote).RequireAccepted(); - } - - public void TurntableRed() - { - int CostNumber = 10; - if (wheelLevel != null) - { - CostNumber = wheelLevel.CostNumber; - } - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Turntable, TurntableCoupon >= 10 && TurntableCoupon >= CostNumber); - } - - public void GMSetEvent(int eventId) - { - FishingEvent fishingEvent = _tables.TbFishingEvent.GetOrDefault(eventId); - if (fishingEvent == null) - { - return; - } - - switch (fishingEvent.Type) - { - case 1: - SetEvent1(fishingEvent); - SystemOpen[RedirectType(fishingEvent.Type, fishingEvent.SubType)] = true; - break; - case 3: - case 4: - if (fishingEvent.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)fishingEvent.TimeDefinition; - limitedTimeEventDic[eventId] = new LimitedTimeEvent() - { - id = eventId, - duration = (GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()) - GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow())).TotalMinutes, - startTime = ZZTimeHelper.UtcNow().UtcNowOffset().ToString("yyyy-MM-dd HH:mm:ss") - }; - } - else if (fishingEvent.TimeDefinition is FixedTime) - { - FixedTime fixedTime = (FixedTime)fishingEvent.TimeDefinition; - limitedTimeEventDic[eventId] = new LimitedTimeEvent() - { - id = eventId, - duration = fixedTime.StartTime / 60, - startTime = ZZTimeHelper.UtcNow().UtcNowOffset().ToString("yyyy-MM-dd HH:mm:ss") - }; - } - //保存到PlayFab - SetLimitedTimeEventDic(); - if (fishingEvent.Type == 3) - { - SetEvent3(fishingEvent); - } - else if (fishingEvent.Type == 4) - { - if (fishingEvent.SubType == 5) - { - GContext.container.Resolve().ActivateEvent(fishingEvent); - } - else if (fishingEvent.SubType == 6) - { - GContext.container.Resolve().ActivateEvent(fishingEvent); - } - } - else if (fishingEvent.Type == 6) - { - SetEvent6(fishingEvent); - } - - SystemOpen[RedirectType(fishingEvent.Type, fishingEvent.SubType)] = true; - break; - case 7: - if (fishingEvent.SubType == 3) - { - GContext.container.Resolve().ActivateEvent(fishingEvent); - } - break; - } - GContext.Publish(new TargetEvent(eventId, fishingEvent.Type, fishingEvent.SubType)); - } - - void SetLimitedTimeEventDic() - { - playerSaveStore.Write("LimitedTimeEventDic", Newtonsoft.Json.JsonConvert.SerializeObject(limitedTimeEventDic)).RequireAccepted(); - } - - #region 目标奖励活动 - #region 新目标奖励活动 - public float OnFishReward(int mapId, int index, int fishCount) - { - float extraPoint = 0; - if (collectingTargetInit != null) - { - EventTargetExtraDrop eventTargetExtraDrop = collectingTargetInit.FishingExtraDrop; - int itemId = 0; - if (eventTargetExtraDrop is ETKeepsake) - { - var eTKeepsake = eventTargetExtraDrop as ETKeepsake; - itemId = eTKeepsake.FishIDList[index]; - if (index == 0) - { - int curHour = ZZTimeHelper.UtcNow().UtcNowOffset().Hour; - if (curHour >= 16) - { - curHour = 16; - } - else if (curHour >= 8) - { - curHour = 8; - } - else - { - curHour = 0; - } - //每日清空的数据 - GContext.container.Resolve().AddShopPackDailyBuyCount("CTFishID0" + curHour); - } - } - else if (eventTargetExtraDrop is ETNewItem) - { - var etNewItem = eventTargetExtraDrop as ETNewItem; - itemId = etNewItem.NewItemID[index]; - } - if (itemId > 0) - { - var itemToFishID = _tables.TbItem[itemId].RedirectID; - if (ETDropAfterDropDic.ContainsKey(itemToFishID)) - { - ETDropAfterDropDic[itemToFishID] += fishCount; - ETDropAfterDropDic[itemId]++; - } - else - { - ETDropAfterDropDic.Add(itemId, 1); - ETDropAfterDropDic.Add(itemToFishID, fishCount); - } - SaveCollectingTargetEvent(); - extraPoint += GContext.container.Resolve().GetCollectionTargetExtraPointBuffValue(mapId); - } - } - return extraPoint; - } - void SaveCollectingTargetEvent() - { - GContext.container.Resolve().SavePlayerData(); - //PlayFabMgr.Instance.UpdateUserDataValue("ETDropAfterDropDic", JsonMapper.ToJson(ETDropAfterDropDic)); - } - public string CTSerialize() - { - if (ETDropAfterDropDic.Count > 0) - { - return ETDropAfterDropDic.Select(kv => kv.Key + ":" + kv.Value).Aggregate((a, b) => a + "," + b); - } - else - { - return ""; - } - } - public void CTDeserialize(string data) - { - if (!string.IsNullOrEmpty(data)) - { - ETDropAfterDropDic.Clear(); - var pairs = data.Split(','); - foreach (var pair in pairs) - { - var kv = pair.Split(':'); - if (kv.Length == 2 && int.TryParse(kv[0], out int key) && int.TryParse(kv[1], out int value)) - { - ETDropAfterDropDic[key] = value; - } - } - } - } - #endregion - void SetCollectingTargetEvent(FishingEvent t) - { - int idOffset = _mmtService.GetEventTargetIDOffset(); - int RedirectID = t.RedirectID + idOffset; - var curTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - //ETDropAfterDropDic.Clear(); - if (!ETDropAfterDropDic.ContainsKey(0)) - { - //新手活动 - NewPlayerEvent = curTime.AddSeconds(_tables.TbGlobalConfig.EventtargetNoviceMinTime); - if (t.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)t.TimeDefinition; - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()).UtcNowOffset(); - //下一个目标奖励活动为常规目标奖励活动,如果其剩余时间小于1天,则时间会被归并到本次目标奖励活动 - if (endTime < NewPlayerEvent) - { - endTime = endTime.AddDays(3); - } - if (endTime < curTime.AddSeconds(_tables.TbGlobalConfig.EventtargetNextToNoviceMaxTime)) - { - NewPlayerEvent = endTime; - } - } - ETDropAfterDropDic[0] = 0; - ETDropAfterDropDic[-3] = (int)(NewPlayerEvent - new DateTime(2025, 10, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;//存储新手活动结束时间 - SaveCollectingTargetEvent(); - } - else if (ETDropAfterDropDic.ContainsKey(-3)) - { - NewPlayerEvent = new DateTime(2025, 10, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ETDropAfterDropDic[-3]); - } - if (NewPlayerEvent > curTime) - { - //随便输入一个不存在的ID - collectingTargetEventID = virtualCollectingTargetEventID; - RedirectID = _tables.TbGlobalConfig.EventtargetNoviceID + idOffset; - } - else - { - collectingTargetEventID = t.ID; - } - bool redirectIDChanged = ETDropAfterDropDic.TryGetValue(-6, out var savedRedirectID) && savedRedirectID != RedirectID; - if (collectingTargetInit == null || ETDropAfterDropDic[0] != collectingTargetEventID || redirectIDChanged) - { - //new target event - collectingTargetInit = _tables.TbCollectingTargetInit.GetOrDefault(RedirectID); - if (collectingTargetInit == null && idOffset != 0) - { - Debug.LogError($"CollectingTargetInit not found with MMT offset, fallback: {RedirectID} -> {RedirectID - idOffset}"); - RedirectID -= idOffset; - collectingTargetInit = _tables.TbCollectingTargetInit.GetOrDefault(RedirectID); - } - if (collectingTargetInit == null) - { - Debug.LogError($"CollectingTargetInit Error Id == {RedirectID} EventId == {collectingTargetEventID}"); - GContext.container.Resolve().ClearTargetBuff(); - collectingTarget = null; - collectingTargetResoure = false; - } - else - { - if (redirectIDChanged) - { - ETDropAfterDropDic.Clear(); - ETDropAfterDropDic[0] = 0; - } - collectingTargetResoure = false; - collectingTargetInitTokenID = collectingTargetInit.TokenID; - collectingTargetInitTaskID = collectingTargetInit.TaskID; - InitCollectingTarget(); - ETDropAfterDropDic[-6] = RedirectID; - SaveCollectingTargetEvent(); - UITypes.FishingTargetPopupPanel.SetType(collectingTargetInit.BgDescPrefab); - } - } - } - - public async Task CheckResourceLoadQueue(string key, List label) - { - var store = playerSaveStore; - if (!store.IsCurrent) return false; - if (!collectingTargetResoure) - { - ILoadResourceService loadResourceService = GContext.container.Resolve(); - var loaded = await loadResourceService.CheckResourceLoadQueue(key, label); - if (!store.IsCurrent) return false; - collectingTargetResoure = loaded; - } - return collectingTargetResoure; - } - - int requiredCount = 0; - void InitCollectingTarget() - { - if (!ETDropAfterDropDic.ContainsKey(0)) - { - ETDropAfterDropDic[0] = 0; - } - //Event Still Launch - if (collectingTargetEventID == ETDropAfterDropDic[0]) - { - SetTargetList(); - ETDropAfterDropDic.TryGetValue(collectingTargetInitTokenID, out var progress); - while (collectingTarget != null && collectingTarget.NextTarget > 0 && requiredCount <= progress) - { - collectingTarget = _tables.TbCollectingTargetReward.GetOrDefault(collectingTarget.NextTarget); - requiredCount += collectingTarget.TokenRequiredB; - ETDropAfterDropDic.TryGetValue(collectingTargetInitTokenID, out progress); - } - } - //Event Still Launch - else - { - RefreshTargetGuidance(); - if (collectingTargetEventID == virtualCollectingTargetEventID) - { - ETDropAfterDropDic[0] = virtualCollectingTargetEventID; - } - else - { - ETDropAfterDropDic.Clear(); - ETDropAfterDropDic[0] = collectingTargetEventID; - } - - var TargetGroupByHook = collectingTargetInit.TargetGroupByHook; - int hook = GContext.container.Resolve().Energy; - for (int i = TargetGroupByHook.Count - 1; i >= 0; i--) - { - if (hook >= TargetGroupByHook[i]) - { - ETDropAfterDropDic[-5] = i; //记录当前钩子档位 - break; - } - } - ETDropAfterDropDic[-4] = (int)(GContext.container.Resolve().InflationRate * 100); - SetTargetList(); - GContext.container.Resolve().ClearTargetBuff(); - } - } - void SetTargetList() - { - TargetList = GetIndexOfCollectingTargetHook(); - collectingTarget = _tables.TbCollectingTargetReward.GetOrDefault(TargetList[0]); - requiredCount = collectingTarget.TokenRequiredB; - } - public bool VirtualCollectingTargetEvent => collectingTargetEventID == virtualCollectingTargetEventID; - - /// - /// 特殊鱼,技能新手引导数量 - /// - public bool TargetGuidance(string guidanceName) - { - if (_isTargetGuidance) - { - _isTargetGuidance = false; - int SkillGuidanceRemainings = _tables.TbGlobalConfig.SkillGuidanceRemainings; - if (SkillGuidanceRemainings > (ETDropAfterDropDic.TryGetValue(1, out var progress) ? progress : 0)) - { - bool isGuide = GContext.container.Resolve().TriggerGuide(guidanceName, "FishingPanel_Advanced", true); - if (isGuide) - { - if (!ETDropAfterDropDic.ContainsKey(1)) - { - ETDropAfterDropDic[1] = 1; - } - else - { - ETDropAfterDropDic[1]++; - } - SaveCollectingTargetEvent(); - } - return isGuide; - } - } - return false; - } - - public void RefreshTargetGuidance() - { - _isTargetGuidance = true; - } - - public int GetCollectingTargetCount() - { - return ETDropAfterDropDic.TryGetValue(-1, out var progress) ? progress : 0; - } - public void AddCollectingTarget(int progress) - { - if (collectingTarget != null) - { - preCollectingTarget = null; - if (!ETDropAfterDropDic.ContainsKey(collectingTargetInitTokenID)) - { - ETDropAfterDropDic[collectingTargetInitTokenID] = 0; - } - //float Enhanced = GContext.container.Resolve().GetDoubleTokenEnhanced(); - //if (Enhanced > UnityEngine.Random.value) - //{ - // progress += progress; - //} - int _progress; - bool isMax = requiredCount <= (ETDropAfterDropDic.TryGetValue(collectingTargetInitTokenID, out _progress) ? _progress : 0); - GContext.Publish(new TargetAddData(collectingTargetInitTokenID, GetCurCollectingTarget(), progress)); - ETDropAfterDropDic[collectingTargetInitTokenID] += progress; - targetItemDatas = null; - if (!isMax && requiredCount <= (ETDropAfterDropDic.TryGetValue(collectingTargetInitTokenID, out _progress) ? _progress : 0)) - { - List dropIDs = new List(); - preCollectingTarget = new Queue(); - SetNextCollectingTarget(dropIDs); - var fishingStage = GContext.container.ResolveStage("FishingStage") as FishingStage; - if (fishingStage != null) - { - fishingStage.IsNextQueue = true; - fishingStage.NextQueueKey = NextQueueKey; - } - PlayerItemData playerItemData = GContext.container.Resolve(); - ChangeSource changeSource = new ChangeSource(ETDropAfterDropDic[0], "Event_CollectingTarget", "Event_CollectingTarget", "TaskReward"); - - targetItemDatas = playerItemData.AddItemByDropListLureInflation(CollectingTargetInflation, dropIDs, changeSource); - if (fishingStage != null) - { - fishingStage.IsNextQueue = false; - fishingStage.NextQueueKey = string.Empty; - } - //时间不同 特殊处理 - GContext.Publish(new TargetEvent(collectingTargetInitTaskID, 3, 2)); - } -#if AGG - using (var e = GEvent.GameEvent("target_event")) - { - e.AddContent("event_no", collectingTargetInitTaskID) - .AddContent("reward_info", progress) - .AddContent("group_index", ETDropAfterDropDic.GetValueOrDefault(-5)) - .AddContent("range_no", collectingTarget.TaskID); - if (targetItemDatas != null) - { - int reward_hook = 0; - int hook_origin = 0; - int reward_cash = 0; - for (int i = 0; i < targetItemDatas.Count; i++) - { - if (targetItemDatas[i].id == 1001) - { - reward_hook += targetItemDatas[i].count; - hook_origin += targetItemDatas[i].origin; - } - else if (targetItemDatas[i].id == 1002) - { - reward_cash += targetItemDatas[i].count; - } - } - e.AddContent("reward_hook", reward_hook) - .AddContent("hook_origin", hook_origin) - .AddContent("reward_cash", reward_cash); - } - } -#endif - SaveCollectingTargetEvent(); - } - } - void SetNextCollectingTarget(List dropIDs) - { - //掉落奖励 - dropIDs.Add(collectingTarget.DropID); // GContext.container.Resolve().GetItemDataByDropId(collectingTarget.DropID); - preCollectingTarget.Enqueue(collectingTarget); - if (collectingTarget.NextTarget <= 0) - { - return; - } - collectingTarget = _tables.TbCollectingTargetReward.GetOrDefault(collectingTarget.NextTarget); - requiredCount += collectingTarget.TokenRequiredB; - if (requiredCount <= ETDropAfterDropDic[collectingTargetInitTokenID]) - { - SetNextCollectingTarget(dropIDs); - } - } - - public int GetAllCollectingTarget() - { - if (collectingTarget != null) - { - return GetEtDropAfterDropDic(collectingTargetInitTokenID); - } - return 0; - } - public int GetCurCollectingTarget() - { - if (collectingTarget != null) - { - int startNum = 0; - int id = TargetList[0]; - CollectingTargetReward localcollectingTarget = _tables.TbCollectingTargetReward.GetOrDefault(id); - if (collectingTarget.TaskID != id) - { - startNum += localcollectingTarget.TokenRequiredB; - ETDropAfterDropDic.TryGetValue(collectingTargetInitTokenID, out var progress); - while (localcollectingTarget != null && startNum <= progress) - { - localcollectingTarget = _tables.TbCollectingTargetReward.GetOrDefault(localcollectingTarget.NextTarget); - if (localcollectingTarget.NextTarget <= 0) - { - if (localcollectingTarget.NextTarget == 0) - { - Debug.LogError("CollectingTargetReward NextTarget == 0"); - } - break; - } - startNum += localcollectingTarget.TokenRequiredB; - if (startNum > progress) - { - startNum -= localcollectingTarget.TokenRequiredB; - break; - } - } - } - return GetAllCollectingTarget() - startNum; - } - return 0; - } - public void AddCollectingTarget(int id, int progress) - { - int idOffset = _mmtService.GetEventTargetIDOffset(); - if (collectingTarget == null || (id != collectingTargetInitTaskID && id + idOffset != collectingTargetInitTaskID)) - { - return; - } - AddCollectingTarget(progress); - } - public void GetRankData() - { - if (IsOpenRank()) - { - _ = GContext.container.Resolve().GetLeaderboard(RankTargetCount[rankInit.TokenID]); - } - if (GContext.container.Resolve().IsOpenleaderboard) - { - //GContext.container.Resolve().SetLvData(); - - GContext.container.Resolve().GetLevelLeadboardData(); - GContext.container.Resolve().GetLevelLeadboardData(true); - } - } - public string RTSerialize() - { - if (RankTargetCount.Count > 0) - { - return RankTargetCount.Select(kv => kv.Key + ":" + kv.Value).Aggregate((a, b) => a + "," + b); - } - else - { - return ""; - } - } - public void RTDeserialize(string data) - { - if (!string.IsNullOrEmpty(data)) - { - RankTargetCount.Clear(); - var pairs = data.Split(','); - foreach (var pair in pairs) - { - var kv = pair.Split(':'); - if (kv.Length == 2 && int.TryParse(kv[0], out int key) && int.TryParse(kv[1], out int value)) - { - RankTargetCount[key] = value; - } - } - } - } - public void AddRankTarget(int progress) - { - if (rankInit != null) - { - preRankTarget = null; - if (!RankTargetCount.ContainsKey(rankInit.TokenID)) - { - RankTargetCount[rankInit.TokenID] = 0; - } - GContext.Publish(new TargetAddData(rankInit.TokenID, GetCurRankTarget(), progress)); - bool isMax = requiredRankCount <= RankTargetCount[rankInit.TokenID]; - RankTargetCount[rankInit.TokenID] += progress; - if (IsOpenRank()) - { - GContext.container.Resolve().UpdateScore(RankTargetCount[rankInit.TokenID]); - } - GContext.container.Resolve().SavePlayerData(); - //PlayFabMgr.Instance.UpdateUserDataValue("RankTargetCount", JsonMapper.ToJson(RankTargetCount)); - rankItemDatas = null; - if (!isMax && requiredRankCount <= RankTargetCount[rankInit.TokenID]) - { - List dropIDs = new List(); - preRankTarget = new List(); - //掉落奖励 - SetNextRankTarget(dropIDs); - ChangeSource changeSource = new ChangeSource(RankTargetCount[0], "Event_Rank", "Event_Rank", "TaskReward"); - rankItemDatas = GContext.container.Resolve().AddItemByDropListLureInflation(RankTargetInflation, dropIDs, changeSource); - } -#if AGG - using (var e = GEvent.GameEvent("rank_reward")) - { - e.AddContent("event_no", rankInit.ID) - .AddContent("reward_info", progress) - .AddContent("range_no", rankTarget.TaskID); - if (rankItemDatas != null) - { - int reward_hook = 0; - int hook_origin = 0; - int reward_cash = 0; - for (int i = 0; i < rankItemDatas.Count; i++) - { - if (rankItemDatas[i].id == 1001) - { - reward_hook += rankItemDatas[i].count; - hook_origin += rankItemDatas[i].origin; - } - else if (rankItemDatas[i].id == 1002) - { - reward_cash += rankItemDatas[i].count; - } - } - e.AddContent("reward_hook", reward_hook) - .AddContent("hook_origin", hook_origin) - .AddContent("reward_cash", reward_cash); - } - } -#endif - } - } - void SetNextRankTarget(List dropIDs) - { - preRankTarget.Add(rankTarget); - //掉落奖励 - dropIDs.Add(rankTarget.DropID); - - if (rankTarget.NextTarget <= 0) - { - return; - } - rankTarget = _tables.TbRankTargets.GetOrDefault(rankTarget.NextTarget); - requiredRankCount += rankTarget.TokenRequiredB; - if (requiredRankCount <= RankTargetCount[rankInit.TokenID]) - { - SetNextRankTarget(dropIDs); - } - } - public int GetAllRankTarget() - { - if (rankInit != null) - { - return RankTargetCount.TryGetValue(rankInit.TokenID, out int progress) ? progress : 0; - } - return 0; - } - public int GetCurRankTarget() - { - if (rankInit != null) - { - int startNum = 0; - int id = rankInit.TargetList[0]; - RankTargets localRankTarget = _tables.TbRankTargets.GetOrDefault(id); - - if (rankTarget.TaskID != id) - { - startNum += localRankTarget.TokenRequiredB; - RankTargetCount.TryGetValue(rankInit.TokenID, out int progress); - while (localRankTarget != null && startNum <= progress) - { - localRankTarget = _tables.TbRankTargets.GetOrDefault(localRankTarget.NextTarget); - if (localRankTarget.NextTarget <= 0) - { - if (localRankTarget.NextTarget == 0) - { - Debug.LogError("RankTargets NextTarget == 0"); - } - break; - } - startNum += localRankTarget.TokenRequiredB; - if (startNum > progress) - { - startNum -= localRankTarget.TokenRequiredB; - break; - } - } - } - return GetAllRankTarget() - startNum; - } - return 0; - } - public void AddRankTarget(int id, int progress) - { - if (rankTarget == null || id != rankInit.ID) - { - return; - } - AddRankTarget(progress); - } - /// - /// 目标奖励活动相关 - /// - /// 0==eventID - /// - public int GetEtDropAfterDropDic(int id) - { - return ETDropAfterDropDic.TryGetValue(id, out int progress) ? progress : 0; - } - public List GetIndexOfCollectingTargetHook() - { - int index = ETDropAfterDropDic.GetValueOrDefault(-5); - if (index >= collectingTargetInit.TargetList.Count) - { - Debug.LogError("TargetList.Count"); - return collectingTargetInit.TargetList[0]; - } - return collectingTargetInit.TargetList[index]; - } - public float CollectingTargetInflation - { - get - { - return GetEtDropAfterDropDic(-4) / 100f; - } - } - public int GetWheelLevelCount(int id) - { - return WheelLevelCount.TryGetValue(id, out int progress) ? progress : 0; - } - public DateTime GetCollectingTargetEndTime() - { - DateTime endTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - if (NewPlayerEvent > endTime) - { - return NewPlayerEvent; - } - return GetEventEndTime(collectingTargetEventID); - } - /// - /// 统一计算 固定时间段时间计算 真实时间和配置时间全加偏移(其他配置是偏移后的时间) - /// 计算的时候要使用 ZZTimeHelper.UtcNow()).UtcNowOffset() 时间 - /// 也可以自己写代码计算结束时间 - /// - /// - /// - public DateTime GetEventEndTime(int eventId) - { - FishingEvent fishingEvent = _tables.TbFishingEvent.GetOrDefault(eventId); - DateTime endTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - if (fishingEvent == null) - { - Debug.LogError($"FishingEvent not found for ID: {eventId}"); - return endTime; - } - if (fishingEvent.TimeDefinition is LimitedTime) - { - //统一计算 固定时间段时间计算 真实时间和配置时间全加偏移(其他配置是偏移后的时间) - LimitedTime limitedTime = (LimitedTime)fishingEvent.TimeDefinition; - endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()).UtcNowOffset(); - } - else if (fishingEvent.TimeDefinition is FixedTime) - { - if (fixedTimeEventDic.TryGetValue(fishingEvent.ID, out FixedTimeEvent fixedTimeEvent)) - { - endTime = GlobalUtils.TryParseDateTime(fixedTimeEvent.endTime, ZZTimeHelper.UtcNow().UtcNowOffset()); - } - } - else if (fishingEvent.TimeDefinition is Weekly) - { - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset().Date; - Weekly weekly = (Weekly)fishingEvent.TimeDefinition; - int offfset = (int)dateTime.DayOfWeek - weekly.StartTime; - - if (offfset < 0) - { - offfset = -offfset; - } - else - { - offfset = 7 - offfset; - } - endTime = dateTime.AddDays(offfset); - //endTime = GlobalUtils.TryParseDateTime(time, ZZTimeHelper.UtcNow().UtcNowOffset()); - } - else if (fishingEvent.TimeDefinition is UserRegistration) - { - UserRegistration userRegistrationEvent = (UserRegistration)fishingEvent.TimeDefinition; - endTime = GContext.container.Resolve().CreateTime.AddSeconds(userRegistrationEvent.EndTime).UtcNowOffset(); - } - - if (limitedTimeEventDic.TryGetValue(fishingEvent.ID, out LimitedTimeEvent limitedTimeEvent)) - { - LimitedTime limitedTime = (LimitedTime)fishingEvent.TimeDefinition; - var timer = ZZTimeHelper.UtcNow(); - endTime = GlobalUtils.TryParseDateTime(limitedTimeEvent.startTime, timer.UtcNowOffset()) - .Add((GlobalUtils.TryParseDateTime(limitedTime.EndTime, timer) - GlobalUtils.TryParseDateTime(limitedTime.StartTime, timer))); - } - return endTime; - } - //获取掉落的挂件 - public EventTargetExtraDrop GetEventTargetExtraDrop() - { - if (collectingTargetInit != null) - { - return collectingTargetInit.FishingExtraDrop; - } - - return null; - } - - #endregion - #region 排行榜事件 - int requiredRankCount = 0; - void InitRankTarget() - { - if (!RankTargetCount.ContainsKey(0)) - { - RankTargetCount[0] = 0; - } - if (rankInit != null && rankInit.TargetList.Count > 0) - { - rankTarget = _tables.TbRankTargets.GetOrDefault(rankInit.TargetList[0]); - requiredRankCount = rankTarget.TokenRequiredB; - if (rankTarget != null && rankEvent.ID == RankTargetCount[0]) - { - RankTargetCount.TryGetValue(rankInit.TokenID, out int progress); - while (rankTarget != null && rankTarget.NextTarget > 0 && requiredRankCount <= progress) - { - rankTarget = _tables.TbRankTargets.GetOrDefault(rankTarget.NextTarget); - requiredRankCount += rankTarget.TokenRequiredB; - RankTargetCount.TryGetValue(rankInit.TokenID, out progress); - } - } - else - { - RankTargetCount.Clear(); - RankTargetCount[0] = rankEvent.ID; - RankTargetCount[-4] = (int)(GContext.container.Resolve().InflationRate * 100); - } - if (!RankTargetCount.ContainsKey(rankInit.TokenID)) - { - RankTargetCount[rankInit.TokenID] = 0; - } - LeadboardData leadboardData = GContext.container.Resolve(); - if (IsOpenRank()) - { - leadboardData.UpdateScore(RankTargetCount[rankInit.TokenID]); - } - else - { - leadboardData.rankTarget = null; - leadboardData.GetRewards(); - } - } - else - rankTarget = null; - } - public float RankTargetInflation - { - get - { - return (RankTargetCount.TryGetValue(-4, out int progress) ? progress : 0) / 100f; - } - } - public DateTime GetRankEndTime() - { - return GetEventEndTime(rankEvent.ID); - } - public bool IsOpenRank() - { - return (rankTarget != null && rankInit != null && GetAllRankTarget() >= rankInit.UnlockPoint); - } - #endregion - #region 转盘事件 - void InitWheelLevel() - { - if (wheelInit != null) - { - if (WheelLevelCount[0] != turntableEvent.ID) - { - int welcome = GetInitWelcomeGift(turntableEvent.ID); - if (WheelLevelCount[0] != 0 || TurntableCoupon < welcome) - { - //不是第一次开启,代币归零 - TurntableCoupon = welcome; - } - - SaveTransitionData(turntableEvent.ID, TurntableCoupon); - WheelLevelCount.Clear(); - WheelLevelCount[0] = turntableEvent.ID; - WheelLevelCount[-2] = 0; - freecount = 0; - wheelLevel = _tables.TbWheelLevel.DataList[0]; - UpdateTurnTableData(); - } - else - { - int currentKey = WheelLevelCount.Keys.Max(); - currentKey = currentKey < 1 ? 1 : currentKey; - wheelLevel = _tables.TbWheelLevel.GetOrDefault(currentKey); - } - - if (wheelLevel != null) - { - TurntableRed(); - } - } - } - - public void UpdateTurnTableData() - { - playerSaveStore.Write("WheelLevelCount", JsonMapper.ToJson(WheelLevelCount)).RequireAccepted(); - playerSaveStore.Write("WheelLevelFreeCount", freecount.ToString()).RequireAccepted(); - } - /// - /// Add item by dropId and multiplier, or just return that item without giving to player, if doAdd is false. - /// - /// Drop ID. - /// Multiplier of item. - /// If true, items will actually be given to player. Otherwise, just resolve item. - /// Item resolved. Potentially given to player, if doAdd is true. - public ItemData UpdateWheel(int dropId, int magnification, bool doAdd = true) - { - ItemData itemData = GContext.container.Resolve().GetItemDataOne(dropId); - itemData.count *= magnification; - if (doAdd) - GContext.container.Resolve().AddItem(itemData, null); - return itemData; - } - public void AddIncreaseScore(int score, int multiplier) - { - IncreaseScore(score * multiplier); - WheelOperateCount++; - playerSaveStore.Write("WheelOperateCount", WheelOperateCount.ToString()).RequireAccepted(); - AllWheelOperateCount += multiplier; - - playerSaveStore.Write("AllWheelOperateCount", AllWheelOperateCount.ToString()).RequireAccepted(); - } - public void IncreaseScore(int score) - { - // 获取当前转盘等级和积分进度 - int progress = GetWheelLevelCount(wheelLevel.Level); - - // 增加对应积分 - progress += score; - WheelLevelCount[wheelLevel.Level] = progress; - // 检查是否需要升级 - if (progress >= wheelLevel.NextLevelPoint) - { - IncreaseWheelLevel(); - } - else - { - playerSaveStore.Write("WheelLevelCount", JsonMapper.ToJson(WheelLevelCount)).RequireAccepted(); - } - - } - public void AddFreecount(int count) - { -#if AGG - if (count < 0) - { - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", 6002) - .AddContent("state_info", "cost") - .AddContent("change_num", count); - } - } -#endif - freecount += count; - if (freecount < 0) - { - freecount = 0; - } - playerSaveStore.Write("WheelLevelFreeCount", freecount.ToString()).RequireAccepted(); - } - //转盘等级增加函数 - public void IncreaseWheelLevel() - { - if (wheelLevel != null) - { - int progress = GetWheelLevelCount(wheelLevel.Level); - int requiredPoints = wheelLevel.NextLevelPoint; - // 循环检查是否需要升级到多个未来等级 - while (wheelLevel.NextLevel > 0 && wheelLevel.NextLevel != wheelLevel.Level && progress >= requiredPoints && requiredPoints != -1) - { - WheelLevelCount[wheelLevel.Level] = wheelLevel.NextLevelPoint; - wheelLevel = _tables.TbWheelLevel.GetOrDefault(wheelLevel.NextLevel); - progress -= requiredPoints; - requiredPoints = wheelLevel.NextLevelPoint; - } - // 更新积分进度 - WheelLevelCount[wheelLevel.Level] = progress; - TurntableRed(); - playerSaveStore.Write("WheelLevelCount", JsonMapper.ToJson(WheelLevelCount)).RequireAccepted(); - } - } - - public DateTime GetTurntableEndTime() - { - return GetEventEndTime(turntableEvent.ID); - } - - public bool IsShowTurntable() - { - if (turntableEvent == null) - { - return false; - } - var endTime = DateTime.Parse((turntableEvent.TimeDefinition as LimitedTime).EndTime); - var startTime = DateTime.Parse((turntableEvent.TimeDefinition as LimitedTime).StartTime); - var dateTime = ZZTimeHelper.UtcNow(); - return wheelLevel != null - && endTime > dateTime - && startTime <= dateTime; - } - - #endregion - #region 事件驱动礼包 eventPack - //private bool - private void SetEventPackData(FishingEvent t) - { - //Debug.Log("I tried."); - int packType = _tables.TbEventPackManager[t.RedirectID].PackType; - switch (packType) - { - case 1: ActivateThreeChoseOnePack(t); break; - case 2: ActivatePiggyBankPack(t); break; - case 3: ActiavteBargainPack(t); break; - case 6: - SetPack1A1(t); - break; - //case 7: - // SetPack1A2(t); - // break; - default: Debug.Log($"Pack Type {packType} of event {t.ID} unrecognized."); break; - } - - } - private void ActivateThreeChoseOnePack(FishingEvent t) - { - var eventPackDataSaved = GContext.container.Resolve();//pack data to be saved to remote server - var eventPackDataRead = GContext.container.Resolve() - .TbEventPackManager.DataMap[t.RedirectID];//pack data read from tables - bool eventUpdated = eventPackDataSaved.UpdateEventData(t);//event is updated only when event changed or user login - if (eventPackDataSaved.PurchaseCount < eventPackDataRead.MaxCount && eventUpdated) - //TODO:change panel according to RedirecctID of current event - GContext.container.Resolve().AddGiftFaceUI(t.ID, UITypes.GiftPopupPanel_9, eventPackDataRead.PackType); - } - private void ActivatePiggyBankPack(FishingEvent t) - { - var eventPackDataSaved = GContext.container.Resolve();//pack data to be saved to remote server - //var eventPackDataRead = GContext.container.Resolve() - // .TbEventPackManager.DataMap[t.RedirectID];//pack data read from tables - eventPackDataSaved.UpdateData(t);//event is updated only when event changed or user login - } - private void ActiavteBargainPack(FishingEvent t) - { - var eventPackDataSaved = GContext.container.Resolve();//pack data to be saved to remote server - //var eventPackDataRead = GContext.container.Resolve() - // .TbEventPackManager.DataMap[t.RedirectID];//pack data read from tables - eventPackDataSaved.UpdateData(t);//event is updated only when event changed or user login - } - #endregion - - - #region 获取事件礼包关于钓鱼的数据 - public int curActivateItemId { get; set; } - public int GetActivateItemId() - { - float BasicProb = UnityEngine.Random.Range(0, 1f); - if (BasicProb <= _tables.TbGlobalConfig.CommercialFishParam) - { - try - { - PiggyBankPackData piggyBankPackData = GContext.container.Resolve(); - if (piggyBankPackData.DoNeedUpdate && piggyBankPackData.IsWithinEventTime) - { - return piggyBankPackData.ActivateItemId; - } - BargainPackData barginPackData = GContext.container.Resolve(); - if (barginPackData.DoNeedTrigger && barginPackData.IsWithinEventTime) - { - return barginPackData.ActivateItemId; - } - } - catch (Exception e) - { - Debug.LogError($"GetActivateItemId Error: {e.Message}"); - return 0; - } - } - return 0; - } - - public void AddProgress(int fishTier, int magnification) - { - PiggyBankPackData piggyBankPackData = GContext.container.Resolve(); - if (piggyBankPackData != null) - { - piggyBankPackData.AddProgress(fishTier, magnification); - } - BargainPackData barginPackData = GContext.container.Resolve(); - if (barginPackData != null) - { - barginPackData.AddProgress(fishTier, magnification); - } - } - #endregion - public void Dispose() - { - disposable?.Dispose(); - disposable = null; - } - - #region 活动代币转换(委托给 EventTokenService,避免双写数据不同步) - public Dictionary curTransitionData { get; private set; } = new Dictionary(); - public void SaveTransitionData(int eventId, int count) - { - if (eventId > 0) - { - TokenService.SetToken(eventId, count); - } - } - public int GetTransitionDataCount(int eventId) - { - return TokenService.GetTokenCount(eventId); - } - void InitTransitionDataDic() - { - GetTransitionData(); - } - int EVENT_END_TIME_EXTEND_DAYS = 9; - void GetTransitionData() - { - var allTokens = TokenService.GetAllTokens(); - if (allTokens != null && allTokens.Count > 0) - { - List removeKeys = new List(); - foreach (var item in allTokens) - { - FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(item.Key); - if (fe != null && (fe.Type == 4 || fe.Type == 8 || fe.Type == 7 || fe.Type == 15) && !Condition(fe)) - { - int count = item.Value; - if (count <= 0) - { - removeKeys.Add(item.Key); - continue; - } - var timeDefinition = fe.TimeDefinition; - if (timeDefinition is LimitedTime limitedTime) - { - DateTime endTime = DateTime.Parse(limitedTime.EndTime).AddDays(EVENT_END_TIME_EXTEND_DAYS); - if (endTime < ZZTimeHelper.UtcNow()) - { - removeKeys.Add(item.Key); - continue; - } - } - FishingEventCycleItem cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fe.RedirectID); - if (cycle == null) - { - removeKeys.Add(item.Key); - continue; - } - SetTransitionData(fe.ID, cycle.EventName_l10n_key, cycle.ItemId, cycle.EventEndSettlement); - } - } - if (removeKeys.Count > 0) - { - Debug.Log($"GetTransitionData removeKeys Count:{removeKeys.Count} IDs {string.Join(',', removeKeys)}"); - for (int i = 0; i < removeKeys.Count; i++) - { - Debug.Log($"GetTransitionData removeKeys :{removeKeys[i]} count : {allTokens.GetValueOrDefault(removeKeys[i], 0)}"); - } - TokenService.ClearTokens(removeKeys); - } - } - } - - void SetTransitionData(int eventID, string eventName, int itemId, List EventEndSettlement) - { - TransitionData transitionData = new TransitionData(); - - int sourceCount = TokenService.GetTokenCount(eventID); - transitionData.eventID = eventID; - transitionData.eventName = eventName; - transitionData.sourceItemID = itemId; - transitionData.sourceCount = sourceCount; - transitionData.targetItemID = EventEndSettlement[0]; - int targetCount = sourceCount * EventEndSettlement[1]; - if (transitionData.targetItemID == 1002) - { - targetCount = GContext.container.Resolve().GetExtraCoinMag(targetCount); - } - if (targetCount < 0) - { - targetCount = int.MaxValue; - Debug.LogError($"TransitionData targetCount overflow {eventID} {itemId} {transitionData.sourceCount} {EventEndSettlement[1]}"); - } - transitionData.targetCount = targetCount; - curTransitionData[eventID] = transitionData; - GContext.container.Resolve().AddFaceCustomUIData(UITypes.EventConvertedPopupPanel, true); - - } - public void ClearTransitionData(TransitionData transitionData) - { - curTransitionData.Remove(transitionData.eventID); - if (TokenService.GetTokenCount(transitionData.eventID) > 0) - { -#if AGG - using (var e = GEvent.GameEvent("cycle_item_redemption")) - { - e.AddContent("event_id", transitionData.eventID) - .AddContent("charge_count", GContext.container.Resolve().GetBuyPaymentAmount()) - .AddContent("item_id", transitionData.sourceItemID) - .AddContent("item_count", transitionData.sourceCount) - .AddContent("change_item", transitionData.targetItemID) - .AddContent("change_count", transitionData.targetCount); - } -#endif - TokenService.ClearToken(transitionData.eventID); - } - } - public int GetInitWelcomeGift(int eventID) - { - int welcomeGift = 0; - if (eventID > 0) - { - FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(eventID); - if (fe != null) - { - FishingEventCycleItem cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fe.RedirectID); - if (cycle != null) - { - welcomeGift = cycle.WelcomeGift; - } - } - } - return welcomeGift; - } - - #endregion 代币转换 - - #region 事件礼包补单 - - public void OnBuyEventPack(int eventID) - { - FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(eventID); - if (fe != null && fe.TimeDefinition is LimitedTime && - (DateTime.Parse((fe.TimeDefinition as LimitedTime).EndTime) - ZZTimeHelper.UtcNow()).TotalSeconds > 1) - { - if (fe.Type == 3) - { - if (fe.SubType == 8 || fe.SubType == 11) - { - int packType = _tables.TbEventPackManager[fe.RedirectID].PackType; - switch (packType) - { - case 1: - GContext.container.Resolve().AddPurchaceCount(); - break; - case 2: - GContext.container.Resolve().AddPurchase(); - break; - case 3: - GContext.container.Resolve().AddPurchase(); - break; - case 6: - SetPack1A1Index(1); - break; - } - } - else if (fe.SubType == 10) - { - GContext.container.Resolve().AddOpenChainGifIndex(); - } - } - else if (fe.Type == 4) - { - ChainPackWithProgressMigrationData.OnBuySuccess(); - } - else if (fe.Type == 6) - { - if (fe.SubType == 1) - { - SetPack1A2Index(); - RedPointManager.Instance.SetRedPointState(HomeBtnOneTwoPack.redKey, false); - } - else if (fe.SubType == 2) - { - ThanksGivingPackData.OnBuySuccess(); - } - } - else if (fe.Type == 7) - { - switch (fe.SubType) - { - case 1: - var shootingPackData = GContext.container.Resolve(); - if (!shootingPackData.IsChainPackDepleted) - shootingPackData.OnBuySuccess(); - break; - case 2: - var breakPackData = GContext.container.Resolve().ToChainPackData(); - if (!breakPackData.IsChainPackDepleted) - breakPackData.OnBuySuccess(); - break; - case 3: - var ScratchTicketData = GContext.container.Resolve().GetChainPackData(); - if (ScratchTicketData != null && !ScratchTicketData.IsChainPackDepleted) - ScratchTicketData.OnBuySuccess(); - break; - case 4: - var chainPackData = GContext.container.Resolve(); - if (chainPackData != null && !chainPackData.IsChainPackDepleted) - chainPackData.OnBuySuccess(); - break; - case 5: - var gatherCoreData = GContext.container.Resolve(); - if (gatherCoreData != null) - { - var gatherCoreChainData = gatherCoreData.ToChainPackData(); - if (gatherCoreChainData?.IsChainPackDepleted == false) - gatherCoreChainData.OnBuySuccess(); - } - break; - case 6: - GContext.container.Resolve()?.AddChainPackProgress(); - break; - } - } - else if (fe.Type == 8) - { - switch (fe.SubType) - { - case 3: - var luckMagicChainPackData = GContext.container.Resolve().ToChainPackData(); - if (luckMagicChainPackData != null && !luckMagicChainPackData.IsChainPackDepleted) - luckMagicChainPackData.OnBuySuccess(); - break; - } - } - else if (fe.Type == 9) - { - switch (fe.SubType) - { - case 4: - var actManager = GContext.container.Resolve(); - actManager?.OnBuySuccess(); - break; - case 5: - var EventOfferJourneyData = GContext.container.Resolve(); - EventOfferJourneyData?.OnBuySuccess(); - break; - case 7: - GContext.container.Resolve()?.OnBuySuccess(); - break; - case 9: - GContext.container.Resolve()?.MoveToNextSlotAndTryGrantFinalReward(); - break; - case 11: - GContext.container.Resolve()?.OnBuySuccess(); - break; - } - } - - GContext.Publish(new TargetEvent(fe.ID, fe.Type, fe.SubType)); - } - } - - #endregion 事件礼包补单 - - void SetEvent15(FishingEvent t) - { - if (t.Type != 15) - return; - switch (t.SubType) - { - case 1: - InitPartnerGatherData(t); - break; - case 2: - - EventPartnerStatueArc.Load(t); - var arc = GContext.container.Resolve(); - EventPartnerStatueArc.EnsureTokenExchangeContextRegistered(arc); - EventPartnerStatueTokenExchangeData.Load(t); - break; - } - } - - int RedirectType(int type, int subType) - { - return type * 1000 + subType; - } - } - -} -public struct TransitionData -{ - public int eventID; - public string eventName; - public int sourceItemID; - public int sourceCount; - public int targetItemID; - public int targetCount; -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/009-DataCenter.GuideData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/009-DataCenter.GuideData.cs.txt deleted file mode 100644 index 5faa34d71..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/009-DataCenter.GuideData.cs.txt +++ /dev/null @@ -1,740 +0,0 @@ -using asap.core; -using cfg; -using game; -using LitJson; -using System; -using System.Collections.Generic; -using System.Linq; -using tysdk; -using UniRx; -using UnityEngine; -using UnityEngine.AddressableAssets; - -namespace GameCore -{ - public class GuideNextEvent - { - - } - public class AddIndexEvent - { - public bool CompleteGuide; - public int guideSubIndex; - public bool isAutoNext; - } - /// - /// 废弃 - /// - public struct OnEventTriggerGuide - { - public OnEventTriggerGuide(string panelName) - { - this.panelName = panelName; - } - public string panelName; - } - public class GuideSaveData - { - public int guideSubIndex = 0; - public bool isFinish = false; - public string groupName; - } - public class GuideDataCenter : IDisposable - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - Tables _tables; - PlayerData playerData; - public GuideDataCenter(cfg.Tables tables, PlayerData playerData) - { - this._tables = tables; - this.playerData = playerData; - } - public string CurPanelName; - public Dictionary GuideSaveDataDic = new Dictionary(); - public GuideSaveData curSaveData; - public GuidanceGroupDefine[] guidanceGroupDefines; - public GuidanceDefine curDefine; - public string popupPanelNode; - public GuidanceGroupDefine curGroupDefine; - public GuidanceDefineSetting guidanceDefineSetting; - - internal static game.PlayerDataStorage.PlayerKVGuideState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeGuides(raw,errors); - internal void ResetForKVLoad() - { - GuideSaveDataDic = new Dictionary(StringComparer.Ordinal); - curSaveData = null; curDefine = null; curGroupDefine = null; popupPanelNode = null; CurPanelName = null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVGuideState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - GuideSaveDataDic = state.Values.ToDictionary(p=>p.Key, - p=>new GuideSaveData { guideSubIndex=p.Value.Index, isFinish=p.Value.Finished, groupName=p.Value.Group },StringComparer.Ordinal); - } - //待释放 - IDisposable disposable; - IDisposable disposable2; - IDisposable disposable3; - - public void GMClearGuide() - { - foreach (var item in guidanceGroupDefines) - { - if (!GuideSaveDataDic.TryGetValue(item.groupName.ToString(), out GuideSaveData _saveData)) - { - _saveData = new GuideSaveData(); - _saveData.groupName = item.groupName.ToString(); - GuideSaveDataDic.Add(item.groupName.ToString(), _saveData); - } - _saveData.isFinish = true; - } - GContext.Publish(new ConditionTypeEvent(ConditionType.CompleteGuide, 0)); - curDefine = null; - curGroupDefine = null; - Save(); - } - public async void Init() - { - var store = playerSaveStore; - var setting = (GuidanceDefineSetting)await Addressables.LoadAssetAsync("GuidanceConfig"); - if (disposed || !store.IsCurrent) return; - guidanceDefineSetting = setting; - if (guidanceDefineSetting != null) - { - bool isUpdate = false; - guidanceGroupDefines = guidanceDefineSetting.guidanceGroupDefines; - List Skip = guidanceDefineSetting.SkipGroupNames; - bool isSkip = playerData.lv >= guidanceDefineSetting.SkipLevel; - if (GuideSaveDataDic == null) - { - GuideSaveDataDic = new Dictionary(); - } - else - { - GuideSaveData _saveData; - GuidanceDefine _define; - Dictionary keyValuePairs = new Dictionary(); - foreach (var item in guidanceGroupDefines) - { - - if (GuideSaveDataDic.TryGetValue(item.groupName.ToString(), out _saveData)) - { -#if UNITY_EDITOR && !SERVICE_HOST - if (DeferUnavailablePotionGuide(item, _saveData)) - { - keyValuePairs[item.groupName.ToString()] = _saveData; - continue; - } -#endif - if (!_saveData.isFinish && _saveData.guideSubIndex > 0) - { - for (int i = _saveData.guideSubIndex; i < item.guidanceDefines.Length; i++) - { - _define = item.guidanceDefines[i]; - if (_define.isKey) - { - _saveData.guideSubIndex = _define.JumpIndex; - if (_saveData.guideSubIndex < item.guidanceDefines.Length) - { - _saveData.isFinish = false; - curSaveData = _saveData; - curGroupDefine = item; - curDefine = curGroupDefine.guidanceDefines[_saveData.guideSubIndex]; - } - else - { - _saveData.isFinish = true; - GContext.Publish(new ConditionTypeEvent(ConditionType.CompleteGuide, 1)); - } - break; - } - else - { - _saveData.isFinish = true; - } - } - isUpdate = true; - } - keyValuePairs[item.groupName.ToString()] = _saveData; - } - else if (isSkip && Skip.Contains(item.groupName)) - { - _saveData = new GuideSaveData(); - _saveData.groupName = item.groupName.ToString(); - _saveData.isFinish = true; - keyValuePairs[item.groupName.ToString()] = _saveData; - isUpdate = true; - } - } - GuideSaveDataDic = keyValuePairs; - if (isUpdate) - { - Save(); - } - } - if (disposable2 == null) - { - disposable2 = GContext.OnEvent().Subscribe(TriggerGuideNext); - } - } - } -#if UNITY_EDITOR && !SERVICE_HOST - private static bool DeferUnavailablePotionGuide(GuidanceGroupDefine group, GuideSaveData saved) - { - if (!game.PlayerDataStorage.PlayerKVGameplayLoop.Enabled || !game.PlayerDataStorage.PlayerKVGameplayLoop.Ready || - group.groupName != GroupName.EventPotion01 || saved == null || saved.isFinish || saved.guideSubIndex <= 0 || - group.guidanceDefines == null || saved.guideSubIndex >= group.guidanceDefines.Length || - group.guidanceDefines[saved.guideSubIndex] == null || - group.guidanceDefines[saved.guideSubIndex].panelName != "EventPotionPanel") - return false; - try - { - // Existing potion activity classification; availability query does not initialize activity data. - const int potionEventType = 4; - const int potionEventSubType = 5; - return GContext.container.Resolve().GetEvent(potionEventType, potionEventSubType) == -1; - } - catch (Exception ex) - { - Debug.LogWarning("Potion guide availability query failed; retaining original guide recovery: " + ex); - return false; - } - } -#endif - public bool GetIsFinish(string groupName) - { - return GuideSaveDataDic.ContainsKey(groupName) && GuideSaveDataDic[groupName].isFinish; - } - public bool InspectTriggerGuide(string panelName, string prePanelName = "", string curPanelName = "") - { - if (prePanelName.Contains("FishingRodPanel")) - { - return false; - } - if (guidanceDefineSetting == null) - { - return false; - } - if (curGroupDefine != null - && GuideSaveDataDic.TryGetValue(curGroupDefine.groupName.ToString(), out var guideSaveData) - //&& !guideSaveData.isFinish - && curGroupDefine.guidanceDefines.Length > guideSaveData.guideSubIndex - && panelName == curGroupDefine.guidanceDefines[guideSaveData.guideSubIndex].panelName) - { - CurPanelName = curPanelName; - TriggerGuideNext(new OnEventTriggerGuide(panelName)); - return true; - } - PlayerFishData playerFishData = GContext.container.Resolve(); - GuidanceGroupDefine guidanceGroupDefine; - for (int i = 0; i < guidanceGroupDefines.Length; i++) - { - guidanceGroupDefine = guidanceGroupDefines[i]; - - bool isFinish = GetIsFinish(guidanceGroupDefine.groupName.ToString()); - if (isFinish || panelName != guidanceGroupDefine.guidanceDefines[0].panelName) - { - continue; - } - - if (CheckTriggerGuideFinish(guidanceGroupDefine)) - { - continue; - } - - int count; - switch (guidanceGroupDefine.TriggerConditionsType) - { - case GuideTriggerConditions.Next: - break; - case GuideTriggerConditions.First_login: - break; - case GuideTriggerConditions.OpenSystem_Shop: - if (GContext.container.Resolve().IsShopOpen == false) - { - continue; - } - break; - //case GuideTriggerConditions.UnlockSystem_Album: - // if (GContext.container.Resolve().theme == null) - // { - // continue; - // } - // break; - case GuideTriggerConditions.Level_2: - if (playerData.lv >= 2) - { - break; - } - continue; - case GuideTriggerConditions.Group_Finish: - if (GuideSaveDataDic.TryGetValue(guidanceGroupDefine.TriggerConditionsParameter, out var _data) && _data.isFinish) - { - break; - } - continue; - case GuideTriggerConditions.GetDiffFishCount: - if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && playerFishData.GetDiffFishCount() >= count) - { - if (playerFishData.GetDiffFishCount() > count) - { - TriggerGuideFinish(guidanceGroupDefine); - continue; - } - break; - } - continue; - case GuideTriggerConditions.GetFishCount: - if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && playerFishData.GetAnglingCount() >= count) - { - if (playerFishData.GetAnglingCount() > count) - { - TriggerGuideFinish(guidanceGroupDefine); - continue; - } - break; - } - continue; - case GuideTriggerConditions.FirstClickMap_AtMap2: - if (playerData.lastMapId == _tables.TbMapData.DataList[1].ID) - { - break; - } - continue; - case GuideTriggerConditions.AccountLevel: - if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && playerData.lv >= count) - { - break; - } - continue; - case GuideTriggerConditions.UnlockSystem: - if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && GContext.container.Resolve().GetSystemOpen(count)) - { - break; - } - continue; - case GuideTriggerConditions.UnlockEvent: - string[] str = guidanceGroupDefine.TriggerConditionsParameter.Split('-'); - if (str.Length == 2) - { - if (int.TryParse(str[0], out count) && int.TryParse(str[1], out int count2) && GContext.container.Resolve().GetEvent(count, count2) > 0) - { - break; - } - } - else if (str.Length == 3) - { - if (int.TryParse(str[0], out count) && int.TryParse(str[1], out int count2) && int.TryParse(str[2], out int count3) && GContext.container.Resolve().GetEventRedirectID(count, count2) == count3) - { - - break; - } - } - //if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && GContext.container.Resolve().GetSystemOpen(count)) - //{ - // break; - //} - continue; - case GuideTriggerConditions.MaxMultiplierCount: - if (playerData.IsOpenMagnification && - int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && - playerData.ContainsOrGreaterRatio(count)) - { - break; - } - continue; - case GuideTriggerConditions.GetSecondRod: - if (!prePanelName.Contains("HomePanel") && playerFishData.IsOpenRod && playerFishData.GetRodAllCount() > 1) - { - break; - } - continue; - case GuideTriggerConditions.RodAscendAvailable: - if (!prePanelName.Contains("HomePanel") && playerFishData.IsOpenRod && playerFishData.GetRodCanUp()) - { - break; - } - continue; - case GuideTriggerConditions.RodUpgradeAvailable: - if (!prePanelName.Contains("HomePanel") && playerFishData.IsOpenRod && playerFishData.GetRodCanUpLevel()) - { - break; - } - continue; - case GuideTriggerConditions.BuyPack: - if (int.TryParse(guidanceGroupDefine.TriggerConditionsParameter, out count) && GContext.container.Resolve().GetAllPackCount(count) > 0) - { - break; - } - continue; - case GuideTriggerConditions.BoxOpenCondition: - FishingBoxDataProvier fishingBoxData = GContext.container.Resolve(); - if (fishingBoxData.IsUnclocked && fishingBoxData.GetBoxCount(fishingBoxData.GetIDByQuality(3)) > 0) - { - break; - } - continue; - case GuideTriggerConditions.GoBuilding: - if (GContext.container.Resolve().GoBuilding()) - { - break; - } - continue; - case GuideTriggerConditions.GoBuilding02: - if (playerData.lv >= 12) - { - TriggerGuideFinish(guidanceGroupDefine); - Debug.Log("TriggerGuideFinish(guidanceGroupDefine);"); - continue; - } - if (GContext.container.Resolve().GoBuilding02(101012)) - { - Debug.Log("TriggerGuideFinish();"); - break; - } - continue; - default: - continue; - } - - if (curGroupDefine == guidanceGroupDefine) - { - return false; - } - if (panelName == guidanceGroupDefine.guidanceDefines[0].panelName) - { - TriggerGuide(guidanceGroupDefine, curPanelName); - return true; - } - } - return false; - } - - public void MarkGuideFinished(GroupName groupName) - { - string key = groupName.ToString(); - if (GetIsFinish(key)) return; - if (!GuideSaveDataDic.TryGetValue(key, out var saveData)) - { - saveData = new GuideSaveData(); - saveData.groupName = key; - GuideSaveDataDic.Add(key, saveData); - } - saveData.isFinish = true; - Save(); - } - - public void ClearGuide(string groupName) - { - if (GuideSaveDataDic.ContainsKey(groupName)) - { - GuideSaveDataDic.Remove(groupName); - Save(); - } - } - - /// - /// 特殊屏蔽的新手引导 - /// - /// - bool CheckTriggerGuideFinish(GuidanceGroupDefine group) - { - bool isFinishPass = false; - //判断是否直接完成 - if (group.groupName == GroupName.Chanllenge) - { - // isFinishPass = !GContext.container.Resolve().IsFirstOpen; - isFinishPass = !GContext.container.Resolve().IsFirstOpen; - } - - if (isFinishPass) - { - TriggerGuideFinish(group); - } - return isFinishPass; - } - - void TriggerGuideFinish(GuidanceGroupDefine group) - { - string groupName = group.groupName.ToString(); - if (!GuideSaveDataDic.TryGetValue(groupName, out var guideSaveData)) - { - guideSaveData = new GuideSaveData(); - guideSaveData.groupName = groupName; - GuideSaveDataDic.Add(groupName, guideSaveData); - } - guideSaveData.guideSubIndex = group.guidanceDefines.Length; - guideSaveData.isFinish = true; - Save(); - } - public bool TriggerGuide(string groupName, string panelName, bool loop = true,string curPanelName = "") - { - if (guidanceDefineSetting == null) - { - return false; - } - GuidanceGroupDefine guidanceGroupDefine; - if (!loop) - { - bool isFinish = GetIsFinish(groupName.ToString()); - if (isFinish) - { - return false; - } - } - for (int i = 0; i < guidanceGroupDefines.Length; i++) - { - guidanceGroupDefine = guidanceGroupDefines[i]; - if (guidanceGroupDefine.groupName.ToString() == groupName) - { - if (panelName != guidanceGroupDefine.guidanceDefines[0].panelName) - { - return false; - } - TriggerGuide(groupName, curPanelName, guidanceGroupDefine); - return true; - } - } - return false; - } - async void TriggerGuide(string groupName, string curPanelName, GuidanceGroupDefine guidanceGroupDefine) - { - var store = playerSaveStore; - await System.Threading.Tasks.Task.Delay(200); - if (disposed || !store.IsCurrent) return; - curSaveData = new GuideSaveData(); - curSaveData.groupName = groupName; - GuideSaveDataDic[groupName] = curSaveData; - curGroupDefine = guidanceGroupDefine; - curDefine = curGroupDefine.guidanceDefines[0]; - ShowPanel(curPanelName); - curSaveData.guideSubIndex++; - } - void TriggerGuide(GuidanceGroupDefine group, string curPanelName) - { - string groupName = group.groupName.ToString(); - if (!GuideSaveDataDic.TryGetValue(groupName, out var guideSaveData)) - { - guideSaveData = new GuideSaveData(); - guideSaveData.groupName = groupName; - GuideSaveDataDic.Add(groupName, guideSaveData); - } - if (guideSaveData.isFinish) - { - return; - } - guideSaveData.guideSubIndex = 0; - curSaveData = guideSaveData; - - curGroupDefine = group; - curDefine = group.guidanceDefines[0]; - ShowPanel(curPanelName); - curSaveData.guideSubIndex++; - - } - public void TriggerGuideNext(OnEventTriggerGuide eventTriggerGuide) - { - if (curGroupDefine != null && GuideSaveDataDic.TryGetValue(curGroupDefine.groupName.ToString(), out var guideSaveData)) - { - if (curGroupDefine.guidanceDefines.Length <= curSaveData.guideSubIndex || eventTriggerGuide.panelName != curGroupDefine.guidanceDefines[guideSaveData.guideSubIndex].panelName) - { - return; - } - curDefine = curGroupDefine.guidanceDefines[guideSaveData.guideSubIndex]; - if (curDefine.completeType == CompleteType.PanelOpen) - { - string uIType = curDefine.completeTypeParameter; - if (!string.IsNullOrEmpty(uIType) && UIManager.Instance.ContainsUI(uIType)) - { - curSaveData.guideSubIndex++; - AddIndex(); - } - else - { - disposable = GContext.OnEvent().Subscribe(data => - { - if (uIType == data.uIType && data.show) - { - curSaveData.guideSubIndex++; - AddIndex(); - } - }); - - } - } - else - { - ShowPanel(CurPanelName); - curSaveData.guideSubIndex++; - } - } - else - { - InspectTriggerGuide(eventTriggerGuide.panelName); - } - } - public void AddIndex(bool is_pass = false) - { - if (curDefine == null) - { - return; - } - if (disposable != null) - { - disposable.Dispose(); - disposable = null; - } - if (disposable3 != null) - { - disposable3.Dispose(); - disposable3 = null; - } - UIManager.Instance.HideUI(UITypes.GuidancePanel); - bool isAutoNext = curDefine.isAutoNext; - AddIndexEvent addIndexEvent = new AddIndexEvent(); - addIndexEvent.isAutoNext = isAutoNext; - if (curGroupDefine.guidanceDefines.Length <= curSaveData.guideSubIndex || is_pass) - { -#if AGG - using (var e = GEvent.GameEvent("guide_complete")) - { - e.AddContent("guide_id", curGroupDefine.groupName.ToString()) - .AddContent("is_pass", is_pass); - } -#endif - string panelName = curDefine.panelName; - curDefine = null; - curGroupDefine = null; - curSaveData.isFinish = true; - Save(); - if (isAutoNext) - { - InspectTriggerGuide(panelName, panelName); - } - GContext.Publish(new ConditionTypeEvent(ConditionType.CompleteGuide, 1)); - addIndexEvent.CompleteGuide = true; - addIndexEvent.guideSubIndex = curSaveData.guideSubIndex; - GContext.Publish(addIndexEvent); - } - else - { - Save(); - var define = curGroupDefine.guidanceDefines[curSaveData.guideSubIndex]; - if (isAutoNext && define.panelName == curDefine.panelName) - { - curDefine = define; - ShowPanel(CurPanelName); - curSaveData.guideSubIndex++; - } - else if (!isAutoNext) - { - for (int i = curSaveData.guideSubIndex; i < curGroupDefine.guidanceDefines.Length; i++) - { - var _define = curGroupDefine.guidanceDefines[i]; - if (_define.isKey) - { - curSaveData.isFinish = false; - break; - } - else - { - curSaveData.isFinish = true; - } - } - } - addIndexEvent.guideSubIndex = curSaveData.guideSubIndex; - GContext.Publish(addIndexEvent); - } - } - async void ShowPanel(string PanelName) - { - if (disposed || !playerSaveStore.IsCurrent) return; - if (curDefine.fingerType != FingerType.None) - { - disposable3 = GContext.OnEvent().Subscribe(GuideNextEvent); - } - CurPanelName = PanelName; - await UIManager.Instance.ShowUI(UITypes.GuidancePanel); - } - - public async void ShowGuidancePopupPanel(string nodeName) - { - var store = playerSaveStore; - if (disposed || !store.IsCurrent) return; - popupPanelNode = nodeName; - if (!string.IsNullOrEmpty(popupPanelNode)) - { - await UIManager.Instance.ShowUI(UITypes.GuidancePopupPanel); - if (disposed || !store.IsCurrent) return; - UIManager.Instance.HideUI(UITypes.GuidancePanel); - } - } - - void GuideNextEvent(GuideNextEvent guideLongEvent) - { - if (curDefine != null && curDefine.fingerType != FingerType.None) - { - AddIndex(); - } - } - - public bool IsGuide(string panelName) - { - bool isGuide = curDefine != null; - if (!isGuide) - { - InspectTriggerGuide(panelName); - } - return curDefine != null && curDefine.panelName == panelName; - } - - public bool IsGuide(string panelName, int index, GroupName groupName) - { - bool isGuide = curDefine != null; - - if (isGuide && curGroupDefine.groupName == groupName && curSaveData.guideSubIndex == index) - { - InspectTriggerGuide(panelName); - return true; - } - return false;// curDefine != null && curDefine.panelName == panelName; - } - public void SetData(string value) - { - string[] groupStrings = value.Split(';'); - foreach (var groupString in groupStrings) - { - string[] strings = groupString.Split('|'); - if (strings.Length == 3) - { - GuideSaveData saveData = new GuideSaveData(); - saveData.groupName = strings[0]; - if (int.TryParse(strings[1], out int guideSubIndex)) - { - saveData.guideSubIndex = guideSubIndex; - } - saveData.isFinish = strings[2] == "1"; - GuideSaveDataDic[saveData.groupName] = saveData; - } - } - } - public void Save() - { - List strings = GuideSaveDataDic.Select(kv => kv.Key + "|" + kv.Value.guideSubIndex + "|" + (kv.Value.isFinish ? "1" : "0")).ToList(); - string value = string.Join(";", strings); - playerSaveStore.Write("GuideSaveDataNew", value).RequireAccepted(); - } - - bool disposed; - public void Dispose() - { - disposed = true; - disposable?.Dispose(); - disposable = null; - disposable2?.Dispose(); - disposable2 = null; - disposable3?.Dispose(); - disposable3 = null; - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/010-DataCenter.PlayerData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/010-DataCenter.PlayerData.cs.txt deleted file mode 100644 index aa92b6e2b..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/010-DataCenter.PlayerData.cs.txt +++ /dev/null @@ -1,1526 +0,0 @@ -using asap.core; -using Assets.Scripts.UI.OfferSweep; -using cfg; -using CodeStage.AntiCheat.ObscuredTypes; -using DataCenter; -using game; -using LitJson; -using Newtonsoft.Json; -using Script.RuntimeScript; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine; - -namespace GameCore -{ - public class PlayerData - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - private cfg.Tables _tables; - MMTService _MMService; - public PlayerData(cfg.Tables tables, MMTService mmService) - { - this._tables = tables; - _MMService = mmService; - } - public const string Gold = "Gold"; - /// - /// "Diamond"==>"Pearl"(不改名是因为数据已经通过Diamond键存储到云端了) - /// - public const string Pearl = "Diamond"; - public const string RodLevel = "RodLevel"; - public const string WeightScore = "WeightScore"; - public const string Diamond = "DiamondTrue"; - Dictionary NewPlayerDataDic = new Dictionary(); - public IReadOnlyDictionary PlayerDataDic => NewPlayerDataDic; - - internal static game.PlayerDataStorage.PlayerKVPlayerState DecodeForKVLoad(IReadOnlyDictionary raw, - IReadOnlyDictionary modern,game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodePlayer(raw,modern,snapshot,errors); - internal void ResetForKVLoad() - { - NewPlayerDataDic=new Dictionary(StringComparer.Ordinal); vipScoreDic=new Dictionary(); - newRodList=new List(); - lv=vip=vipAllScore=0; vipLastScore=PriceLv=0; priceLevel=null; - energy=pearl=diamond=equipRodID=magnification=seasonId=rewardNewMap=0; - gold=0; goldRM=0; energyRM=0; _currentMapId=_lastMapId=0; - _fishingFrequency=_allFishingFrequency=0; _lastEnergyRecoveryTime=DateTime.MinValue; - IsOpenAppraise=false; InfiniteBuildingData=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVPlayerState state) - { - if(state==null || state.Core==null) throw new ArgumentNullException(nameof(state)); - var modern=state.Modern.ToDictionary(p=>p.Key,p=>p.Value,StringComparer.Ordinal); - var scores=state.VipScores.ToDictionary(p=>p.Key,p=>p.Value); - var rods=new List(state.NewRods); - var core=state.Core; - lv=core.Integer(0); gold=core.Unsigned(1); vipAllScore=core.Integer(2); energy=core.Integer(3); - pearl=core.Integer(4); magnification=core.Integer(5); equipRodID=core.Integer(6); _lastEnergyRecoveryTime=core.EnergyTime; - rewardNewMap=core.Integer(8); energyRM=core.Integer(9); goldRM=core.Unsigned(10); diamond=core.Integer(11); - _currentMapId=core.Integer(12); _lastMapId=core.Integer(13); _fishingFrequency=core.Integer(14); _allFishingFrequency=core.Integer(15); - NewPlayerDataDic=modern; vipScoreDic=scores; newRodList=rods; - seasonId=state.Season; IsOpenAppraise=state.Appraise; InfiniteBuildingData=state.Building; - } -#if UNITY_EDITOR - internal game.PlayerDataStorage.PlayerKVPlayerState SnapshotForKVValidation() => - new game.PlayerDataStorage.PlayerKVPlayerState(new game.PlayerDataStorage.PlayerKVCoreState(new object[] { - (int)lv,(ulong)gold,(int)vipAllScore,(int)energy,(int)pearl,(int)magnification,(int)equipRodID,_lastEnergyRecoveryTime, - (int)rewardNewMap,energyRM,goldRM,(int)diamond,(int)_currentMapId,(int)_lastMapId,_fishingFrequency,_allFishingFrequency,0,0,0 - }),NewPlayerDataDic,vipScoreDic,newRodList,seasonId,IsOpenAppraise,InfiniteBuildingData); - internal bool IsDerivedEmptyForKVValidation => (int)vip==0 && vipLastScore==0 && PriceLv==0 && priceLevel==null; -#endif - public ObscuredInt lv { get; set; } - public ObscuredInt vip { get; private set; } - public ObscuredInt vipAllScore { get; private set; } - public int vipLastScore { get; private set; } - Dictionary vipScoreDic = new Dictionary(); - #region 付费积分 - public int PriceLv { get; private set; } - - public VipLevel priceLevel; - #endregion 付费积分 - private ObscuredInt energy; - int energyRM; - public ObscuredULong gold { get; private set; } - ulong goldRM; - public ObscuredInt pearl { get; private set; } - public ObscuredInt diamond { get; private set; } - - public ObscuredInt equipRodID = 10001; - public ObscuredInt magnification; - public ObscuredInt seasonId = 0; - public ObscuredInt rewardNewMap = 0; - bool IsOpenAppraise = false; - ObscuredInt _currentMapId = 0; - public string InfiniteBuildingData = "0"; - public string InfiniteBuildingLevel => InfiniteBuildingData.Split(',')[0]; - public ObscuredInt currentMapId - { - set { _currentMapId = value; } - get - { - if (_currentMapId == 0 || !_tables.TbMapData.DataMap.ContainsKey(_currentMapId)) - { - _currentMapId = _tables.TbMapData.DataList[0].ID; - } - //if (_TestService.TestMapIDs != null) - //{ - // var ab = _TestService.TestMapIDs.FirstOrDefault(a => a.OldID == _currentMapId); - // return ab != null ? ab.NewID : _currentMapId; - //} - return _currentMapId; - } - } - //膨胀系数 - public float InflationRate { get; private set; } - - ObscuredInt _lastMapId = 0; - public ObscuredInt lastMapId - { - set { _lastMapId = value; } - get - { - if (_lastMapId == 0) - { - _lastMapId = _tables.TbMapData.DataList[0].ID; - } - //if (_TestService.TestMapIDs != null) - //{ - // var ab = _TestService.TestMapIDs.FirstOrDefault(a => a.OldID == _lastMapId); - // return ab != null ? ab.NewID : _lastMapId; - //} - return _lastMapId; - } - } - public int _fishingFrequency = 0; - public int _allFishingFrequency = 0; - public List newRodList = new List(); - - public List showNewRodList = new List(); - - bool addShowNewRod = true; - - public float benefitsCashMag { get; private set; } - public float benefitsCashMagLimited { get; private set; } - public int benefitsEnergyLimit { get; private set; } - public int benefitsEnergyRecover { get; private set; } - public float benefitsEventFishCashMag { get; private set; } - public float benefitsEventFishDamage { get; private set; } - public int benefitsAquariumLimit { get; private set; } - public float benefitsAquariumCashMag { get; private set; } - public List benefitsLevel; - public int OpenGradeID = 0; - public bool OpenGrade = false; - public int MagnificationCount - { - get - { - List DataList = _tables.TbEnergyDef.DataList; - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isSuperEnergy = buffTimeData != null; - for (int i = 0; i < DataList.Count; i++) - { - int demandEnergy = DataList[i].Energy; - if (isSuperEnergy) - { - demandEnergy = DataList[i].FishBuffEnergy; - } - if (demandEnergy < 0 || Energy < demandEnergy) - { - return i; - } - } - return DataList.Count; - } - } - public Account nextAccountData; - public bool IsOpenMagnification = false; - public int GetCurMaxMagnification() - { - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isSuperEnergy = buffTimeData != null; - List DataList = _tables.TbEnergyDef.DataList; - for (int i = DataList.Count - 1; i >= 0; i--) - { - int demandEnergy = DataList[i].Energy; - if (isSuperEnergy) - { - demandEnergy = DataList[i].FishBuffEnergy; - } - if (demandEnergy >= 0) - { - if (Energy >= demandEnergy) - { - return i; - } - } - } - return 0; - } - public void SaveFishingFrequency() - { - _fishingFrequency++; - GContext.Publish(new ExchangeFishCount(_fishingFrequency)); - _allFishingFrequency += GContext.container.Resolve().GetMagnification(); - GContext.Publish(new ConditionTypeEvent(ConditionType.GetFishCount, 1)); - SavePlayerData(); - } - /// - /// buff 过期 - /// - public void CheckSuperEnergyBuff() - { - List DataList = _tables.TbEnergyDef.DataList; - for (int i = DataList.Count - 1; i >= 0; i--) - { - if (DataList[i].Energy >= 0) - { - if (i < magnification) - { - magnification = i; - SetMagnification(); - } - return; - } - } - } - - public ObscuredInt Energy - { - get => energy; - private set { SetEnergy(value); } - } - int RecoverNotificationID = 1002; - public ObscuredInt MaxEnergy => benefitsEnergyLimit; - - public int EnergyRecover => benefitsEnergyRecover; - - DateTime _lastEnergyRecoveryTime = ZZTimeHelper.UtcNow(); - - public void SetEnergy(int count, bool remote = true) - { - if (count < 0) - { - count = 0; - } - if (count < energy) - { - energyRM += energy - count; - } - energy = count; - if (energy >= MaxEnergy) - { - GContext.container.Resolve().ClearNotification(RecoverNotificationID); - } - SavePlayerData(remote); - } - public int GetEnergyRM() - { - return energyRM; - } - public void AddGold(ulong count) - { - SetGold(gold + count); - } - public void SetGold(ulong count) - { - if (count < gold) - { - goldRM += gold - count; - } - gold = count; - SavePlayerData(); - } - - public void SetPearl(int count) - { - if (count < 0) - { - count = 0; - } - pearl = count; - SavePlayerData(); - GContext.container.Resolve().CheckAllRodUpLevel(); - } - public void AddDiamond(int count) - { - var newCount = diamond + count; - if (newCount < 0) - { - newCount = 0; - } - diamond = newCount; - if (count < 0) - { - GContext.Publish(new ConditionTypeEvent { type = ConditionType.ConsumeDiamondCount, count = -count }); - GContext.Publish(new ResAddEvent(1005)); - } - SavePlayerData(); - } - - - public void SetEquipRodID(int ID) - { - equipRodID = ID; - GContext.container.Resolve().SetRedPoint(); - SavePlayerData(); - } - - public void SetMagnification() - { - SavePlayerData(); - } - - public void AddNewMap(int index) - { - rewardNewMap |= 1 << index; - } - - public void RewardNewMap(int index) - { - int newMap = 1 << index; - rewardNewMap &= ~newMap; - SavePlayerData(); - } - - public bool IsNewMap(int index) - { - int newMap = 1 << index; - return (rewardNewMap & newMap) == newMap; - } - - - public void AddNewRod(int id) - { - if (!newRodList.Contains(id)) - { - newRodList.Add(id); - playerSaveStore.Write("NewRodList", JsonMapper.ToJson(newRodList)).RequireAccepted(); - if (addShowNewRod) - { - showNewRodList.Add(id); - } - } - } - - public void StartAddNewRod() - { - addShowNewRod = true; - } - - public void ShowNewRod() - { - //addShowNewRod = false; - if (showNewRodList.Count > 0) - { - List itemDatas = new List(); - for (int i = 0; i < showNewRodList.Count; i++) - { - itemDatas.Add(new ItemData { id = showNewRodList[i], count = 1 }); - } - GContext.Publish(new ShowData(itemDatas, RewardType.NewRod)); - showNewRodList.Clear(); - } - } - - public void RewardNewRod(int id) - { - newRodList.Remove(id); - playerSaveStore.Write("NewRodList", JsonMapper.ToJson(newRodList)).RequireAccepted(); - GContext.container.Resolve().SetRedPoint(); - } - - public bool IsNewRod(int id) - { - return newRodList.Contains(id); - } - - public void SetLv(int count) - { - int addLevel = count - lv; - GContext.container.Resolve().CheckBuildBehavior(addLevel); - - lv = count; - -#if AGG - GEvent.SetProp("building_times", count); - GEvent.SetUserProp("building_times", count); -#endif - GContext.Publish(new ConditionTypeEvent(ConditionType.AccountLevel, addLevel)); - GContext.Publish(new ConditionTypeEvent(ConditionType.ConstructionCount, addLevel)); - OnLvChange(); - SavePlayerData(); - GContext.container.Resolve().AwaitSetLvData(); - } - //等级改变的时候 - - public void OnLvChange() - { - var account = _tables.TbAccount.DataList; - nextAccountData = account[^1]; - - Account curAccountData = null; - for (int i = 0; i < account.Count; i++) - { - if (lv < account[i].ID) - { - nextAccountData = account[i]; - break; - } - else - { - curAccountData = account[i]; - } - } - SetBenefits(curAccountData); - //解锁地图 - int unLockIndex = 0; - var dataList = _tables.TbMapData.DataList; - var mapData = dataList[^1]; - int count = dataList.Count; - InflationRate = 0; - for (int i = 0; i < count; i++) - { - if (lv < dataList[i].LevelRequired) - { - unLockIndex = i; - mapData = dataList[i]; - break; - } - //计算膨胀系数 - InflationRate = dataList[i].LureScalePercent / 100; - } - int newMapId = mapData.ID; - - if (lastMapId != newMapId) - { - lastMapId = newMapId; - LoadNewMap(); -#if AGG - using (var e = GEvent.GameEvent("open_new")) - { - e.AddContent("open_type", 1) - .AddContent("map_id", lastMapId); - - } -#endif - if (unLockIndex > 0) - { - GContext.container.Resolve().SendSystemMessage2(unLockIndex); - AddNewMap(unLockIndex); - } - } - GContext.Publish(new OnLvChangeEvent() { lvl = lv }); - AiHelpManager.Instance.Update(); - if (lv >= _tables.TbGlobalConfig.NotPopUpUnlockLevel - && GContext.container.Resolve().CheckRequestPermission()) - { - GContext.container.Resolve().AddFaceCustomUIData(new UIType("SettingNotificationsGradePopupPanel")); - } - } - void SetBenefits(Account curAccountData) - { - int levelCashMag = 0; - int levelCashMagLimited = 0; - int levelEnergyLimit = 0; - int levelEnergyRecover = 0; - int levelEventFishCashMag = 0; - int levelEventFishDamage = 0; - int levelAquariumLimit = 0; - int levelAquariumCashMag = 0; - if (curAccountData != null) - { - levelCashMag = curAccountData.CashMag; - levelCashMagLimited = curAccountData.CashMagLimited; - levelEnergyLimit = curAccountData.EnergyLimit; - levelEnergyRecover = curAccountData.EnergyRecover; - levelEventFishCashMag = curAccountData.EventFishCashMag; - levelEventFishDamage = curAccountData.EventFishDamage; - levelAquariumLimit = curAccountData.AquariumLimit; - levelAquariumCashMag = curAccountData.AquariumCashMag; - } - benefitsLevel = new List - { - levelCashMag, - levelCashMagLimited, - levelEnergyLimit, - levelEnergyRecover, - levelEventFishCashMag, - levelEventFishDamage, - levelAquariumLimit, - levelAquariumCashMag, - }; - var TbBenefits = _tables.TbBenefits; - benefitsCashMag = TbBenefits.GetOrDefault(1).BenefitsValue[levelCashMag]; - benefitsCashMagLimited = TbBenefits.GetOrDefault(2).BenefitsValue[levelCashMagLimited]; - benefitsEnergyLimit = Mathf.RoundToInt(TbBenefits.GetOrDefault(3).BenefitsValue[levelEnergyLimit]); - benefitsEnergyRecover = Mathf.RoundToInt(TbBenefits.GetOrDefault(4).BenefitsValue[levelEnergyRecover]); - benefitsEventFishCashMag = TbBenefits.GetOrDefault(5).BenefitsValue[levelEventFishCashMag]; - benefitsEventFishDamage = TbBenefits.GetOrDefault(6).BenefitsValue[levelEventFishDamage]; - benefitsAquariumLimit = Mathf.RoundToInt(TbBenefits.GetOrDefault(7).BenefitsValue[levelAquariumLimit]); - benefitsAquariumCashMag = TbBenefits.GetOrDefault(8).BenefitsValue[levelAquariumCashMag]; - } - public void LoadNewMap() - { - ILoadResourceService loadResourceService = GContext.container.Resolve(); - var mapData = _tables.TbMapData.GetOrDefault(lastMapId); - if (mapData != null && mapData.DownloadPkg != null && mapData.DownloadPkg.Count > 0) - { - var fishList = _tables.TbAquariumConfig.AquariumSpFishList; - List strings = new List(); - foreach (var fish in fishList) - { - var item = _tables.TbItem.GetOrDefault(fish); - var fishData = _tables.TbFishData.GetOrDefault(item.RedirectID); - if (item != null && !string.IsNullOrEmpty(fishData.Fbx)) - { - strings.Add(fishData.Fbx); - } - } - strings.AddRange(mapData.DownloadPkg); - strings.Add("entermap"); - loadResourceService.EnqueueBundleSilently(strings); - } - } - public MapData GetCurrentMapData() - { - return _tables.TbMapData.GetOrDefault(currentMapId); - } - public bool MapIsUnlock(List Param) - { - return Param.Contains(lastMapId.ToString()); - } - public void SetCurrentMapId(int id) - { - currentMapId = id; - SavePlayerData(); - } - - public void AddVIPScore(int count, bool isBuy = false) - { - UpdateVIPScoreDic(); - - vipAllScore += count; - if (vipScoreDic.ContainsKey(0)) - { - vipScoreDic[0] += count; - } - else - { - vipScoreDic[0] = count; - } -#if AGG - using (var e = GEvent.GameEvent("getpoint_vip")) - { - e.AddContent("add_count", count).AddContent("all_count", vipAllScore); - } -#endif - VipChange(); - SavePlayerData(); - } - void VipChange() - { - vipLastScore = vipScoreDic.Where(_ => _.Key >= 0 && _.Key < 10).Select(_ => _.Value).Sum(); - SetVIP(); - } - public void SetPriceLevel(int level) - { - priceLevel = _tables.TbVipLevel.GetOrDefault(level); - var dynamicVipParam = _tables.TbGlobalConfig.DynamicVipParam; - vipAllScore = 0; - vipScoreDic.Clear(); - vipScoreDic[0] = level == 0 ? 0 : (int)(priceLevel.LevelScore / dynamicVipParam[1]) + 1; - VipChange(); - } - void SetVIP() - { - int LevelScore = 0; - //设置vip等级 - var vipData = _tables.TbVipLevel.DataList; - PriceLv = vip = vipData.Count - 1; - //付费等级=f1(vip积分,地区积分)+f2(活跃积分) - var dynamicVipParam = _tables.TbGlobalConfig.DynamicVipParam; - - int allPackPoints = (int)(vipAllScore * dynamicVipParam[0] + vipLastScore * dynamicVipParam[1]); - for (int i = 0; i < vipData.Count; i++) - { - LevelScore += vipData[i].LevelScore; - if (i < vip && vipAllScore < LevelScore) - { - vip = i; - } - if (i < PriceLv && allPackPoints < LevelScore) - { - PriceLv = i; - } - } - int dynamicVipLifeTime = _tables.TbGlobalConfig.DynamicVipLifeTime; - var userService = GContext.container.Resolve(); - //注册时间 - var register_days = (ZZTimeHelper.UtcNow() - userService.CreateTime).TotalSeconds; - if (register_days < dynamicVipLifeTime) - { - PriceLv = vip; - } - - priceLevel = vipData[PriceLv]; -#if AGG - GEvent.SetProp("Dynamic_Vip_Level", PriceLv); - GEvent.SetUserProp("Dynamic_Vip_Level", PriceLv); - - GEvent.SetProp("vip_level", vip); - GEvent.SetUserProp("vip_level", vip); -#endif - AiHelpManager.Instance.Update(); - } - public void LoadPlayerData(Dictionary userDatas) - { - lv = 1; - gold = (ulong)_tables.TbGlobalConfig.InitCash; - vipAllScore = 0; - vipLastScore = 0; - energy = _tables.TbGlobalConfig.InitEnergy; - pearl = _tables.TbGlobalConfig.InitResin; - magnification = 0; - equipRodID = _tables.TbGlobalConfig.InitRodID; - _lastEnergyRecoveryTime = ZZTimeHelper.UtcNow(); - rewardNewMap = 0b1; - GContext.container.Resolve().InitData(userDatas); - if (userDatas == null || userDatas.Count < 1) - { - GameDebug.Log( - "[PlayerData]LoadPlayerData: No player data in User Data, initializing with default values"); - } - else - { - GameDebug.Log("[PlayerData]LoadPlayerData: Load Player data from User Data"); - GContext.container.Resolve().InitData(userDatas); - GContext.container.Resolve().InitData(userDatas); - - GContext.container.Resolve().InitData(userDatas); - - GContext.container.Resolve().InitData(userDatas); - - var etor = userDatas.GetEnumerator(); - - while (etor.MoveNext()) - { - var data_key = etor.Current.Key; - var data_value = etor.Current.Value; - - switch (data_key) - { - - #region 旧数据兼容 - case "Lv": - lv = GlobalUtils.TryParseInt(data_value); - break; - case "Energy": - energy = GlobalUtils.TryParseInt(data_value, _tables.TbGlobalConfig.InitEnergy); - if (energy < 0) - { - energy = 0; - } - break; - case "EnergyRM": - energyRM = GlobalUtils.TryParseInt(data_value, 0); - break; - case "Gold": - gold = GlobalUtils.TryParseUlong(data_value, (ulong)_tables.TbGlobalConfig.InitCash); - break; - case "GoldRM": - goldRM = GlobalUtils.TryParseUlong(data_value, 0); - break; - case Pearl: - pearl = GlobalUtils.TryParseInt(data_value, 0); - break; - case Diamond: - diamond = GlobalUtils.TryParseInt(data_value, 0); - break; - case "Magnification": - magnification = GlobalUtils.TryParseInt(data_value); - break; - case "EquipRodID": - equipRodID = GlobalUtils.TryParseInt(data_value); - if (!_tables.TbRodData.DataMap.ContainsKey(equipRodID)) - { - equipRodID = _tables.TbGlobalConfig.InitRodID; - } - break; - case "LastEnergyRecoveryTime": - _lastEnergyRecoveryTime = GlobalUtils.TryParseDateTime(data_value, ZZTimeHelper.UtcNow()); - break; - - case "RewardNewMap": - rewardNewMap = GlobalUtils.TryParseInt(data_value); - break; - - case "vipAllScore": - vipAllScore = GlobalUtils.TryParseInt(data_value); - break; - - case "CurrentMapId": - currentMapId = GlobalUtils.TryParseInt(data_value); - break; - case "LastMapId": - lastMapId = GlobalUtils.TryParseInt(data_value); - break; - case "FishingFrequency": - _fishingFrequency = GlobalUtils.TryParseInt(data_value); - break; - case "AllFishingFrequency": - _allFishingFrequency = GlobalUtils.TryParseInt(data_value); - break; - case "HeistGameCount": - GContext.container.Resolve().SetHeistGameCount(GlobalUtils.TryParseInt(data_value)); - break; - case "BombGameCount": - GContext.container.Resolve().SetBombGameCount(GlobalUtils.TryParseInt(data_value)); - break; - case "FishHuntGameCount": - GContext.container.Resolve().SetFishHuntGameCount(GlobalUtils.TryParseInt(data_value)); - break; - - case "LuckDataDic": - GContext.container.Resolve().LuckDataDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - break; - - case "AchievementData": - GContext.container.Resolve().LoadAchievementData(data_value); - break; - case "FishingBoxData": - GContext.container.Resolve().InitData(data_value); - break; - - case "GuideSaveData": - try - { - var guideSaveData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - if (guideSaveData != null) - { - GContext.container.Resolve().GuideSaveDataDic = guideSaveData; - } - } - catch (Exception) - { - GameDebug.LogWarning($"[PlayerData]LoadPlayerData: Fail to parse GuideSaveData {data_value}!"); - } - break; - #endregion 旧数据兼容 - - case "NewRodList": - newRodList = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - break; - case "SeasonId": - GContext.container.Resolve().seasonId = GlobalUtils.TryParseInt(data_value); - break; - - case "MonthlySignEvent": - GContext.container.Resolve().monthlySignEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(data_value); - break; - - case "TriggerPackDataList": - GContext.container.Resolve().triggerPackList = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - break; - case "GiftVIPDData": - var giftVIPDData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - GContext.container.Resolve().giftVIPDData = giftVIPDData; - break; - case "FixedTimeShopDic": - var FixedTimeshopDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - GContext.container.Resolve().SetFixedTimeShopDic(FixedTimeshopDic); - break; - - case "ClubSignin": - GContext.container.Resolve().SetClubSignin(data_value); - break; - case "LureDonateData": - GContext.container.Resolve().SetLureDonateData(data_value); - break; - - case "IsOpenAppraise": - IsOpenAppraise = true; - break; - - //case "MonthCardData": - // GContext.container.Resolve().InitMonthCardData(data_value); - // break; - // case "ChallengeData": - // GContext.container.Resolve().InitChallengeData(data_value); - // break; - case "FishingChallengeData": - GContext.container.Resolve().InitChallengeData(data_value); - break; - case OfferChainsChestManager.SaveKey: - GContext.container.Resolve().LoadData(data_value); - break; - case OfferDiscoPartyManager.SaveKey: - GContext.container.Resolve().LoadData(data_value); - break; - - case EventPartnerGatherManager.SaveKey: - GContext.container.Resolve().LoadData(data_value); - break; - case EventCubeMeltManager.SaveKey: - GContext.container.Resolve().LoadData(data_value); - break; - - //case "TargetEventPackData": - // GContext.container.Resolve().InitTargetEventData(data_value); - // break; - - - case "IsOpenClubRed": - GContext.container.Resolve().IsOpenClubRed = false; - break; - //case "PokerScoreData": - // GContext.container.Resolve().InitPockerScore(data_value); - // break; - - case "EventPackData": - GContext.container.Resolve().LoadEventPackData(data_value); - break; - - - case "PiggyBankPackData": - GContext.container.Resolve().LoadData(data_value); - break; - case "GeneralEventPackData": - var tempData = JsonConvert.DeserializeObject(data_value); - int packType = _tables.TbEventPackManager[tempData.redirectID].PackType; - switch (packType) - { - case 3: - GContext.container.Resolve().LoadData(tempData); - break; - } - break; - case "InfiniteBuildingData": - InfiniteBuildingData = data_value; - break; - /* case "EventPartnerData": - GContext.container.Resolve().LoadPlayfabData(data_value); - break; */ - - case "FootPrint": - GContext.container.Resolve().LoadData(data_value); - break; - case EventShootingRangeData.Key: - var data = GContext.container.Resolve(); - if (data == null) - { - GContext.container.Register().AsSingleton(); - data = GContext.container.Resolve(); - } - data.LoadData(data_value); - break; - case EventPotionConfig.SAVE_DATA_KEY: - GContext.container.Resolve().GetDataFromServer(data_value); - break; - case EventPinballConfig.SAVE_DATA_KEY: - GContext.container.Resolve().GetDataFromServer(data_value); - break; - case EventScratchTicketConfig.SAVE_DATA_KEY: - GContext.container.Resolve().GetDataFromServer(data_value); - break; - case ThanksGivingPackData.Key: - GContext.container.Resolve().ThanksGivingPackData.LoadData(data_value); - break; - case ChainPackWithProgressMigrationData.Key: - GContext.container.Resolve().ChainPackWithProgressMigrationData.LoadData(data_value); - break; - // case EventBreakPfData.PfKey: - // EventBreakPfData.Stash = EventBreakPfData.Deserialize(data_value); - // break; - // case EventCanPlayfabData.PlayFabKey: - // EventCanPlayfabData.Deserialize(data_value).Save(); - // break; - case nameof(EventPinataPackData): - GContext.container.Resolve().LoadData(data_value); - break; - default: - break; - } - } - } - GContext.container.Resolve().InitServerData(userDatas); - LoadPlayerDataNew(userDatas); - } - // 新版玩家数据加载 - public void LoadPlayerDataNew(Dictionary userDatas) - { - if (userDatas.TryGetValue("NewPlayerDataDic", out string newPlayerDataDic)) - { - NewPlayerDataDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(newPlayerDataDic); - SetPlayerData(); - } - GContext.container.Resolve().InitData(userDatas); - if (userDatas.TryGetValue("GuideSaveDataNew", out string data_value)) - { - try - { - GContext.container.Resolve().SetData(data_value); - } - catch (Exception) - { - GameDebug.LogWarning($"[PlayerData]LoadPlayerData: Fail to parse GuideSaveData {data_value}!"); - } - } - } - void SetPlayerDataOld() - { - string data_value; - //========================兼容========================= - if (NewPlayerDataDic.TryGetValue("lv", out data_value)) - { - lv = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("lv"); - } - if (NewPlayerDataDic.TryGetValue("gold", out data_value)) - { - gold = GlobalUtils.TryParseUlong(data_value, (ulong)_tables.TbGlobalConfig.InitCash); - NewPlayerDataDic.Remove("gold"); - } - if (NewPlayerDataDic.TryGetValue("vipS", out data_value)) - { - vipAllScore = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("vipS"); - } - - if (NewPlayerDataDic.TryGetValue("energy", out data_value)) - { - energy = GlobalUtils.TryParseInt(data_value); - if (energy < 0) - { - energy = 0; - } - NewPlayerDataDic.Remove("energy"); - } - if (NewPlayerDataDic.TryGetValue("pearl", out data_value)) - { - pearl = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("pearl"); - } - if (NewPlayerDataDic.TryGetValue("mag", out data_value)) - { - magnification = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("mag"); - } - if (NewPlayerDataDic.TryGetValue("rodID", out data_value)) - { - equipRodID = GlobalUtils.TryParseInt(data_value); - if (!_tables.TbRodData.DataMap.ContainsKey(equipRodID)) - { - equipRodID = _tables.TbGlobalConfig.InitRodID; - } - NewPlayerDataDic.Remove("rodID"); - } - if (NewPlayerDataDic.TryGetValue("EnergyTime", out data_value)) - { - _lastEnergyRecoveryTime = GlobalUtils.TryParseDateTime(data_value, ZZTimeHelper.UtcNow()); - - NewPlayerDataDic.Remove("EnergyTime"); - } - - if (NewPlayerDataDic.TryGetValue("rewardNewMap", out data_value)) - { - rewardNewMap = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("rewardNewMap"); - } - if (NewPlayerDataDic.TryGetValue("energyRM", out data_value)) - { - energyRM = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("energyRM"); - } - if (NewPlayerDataDic.TryGetValue("goldRM", out data_value)) - { - goldRM = GlobalUtils.TryParseUlong(data_value); - NewPlayerDataDic.Remove("goldRM"); - } - if (NewPlayerDataDic.TryGetValue("diamond", out data_value)) - { - diamond = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("diamond"); - } - - if (NewPlayerDataDic.TryGetValue("cMapID", out data_value)) - { - currentMapId = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("cMapID"); - } - if (NewPlayerDataDic.TryGetValue("lMapID", out data_value)) - { - lastMapId = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("lMapID"); - } - if (NewPlayerDataDic.TryGetValue("FF", out data_value)) - { - _fishingFrequency = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("FF"); - } - if (NewPlayerDataDic.TryGetValue("AFF", out data_value)) - { - _allFishingFrequency = GlobalUtils.TryParseInt(data_value); - NewPlayerDataDic.Remove("AFF"); - } - SmallGameData smallGameData = GContext.container.Resolve(); - if (NewPlayerDataDic.TryGetValue("HGC", out data_value)) - { - smallGameData.SetHeistGameCount(GlobalUtils.TryParseInt(data_value)); - NewPlayerDataDic.Remove("HGC"); - } - if (NewPlayerDataDic.TryGetValue("BGC", out data_value)) - { - smallGameData.SetBombGameCount(GlobalUtils.TryParseInt(data_value)); - NewPlayerDataDic.Remove("BGC"); - } - if (NewPlayerDataDic.TryGetValue("FHGC", out data_value)) - { - smallGameData.SetFishHuntGameCount(GlobalUtils.TryParseInt(data_value)); - NewPlayerDataDic.Remove("FHGC"); - } - if (NewPlayerDataDic.TryGetValue("LDD", out data_value)) - { - GContext.container.Resolve().LuckDataDic = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - NewPlayerDataDic.Remove("LDD"); - } - if (NewPlayerDataDic.TryGetValue("AD", out data_value)) - { - GContext.container.Resolve().LoadAchievementDataToObject(data_value); - NewPlayerDataDic.Remove("AD"); - } - //========================兼容========================= - } - void SetPlayerData() - { - SetPlayerDataOld(); - string data_value; - - if (NewPlayerDataDic.TryGetValue("newData", out data_value)) - { - string[] strings = data_value.Split(','); - if (strings.Length > 18) - { - lv = GlobalUtils.TryParseInt(strings[0]); - gold = GlobalUtils.TryParseUlong(strings[1], (ulong)_tables.TbGlobalConfig.InitCash); - vipAllScore = GlobalUtils.TryParseInt(strings[2]); - energy = GlobalUtils.TryParseInt(strings[3]); - if (energy < 0) - { - energy = 0; - } - pearl = GlobalUtils.TryParseInt(strings[4]); - magnification = GlobalUtils.TryParseInt(strings[5]); - equipRodID = GlobalUtils.TryParseInt(strings[6]); - if (!_tables.TbRodData.DataMap.ContainsKey(equipRodID)) - { - equipRodID = _tables.TbGlobalConfig.InitRodID; - } - _lastEnergyRecoveryTime = GlobalUtils.TryParseDateTime(strings[7], ZZTimeHelper.UtcNow()); - rewardNewMap = GlobalUtils.TryParseInt(strings[8]); - energyRM = GlobalUtils.TryParseInt(strings[9]); - goldRM = GlobalUtils.TryParseUlong(strings[10]); - diamond = GlobalUtils.TryParseInt(strings[11]); - currentMapId = GlobalUtils.TryParseInt(strings[12]); - lastMapId = GlobalUtils.TryParseInt(strings[13]); - _fishingFrequency = GlobalUtils.TryParseInt(strings[14]); - _allFishingFrequency = GlobalUtils.TryParseInt(strings[15]); - SmallGameData smallGameData = GContext.container.Resolve(); - smallGameData.SetHeistGameCount(GlobalUtils.TryParseInt(strings[16])); - smallGameData.SetBombGameCount(GlobalUtils.TryParseInt(strings[17])); - smallGameData.SetFishHuntGameCount(GlobalUtils.TryParseInt(strings[18])); - } - - } - if (NewPlayerDataDic.TryGetValue("vipL", out data_value)) - { - vipScoreDic = data_value.Split('|').Select(part => part.Split(',')) - .ToDictionary(arr => int.Parse(arr[0]), arr => int.Parse(arr[1])); - } - if (NewPlayerDataDic.TryGetValue("ld", out data_value)) - { - string[] luckDataDic = data_value.Split('|'); - var LuckDataDic = new Dictionary(); - if (luckDataDic.Length == 3) - { - LuckDataDic["InitFishLuck"] = float.Parse(luckDataDic[0]); - LuckDataDic["InitBotLuck"] = float.Parse(luckDataDic[1]); - LuckDataDic["BotCount"] = float.Parse(luckDataDic[2]); - } - GContext.container.Resolve().LuckDataDic = LuckDataDic; - } - - if (NewPlayerDataDic.TryGetValue("ad", out data_value)) - { - GContext.container.Resolve().LoadAchievementDataToObjectNew(data_value); - } - - if (NewPlayerDataDic.TryGetValue("bd", out data_value)) - { - GContext.container.Resolve().InitDataNew(data_value); - } - if (NewPlayerDataDic.TryGetValue("ct", out data_value)) - { - GContext.container.Resolve().CTDeserialize(data_value); - } - if (NewPlayerDataDic.TryGetValue("rt", out data_value)) - { - GContext.container.Resolve().RTDeserialize(data_value); - } - } - public void UpdateVIPScoreDic() - { - int currentDayOfYear = (int)(ZZTimeHelper.UtcNow() - new DateTime(2025, 10, 20)).TotalDays; - if (!vipScoreDic.ContainsKey(-1)) - { - vipScoreDic[-1] = currentDayOfYear; - } - if (currentDayOfYear > vipScoreDic[-1]) - { - int offsetDays = currentDayOfYear - vipScoreDic[-1]; - var scoreDic = new Dictionary(); - foreach (var kvp in vipScoreDic) - { - if (kvp.Key >= 0 && kvp.Key < 14 - offsetDays) - { - scoreDic[kvp.Key + offsetDays] = kvp.Value; - } - } - scoreDic[-1] = currentDayOfYear; - scoreDic[0] = 0; - vipScoreDic = scoreDic; - } - else if (currentDayOfYear < vipScoreDic[-1]) - { - vipScoreDic[-1] = currentDayOfYear; - } - } - public void SavePlayerData(bool remote = true) - { - GContext.Publish(this); - SerializeAndSavePlayerData(remote); - } - -#if UNITY_EDITOR && !SERVICE_HOST - internal async System.Threading.Tasks.Task ConsumeEnergyForKVLoopAsync(int cost, - game.PlayerDataStorage.PlayerKVGameplayLoop.FishingAction action) - { - if(cost<=0 || Energy!r.Remote)}); - await game.PlayerDataStorage.PlayerKVGameplayLoop.ConfirmFishingAsync(action,batch,primary); - } - catch(System.Exception e) { game.PlayerDataStorage.PlayerKVGameplayLoop.Fault(e.Message); throw; } - } - internal async System.Threading.Tasks.Task SetEquipRodIDForKVLoopAsync(int id) - { - var batch=game.PlayerDataStorage.PlayerKVGameplayLoop.BeginEquip(); - game.PlayerDataStorage.PlayerKVEditResult primary; - try - { - using(batch) - { - equipRodID=id; - GContext.container.Resolve().SetRedPoint(); - GContext.Publish(this); - primary=SerializeAndSavePlayerData(true); - } - await game.PlayerDataStorage.PlayerKVGameplayLoop.ConfirmEquipAsync(batch,primary); - } - catch(System.Exception e) { game.PlayerDataStorage.PlayerKVGameplayLoop.Fault(e.Message); throw; } - } -#endif -#if UNITY_EDITOR && !SERVICE_HOST - internal game.PlayerDataStorage.PlayerKVEditResult SaveFishingRewardForKVLoop() - { - game.PlayerDataStorage.PlayerKVGameplayLoop.CheckRewardMainSave(); - return SerializeAndSavePlayerData(true); - } -#endif - private game.PlayerDataStorage.PlayerKVEditResult SerializeAndSavePlayerData(bool remote) - { - StringBuilder sb = new StringBuilder(); - sb.Append(lv).Append(","); - sb.Append(gold).Append(","); - sb.Append(vipAllScore).Append(","); - sb.Append(energy).Append(","); - sb.Append(pearl).Append(","); - sb.Append(magnification).Append(","); - sb.Append(equipRodID).Append(","); - sb.Append(_lastEnergyRecoveryTime.ToString()).Append(","); - sb.Append(rewardNewMap).Append(","); - sb.Append(energyRM).Append(","); - sb.Append(goldRM).Append(","); - sb.Append(diamond).Append(","); - sb.Append(currentMapId).Append(","); - sb.Append(lastMapId).Append(","); - sb.Append(_fishingFrequency).Append(","); - sb.Append(_allFishingFrequency).Append(","); - SmallGameData smallGameData = GContext.container.Resolve(); - sb.Append(smallGameData.HeistGameCount).Append(","); - sb.Append(smallGameData.BombGameCount).Append(","); - sb.Append(smallGameData.FishHuntGameCount); - NewPlayerDataDic["newData"] = sb.ToString(); - - string vipl = vipScoreDic.Select(kvp => $"{kvp.Key},{kvp.Value}").Aggregate((a, b) => $"{a}|{b}"); - //GameDebug.Log($"[PlayerData]SavePlayerData: vipScoreDic string = {vipl}"); - NewPlayerDataDic["vipL"] = vipl; - string luckDataDic = ""; - var LuckDataDic = GContext.container.Resolve().LuckDataDic; - luckDataDic += LuckDataDic.GetValueOrDefault("InitFishLuck") + "|"; - luckDataDic += LuckDataDic.GetValueOrDefault("InitBotLuck") + "|"; - luckDataDic += LuckDataDic.GetValueOrDefault("BotCount"); - - NewPlayerDataDic["ld"] = luckDataDic; - - NewPlayerDataDic["ad"] = GContext.container.Resolve().AchievementDataToJson(); - - NewPlayerDataDic["bd"] = GContext.container.Resolve().GetString(); - - NewPlayerDataDic["ct"] = GContext.container.Resolve().CTSerialize(); - NewPlayerDataDic["rt"] = GContext.container.Resolve().RTSerialize(); ; -#if UNITY_EDITOR && !SERVICE_HOST - if(game.PlayerDataStorage.PlayerKVGameplayLoop.Enabled) return game.PlayerDataStorage.PlayerKVGameplayLoop.Write("NewPlayerDataDic",Newtonsoft.Json.JsonConvert.SerializeObject(NewPlayerDataDic),remote); -#endif - playerSaveStore.Write("NewPlayerDataDic", Newtonsoft.Json.JsonConvert.SerializeObject(NewPlayerDataDic), remote).RequireAccepted(); - return null; - } - public void Init() - { - OnLvChange(); - UpdateVIPScoreDic(); - VipChange(); - RecoveryEnergy(); - } - void InitEnergy() - { - List DataList = _tables.TbEnergyDef.DataList; - if (magnification >= DataList.Count) - { - magnification = 0; - } - EnergyDef energyDef = DataList[magnification]; - if (energyDef.Energy >= 0) - { - return; - } - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isSuperEnergy = buffTimeData != null; - if (isSuperEnergy) - { - return; - } - for (int i = DataList.Count - 1; i >= 0; i--) - { - if (DataList[i].Energy >= 0) - { - if (i < magnification) - { - magnification = i; - } - return; - } - } - } - public bool ContainsOrGreaterRatio(int ratio) - { - List DataList = _tables.TbEnergyDef.DataList; - var buffTimeData = GContext.container.Resolve().GetWeelyBuffTimeData(); - bool isSuperEnergy = buffTimeData != null; - for (int i = 0; i < DataList.Count; i++) - { - int demandEnergy = DataList[i].Energy; - if (isSuperEnergy) - { - demandEnergy = DataList[i].FishBuffEnergy; - } - if (demandEnergy >= 0 && Energy > demandEnergy) - { - if (ratio <= DataList[i].Mag) - { - return true; - } - } - else - { - return false; - } - } - return false; - } - public int GetMagnification() - { - if (magnification >= _tables.TbEnergyDef.DataList.Count) - { - magnification = _tables.TbEnergyDef.DataList.Count - 1; - } - return _tables.TbEnergyDef.DataList[magnification].Mag; - } - public string GetMagnificationIcon() - { - if (magnification >= _tables.TbEnergyDef.DataList.Count) - { - magnification = _tables.TbEnergyDef.DataList.Count - 1; - } - return _tables.TbEnergyDef.DataList[magnification].Icon; - } - public int SetLittleMagnification() - { - List DataList = _tables.TbEnergyDef.DataList; - for (int i = 3; i >= 0; i--) - { - int demandEnergy = DataList[i].Mag; - - if (demandEnergy >= 0) - { - if (Energy >= demandEnergy) - { - return i; - } - } - } - return 0; - } - public float GetLuckMultipier() - { - if (magnification >= _tables.TbEnergyDef.DataList.Count) - { - magnification = _tables.TbEnergyDef.DataList.Count - 1; - } - return _tables.TbEnergyDef.DataList[magnification].LuckMultipier; - } - public bool GetCanMagnification() - { - return GetMagnification() <= Energy; - } - public bool GetCanRetryCost() - { - if (magnification >= _tables.TbEnergyDef.DataList.Count) - { - magnification = _tables.TbEnergyDef.DataList.Count - 1; - } - return _tables.TbEnergyDef.DataList[magnification].RetryCost <= Energy; - } - public bool IsShowEffectBeilvLoop() - { - return _tables.TbEnergyDef.DataList[magnification + 1].Mag <= Energy; - } - public bool IsMaxMagnification() - { - return magnification >= MagnificationCount - 1; - } - - bool _isRecoveryEnergy; - public void RecoveryEnergy(int time) - { - _lastEnergyRecoveryTime = ZZTimeHelper.UtcNow(); - SavePlayerData(); - if (!_isRecoveryEnergy) - { - CoRecoveryEnergy(time); - if (Energy < MaxEnergy) - { - SetRecoverNotification(); - } - } - } - private System.Threading.CancellationTokenSource tokenSource; - public void RecoveryEnergy() - { - InitEnergy(); - CoRecoveryEnergy((int)((ZZTimeHelper.UtcNow() - _lastEnergyRecoveryTime).TotalSeconds)); - if (Energy < MaxEnergy) - { - SetRecoverNotification(); - } - } - public void StopRecoveryEnergy() - { - tokenSource?.Cancel(); - tokenSource = null; - } - public async void CoRecoveryEnergy(int energyRecoveryTime) - { - var store = playerSaveStore; - tokenSource?.Cancel(); - tokenSource = new System.Threading.CancellationTokenSource(); - var token = tokenSource.Token; - _isRecoveryEnergy = true; - int initEnergyRestorationSpeed = _tables.TbGlobalConfig.InitEnergyRestorationSpeed * 60; - - while (Energy < MaxEnergy && !token.IsCancellationRequested && store.IsCurrent) - { - if (energyRecoveryTime >= initEnergyRestorationSpeed) - { - int count = energyRecoveryTime / initEnergyRestorationSpeed * EnergyRecover; - int curEnergy = Energy; - Energy += count; - energyRecoveryTime %= initEnergyRestorationSpeed; - GameDebug.Log($"回复Energy:{Energy}"); - - if (Energy > MaxEnergy) - { - Energy = MaxEnergy; - } - int addEnergy = Energy - curEnergy; -#if AGG - using (var e = GEvent.GameEvent("auto_hook_revitalized")) - { - e.AddContent("map_id", lastMapId) - .AddContent("change_num", addEnergy); - } - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", 1001) - .AddContent("state_info", "get") - .AddContent("change_num", addEnergy); - } -#endif - GContext.Publish(new ResAddEvent(1001)); - _lastEnergyRecoveryTime = ZZTimeHelper.UtcNow().AddSeconds(-energyRecoveryTime); - SavePlayerData(); - } - await Awaiters.Seconds(1); - if (token.IsCancellationRequested || !store.IsCurrent) - { - return; - } - energyRecoveryTime = (int)(ZZTimeHelper.UtcNow() - _lastEnergyRecoveryTime).TotalSeconds; - } - _isRecoveryEnergy = false; - } - - public void ReduceEnergy(int reEnergy, bool remote = true) - { - if (reEnergy == 0) - { - reEnergy = GetMagnification(); - } - int lastEnergy = Energy; - - if (remote) - { - Energy = Mathf.Max(Energy - reEnergy, 0); - } - else - { - SetEnergy(Energy - reEnergy, false); - } - - if (lastEnergy >= MaxEnergy && Energy < MaxEnergy) - { - RecoveryEnergy(0); - } - } - - public void RecoverEnergy() - { - Energy += GetMagnification(); - } - void SetRecoverNotification() - { - var item = _tables.TbNotification.GetOrDefault(RecoverNotificationID); - if (item != null) - { - int en = MaxEnergy - Energy - 1; - int count = (en / EnergyRecover) + 1; - DateTime dateTime = _lastEnergyRecoveryTime + TimeSpan.FromMinutes(count * _tables.TbGlobalConfig.InitEnergyRestorationSpeed); - GContext.container.Resolve(). - ScheduleOneTimeNotification(item.ID, dateTime, LocalizationMgr.GetText(item.Title_l10n_key), LocalizationMgr.GetText(item.Content_l10n_key)); - } - else - { - Debug.LogError($"TbNotification Not {RecoverNotificationID}"); - } - } - public TimeSpan GetEnergyRecoveryTimeMAndS() - { - return _lastEnergyRecoveryTime + TimeSpan.FromMinutes(_tables.TbGlobalConfig.InitEnergyRestorationSpeed) - ZZTimeHelper.UtcNow(); - } - public float GrtEscapeDistanceMag() - { - float ExtraPoint = 1; - //地图加成 - MapData data = _tables.TbMapData.GetOrDefault(lastMapId); - if (data != null) - { - ExtraPoint = data.EscapeDistanceMag; - } - return ExtraPoint; - } - - - public async void OpenAppraisePopupPanel(int fishId) - { - var store = playerSaveStore; - if (!store.IsCurrent) return; - if (lastMapId != _tables.TbMapData.DataList[0].ID && !IsOpenAppraise) - { - var fishData = _tables.TbFishData.GetOrDefault(fishId); - if (fishData != null && fishData.Quality >= 5) - { - await UIManager.Instance.ShowUI(UITypes.AppraisePopupPanel); - if (!store.IsCurrent) return; - IsOpenAppraise = true; - playerSaveStore.Write("IsOpenAppraise", "true").RequireAccepted(); - } - } - } - - #region GM相关 - public int SupplyDropIndex = -1; - #endregion - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/011-DataCenter.PlayerFishData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/011-DataCenter.PlayerFishData.cs.txt deleted file mode 100644 index 68b0c02fe..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/011-DataCenter.PlayerFishData.cs.txt +++ /dev/null @@ -1,1516 +0,0 @@ -using System; -using System.Linq; -using UnityEngine; -using cfg; -using LitJson; -using System.Collections.Generic; -using asap.core; -using game; -using tysdk; -using UnityEngine.UI; - -namespace GameCore -{ - public class FishWeightData - { - public int Level; - public float MaxG; - //public float TotalG; - //public int MaxPTS; - //public long TotalPTS; - public int TotalCard; - public int TotalNum; - public bool NewFish = true; - //public float fishRate; - public string Serialize() - { - //return $"{Level}|{MaxG}|{TotalG}|{MaxPTS}|{TotalPTS}|{TotalCard}|{TotalNum}|{NewFish}|{fishRate}"; - return $"{Level}|{MaxG}|{TotalCard}|{TotalNum}|{NewFish}"; - } - public static FishWeightData Deserialize(string s) - { - string[] arr = s.Split('|'); - FishWeightData data = new FishWeightData(); - if (arr.Length == 9) - { - data.Level = int.Parse(arr[0]); - data.MaxG = float.Parse(arr[1]); - data.TotalCard = int.Parse(arr[5]); - data.TotalNum = int.Parse(arr[6]); - data.NewFish = bool.Parse(arr[7]); - } - else if (arr.Length == 5) - { - data.Level = int.Parse(arr[0]); - data.MaxG = float.Parse(arr[1]); - data.TotalCard = int.Parse(arr[2]); - data.TotalNum = int.Parse(arr[3]); - data.NewFish = bool.Parse(arr[4]); - } - return data; - } - } - public partial class PlayerFishData - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - private cfg.Tables _tables; - private ICustomServerMgr customServerMgr; - public PlayerFishData(cfg.Tables tables, ICustomServerMgr customServerMgr) - { - this._tables = tables; - this.customServerMgr = customServerMgr; - } - Dictionary> mapFishData = new Dictionary>(); - Dictionary mapProgress = new Dictionary(); - - Dictionary fishData = new Dictionary(); - Dictionary fishCardData = new Dictionary(); - //鱼杆星级 和 鱼杆碎片数量 - Dictionary rodData = new Dictionary(); - Dictionary rodLevelData = new Dictionary(); - //每个地图上的的游弋鱼 item map - Dictionary fishSwimToMap = new Dictionary(); - Dictionary fishSwimToMapCount = new Dictionary(); - - bool _isRedPoint_up; - bool RodCanUp = false; - bool RodCanUpLevel = false; - public int MapTipforUnlocked; - public bool IsOpenMap = false; - public bool IsOpenRod = false; - //public bool IsOpenAutoFish = false; - - public float InitBotLuck; - public float InitFishLuck; - public int BotCount = 0; - public Dictionary LuckDataDic = new Dictionary(); - public bool IsOpenPiercing = false; - public int RodSelectedInPack = 0; - internal static game.PlayerDataStorage.PlayerKVFishState DecodeForKVLoad(IReadOnlyDictionary raw, - IReadOnlyDictionary modern,game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) - => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeFish(raw,modern,snapshot,errors); - internal void ResetForKVLoad() - { - mapFishData=new Dictionary>(); fishData=new Dictionary(); fishCardData=new Dictionary(); - mapProgress=new Dictionary(); rodData=new Dictionary(); rodLevelData=new Dictionary(); - fishSwimToMap=new Dictionary(); fishSwimToMapCount=new Dictionary(); _honorlevel=new Dictionary(); - LuckDataDic=new Dictionary(StringComparer.Ordinal); rodAccessoriesData=null; - InitBotLuck=0; InitFishLuck=0; BotCount=0; _isRedPoint_up=false; RodCanUp=false; RodCanUpLevel=false; - MapTipforUnlocked=0; IsOpenMap=false; IsOpenRod=false; IsOpenPiercing=false; RodSelectedInPack=0; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVFishState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - var maps=state.Maps.ToDictionary(m=>m.Key,m=>m.Value.ToDictionary(p=>p.Key,p=>new FishWeightData { - Level=p.Value.Level,MaxG=p.Value.Weight,TotalCard=p.Value.Cards,TotalNum=p.Value.Number,NewFish=p.Value.New })); - var flat=new Dictionary(); - foreach(var map in maps.Values) foreach(var p in map) flat.Add(p.Key,p.Value); - mapFishData=maps; fishData=flat; fishCardData=state.Cards.ToDictionary(p=>p.Key,p=>p.Value); - rodData=state.Rods.ToDictionary(p=>p.Key,p=>p.Value); rodLevelData=state.RodLevels.ToDictionary(p=>p.Key,p=>p.Value); - fishSwimToMap=state.Swim.ToDictionary(p=>p.Key,p=>p.Value); fishSwimToMapCount=state.SwimCount.ToDictionary(p=>p.Key,p=>p.Value); - mapProgress=state.Progress.ToDictionary(p=>p.Key,p=>p.Value); _honorlevel=state.Honor.ToDictionary(p=>p.Key,p=>p.Value); - LuckDataDic=state.Luck.ToDictionary(p=>p.Key,p=>p.Value,StringComparer.Ordinal); - var a=state.Accessories; - rodAccessoriesData=a==null ? null : new RodGSAData { GloveID=a.Glove,RodToSkin=a.RodSkin.ToDictionary(p=>p.Key,p=>p.Value), - GloveIds=new List(a.Gloves),SkinIds=new List(a.Skins),GloveNewIds=new List(a.NewGloves),SkinNewIds=new List(a.NewSkins) }; - } -#if UNITY_EDITOR - internal FishWeightData FishForKVValidation(int map,int id) => mapFishData[map][id]; - internal bool IndexesMatchForKVValidation(int map,int id,int card) => ReferenceEquals(mapFishData[map][id],fishData[id]) && fishCardData[card]==fishData[id].TotalCard; - internal bool EmptyForKVValidation => mapFishData.Count==0 && fishData.Count==0 && fishCardData.Count==0 && mapProgress.Count==0 && rodData.Count==0 && rodLevelData.Count==0 && - fishSwimToMap.Count==0 && fishSwimToMapCount.Count==0 && _honorlevel.Count==0 && LuckDataDic.Count==0 && rodAccessoriesData==null && - InitBotLuck==0 && InitFishLuck==0 && BotCount==0 && !_isRedPoint_up && !RodCanUp && !RodCanUpLevel && !IsOpenMap && !IsOpenRod && !IsOpenPiercing && MapTipforUnlocked==0 && RodSelectedInPack==0; - internal bool DictionariesMatchForKVValidation(game.PlayerDataStorage.PlayerKVFishState s) => - rodData.OrderBy(p=>p.Key).SequenceEqual(s.Rods.OrderBy(p=>p.Key)) && rodLevelData.OrderBy(p=>p.Key).SequenceEqual(s.RodLevels.OrderBy(p=>p.Key)) && - fishSwimToMap.OrderBy(p=>p.Key).SequenceEqual(s.Swim.OrderBy(p=>p.Key)) && fishSwimToMapCount.OrderBy(p=>p.Key).SequenceEqual(s.SwimCount.OrderBy(p=>p.Key)) && - mapProgress.OrderBy(p=>p.Key).SequenceEqual(s.Progress.OrderBy(p=>p.Key)) && _honorlevel.OrderBy(p=>p.Key).SequenceEqual(s.Honor.OrderBy(p=>p.Key)); -#endif - - public void InitData(Dictionary userDatas) - { - string data_value; - if (userDatas.TryGetValue("RodData", out data_value)) - { - rodData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("RodLevelData", out data_value)) - { - rodLevelData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("FishSwimToMap", out data_value)) - { - fishSwimToMap = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("FishSwimToMapCount", out data_value)) - { - fishSwimToMapCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("MapProgress", out data_value)) - { - InitMapProgress(data_value); - } - - if (userDatas.TryGetValue(InitRodAccessoriesDataKey, out data_value)) - { - InitRodAccessoriesData(data_value); - } - if (userDatas.TryGetValue(HonorLevelDataKey, out data_value)) - { - _honorlevel = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - Dictionary mapTBData = _tables.TbMapData.DataMap; - foreach (var map in mapTBData) - { - if (userDatas.TryGetValue($"Map_5_{map.Key}", out data_value)) - { - Dictionary mapDataStr = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - Dictionary mapData = new Dictionary(); - foreach (var item in mapDataStr) - { - mapData[item.Key] = FishWeightData.Deserialize(item.Value); - } - SetFishAllData(map.Key, mapData); - } - else if (userDatas.TryGetValue($"Map_{map.Key}", out data_value)) - { - //兼容老数据 - Dictionary mapData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - - SetFishAllData(map.Key, mapData); - } - } -#if AGG - int lv = GetAllLevel(); - GEvent.SetProp("fishcard_level", lv); - GEvent.SetUserProp("fishcard_level", lv); -#endif - } - - float FishMaxG(FishData fishData, int level, float maxG) - { - var _fishWeight = fishData.BaseWeight * fishData.PointExtraParam * (1 + fishData.WeightRandom); - if (level > 0) - { - FishCard fishCard = _tables.TbFishCard.GetOrDefault(fishData.FishCardID); - if (fishCard == null) - { - return _fishWeight; - } - var weightIncEvent = fishCard.WeightMagList[level - 1]; - _fishWeight *= (1 + weightIncEvent); - } - _fishWeight = Mathf.Round(_fishWeight * 100) / 100; - if (maxG > _fishWeight) - { - //Debug.LogWarning($"FishMaxG: fishID={fishData.ID}, level={level}, maxG={maxG}, _fishWeight={_fishWeight}"); - return _fishWeight; - } - else - { - return maxG; - } - } - - public int GetDiffFishCount() - { - return fishData.Count; - } - public int GetAnglingCount() - { - return GContext.container.Resolve()._fishingFrequency; - } - //public int GetFishingCount() - //{ - // SmallGameData smallGameData = GContext.container.Resolve(); - // return _fishingFrequency - smallGameData.BombGameCount - smallGameData.HeistGameCount; - //} - - public void Init() - { - InitRodAccessoriesData(); - InitLuck(); - InitRod(); - } - void InitLuck() - { - var config = _tables.TbGlobalConfig; - if (!LuckDataDic.TryGetValue("InitBotLuck", out InitBotLuck)) - { - InitBotLuck = config.InitBotLuck; - } - if (!LuckDataDic.TryGetValue("InitFishLuck", out InitFishLuck)) - { - InitFishLuck = config.InitFishLuck; - } - float botCount; - if (!LuckDataDic.TryGetValue("BotCount", out botCount)) - { - botCount = 0; - } - BotCount = (int)botCount; - } - /// - /// 修改幸运值 - /// - /// 鱼的品质 0=》漂流瓶 - public void SetBotCount(int value) - { - //添加幸运值 - if (value > 5) - { - return; - } - float luck = GContext.container.Resolve().GetLuckMultipier(); - var config = _tables.TbGlobalConfig; - if (value == 0) - { - BotCount++; - InitBotLuck += config.ModifierToBotLuck[0] * luck; - } - else - { - InitBotLuck += config.ModifierToBotLuck[1] * luck; - MoreFish moreFish = GContext.container.Resolve().GetWeelyBuffTimeData(); - if (moreFish != null && moreFish.Quality == value) - { - InitFishLuck += moreFish.ModifierToFishLuck * luck; - } - else - { - InitFishLuck += config.ModifierToFishLuck[value - 1] * luck; - } - - BotCount = 0; - } - if (InitFishLuck < 0) - { - InitFishLuck = 0; - } - if (InitBotLuck < 0) - { - InitBotLuck = 0; - } - GameDebug.Log("InitBotLuck:" + InitBotLuck + " InitFishLuck:" + InitFishLuck + " BotCount:" + BotCount); - LuckDataDic["InitFishLuck"] = InitFishLuck; - LuckDataDic["InitBotLuck"] = InitBotLuck; - LuckDataDic["BotCount"] = BotCount; - GContext.container.Resolve().SavePlayerData(); - } - void InitRod() - { - if (!rodData.ContainsKey(_tables.TbRodData.DataList[0].ID)) - { - rodData[_tables.TbRodData.DataList[0].ID] = 0; - } - else - { - CheckRodRedPointUp(); - CheckAllRodUpLevel(); - } - } - public void CheckRodRedPointUp() - { - _isRedPoint_up = false; - RodCanUp = false; - List rodDatas = _tables.TbRodData.DataList; - RodAscend rodAscend; - for (int i = 0; i < rodDatas.Count; i++) - { - rodAscend = _tables.TbRodAscend[rodDatas[i].AscendID]; - if (rodData.TryGetValue(rodAscend.FragmentID, out int itemCount)) - { - if (rodData.TryGetValue(rodDatas[i].ID, out int star)) - { - if (rodAscend.MaxAscent > star && itemCount >= rodAscend.AscentTransformed[star + 1]) - { - RodCanUp = true; - _isRedPoint_up = true; - break; - } - } - else - { - if (itemCount >= rodAscend.AscentTransformed[0]) - { - _isRedPoint_up = true; - break; - } - } - } - } - SetRedPoint(); - } - public bool CheckRodUpLevelByID(int id) - { - RodData rodDataA = _tables.TbRodData.GetOrDefault(id); - bool isUp = CheckRodUpLevel(rodDataA); - return isUp; - } - public bool CheckRodUpLevel(RodData rodDataA) - { - bool isUp = false; - if (rodData.TryGetValue(rodDataA.ID, out int star)) - { - RodLevelup rodLevelup = _tables.TbRodLevelup.GetOrDefault(rodDataA.LevelupID); - int level = GetRodLevel(rodDataA.ID) + 1;//数据从0开始,显示从1开始 - bool isMax = rodLevelup.MaxLevel <= level; - if (!isMax) - { - var fragment = GContext.container.Resolve().pearl; - var requireNum = rodLevelup.LevelupConsume[level]; - - List Millestones = rodLevelup.Millestones; - int maxLevel = level + 1; - - for (int i = 0; i < Millestones.Count; i++) - { - if (i == star) - { - maxLevel = Millestones[i]; - break; - } - } - if (maxLevel > level && fragment >= requireNum) - { - isUp = true; - } - } - } - return isUp; - } - public void CheckAllRodUpLevel() - { - RodCanUpLevel = false; - List rodDatas = _tables.TbRodData.DataList; - for (int j = 0; j < rodDatas.Count; j++) - { - RodData rodDataA = rodDatas[j]; - - RodCanUpLevel = CheckRodUpLevel(rodDataA); - if (RodCanUpLevel) - { - break; - } - } - SetRedPoint(); - } - public void SetRedPoint() - { - PlayerData playerData = GContext.container.Resolve(); - //bool isUp = CheckRodUpLevelByID(playerData.equipRodID); - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Rod, RodCanUpLevel || _isRedPoint_up || playerData.newRodList.Count > 0); - } - public ExchangeItemData AddNewRod(int id, int count) - { - ExchangeItemData itemRodExchangePiece = new ExchangeItemData(); - for (int i = 0; i < count; i++) - { - if (rodData.ContainsKey(id)) - { - RodData _rodData = _tables.TbRodData.GetOrDefault(id); - if (_rodData != null) - { - RodAscend rodAscend = _tables.TbRodAscend.GetOrDefault(_rodData.AscendID); - if (rodAscend != null) - { - itemRodExchangePiece.exchangeId = rodAscend.FragmentID; - itemRodExchangePiece.exchangeCount += rodAscend.DuplicationTransformed; - AddRodPiece(rodAscend.FragmentID, rodAscend.DuplicationTransformed); - } - } - } - else - { - GContext.container.Resolve().AddNewRod(id); - rodData.Add(id, 0); - playerSaveStore.Write("RodData", JsonMapper.ToJson(rodData)).RequireAccepted(); - //鱼竿红点数据修改 - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Rod, true); - } - } - return itemRodExchangePiece; - } - public bool GetRodCanUp() - { - return RodCanUp; - } - public bool GetRodCanUpLevel() - { - return RodCanUpLevel; - } - public int GetRodAllCount() - { - int count = 0; - foreach (var item in rodData) - { - if (item.Key < 10000000) - { - count++; - } - } - return count; - } - public int GetRoodAllLevel() - { - int count = 0; - foreach (var item in rodLevelData) - { - count += item.Value; - } - return count; - } - int GetRodAllStar() - { - int count = 0; - foreach (var item in rodData) - { - if (item.Key < 10000000) - { - count += item.Value; - } - } - return count; - } - public int GetRodAllScore() - { - int points1 = _tables.TbRodEarnPoints[1].Points; - int points2 = _tables.TbRodEarnPoints[2].Points; - int allLevel = GetRoodAllLevel(); - int allStar = GetRodAllStar(); - int score = allStar * points2 + allLevel * points1; - return score; - } - - public float GetRodAscendStats() - { - int allScore = GetRodAllScore(); - var dataList = GContext.container.Resolve().TbRodLevelupStats.DataList; - float PointBonus = 0; - for (int i = 0; i < dataList.Count; i++) - { - if (allScore < dataList[i].Count) - { - break; - } - PointBonus += dataList[i].CashBonus; - } - return PointBonus; - } - - public void RodLevelUp(int id, int count) - { - GContext.Publish(new ConditionTypeEvent { type = ConditionType.UpgradeRodTimes, count = 1 }); - if (rodLevelData.TryGetValue(id, out int level)) - { - rodLevelData[id]++; - } - else - { - rodLevelData[id] = 1; - } -#if AGG - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", 1003) - .AddContent("state_info", "cost") - .AddContent("change_num", count); - } - using (var e = GEvent.GameEvent("rod_upgrade")) - { - e.AddContent("rod_id", id) - .AddContent("rod_level", GetRodLevel(id)) - .AddContent("resin_consume", count) - .AddContent("rod_star", rodData[id]) - .AddContent("rod_chips_consume", 0); - } -#endif - playerSaveStore.Write("RodLevelData", JsonMapper.ToJson(rodLevelData)).RequireAccepted(); - - GContext.container.Resolve().SetPearl(GContext.container.Resolve().pearl - count); - } - public int GetRodLevel(int id) - { - return rodLevelData.TryGetValue(id, out int level) ? level : 0; - } - public bool CheckUpgrade(RodAscend _rodAscend) - { - int fragment = GetRodPiece(_rodAscend.FragmentID); - int requireNum = _rodAscend.AscentTransformed[0]; - return fragment >= requireNum; - } - public bool CheckUpgrade(RodData data) - { - int rodId = data.ID; - RodAscend _rodAscend = _tables.TbRodAscend.GetOrDefault(data.AscendID); - bool isLock = NotRod(rodId); - int star = isLock ? -1 : GetRodPiece(rodId); - - bool isMax = star >= _rodAscend.MaxAscent; - if (isLock || isMax) - { - return false; - } - int fragment = GetRodPiece(_rodAscend.FragmentID); - int requireNum = _rodAscend.AscentTransformed[star + 1]; - if (fragment >= requireNum) - { - return true; - } - - ///还有判断通用碎片 - int rquiredFragments = requireNum - fragment; - fragment = 0; - RodFragmentExchange rodFragmentExchange = _tables.TbRodFragmentExchange.GetOrDefault(data.Quality); - if (rodFragmentExchange != null) - { - rquiredFragments *= rodFragmentExchange.ExchangeRate; - fragment = GetRodPiece(rodFragmentExchange.GeneralFragmentID); - } - return fragment >= rquiredFragments; - - } - - - public void AddRodPiece(int id, int count) - { - if (rodData.ContainsKey(id)) - { - rodData[id] += count; - } - else - { - rodData.Add(id, count); - } - //鱼竿红点数据修改 - CheckRodRedPointUp(); - playerSaveStore.Write("RodData", JsonMapper.ToJson(rodData)).RequireAccepted(); - } - - public int GetRodPiece(int id) - { - return rodData.ContainsKey(id) ? rodData[id] : 0; - } - - public void GMSetLvAll(int lv) - { - if (lv <= 0) - { - return; - } - List rodTBData = _tables.TbRodData.DataList; - for (int i = 0; i < rodTBData.Count; i++) - { - RodData rodData = rodTBData[i]; - rodLevelData[rodData.ID] = lv; - RodLevelup rodLevelup = _tables.TbRodLevelup.GetOrDefault(rodData.LevelupID); - if (lv >= rodLevelup.MaxLevel) - { - rodLevelData[rodData.ID] = rodLevelup.MaxLevel - 1; - } - else - { - rodLevelData[rodData.ID] = lv; - } - } - - playerSaveStore.Write("RodData", JsonMapper.ToJson(rodData)).RequireAccepted(); - } - - public void GMSetStarAll(int lv) - { - if (lv <= 0) - { - return; - } - List rodTBData = _tables.TbRodData.DataList; - for (int i = 0; i < rodTBData.Count; i++) - { - RodData _rodData = rodTBData[i]; - - RodAscend rodAscend = _tables.TbRodAscend.GetOrDefault(_rodData.AscendID); - - if (lv >= rodAscend.AscentTransformed.Count) - { - rodData[_rodData.ID] = rodAscend.AscentTransformed.Count - 1; - } - else - { - rodData[_rodData.ID] = lv; - } - } - - playerSaveStore.Write("RodData", JsonMapper.ToJson(rodData)).RequireAccepted(); - } - - public void GMAddAllFishMastery(bool all = false) - { - FishData fishTBData; - cfg.FishCard cardTBData; - if (!all) - { - MapData mapTBData = _tables.TbMapData.DataMap[GContext.container.Resolve().currentMapId]; - List fishList = mapTBData.FishList; - Dictionary _fishData = - mapFishData.TryGetValue(GContext.container.Resolve().currentMapId, out var v) - ? v - : new Dictionary(); - foreach (var fish in fishList) - { - fishTBData = _tables.TbFishData.DataMap[fish]; - cardTBData = _tables.TbFishCard.DataMap[fishTBData.FishCardID]; - FishWeightData fishWeightData = new FishWeightData(); - - if (fishData.ContainsKey(fishTBData.ID)) - { - fishWeightData = fishData[fishTBData.ID]; - } - else - { - fishData[fishTBData.ID] = fishWeightData; - if (mapFishData.ContainsKey(mapTBData.ID)) - { - mapFishData[mapTBData.ID][fishTBData.ID] = fishWeightData; - } - else - { - mapFishData[mapTBData.ID] = new Dictionary - { - [fishTBData.ID] = fishWeightData - }; - } - - } - - if (fishWeightData.MaxG <= 0) - { - fishWeightData.MaxG = 1; - } - if (fishWeightData.Level < cardTBData.MaxLevel) - { - fishWeightData.Level += 1; - } - - fishWeightData.TotalCard = - Math.Max(cardTBData.CardsRequiredList[fishWeightData.Level - 1], - fishWeightData.TotalCard); - fishCardData[fishTBData.FishCardID] = fishWeightData.TotalCard; - } - - MapNewUpdateUserDataValue(GContext.container.Resolve().currentMapId, _fishData); - } - else - { - Dictionary mapTBData = _tables.TbMapData.DataMap; - foreach (var map in mapTBData) - { - List fishList = map.Value.FishList; - Dictionary _fishData = mapFishData.TryGetValue(map.Key, out var v) - ? v - : new Dictionary(); - foreach (var fish in fishList) - { - fishTBData = _tables.TbFishData.DataMap[fish]; - cardTBData = _tables.TbFishCard.DataMap[fishTBData.FishCardID]; - FishWeightData fishWeightData = new FishWeightData(); - if (fishData.ContainsKey(fishTBData.ID)) - { - fishWeightData = fishData[fishTBData.ID]; - } - else - { - fishData[fishTBData.ID] = fishWeightData; - if (mapFishData.ContainsKey(map.Key)) - { - mapFishData[map.Key][fishTBData.ID] = fishWeightData; - } - else - { - mapFishData[map.Key] = new Dictionary - { - [fishTBData.ID] = fishWeightData - }; - } - - } - - if (fishWeightData.MaxG <= 0) - { - fishWeightData.MaxG = 1; - } - if (fishWeightData.Level < cardTBData.MaxLevel) - { - fishWeightData.Level += 1; - } - - fishWeightData.TotalCard = - Math.Max(cardTBData.CardsRequiredList[fishWeightData.Level - 1], - fishWeightData.TotalCard); - fishCardData[fishTBData.FishCardID] = fishWeightData.TotalCard; - } - - MapNewUpdateUserDataValue(map.Key, _fishData); - } - } - } - - public void GMAddAllFishMastery1(bool all = false) - { - FishData fishTBData; - cfg.FishCard masteryTBData; - - if (!all) - { - MapData mapTBData = _tables.TbMapData.DataMap[GContext.container.Resolve().currentMapId]; - List fishList = mapTBData.FishList; - - foreach (var fish in fishList) - { - fishTBData = _tables.TbFishData.DataMap[fish]; - masteryTBData = _tables.TbFishCard.DataMap[fishTBData.FishCardID]; - FishWeightData fishWeightData = new FishWeightData(); - if (fishData.ContainsKey(fishTBData.ID)) - { - fishWeightData = fishData[fishTBData.ID]; - } - else - { - fishData[fishTBData.ID] = fishWeightData; - if (mapFishData.ContainsKey(mapTBData.ID)) - { - mapFishData[mapTBData.ID][fishTBData.ID] = fishWeightData; - } - else - { - mapFishData[mapTBData.ID] = new Dictionary - { - [fishTBData.ID] = fishWeightData - }; - } - - } - fishWeightData.TotalCard = masteryTBData.CardsRequiredList[masteryTBData.MaxLevel - 1]; - fishWeightData.Level = masteryTBData.MaxLevel; - fishCardData[fishTBData.FishCardID] = fishWeightData.TotalCard; - } - int mapID = GContext.container.Resolve().currentMapId; - MapNewUpdateUserDataValue(mapID, mapFishData[mapID]); - } - else - { - Dictionary mapTBData = _tables.TbMapData.DataMap; - foreach (var map in mapTBData) - { - List fishList = map.Value.FishList; - - foreach (var fish in fishList) - { - fishTBData = _tables.TbFishData.DataMap[fish]; - masteryTBData = _tables.TbFishCard.DataMap[fishTBData.FishCardID]; - FishWeightData fishWeightData = new FishWeightData(); - if (fishData.ContainsKey(fishTBData.ID)) - { - fishWeightData = fishData[fishTBData.ID]; - } - else - { - fishData[fishTBData.ID] = fishWeightData; - if (mapFishData.ContainsKey(map.Key)) - { - mapFishData[map.Key][fishTBData.ID] = fishWeightData; - } - else - { - mapFishData[map.Key] = new Dictionary - { - [fishTBData.ID] = fishWeightData - }; - } - - } - - fishWeightData.TotalCard = masteryTBData.CardsRequiredList[masteryTBData.MaxLevel - 1]; - fishWeightData.Level = masteryTBData.MaxLevel; - fishCardData[fishTBData.FishCardID] = fishWeightData.TotalCard; - } - MapNewUpdateUserDataValue(map.Key, mapFishData[map.Key]); - } - } - - } - - public bool NotRod(int id) - { - return !rodData.ContainsKey(id); - } - - public void SetFishAllData(int key, Dictionary mapData) - { - Dictionary mapDataNew = new Dictionary(); - foreach (var fishWeightData in mapData) - { - - FishData _fish = _tables.TbFishData.GetOrDefault(fishWeightData.Key); - if (_fish != null) - { - if (_fish.AreaID != key) - { - Debug.Log("fishWeightData.AreaID " + fishWeightData.Key + " " + key); - - continue; - } - FishWeightData newData = new FishWeightData - { - Level = fishWeightData.Value.Level, - MaxG = fishWeightData.Value.MaxG, - TotalCard = fishWeightData.Value.TotalCard, - TotalNum = fishWeightData.Value.TotalNum, - NewFish = fishWeightData.Value.NewFish - }; - - //修正最大重量,过一段时间删除 - if (_fish.Quality <= 5) - { - newData.MaxG = FishMaxG(_fish, newData.Level, newData.MaxG); - } - //修正最大重量 - - mapDataNew.Add(_fish.ID, newData); - fishData[_fish.ID] = newData; - if (newData.Level > 0) - { - cfg.FishCard fishCard = _tables.TbFishCard[_fish.FishCardID]; - if (newData.Level > fishCard.MaxLevel) - { - newData.Level = fishCard.MaxLevel; - } - int startWeight = fishCard.CardsRequiredList[newData.Level - 1]; - if (startWeight > newData.TotalCard) - { - newData.TotalCard = startWeight; - } - } - fishCardData[_fish.FishCardID] = newData.TotalCard; - } - } - mapFishData[key] = mapDataNew; - } - - public void SetDataLevel(int id) - { - if (fishData.ContainsKey(id)) - { - fishData[id].Level++; - SetFishData(id, fishData[id]); - } - } - public void SetDataLevel(int id, int lv) - { - if (fishData.ContainsKey(id)) - { - fishData[id].Level = lv; - SetFishData(id, fishData[id]); - } - } - public void UpDateLevel(int id) - { - SetDataLevel(id); - //鱼卡战令 - GContext.container.Resolve().UpdateTaskData(MiniBattlePassType.Fishcard, 1); - //GContext.Publish(new ConditionTypeEvent(ConditionType.FishCardLevelUp, 1)); -#if AGG - int allLv = GetAllLevel(); - GEvent.SetProp("fishcard_level", allLv); - GEvent.SetUserProp("fishcard_level", allLv); - using (var e = GEvent.GameEvent("fishcard_upgrade")) - { - e.AddContent("level_count", 1); - } - -#endif - } - - public void SetWeight(int fishId, float weight) - { - //获取鱼重量记录为g - GContext.Publish(new ConditionTypeEvent(ConditionType.GetFishWeight, (int)(weight * 1000))); - CheckFishData(fishId); - if (fishData[fishId].MaxG < weight) - { - fishData[fishId].MaxG = weight; - SetFishData(fishId, fishData[fishId]); - } - GContext.Publish(new ConditionTypeEvent(ConditionType.GetFishID, fishId)); - } - - public ExchangeItemData AddTotalCard(int id, int totalCard) - { - ExchangeItemData exchangeItemData = null; - GContext.Publish(new ConditionTypeEvent { type = ConditionType.CollectFishCardCount, count = totalCard }); - if (fishCardData.ContainsKey(id)) - { - fishCardData[id] += totalCard; - } - else - { - fishCardData[id] = totalCard; - } - - var cardData = _tables.TbFishCard.DataMap[id]; - int fishId = cardData.FishID; - CheckFishData(fishId); - fishData[fishId].TotalCard += totalCard; - - int cardCount = fishCardData[id]; - int allCount = cardData.CardsRequiredList[^1]; - if (cardCount > allCount) - { - int extra = cardCount - allCount; - fishCardData[id] = allCount; - fishData[fishId].TotalCard = allCount; - //鱼卡转换道具 - var dropExchange = _tables.TbFishCardExchange.GetOrDefault(cardData.Quality); - if (dropExchange != null) - { - var itemData = GContext.container.Resolve().GetItemDataOne(dropExchange.DropID); - itemData.count *= extra; - GContext.container.Resolve().AddItemCount(itemData.id, itemData.count, null); - exchangeItemData = new ExchangeItemData - { - exchangeId = itemData.id, - curCount = itemData.curCount, - exchangeCount = Mathf.RoundToInt(itemData.count) - }; - } - } - SetFishData(fishId, fishData[fishId]); - return exchangeItemData; - } - void CheckFishData(int fishId) - { - if (!fishData.ContainsKey(fishId)) - { - fishData.Add(fishId, new FishWeightData() { NewFish = true }); - } - } - public void SetGetFishCount(int fishId) - { - int count = GContext.container.Resolve().GetMagnification(); - CheckFishData(fishId); - fishData[fishId].TotalNum += count; - } - public int GetCardDataProficiency(int id) - { - if (fishCardData.ContainsKey(id)) - { - return fishCardData[id]; - } - else - { - return 0; - } - } - - public bool GetFishCanLevel() - { - var dataList = _tables.TbMapData.DataList; - int count = dataList.Count; - int levelRequired = 0; - for (int i = 0; i < count; i++) - { - if (i > 0) - { - levelRequired = dataList[i - 1].LevelRequired; - } - if (GContext.container.Resolve().lv >= levelRequired) - { - if (GetMapRedCount(dataList[i].FishList) > 0) - { - return true; - } - } - else - { - break; - } - } - return false; - } - public List GetFishCardIdsCanLevelUpAll() - { - var dataList = _tables.TbMapData.DataList; - int count = dataList.Count; - int levelRequired = 0; - var fishCardIds = new List(); - for (int i = 0; i < count; i++) - { - if (i > 0) - { - levelRequired = dataList[i - 1].LevelRequired; - } - if (GContext.container.Resolve().lv >= levelRequired) - { - var fishIds = dataList[i].FishList; - foreach (var id in fishIds) - { - var fishCard = _tables.TbFishCard[_tables.TbFishData.DataMap[id].FishCardID]; - int level = GetDataLevel(id); - if (level < fishCard.MaxLevel && GetCardDataProficiency(fishCard.ID) >= fishCard.CardsRequiredList[level]) - { - fishCardIds.Add(fishCard.ID); - } - } - } - else - { - break; - } - } - return fishCardIds; - } - public void AutoUpgradeFishCardAll() - { - int level; - int fishId; - Dictionary cardData = new Dictionary(fishCardData); - int allUpLevel = 0; - foreach (var fishData in cardData) - { - var fishCard = _tables.TbFishCard.GetOrDefault(fishData.Key); - if (fishCard == null) - { - Debug.LogError($"FishCard not found for ID: {fishData.Key}"); - continue; - } - fishId = fishCard.FishID; - level = GetDataLevel(fishId); - var cardsRequiredList = fishCard.CardsRequiredList; - var proficiency = GetCardDataProficiency(fishCard.ID); - int newLevel = level; - for (int i = level; i < cardsRequiredList.Count; i++) - { - if (proficiency >= cardsRequiredList[i]) - { - newLevel = i + 1; - } - else - { - break; - } - } - if (newLevel > level) - { - SetDataLevel(fishId, newLevel); - allUpLevel += newLevel - level; - } - } - //GContext.Publish(new ConditionTypeEvent(ConditionType.FishCardLevelUp, allUpLevel)); - GContext.container.Resolve().UpdateTaskData(MiniBattlePassType.Fishcard, allUpLevel); - -#if AGG - int lv = GetAllLevel(); - GEvent.SetProp("fishcard_level", lv); - GEvent.SetUserProp("fishcard_level", lv); - using (var e = GEvent.GameEvent("fishcard_upgrade")) - { - e.AddContent("level_count", allUpLevel); - } - -#endif - } - - - public bool IsNewFish(int id) - { - if (fishData.ContainsKey(id)) - { - return fishData[id].MaxG < 0.001f; - } - else - { - return true; - } - } - public int GetDataLevel(int id) - { - if (fishData.ContainsKey(id)) - { - return fishData[id].Level; - } - else - { - return 0; - } - } - public int GetAllLevel() - { - int level = 0; - foreach (var fish in fishData) - { - level += fish.Value.Level; - } - - return level; - } - - public float GetDataMaxWeight(int id) - { - if (fishData.ContainsKey(id)) - { - return fishData[id].MaxG; - } - else - { - return 0; - } - } - - public bool GetDataNewFish(int id) - { - if (fishData.ContainsKey(id)) - { - return fishData[id].NewFish; - } - else - { - return true; - } - } - - public void SetDataNewFish(int id) - { - if (!fishData.ContainsKey(id) || !fishData[id].NewFish) - { - return; - } - - if (fishData.ContainsKey(id)) - { - fishData[id].NewFish = false; - } - - SetFishData(id, fishData[id]); - } - -#if UNITY_EDITOR && !SERVICE_HOST - internal void SaveCaughtFishForKVLoop(int fishId) - { - if(!fishData.TryGetValue(fishId,out var data)) throw game.PlayerDataStorage.PlayerKVGameplayLoop.Stop("Caught fish data is missing."); - game.PlayerDataStorage.PlayerKVGameplayLoop.CheckCaughtFishSave(fishId,data.TotalNum); - SetFishData(fishId,data); - } -#endif - void SetFishData(int id, FishWeightData data) - { - int mapID = _tables.TbFishData.GetOrDefault(id).AreaID; - if (mapFishData.ContainsKey(mapID)) - { - mapFishData[mapID][id] = data; - } - else - { - mapFishData[mapID] = new Dictionary - { - [id] = data - }; - } - MapNewUpdateUserDataValue(mapID, mapFishData[mapID]); - } - void MapNewUpdateUserDataValue(int mapID, Dictionary keyValuePairs) - { - Dictionary mapData = keyValuePairs.ToDictionary(_ => _.Key, _ => _.Value.Serialize()); - playerSaveStore.Write($"Map_5_{mapID}", JsonMapper.ToJson(mapData)).RequireAccepted(); - } - public int GetFishLevelByMap(int mapId) - { - int level = 0; - if (mapFishData.ContainsKey(mapId)) - { - Dictionary keyValuePairs = mapFishData[mapId]; - foreach (var fish in keyValuePairs) - { - level += fish.Value.Level; - } - } - return level; - } - public void SetMapRed() - { - if (!IsOpenMap) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Map, false); - return; - } - int allCount = 0; - var dataList = _tables.TbMapData.DataList; - int count = dataList.Count; - int levelRequired = 0; - for (int i = 0; i < count; i++) - { - if (i > 0) - { - levelRequired = dataList[i - 1].LevelRequired; - } - if (GContext.container.Resolve().lv >= levelRequired) - { - allCount += GetMapRedCount(dataList[i].FishList); - if (allCount > 99) - { - break; - } - } - else - { - break; - } - } - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Map, allCount > 0, allCount); - } - int GetMapRedCount(List fishList) - { - int count = 0; - for (int i = 0; i < fishList.Count; i++) - { - var data = _tables.TbFishData.GetOrDefault(fishList[i]); - if (data == null) - { - continue; - } - var fishCard = _tables.TbFishCard.GetOrDefault(data.FishCardID); - if (fishCard == null) - { - continue; - } - var curProficiency = GetCardDataProficiency(data.FishCardID); - var level = GetDataLevel(data.ID); - for (int j = level; j < fishCard.MaxLevel; j++) - { - if (curProficiency >= fishCard.CardsRequiredList[j]) - { - count++; - } - else - { - break; - } - } - } - return count; - } - public bool GetMapRed(List fishList) - { - for (int i = 0; i < fishList.Count; i++) - { - var data = _tables.TbFishData.GetOrDefault(fishList[i]); - if (data == null) - { - continue; - } - int curProficiency = GetCardDataProficiency(data.FishCardID); - var level = GetDataLevel(data.ID); - var fishCard = _tables.TbFishCard.GetOrDefault(data.FishCardID); - if (fishCard == null) - { - continue; - } - - if (level < fishCard.MaxLevel) - { - int endWeight = fishCard.CardsRequiredList[level]; - if (curProficiency >= endWeight) - { - return true; - } - } - } - return false; - } - - //实际数值 - public float GetAscendValue(float _rodDataValue, List _valueRange) - { - if (_valueRange.Count == 1) - { - return _rodDataValue * _valueRange[0]; - } - _rodDataValue = Mathf.Clamp(_rodDataValue, _valueRange[2], _valueRange[3]); - return (_rodDataValue - _valueRange[2]) / (_valueRange[3] - _valueRange[2]) * (_valueRange[1] - _valueRange[0]) + _valueRange[0]; - } - - //游弋鱼 - public int GetFishSwimToMap(int id) - { - if (fishSwimToMap.TryGetValue(id, out var fishId)) - { - return fishId; - } - return -1; - } - - public void SetFishSwimToMap(int id, int fishId) - { - if (fishId != 0) - { - fishSwimToMapCount[id] = 0; - playerSaveStore.Write("FishSwimToMapCount", JsonMapper.ToJson(fishSwimToMapCount)).RequireAccepted(); - } - fishSwimToMap[id] = fishId; - playerSaveStore.Write("FishSwimToMap", JsonMapper.ToJson(fishSwimToMap)).RequireAccepted(); - } - public void SetFishSwimToMapCount(int id, int count) - { - if (fishSwimToMapCount.ContainsKey(id)) - { - fishSwimToMapCount[id]++; - if (fishSwimToMapCount[id] >= count) - { - SetFishSwimToMap(id, 0); - } - playerSaveStore.Write("FishSwimToMapCount", JsonMapper.ToJson(fishSwimToMapCount)).RequireAccepted(); - } - } - //===========================鱼图鉴=========================== - #region 鱼图鉴相关 - public void InitMapProgress(string value) - { - mapProgress = Newtonsoft.Json.JsonConvert.DeserializeObject>(value); - } - public int GetMapProgress(int mapID) - { - if (mapProgress.TryGetValue(mapID, out int progress)) - { - MapData mapData = _tables.TbMapData.GetOrDefault(mapID); - int AllPTS = GetAllPTSByMap(mapData.ID); - var pointsRequire = mapData.PointsRequire; - for (int i = 0; i < pointsRequire.Count; i++) - { - if (i >= progress) - { - break; - } - else if (AllPTS < pointsRequire[i]) - { - mapProgress[mapID] = i; - return i; - } - } - return progress; - } - else - { - return 0; - } - } - public void GetMapProgressReward(MapData mapData) - { - int mapID = mapData.ID; - int AllPTS = GetAllPTSByMap(mapData.ID); - var pointsRequires = mapData.PointsRequire; - mapProgress.TryGetValue(mapID, out int progress); - mapProgress[mapID] = pointsRequires.Count; - List dorpList = new List(); - for (int i = progress; i < pointsRequires.Count; i++) - { - if (AllPTS < pointsRequires[i]) - { - mapProgress[mapID] = i; - } - else - { - int dorpID = mapData.PointsReward[i]; - int pointsRequire = mapData.PointsRequire[i]; - dorpList.Add(dorpID); -#if AGG - using (var e = GEvent.GameEvent("map_points_reward")) - { - float averageLevel = GetFishLevelByMap(mapID); - averageLevel /= mapData.FishList.Count; - e.AddContent("map_id", mapID) - .AddContent("points", pointsRequire) - .AddContent("drop_id", dorpID) - .AddContent("current_map_fishcard_lv", averageLevel) - ; - } -#endif - } - } - - GContext.container.Resolve().AddItemByDropList(dorpList, null); - playerSaveStore.Write("MapProgress", Newtonsoft.Json.JsonConvert.SerializeObject(mapProgress)).RequireAccepted(); - } - - public int GetAllPTSByMap(int mapID) - { - if (mapFishData.TryGetValue(mapID, out Dictionary weightData)) - { - int allPts = 0; - foreach (var item in weightData) - { - int id = item.Key; - float MaxG = item.Value.MaxG; - FishData fishData = _tables.TbFishData.GetOrDefault(id); - if (fishData != null) - { - DropPackageList dropPackageList = _tables.TbDrop[fishData.DropID].DropList; - float proficiency = dropPackageList.DropCountList[0] * MaxG / fishData.BaseWeight; - allPts += (int)(proficiency); - } - } - return allPts; - } - else - { - return 0; - } - } - public bool PTSRed() - { - if (GContext.container.Resolve().OpenGrade) - { - var DataMap = GContext.container.Resolve().TbMapData.DataMap; - foreach (var mapData in DataMap.Values) - { - int progress = GetMapProgress(mapData.ID); - var pointsRequire = mapData.PointsRequire; - if (progress < pointsRequire.Count && GetAllPTSByMap(mapData.ID) >= pointsRequire[progress]) - { - RedPointManager.Instance.SetRedPointState("menu.achieve", true); - - return true; - } - } - } - RedPointManager.Instance.SetRedPointState("menu.achieve", false); - return false; - } - #endregion - //===========================鱼图鉴=========================== - public static void SetFishIcon(Image icon_fish, Item item) - { - IUIService uIService = GContext.container.Resolve(); - string spriteName = "fishicon_empty_02"; - if (item.Quality < 3) - { - spriteName = "fishicon_empty_01"; - } - else if (item.Quality > 3) - { - spriteName = "fishicon_empty_03"; - } - icon_fish.sprite = uIService.GetSprite(spriteName); - uIService.SetImageSprite(icon_fish, item.Icon);//鱼头像 - } - } -} - -public struct ExchangeFishCount -{ - public ExchangeFishCount(int fishCount) - { - FishCount = fishCount; - } - public int FishCount; -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/012-DataCenter.PlayerItemData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/012-DataCenter.PlayerItemData.cs.txt deleted file mode 100644 index 05321f29a..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/012-DataCenter.PlayerItemData.cs.txt +++ /dev/null @@ -1,1651 +0,0 @@ -using cfg; -using asap.core; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using game; -using Script.RuntimeScript; -using TMPro; -using System; -using DataCenter; -using GameCore.Events; - -namespace GameCore -{ - public class ItemData - { - public int id; - public ulong curCount; - public int count; - [System.NonSerialized] - public int origin; - [System.NonSerialized] - public float inflate; - [System.NonSerialized] - public ExchangeItemData exchangeItemData; - [System.NonSerialized] - public ChangeSource changeSource; - public ItemData() { } - public ItemData(int id, int count) - { - this.id = id; - this.count = count; - } - } - public class ExchangeItemData - { - public int exchangeId; - public int exchangeCount; - public ulong curCount; - [System.NonSerialized] - public ExchangeItemData nextExchangeItemData; - } - public partial class PlayerItemData - { - private cfg.Tables _tables; - public PlayerItemData(cfg.Tables tables) - { - this._tables = tables; - } - void AddCurrency(int subType, float count) - { - switch (subType) - { - case 1: - GContext.container.Resolve().SetEnergy(GContext.container.Resolve().Energy + (int)count); - break; - case 2: - if (count > 0) - { - GContext.container.Resolve().AddGold((ulong)count); - } - break; - case 3: - GContext.container.Resolve().SetPearl(GContext.container.Resolve().pearl + (int)count); - break; - case 4: - GContext.container.Resolve().AddTurntableCoupon((int)count); - break; - case 5: - GContext.container.Resolve().AddDiamond((int)count); - break; - case 6: - GContext.container.Resolve().AddAdticket((int)count); - break; - case 9: - GContext.container.Resolve().AddVoucher((int)count); - break; - } - } - void AddTokens(int subType, float count, int id) - { - switch (subType) - { - case 1: - GContext.container.Resolve().SetLv(GContext.container.Resolve().lv + (int)count); - break; - case 3: - //转盘积分 - //GContext.container.Resolve().IncreaseScore((int)count); - break; - case 2: - GContext.container.Resolve().AddVIPScore((int)count); - break; - case 7: - //GContext.container.Resolve().AddPokerScore((int)count); - break; - case 5: - //小玩法代币 - //GContext.container.Resolve().AddPokerToken((int)count); - break; - case 11: - //GContext.container.Resolve().AddPokerToken((int)count); - break; - case 12: - GContext.container.Resolve().AddTicket((int)count); - break; - case 21: - GContext.container.Resolve()?.AddTicket((int)count); - break; - - // case 18: - // GContext.container.Resolve().AddTicket((int)count); - // break; - case 19: - GContext.container.Resolve().Model.AddTicket((int)count); - break; - case 51: - //1v1门票 - GContext.container.Resolve().AddDuelTickets((int)count); - break; - case 52: - GContext.container.Resolve().AddPVPToken((int)count); - break; - case 53: - GContext.container.Resolve().ChainPackWithProgressMigrationData.AddToken((int)count); - break; - case 15: - // 魔药 - GContext.container.Resolve().AddToken((int)count); - break; - case 16: - // 弹珠 - GContext.container.Resolve().AddToken((int)count); - break; - case 17: - var bingoModel = GContext.container.Resolve(); - if (bingoModel == null) - Debug.LogWarning("[EventBingo] Try to add bingo token, but bingo model not found."); - else - bingoModel.AddTicket((int)count); - break; - case 20: - GContext.container.Resolve()?.AddToken((int)count); - break; - case 70: - var eventOfferJourneyData = GContext.container.Resolve(); - eventOfferJourneyData?.AddTicket((int)count); - break; - case 80: - GContext.container.Resolve().AddToken((int)count); - break; - case 90: - GContext.container.Resolve().AddTicket((int)count); - break; - } - } - - - - void AddActivityTokens(int subType, float count, int id) - { - switch (subType) - { - case 1: - GContext.container.Resolve().AddCollectingTarget(id, (int)count); - break; - case 2: - GContext.container.Resolve().AddRankTarget(id, (int)count); - break; - case 11: - GContext.container.Resolve().AddCollectingTarget((int)count); - break; - case 12: - GContext.container.Resolve().AddRankTarget((int)count); - break; - case 13: - GContext.container.Resolve().AddDigCount((int)count); - break; - } - } - ExchangeItemData AddRodItem(Item item, float count) - { - PlayerFishData playerFishData = GContext.container.Resolve(); - ExchangeItemData exchangeItemData = null; - switch (item.SubType) - { - case 1: - exchangeItemData = playerFishData.AddNewRod(item.RedirectID, (int)count); - break; - case 2: - playerFishData.AddRodPiece(item.ID, (int)count); - break; - case 3: - playerFishData.UnlockSkin(item.RedirectID); - break; - case 4: - break; - case 11: - playerFishData.UnlockGlove(item.RedirectID); - break; - } - return exchangeItemData; - } - public void AddItemCount(int id, float count, ChangeSource changeSource, ItemData itemData = null) - { - if (!_tables.TbItem.DataMap.ContainsKey(id)) - { - GameDebug.LogError($"[PlayerItemData]AddItemCount: Not found id({id}) in DataMap"); - return; - } - - Item item = _tables.TbItem.DataMap[id]; - //if (changeSource != null) - //{ - // Debug.Log($"item_change_source Group : {changeSource.Source_Group} Type : {changeSource.Source_Type} Module : {changeSource.Source_Module}"); - //} -#if AGG - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", id) - .AddContent("state_info", "get") - .AddContent("change_num", count); - if (id == 1001 && itemData != null) - { - e.AddContent("hook_origin", itemData.origin); - } - if (changeSource != null) - { - e.AddContent("Source_EventId", changeSource.Source_EventId) - .AddContent("Source_Group", changeSource.Source_Group) - .AddContent("Source_Type", changeSource.Source_Type) - .AddContent("Source_Module", changeSource.Source_Module); - } - } -#endif - - // 发布物品添加事件,活动系统会通过配置表自动处理代币添加 - GContext.Publish(new ItemAddedEvent - { - ItemId = item.ID, - ItemType = (int)item.Type, - ItemSubType = (int)item.SubType, - Count = (int)count - }); - - GContext.container.Resolve().CheckItemChangeBehavior(id, (int)count); - - ExchangeItemData exchangeItemData = null; - switch (item.Type) - { - case 1: - AddCurrency(item.SubType, count); - break; - case 2: - AddTokens(item.SubType, count, item.ID); - break; - case 3: - exchangeItemData = AddRodItem(item, count); - break; - case 4: - //if (item.SubType == 2) - //{ - // GContext.container.Resolve().AddTotalMastery(item.RedirectID, Mathf.RoundToInt(count)); - //} - if (item.SubType == 3) - { - exchangeItemData = GContext.container.Resolve().AddTotalCard(item.RedirectID, Mathf.RoundToInt(count)); - } - - // if (item.SubType == 8) - // { - // GContext.container.Resolve().AddTicket((int)count); - // } - if (item.SubType == 11) - { - GContext.container.Resolve().AddTicket((int)count); - } - break; - case 5: - if (item.SubType == 1 || item.SubType == 2) - { - AddFishCardData(new ItemData(id, (int)count)); - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(RewardType.CardHolder))); - //OnDropFishCard(item.SubType, item.RedirectID, id, (int)count); - } - break; - case 6: - if (item.SubType == 1) - { - //转盘积分 - GContext.container.Resolve().IncreaseScore((int)count); - } - else if (item.SubType == 2) - { - //转盘免费次数 - GContext.container.Resolve().AddFreecount((int)count); - } - else - { - new EventMatchGameManager().AddTokens(item.SubType, (int)count); - } - break; - case 7: - if (item.SubType == 1) - { - //GContext.container.Resolve().AddMonthCardTime(item.RedirectID); - } - switch (item.SubType) - { - case 1: - break; - case 2: - GContext.container.Resolve().SetVipUnlock(); - break; - case 3: - GContext.container.Resolve().SetBPExp((int)count); - break; - //case 4: - //case 5: - //case 6: - // break; - default: - GContext.container.Resolve().SetVipUnlock(item.SubType); - break; - - } - break; - case 8: - switch (item.SubType) - { - case 2: - GContext.container.Resolve().AddTurntableCoupon((int)count); - break; - case 3: - var data = GContext.container.Resolve(); - if (data == null) - Debug.LogWarning("Event luck magic is likely not available."); - else - data.AddTicket((int)count); - break; - default: - EventLuckyGameModel.Get().AddTicket((int)count); - break; - } - break; - case 9: - switch (item.SubType) - { - case 1: - case 3: - case 4: - OnGetDropPackage(item.RedirectID, (int)count, itemData?.inflate ?? 0, changeSource); - break; - case 7: - OnGetDropPackage7(item.RedirectID, (int)count, itemData?.inflate ?? 0, changeSource); - break; - case 8: - OnGetDropPackage8(item.RedirectID, (int)count, itemData?.inflate ?? 0, changeSource); - break; - case 6: - OnGetDropPackage6(item.RedirectID, (int)count, changeSource); - break; - //case 5: - // OnGetPicturePackage(item.RedirectID, id, (int)count); - // break; - //TODO: 获取鱼箱 - case 2: - OnGetFishingBox(item.RedirectID, (int)count); - break; - case 9: - OnGetDropPackage9(item, (int)count, itemData?.inflate ?? 0, changeSource); - break; - } - break; - case 10: - AddActivityTokens(item.SubType, count, item.RedirectID); - break; - case 11: - if (item.SubType == 1) - { - GContext.container.Resolve().AddGlobalBuff(item.RedirectID); - } - break; - //case 12: - // GContext.container.Resolve().AddBenefitUpgrade((int)count, id); - //break; - case 13: - switch (item.SubType) - { - case 2: - var data = GContext.container.Resolve(); - if (data != null) - data.AddAmmo((int)count); - else - Debug.LogError("Trying to add ammo but event data is null. SUS"); - break; - case 3: - var drillModel = GContext.container.Resolve(); - if (drillModel == null) - { - Debug.Log($"[EventBreak] Trying to add gas but event break data is null. SUS"); - break; - } - drillModel.AddTicket((int)count); - break; - case 11: - // 刮刮乐 - GContext.container.Resolve().AddToken((int)count); - break; - case 12: - var canModel = GContext.container.Resolve(); - if (canModel == null) - { - Debug.Log($"[EventCan] Trying to add gas but event can data is null. SUS"); - break; - } - canModel.AddTicket((int)count); - break; - case 13: - var eventGatherCoreData = GContext.container.Resolve(); - if (eventGatherCoreData == null) - { - Debug.Log($"[EventGatherCore] Trying to add token but event gather core data is null. SUS"); - break; - } - eventGatherCoreData.AddTicket((int)count); - break; - case 14: - GContext.container.Resolve()?.AddToken((int)count); - break; - } - break; - case 15: - switch (item.SubType) - { - case 3: - GContext.container.Resolve()?.Model?.AddTicket((int)count); - break; - case 2: - GContext.container.Resolve().AddTicket((int)count); - break; - case 5: - var socialRushArc = GContext.container.Resolve(); - socialRushArc?.AddProgress((int)count); - break; - } - break; - } - if (itemData != null) - { - itemData.exchangeItemData = exchangeItemData; - } - } - - void OnGetDropPackage6(int id, int count, ChangeSource changeSource) - { - List itemDataGift = GetItemDataByDropIdAndType(id); - for (int i = 0; i < itemDataGift.Count; i++) - { - itemDataGift[i].count *= count; - } - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataGift, RewardType.Normal))); - AddItem(itemDataGift, changeSource); - } - /// - /// 直接打开 - /// - - /// - /// 随机鱼杆碎片、鱼杆 - /// - - void OnGetDropPackage(int id, int count, float inflate, ChangeSource changeSource) - { - List itemDataGift = GetItemDropPackageItemList(id, count); - - LureInflation(itemDataGift, inflate); - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataGift, RewardType.Normal))); - AddItem(itemDataGift, changeSource); - } - void OnGetDropPackage7(int redirectID, int count, float inflate, ChangeSource changeSource) - { - List itemDataGift = GetItemDropItemList(redirectID, count); - - LureInflation(itemDataGift, inflate); - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataGift, RewardType.Normal))); - AddItem(itemDataGift, changeSource); - } - void OnGetDropPackage8(int redirectID, int count, float inflate, ChangeSource changeSource) - { - List itemDataGift = GetItemDataByDropIdAndType(redirectID); - for (int i = 1; i < count; i++) - { - itemDataGift.AddRange(GetItemDataByDropIdAndType(redirectID)); - } - - LureInflation(itemDataGift, inflate); - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataGift, RewardType.Normal))); - AddItem(itemDataGift, changeSource); - } - void OnGetDropPackage9(Item item, int count, float inflate, ChangeSource changeSource) - { - if (item == null) return; - var itemClick = _tables.TbItemClick.GetOrDefault(item.ID); - if (itemClick != null) - { - GContext.Publish(itemClick); - } - - List itemDataGift = GetItemDropItemList(item.RedirectID, count); - if (changeSource != null) - { - for (int i = 0; i < itemDataGift.Count; i++) - { - itemDataGift[i].changeSource = changeSource; - } - } - LureInflation(itemDataGift, inflate); - GContext.Publish(new DeferredRewardStashService.EventStashItems() { Items = itemDataGift }); - } - /// - /// 钓箱 - /// - void OnGetFishingBox(int itemID, int count) - { - GContext.container.Resolve().SetFishingBoxCount(itemID, count); - if (count > 0) - { - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(new List() { new ItemData(itemID, count) }, RewardType.FishBoxOpen, 1))); - } - } - - public List GetItemDropPackageItemList(int id, int count) - { - ItemDropPackage itemDropPackage = _tables.TbItemDropPackage[id]; - List dropIdList = itemDropPackage.DropList; - List itemDataList = new List(); - foreach (var t in dropIdList) - { - itemDataList.AddRange(GetItemDataByDropIdAndType(t)); - } - for (int i = 0; i < itemDataList.Count; i++) - { - itemDataList[i].count *= count; - } - return itemDataList; - } - public List GetItemDropItemList(int id, int count) - { - List itemDataList = GetItemDataByDropIdAndType(id); - for (int i = 0; i < itemDataList.Count; i++) - { - itemDataList[i].count *= count; - } - return itemDataList; - } - /// - /// - /// - /// - /// - /// - public List AddItemByDropList(List dropIDList, ChangeSource changeSource, bool isShow = true, RewardType rewardType = RewardType.Normal) - { - if (dropIDList == null || dropIDList.Count == 0) - { - return null; - } - List itemDataList = new List(); - foreach (var t in dropIDList) - { - List itemDatas = GetItemDataByDropIdAndType(t); - if (itemDatas != null && itemDatas.Count > 0) - { - itemDataList.AddRange(itemDatas); - } - } - if (itemDataList.Count == 0) - { - return null; - } - - if (isShow) - { - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataList, rewardType))); - } - AddItem(itemDataList, changeSource); - return itemDataList; - } - - /// - /// Get ItemData by drop list, merging same items if necessary. - /// - /// - /// List of items, merged. - public List GetMergedItemDataByDropList(List dropIDList) - { - if (dropIDList == null || dropIDList.Count == 0) - { - return new List(); - } - var itemDataList = new List(); - foreach (var itemDatas in dropIDList.Select(t => GetItemDataByDropIdAndType(t)).Where(itemDatas => itemDatas is - { - Count: > 0 - })) - { - itemDataList.AddRange(itemDatas); - } - //itemDataList不需要重复合并 - if (itemDataList.Count == 0) - { - return null; - } - - var map = new Dictionary(); - //itemDataList重复合并 - foreach (var itemData in itemDataList) - { - if (map.ContainsKey(itemData.id)) - { - map[itemData.id] += itemData.count; - } - else - { - map[itemData.id] = itemData.count; - } - } - var newData = new List(); - foreach (var item in map) - { - ItemData itemData1 = new ItemData() - { - id = item.Key, - count = item.Value - }; - itemData1.curCount = (ulong)GetItemCount(itemData1.id); - newData.Add(itemData1); - } - // AddItem(newData); - return newData; - } - - /// - /// Get ItemData list from a drop id list where all drop id points to only one item. - /// - /// drop id list - /// ItemData list. - public List GetItemDataListFromListOfSingleDropId(List singleDropIdList) - { - var res = new List(); - if (singleDropIdList == null || singleDropIdList.Count <= 0) - { - return res; - } - var itemLists = singleDropIdList.Select(i => GetItemDataByDropIdAndType(i)).ToList(); - for (int i = 0; i < itemLists.Count; i++) - { - if (itemLists[i].Count == 1) - continue; - else - { - Debug.LogError($"GetItemDataListFromListOfSingleDropId: drop id {singleDropIdList[i]} points to more than one item."); - break; - } - } - foreach (var itemDatas in itemLists.Where(itemDatas => itemDatas.Count == 1)) - res.AddRange(itemDatas); - return res; - } - - /// - /// - /// - /// - /// - /// - /// - public List AddItemByDrop(int dropID, ChangeSource changeSource, bool isShow = true, RewardType rewardType = RewardType.Normal) - { - List itemDataList = GetItemDataByDropIdAndType(dropID); - if (itemDataList != null) - { - if (isShow) - { - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataList, rewardType))); - } - AddItem(itemDataList, changeSource); - } - return itemDataList; - } - /// - /// 分批获得的时候,卡包合并开启 - /// - /// - /// - public void AddItem(List itemDataList, ChangeSource changeSource) - { - Dictionary cardItemDataList = new Dictionary(); - foreach (var itemData in itemDataList) - { - if (!_tables.TbItem.DataMap.ContainsKey(itemData.id)) - { - GameDebug.LogError($"[PlayerItemData]AddItem: Not found id({itemData.id}) in DataMap"); - continue; - } - Item item = _tables.TbItem.DataMap[itemData.id]; - if (item.Type == 5) - { - if (cardItemDataList.ContainsKey(itemData.id)) - { - cardItemDataList[itemData.id] += itemData.count; - } - else - { - cardItemDataList.Add(itemData.id, itemData.count); - } - continue; - } - AddItemCount(itemData.id, itemData.count, changeSource ?? itemData.changeSource, itemData); - } - if (cardItemDataList.Count > 0) - { - foreach (var item in cardItemDataList) - { - ItemData itemData = new ItemData() - { - id = item.Key, - count = item.Value - }; - itemData.curCount = (ulong)GetItemCount(item.Key); - AddItemCount(itemData.id, itemData.count, changeSource ?? itemData.changeSource, itemData); - } - } - } - public void AddItem(ItemData itemData, ChangeSource changeSource) - { - AddItemCount(itemData.id, itemData.count, changeSource ?? itemData.changeSource, itemData); - } - public double GetItemCount(int itemID) - { - Item item = _tables.TbItem.GetOrDefault(itemID); - if (item == null) - { - GameDebug.LogError($"[PlayerItemData]GetItemCount: Not found item with ID({itemID})"); - return 0; - } - return GetItemCount(item); - } - public double GetItemCount(Item item, float defaultCount = 0) - { - switch (item.Type) - { - case 1: - switch (item.SubType) - { - case 1: - return GContext.container.Resolve().Energy; - case 2: - return GContext.container.Resolve().gold; - case 3: - return GContext.container.Resolve().pearl; - case 4: - return GContext.container.Resolve().TurntableCoupon; - case 5: - return GContext.container.Resolve().diamond; - case 6: - return GContext.container.Resolve().GetAdticketCount(); - //case 9: - // return GContext.container.Resolve().GetVoucher(); - } - break; - case 2: - switch (item.SubType) - { - case 1: - return GContext.container.Resolve().lv; - //case 2: - // return GContext.container.Resolve().vipScore; - case 5: - case 11: - //猜玩法代币通用代币 - //return GContext.container.Resolve().GetPokerToken(); - case 12: - return GContext.container.Resolve().TicketCount; - // case 18: - // return GContext.container.Resolve().GatherData.TicketCount; - case 51: - //1v1门票 - return GContext.container.Resolve().GetDuelTickets(); - case 52: - return GContext.container.Resolve().PVPToken; - case 53: - return GContext.container.Resolve().ChainPackWithProgressMigrationData.TokenProgress; - case 15: - // 魔药 - return GContext.container.Resolve().GetToken(); - case 16: - // 弹珠 - return GContext.container.Resolve().GetToken(); - case 17: - var bingoModel = GContext.container.Resolve(); - if (bingoModel == null || !bingoModel.IsActivated) - { - Debug.LogWarning("[EventBingo] Try to get bingo token, but bingo model not found or not activated."); - return 0; - } - else - return GContext.container.Resolve().TicketCount; - - case 90: - return GContext.container.Resolve().GetTicketCount(); - case 21: - var pbManager = GContext.container.Resolve(); - if (pbManager == null) - return 0; - return pbManager.GetTicketCount(); - } - break; - case 3: - switch (item.SubType) - { - case 1: - return GContext.container.Resolve().GetRodPiece(item.RedirectID); - case 2: - return GContext.container.Resolve().GetRodPiece(item.ID); - } - break; - case 4: - if (item.SubType == 2) - { - return GContext.container.Resolve().GetCardDataProficiency(item.RedirectID); - } - break; - case 5: - return 0;//ntext.container.Resolve().GetPictureProgress(id); - case 6: - var _fishingEventData = GContext.container.Resolve(); - if (item.SubType == 1) - { - return _fishingEventData.GetWheelLevelCount(_fishingEventData.wheelLevel.Level); - } - else if (item.SubType == 3) - { - return new EventMatchGameManager().GetTokenCount(); - } - break; - case 7: - var bpDataProvider = GContext.container.Resolve(); - if (item.SubType == 3) - return bpDataProvider.Data.BattlePassRecord.Exp; - break; - case 8: - if (item.SubType == 2) - return GContext.container.Resolve().TurntableCoupon; - if (item.SubType == 3) - { - var data = GContext.container.Resolve(); - if (data == null) - { - Debug.LogWarning("It is very likely that event luck magic is not available at this time."); - return 0; - } - return data.TicketCount; - } - - return EventLuckyGameModel.Get().TicketCount; - case 9: - if (item.SubType == 2) - { - return GContext.container.Resolve().GetFishingBoxCount(item.RedirectID); - } - else - { - return 0; - } - case 10: - switch (item.SubType) - { - case 1: - case 11: - return GContext.container.Resolve().GetAllCollectingTarget(); - case 2: - case 12: - return GContext.container.Resolve().GetAllRankTarget(); - case 13: - return GContext.container.Resolve().DataModel.GetDigCount(); - case 14: - return 1;//小马皮纳塔棒 不需要计数 - } - break; - case 13: - // var handler = EventBreakAct.DrillModel; - var drillModel = GContext.container.Resolve(); - switch (item.SubType) - { - case 2: - return GContext.container.Resolve().AmmoCount; - case 3: - if (drillModel == null) - return defaultCount; - return drillModel.TicketCount; - case 6: - if (drillModel == null || drillModel.TaskInfoList == null || drillModel.TaskInfoList.Length <= 0) - return defaultCount; - return drillModel.TaskInfoList[0].CurrentGemProgress; - case 5: - if (drillModel == null || drillModel.TaskInfoList == null || drillModel.TaskInfoList.Length <= 1) - return defaultCount; - return drillModel.TaskInfoList[1].CurrentGemProgress; - case 4: - if (drillModel == null || drillModel.TaskInfoList == null || drillModel.TaskInfoList.Length <= 2) - return defaultCount; - return drillModel.TaskInfoList[2].CurrentGemProgress; - case 11: - // 刮刮乐 - return GContext.container.Resolve().GetToken(); - } - break; - case 15: - switch (item.SubType) - { - case 2: - return GContext.container.Resolve().GatherData.TicketCount; - case 3: - { - var arc = GContext.container.Resolve(); - if (arc == null || arc.Model == null) - return 0; - return arc.Model.TicketCount; - } - case 5: - { - var socialRushArc = GContext.container.Resolve(); - if (socialRushArc == null || socialRushArc.Model == null) - return 0; - return socialRushArc.Model.ProgressActual; - } - } - break; - default: - GameDebug.LogWarning( - $"[PlayerItemData]GetItemCount: Item ID({item.ID}) type({item.Type}) subType({item.SubType}) not handled"); - break; - } - - return defaultCount; - } - - public void ItemTransition(ItemData itemData) - { - FishingEvent fishingEvent; - FishingEventData fishingEventData = GContext.container.Resolve(); - if (itemData.id == 2005) - { - fishingEvent = fishingEventData.GetEventTable(4); - Item4ToEventItem(fishingEvent, itemData); - } - else if (itemData.id == 2050) - { - fishingEvent = fishingEventData.GetEventTable(5); - Item5ToEventItem(fishingEvent, itemData); - } - else if (itemData.id == 70000) - { - fishingEvent = fishingEventData.GetEventTable(7); - Item7ToEventItem(fishingEvent, itemData); - } - else if (itemData.id == 8000000) - { - fishingEvent = fishingEventData.GetEventTable(8); - Item8ToEventItem(fishingEvent, itemData); - } - else if (itemData.id == 15000000) - { - fishingEvent = fishingEventData.GetEventTable(15); - Item15ToEventItem(fishingEvent, itemData); - } - - //可能其他转换成1002 然后吃加成 - if (itemData.id == 1002) - { - itemData.count = GetExtraCoinMag(itemData.count); - } - if (itemData.id == 101000000) - { - //itemData.origin = itemData.count; - itemData.id = fishingEventData.collectingTargetInitTokenID; - //ItemInflation(itemData, fishingEventData.CollectingTargetInflation); - } - itemData.curCount = (ulong)GetItemCount(itemData.id); - } - - void ItemTransition(ItemData itemData, int ExchangeRate, int ItemId) - { - itemData.count = (int)Math.Round(itemData.count / (float)ExchangeRate, MidpointRounding.AwayFromZero); - if (itemData.count < 1) - { - itemData.count = 1; - } - itemData.id = ItemId; - } - void Item4ToEventItem(FishingEvent fishingEvent, ItemData itemData) - { - FishingEventCycleItem cycle; - if (fishingEvent != null) - { - if (fishingEvent.Type == 4) - { - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fishingEvent.RedirectID); - - if (cycle != null) - { - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - } - //没有活动时默认转换 - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(40000); - if (cycle != null) - { - itemData.count *= 1000; - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - void Item5ToEventItem(FishingEvent fishingEvent, ItemData itemData) - { - PvpEventCycleItem cycle; - if (fishingEvent != null) - { - if (fishingEvent.Type == 5) - { - cycle = _tables.TbPvpEventCycleItem. - DataList.Find(x => x.Type == fishingEvent.Type && x.SubType == fishingEvent.SubType); - if (cycle != null) - { - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - } - //没有活动时默认转换 - cycle = _tables.TbPvpEventCycleItem.DataList[0]; - if (cycle != null) - { - itemData.count *= 1000; - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - void Item7ToEventItem(FishingEvent fishingEvent, ItemData itemData) - { - FishingEventCycleItem cycle; - if (fishingEvent != null) - { - if (fishingEvent.Type == 7) - { - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fishingEvent.RedirectID); - if (cycle != null) - { - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - } - //没有活动时默认转换 - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(70000); - if (cycle != null) - { - itemData.count *= 1000; - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - - void Item8ToEventItem(FishingEvent fishingEvent, ItemData itemData) - { - FishingEventCycleItem cycle; - if (fishingEvent != null) - { - if (fishingEvent.Type == 8) - { - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fishingEvent.RedirectID); - - if (cycle != null) - { - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - } - //没有活动时默认转换 - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(8000000); - if (cycle != null) - { - itemData.count *= 1000; - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - - void Item15ToEventItem(FishingEvent fishingEvent, ItemData itemData) - { - FishingEventCycleItem cycle; - if (fishingEvent != null) - { - if (fishingEvent.Type == 15) - { - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(fishingEvent.RedirectID); - if (cycle != null) - { - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - } - //没有活动时默认转换 - cycle = _tables.TbFishingEventCycleItem.GetOrDefault(15000000); - if (cycle != null) - { - itemData.count *= 1000; - ItemTransition(itemData, cycle.ExchangeRate, cycle.ItemId); - return; - } - } - - public ItemData GetItemDataOne(int dropId, int index = 0) - { - DropPackageList dropPackageList = _tables.TbDrop.GetOrDefault(dropId)?.DropList; - if (dropPackageList == null) - { - GameDebug.LogError("null dropID" + dropId); - return null; - } - int len = dropPackageList.DropIDList.Count; - int len2 = dropPackageList.DropCountList.Count; - if (len != len2) - { - if (len > len2) - { - len = len2; - } - Debug.LogError($"[PlayerItemData]GetItemDataByDropIdAndType: DropPackageList count not equal [DropId]=={dropId}"); - } - if (index >= len) - { - return null; - } - ItemData itemData = new ItemData() - { - id = dropPackageList.DropIDList[index], - count = dropPackageList.DropCountList[index] - }; - - ItemTransition(itemData); - - return itemData; - } - /// - /// 处理有选定地图鱼卡的情况 - /// - /// - public List GetItemDataByDropId(int dropId, int mapId = -1, bool afterAdding = false) - { - var drop = _tables.TbDrop.GetOrDefault(dropId); - DropPackageList dropPackageList = drop?.DropList; - if (dropPackageList == null) - { - GameDebug.LogError("null dropID" + dropId); - return null; - } - - List itemDataList = new List(); - if (drop.Type == DropType.Beta) - { - Debug.LogError($"[PlayerItemData] DropType == DropType.Beta user [GetItemDataByDropIdAndType]"); - return null; - } - - int len = dropPackageList.DropIDList.Count; - int len2 = dropPackageList.DropCountList.Count; - if (len != len2) - { - if (len > len2) - { - len = len2; - } - Debug.LogError($"[PlayerItemData]GetItemDataByDropId: DropPackageList count not equal [DropId]=={dropId}"); - } - - for (int i = 0; i < len; i++) - { - var itemID = dropPackageList.DropIDList[i]; - if (mapId > 0) - { - var item = _tables.TbItem.GetOrDefault(itemID); - if (item.Type == 5 && item.SubType == 4) - { - itemID = GetFishCardItemIdByRedirectIDAndMapId(item.RedirectID - 1, mapId); - } - } - ItemData itemData = new ItemData() - { - id = itemID, - count = dropPackageList.DropCountList[i] - }; - ItemTransition(itemData); - if (afterAdding && itemData.curCount >= (ulong)itemData.count) - { - itemData.curCount -= (ulong)itemData.count; - } - itemDataList.Add(itemData); - } - - return itemDataList; - } - public int GetExtraCoinMag(float number) - { - PlayerData playerData = GContext.container.Resolve(); - float mg = (1 + playerData.benefitsCashMag) * (1 + playerData.benefitsCashMagLimited); - number *= mg; - int targetCount = Mathf.RoundToInt(number); - if (targetCount < 0) - { - targetCount = int.MaxValue; - Debug.LogError($" ExtraCoinMag overflow {number} {mg} {targetCount}"); - } - return targetCount; - } - public float ExtraCoinMag() - { - PlayerData playerData = GContext.container.Resolve(); - float mg = (1 + playerData.benefitsCashMag) * (1 + playerData.benefitsCashMagLimited); - return mg; - } - //获取地图的加成 - //public float GetExtraCoinMag() - //{ - // float ExtraCoinMag = 0; - // //地图加成 - // MapData data = _tables.TbMapData.GetOrDefault(GContext.container.Resolve().lastMapId); - // if (data != null) - // { - // ExtraCoinMag = data.CashMag; - // } - // //float mcCoinMag = GContext.container.Resolve().GetPrivilege2(); - // //ExtraCoinMag += mcCoinMag; - // return ExtraCoinMag; - //} - - public List GetItemDataByDropIdAndType(int dropId, int mapId = -1) - { - List itemDataList = new List(); - Drop drop = _tables.TbDrop.GetOrDefault(dropId); - if (drop == null) - { - GameDebug.LogError("null dropID" + dropId); - return null; - } - DropPackageList dropList = drop.DropList; - int len = dropList.DropIDList.Count; - int len2 = dropList.DropCountList.Count; - int len3 = dropList.DropProbList.Count; - if (drop.Type == DropType.Beta) - { - len2 /= 2; - len3 /= 2; - } - if (len != len2 || len2 != len3) - { - Debug.LogError($"[PlayerItemData] DropPackageList count not equal [DropId]=={dropId} DropIDList=={len} DropCountList=={len2} DropProbList=={len3}"); - if (len2 < len) - { - len = len2; - } - - if (len3 < len) - { - len = len3; - } - } - if (drop.Type == DropType.Probability) - { - Dictionary itemDataSubList = new Dictionary(); - for (int i = 0; i < len; i++) - { - if (Mathf.Ceil(dropList.DropProbList[i] * 100) >= UnityEngine.Random.Range(0, 100) - 0.00001f) - { - if (itemDataSubList.ContainsKey(dropList.DropIDList[i])) - { - itemDataSubList[dropList.DropIDList[i]] += dropList.DropCountList[i]; - } - else - { - itemDataSubList.Add(dropList.DropIDList[i], dropList.DropCountList[i]); - } - } - } - - foreach (var itemDataSub in itemDataSubList) - { - itemDataList.Add(new ItemData() - { - id = itemDataSub.Key, - count = itemDataSub.Value - }); - } - } - else if (drop.Type == DropType.Weight) - { - float totalSum = dropList.DropProbList.Sum(); - float random = UnityEngine.Random.Range(0, totalSum); - float sum = 0; - for (int i = 0; i < len; i++) - { - sum += dropList.DropProbList[i]; - if (random <= sum - 0.00001f) - { - if (dropList.DropIDList[i] > 0) - { - itemDataList.Add(new ItemData() - { - id = dropList.DropIDList[i], - count = dropList.DropCountList[i] - }); - } - break; - } - } - } - else if (drop.Type == DropType.Beta) - { - int minCount; - int maxCount; - float betaA; - float betaB; - double b; - int count; - int id; - for (int i = 0; i < len; i++) - { - minCount = dropList.DropCountList[i * 2]; - maxCount = dropList.DropCountList[i * 2 + 1]; - id = dropList.DropIDList[i]; - if (minCount == maxCount) - { - count = minCount; - } - else - { - betaA = dropList.DropProbList[i * 2]; - betaB = dropList.DropProbList[i * 2 + 1]; - b = Beta.Sample(betaA, betaB); - count = minCount + (int)((maxCount - minCount) * b); - GameDebug.Log($"[DropType.Beta] dropID == {dropId} itemID == {id} DropType.Beta == {b}"); - } - count = BetaRoundingStep(id, count); - ItemData itemData = new ItemData() - { - id = id, - count = count - }; - itemDataList.Add(itemData); - } - } - else - { - for (int i = 0; i < len; i++) - { - itemDataList.Add(new ItemData() - { - id = dropList.DropIDList[i], - count = dropList.DropCountList[i] - }); - } - } - - for (int i = 0; i < itemDataList.Count; i++) - { - if (mapId > 0) - { - var item = _tables.TbItem.GetOrDefault(itemDataList[i].id); - if (item.Type == 5 && item.SubType == 4) - { - itemDataList[i].id = GetFishCardItemIdByRedirectIDAndMapId(item.RedirectID - 1, mapId); - } - } - - ItemTransition(itemDataList[i]); - } - return itemDataList; - } - public int BetaRoundingStep(int id, int count) - { - List roundingStep = null; - if (id == 1001) - { - roundingStep = _tables.TbGlobalConfig.BetaLureRoundingStep; - } - else if (id == 1002) - { - roundingStep = _tables.TbGlobalConfig.BetaCashRoundingStep; - } - if (roundingStep != null && roundingStep.Count > 2) - { - int stepCount = roundingStep.Count / 2; - int step = roundingStep[stepCount * 2]; - for (int i = 0; i < stepCount; i++) - { - if (count <= roundingStep[i]) - { - step = roundingStep[i + stepCount]; - break; - } - } - int a = count / step; - int b = count % step; - count = a * step; - if (b > 0) - { - float r = b / (float)step; - if (UnityEngine.Random.value < r) - { - count += step; - } - } - } - return count; - } - public async void ShowItemTips(int id, Transform trans, float count = -1, float inflate = 0) - { //物品详情弹窗 - Item item = _tables.TbItem.GetOrDefault(id); - if (item.Type == 9 && (item.SubType == 7 || item.SubType == 8)) - { - try - { - if (item.SubType == 7) - { - item_sanddig_tips.Show(trans.position, item.RedirectID, inflate); - } - else - { - item_sanddig_tips.ShowBeta(trans.position, item.RedirectID, inflate); - } - } - catch (System.Exception e) - { - Debug.LogError($"[PlayerItemData]ShowItemTips: Error showing sand dig tips for item ID {id}: {e.Message}"); - } - } - else if (item.Type == 12) - { - GameObject go = await UIManager.Instance.ShowUI(UITypes.PlayerGradeBenefitInfoPopupPanel); - PlayerGradeBenefitInfoPopupPanel panel = go.GetComponent(); - panel.Init(item, Mathf.RoundToInt(count)); - } - else if (item.Type == 11 && item.SubType == 1) - { - var buff = _tables.TbFishBuff.GetOrDefault(item.RedirectID); - GameObject go = await UIManager.Instance.ShowUI(UITypes.FishingBuffInfoPopupPanel); - FishingBuffInfoPopupPanel fishingBuffInfoPopupPanel = go.GetComponent(); - fishingBuffInfoPopupPanel.InitPanel(buff); - } - else - { - var curCount = GetItemCount(item, -1); - if (curCount > -0.5f) - { - item_tips _item_tips = await item_tips.Show(); - if (_item_tips == null /*|| trans.gameObject.GetInstanceID() == _item_tips.clickInstanceID*/) - { - return; - } - _item_tips.Init(trans.gameObject.GetInstanceID(), trans.position, item, curCount, inflate); - } - } - } - - public List ShowItemDropPackage(ItemDropPackage itemDropPackage) - { - var ItemDisplay = itemDropPackage.ItemDisplay; - List CountDisplay = new List(itemDropPackage.CountDisplay); - for (int i = 0; i < ItemDisplay.Count; i++) - { - if (ItemDisplay[i] == 1002) - { - string[] strings = CountDisplay[i].Split('-'); - if (strings.Length != 2) - { - if (float.TryParse(strings[0], out float ab)) - { - ab = GetExtraCoinMag(ab); - CountDisplay[i] = ConvertTools.GetNumberString((int)ab); - } - continue; - } - if (!float.TryParse(strings[0], out float a) || !float.TryParse(strings[1], out float b)) - { - continue; - } - - a = GetExtraCoinMag(a); - b = GetExtraCoinMag(b); - CountDisplay[i] = $"{ConvertTools.GetNumberString((int)a)}-{ConvertTools.GetNumberString((int)b)}"; - } - } - return CountDisplay; - } - - public int GetFishCardItemIdByRedirectIDAndMapId(int index, int mapID) - { - var cardList = _tables.TbMapData.GetOrDefault(mapID).FishCardItemList; - var fishCardId = cardList[index]; - return fishCardId; - - } - public int GetFishCardItemIdByItemIDAndMapId(int itemID, int mapID) - { - Item item = _tables.TbItem.GetOrDefault(itemID); - return GetFishCardItemIdByRedirectIDAndMapId(item.RedirectID - 1, mapID); - } - /// - /// Get iap item list and text price string by iap id. - /// - /// - /// - /// - public void ResolveIapId(in int iapId, out IAPItemList iapItemList, out string price) - { - var doesIapExist = _tables.TbIAPItemList.DataMap.TryGetValue(iapId, out iapItemList); - if (!doesIapExist) - { - Debug.LogError($"IapId {iapId} not found in iap list."); - price = ""; - return; - } - var sdde = new SKUDetailDataEvent(iapItemList); - GContext.Publish(sdde); - price = sdde.price; - } - /// - /// Get iap item list and set text price by iap id. - /// - /// - /// - /// - public void ResolveIapId(in int iapId, out IAPItemList iapItemList, TMP_Text textPrice) - { - var doesIapExist = _tables.TbIAPItemList.DataMap.TryGetValue(iapId, out iapItemList); - if (!doesIapExist) - { - Debug.LogError($"IapId {iapId} not found in iap list."); - textPrice.text = ""; - return; - } - var sdde = new SKUDetailDataEvent(iapItemList); - GContext.Publish(sdde); - textPrice.text = sdde.price; - } - - public ItemData GetRandomItemDataByDropId(System.Random rng, int dropId, int mapId = -1) - { - Drop drop = _tables.TbDrop.GetOrDefault(dropId); - if (drop == null) - { - GameDebug.LogError("null dropID" + dropId); - return null; - } - DropPackageList dropList = drop.DropList; - var itemData = new ItemData() { id = dropList.DropIDList[0], count = dropList.DropCountList[0] };// Just in case. - int len = dropList.DropIDList.Count; - int len2 = dropList.DropCountList.Count; - int len3 = dropList.DropProbList.Count; - if (len != len2 || len2 != len3) - { - Debug.LogError($"[PlayerItemData] DropPackageList count not equal [DropId]=={dropId} DropIDList=={len} DropCountList=={len2} DropProbList=={len3}"); - if (len2 < len) - { - len = len2; - } - - if (len3 < len) - { - len = len3; - } - } - if (drop.Type == DropType.Weight) - { - float totalSum = dropList.DropProbList.Sum(); - // float random = Random.Range(0, totalSum); - float random = (float)rng.NextDouble() * totalSum; - float sum = 0; - for (int i = 0; i < len; i++) - { - sum += dropList.DropProbList[i]; - if (random <= sum - 0.00001f) - { - itemData = new ItemData() { id = dropList.DropIDList[i], count = dropList.DropCountList[i] }; - break; - } - } - } - else - { - Debug.Log($"[PlayerItemData] Drop id {dropId} is not a drop with weight. This is likely a wrong call."); - return null; - } - - - if (mapId > 0) - { - var item = _tables.TbItem.GetOrDefault(itemData.id); - if (item.Type == 5 && item.SubType == 4) - { - itemData.id = GetFishCardItemIdByRedirectIDAndMapId(item.RedirectID - 1, mapId); - } - } - - ItemTransition(itemData); - - return itemData; - } - - } - public class DropFishCardData - { - public int ItemID; - public ItemData exchangeItemData; - public List FishCardItemList; - } - /// - /// 一般情况下,添加物品的 AddItem…… 传入 changeSource 就行 - /// 如果一次添加多个 Item 有不同的来源设置 changeSource 传入 null ,设置每一个ItemData.changeSource - /// - public class ChangeSource - { - public ChangeSource(int Source_EventId, string Source_Group, string Source_Type, string Source_Module) - { - this.Source_EventId = Source_EventId; - this.Source_Group = Source_Group; - this.Source_Type = Source_Type; - this.Source_Module = Source_Module; - } - public int Source_EventId; - public string Source_Group; - public string Source_Type; - public string Source_Module; - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/013-DataCenter.PlayerShopData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/013-DataCenter.PlayerShopData.cs.txt deleted file mode 100644 index 6addb4e73..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/013-DataCenter.PlayerShopData.cs.txt +++ /dev/null @@ -1,1426 +0,0 @@ -using game.PlayerDataStorage; -using asap.core; -using cfg; -using CodeStage.AntiCheat.ObscuredTypes; -using game; -using LitJson; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using tysdk; -using UniRx; -using UnityEngine; - -namespace GameCore -{ - public class SKUDetailDataEvent - { - public SKUDetailDataEvent(IAPItemList iap) - { - this.iap = iap; - } - public IAPItemList iap; - public string price; - public float prodPrice; - } - public enum ShopBuyType - { - None = 0, - ShopToken = 1, - ShopPackDailyBuy = 2, - EventPack = 3, - TriggerPack = 4, - } - public class ShopBuyTypeData - { - public ShopBuyType type = ShopBuyType.ShopToken; - /// - /// ShopToken = ID 记录是否买过(首次有赠送) 获取IAPID - /// EventPack = Event活动ID,具体数据处理 FishingEventData.OnBuyEventPack - /// TriggerPack = TriggerPackManager.ID,购买删除礼包 - /// ShopPack = ShopPackManager.ID 根据类型处理 type = 3 礼包链增加次数 - /// - public int ID; - /// - /// 每日礼包记录key - /// - public string key;//自定义数据 - /// - /// 非Event礼包的结束时间,以天为单位 - /// - public int endDay;//自定义数据 - public JObject extraPurcheData; - public bool IsHide;//不自动塞入 ShowData 展示队列 - [NonSerialized] - public bool NoShow;//不自动展示 ShowData 展示队列 - } - public class ReplenishmentData - { - public ShopBuyTypeData BuyType; - public int IAPID; - public List ItemData; - public RewardType ShowType; - //以下是打点信息 - public string CONTENT_ID; - public float PRICE; - public string CURRENCY; - public float ProdPrice; - public JObject extraPurcheData; - public string orderId; - public string time; - } - public partial class PlayerShopData : IDisposable - { - game.PlayerDataStorage.IPlayerSaveStore boundSaveStore; - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore - { - get => boundSaveStore; - set { CouponData.BindSaveStore(value); boundSaveStore = value; } - } - - [Inject] - public cfg.Tables _tables { get; set; } - [Inject] - public IIAPService IAPService { get; set; } - public const int freeRefreshTime = 8; - IList SKUDetails; - Dictionary SKUDetailDataMap = new Dictionary(); - Dictionary PackManagerMap = new Dictionary(); - List PackManagerataList = new List(); - List buyData = new List(); - - //ShopPack每日购买次数 - public Dictionary shopPackDailyBuyCount = new Dictionary(); - // Pack全部购买次数 - public Dictionary shopAllPackBuyCount = new Dictionary(); - // 金币鱼饵礼包购买次数 - public Dictionary shopGiftBuyCount = new Dictionary(); - public int shopTipforUnlocked; - public int vipTipforUnlocked; - public EventPackManager chainPackM; - public DailySignEvent ChainPackData; - public AdvertData VIPAdPackData; - public ObscuredInt Voucher { get; private set; } - // public bool IsShopOpen = false; - public bool IsShopTopOpen = false; - public bool IsVIPOpen = false; - DateTime CreateTime; - //待释放 - CompositeDisposable disposables = null; - List ReplenishmentDatas = new List(); - Dictionary replenishmentDataStrs = new Dictionary(); - - //const string ReplenishmentDataKey = "ReplenishmentDataStr"; - //const string OldReplenishmentDataKey = "OldReplenishmentDataKey"; - - public readonly BlackFridayCouponData CouponData = new BlackFridayCouponData(); - - #region Diamond Shop - //Diamond Shop - public bool IsShopOpen = false; - private Dictionary _diamondShopItemRecords = new(); - private int _diamondShopRefreshCount; - private DateTime _diamondShopRefreshTime; - - #endregion - - #region 广告次数 - /// - /// -2 广告券数量 -1 数据所属天数 0 总广告次数 - /// - Dictionary advertCount = new Dictionary(); - #endregion - - internal static game.PlayerDataStorage.PlayerKVShopState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) - => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeShop(raw,snapshot,errors); - internal void ResetForKVLoad() - { - shopPackDailyBuyCount=new Dictionary(StringComparer.Ordinal); shopAllPackBuyCount=new Dictionary(); - shopGiftBuyCount=new Dictionary(); buyData=new List(); advertCount=new Dictionary(); - Voucher=0; ChainPackData=null; VIPAdPackData=null; TurntableAdData=null; - _diamondShopItemRecords=new Dictionary(); _diamondShopRefreshCount=0; _diamondShopRefreshTime=default; - CouponData.ResetForKVLoad(); - } - static DailySignEvent KVDaily(game.PlayerDataStorage.PlayerKVDailyValue value) => value==null ? null : - new DailySignEvent { ID=value.Id,index=value.Index,lastID=value.LastId,time=value.Time }; - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVShopState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - shopPackDailyBuyCount=state.Daily.ToDictionary(p=>p.Key,p=>p.Value,StringComparer.Ordinal); - shopAllPackBuyCount=state.All.ToDictionary(p=>p.Key,p=>p.Value); shopGiftBuyCount=state.Gift.ToDictionary(p=>p.Key,p=>p.Value); - advertCount=state.Advert.ToDictionary(p=>p.Key,p=>p.Value); buyData=new List(state.Buy); Voucher=state.Voucher; - ChainPackData=KVDaily(state.Chain); TurntableAdData=KVDaily(state.Turntable); - VIPAdPackData=state.Vip==null ? null : new AdvertData { ID=state.Vip.Id,index=state.Vip.Index,day=state.Vip.Day,cdTime=state.Vip.Time,isOpen=state.Vip.Open }; - _diamondShopItemRecords=state.Items.ToDictionary(p=>p.Key,p=>new ItemShopRecord(p.Value.Id,p.Value.Discount,p.Value.Bought)); - _diamondShopRefreshCount=state.RefreshCount; _diamondShopRefreshTime=state.RefreshTime; CouponData.ReplaceFromKVDecoded(state.Coupon); - } -#if UNITY_EDITOR - internal game.PlayerDataStorage.PlayerKVShopState SnapshotForKVValidation() - { - game.PlayerDataStorage.PlayerKVDailyValue Daily(DailySignEvent v) => v==null ? null : new game.PlayerDataStorage.PlayerKVDailyValue(v.ID,v.index,v.lastID,v.time); - return new game.PlayerDataStorage.PlayerKVShopState(shopPackDailyBuyCount,shopAllPackBuyCount,shopGiftBuyCount,advertCount, - _diamondShopItemRecords.ToDictionary(p=>p.Key,p=>new game.PlayerDataStorage.PlayerKVShopItemValue(p.Value.ItemID,p.Value.Discount,p.Value.hasBought)), - buyData,Voucher,_diamondShopRefreshCount,_diamondShopRefreshTime,Daily(ChainPackData),Daily(TurntableAdData), - VIPAdPackData==null ? null : new game.PlayerDataStorage.PlayerKVAdvertValue(VIPAdPackData.ID,VIPAdPackData.index,VIPAdPackData.day,VIPAdPackData.cdTime,VIPAdPackData.isOpen), - new game.PlayerDataStorage.PlayerKVCouponState(CouponData.ActivateTime,CouponData.EventId,CouponData.RedirectId,CouponData.IsBought)); - } - internal void MutateCollectionsForKVValidation() - { buyData.Clear(); advertCount.Clear(); _diamondShopItemRecords.Values.First().Discount=99; } -#endif - - public void InitData(Dictionary userDatas) - { - if (userDatas == null || userDatas.Count < 1) - { - return; - } - string data_value; - if (userDatas.TryGetValue("ShopPackBuyCount", out data_value)) - { - shopPackDailyBuyCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("ShopAllPackBuyCount", out data_value)) - { - shopAllPackBuyCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("ShopGiftBuyCount", out data_value)) - { - shopGiftBuyCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - - if (userDatas.TryGetValue("Voucher", out data_value)) - { - InitVoucher(GlobalUtils.TryParseInt(data_value)); - } - if (userDatas.TryGetValue("ChainPackDataNew", out data_value)) - { - SetChainPackData(Newtonsoft.Json.JsonConvert.DeserializeObject(data_value)); - } - if (userDatas.TryGetValue("VIPAdPackData", out data_value)) - { - SetVIPAdPackData(Newtonsoft.Json.JsonConvert.DeserializeObject(data_value)); - } - if (userDatas.TryGetValue("TurntableAdData", out data_value)) - { - TurntableAdData = Newtonsoft.Json.JsonConvert.DeserializeObject(data_value); - } - //if (userDatas.TryGetValue("FishCardPackData", out data_value)) - //{ - // SetFishCardPackData(data_value); - //} - - if (userDatas.TryGetValue("BuyData", out data_value)) - { - buyData = Newtonsoft.Json.JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue("AdvertAllCount", out data_value)) - { - InitAdvertCount(data_value); - } - - if (userDatas.TryGetValue("DiamondShopRefreshCount", out data_value)) - { - _diamondShopRefreshCount = (int.Parse(data_value)); - } - if (userDatas.TryGetValue("DiamondShopRefreshTime", out data_value)) - { - _diamondShopRefreshTime = DateTime.Parse(data_value); - } - if (userDatas.TryGetValue("DiamondShopItemRecords", out data_value)) - { - _diamondShopItemRecords = JsonConvert.DeserializeObject>(data_value); - } - - if (userDatas.TryGetValue(BlackFridayCouponData.PlayFabDataKey, out data_value)) - { - // Debug.Log($"Black Friday load data!!"); - CouponData.LoadData(data_value); - } - } - - public float GetBuyPaymentAmount() - { - if (buyData.Count > 0) - { - return buyData[0]; - } - return 0; - } - - public void AddVoucher(int value) - { - Voucher = Voucher + value; - SaveStore.Write("Voucher", Voucher.ToString()).RequireAccepted(); - } - public void Init() - { - PackManagerMap = _tables.TbShopPackManager.DataMap; - PackManagerataList = _tables.TbShopPackManager.DataList; - - CreateTime = GContext.container.Resolve().CreateTime; - InitShopPackData(); - ClearAdvertCount(); - if (disposables == null) - { - disposables = new CompositeDisposable(); - GContext.OnEvent().Subscribe(GetIAPPrice).AddTo(disposables); - } - GetSKUs(); - } - - private static System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[A-Z]+"); - private string RemoveCurrencyCode(string price) - { - return regex.Replace(price, string.Empty); - } - - public async void GetSKUs() - { - Debug.Log("[DataCenter.PlayerData] GetSKUList fetch"); - if (!SaveSessionCurrent) return; - var details = await IAPService.GetSKUs(); - if (!SaveSessionCurrent) return; - SKUDetails = details; - SKUDetailDataMap.Clear(); - if (SKUDetails != null && SKUDetails.Count > 0) - { - for (int i = 0; i < SKUDetails.Count; i++) - { - if (!SKUDetailDataMap.ContainsKey(SKUDetails[i].ProdKey)) - { -#if UNITY_ANDROID || UNITY_EDITOR - var price = SKUDetails[i].price; - SKUDetails[i].price = RemoveCurrencyCode(price); -#endif - SKUDetailDataMap.Add(SKUDetails[i].ProdKey, SKUDetails[i]); - } - } - } - } - - - void GetIAPPrice(SKUDetailDataEvent data) - { - if (data.iap != null) - { - if (SKUDetailDataMap.TryGetValue(data.iap.ProductId1, out var v)) - { - -#if UNITY_ANDROID || UNITY_EDITOR - data.price = v.ProdPriceStr; -#else - data.price =$"{v.localeCurrencySymbol}{v.price}"; -#endif - -#if UNITY_EDITOR - data.prodPrice = data.iap.PaymentAmount; -#else - data.prodPrice = v.ProdPrice; -#endif - } - else - { - data.prodPrice = data.iap.PaymentAmount; - data.price = $"US${data.iap.PaymentAmount}"; - } - } - else - { - data.price = LocalizationMgr.GetText("UI_TurntableInfoPopupPanel_10"); - } - } - public ShopPackManager TbPackManagerGetOrDefault(int id) - { - return PackManagerMap.TryGetValue(id, out var v) ? v : null; - } - - - public void InitVoucher(int value) - { - Voucher = value; - } - - private JObject GenExtraPurcheData(int dropID, IAPItemList iAPItemList, List itemDataGift) - { - int buyDataCount = buyData.Count; - var extraPurcheData = new JObject(); - extraPurcheData["purchase_count"] = buyDataCount == 0 ? 1 : buyDataCount; - extraPurcheData["trade_name"] = iAPItemList.TradeName; - extraPurcheData["trade_type"] = iAPItemList.TradeType; - extraPurcheData["usd_price"] = iAPItemList.PaymentAmount; - extraPurcheData["iap_id"] = iAPItemList.ID; - extraPurcheData["drop_id"] = dropID; - extraPurcheData["trade_group"] = iAPItemList.TradeGroup; - - if (itemDataGift != null) - { - for (int i = 0; i < itemDataGift.Count; i++) - { - extraPurcheData[$"item_{itemDataGift[i].id}"] = itemDataGift[i].count; - } - } - - return extraPurcheData; - } - - bool purchasePending, disposed; - readonly HashSet rewardedOrders = new HashSet(StringComparer.Ordinal); - readonly HashSet sdkOrders = new HashSet(StringComparer.Ordinal); - bool SaveSessionCurrent => !disposed && SaveStore.IsCurrent; - public async Task OnBuy(int dropID, ShopBuyTypeData buyType, IAPItemList iAPItemList, List itemDataGift, RewardType rewardShowType = RewardType.Normal) - { - if (!SaveSessionCurrent || purchasePending) return false; - if (SaveStore is KVPlayerSaveStore && !SaveStore.Read("NewPlayerDataDic").Success) return false; - purchasePending = true; - try - { - bool result = await BuyAndSaveAsync(dropID, buyType, iAPItemList, itemDataGift, rewardShowType); - if (!SaveSessionCurrent) return false; - purchasePending = false; - return result; - } - catch (Exception e) { Debug.LogException(e); return false; } - } - async Task BuyAndSaveAsync(int dropID, ShopBuyTypeData buyType, IAPItemList iAPItemList, List itemDataGift, RewardType rewardShowType) - { - if (iAPItemList == null) return false; - var player = GContext.container.Resolve(); - if (Voucher >= iAPItemList.CostToken) - { - await PlayerSaveAction.RunAsync(SaveStore, "shop-voucher", () => - { - Voucher = Voucher - iAPItemList.CostToken; - SaveStore.Write("Voucher", Voucher.ToString()).RequireAccepted(); - //二次弹窗 - //回调 - SaveStore.Write("LastPaymentTime", $"{ZZTimeHelper.UtcNow()}__{0}").RequireAccepted(); - BuySuccess(buyType, iAPItemList, itemDataGift, rewardShowType, true); - OrderManager.OrderManager.OnOrderSuccess(buyType, iAPItemList, itemDataGift, rewardShowType, true); - if (!buyType.NoShow) - { - PlayerSaveAction.Present(() => GContext.Publish(new ShowData())); - } - }, () => player.SavePlayerData()); - return true; - } - else if (SKUDetailDataMap.TryGetValue(iAPItemList.ProductId1, out SKUDetail sku)) - { - //充值购买平台 - GameDebug.Log($"IAP_ID:{iAPItemList.ID}Price:${iAPItemList.PaymentAmount}"); - - var extraPurcheData = GenExtraPurcheData(dropID, iAPItemList, itemDataGift); -#if !UNITY_EDITOR - if (iAPItemList.PaymentAmount <= 0.5f || sku.ProdPrice <= 0.5f) - return false; -#endif - - //在这里存补单数据 - ReplenishmentData replenishmentData = new ReplenishmentData() - { - BuyType = buyType, - ItemData = itemDataGift, - IAPID = iAPItemList.ID, - ShowType = rewardShowType, - CONTENT_ID = sku.ProdID, - CURRENCY = sku.price_currency_code, -#if !UNITY_EDITOR - ProdPrice = sku.ProdPrice, -#endif - PRICE = iAPItemList.PaymentAmount, - extraPurcheData = extraPurcheData, - //orderId = orderId; - time = ZZTimeHelper.UtcNow().ToString() - }; - - string replenishmentDataStr = JsonConvert.SerializeObject(replenishmentData); - - //付费成功的回调,可能购买成功之后也会调用一次 - Action OnSuccessFromSdk = (orderId) => - { - if (!SaveSessionCurrent || string.IsNullOrEmpty(orderId) || !sdkOrders.Add(orderId)) return; - switch (buyType.type) - { - case ShopBuyType.ShopToken: - //商店首次购买记录 - OnShopTokenSuccess(buyType.ID, true); - break; - } - }; - - PaymentInfo result = await IAPService.Pay(OnSuccessFromSdk, replenishmentDataStr, - sku, 1, iAPItemList.PaymentAmount, extraPurcheData); - if (!SaveSessionCurrent) return false; - - if (result.isSuccess) - { - if (SaveStore is KVPlayerSaveStore && string.IsNullOrEmpty(result.orderId)) - throw new InvalidOperationException("Confirmed payment requires its original order ID."); - if (!string.IsNullOrEmpty(result.orderId) && !rewardedOrders.Add(result.orderId)) return false; - await PlayerSaveAction.RunAsync(SaveStore, "shop-order:" + result.orderId, () => - { - SaveStore.Write("LastPaymentTime", $"{ZZTimeHelper.UtcNow()}__{sku.price}").RequireAccepted(); - BuySuccess(buyType, iAPItemList, itemDataGift, rewardShowType); - OrderManager.OrderManager.OnOrderSuccess(buyType, iAPItemList, itemDataGift, rewardShowType); - if (!buyType.NoShow) - { - PlayerSaveAction.Present(() => GContext.Publish(new ShowData())); - } - }, () => player.SavePlayerData()); - return true; - } - else - { - if (result.isSuccessFromSdk || result.code == "10000") - { - GameObject go = await UIManager.Instance.ShowUI(UITypes.NoticeConfirmPopupPanel); - if (!SaveSessionCurrent) return false; - var NoticeConfirmPopupPanel = go.GetComponent(); - string info = LocalizationMgr.GetText("UI_ToastPanel_ErrCode_1"); - string title = LocalizationMgr.GetText("UI_FishingShopPanel_25"); - NoticeConfirmPopupPanel.Init(1, title, info); - } - else - { - switch (result.code) - { - case "10001": - { - GameObject go = await UIManager.Instance.ShowUI(UITypes.NoticeConfirmPopupPanel); - if (!SaveSessionCurrent) return false; - var NoticeConfirmPopupPanel = go.GetComponent(); - string info = LocalizationMgr.GetText("UI_FishingShopPanel_28"); - string title = LocalizationMgr.GetText("UI_FishingShopPanel_27"); - NoticeConfirmPopupPanel.Init(1, title, info); - } - break; - case "10002": - { - GameObject go = await UIManager.Instance.ShowUI(UITypes.NoticeConfirmPopupPanel); - if (!SaveSessionCurrent) return false; - var NoticeConfirmPopupPanel = go.GetComponent(); - string info = LocalizationMgr.GetText("UI_ToastPanel_ErrCode_1"); - string title = LocalizationMgr.GetText("UI_FishingShopPanel_25"); - NoticeConfirmPopupPanel.Init(1, title, info); - } - break; - default: - ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_2")); - break; - } - } - return false; - } - } - else - { - ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_28")); - return false; - } - } - - /// - /// 商店购买记录 - /// - /// - /// 是付费成功 还是验证成功 - void OnShopTokenSuccess(int id, bool isFromSdk) - { - var shopToken = _tables.TbShopToken.GetOrDefault(id); - if (shopToken != null) - { - if (isFromSdk) - { - //商店物品购买付费成功的回调记录 ShopTokenID - AddShopGiftBuyCount(id); - } - else - { - //商店物品购买付费成功并验证通过的回调记录 IAPItemListID - AddShopGiftBuyCount(shopToken.IAPID); - - if (shopToken.Type == 3) - { - //钻石付费成功 或者购买成功 - if (CouponData.IsActive) - { - CouponData.SetStateBought(); - } - } - } - - } - } - public async System.Threading.Tasks.Task GetReplenishmentData() - { - //补单信息从服务器拿 - if (!SaveSessionCurrent) return; - var orders = await IAPService.GetOrderUnreceived(); - if (!SaveSessionCurrent) return; - replenishmentDataStrs = orders; - } - - public async System.Threading.Tasks.Task ReleaseReplenishment() - { - if (!SaveSessionCurrent) return; - ReplenishmentDatas.Clear(); - if (replenishmentDataStrs == null || replenishmentDataStrs.Count == 0) - { - return; - } - List orderIDList = new List(); - foreach (var item in replenishmentDataStrs) - { - //服务器判断是否支付 - ReplenishmentData replenishment = JsonConvert.DeserializeObject(item.Value); - replenishment.orderId = item.Key; - ReplenishmentDatas.Add(replenishment); - orderIDList.Add(item.Key); - } - bool result = await IAPService.ConfirmOrders(orderIDList); - if (!SaveSessionCurrent) return; - if (!result) - { - //服务器返回错误 - ReplenishmentDatas.Clear(); - } - } - - public void ReleaseReplenishmentData() - { - if (ReplenishmentDatas.Count > 0) - { - //确认补单 删除订单 - for (int i = 0; i < ReplenishmentDatas.Count; i++) - { - try - { - Replenishment(ReplenishmentDatas[i]); - } - catch (Exception ex) - { - Debug.LogError($"Replenishment Exception:{ex}"); - } - } - replenishmentDataStrs.Clear(); - ReplenishmentDatas.Clear(); - } - } - - private string payment => ChannelManager.IsRustoreStore ? "rustore" : "google"; - void Replenishment(ReplenishmentData data) - { - IAPItemList iAPItemList = _tables.TbIAPItemList.GetOrDefault(data.IAPID); - data.ShowType = RewardType.NormalRestore; - var itemDataGift = data.ItemData; - - var config = GContext.container.Resolve(); - var s2s = config.Get("AFS2S", "Off").ToLower() == "on"; - using (var e = GEvent.RevenueEvent(s2s)) - { - e.AddContent(AFInAppEvents.CONTENT_ID, data.CONTENT_ID) - .AddContent(AFInAppEvents.PRICE, data.PRICE) - .AddContent(AFInAppEvents.CURRENCY, data.CURRENCY) -#if UNITY_ANDROID - .AddContent("payment", payment) -#else - .AddContent("payment", "apple") -#endif - .AddContent(AFInAppEvents.QUANTITY, 1) - .AddContent("order_id", data.orderId) - .AddContent("payment_state", "finish") - .AddContent("restore", true) - .AddContent("af_revenue", data.ProdPrice); - - int buyDataCount = buyData.Count; - data.extraPurcheData["purchase_count"] = buyDataCount == 0 ? 1 : buyDataCount; - - if (null != data.extraPurcheData) - { - foreach (var item in data.extraPurcheData) - { - e.AddContent(item.Key, item.Value); - } - } - } - SaveStore.Write("LastPaymentTime", $"{ZZTimeHelper.UtcNow()}__{data.ProdPrice}").RequireAccepted(); - BuySuccess(data.BuyType, iAPItemList, itemDataGift, data.ShowType); - if (data.BuyType.extraPurcheData != null) - { - OrderManager.OrderManager.OnReplenish(data.BuyType, iAPItemList, itemDataGift, data.ShowType); - } - } - public float GetBuyData() - { - return buyData.Count > 0 ? buyData[0] : 0; - } - void BuySuccess(ShopBuyTypeData buyType, IAPItemList iAPItemList, List itemDataGift, RewardType rewardShowType, bool Voucher = false) - { - if (!Voucher) - { - if (buyData.Count == 0) - { - buyData.Add(iAPItemList.PaymentAmount); - } - else - { - buyData[0] += iAPItemList.PaymentAmount; - } - buyData.Add(iAPItemList.ID); - SaveStore.Write("BuyData", JsonMapper.ToJson(buyData)).RequireAccepted(); -#if AGG - GEvent.SetUserProp("Total_consumption", buyData[0]); -#endif - } - new TotalRechargeManager().AddProgress(iAPItemList.VIPPoint); - GContext.Publish(new ConditionTypeEvent(ConditionType.RechargeAmount, iAPItemList.VIPPoint)); - PlayerSaveAction.Present(() => ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_3"))); - if (!buyType.IsHide && itemDataGift != null && itemDataGift.Count > 0) - { - var newItemData = itemDataGift.Where(x => x.id != 3002).ToList(); - PlayerSaveAction.Present(() => GContext.Publish(new ShowData(newItemData, rewardShowType))); - } - - GContext.container.Resolve().AddVIPScore(iAPItemList.VIPPoint, true); - if (itemDataGift != null && itemDataGift.Count > 0) - { - GContext.container.Resolve().AddItem(itemDataGift, null); - } - int curEnd = ZZTimeHelper.UtcNow().UtcNowOffset().Day; - switch (buyType.type) - { - case ShopBuyType.None: - break; - case ShopBuyType.ShopToken: - //商店首次购买记录 - OnShopTokenSuccess(buyType.ID, false); - break; - case ShopBuyType.ShopPackDailyBuy: - if (buyType.endDay == curEnd) - { - //每日更新礼包 - AddShopPackDailyBuyCount(buyType.key, 1); - } - break; - case ShopBuyType.EventPack: - //Event 礼包 - GContext.container.Resolve().OnBuyEventPack(buyType.ID); - break; - case ShopBuyType.TriggerPack: - //触发礼包 - if (buyType.ID == 4000002) - GContext.container.Resolve()?.OnBuySuccess(); - else - GContext.container.Resolve().AddTriggerPackCount(buyType.ID); - break; - - } - GContext.Publish(new ConditionTypeEvent(ConditionType.MakeInAppPurchase, 1)); - } - /// - /// 一个统一的跨天刷新节点 - /// - public void InitShopPackData() - { - int dayOfYear = shopPackDailyBuyCount.GetValueOrDefault("0"); - //if (shopPackDailyBuyCount.TryGetValue("0", out int dayOfYear)) - //{ - if (dayOfYear != ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear) - { - shopPackDailyBuyCount.Clear(); - GContext.container.Resolve().AllRefresh(); - if (VIPAdPackData != null) - { - VIPAdPackData.day = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - VIPAdPackData.index = 0; - VIPAdPackData.cdTime = null; - SetAdvRedPoint(); - } - TurntableAdData = null; - shopPackDailyBuyCount["0"] = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - SaveStore.Write("ShopPackBuyCount", JsonMapper.ToJson(shopPackDailyBuyCount)).RequireAccepted(); - } - //} - } - - //每日购买(ID)次数(触发(Type)),每日重置 - public void AddShopPackDailyBuyCount(int id, int count, bool addAll = true) - { - string idStr = id.ToString(); - AddShopPackDailyBuyCount(idStr, count); - if (addAll) - { - AddAllPackCount(id, count); - } - } - //需要每日清空的数据 懒得改名 - public void AddShopPackDailyBuyCount(string idStr, int count = 1) - { - if (shopPackDailyBuyCount.ContainsKey(idStr)) - { - shopPackDailyBuyCount[idStr] += count; - } - else - { - shopPackDailyBuyCount.Add(idStr, count); - } - if (!shopPackDailyBuyCount.ContainsKey("0")) - { - shopPackDailyBuyCount["0"] = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - SaveStore.Write("ShopPackBuyCount", JsonMapper.ToJson(shopPackDailyBuyCount)).RequireAccepted(); - } - public int GetShopPackBuyCount(int id) - { - string idStr = id.ToString(); - return GetShopPackBuyCount(idStr); - } - public int GetShopPackBuyCount(string id) - { - if (shopPackDailyBuyCount.ContainsKey(id)) - { - return shopPackDailyBuyCount[id]; - } - return 0; - } - - public void SetAdvRedPoint() - { - bool isRed = false; - var DailyGiftPackList = GContext.container.Resolve().priceLevel.DailyGiftPackList; - int id; - Daily daily; - DateTime now = ZZTimeHelper.UtcNow().UtcNowOffset(); - ShopPackManager dailyGiftPackM = null; - for (int i = 0; i < DailyGiftPackList.Count; i++) - { - id = DailyGiftPackList[i]; - dailyGiftPackM = TbPackManagerGetOrDefault(id); - if (dailyGiftPackM == null) continue; - daily = dailyGiftPackM.TimeDefinition as Daily; - if (TimeSpan.FromSeconds(daily.StartTime) <= now.TimeOfDay && TimeSpan.FromSeconds(daily.EndTime) > now.TimeOfDay) - { - break; - } - } - if (dailyGiftPackM != null) - { - isRed = GetShopPackBuyCount(dailyGiftPackM.ID) < 1; - } - RedPointManager.Instance.SetRedPointState(HomeBtnAdvert.redKey, isRed && IsOpenAdPack()); - } - - /// - /// 作为首次购买的依据 ShopTokenID 或 IAPItemListID有次数都不是首充 - /// - /// - /// - public void AddShopGiftBuyCount(int id, int count = 1) - { - if (shopGiftBuyCount.ContainsKey(id)) - { - shopGiftBuyCount[id] += count; - } - else - { - shopGiftBuyCount.Add(id, count); - } - SaveStore.Write("ShopGiftBuyCount", JsonMapper.ToJson(shopGiftBuyCount)).RequireAccepted(); - } - - /// - /// 作为首次购买的依据 ShopTokenID 或 IAPItemListID有次数都不是首充 - /// - /// - public int GiftBuyCount(int id) - { - shopGiftBuyCount.TryGetValue(id, out int buyCount); - return buyCount; - } - //=====================================礼包===================================== - #region =================礼包========================= - #region 链式礼包 - public void SetChainPackData(DailySignEvent chainPackData) - { - ChainPackData = chainPackData; - } - void SetChainPackRed() - { - bool isRed = false; - if (chainPackM != null) - { - if (chainPackM.VIPPackList[ChainPackData.lastID].Count > ChainPackData.index) - { - var pack = _tables.TbPack.GetOrDefault(chainPackM.VIPPackList[ChainPackData.lastID][ChainPackData.index]); - isRed = _tables.TbIAPItemList.GetOrDefault(pack.IAPID) == null; - } - } - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Gift2, isRed); - } - - public void AddChainPack(FishingEvent t) - { - if (ChainPackData == null || ChainPackData.ID != t.ID) - { - - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - var time = dateTime.AddDays(10).Date; - if (t.TimeDefinition is Weekly) - { - Weekly weekly = (Weekly)t.TimeDefinition; - int offfset = (int)dateTime.DayOfWeek - weekly.StartTime; - - if (offfset < 0) - { - offfset = -offfset; - } - else - { - offfset = 7 - offfset; - } - time = dateTime.AddDays(offfset).Date; - } - else if (t.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)t.TimeDefinition; - time = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()).UtcNowOffset(); - } - - - ChainPackData = new DailySignEvent() - { - ID = t.ID, - lastID = GContext.container.Resolve().PriceLv,//VIP等级,礼包连该新,尽量少改代码 - index = 0, - time = time.ToString() - }; - SaveStore.Write("ChainPackDataNew", JsonMapper.ToJson(ChainPackData)).RequireAccepted(); - chainPackM = null; - } - if (chainPackM == null) - { - chainPackM = _tables.TbEventPackManager.GetOrDefault(t.RedirectID); - UITypes.GiftChainCommon_SubmarinePanel.SetType(chainPackM.Panel); - GContext.container.Resolve().AddGiftFaceUI(chainPackM.ID, UITypes.GiftChainCommon_SubmarinePanel, chainPackM.PackType); - SetChainPackRed(); - GContext.Publish(new TargetEvent(chainPackM.ID, 3, 10)); - ILoadResourceService loadResourceService = GContext.container.Resolve(); - loadResourceService.EnqueueBundleSilently(new List() { chainPackM.Panel }); - } - } - - public bool IsOpenChainGiftPack() - { - bool isOpen = false; - if (chainPackM != null) - { - if (chainPackM.VIPPackList[ChainPackData.lastID].Count > ChainPackData.index) - { - var endTime = GetChainEndTime(); - TimeSpan now = endTime - ZZTimeHelper.UtcNow().UtcNowOffset(); - double seconds = now.TotalSeconds; - isOpen = seconds > 0; - } - } - return isOpen; - } - public void AddOpenChainGifIndex() - { - if (chainPackM == null || ChainPackData == null) - { - return; - } - ChainPackData.index++; - SetChainPackRed(); - if (chainPackM.VIPPackList[ChainPackData.lastID].Count <= ChainPackData.index) - { - AddAllPackCount(chainPackM.ID, 1); - } - SaveStore.Write("ChainPackDataNew", JsonMapper.ToJson(ChainPackData)).RequireAccepted(); - //链式礼包 特殊处理 - GContext.Publish(new TargetEvent(chainPackM.ID, 3, 10)); - } - - public DateTime GetChainEndTime() - { - return GlobalUtils.TryParseDateTime(ChainPackData.time, ZZTimeHelper.UtcNow().UtcNowOffset()); - } - #endregion - public int GetAllPackCount(int id) - { - if (shopAllPackBuyCount.ContainsKey(id)) - { - return shopAllPackBuyCount[id]; - } - return 0; - } - //总购买次数 - public void AddAllPackCount(int id, int count) - { - if (shopAllPackBuyCount.ContainsKey(id)) - { - shopAllPackBuyCount[id] += count; - } - else - { - shopAllPackBuyCount.Add(id, count); - } - GContext.Publish(new ConditionTypeEvent(ConditionType.BuyPack, count)); - SaveStore.Write("ShopAllPackBuyCount", JsonMapper.ToJson(shopAllPackBuyCount)).RequireAccepted(); - } - #endregion - //========================================礼包======================================== - #region 广告次数 - public void InitAdvertCount(string data) - { - if (string.IsNullOrEmpty(data) == false) - { - advertCount = Newtonsoft.Json.JsonConvert.DeserializeObject>(data); - } - } - public void AddAdticket(int count) - { - if (advertCount.ContainsKey(-2)) - { - advertCount[-2] += count; - } - else - { - advertCount[-2] = count; - } - if (advertCount[-2] < 0) - { - advertCount[-2] = 0; - } -#if AGG - if (count < 0) - { - - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", 1006) - .AddContent("state_info", "cost") - .AddContent("change_num", count); - } - } -#endif - SaveStore.Write("AdvertAllCount", JsonMapper.ToJson(advertCount)).RequireAccepted(); - GContext.Publish(new ResAddEvent(1006)); - } - public int GetAdticketCount() - { - return advertCount.GetValueOrDefault(-2); - } - public int AddAdvertCount(int id) - { - ClearAdvertCount(); - if (advertCount.ContainsKey(0)) - { - advertCount[0]++; - } - else - { - advertCount[0] = 1; - } - if (advertCount.ContainsKey(id)) - { - advertCount[id] += 1; - } - else - { - advertCount.Add(id, 1); - } - SaveStore.Write("AdvertAllCount", JsonMapper.ToJson(advertCount)).RequireAccepted(); - return advertCount[id]; - } - public void ClearAdvertCount() - { - int allCount = advertCount.GetValueOrDefault(0); - int ticket = advertCount.GetValueOrDefault(-2); - if (advertCount.TryGetValue(-1, out int day)) - { - if (day != ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear) - { - advertCount.Clear(); - advertCount[-1] = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - advertCount[0] = allCount; - advertCount[-2] = ticket; - SaveStore.Write("AdvertAllCount", JsonMapper.ToJson(advertCount)).RequireAccepted(); - } - } - else - { - advertCount[-1] = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - } - public int GetAdvertCount(int id) - { - if (advertCount.ContainsKey(id)) - { - return advertCount[id]; - } - return 0; - } - #endregion - - #region 主界面VIP礼包 - public void SetVIPAdPackData(AdvertData vipAdPackData) - { - int dayOfYear = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - if (vipAdPackData != null && vipAdPackData.day != dayOfYear) - { - vipAdPackData = null; - } - VIPAdPackData = vipAdPackData; - } - public void SetVIPPackNext() - { - List adConfigs = _tables.TbAdConfig.DataList; - if (VIPAdPackData == null) - { - VIPAdPackData = new AdvertData(); - VIPAdPackData.day = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - VIPAdPackData.index++; - if (VIPAdPackData.index < adConfigs.Count) - { - AdConfig adConfig = adConfigs[VIPAdPackData.index]; - VIPAdPackData.ID = adConfig.ID; - AdConfig adConfig1 = adConfigs[VIPAdPackData.index - 1]; - VIPAdPackData.cdTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(adConfig1.Interval).ToString(); - } - SaveStore.Write("VIPAdPackData", JsonMapper.ToJson(VIPAdPackData)).RequireAccepted(); - //GContext.Publish(new VIPAdPackDataEvent()); - } - public DateTime GetVIPAdPackTime() - { - if (VIPAdPackData != null) - { - return GlobalUtils.TryParseDateTime(VIPAdPackData.cdTime, ZZTimeHelper.UtcNow().UtcNowOffset()); - } - else - { - return ZZTimeHelper.UtcNow().UtcNowOffset(); - } - } - //public AdConfig GetVIPAdPackConfig() - //{ - // if (VIPAdPackData == null) - // { - // VIPAdPackData = new AdvertData(); - // VIPAdPackData.day = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - // } - // return _tables.TbAdConfig.DataList[VIPAdPackData.index]; - //} - public void OpenAdPack() - { - if (VIPAdPackData != null && VIPAdPackData.isOpen) - { - return; - } - VIPAdPackData = new AdvertData(); - VIPAdPackData.day = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - VIPAdPackData.isOpen = true; - SaveStore.Write("VIPAdPackData", JsonMapper.ToJson(VIPAdPackData)).RequireAccepted(); - } - public bool IsOpenAdPack() - { - //if (GContext.container.Resolve().ABAdOpen - // && GContext.container.Resolve().lv < 40) - //{ - // return false; - //} - return VIPAdPackData != null && VIPAdPackData.isOpen; - } - public bool IsShowVIPAdTimer() - { - List adConfigs = _tables.TbAdConfig.DataList; - return VIPAdPackData.index >= adConfigs.Count; - } - #endregion - - #region TurntableAd - public DailySignEvent TurntableAdData; - /* - About TurntableAdData: - lastID: the day this ad is activated - ID: ID of the current ad - time: The end time of coolDown for the current Ad - */ - public WheelAd GetTurntableAdCofig() - { - if (TurntableAdData == null) - { - TurntableAdData = new DailySignEvent(); - TurntableAdData.index = 1; - TurntableAdData.lastID = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - return _tables.TbWheelAd[TurntableAdData.index]; - } - public void UpdateTurntableAd() - { - var adConfigs = _tables.TbWheelAd; - if (TurntableAdData == null) - { - TurntableAdData = new DailySignEvent(); - TurntableAdData.index = 1; - TurntableAdData.lastID = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - TurntableAdData.index++; - if (TurntableAdData.index <= adConfigs.DataList.Count) - { - TurntableAdData.ID = adConfigs[TurntableAdData.index].ID; - TurntableAdData.time = ZZTimeHelper.UtcNow().UtcNowOffset() - .AddSeconds(adConfigs[TurntableAdData.index - 1].Interval).ToString(); - // isOverForToday = false; - // } - // else - // { - // isOverForToday = true; - } - SaveStore.Write("TurntableAdData", Newtonsoft.Json.JsonConvert.SerializeObject(TurntableAdData)).RequireAccepted(); - // GContext.Publish(new VIPAdPackDataEvent()); - } - public bool IsTurntableAdMaxOut() - { - if (TurntableAdData == null) - { - TurntableAdData = new DailySignEvent(); - TurntableAdData.index = 1; - TurntableAdData.lastID = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - } - return TurntableAdData.index > _tables.TbWheelAd.DataList.Count; - } - public DateTime GetTurnTableNextAdTime() - { - if (TurntableAdData == null) - { - return ZZTimeHelper.UtcNow().UtcNowOffset(); - } - return GlobalUtils.TryParseDateTime(TurntableAdData.time, ZZTimeHelper.UtcNow().UtcNowOffset()); - } - #endregion - #region Diamond Shop - public class ItemShopData - { - public int ItemShopID; - public ItemShopRecord Record; - // public int SortID; - public int Count; - public int DiamondCost; - - public int GetDiscountDiamondCost() - { - return Mathf.RoundToInt(DiamondCost * Record.Discount); - } - } - public List GetItemShopData() - { - if (CheckIfRefreshItemShop()) - { - AutoRefreshDiamonShop(); - } - var itemShopDatas = new List(); - var diamondStoreData = _tables.TbItemStore.DataMap; - foreach (var record in _diamondShopItemRecords) - { - if (!diamondStoreData.ContainsKey(record.Key)) - continue; - - var itemShopData = diamondStoreData[record.Key]; - var count = itemShopData.ItemNumber; - var diamondCost = itemShopData.TokenNumber; - // var sortID = itemShopData.SortId; - itemShopDatas.Add(new ItemShopData - { - ItemShopID = record.Key, - // SortID = sortID, - Record = record.Value, - Count = count, - DiamondCost = diamondCost, - }); - } - - return itemShopDatas.ToList(); - } - - public TimeSpan GetDiamondShopRefreshTime() - { - var now = ZZTimeHelper.UtcNow().UtcNowOffset(); - return _diamondShopRefreshTime - now; - } - public int GetDiamondShopRefreshCost() - { - var refreshCost = _tables.TbStoreConfig.Get(1).RefreshPrice; - if (_diamondShopRefreshCount >= refreshCost.Count) - { - //Test - // Debug.LogError("[PlayerShopData::GetDiamondShopRefreshCost]Can not refresh!"); - return refreshCost[refreshCost.Count - 1]; - - } - return refreshCost[_diamondShopRefreshCount]; - } - public (int refresh, int maxRefresh) GetDiamondShopRefreshInfo() - { - var maxRefresh = _tables.TbStoreConfig.Get(1).RefreshTimes; - return (maxRefresh - _diamondShopRefreshCount, maxRefresh); - } - - - public void SetItemShopSlotBought(int itemShopId) - { - _diamondShopItemRecords[itemShopId].hasBought = 1; - SetItemShopRedPoint(); - SaveStore.Write("DiamondShopItemRecords", JsonConvert.SerializeObject(_diamondShopItemRecords)).RequireAccepted(); - } - - - private bool CheckIfRefreshItemShop() - { - return _diamondShopRefreshTime <= ZZTimeHelper.UtcNow().UtcNowOffset(); - } - - public void RefreshDiamondShop() - { - if (_diamondShopRefreshCount < _tables.TbStoreConfig.Get(1).RefreshTimes) - { - RefreshItemShop(); - _diamondShopRefreshCount++; - SaveStore.Write("DiamondShopRefreshCount", _diamondShopRefreshCount.ToString()).RequireAccepted(); - } - } - - public void OnHonePanelLoaded() - { - if (CheckIfRefreshItemShop()) - { - - AutoRefreshDiamonShop(); - } - SetItemShopRedPoint(); - } - - private void SetItemShopRedPoint() - { - var diamondSotre = _tables.TbItemStore.DataMap; - foreach (var record in _diamondShopItemRecords) - { - if (record.Value.hasBought == 0 && diamondSotre[record.Key].TokenNumber == 0) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Shop_Item, true); - return; - } - } - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Shop_Item, false); - - } - - public void AutoRefreshDiamonShop() - { - Debug.Log("[PlayerShopData::GetItemSHopData] Refresh itemShop Data!"); - //明天这个时候刷新 - var now = ZZTimeHelper.UtcNow().UtcNowOffset(); - var timeList = _tables.TbStoreConfig.Get(1).AutoRefresh.Split(':'); - var hour = int.Parse(timeList[0]) == 24 ? 0 : int.Parse(timeList[0]); - var timeSpan = new TimeSpan(hour, int.Parse(timeList[1]), int.Parse(timeList[2])); - _diamondShopRefreshTime = new DateTime(now.Year, now.Month, now.Day).AddDays(1) + timeSpan; - - _diamondShopRefreshCount = 0; - SaveStore.Write("DiamondShopRefreshCount", _diamondShopRefreshCount.ToString()).RequireAccepted(); - SaveStore.Write("DiamondShopRefreshTime", _diamondShopRefreshTime.ToString()).RequireAccepted(); - RefreshItemShop(); - } - private void RefreshItemShop() - { - _diamondShopItemRecords.Clear(); - var diamondStoreData = _tables.TbItemStore.DataMap; - - //格子数量增加时修改调整 - var totalCell = 6; - for (int i = 1; i <= totalCell; i++) - { - var datas = diamondStoreData.Values.Where(x => x.CellId == i).ToList(); - var totalWeight = 0; - datas.ForEach(x => totalWeight += x.Weight); - var randomWeight = UnityEngine.Random.Range(1, totalWeight); - var curWeight = 0; - var itemID = -1; - foreach (var data in datas) - { - curWeight += data.Weight; - if (curWeight >= randomWeight) - { - itemID = data.ItemId; - if (data.ItemType == 1) - { - //随机鱼竿 - var dropID = _tables.TbItem.DataMap[data.ItemId].RedirectID; - itemID = GContext.container.Resolve().GetItemDataByDropIdAndType(dropID)[0].id; - } - else if (data.ItemType == 9) - { - //随机鱼卡 - var mapDatas = _tables.TbMapData.DataList; - var lastMapID = GContext.container.Resolve().lastMapId; - var mapIDs = new List(); - foreach (var map in mapDatas) - { - if (map.ID <= lastMapID) - { - mapIDs.Add(map.ID); - } - else - { - break; - } - } - var mapID = mapIDs[UnityEngine.Random.Range(0, mapIDs.Count)]; - var mapData = _tables.TbMapData.GetOrDefault(mapID); - if (mapData != null) - { - itemID = mapData.FishCardItemList[itemID]; - } - } - - //Get disCount - var discount = 1.0f; - var allWeight = 0; - data.DiscountWeight.ForEach(weight => allWeight += weight); - var curWeight1 = UnityEngine.Random.Range(0, allWeight); - for (int j = 0; j < data.DiscountWeight.Count; j++) - { - curWeight1 -= data.DiscountWeight[j]; - if (curWeight1 <= 0) - { - discount = data.Discount[j]; - break; - } - } - _diamondShopItemRecords.Add(data.Id, new ItemShopRecord(itemID, discount, 0)); - break; - } - } - - } - SaveStore.Write("DiamondShopItemRecords", JsonConvert.SerializeObject(_diamondShopItemRecords)).RequireAccepted(); - SetItemShopRedPoint(); - } - #endregion - - public void Dispose() - { - disposed = true; - disposables?.Dispose(); - disposables = null; - } - } -} - diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/014-DataCenter.SignupData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/014-DataCenter.SignupData.cs.txt deleted file mode 100644 index 3bd41007b..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/014-DataCenter.SignupData.cs.txt +++ /dev/null @@ -1,232 +0,0 @@ -using asap.core; -using cfg; -using game; -using LitJson; -using System; -using System.Collections.Generic; - -namespace GameCore -{ - public class DailySignEvent - { - public int ID; - //领取第几个 - public int index; - //签到最后一次是哪一天or链式礼包PackManager.ID - public int lastID; - //结束时间 - public string time; - } - public class MonthlySignEvent - { - public int index; - //结束时间 - public DailySignEvent dailySignEvent; - } - public class OnSignEvent - { - public List itemDataList; - } - public class SigninData - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - private cfg.Tables _tables; - public SigninData(cfg.Tables tables) - { - this._tables = tables; - } - - MonthlySignEvent _monthlySignEvent = null; - - internal static game.PlayerDataStorage.PlayerKVMonthlySignState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeMonthlySign(raw,errors); - internal void ResetForKVLoad() { _monthlySignEvent = null; } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVMonthlySignState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - _monthlySignEvent = !state.IsPresent ? null : new MonthlySignEvent - { - index = state.Index, - dailySignEvent = new DailySignEvent { ID=state.DailyId, index=state.DailyIndex, lastID=state.LastId, time=state.Time } - }; - } - - public DailySignEvent dailySignEvent - { - get => _monthlySignEvent == null ? null : _monthlySignEvent.dailySignEvent; - } - - public MonthlySignEvent monthlySignEvent - { - get => _monthlySignEvent; - set => _monthlySignEvent = value; - } - public void SetDailySignEvent(FishingEvent t) - { - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - bool isSave = false; - DailySignEvent data = null; - if (_monthlySignEvent == null) - { - _monthlySignEvent = new MonthlySignEvent() - { - index = 0, - }; - isSave = true; - } - else - { - List MonthlySignL = _tables.TbMonthlySign.DataList; - - data = _monthlySignEvent.dailySignEvent; - if (_monthlySignEvent.index >= MonthlySignL[^1].SignDayAccount && data.lastID != dateTime.DayOfYear) - { - _monthlySignEvent = new MonthlySignEvent() - { - index = 0, - dailySignEvent = data, - }; - isSave = true; - } - } - SetTheme(); - if (data == null || (data.index >= 7 && data.lastID != dateTime.DayOfYear)) - { - _monthlySignEvent.dailySignEvent = new DailySignEvent() - { - ID = t.RedirectID, - lastID = -1, - index = 0, - time = dateTime.Date.ToString() - }; - isSave = true; - } - if (isSave) - { - SaveStore.Write("MonthlySignEvent", JsonMapper.ToJson(_monthlySignEvent)).RequireAccepted(); - } - bool isReward = CanDailySign(); - if (isReward) - { - ILoadResourceService loadResourceService = GContext.container.Resolve(); - loadResourceService.EnqueueBundleSilently(new List() { UITypes.EventSignupPopupPanel_2.Name }); - GContext.container.Resolve().AddGiftFaceUI(t.ID, UITypes.EventSignupPopupPanel_2); - } - - } - - - //签到 - public bool OnDailySign(int index, int DropID) - { - if (_monthlySignEvent == null || _monthlySignEvent.dailySignEvent == null) - { - return false; - } - bool isSign = SignEvent(_monthlySignEvent.dailySignEvent, index); - if (isSign) - { - _monthlySignEvent.index++; - List itemDataList = GContext.container.Resolve().AddItemByDropLureInflation(null, DropID, null, false); -#if AGG - DateTime tomorrow = GlobalUtils.TryParseDateTime(_monthlySignEvent.dailySignEvent.time, ZZTimeHelper.UtcNow().UtcNowOffset()); - TimeSpan remaining = ZZTimeHelper.UtcNow().UtcNowOffset() - tomorrow; - using (var e = GEvent.GameEvent("user_checkin")) - { - e.AddContent("day_num", remaining.Days) - .AddContent("day_count", _monthlySignEvent.dailySignEvent.index); - if (itemDataList != null) - { - for (int i = 0; i < itemDataList.Count; i++) - { - e.AddContent($"item_{itemDataList[i].id}", itemDataList[i].count); - } - } - } -#endif - List MonthlySignL = _tables.TbMonthlySign.DataList; - List monthlySignReward = null; - for (int i = 0; i < MonthlySignL.Count; i++) - { - if (_monthlySignEvent.index == MonthlySignL[i].SignDayAccount) - { - monthlySignReward = GContext.container.Resolve().AddItemByDropLureInflation(null, MonthlySignL[i].DropID, null, false); - break; - } - } - //GContext.Publish(new ShowData()); - SaveStore.Write("MonthlySignEvent", JsonMapper.ToJson(_monthlySignEvent)).RequireAccepted(); - GContext.Publish(new OnSignEvent() { itemDataList = monthlySignReward }); - } - return isSign; - } - - - bool SignEvent(DailySignEvent data, int index) - { - if (data.lastID == ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear) - { - ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_1")); - return false; - } - if (index == data.index) - { - data.lastID = ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear; - data.index++; - return true; - } - return false; - } - public bool DailySignIsOpen() - { - return _monthlySignEvent != null && _monthlySignEvent.dailySignEvent != null; - } - - public bool CanDailySign() - { - DailySignEvent data = dailySignEvent; - return data != null - && data.lastID != ZZTimeHelper.UtcNow().UtcNowOffset().DayOfYear - && data.index < 7; - } - - public bool ShouldLoadSignInInterstitial() - { - return DailySignIsOpen() && FishingEventData.Condition_NoRechargeDay(15); - } - - private const string DefaultPanel = "EventSignupPopupPanel_2"; - private void SetTheme() - { - var themeList = _tables.TbEventSignSpTheme.DataList; - UITypes.EventSignupPopupPanel_2.SetType(DefaultPanel); - foreach (var theme in themeList) - { - try - { - var startTime = DateTime.Parse((theme.TimeDefinition as LimitedTime).StartTime); - var endTime = DateTime.Parse((theme.TimeDefinition as LimitedTime).EndTime); - var timeNow = ZZTimeHelper.UtcNow(); - if (startTime <= timeNow && timeNow <= endTime) - { - UITypes.EventSignupPopupPanel_2.SetType(theme.Prefab); - break; - } - } - catch (Exception e) - { - UnityEngine.Debug.LogError($"[DataCenter] SetSignInTheme Error:"); - UnityEngine.Debug.LogError(e); - continue; - } - } - } - - private async void ResetTheme(TimeSpan duration) - { - await System.Threading.Tasks.Task.Delay(duration); - UITypes.EventSignupPopupPanel_2.SetType(DefaultPanel); - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/015-DataCenter.SmallGame.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/015-DataCenter.SmallGame.cs.txt deleted file mode 100644 index dd388e975..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/015-DataCenter.SmallGame.cs.txt +++ /dev/null @@ -1,706 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using asap.core; -using cfg; -using game; -using LitJson; -using Newtonsoft.Json; -using UnityEngine; -using static EventPartnerData; - -namespace GameCore -{ - public class ChangeSmallGameTargetEvent - { - public OpponentItemData opponentItemData; - public System.Threading.Tasks.TaskCompletionSource ts; - public bool random; - } - public class SmallGameData - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - private cfg.Tables _tables; - IUserService userService; - ICustomServerMgr customServerMgr; - public SmallGameData(cfg.Tables tables, IUserService userService, ICustomServerMgr customServerMgr) - { - this._tables = tables; - this.userService = userService; - this.customServerMgr = customServerMgr; - BottleCashParamBase = _tables.TbGlobalConfig.BottleCashParamBase; - BottleCashParamDiv = _tables.TbGlobalConfig.BottleCashParamDiv; - BottleCashParamLevel = _tables.TbGlobalConfig.BottleCashParamLevel; - } - public void Init() - { - campData = GContext.container.Resolve(); - - LoginRandomOpponent(); - } - CampDataMM campData; - - int _heistGameCount = 0; - int _bombGameCount = 0; - int _fishHuntGameCount = 0; - public int HeistGameCount => _heistGameCount; - public int FishHuntGameCount => _fishHuntGameCount; - public int BombGameCount => _bombGameCount; - - internal void ResetForKVLoad() - { - _heistGameCount=_bombGameCount=_fishHuntGameCount=0; - opponentItemDatas=new List(); opponentFriendItemDatas=new List(); - opponentNotFriendItemDatas=new List(); opponentFriend=new List(); - opponentFriendDic=new Dictionary(); opponentEnemy=new Dictionary>(); - opponentItemDatasPre=new List(); opponentFriendItemDatasPre=new List(); - opponentNotFriendItemDatasPre=new List(); powerData=new Dictionary(); - opponentData=null; nextOpponent=null; curEnemyType=EnemyType.Aquarium; RobotMapId=nextRobotMapId=0; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVCoreState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - _heistGameCount=state.Integer(16); _bombGameCount=state.Integer(17); _fishHuntGameCount=state.Integer(18); - } - internal bool IsOpponentEmptyForKVValidation => opponentItemDatas.Count==0 && opponentFriendItemDatas.Count==0 && - opponentNotFriendItemDatas.Count==0 && opponentFriend.Count==0 && opponentFriendDic.Count==0 && opponentEnemy.Count==0 && - opponentItemDatasPre.Count==0 && opponentFriendItemDatasPre.Count==0 && opponentNotFriendItemDatasPre.Count==0 && - powerData.Count==0 && opponentData==null && nextOpponent==null && RobotMapId==0 && nextRobotMapId==0; - - //public UnityEngine.Vector3 image_extra_pos { set; get; } - - public void SetHeistGameCount(int value) - { - _heistGameCount = value; - } - public void SaveHeistGameCount() - { - _heistGameCount++; - playerSaveStore.Write("HeistGameCount", _heistGameCount.ToString()).RequireAccepted(); - } - public void SetBombGameCount(int value) - { - _bombGameCount = value; - } - public void SaveBombGameCount() - { - _bombGameCount++; - playerSaveStore.Write("BombGameCount", _bombGameCount.ToString()).RequireAccepted(); - } - public void SetFishHuntGameCount(int value) - { - _fishHuntGameCount = value; - } - public void SaveFishHuntGameCount() - { - _fishHuntGameCount++; - playerSaveStore.Write("FishHuntGameCount", _fishHuntGameCount.ToString()).RequireAccepted(); - } - #region 小游戏仇人 - public List opponentItemDatas = new List(); - public List opponentFriendItemDatas = new List(); - public List opponentNotFriendItemDatas = new List(); - public List opponentFriend = new List(); - Dictionary opponentFriendDic = new Dictionary(); - public Dictionary> opponentEnemy = new Dictionary>(); - List opponentItemDatasPre = new List(); - List opponentFriendItemDatasPre = new List(); - List opponentNotFriendItemDatasPre = new List(); - EnemyType curEnemyType = EnemyType.Aquarium; - public Dictionary powerData; - public OpponentItemData opponentData; - OpponentItemData nextOpponent; - int GMbobmName = 0; - int BottleCashParamBase; - int BottleCashParamDiv; - int BottleCashParamLevel; - public int RobotMapId; - public int nextRobotMapId; - public void GMSetBomb(string bobmName) - { - GMbobmName = int.Parse(bobmName); - } - - public async void LoginRandomOpponent() - { - GetRobotData(); - RandomOpponent(); - await LoadData(); - RandomOpponent(); - } - - void RandomOpponent() - { - Synchrodata(); - nextOpponent = NextOpponent(); - LoadNextOpponentResource(); - } - - public List GetOpponentEnemy() - { - return opponentEnemy.GetValueOrDefault(curEnemyType); - } - - public OpponentItemData GetBankHeistOpponent(EnemyType enemyType) - { - this.curEnemyType = enemyType; - if (opponentItemDatasPre == null || opponentItemDatasPre.Count == 0) - { - ClearOpponent(); - GetFriendData(); - GetRobotData(); - } - opponentData = RandomItem(); - LoadData(); - GetEnemyData(curEnemyType); - if (GMbobmName > 0) - { - opponentData.BombID = GMbobmName; - } - return opponentData; - } - - void Synchrodata() - { - if (opponentItemDatasPre != null && opponentItemDatasPre.Count > 0) - { - opponentItemDatas = opponentItemDatasPre; - } - if (opponentFriendItemDatasPre != null && opponentFriendItemDatasPre.Count > 0) - { - opponentFriendItemDatas = opponentFriendItemDatasPre; - } - if (opponentNotFriendItemDatasPre != null && opponentNotFriendItemDatasPre.Count > 0) - { - opponentNotFriendItemDatas = opponentNotFriendItemDatasPre; - } - } - public OpponentItemData RandomItem() - { - OpponentItemData target = nextOpponent; - Synchrodata(); - nextOpponent = NextOpponent(); - RobotMapId = nextRobotMapId; - LoadNextOpponentResource(); - return target; - } - - async void LoadNextOpponentResource() - { - if (nextOpponent != null) - { - ILoadResourceService loadResourceService = GContext.container.Resolve(); - RobotSetMap(); - int mapId; - if (nextOpponent.isRobot) - { - mapId = nextRobotMapId; - } - else - { - mapId = await LoadAquariumResource(nextOpponent.playFabID); - if (mapId > 0) - { - nextRobotMapId = mapId; - } - else - { - mapId = nextRobotMapId; - } - } - Debug.Log($"nextOpponent Next MapID {mapId}"); - - if (mapId > 0) - { - MapDownloadRes mapData = _tables.TbMapDownloadRes.GetOrDefault(mapId); - if (mapData != null) - { - loadResourceService.EnqueueBundleSilently(mapData.FishRes); - } - } - - string bombPrefab = _tables.TbConstruction.GetOrDefault(nextOpponent.BombID)?.BombPrefab; - if (!string.IsNullOrEmpty(bombPrefab)) - { - loadResourceService.EnqueueBundleSilently(new List() { bombPrefab }); - } - } - - } - - void RobotSetMap() - { - int curMapId = nextRobotMapId; - - var mapDatas = _tables.TbMapData.DataList; - var maxMapID = GContext.container.Resolve().lastMapId; - - //非当前地图 - var mapIDs = new List(); - for (int i = 0; i < mapDatas.Count; i++) - { - if (mapDatas[i].ID <= maxMapID) - { - if (mapDatas[i].ID != curMapId) - { - mapIDs.Add(mapDatas[i].ID); - } - } - else - { - break; - } - } - if (mapIDs.Count == 0) - { - nextRobotMapId = maxMapID; - } - else - { - nextRobotMapId = mapIDs[UnityEngine.Random.Range(0, mapIDs.Count)]; - } - } - - async Task LoadAquariumResource(string playFabId) - { - GetAquariumDataRequest request = new GetAquariumDataRequest(); - request.playFabId = playFabId; - string result = await customServerMgr.CustomServerPost("aquarium/GetAquariumData", Newtonsoft.Json.JsonConvert.SerializeObject(request)); - if (result != null) - { - var resp = JsonConvert.DeserializeObject(result); - if (resp.code == 0) - { - var data = resp.data; - List slotDatas = data.slotDatas; - if (slotDatas == null) - { - return 0; - } - - var time = ZZTimeHelper.UtcNow(); - List aquariumResultDatas = data.aquariumResultDatas; - for (int i = 0; i < slotDatas.Count; i++) - { - AquariumSlotData slotData = slotDatas[i]; - slotData.index = i; - var HatchTime = slotData.FishHatchTime(); - - if (HatchTime < time) - { - if (!slotData.IsResult() && aquariumResultDatas.Count > i && !aquariumResultDatas[i].IsResult()) - { - return resp.data.mapId; - } - } - } - } - } - return 0; - } - public OpponentItemData NextOpponent() - { - int friendW = Math.Min(100, opponentFriendItemDatas.Count * 20); - if (opponentFriendItemDatas.Count == 0) - { - friendW = 0; - } - int noFriendW = 70; - if (opponentNotFriendItemDatas.Count == 0) - { - noFriendW = 0; - } - int robotW = 30; - int allW = friendW + noFriendW + robotW; - int w = UnityEngine.Random.Range(0, allW); - OpponentItemData target; - if (friendW > 0 && opponentFriendItemDatas.Count > 0 && w < friendW) - { - target = opponentFriendItemDatas[UnityEngine.Random.Range(0, opponentFriendItemDatas.Count)]; - target.target_group = 1; - } - else if (noFriendW > 0 && opponentNotFriendItemDatas.Count > 0 && w < friendW + noFriendW) - { - target = opponentNotFriendItemDatas[UnityEngine.Random.Range(0, opponentNotFriendItemDatas.Count)]; - target.target_group = 2; - } - else - { - if (opponentItemDatas == null || opponentItemDatas.Count == 0) - { - GetRobotData(); - opponentItemDatas = opponentItemDatasPre; - Debug.LogError("opponentItemDatas Count == 0"); - } - target = opponentItemDatas[UnityEngine.Random.Range(0, opponentItemDatas.Count)]; - target.target_group = 3; - } - return target; - } - - void ClearOpponent() - { - Synchrodata(); - opponentFriendItemDatasPre = new List(); - opponentNotFriendItemDatasPre = new List(); - opponentItemDatasPre = new List(); - powerData = new Dictionary(); - opponentFriend = new List(); - opponentFriendDic = new Dictionary(); - } - public async Task LoadData() - { - ClearOpponent(); - GetFriendData(); - try - { - await GetActiveNotFriendData(); - await GetLeaderboardData(curEnemyType); - } - catch (Exception ex) - { - Debug.LogError(ex.Message); - } - GetRobotData(); - } - - async Task GetActiveNotFriendData() - { - var request = new EventBuildRecommendPlayerRequest(); - int lv = GContext.container.Resolve().lv; - int minLevel = (int)(lv * 0.5f); - if (minLevel < 0) - { - minLevel = 0; - } - request.MinLevel = minLevel; - request.MaxLevel = lv * 2; - request.Exclude = new List(); - - string json = await customServerMgr.CustomServerPost($"eventpartner/recommend", - Newtonsoft.Json.JsonConvert.SerializeObject(request)); - if (!string.IsNullOrEmpty(json) && json != "[]") - { - EventBuildRecommendPlayerResp resp = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - if (resp.State == EEventBuildState.Success && resp.Players != null) - { - List _dataList = _tables.TbConstruction.DataList; - for (int i = 0; i < resp.Players.Count; i++) - { - if (resp.Players[i].PlayFabId == userService.UserId) - { - continue; - } - OpponentItemData opponentItemData = new OpponentItemData(); - opponentItemData.playFabID = resp.Players[i].PlayFabId; - opponentItemData.target_source = 2; - - userService.SetPlayInfo(resp.Players[i].PlayFabId, resp.Players[i].DisplayName, resp.Players[i].AvatarUrl); - userService.SetPlayerLv(resp.Players[i].PlayFabId, resp.Players[i].Level); - int level = resp.Players[i].Level; - - opponentItemData.BombID = GetConstructionID(level); - opponentItemData.power = (float)Math.Log10(BottleCashParamBase + level / BottleCashParamLevel) / BottleCashParamDiv; - powerData[opponentItemData.playFabID] = opponentItemData.power; - //opponentItemDatasPre.Add(opponentItemData); - opponentNotFriendItemDatasPre.Add(opponentItemData); - } - } - } - } - int GetConstructionID(int level) - { - List _dataList = _tables.TbConstruction.DataList; - int id = _dataList[0].ID; - for (int j = _dataList.Count - 1; j >= 0; j--) - { - if (_dataList[j].InitialLevel <= level) - { - id = _dataList[j].ID; - break; - } - } - return id; - } - void GetFriendData() - { - var FriendList = GContext.container.Resolve().FriendList; - opponentFriendItemDatasPre.Clear(); - DateTime dateTime = ZZTimeHelper.UtcNow().Date.AddDays(-1); - if (FriendList != null && FriendList.Count > 0) - { - for (int i = 0; i < FriendList.Count; i++) - { - if (FriendList[i].playFabId == userService.UserId) - { - continue; - } - OpponentItemData opponentItemData = new OpponentItemData(); - opponentItemData.playFabID = FriendList[i].playFabId; - opponentItemData.target_source = 1; - - opponentFriendItemDatasPre.Add(opponentItemData); - int level = FriendList[i].value / LeadboardData.LV_MODELING; - - opponentItemData.BombID = GetConstructionID(level); - opponentItemData.power = (float)Math.Log10(BottleCashParamBase + level / BottleCashParamLevel) / BottleCashParamDiv; - powerData[opponentItemData.playFabID] = opponentItemData.power; - //opponentItemDatasPre.Add(opponentItemData); - opponentFriend.Add(opponentItemData); - opponentFriendDic[opponentItemData.playFabID] = opponentItemData; - } - } - } - - public async void SetEnemy(EnemyType enemyType, long glod) - { - if (!opponentData.isRobot && opponentData.playFabID.Length > 10) - { - SetEnemyIDRequest setEnemyCampIDRequest = new SetEnemyIDRequest() - { - enemyType = enemyType, - playerID = userService.UserId, - enemyID = opponentData.playFabID, - content = glod.ToString() - }; - var customServerMgr = GContext.container.Resolve(); - string json = await customServerMgr.BombRequest("SetEnemyID", setEnemyCampIDRequest); - if (!string.IsNullOrEmpty(json) && json != "[]") - { - SetEnemyIDResponse setCampIDResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - } - } - } - //向服务器请求仇人列表 - async Task GetEnemyData(EnemyType enemyType) - { - GetEnemyIDRequest getEnemyCampIDRequest = new GetEnemyIDRequest() - { - playerID = userService.UserId, - enemyType = enemyType, - }; - var customServerMgr = GContext.container.Resolve(); - string json = await customServerMgr.BombRequest("GetEnemyID", getEnemyCampIDRequest); - if (!string.IsNullOrEmpty(json) && json != "[]") - { - GetEnemyIDResponse getCampIDResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - if (getCampIDResponse.enemyIDs == null) - { - return; - } - List eventPopupDatas = GContext.container.Resolve().eventPopupDatas; - //DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - //EventPopupData eventPopupData; - int count; - ReportDataType reportDataType = ReportDataType.Bomb; - switch (enemyType) - { - case EnemyType.Bomb: - reportDataType = ReportDataType.Bomb; - break; - case EnemyType.Heist: - reportDataType = ReportDataType.Heist; - break; - case EnemyType.Aquarium: - reportDataType = ReportDataType.Aquarium; - break; - } - List opponentItemDatas = new List(); - opponentEnemy[enemyType] = opponentItemDatas; - eventPopupDatas = eventPopupDatas.Where(x => (int)(x.type) == (int)reportDataType).ToList(); - for (int i = 0; i < getCampIDResponse.enemyIDs.Count; i++) - { - if (getCampIDResponse.enemyIDs[i] == userService.UserId) - { - continue; - } - - OpponentItemData opponentItemData = new OpponentItemData(); - opponentItemData.playFabID = getCampIDResponse.enemyIDs[i]; - - if (getCampIDResponse.levels != null) - { - if (getCampIDResponse.levels.TryGetValue(opponentItemData.playFabID, out int level)) - { - opponentItemData.BombID = GetConstructionID(level); - } - } - - if (powerData.ContainsKey(opponentItemData.playFabID)) - { - opponentItemData.power = powerData[opponentItemData.playFabID]; - } - else - { - opponentItemData.power = 1; - } - count = eventPopupDatas.Where(x => x.playerID == opponentItemData.playFabID).Count(); - if (reportDataType == ReportDataType.Aquarium) - { - if (count > 1) - { - opponentItemData.info = LocalizationMgr.GetFormatTextValue("UI_EventBankHeistOpponentPopupPanel_3", count); - } - else - { - opponentItemData.info = LocalizationMgr.GetFormatTextValue("UI_EventBankHeistOpponentPopupPanel_5", 1); - } - } - else - { - if (count > 1) - { - opponentItemData.info = LocalizationMgr.GetFormatTextValue("UI_EventBankHeistOpponentPopupPanel_6", count); - } - else - { - opponentItemData.info = LocalizationMgr.GetFormatTextValue("UI_EventBankHeistOpponentPopupPanel_7", 1); - } - } - if (opponentFriendDic.TryGetValue(opponentItemData.playFabID, out OpponentItemData friendData)) - { - friendData.info = opponentItemData.info; - } - opponentItemData.target_source = 4; - - opponentItemDatas.Add(opponentItemData); - //opponentNotFriendItemDatasPre.Add(opponentItemData); - } - } - } - void GetRobotData() - { - int count = opponentItemDatasPre.Count; - int allCount = 20; - if (count >= 20) - { - allCount = count + 1; - } - var robots = new List(_tables.TbRobot.DataList); - cfg.Robot robot; - int myID = campData.Id; - cfg.TbConstruction tbConstruction = _tables.TbConstruction; - int constructionFirstId = tbConstruction.DataList[0].ID % 1000; - int constructionLastId = tbConstruction.DataList[^1].ID; - int campId; - for (int i = count; i < allCount; i++) - { - robot = robots[UnityEngine.Random.Range(0, robots.Count)]; - robots.Remove(robot); - OpponentItemData opponentItemData = new OpponentItemData(); - opponentItemData.playFabID = robot.ID.ToString("X"); - opponentItemData.target_source = -1; - userService.SetPlayInfo(opponentItemData.playFabID, LocalizationMgr.GetText(robot.Name_l10n_key), robot.Avatar); - //opponentItemData.playName = robot.Name; - //opponentItemData.url = robot.Avatar; - opponentItemData.isRobot = true; - - campId = robot.ConstructionOffset + myID; - if (campId < constructionFirstId) - { - campId = constructionFirstId; - } - if (campId > constructionLastId) - { - campId = constructionLastId; - } - opponentItemData.BombID = campId; - opponentItemData.power = (float)Math.Log10(BottleCashParamBase - i) / BottleCashParamDiv; - opponentItemDatasPre.Add(opponentItemData); - } - } - async Task GetLeaderboardData(EnemyType enemyType) - { - FishingEventData _fishingEventData = GContext.container.Resolve(); - if (!_fishingEventData.IsOpenRank()) - { - return; - } - LeadboardData leadboardData = GContext.container.Resolve(); - if (leadboardData.curEventRank == null) - { - return; - } - Dictionary robots = GContext.container.Resolve().TbRobot.DataMap; - GetLeaderboardsResp curEventRank = leadboardData.curEventRank; - int myID = campData.Id; - cfg.TbConstruction tbConstruction = _tables.TbConstruction; - int constructionFirstId = tbConstruction.DataList[0].ID % 1000; - int constructionLastId = tbConstruction.DataList[^1].ID; - int campId = myID; - Dictionary playerList = new Dictionary(); - for (int i = 0; i < curEventRank.data.Length; i++) - { - if (curEventRank.data[i].isMe || curEventRank.data[i].id == userService.UserId) - { - continue; - } - - if (curEventRank.data[i].id == null || powerData.ContainsKey(curEventRank.data[i].id)) - { - continue; - } - - OpponentItemData opponentItemData = new OpponentItemData(); - opponentItemData.playFabID = curEventRank.data[i].id; - if (curEventRank.data[i].isBot) - { - int b = Convert.ToInt32(opponentItemData.playFabID, 16); - if (robots.TryGetValue(b, out cfg.Robot robot)) - { - campId = robot.ConstructionOffset + myID; - } - if (campId < constructionFirstId) - { - campId = constructionFirstId; - } - if (campId > constructionLastId) - { - campId = constructionLastId; - } - opponentItemData.isRobot = true; - opponentItemData.target_source = -1; - opponentItemDatasPre.Add(opponentItemData); - } - else - { - playerList[opponentItemData.playFabID] = opponentItemData; - opponentItemData.target_source = 3; - userService.GetPlayInfo(opponentItemData.playFabID); - opponentNotFriendItemDatasPre.Add(opponentItemData); - } - opponentItemData.BombID = campId; - opponentItemData.power = (float)Math.Log10(BottleCashParamBase - curEventRank.data[i].rank) / BottleCashParamDiv; - powerData[opponentItemData.playFabID] = opponentItemData.power; - } - if (playerList.Count > 0 /*&& enemyType == EnemyType.Bomb*/) - { - await GetCampID(playerList); - } - } - async Task GetCampID(Dictionary playerList) - { - List playFabIds = playerList.Values.Select(x => x.playFabID).ToList(); - - GetCampIDRequest getCampIDRequest = new GetCampIDRequest() - { - playerIDs = playFabIds - }; - var customServerMgr = GContext.container.Resolve(); - string json = await customServerMgr.BombRequest("GetCampID", getCampIDRequest); - if (!string.IsNullOrEmpty(json) && json != "[]") - { - GetCampIDResponse getCampIDResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - if (getCampIDResponse != null && getCampIDResponse.levels != null && getCampIDResponse.levels.Count > 0) - { - foreach (var item in getCampIDResponse.levels) - { - playerList[item.Key].BombID = GetConstructionID(item.Value); - } - } - } - } - #endregion - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/016-DataCenter.TriggerPackData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/016-DataCenter.TriggerPackData.cs.txt deleted file mode 100644 index ad7827993..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/016-DataCenter.TriggerPackData.cs.txt +++ /dev/null @@ -1,657 +0,0 @@ -using asap.core; -using cfg; -using game; -using LitJson; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using UniRx; -using UnityEngine; - -namespace GameCore -{ - public class TriggerPackBuyData - { - public int ID; - //领取第几个 - public int index; - //礼包类型 - public int lastID; - //结束时间 - public string time; - //触发当时VIP等级 - public int vipLevel; - //触发当时地图ID - public int mapID; - } - public class GiftVIPDData - { - public int oldVipLevel; - public int curVipLevel; - //记录数据用于明天时间(天) - public int timer; - } - public class TriggerPackEvent - { - - } - public class TriggerPackData - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - Tables _tables; - PlayerShopData playerShopData; - public TriggerPackData(Tables tables) - { - _tables = tables; - } - //固定时机开启的过期时间 - Dictionary fixedTimeShopDic = new Dictionary(); - - //触发礼包的数据 - public List triggerPackList = new List(); - - //VIP 等级叠加 - public Dictionary giftVIPDData = new Dictionary(); - - internal static game.PlayerDataStorage.PlayerKVTriggerState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodeTriggers(raw,errors); - internal void ResetForKVLoad() - { - triggerPackList=new List(); - giftVIPDData=new Dictionary(StringComparer.Ordinal); - fixedTimeShopDic=new Dictionary(); - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVTriggerState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - var packs=state.Packs.Select(p=>new TriggerPackBuyData { - ID=p.ID,index=p.index,lastID=p.lastID,vipLevel=p.vipLevel,mapID=p.mapID,time=p.time }).ToList(); - var gifts=state.Gifts.ToDictionary(p=>p.Key,p=>new GiftVIPDData { - oldVipLevel=p.Value.oldVipLevel,curVipLevel=p.Value.curVipLevel,timer=p.Value.timer },StringComparer.Ordinal); - var fixedValues=state.Fixed.ToDictionary(p=>p.Key,p=>new FixedTimeEvent { id=p.Value.id,endTime=p.Value.endTime }); - triggerPackList=packs; giftVIPDData=gifts; fixedTimeShopDic=fixedValues; - } -#if UNITY_EDITOR - internal FixedTimeEvent FixedForKVValidation(int key) => fixedTimeShopDic.TryGetValue(key,out var value) ? value : null; - internal bool IsEmptyForKVValidation => triggerPackList.Count==0 && giftVIPDData.Count==0 && fixedTimeShopDic.Count==0; -#endif - public void Init() - { - playerShopData = GContext.container.Resolve(); - GContext.OnEvent().Subscribe(UpdateTriggerPackData); - InitPackData(); - } - #region 礼包限制、开启、初始化 - public void SetFixedTimeShopDic(Dictionary _limitedTimeShopDic) - { - fixedTimeShopDic = _limitedTimeShopDic; - } - public bool FixedTimeEventExpired(int eventId) - { - if (fixedTimeShopDic.TryGetValue(eventId, out FixedTimeEvent fixedTimeEvent)) - { - var endTime = GlobalUtils.TryParseDateTime(fixedTimeEvent.endTime, ZZTimeHelper.UtcNow().UtcNowOffset()); - return endTime.Ticks > ZZTimeHelper.UtcNow().UtcNowOffset().Ticks; - } - return true; - } - public void InitPackData() - { - InitGiftVIPDData(); - //过期礼包删除 - DateTime curTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - for (int i = triggerPackList.Count - 1; i >= 0; i--) - { - TriggerPackBuyData item = triggerPackList[i]; - DateTime endTime = GlobalUtils.TryParseDateTime(item.time, curTime); - if (endTime.Ticks <= curTime.Ticks) - { - triggerPackList.Remove(item); - } - } - List _dataList = _tables.TbTriggerPackManager.DataList; - foreach (var t in _dataList) - { - if (t.PackType == 2) - { - ConditionTypeAdd(t); - } - } - triggerPackList.Sort((a, b) => a.lastID.CompareTo(b.lastID)); - } - bool isInitFace; - public void SetInitFace() - { - if (isInitFace) - { - return; - } - isInitFace = true; - - for (int i = 0; i < triggerPackList.Count; i++) - { - if (playerShopData.GetShopPackBuyCount(triggerPackList[i].lastID) == 0 && triggerPackList[i].lastID != 4) - { - playerShopData.AddShopPackDailyBuyCount(triggerPackList[i].lastID, 1, false); - } - if (triggerPackList[i].mapID <= 0) - { - triggerPackList[i].mapID = GContext.container.Resolve().currentMapId; - } - if (triggerPackList[i].lastID == 53) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(triggerPackList[i].ID, UITypes.MapPackPanel, triggerPackList[i].lastID); - } - else if (triggerPackList[i].lastID == 2) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(triggerPackList[i].ID, UITypes.CommerceNoviceGiftPopupPanel, triggerPackList[i].lastID); - } - else if (triggerPackList[i].lastID == 1) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(triggerPackList[i].ID, UITypes.GiftPopupPanel_6, triggerPackList[i].lastID); - } - else if (triggerPackList[i].lastID == 5) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(triggerPackList[i].ID, UITypes.AdsPackPanel, triggerPackList[i].lastID); - } - - } - } - public void UpdateTriggerPackData(ConditionTypeEvent typeData) - { - ConditionType type = typeData.type; - List _dataList = _tables.TbTriggerPackManager.DataList; - foreach (var t in _dataList) - { - if (t.Condition == type) - { - if (ConditionTypeAdd(t, true, typeData.count)) - { - if (t.PackType == 53) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.MapPackPanel, t.PackType); - GContext.Publish(new TriggerPackEvent()); - } - else if (t.PackType == 2) - { - //SetPack2Panel(t); - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.CommerceNoviceGiftPopupPanel, t.PackType); - GContext.Publish(new TriggerPackEvent()); - } - else if (t.PackType == 1) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.GiftPopupPanel_6, t.PackType); - } - } - } - } - } - - - /// - /// 钓鱼失败 看完广告 触发礼包 - /// - public void TriggerAdsPack() - { - if (!playerShopData.IsOpenAdPack() || playerShopData.GetAdticketCount() >= 5 || - GContext.container.Resolve().vip < 1) - { - return; - } - - TriggerPackManager t = _tables.TbTriggerPackManager.GetOrDefault(4000101); - if (t == null || t.PackType != 5) - { - return; - } - //特殊的 广告礼包 使用 fixedTimeShopDic 记录CD时间 - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - - if (!FixedTimeEventExpired(t.ID)) - { - fixedTimeShopDic.Remove(t.ID); - } - if (!fixedTimeShopDic.ContainsKey(t.ID)) - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - //广告礼包记录的是 cd时间 - fixedTimeShopDic[t.ID] = new FixedTimeEvent() - { - id = t.ID, - endTime = dateTime.AddSeconds(fixedTime.EndTime).ToString(), - }; - SaveStore.Write("FixedTimeShopDic", JsonMapper.ToJson(fixedTimeShopDic)).RequireAccepted(); - - TriggerPackBuyData _newSignEvent = null; - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].ID == t.ID) - { - _newSignEvent = triggerPackList[i]; - break; - } - } - string time = dateTime.AddSeconds(fixedTime.StartTime).ToString(); - if (_newSignEvent == null) - { - _newSignEvent = new TriggerPackBuyData() - { - ID = t.ID, - lastID = t.PackType, - index = 0, - time = time, - vipLevel = GetVIPLevel(t.PackType), - mapID = GContext.container.Resolve().lastMapId, - }; - triggerPackList.Insert(0, _newSignEvent); - } - else - { - _newSignEvent.time = time; - _newSignEvent.vipLevel = GetVIPLevel(t.PackType); - } - GContext.container.Resolve().AddGiftFaceUIOnLogin(_newSignEvent.ID, UITypes.AdsPackPanel, _newSignEvent.lastID); - SaveStore.Write("TriggerPackDataList", JsonMapper.ToJson(triggerPackList)).RequireAccepted(); - } - } - - public void RefreshTriggerPackData(int id, int mapID) - { - TriggerPackManager t = _tables.TbTriggerPackManager.GetOrDefault(id); - bool isOpen = playerShopData.GetShopPackBuyCount(t.PackType) < t.MaxTrigger; - - if (isOpen) - { - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - TriggerPackBuyData _newSignEvent = null; - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].ID == t.ID) - { - _newSignEvent = triggerPackList[i]; - break; - } - } - if (_newSignEvent != null) - { - triggerPackList.Remove(_newSignEvent); - } - string time = dateTime.AddDays(10).ToString(); - if (t.TimeDefinition is FixedTime) - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - time = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(fixedTime.StartTime).ToString(); - FixedTimeEvent fixedTimeEvent = new FixedTimeEvent() - { - id = t.ID, - endTime = time, - }; - fixedTimeShopDic[t.ID] = fixedTimeEvent; - SaveStore.Write("FixedTimeShopDic", JsonMapper.ToJson(fixedTimeShopDic)).RequireAccepted(); - } - else if (t.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)t.TimeDefinition; - time = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()).UtcNowOffset().ToString(); - } - - _newSignEvent = new TriggerPackBuyData() - { - ID = t.ID, - lastID = t.PackType, - index = 0, - time = time, - vipLevel = GetVIPLevel(t.PackType), - mapID = mapID, - }; - triggerPackList.Insert(0, _newSignEvent); - playerShopData.AddShopPackDailyBuyCount(t.PackType, 1, false); - SaveStore.Write("TriggerPackDataList", JsonMapper.ToJson(triggerPackList)).RequireAccepted(); - } - } - /// - /// 特殊触发礼包 - /// - /// - public void AddTriggerPackData(int id) - { - TriggerPackManager t = _tables.TbTriggerPackManager.GetOrDefault(id); - - bool isOpen = t.MaxTrigger == 0 || ((t.PackType == 1 || t.PackType == 2) && GContext.container.Resolve().GetAllPackCount(t.ID) < t.MaxTrigger)//类型为1.2新手礼包 - || (t.PackType != 1 && t.PackType != 2 && playerShopData.GetShopPackBuyCount(t.PackType) < t.MaxTrigger);//每日限购礼包 - - if (isOpen) - { - if (t.TimeDefinition is FixedTime) - { - if (t.PackType == 53) - { - fixedTimeShopDic.Remove(t.ID); - } - if (!fixedTimeShopDic.ContainsKey(t.ID)) - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - fixedTimeShopDic[t.ID] = new FixedTimeEvent() - { - id = t.ID, - endTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(fixedTime.StartTime).ToString(), - }; - - SaveStore.Write("FixedTimeShopDic", JsonMapper.ToJson(fixedTimeShopDic)).RequireAccepted(); - } - if (FixedTimeEventExpired(t.ID)) - { - AddTriggerPack(t); - } - } - else - { - AddTriggerPack(t); - } - } - } - bool ConditionTypeAdd(TriggerPackManager t, bool trigger = false, int Param = 0) - { - bool isOpen = false; - if (Condition(t, false, Param)) - { - if (t.TimeDefinition is FixedTime) - { - if (trigger && (t.PackType == 53)) - { - fixedTimeShopDic.Remove(t.ID); - } - if (!fixedTimeShopDic.ContainsKey(t.ID)) - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - fixedTimeShopDic[t.ID] = new FixedTimeEvent() - { - id = t.ID, - endTime = ZZTimeHelper.UtcNow().UtcNowOffset().AddSeconds(fixedTime.StartTime).ToString(), - }; - - SaveStore.Write("FixedTimeShopDic", JsonMapper.ToJson(fixedTimeShopDic)).RequireAccepted(); - } - if (FixedTimeEventExpired(t.ID)) - { - AddTriggerPack(t); - isOpen = true; - } - } - else - { - AddTriggerPack(t); - isOpen = true; - } - } - return isOpen; - } - bool Condition(TriggerPackManager packManager, bool isAdd, int Param) - { - if (packManager.PackType == 5) - { - return false; - } - bool isOpen = packManager.MaxTrigger == 0 || ((packManager.PackType == 1 || packManager.PackType == 2) && GContext.container.Resolve().GetAllPackCount(packManager.ID) < packManager.MaxTrigger)//类型为1.2新手礼包 - || (packManager.PackType != 1 && packManager.PackType != 2 && playerShopData.GetShopPackBuyCount(packManager.PackType) < packManager.MaxTrigger);//每日限购礼包 - if (!isOpen) - { - return false; - } - - if (packManager.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)packManager.TimeDefinition; - var timer = ZZTimeHelper.UtcNow(); - isOpen = GlobalUtils.TryParseDateTime(limitedTime.StartTime, timer) <= timer && timer < GlobalUtils.TryParseDateTime(limitedTime.EndTime, timer); - } - - switch (packManager.Condition) - { - case ConditionType.AccountLevel: - if (isAdd) - { - isOpen &= GContext.container.Resolve().lv >= int.Parse(packManager.Param[0]); - } - else - { - isOpen &= GContext.container.Resolve().lv == int.Parse(packManager.Param[0]); - } - break; - case ConditionType.GetFishCount: - if (isAdd) - { - isOpen &= GContext.container.Resolve().GetAnglingCount() >= int.Parse(packManager.Param[0]); - } - else - { - isOpen &= GContext.container.Resolve().GetAnglingCount() == int.Parse(packManager.Param[0]); - } - break; - case ConditionType.CompleteGuide: - isOpen &= GContext.container.Resolve().GetIsFinish(packManager.Param[0]); - break; - case ConditionType.BuyPack: - isOpen &= playerShopData.shopAllPackBuyCount.GetValueOrDefault(int.Parse(packManager.Param[0])) > 0; - break; - case ConditionType.MapUnlocked: - //isOpen &= GContext.container.Resolve().MapIsUnlock(packManager.Param); - isOpen &= packManager.Param.Contains(Param.ToString()); - break; - } - // if ( packManager.PackType == 2 ) - // Debug.Log("??" + packManager.Condition+GContext.container.Resolve().lv+int.Parse(packManager.Param[0])+ (GContext.container.Resolve().lv >= int.Parse(packManager.Param[0])) + " " +isOpen); - return isOpen; - } - #endregion - void InitGiftVIPDData() - { - if (giftVIPDData.Count > 0) - { - var timer = ZZTimeHelper.UtcNow().UtcNowOffset(); - int dateTime = timer.AddDays(1).DayOfYear; - bool isUpdate = false; - foreach (var item in giftVIPDData) - { - GiftVIPDData giftVIPDData = item.Value; - if (giftVIPDData.timer != dateTime) - { - isUpdate = true; - if (giftVIPDData.timer == timer.DayOfYear) - { - giftVIPDData.oldVipLevel = giftVIPDData.curVipLevel; - giftVIPDData.curVipLevel = 0; - } - else - { - giftVIPDData.oldVipLevel = 0; - giftVIPDData.curVipLevel = 0; - } - giftVIPDData.timer = dateTime; - } - } - if (isUpdate) - { - SaveStore.Write("GiftVIPDData", JsonMapper.ToJson(giftVIPDData)).RequireAccepted(); - } - } - } - public int GetVIPLevel(int packType) - { - string PackType = packType.ToString(); - return GetVIPLevel(PackType); - } - public void SetVIPLevel(int packType, int VIPBonusForNextType) - { - string PackType = packType.ToString(); - SetVIPLevel(PackType, VIPBonusForNextType); - } - public int GetVIPLevel(string type) - { - int vipLevel = GContext.container.Resolve().PriceLv; - if (giftVIPDData.TryGetValue(type, out GiftVIPDData giftVIPD)) - { - vipLevel += giftVIPD.oldVipLevel; - } - if (vipLevel >= _tables.TbVipLevel.DataList.Count) - { - vipLevel = _tables.TbVipLevel.DataList.Count - 1; - } - return vipLevel; - } - public void SetVIPLevel(string PackType, int VIPBonusForNextType) - { - if (VIPBonusForNextType > 0) - { - if (giftVIPDData.TryGetValue(PackType, out GiftVIPDData giftVIPD)) - { - giftVIPD.curVipLevel += VIPBonusForNextType; - } - else - { - giftVIPD = new GiftVIPDData() - { - curVipLevel = VIPBonusForNextType, - timer = ZZTimeHelper.UtcNow().UtcNowOffset().AddDays(1).DayOfYear, - }; - } - giftVIPDData[PackType] = giftVIPD; - SaveStore.Write("GiftVIPDData", JsonMapper.ToJson(giftVIPDData)).RequireAccepted(); - } - } - #region 触发礼包 - public void AddTriggerPack(TriggerPackManager t) - { - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - TriggerPackBuyData _newSignEvent = null; - //if (t.PackType != 53) - //{ - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].ID == t.ID) - { - _newSignEvent = triggerPackList[i]; - break; - } - } - //} - if (_newSignEvent != null && - (GlobalUtils.TryParseDateTime(_newSignEvent.time, ZZTimeHelper.UtcNow()).Ticks < dateTime.Ticks)) - { - triggerPackList.Remove(_newSignEvent); - _newSignEvent = null; - } - if (_newSignEvent == null) - { - string time = dateTime.AddDays(10).ToString(); - if (t.TimeDefinition is FixedTime) - { - if (fixedTimeShopDic.TryGetValue(t.ID, out FixedTimeEvent fixedTimeEvent)) - { - time = fixedTimeEvent.endTime; - } - else - { - FixedTime fixedTime = (FixedTime)t.TimeDefinition; - time = dateTime.AddSeconds(fixedTime.StartTime).ToString(); - } - } - else if (t.TimeDefinition is LimitedTime) - { - LimitedTime limitedTime = (LimitedTime)t.TimeDefinition; - time = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()).UtcNowOffset().ToString(); - } - - _newSignEvent = new TriggerPackBuyData() - { - ID = t.ID, - lastID = t.PackType, - index = 0, - time = time, - vipLevel = GetVIPLevel(t.PackType), - mapID = GContext.container.Resolve().lastMapId, - }; - triggerPackList.Insert(0, _newSignEvent); - playerShopData.AddShopPackDailyBuyCount(t.PackType, 1, false); - SaveStore.Write("TriggerPackDataList", JsonMapper.ToJson(triggerPackList)).RequireAccepted(); - } - } - public void AddTriggerPackCount(int id) - { - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].ID == id) - { - if (++triggerPackList[i].index >= _tables.TbTriggerPackManager.Get(triggerPackList[i].ID).VIPPackList[GetVIPLevel(triggerPackList[i].lastID)].Count) - { - triggerPackList.Remove(triggerPackList[i]); - } - SaveStore.Write("TriggerPackDataList", JsonMapper.ToJson(triggerPackList)).RequireAccepted(); - break; - } - } - playerShopData.AddAllPackCount(id, 1); - TriggerPackManager packManager = _tables.TbTriggerPackManager.GetOrDefault(id); - GContext.Publish(new TriggerPackEvent()); - if (packManager.VIPBonus > 0) - { - SetVIPLevel(packManager.PackType, packManager.VIPBonus); - } - } - public List GetTriggerPackList(int type) - { - List newTriggerPackList = new List(); - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].lastID == type && _tables.TbTriggerPackManager.GetOrDefault(triggerPackList[i].ID) != null) - { - newTriggerPackList.Add(triggerPackList[i]); - } - } - newTriggerPackList.Sort((a, b) => a.ID.CompareTo(b.ID)); - return newTriggerPackList; - } - public void ShowTriggerPack(int type, int id) - { - for (int i = 0; i < triggerPackList.Count; i++) - { - if (triggerPackList[i].lastID == type && triggerPackList[i].ID == id) - { - var t = _tables.TbTriggerPackManager.GetOrDefault(id); - if (t.PackType == 53) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.MapPackPanel, t.PackType); - } - else if (t.PackType == 2) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.CommerceNoviceGiftPopupPanel, t.PackType); - } - else if (t.PackType == 1) - { - GContext.container.Resolve().AddGiftFaceUIOnLogin(t.ID, UITypes.GiftPopupPanel_6, t.PackType); - } - } - } - } - public TimeSpan GetCurTriggerPackEndTime(TriggerPackBuyData dailySignEvent) - { - DateTime curTime = ZZTimeHelper.UtcNow().UtcNowOffset(); - DateTime endTime = GlobalUtils.TryParseDateTime(dailySignEvent.time, curTime); - if (endTime.Ticks <= curTime.Ticks) - { - triggerPackList.Remove(dailySignEvent); - GContext.Publish(new TriggerPackEvent()); - SaveStore.Write("TriggerPackDataList", JsonMapper.ToJson(triggerPackList)).RequireAccepted(); - } - return endTime - curTime; - } - #endregion - - public TriggerPackBuyData GetTriggerPackBuyDataById(int packId) - { - return triggerPackList.FirstOrDefault(x => x.ID == packId); - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/017-EventPackData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/017-EventPackData.cs.txt deleted file mode 100644 index f146e69d7..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/017-EventPackData.cs.txt +++ /dev/null @@ -1,118 +0,0 @@ -using asap.core; -using GameCore; -using cfg; -public class EventPackData -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - private Tables _tables = GContext.container.Resolve(); - private struct Data - { - public int currentEventID; - public int purchaseCount; - public int VIPLvlWhenEventActivate; - public int redirectID; - public Data(int eventID = 0, int p = 0, int v = 0, int rid = 0) - { - currentEventID = eventID; - purchaseCount = p; - VIPLvlWhenEventActivate = v; - redirectID = rid; - } - } - private Data _data; - - internal static game.PlayerDataStorage.PlayerKVEventPackState DecodeForKVLoad(System.Collections.Generic.IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeEventPack(raw,snapshot,errors); - internal void ResetForKVLoad() { _data=default(Data); } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVEventPackState state) - { - if (state == null) throw new System.ArgumentNullException(nameof(state)); - _data=new Data { currentEventID=state.EventId,purchaseCount=state.PurchaseCount, - VIPLvlWhenEventActivate=state.VipLevel,redirectID=state.RedirectId }; - } - internal game.PlayerDataStorage.PlayerKVEventPackState SnapshotForKVValidation() => - new game.PlayerDataStorage.PlayerKVEventPackState(_data.currentEventID,_data.purchaseCount,_data.VIPLvlWhenEventActivate,_data.redirectID); - public int CurrentEventID { get { return _data.currentEventID; } } - public int PurchaseCount { get { return _data.purchaseCount; } } - public int VIPLvlWhenEventActivated { get { return _data.VIPLvlWhenEventActivate; } } - - public bool IsActive => _tables.TbFishingEvent.DataMap.ContainsKey(_data.currentEventID) && - (System.DateTime.Parse( - (_tables.TbFishingEvent[_data.currentEventID].TimeDefinition as LimitedTime) - ?.EndTime) - - ZZTimeHelper.UtcNow()).TotalSeconds > 0 && - PurchaseCount < _tables.TbEventPackManager[_data.redirectID].MaxCount; - public EventPackData() - { - //Debug.Log("construct"); - _data = new Data(); - //PlayFabMgr.Instance.UpdateUserDataValue("EventPackData", - // Newtonsoft.Json.JsonConvert.SerializeObject(_data)); - } - - public void AddPurchaceCount() - { - _data.purchaseCount++; - SaveEventPackData(); - } - /// - /// Refresh and update EventPackData if current event is not the event given. Will reset current - /// event if the event given is null - /// - /// New event - public bool UpdateEventData(cfg.FishingEvent e = null) - { - bool isUpdated = false; - if (e == null) - { - _data = new Data(); - isUpdated = true; - } - else if (_data.currentEventID != e.ID) - { - _data = new Data(e.ID, 0, GContext.container.Resolve().PriceLv, e.RedirectID); - isUpdated = true; - } - //else - // do nothing - SaveEventPackData(); - return isUpdated; - } - public void LoadEventPackData(string s) - { - //Debug.Log("load epd"); - _data = Newtonsoft.Json.JsonConvert.DeserializeObject(s); - //Debug.Log($"load: {_data.currentEventID}"); - if (!_tables.TbFishingEvent.DataMap.ContainsKey(_data.currentEventID) || - (System.DateTime.Parse((_tables.TbFishingEvent[_data.currentEventID].TimeDefinition - as LimitedTime).EndTime) - ZZTimeHelper.UtcNow()).TotalSeconds <= 0 ) - { - return; - } - if (_tables.TbEventPackManager[_tables.TbFishingEvent[_data.currentEventID].RedirectID].PackType != 1) - { - _data = new Data(); - return; - } - if (_data.redirectID == 0) - _data.redirectID = 4054001; - TriggerEventPack(); - } - public void SaveEventPackData() - { - playerSaveStore.Write("EventPackData", - Newtonsoft.Json.JsonConvert.SerializeObject(_data)).RequireAccepted(); - } - private void TriggerEventPack() - { - var tables = GContext.container.Resolve(); - FishingEvent e = tables.TbFishingEvent.DataMap[_data.currentEventID]; - int packID = _data.redirectID; - var packData = tables.TbEventPackManager.DataMap[packID];//pack data read from tables - // if (_data.purchaseCount < packData.MaxCount && packData.PackType == 1) - //TODO:change panel according to RedirecctID of current event - // GContext.container.Resolve(). - // AddGiftFaceUI(e.ID, UITypes.GiftPopupPanel_9, packData.PackType, true); - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/018-EventPartnerGatherManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/018-EventPartnerGatherManager.cs.txt deleted file mode 100644 index cc77fb685..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/018-EventPartnerGatherManager.cs.txt +++ /dev/null @@ -1,1755 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using asap.core; -using cfg; -using EventPartnerGather; -using game; -using GameCore; -using Newtonsoft.Json; -using UniRx; -using UnityEngine; - -using EEventBuildBuildState = EventPartnerGatherRequests.EEventBuildBuildState; -using EventPartnerGatherDetailResp = EventPartnerGatherRequests.EventPartnerGatherDetailResp; -using EventBuildBotInfo = EventPartnerData.EventBuildBotInfo; -using EEventBuildState = EventPartnerGatherRequests.EEventBuildState; -using AutoMatchStatusResponse = EventPartnerGatherRequests.AutoMatchStatusResponse; -using AutoMatchToggleResponse = EventPartnerGatherRequests.AutoMatchToggleResponse; - -namespace DataCenter -{ - public enum ESpinState - { - Normal, - Freespin, - Morespin - } - - // EventPartnerGather 游戏数据结构 - public class EventPartnerGatherData - { - public bool FirstOpen = true; - public int EventId; - public DateTime StartTime; - public DateTime EndTime; - - // UI数据 和实际数据可能不同,进入游戏的时候,可以进入下一步,保存的情况下执行开发 - // public int CurrentUIPoints = 0; - - - // 核心游戏数据 - public int CurrentPoints = 0; // 当前积分 - public int CurrentMiningProgress = 0; // 挖矿进度 - - // 同意需要多个 - // public readonly List CompletedNodes = new(); // 已完成的节点 - - // 好友系统数据(第二阶段) - // public List Friends = new(); - public int Token = 0; - - public int InvitedCount = 0; - // 代币数量, Detail的时候会获得吗 - public int TicketCount; // 公用的 - - public List> CompletedNodesList; - // - public List<(int myScore, int FriendScore)> BuilderPartnerScore; - - // 获取当前的 More状态 - // public List<(float BonusPercent, DateTime BonusExpireUtc)> BuilderPartnerBonus; - - // public List BuildFreeSpinNum; - - - public (float BonusPercent, DateTime BonusExpireUtc) PartnerBonus; - - public int FreeSpinNum; - - - // 获取机器人 - public Dictionary Bots { get; set; } - - // 是否领取最终奖励 - public bool IsRecvFinalReward = false; - - // UI 上显示是否完成, - public List UIFinishedPartners; - - // 当前活动 是否结束 - public bool IsFinished = false; - // 默认显示 - // public ESpinState SpinState = ESpinState.Normal; - //MoreSpin - // public float BonusPercent = 0f; - // public DateTime BonusExpireUtc = DateTime.MinValue; - //FreeSpin - // public int freeSpinNum = 0; - public ESpinState SpinState; - - public float InflationRate; - - // 自动匹配状态 - public bool IsEnableAutoMatch = false; // 自动匹配开关 - public DateTime LastAutoMatchTime = DateTime.MinValue; // 上次匹配时间 - } - - // EventPartnerGather 管理器 - public class EventPartnerGatherManager : IAutoMatchManagerContext - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - private const bool EnableTraceLogs = false; - public const string SaveKey = "EventPartnerGatherData"; - internal static game.PlayerDataStorage.PlayerKVPartnerState DecodeForKVLoad( - IReadOnlyDictionary raw,game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => game.PlayerDataStorage.PlayerKVSaveSchema.DecodePartner(raw,snapshot,errors); - - internal void ResetForKVLoad() - { - // Only a fresh controlled container is admitted. Never detach active gameplay work. - if(_isInit || _act!=null || _disposables!=null || _autoMatchStatusInFlight!=null || PartnerInfoManager.HasSubscriptionsForKVLoad) - throw new InvalidOperationException("Active partner module cannot enter KV load."); - var partner=new PartnerInfoManager(); - var robot=new EventPartnerGatherRobotInvitationSystem(); - GatherData=null; _isEventDataChanged=false; CurrentBuildPartner=null; - PartnerInfoManager=partner; RobotInvitationSystem=robot; - _fishingEvent=null; EventPartnerMineMainData=null; EventPartnerMineSpinPointList=null; EventPartnerMineInitData=null; - _nodeCumulativeSteps.Clear(); _nodeSteps.Clear(); _stageDropList.Clear(); StartTime=default; EndTime=default; - _isInit=false; _spinId=-1; _userGm=false; BonusPercent=0; BonusExpireDuration=0; - _dateTimeForGetEvent=default; startTime=0; delta=0; _lastAutoMatchStatusUtc=default; _cachedAutoMatchStatus=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVPartnerState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - if(!state.Present) { GatherData=null; return; } - GatherData=new EventPartnerGatherData - { - FirstOpen=state.FirstOpen,EventId=state.EventId,StartTime=state.StartTime,EndTime=state.EndTime, - CurrentPoints=state.CurrentPoints,CurrentMiningProgress=state.CurrentMiningProgress,Token=state.Token, - InvitedCount=state.InvitedCount,TicketCount=state.TicketCount, - CompletedNodesList=state.CompletedNodesList.Select(n=>new List(n)).ToList(), - BuilderPartnerScore=new List<(int,int)>(state.BuilderPartnerScore),PartnerBonus=(state.BonusPercent,state.BonusExpireUtc), - FreeSpinNum=state.FreeSpinNum,Bots=state.Bots.ToDictionary(p=>p.Key,p=>new EventBuildBotInfo - { Id=p.Value.Id,ScorePlayer=p.Value.ScorePlayer,ScoreBot=p.Value.ScoreBot,Grade=p.Value.Grade, - TargetScore=p.Value.TargetScore,WakeStartTime=p.Value.WakeStartTime,WakingSeconds=p.Value.WakingSeconds }), - IsRecvFinalReward=state.IsRecvFinalReward,UIFinishedPartners=new List(state.UIFinishedPartners), - IsFinished=state.IsFinished,SpinState=(ESpinState)state.SpinState,InflationRate=state.InflationRate, - IsEnableAutoMatch=state.IsEnableAutoMatch,LastAutoMatchTime=state.LastAutoMatchTime - }; - } -#if UNITY_EDITOR - internal bool RuntimeEmptyForKVValidation => !_isInit && !_isEventDataChanged && _act==null && _disposables==null && - _autoMatchStatusInFlight==null && _cachedAutoMatchStatus==null && _fishingEvent==null && CurrentBuildPartner==null && - EventPartnerMineMainData==null && EventPartnerMineSpinPointList==null && EventPartnerMineInitData==null && - _nodeCumulativeSteps.Count==0 && _nodeSteps.Count==0 && _stageDropList.Count==0 && StartTime==default && EndTime==default && - _spinId==-1 && !_userGm && BonusPercent==0 && BonusExpireDuration==0 && _dateTimeForGetEvent==default && - startTime==0 && delta==0 && _lastAutoMatchStatusUtc==default && !PartnerInfoManager.HasSubscriptionsForKVLoad; -#endif - [Inject] public Tables _tables { get; set; } - - [Inject] public EventPartnerService EventPartnerService { get; set; } - - - private FishingEvent _fishingEvent; - - // 检查数据是否改变过 - private bool _isEventDataChanged = false; - // 管理数值 - public PartnerInfoManager PartnerInfoManager { get; private set; } = new(); - public EventPartnerGatherRobotInvitationSystem RobotInvitationSystem { get; private set; } = new(); - // - public EventPartnerGatherData GatherData { get; private set; } - // 数据 - public EventPartnerMineMain EventPartnerMineMainData { get; private set; } - // 抽奖数据 - public List EventPartnerMineSpinPointList { get; private set; } - // 模型数据,目前开来需要构造模型从表里读取 - public EventPartnerMineInit EventPartnerMineInitData { get; private set; } - // 累分状态 - private readonly List _nodeCumulativeSteps = new(); - // 状态积分,最后需要去除一个 - private readonly List _nodeSteps = new(); - // - public List NodeSteps => _nodeSteps; - public List NodeCumulativeSteps => _nodeCumulativeSteps; - public int MaxSteps => _nodeCumulativeSteps.Count - 1; - public int EventId => GatherData?.EventId ?? -1; - public bool ShouldCloseAutoMatch => PartnerInfoManager.IsFullyMatched; - public bool IsAutoMatchEnabled => GatherData?.IsEnableAutoMatch ?? false; - public int AutoMatchSlotCount => PartnerInfoManager.BuildPartners.Length; - - public DateTime StartTime; - // 结束时间 - public DateTime EndTime; - - - - - private readonly List _stageDropList = new(); - - private CompositeDisposable _disposables; - - public bool IsFirstOpen - { - get => GatherData?.FirstOpen ?? false; - set - { - if (GatherData != null && GatherData.FirstOpen) - { - GatherData.FirstOpen = false; - SaveData(); - } - } - } - - public void UpdateEventData(FishingEvent fishingEvent) - { - Trace($"UpdateEventData eventId={fishingEvent?.ID}"); - _fishingEvent = fishingEvent; - if (GatherData != null && _fishingEvent != null && GatherData.EventId != _fishingEvent.ID) - { - ClearData(); - } - - if (!_isInit || GatherData == null) - { - _isInit = false; - Init(); - } - else - { - // { - UpdateLocalData(); - UpdateTime(); - SetRedPoint(); - // } - } - } - - #region 红点相关 - public void SetRedPoint() - { - if (GatherData != null) - { - RedPointManager.Instance.SetRedPointState(RedPointKey, GatherData.TicketCount > 0, GatherData.TicketCount); - } - else - { - RedPointManager.Instance.SetRedPointState(RedPointKey, false); - } - } - - public string RedPointKey { get; private set; } = RedPointName.Home_Parther; - #endregion - - // 有可能改时间的,改时间不可清空保存的值 - // public void ProcessLastChallenge() - // { - // UpdateTime(); - // if (GatherData != null) - // { - // if (!IsTimeFinished()) - // { - // ClearData(); - // } - // } - // } - - // - - - private bool _isInit = false; - - public void Init() - { - if (_fishingEvent == null) - return; - if (_isInit) - return; - Trace($"Init eventId={EventId}"); - - if (GatherData == null) - { - CreateNewData(); - } - InitManager(); - UpdateLocalData(); - UpdateTime(); - SetRedPoint(); - _isInit = true; - } - - - public void ReInit() - { - _isInit = false; - Init(); - } - - private void CreateNewData() - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - var ticketCount = GContext.container.Resolve().GetInitWelcomeGift(_fishingEvent.ID); - GatherData = new EventPartnerGatherData - { - FirstOpen = true, - EventId = _fishingEvent.ID, - StartTime = startTime, - EndTime = endTime, - CurrentPoints = 0, - CurrentMiningProgress = 0, - TicketCount = ticketCount, - - BuilderPartnerScore = new List<(int myScore, int partnerScore)>(), - - // { - // (0,0),(0,0),(0,0) - // }, - PartnerBonus = (0F, DateTime.MinValue), - CompletedNodesList = new List>(), - // { - // new(), - // new(), - // new(), - // }, - // BuildFreeSpinNum = new List{0,0,0}, - FreeSpinNum = 0, - Bots = new Dictionary(), - // IsGetFinalReward = new List - // { - // false,false,false, - // }, - IsRecvFinalReward = false, - UIFinishedPartners = new List(), - // { false, false, false }, - InflationRate = GContext.container.Resolve().InflationRate, - }; - - for (var i = 0; i < PartnerInfoManager.BuilderCapacity; ++i) - { - GatherData.BuilderPartnerScore.Add( (myScore:0,FriendScore:0)); - GatherData.CompletedNodesList.Add(new List()); - GatherData.UIFinishedPartners.Add(false); - } - - StartTime = startTime; - EndTime = endTime; - GContext.container.Resolve().SaveTransitionData(EventId, GatherData.TicketCount); - SaveData(); - } - - private void InitManager() - { - InitPartnerInfoManager(); - InitRobotInvitationSystem(); - } - - private void InitPartnerInfoManager() - { - PartnerInfoManager.Init(); - PartnerInfoManager.EventId = EventId; - } - - private void InitRobotInvitationSystem() - { - RobotInvitationSystem.Init(); - } - - - private void UpdateLocalData() - { - Trace($"UpdateLocalData eventId={EventId}"); - if (_fishingEvent == null) return; - - var redirectId = _fishingEvent.RedirectID; - var eventPartnerDataList = _tables.TbEventPartnerMineMain.DataList; - EventPartnerMineMainData = eventPartnerDataList.FirstOrDefault(data => data.ID == redirectId); - // var allSpinPoints = _tables.TbEventPartnerMineSpinPoint.DataList; - var ids = EventPartnerMineMainData?.SpinPoint; - if (ids is { Count: > 0 }) - { - var filtered = new List(); - foreach (var id in ids) - { - var sp = _tables.TbEventPartnerMineSpinPoint.GetOrDefault(id); - if (sp != null) filtered.Add(sp); - } - EventPartnerMineSpinPointList = filtered; - } - else - { - EventPartnerMineSpinPointList = new List(); - } - _nodeCumulativeSteps.Clear(); - _nodeSteps.Clear(); - if (EventPartnerMineMainData?.StagePoint is { Count: > 0 }) - { - var sum = 0; - foreach (var stagePoint in EventPartnerMineMainData.StagePoint) - { - _nodeSteps.Add(stagePoint); - sum += stagePoint; - _nodeCumulativeSteps.Add(sum); - } - } - var eventPartnerMineInitDataList = _tables.TbEventPartnerMineInit.DataList; - EventPartnerMineInitData = eventPartnerMineInitDataList.FirstOrDefault(data => data.ID == redirectId); - - // if (EventPartnerMineMainData != null) - // GContext.container.Resolve().EventRefresh(_fishingEvent, EventPartnerMineMainData.RushId, RushType.OneDataKey); - } - - private void UpdateTime() - { - if (_fishingEvent != null) - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow().AddDays(-1)); - if (GatherData != null) - { - if (GatherData.EventId == _fishingEvent.ID) - { - GatherData.StartTime = startTime; - GatherData.EndTime = endTime; - } - else - { - GatherData.EndTime = DateTime.Now.AddDays(-1); - } - } - EndTime = endTime; - StartTime = startTime; - } - } - - private void ValidateAndUpdateData() - { - if (GatherData == null) return; - // 验证时间有效性 - // if (!IsTimeFinished()) - // { - // HandleEventEnd(); - // } - } - - public bool IsTimeFinished() - { - var now = ZZTimeHelper.UtcNow(); - Trace($"CheckTimeFinished now={now} endTime={EndTime}"); - return now > EndTime; - } - - - public bool IsTimeValid() - { - if (GatherData == null) return false; - - var now = ZZTimeHelper.UtcNow(); - return now >= StartTime && now <= EndTime; - } - - public TimeSpan GetRemainingTime() - { - if (GatherData == null) - return TimeSpan.Zero; - - return EndTime - ZZTimeHelper.UtcNow(); - } - - public int GetFreeSpin(int slotId) - { - if (GatherData == null) return 0; - // var freeSpinNum = GatherData.BuildFreeSpinNum[slotId]; - // return freeSpinNum; - return GatherData.FreeSpinNum; - } - - public TimeSpan GetMoreTimeSpan(int slotId) - { - if (GatherData == null) return TimeSpan.Zero; - if (!IsBonusActive(slotId)) return TimeSpan.Zero; - var builderPartnerBonus = GatherData.PartnerBonus; - // var timespan = DateTime.MinValue - ZZTimeHelper.UtcNow(); - // Log($"builderPartnerBonus = {builderPartnerBonus.BonusExpireUtc},{builderPartnerBonus.BonusPercent}"); - return builderPartnerBonus.BonusExpireUtc - ZZTimeHelper.UtcNow(); - } - - - - public bool CheckOpen() - { - if (GatherData == null) return false; - if (!IsTimeValid()) return false; - if (GatherData.IsFinished) return false; - - return true; - } - - public static T WeightedRandom(Dictionary weightTable) - { - // 1. 计算总权重 - var totalWeight = weightTable.Values.Sum(); - // 2. 生成随机数 - var randomValue = UnityEngine.Random.Range(0, totalWeight); - - // 3. 线性遍历选择 - var currentWeight = 0; - foreach (var (key, value) in weightTable) - { - currentWeight += value; - if (randomValue < currentWeight) - return key; - } - return default; // 理论上不会执行到这里 - } - - // 核心游戏逻辑 - // 抽奖数据 - public EventPartnerMineSpinPoint GetSpinPointElem(bool noCheating = false) - { - if (EventPartnerMineSpinPointList is { Count: > 0 }) - { - // 根据权重,生成字典 - var dict = EventPartnerMineSpinPointList.ToDictionary(elem => elem, elem => elem.Weight); - var elem = WeightedRandom(dict); - Trace($"GetSpinPointElem spinId={elem.ID}"); - if (_userGm && _spinId != -1) - { - var elem1 = EventPartnerMineSpinPointList.Find(ele => ele.ID == _spinId); - if (elem1 != null) - { - Trace($"GetSpinPointElemGM spinId={elem1.ID}"); - return elem1; - } - } - return elem; - } - return null; - } - - public void AddPoints(int points) - { - if (GatherData == null) - { - LogWarning($"AddPointsInvalid eventId={EventId} reason=GatherDataNull"); - return; - } - - if (GatherData.IsFinished) - { - LogWarning($"AddPointsInvalid eventId={EventId} reason=EventFinished"); - return; - } - - if (points <= 0) - { - LogWarning($"AddPointsInvalid eventId={EventId} reason=InvalidValue points={points}"); - return; - } - - GatherData.CurrentPoints += points; - // var currentMiningProgress = CalcMiningProgressOld(GatherData.CurrentPoints); - // GatherData.CurrentMiningProgress = currentMiningProgress; - CurrentBuildPartner.AddSelfScore(points); - SavePartnerInfo(CurrentBuildPartner.SlotId); - Trace($"AddPoints eventId={EventId} delta={points} totalPoints={GatherData.CurrentPoints}"); - UpdatePointAdd(); - } - - // 挖完了的时候,Step算在后面 - public int CalcMiningProgressNew(int points) - { - var maxStep = _nodeCumulativeSteps.Count; - for (var i = 0; i < maxStep; ++i) - { - if (points < _nodeCumulativeSteps[i]) - { - return i; - } - } - return maxStep - 1; - } - // 计算落在阶段,考虑机器人用,别出意外 - public int CalcMiningProgressOld(int points) - { - var maxStep = _nodeCumulativeSteps.Count; - for (var i = 0; i < maxStep; ++i) - { - if (points <= _nodeCumulativeSteps[i]) - { - return i; - } - } - return maxStep - 1; - } - - private void UpdatePointAdd() - { - GContext.Publish(new EventPartnerGatherPointsUpdate { Points = GatherData.CurrentPoints }); - // 检查是否需要触发自动挖矿 - // CheckAutoMining(); - } - - public bool CompleteStage(int stageIndex) - { - Trace($"CompleteStage eventId={EventId} stageIndex={stageIndex} slotId={CurrentBuildPartner?.SlotId}"); - var stageReward = EventPartnerMineMainData.StageReward; - - var slotId = CurrentBuildPartner.SlotId; - var completedNodes = GatherData.CompletedNodesList[slotId]; - if (stageIndex >= 0 && stageIndex < stageReward.Count) - { - if (!completedNodes.Contains(stageIndex)) - { - completedNodes.Add(stageIndex); - _stageDropList.Add(EventPartnerMineMainData.StageReward[stageIndex]); - // 发放节点奖励 - // DistributeStageReward(nodeIndex); - if (CurrentBuildPartner.IsPartnerRobot) - { - CurrentBuildPartner.ScheduleBotScoreAction(); - } - SaveData(); - return true; - } - } - return false; - } - - - public bool IsCompleteStageAll(int slotId) - { - var completedNodes = GatherData.CompletedNodesList[slotId]; - var stageReward = EventPartnerMineMainData.StageReward; - - var finalStaqe = stageReward.Count - 1; - return completedNodes.Contains(finalStaqe); - } - - private void DistributeStageReward(int stageIndex) - { - Trace($"DistributeStageReward stageIndex={stageIndex}"); - var stageReward = EventPartnerMineMainData.StageReward; - var playerItemData = GContext.container.Resolve(); - if (stageIndex >= 0 && stageIndex < stageReward.Count - 1) - { - var dropId = stageReward[stageIndex]; - ChangeSource changeSource = new ChangeSource(GatherData.EventId, "Event_Minigame4", "Event_Minigame4_Partner", "StageReward"); - - playerItemData.AddItemByDropListLureInflation(GatherData.InflationRate, new List { dropId, }, changeSource); - GContext.Publish(new ShowData()); - } - } - - private int GetNodeRewardDropId(int nodeIndex) - { - return EventPartnerMineMainData.StageReward[nodeIndex]; - } - - private void DistributeFinalReward() - { - var dropId = GetFinalRewardDropId(); - if (dropId > 0) - { - var playerItemData = GContext.container.Resolve(); - var rewards = playerItemData.GetItemDataByDropIdLureInflation(GatherData.InflationRate, dropId); - ChangeSource changeSource = new ChangeSource(GatherData.EventId, "Event_Minigame4", "Event_Minigame4_Partner", "GrandReward"); - - playerItemData.AddItem(rewards, changeSource); - GContext.Publish(new ShowData(rewards)); - } - } - - private int GetFinalRewardDropId() - { - // 最终奖励掉落ID(后续从配置表读取) - return EventPartnerMineMainData.Reward; - } - - // private void HandleEventEnd() - // { - // if (GatherData == null || GatherData.IsFinished) return; - // - // Log("Event Ended"); - // - // // 结算未领取的奖励 - // if (GatherData.CurrentMiningProgress >= MaxSteps && !GatherData.IsFinished) - // { - // HandleGameComplete(); - // } - // - // ClearData(); - // } - - public int ResolvePointsWithBuffer(int points) - { - var rtPoints = points; - var slotId = CurrentBuildPartner?.SlotId ?? -1; - if (IsBonusActive(slotId)) - { - // rtPoints *= (1 + GatherData.BonusPercent); - // var slotId = CurrentBuildPartner.SlotId; - // var (bonusPercent, bonusExpireUtc) = GatherData.BuilderPartnerBonus[slotId]; - var (bonusPercent, bonusExpireUtc) = GatherData.PartnerBonus; - rtPoints = (int)(rtPoints * (1 + bonusPercent)); - } - return Mathf.Max(0, rtPoints); - } - - // public int ResolveSpinPoints(EventPartnerMineSpinPoint p) - // { - // if (p?.SpinPointParam == null) return 0; - // return p.SpinPointParam switch - // { - // NormalSpinPoint n => ResolvePointsWithBuffer(n.SpinPoints), - // FreeSpinPoint f => ResolvePointsWithBuffer(f.SpinPoints), - // MoreSpinPoint m => ResolvePointsWithBuffer(m.SpinPoints), - // _ => 0 - // }; - // } - // - // public ESpinState GetSpinState(EventPartnerMineSpinPoint p) - // { - // var spinState = p.SpinPointParam switch - // { - // NormalSpinPoint n => ESpinState.Normal, - // FreeSpinPoint f => ESpinState.Freespin, - // MoreSpinPoint m => ESpinState.Morespin, - // _ => ESpinState.Normal - // }; - // return spinState; - // } - - public void DoEventWithSpinState(EventPartnerMineSpinPoint p) - { - switch (p.SpinPointParam) - { - case NormalSpinPoint n: - FinFreeSpin(); - break; - case FreeSpinPoint f: - ApplyFreeSpin(1); - break; - case MoreSpinPoint m: - FinFreeSpin(); - ResolveBonus(m.BonusPercent, m.BonusDuration); - break; - } - } - - - public int ResolveSpinAndGetPoints(EventPartnerMineSpinPoint p, out ESpinState spinState) - { - spinState = ESpinState.Normal; - if (p?.SpinPointParam == null) return 0; - - switch (p.SpinPointParam) - { - case NormalSpinPoint n: - spinState = ESpinState.Normal; - return ResolvePointsWithBuffer(n.SpinPoints); - case FreeSpinPoint f: - spinState = ESpinState.Freespin; - return ResolvePointsWithBuffer(f.SpinPoints); - case MoreSpinPoint m: - spinState = ESpinState.Morespin; - return ResolvePointsWithBuffer(m.SpinPoints); - } - return 0; - } - public void CleanSpinState() - { - if (GatherData == null) return; - // GatherData.freeSpinNum = 0; - GatherData.SpinState = ESpinState.Normal; - } - // 添加FreeSpin 状态 - private void ApplyFreeSpin(int freeSpinNum) - { - if (GatherData == null) return; - var slot = CurrentBuildPartner.SlotId; - // GatherData.BuildFreeSpinNum[slot] = freeSpinNum; - GatherData.FreeSpinNum = freeSpinNum; - } - - public void FinFreeSpin() - { - if (GatherData == null) return; - // var slot = CurrentBuildPartner.SlotId; - // GatherData.BuildFreeSpinNum[slot] = 0; - GatherData.FreeSpinNum = 0; - } - - - // 临时保存 - - public float BonusPercent; - public int BonusExpireDuration; - // public int spinPoint; - // - // public int SavePoint(int point) - // { - // spinPoint = point; - // return point; - // } - public void ResolveBonus(float percent, int durationSec) - { - BonusPercent = percent; - BonusExpireDuration = Mathf.Max(0, durationSec); - Trace($"ResolveBonus percent={BonusPercent} durationSec={BonusExpireDuration}"); - } - - private void ApplyBonus(float percent, int durationSec) - { - if (GatherData == null) return; - if (CurrentBuildPartner == null) return; - - // var buildSlot = CurrentBuildPartner.SlotId; - // if (GatherData.BuilderPartnerBonus != null) - // { - // GatherData.BuilderPartnerBonus[buildSlot] = (Mathf.Max(0f, percent), - // ZZTimeHelper.UtcNow().AddSeconds(Mathf.Max(0, durationSec))); - // } - GatherData.PartnerBonus = (Mathf.Max(0f, percent), - ZZTimeHelper.UtcNow().AddSeconds(Mathf.Max(0, durationSec) + 0.5f)); - SaveData(); - } - - // 确定是否过期?? - public void EnsureBonusValid() - { - if (GatherData == null) return; - if (CurrentBuildPartner == null) return; - - // var slotId = CurrentBuildPartner.SlotId; - // var (_, bonusExpireUtc) = GatherData.BuilderPartnerBonus[slotId]; - var (_, bonusExpireUtc) = GatherData.PartnerBonus; - if (ZZTimeHelper.UtcNow() > bonusExpireUtc) - { - // GatherData.BonusPercent = 0f; - // GatherData.BonusExpireUtc = DateTime.MinValue; - // GatherData.BuilderPartnerBonus[slotId] = (0f, DateTime.MinValue); - GatherData.PartnerBonus = (0f, DateTime.MinValue); - SaveData(); - GContext.Publish(new EventPartnerGatherBonusEndEvent()); - } - - // if (CurrentBuildPartner == null) return; - // if (CurrentBuildPartner.BonusPercent > 0f && ZZTimeHelper.UtcNow() > CurrentBuildPartner.BonusExpireUtc) - // { - // GatherData.BonusPercent = 0f; - // GatherData.BonusExpireUtc = DateTime.MinValue; - // SaveData(); - // GContext.Publish(new EventPartnerGatherRefreshBonus()); - // } - } - public bool IsBonusActive(int slotId) - { - if (GatherData == null) return false; - if (slotId == -1) return false; - // var (bonusPercent, bonusExpireUtc) = GatherData.BuilderPartnerBonus[slotId]; - var (bonusPercent, bonusExpireUtc) = GatherData.PartnerBonus; - return bonusPercent > 0f && ZZTimeHelper.UtcNow() < bonusExpireUtc; - } - public void SaveData() - { - // Log("SaveData()-> "); - -#if UNITY_EDITOR - Trace($"SaveData eventId={EventId}"); -#endif - { - SaveStore.Write(SaveKey, JsonConvert.SerializeObject(GatherData)).RequireAccepted(); - } - } - public void LoadData(string dataValue) - { - Trace($"LoadData eventId={EventId} hasData={!string.IsNullOrEmpty(dataValue)}"); - if (!string.IsNullOrEmpty(dataValue)) - { - GatherData = JsonConvert.DeserializeObject(dataValue); - } - } - public void ClearData() - { - GatherData = null; - - CurrentBuildPartner?.ClearData(); - // CurrentBuildPartner.ClearReceivedCalls(); - SaveData(); - } - - // 进入游戏场景 - public void EnterGatherScene() - { - Trace($"EnterGatherScene eventId={EventId}"); - IsFirstOpen = false; - // var list = EventPartnerMineMainData.Addressable; - GContext.Publish(new UnloadActToNextAct("EventPartnerGatherAct", UITypes.CloudTransitionPanel, 0.5f)); - } - - public BuildPartner CurrentBuildPartner { get; set; } - // 开始采矿 - public void StartBuildProgress(BuildPartner buildPartner) - { - CurrentBuildPartner = buildPartner; - // 更新点数 - var points = buildPartner.ScorePartnerActual + buildPartner.ScoreSelfActual; - GatherData.CurrentPoints = points; - // GatherData.CurrentMiningProgress = CalcMiningProgressNew(points); - Trace($"StartBuildProgress eventId={EventId} slotId={CurrentBuildPartner?.SlotId} partnerId={CurrentBuildPartner?.PartnerId}"); - ((EventPartnerGatherAct)_act)?.OnEnterGather(); - } - - public void FinishMining() - { - Trace($"FinishMining eventId={EventId}"); - ((EventPartnerGatherAct)_act)?.OnLeaveGather(); - } - - private static void LogError(object t) - { - Debug.LogError($"EventPartnerGatherManager-> {t} "); - } - private static void ELog(object t) - { -#if UNITY_EDITOR - Debug.Log($"EventPartnerGatherManager-> {t} "); -#endif - } - [System.Diagnostics.Conditional("UNITY_EDITOR")] - private static void Trace(object t) - { - if (!EnableTraceLogs) return; - ELog(t); - } - //- - public static void Log(string message) - { - Debug.Log($"EventPartnerGatherManager-> {message} "); - } - public static void LogWarning(string message) - { - Debug.LogWarning($"EventPartnerGatherManager-> {message} "); - } - - private AGameAct _act; - public void SetGameAct(AGameAct act) - { - _act = act; - } - - public AGameAct GetGameAct() - { - return _act; - } - - - /// - /// 通知所有绑定组件刷新数据显示 - /// - public void RefreshAllUI() - { - if (GatherData == null) return; - // 刷新抽奖面板 - // if (_drawPanel) - // { - // _drawPanel?.SetMiningProgress(GatherData.CurrentMiningProgress); - // } - - Trace($"RefreshAllUI eventId={EventId}"); - } - - - // 有可能会激活,不应该在OnEnable 中调用Init(); - // public bool CheckForOnEnable() - // { - // - // return false - // } - - // 获取挖矿的数量 - public int CalcWaNum(int point, out int leftPoint) - { - var minePoint = EventPartnerMineMainData.MinePoint; - var num = Mathf.Clamp(point / minePoint, 0, point); - - leftPoint = (point - num * minePoint); - return num; - } - - // 获取当前Spin的Cost - public int CalcSpinCost(int multipleValue) - { - return multipleValue * EventPartnerMineMainData.SpinRequire; - } - // - public int GetCumulativeStepPoint(int prevStep) - { - if (prevStep < 0) - return 0; - prevStep = Mathf.Clamp(0, prevStep, _nodeCumulativeSteps.Count - 1); - return _nodeCumulativeSteps[prevStep]; - } - - public int GetStageReward(int step) - { - return EventPartnerMineMainData.StageReward[step]; - } - // - public int GetStepPoints(int step) - { - return step < _nodeSteps.Count ? _nodeSteps[step] : 0; - } - - public int GetGoColumn(int waPoint, int waProgress) - { - var num = CalcWaNum(waPoint, out var leftPoint); - var column = 0; - // if (leftPoint > 0) - // { - // num += 1; - // } - var mps = EventPartnerMineMainData.MinePointShow[waProgress]; - if (EventPartnerMineMainData != null) - { - column = num / mps; - // column2 = num2 / mps; - } - Trace($"GetGoColumn waPoint={waPoint} num={num} curProgress={waProgress} mps={mps} column={column}"); - return column; - } - - // private readonly int maxCol = 3; - // 每次挖矿最多消耗的点数,根据排数进行计算 - public int GetConsumePoint(int curProgress) - { - var maxCol = EventPartnerMineMainData.MaxColumn; - var oreScore = EventPartnerMineMainData.MinePoint; - var mps = EventPartnerMineMainData.MinePointShow[curProgress]; - return mps * maxCol * oreScore; - } - - // 根据点数获得进度 - - // AGG 使用 - public int GetMiningProgress() - { - // return GatherData.CurrentMiningProgress; - var currentProgress = CalcMiningProgressNew(CurrentBuildPartner.ScorePartnerActual + CurrentBuildPartner.ScoreSelfActual); - return currentProgress; - } - - // - // public int NextMiningProgress() - // { - // Log($"NextMiningProgress()-> {GatherData.CurrentMiningProgress}"); - // GatherData.CurrentMiningProgress += 1; - // // var curLeftPoint = GetStepPoints(GatherData.CurrentMiningProgress); - // // SetLeftPoint(curLeftPoint); - // Log($"NextMiningProgress()-> End: {GatherData.CurrentMiningProgress}"); - // SaveData(); - // return GatherData.CurrentMiningProgress; - // } - // - // public int GetFullStep() - // { - // var stagePoint = EventPartnerMineMainData.StagePoint; - // return stagePoint.Count; - // } - - public bool PlayGetStageReward() - { - Trace($"PlayGetStageReward currentProgress={GatherData?.CurrentMiningProgress} dropCount={_stageDropList.Count}"); - var playerItemData = GContext.container.Resolve(); - if (_stageDropList.Count > 0) - { - ChangeSource changeSource = new ChangeSource(GatherData.EventId, "Event_Minigame4", "Event_Minigame4_Partner", "StageReward"); - - var itemDatas = playerItemData.AddItemByDropListLureInflation(GatherData.InflationRate, _stageDropList, changeSource); - GContext.Publish(new ShowData()); - _stageDropList.Clear(); - - var partnerId = CurrentBuildPartner?.PartnerId ?? ""; - if (CurrentBuildPartner is { IsPartnerRobot: true }) - { - partnerId = "robot"; - } - Trace($"PlayGetFinalReward partnerId={partnerId}"); -#if AGG - using (var e = GEvent.GameEvent("event_partners_gather_reward")) - { - var hookCount = 0; - if (itemDatas is { Count: > 0 }) - { - for (int i = 0; i < itemDatas.Count; i++) - { - if (itemDatas[i].id == 1001) - { - hookCount += itemDatas[i].count; - } - } - } - e.AddContent("teammate_id", partnerId) - .AddContent("position_id", CurrentBuildPartner.SlotId) - .AddContent("stage_id", GetMiningProgress()) - .AddContent("reward_hook", hookCount); - } -#endif - SaveData(); - return true; - } - - return false; - } - // 某一个stage获得奖励 - public bool PlayGetStageReward(int stageIndex) - { - var stageReward = EventPartnerMineMainData.StageReward; - var playerItemData = GContext.container.Resolve(); - if (stageIndex >= 0 && stageIndex < stageReward.Count - 1) - { - var dropId = stageReward[stageIndex]; - ChangeSource changeSource = new ChangeSource(GatherData.EventId, "Event_Minigame4", "Event_Minigame4_Partner", "StageReward"); - - playerItemData.AddItemByDropListLureInflation(GatherData.InflationRate, new List { dropId, }, changeSource); - GContext.Publish(new ShowData()); - } - - // CompleteTrainNode(stageIndex); - return false; - } - private int GetFinalReward() - { - return EventPartnerMineMainData.Reward; - } - public void PlayGetFinalReward() - { - // var slotId = CurrentBuildPartner.SlotId; - if (GatherData.IsRecvFinalReward) - { - return; - } - GatherData.IsRecvFinalReward = true; - // SaveData(); - var playerItemData = GContext.container.Resolve(); - var dropId = GetFinalReward(); - ChangeSource changeSource = new ChangeSource(GatherData.EventId, "Event_Minigame4", "Event_Minigame4_Partner", "GrandReward"); - - var itemDatas = playerItemData.AddItemByDropListLureInflation(GatherData.InflationRate, new List { dropId, }, changeSource); - - var partnerId = CurrentBuildPartner?.PartnerId ?? ""; - if (CurrentBuildPartner is { IsPartnerRobot: true }) - { - partnerId = "robot"; - } - Trace($"PlayGetFinalReward partnerId={partnerId}"); - -#if AGG - using (var e = GEvent.GameEvent("event_partners_gather_reward")) - { - var hookCount = 0; - if (itemDatas is { Count: > 0 }) - { - for (int i = 0; i < itemDatas.Count; i++) - { - if (itemDatas[i].id == 1001) - { - hookCount += itemDatas[i].count; - } - } - } - e.AddContent("teammate_id", partnerId) - .AddContent("position_id", 99) - .AddContent("stage_id", 99) - .AddContent("reward_hook", hookCount); - } -#endif - GContext.Publish(new ShowData()); - - SaveData(); - } - // - public int CollectPointAndCalcValid(int step, int points) - { - // var step = GatherData.CurrentMiningProgress; - // return AddCollectPoints(points) - return points - GetCumulativeStepPoint(step - 1); - } - - private int _spinId = -1; - private bool _userGm = false; - - public void GmSetSpinId(int spinId) - { - _spinId = spinId; - if (spinId > 0) - { - _userGm = true; - } - } - - public void CloseGM() - { - _userGm = false; - _spinId = -1; - } - - public List GetSpinMag() - { - return EventPartnerMineMainData.SpinMag; - } - - public bool IsStepFinished(int slotId, int step) - { - // return GatherData?.CompletedNodes?.Contains(step) ?? false; - // var slotId = CurrentBuildPartner.SlotId; - var completeNode = GatherData?.CompletedNodesList[slotId] ?? new List(); - return completeNode?.Contains(step) ?? false; - } - - - public void LoadPlayFabData() - { - // PartnerInfoManager.LoadPlayFabData(); - - // 之前是为了适配,后面看看是否可删除 - var buildScore = GatherData.BuilderPartnerScore; - if (buildScore == null) - { - //buildScore = new List<(int myScore, int FriendScore)> { (0, 0), (0, 0), (0, 0) }; - buildScore = new List<(int myScore, int FriendScore)>(); - for (var i = 0; i < PartnerInfoManager.BuilderCapacity; ++i) - { - buildScore.Add((0, 0)); - } - - - GatherData.BuilderPartnerScore = buildScore; - // 很少会调用 - SaveData(); - } - - // var builderPartnerBonus = GatherData.BuilderPartnerBonus; - // var builderPartnerBonus = GatherData.PartnerBonus; - // if (builderPartnerBonus == null) - { - // builderPartnerBonus = new List<(float BonusPercent, DateTime BonusExpireUtc)> - // { - // (0F, DateTime.MinValue), (0F, DateTime.MinValue), (0F, DateTime.MinValue) - // }; - // GatherData.PartnerBonus = (0F, DateTime.MinValue); - // SaveData(); - } - - var completedNodesList = GatherData.CompletedNodesList; - if (completedNodesList == null) - { - completedNodesList = new List>(); - // { - // new(), new(), new(), - // }; - for (var i = 0; i < PartnerInfoManager.BuilderCapacity; ++i) - { - completedNodesList.Add(new List()); - } - GatherData.CompletedNodesList = completedNodesList; - SaveData(); - } - - var bots = GatherData.Bots; - if (bots == null) - { - bots = new Dictionary(); - GatherData.Bots = bots; - SaveData(); - } - - - var fi = GatherData.UIFinishedPartners; - if (fi == null) - { - fi = new List { false, false, false }; - GatherData.UIFinishedPartners = fi; - SaveData(); - } - - // var bf = GatherData.BuildFreeSpinNum; - // if (bf == null) - // { - // bf = new List { 0, 0, 0 }; - // GatherData.BuildFreeSpinNum = bf; - // SaveData(); - // } - - PartnerInfoManager.SyncGatherData(this); - } - - // - private readonly int _timeCount = 60 * 2; - // 定时 - private DateTime _dateTimeForGetEvent = DateTime.MinValue; - // 是否允许请求 - private bool CheckGetDetailEnable() - { - var timeSpan = ZZTimeHelper.UtcNow() - _dateTimeForGetEvent; - return timeSpan.TotalSeconds > _timeCount; - } - public async Task GetEventDetail(bool force = false) - { - if (!force && !CheckGetDetailEnable()) - return false; - - _dateTimeForGetEvent = ZZTimeHelper.UtcNow(); - - var resp = await EventPartnerService.GetEventDetail(EventId); - switch (resp?.State) - { - case EEventBuildState.Success: - LoadBuilderData(resp); - return true; - case EEventBuildState.Failed: - case EEventBuildState.InviteNotFound: - case EEventBuildState.AlreadyExist: - case EEventBuildState.NoActiveEvent: - case EEventBuildState.Full: - default: - return false; - } - } - - public void LoadBuilderData(EventPartnerGatherDetailResp resp) - { - Trace($"LoadBuilderData eventId={EventId} state={resp?.State}"); - PartnerInfoManager.LoadBuildInfo(resp.Detail, GatherData.Bots); - PartnerInfoManager.LoadScore(resp.Detail.Scores, GatherData.BuilderPartnerScore); - } - - public async Task BuildWorks(int score, int cost) - { - if (GatherData.TicketCount < cost) - { - // Log("当前的代币不够用了"); - // ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_21")); - GContext.Publish(new EventPartnerGatherShowPack()); - return false; - } - - - if (score <= 0 && cost > 0) - { - return false; - } - - var partnerId = CurrentBuildPartner.PartnerId; - var newScore = CurrentBuildPartner.ScoreSelfActual + score; - // CurrentBuildPartner.ScoreSelfActual = newScore; - Trace($"BuildWorks eventId={EventId} partnerId={partnerId} newScore={newScore} cost={cost}"); - - if (partnerId.EndsWith(EventPartnerBot.RobotIdentifier)) - { - // CurrentBuildPartner.SyncRobotScore(); - // DoNothing(); - } - else - { - var response = await EventPartnerService.BuildWorks(partnerId, newScore, EventId); - if (response.State != EEventBuildBuildState.Success) - { - LogWarning($"BuildRequestFailed eventId={EventId} partnerId={partnerId} state={response.State} reason={response.Message}"); - return false; - } - } - AddTicket(-cost); - return true; - } - - public void AddTicketPure(int costValue) - { - if (GatherData != null) - { - GatherData.TicketCount += costValue; - if (GatherData.TicketCount < 0) - { - GatherData.TicketCount = 0; - } - GContext.container.Resolve().SaveTransitionData(EventId, GatherData.TicketCount); - GContext.Publish(new EventPartnerGatherUpdateTicketCount()); - SaveData(); - } - } - public void AddTicket(int costValue) - { - if (GatherData != null) - { - GatherData.TicketCount += costValue; - if (GatherData.TicketCount < 0) - { - GatherData.TicketCount = 0; - } - GContext.container.Resolve().SaveTransitionData(EventId, GatherData.TicketCount); - GContext.Publish(new EventPartnerGatherUpdateTicketCount()); - SaveData(); - } - SetRedPoint(); - } - - public int GetLeftPoint(int usedPoints, int progress) - { - // var progress = CalcMiningProgressOld(usedPoints); - if (progress >= _nodeCumulativeSteps.Count) - { - return 0; - } - return NodeCumulativeSteps[progress] - usedPoints; - } - - public void AddInvitationCount() - { - GatherData.InvitedCount++; - } - - public void ResetBuildPartner(int slotId) - { - Trace($"ResetBuildPartner eventId={EventId} slotId={slotId}"); - // - if (GatherData.UIFinishedPartners != null && slotId < GatherData.UIFinishedPartners.Count) - { - GatherData.UIFinishedPartners[slotId] = false; - } - - if (GatherData.BuilderPartnerScore != null && slotId < GatherData.BuilderPartnerScore.Count) - { - GatherData.BuilderPartnerScore[slotId] = (0, 0); - } - - if (GatherData.CompletedNodesList != null && slotId < GatherData.CompletedNodesList.Count) - { - GatherData.CompletedNodesList[slotId] = new List(); - } - } - - public void SavePartnerInfo(int slotId) - { - Trace($"SavePartnerInfo eventId={EventId} slotId={slotId}"); - var partners = PartnerInfoManager.BuildPartners; - if (slotId > partners.Length - 1) - { - Trace($"SyncFromPartnerInfoFailed eventId={EventId} slotId={slotId} partnerCount={partners.Length}"); - return; - } - - var partner = partners[slotId]; - partner.ScorePartnerDisplay = partner.ScorePartnerActual; - partner.ScoreSelfDisplay = partner.ScoreSelfActual; - GatherData.BuilderPartnerScore[slotId] = (partner.ScoreSelfActual, partner.ScorePartnerActual); - SaveData(); - } - - public void SyncPartnerInfoToSave() - { - Trace($"SyncFromPartnerInfo eventId={EventId}"); - var partners = PartnerInfoManager.BuildPartners; - for (var i = 0; i < partners.Length; ++i) - { - var partner = partners[i]; - GatherData.BuilderPartnerScore[i] = (partner.ScoreSelfActual, partner.ScorePartnerActual); - } - SaveData(); - } - - public int GetProgressBySlotId(int slotId) - { - if (slotId > GatherData.BuilderPartnerScore.Count) - { - return -1; - } - var (myScore, partnerScore) = GatherData.BuilderPartnerScore[slotId]; - var buildScore = myScore + partnerScore; - return CalcMiningProgressOld(buildScore); - } - - public void SaveBotInfo(int idx, EventBuildBotInfo botInfo) - { - // throw new NotImplementedException(); - var ret = GatherData.Bots.TryAdd(idx, botInfo); - if (ret) - { - // dosmt - } - } - - public int startTime; - - public int delta; - - public void GMRobotStartTIme(int timeSeconds) - { - startTime = timeSeconds; - } - - public void GMRobotDelta(int timeSeconds) - { - delta = timeSeconds; - } - - public bool GetDoRecommendBot() - { - // if (true) - // { - // return true; - // } - return !PartnerInfoManager.IsFullyMatched && (GatherData.InvitedCount >= _tables.TbEventPartnerConfig.RobotRecommendTriggerCount); - } - - public static void EnsureTokenExchangeContextRegistered(EventPartnerGatherManager manager) - { - var context = GContext.container.Resolve(); - if (context == null) - { - GContext.container.Unregister(); - GContext.container.Register().AsSingleton(); - context = GContext.container.Resolve(); - } - if (context is EventPartnerGatherExchangeContext tokenExchangeContext) - tokenExchangeContext.SetManager(manager); - // EventPartnerTokenExchangeContextRegistry.Context = context; - } - - // 结算 - public void OnSettle() - { - Trace($"OnSettle eventId={EventId}"); - FinishMining(); - } - - // 一轮完成的时候调用 - public void UpdateSpinData() - { - if (BonusExpireDuration != 0 && BonusPercent > 0) - { - ApplyBonus(BonusPercent, BonusExpireDuration); - } - BonusPercent = 0; - BonusExpireDuration = 0; - } - - #region 自动匹配相关方法 - - public async Task FetchAndProcessAutoMatchStatus(bool force = true) - { - var response = await GetAutoMatchStatusResponseAsync(force); - if (response?.State == EEventBuildState.Success) - ProcessAutoMatchStatusSuccess(response); - return response; - } - - private void ProcessAutoMatchStatusSuccess(AutoMatchStatusResponse response) - { - if (response?.Partners is { Count: > 0 } && !ShouldCloseAutoMatch) - { - for (var i = 0; i < response.Partners.Count; ++i) - { - if (i >= AutoMatchSlotCount) - break; - TryAddAutoMatchedPartner(i, response.Partners[i]); - } - } - } - - public bool TryAddAutoMatchedPartner(int slotIndex, PlayerInfo partner) - { - if (partner == null || slotIndex < 0 || slotIndex >= PartnerInfoManager.BuildPartners.Length) - return false; - if (partner.PlayFabId.EndsWith(BuildPartner.RobotIdentifier)) - return false; - - var buildPartner = PartnerInfoManager.BuildPartners[slotIndex]; - if (buildPartner != null && buildPartner.IsValid()) - return false; - - var builder = new BuildPartner - { - SlotId = slotIndex, - PartnerId = partner.PlayFabId, - AvatarUrl = partner.AvatarUrl, - DisplayName = partner.DisplayName, - Cache = PartnerInfoManager.Cache, - }; - - var ret = PartnerInfoManager.AddBuildPartner(builder); - if (ret) - { - GContext.Publish(new EventPartnerGatherAddPartner - { - SlotId = slotIndex, - }); - } - -#if AGG - if (ret) - { - using (var e = GEvent.GameEvent("event_partners_gather_invite")) - { - e.AddContent("teammate_id", partner.PlayFabId) - .AddContent("position_id", slotIndex) - .AddContent("inviter_id", "auto"); - } - } -#endif - return ret; - } - - /// 自动匹配 status 请求最短间隔(秒),仅对 force=false 生效 - private const int AutoMatchStatusMinIntervalSeconds = 3; - - private readonly object _autoMatchStatusGate = new object(); - private Task _autoMatchStatusInFlight; - private DateTime _lastAutoMatchStatusUtc = DateTime.MinValue; - private AutoMatchStatusResponse _cachedAutoMatchStatus; - - // 设置自动匹配状态 - public void SetAutoMatchEnabled(bool enabled) - { - GatherData.IsEnableAutoMatch = enabled; - SaveData(); - } - - public async Task ControlAutoMatch(bool enable) - { - return await EventPartnerService.ControlAutoMatch(EventId, enable); - } - - public void NotifyAutoMatchStopped() - { - GContext.Publish(new EventForAutoMatchChangeStage - { - State = AutoMatchState.AutoMatchOff - }); - } - - public void NotifyAutoMatchFailed(string reason) - { - GContext.Publish(new EventAutoMatchFailed { Reason = reason }); - } - - // 检查是否可以开启自动匹配 - public bool CanStopAutoMatch(out int leftTimes) - { - leftTimes = -1; - // 检查是否已满员 - if (PartnerInfoManager.IsFullyMatched) - return false; - - // 检查冷却时间 - var config = _tables.TbEventPartnerConfig; - var cooldownSeconds = config.AutoMatchCD; - var elapsed = (DateTime.UtcNow - GatherData.LastAutoMatchTime).TotalSeconds; - leftTimes = (int)Math.Floor(cooldownSeconds - elapsed); - leftTimes = leftTimes > 0 ? leftTimes : 0; - Trace($"CanStopAutoMatch eventId={EventId} elapsedSec={elapsed:F2} leftSec={leftTimes}"); - return elapsed >= cooldownSeconds; - } - - /// - /// 拉取自动匹配完整状态(合并并发请求、可选短节流)。业务侧应优先通过本方法访问,勿直接调 EventPartnerService.GetAutoMatchResult。 - /// - /// true:忽略短节流(轮询、关键操作后刷新等仍会与进行中的请求合并为一次 HTTP) - public async Task GetAutoMatchStatusResponseAsync(bool force = false) - { - if (GatherData == null || EventId < 0) - { - return new AutoMatchStatusResponse - { - State = EEventBuildState.Failed, - Message = "No active gather data or event", - IsInMatching = false - }; - } - - if (!force && _cachedAutoMatchStatus != null) - { - var elapsed = (DateTime.UtcNow - _lastAutoMatchStatusUtc).TotalSeconds; - if (elapsed < AutoMatchStatusMinIntervalSeconds) - return _cachedAutoMatchStatus; - } - - Task taskToAwait; - lock (_autoMatchStatusGate) - { - if (_autoMatchStatusInFlight != null) - taskToAwait = _autoMatchStatusInFlight; - else - taskToAwait = _autoMatchStatusInFlight = FetchAutoMatchStatusFromServerAsync(); - } - - try - { - return await taskToAwait; - } - finally - { - lock (_autoMatchStatusGate) - { - if (ReferenceEquals(_autoMatchStatusInFlight, taskToAwait)) - _autoMatchStatusInFlight = null; - } - } - } - - private async Task FetchAutoMatchStatusFromServerAsync() - { - try - { - var response = await EventPartnerService.GetAutoMatchResult(EventId); - lock (_autoMatchStatusGate) - { - _cachedAutoMatchStatus = response; - _lastAutoMatchStatusUtc = DateTime.UtcNow; - } - - return response; - } - catch (Exception e) - { - LogError($"AutoMatchFetchStatusFailed eventId={EventId} error={e.Message}"); - return new AutoMatchStatusResponse - { - State = EEventBuildState.Failed, - Message = e.Message, - IsInMatching = false - }; - } - } - - #endregion - - #region Token Exchange - - public int GetTicketItemId() - { - return EventPartnerMineMainData?.ItemID ?? 0; - } - - public int GetTokenExchangeId() - { - return EventPartnerMineMainData?.TokenExchangeId ?? 0; - } - - public int GetTokenExchangeItemId() - { - var tokenExchangeId = GetTokenExchangeId(); - return _tables.TbEventPartnerTokenExchange[tokenExchangeId].TokenItem; - } - #endregion - - - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/019-EventPinballDataManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/019-EventPinballDataManager.cs.txt deleted file mode 100644 index 2510230a3..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/019-EventPinballDataManager.cs.txt +++ /dev/null @@ -1,993 +0,0 @@ -using asap.core; -using cfg; -using GameCore; -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using UnityEngine; - -namespace game -{ - public class EventPinballDataManager - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - -#if UNITY_EDITOR - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 100; -#else - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 0; -#endif - - #region 奖励次数相关 - private int m_BonusResponseNumber = 10; // 相应次数 - public int BonusResponseNumber { set => m_BonusResponseNumber = value; } - private int m_CumulativeResponseNumber = 0; - public int CumulativeResponseNumber - { - get => m_CumulativeResponseNumber; - set - { - m_CumulativeResponseNumber = value; - FishingPinballAct.Publish(new EventPinballUpdateBonusCircularProgress()); - } - } - public bool IsAddScoreValid() - { - return m_CumulativeResponseNumber < m_BonusResponseNumber; - } - public float GetBonusResponseRatio() - { - if (m_BonusResponseNumber <= 0) return 0f; - - return (float)m_CumulativeResponseNumber / m_BonusResponseNumber; - } - - private int m_AccumulatedTriggerCount = 0; // 埋点用 - public int AccumulatedTriggerCount - { - get => m_AccumulatedTriggerCount; - set => m_AccumulatedTriggerCount = value; - } - #endregion - - #region 代币相关 - public int GetToken() - { - if (m_PinballData != null) - return m_PinballData.Token; - return 0; - } - public void SetRedPoint() - { - if (m_PinballData != null) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Pinball, m_PinballData.Token > 0, m_PinballData.Token); - } - else - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Pinball, false); - } - } - public void AddToken(int count) - { - if (m_PinballData != null) - { - m_PinballData.Token += count; - } - else - { - GetFreshPinballData(); - if (m_PinballData == null) return; - m_PinballData.Token += count; - } - - - SetRedPoint(); - FishingPinballAct.Publish(new EventPinballTokenUpdateData()); - - GContext.container.Resolve().SaveTransitionData(m_PinballData.EventID, m_PinballData.Token); - - SyncData(); - } - //public bool ConsumeTokensDefault() - //{ - // EventPinballMain pinballMain = GetCurrentEventPinballMain(); - - // int magnification = GetCurMagnification(); - // bool isEnough = ConsumeTokens(pinballMain.SpinRequire * magnification); - // if (isEnough == false) - // { - // ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_103")); - // } - // return isEnough; - //} - public bool ConsumeTokens(int count) - { - bool isEnough = IsEnough(count); - if (isEnough == false) return false; - - m_PinballData.ConsumedToken += count; - AddToken(-count); - return isEnough; - } - - public bool IsEnough(int spend) - { - if (m_PinballData == null) return false; - return (m_PinballData.Token - spend) >= 0; - } - #endregion - - #region 每一局的临时数据 - public void ClearTemporaryData() - { - m_IsMultipleMax = false; - - CumulativeResponseNumber = 0; - AccumulatedTriggerCount = 0; - - ClearTemporaryScore(); - ClearTemporaryConsumedToken(); - } - - private int m_TemporaryScore = 0; - public int TemporaryScore { get => m_TemporaryScore; } - - public void ClearTemporaryScore() - { - m_TemporaryScore = 0; - } - public void AddTemporaryScore(int score) - { - m_TemporaryScore += score; - } - public void MultiplyTemporaryScore(int multiple) - { - m_TemporaryScore *= multiple; - } - - public void ReturnConsumedToken() - { - AddToken(m_TemporaryConsumedToken); - } - private int m_TemporaryConsumedToken = 0; - public int TemporaryConsumedToken { get => m_TemporaryConsumedToken; } - public void ClearTemporaryConsumedToken() - { - m_TemporaryConsumedToken = 0; - } - public bool ConsumeTemporaryTokensDefault() - { - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - - int magnification = GetCurMagnification(); - bool isEnough = ConsumeTemporaryTokens(pinballMain.SpinRequire * magnification); - //if (isEnough == false) - //{ - // ToastPanel.Show(LocalizationMgr.GetText("UI_ToastPanel_103")); - //} - return isEnough; - } - public bool ConsumeTemporaryTokens(int count) - { - bool isEnough = IsEnough(count); - if (isEnough == false) return false; - - ConsumeTokens(count); - - m_TemporaryConsumedToken += count; - FishingPinballAct.Publish(new EventPinballTokenUpdateData()); - return isEnough; - } - - private bool m_IsMultipleMax = false; - public bool IsMultipleMax { get => m_IsMultipleMax; set => m_IsMultipleMax = value; } - #endregion - - #region 分数相关 - private int m_MagnificationListIndex = 0; - public void ResetMagnification() - { - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - List MagnificationList = pinballMain.SpinMag; - int magnification = GetCurMagnification(); - bool isEnough = IsEnough(pinballMain.SpinRequire * magnification); - - if (isEnough == false) - { - int count = MagnificationList.Count; - int index = 0; - for (int i = count - 1; i >= 0; --i) - { - int tmpMagnification = MagnificationList[i]; - if (IsEnough(pinballMain.SpinRequire * tmpMagnification)) - { - index = i; - break; - } - } - m_MagnificationListIndex = index; - } - - FishingPinballAct.Publish(new EventPinballResetMagnification()); - } - public int GetCurMagnification() - { - if (m_PinballData == null) return -1; - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - List MagnificationList = pinballMain.SpinMag; - return MagnificationList[m_MagnificationListIndex]; - } - public bool IsMaxMagnification() - { - if (m_PinballData == null) return false; - - return IsCurMaxMagnification();// m_MagnificationListIndex == (m_PinballData.MagnificationList.Count - 1); - } - bool IsCurMaxMagnification() - { - if (m_PinballData == null) return false; - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - List MagnificationList = pinballMain.SpinMag; - int count = MagnificationList.Count; - - int tmpIndex = m_MagnificationListIndex + 1; - - if (tmpIndex >= count) - { - return true; - } - - int magnification = MagnificationList[tmpIndex]; - return !IsEnough(pinballMain.SpinRequire * magnification); - } - public void ScrollToTheNextMagnification() - { - if (m_PinballData == null) return; - - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - List MagnificationList = pinballMain.SpinMag; - - int count = MagnificationList.Count; - - int tmpIndex = m_MagnificationListIndex + 1; - - if (tmpIndex >= count) - { - tmpIndex = 0; - } - - int magnification = MagnificationList[tmpIndex]; - bool isEnough = IsEnough(pinballMain.SpinRequire * magnification); - - if (isEnough) - { - m_MagnificationListIndex = tmpIndex; - } - else - { - m_MagnificationListIndex = 0; - } - } - - private List m_RewardList = new List(); - public List RewardList { get => m_RewardList; } - public void InitRewardList() - { - m_RewardList.Clear(); - - int count = m_TbEventPinballReward.DataList.Count; - for (int i = 0; i < count; ++i) - { - var item = m_TbEventPinballReward.DataList[i]; - m_RewardList.Add(item.SpinPoint); - } - if (m_PinballData != null) - { - if (m_PinballData.Scores >= m_RewardList[^1]) - { - m_PinballData.Scores = 0; - } - m_PinballData.RewardIndex = FindInsertionIndex(m_RewardList, m_PinballData.Scores); - } - } - //private int m_RewardIndex, m_RewardMaxIndex; - //public int RewardIndex { get => m_RewardIndex; } - //public int RewardMaxIndex { get => m_RewardMaxIndex; } - //public void CalculateReward() - //{ - // if (m_PinballData == null) return; - - // m_RewardIndex = FindInsertionIndex(m_RewardList, m_PinballData.Scores); - // m_RewardMaxIndex = m_TbEventPinballReward.DataList.Count - 1; - //} - //public void AddScore(int score) - //{ - // if (m_PinballData == null) return; - - // m_PinballData.Scores += score; - // m_PinballData.TotalScores += score; - //} - #endregion - - #region 活动相关 - public void ActivateEvent(FishingEvent fishingEvent) - { - if (fishingEvent == null) return; - - if (!Init()) return; - - if (m_PinballData != null) FixPinballData(); - if (m_PinballData == null) GetFreshPinballData(); - } - - public void GetDataFromServer(string json) - { - if (string.IsNullOrEmpty(json)) - { - GameDebug.LogWarning("EventPinball get data from server has encountered empty data."); - return; - } - - try - { - m_PinballData = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - } - catch (Exception e) - { - GameDebug.LogWarning("EventPinball deserialize data has failed. Exception: " + e.ToString()); - return; - } - - if (!Init()) return; - } - public int FixPinballData() - { - if (m_PinballData == null) return 0; - - // 获取当前开放并符合解锁条件的弹珠活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 6, m_IsCheckCondition); - if (fishingEvent == null) return ClearData(); - int eventID = fishingEvent.ID; - int pinballMainID = fishingEvent.RedirectID; - if (pinballMainID < 0) return ClearData(); - - if (eventID != m_PinballData.EventID || pinballMainID != m_PinballData.PinballMainID) return ClearData(); - - return 0; - } - public TimeSpan RemainingTime - { - get => DateTime.Parse((m_Tables.TbFishingEvent[m_PinballData.EventID].TimeDefinition as LimitedTime).EndTime) - - ZZTimeHelper.UtcNow(); - } - public int ClearData() - { - if (m_PinballData == null) return 0; - m_PinballData = null; - return 0; - } - public void SyncData() - { - if (!m_IsSyncData) return; - playerSaveStore.Write(EventPinballConfig.SAVE_DATA_KEY, Newtonsoft.Json.JsonConvert.SerializeObject(m_PinballData)).RequireAccepted(); - } - #endregion - - #region 生命周期 - public bool Init() - { - InitTables(); - - m_IsSimulatorMode = false; - return true; - } - #endregion - - #region Table Data - private Tables m_Tables; - private TbEventPinballMain m_TbEventPinballMain; - private TbEventPinballPoint m_TbEventPinballPoint; - private TbEventPinballReward m_TbEventPinballReward; - private void InitTables() - { - m_Tables = GContext.container.Resolve(); - if (m_Tables == null) return; - m_TbEventPinballMain = m_Tables.TbEventPinballMain; - m_TbEventPinballPoint = m_Tables.TbEventPinballPoint; - m_TbEventPinballReward = m_Tables.TbEventPinballReward; - - InitRewardList(); - } - public EventPinballReward GetEventPinballReward(int index) - { - return m_TbEventPinballReward.DataList[index]; - } - - public int GetTicketItemId() - { - return m_Tables.TbFishingEventCycleItem[m_Tables.TbFishingEvent[m_PinballData.EventID].RedirectID].ItemId; - } - #endregion - - #region UI 设置相关 - private UIType m_UIPanel = null, m_InfoPanel = null; - public void ClearUIData() - { - m_UIPanel = null; - m_InfoPanel = null; - } - public void InitUIData() - { - GetUIPanel(); - GetInfoPanel(); - } - public UIType GetUIPanel() - { - if (m_UIPanel == null) - { - var data = GetCurrentEventPinballMain(); - m_UIPanel = new UIType(data.UIPanel); - } - return m_UIPanel; - } - public UIType GetInfoPanel() - { - if (m_InfoPanel == null) - { - var data = GetCurrentEventPinballMain(); - m_InfoPanel = new UIType(data.InfoPanel);//EventPinballRewardPoupPanel - } - return m_InfoPanel; - } - #endregion - - #region 数据相关 - private EventPinballData m_PinballData; - internal bool IsInactiveForKVValidation => m_Tables==null && m_TbEventPinballMain==null && m_TbEventPinballPoint==null && - m_TbEventPinballReward==null && m_UIPanel==null && m_InfoPanel==null && m_RewardList.Count==0 && - m_PointWeightList.Count==0 && !m_IsSimulatorMode && !m_IsMultipleMax && m_CumulativeResponseNumber==0 && - m_AccumulatedTriggerCount==0 && m_TemporaryScore==0 && m_TemporaryConsumedToken==0 && m_MagnificationListIndex==0 && m_BonusResponseNumber==10; - - internal static game.PlayerDataStorage.PlayerKVPinballState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodePinball(raw,snapshot,errors); - internal void ResetForKVLoad() - { - m_PinballData=null; m_BonusResponseNumber=10; m_CumulativeResponseNumber=m_AccumulatedTriggerCount=m_TemporaryScore=m_TemporaryConsumedToken=m_MagnificationListIndex=0; - m_IsMultipleMax=false; m_IsSimulatorMode=false; m_RewardList=new List(); m_PointWeightList=new List(); m_UIPanel=m_InfoPanel=null; - m_Tables=null; m_TbEventPinballMain=null; m_TbEventPinballPoint=null; m_TbEventPinballReward=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVPinballState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - m_PinballData=!state.IsPresent ? null : new EventPinballData - { - EventID=state.EventID, - PinballMainID=state.PinballMainID, - SpinPoint=state.SpinPoint, - Scores=state.Scores, - Multiple=state.Multiple, - Token=state.Token, - ConsumedToken=state.ConsumedToken, - RewardIndex=state.RewardIndex, - Force=state.Force, - LuckyValue=state.LuckyValue, - InflationRate=state.InflationRate - }; - } - public EventPinballData PinballData { get { return m_PinballData; } } - public int RewardMaxIndex - { - get { return m_TbEventPinballReward.DataList.Count - 1; } - } - public EventPinballMain GetFreshPinballData() - { - // 获取当前开放并符合解锁条件的弹珠活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 6, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int pinballMainID = fishingEvent.RedirectID; - if (pinballMainID < 0) return null; - - // 获取当前弹珠活动数据 - EventPinballMain pinballMain = m_TbEventPinballMain.GetOrDefault(pinballMainID); - if (pinballMain == null) return null; - - int token = m_DefaultToken; - m_PinballData = null; - - token = GContext.container.Resolve().GetInitWelcomeGift(eventID); - - m_PinballData = new EventPinballData(); - - m_PinballData.InflationRate = GContext.container.Resolve().InflationRate; - Debug.Log("m_PinballData.InflationRate " + GContext.container.Resolve().InflationRate); - m_PinballData.EventID = eventID; - m_PinballData.PinballMainID = pinballMainID; - m_PinballData.Force = 0f; - m_PinballData.SpinPoint = 0; - m_PinballData.Scores = 0; - m_PinballData.Multiple = 0; - - m_PinballData.Token = token; - m_PinballData.ConsumedToken = 0; - - m_PinballData.LuckyValue = (float)pinballMain.InitialLuck; - - m_PinballData.RewardIndex = 0; - - GContext.container.Resolve().SaveTransitionData(m_PinballData.EventID, m_PinballData.Token); - - - UpdateLuckyValueAndWeight(); - - GContext.container.Resolve().ClearGuide(""); - SetRedPoint(); - - // 同步数据 - SyncData(); - return pinballMain; - } - public EventPinballMain GetNextPinballData() - { - // 获取当前开放并符合解锁条件的弹珠活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 6, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int pinballMainID = fishingEvent.RedirectID; - if (pinballMainID < 0) return null; - - if (eventID != m_PinballData.EventID || pinballMainID != m_PinballData.PinballMainID) return GetFreshPinballData(); - - // 获取当前弹珠活动数据 - EventPinballMain pinballMain = m_TbEventPinballMain.GetOrDefault(pinballMainID); - if (pinballMain == null) return null; - - m_PinballData.EventID = eventID; - m_PinballData.PinballMainID = pinballMainID; - - m_PinballData.ConsumedToken = 0; - - UpdateLuckyValueAndWeight(); - - // 同步数据 - SyncData(); - return pinballMain; - } - public EventPinballMain ContinueGame() - { - if (m_PinballData == null) return GetFreshPinballData(); - - // 获取当前开放并符合解锁条件的弹珠活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 6, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int pinballMainID = fishingEvent.RedirectID; - if (pinballMainID < 0) return null; - - if (eventID != m_PinballData.EventID || pinballMainID != m_PinballData.PinballMainID) return GetFreshPinballData(); - - // 获取当前弹珠活动数据 - EventPinballMain pinballMain = m_TbEventPinballMain.GetOrDefault(pinballMainID); - if (pinballMain == null) return null; - - //UpdateLuckyValueAndWeight(); - - return pinballMain; - } - public List m_PointWeightList = new List(); - public EventPinballPoint UpdateLuckyValueAndWeight() - { - if (m_TbEventPinballPoint == null) return null; - - m_PointWeightList.Clear(); - - float luckyValue = m_PinballData.LuckyValue; - int count = m_TbEventPinballPoint.DataList.Count; - - float total = 0; - for (int i = 0; i < count; ++i) - { - EventPinballPoint item = m_TbEventPinballPoint.DataList[i]; - - float weight = item.Weight + luckyValue * item.LuckParameter; - total += weight; - float tmp = total; - m_PointWeightList.Add(tmp); - } - - float randomValue = UnityEngine.Random.Range(0f, total); - int index = FindInsertionIndex(m_PointWeightList, randomValue); - - EventPinballPoint target = m_TbEventPinballPoint.DataList[index]; - if (float.MaxValue - target.DeltaLuck <= m_PinballData.LuckyValue) - { - m_PinballData.LuckyValue = 0; - } - else - { - m_PinballData.LuckyValue += target.DeltaLuck; - if (m_PinballData.LuckyValue < 0f) - { - m_PinballData.LuckyValue = 0f; - } - } - - m_PinballData.SpinPoint = target.SpinPoint; - - return target; - } - public int FindInsertionIndex(List sortedList, float target) - { - if (sortedList == null || sortedList.Count == 0) - { - Debug.LogError("---- EventPinballDataManager->FindInsertionIndex 数组为空"); - return -1; - } - - if (target < sortedList[0]) - { - return 0; - } - - if (target >= sortedList[sortedList.Count - 1]) - { - return -1; - } - - // 使用二分查找算法 - int left = 0; - int right = sortedList.Count - 1; - int result = -1; - - while (left <= right) - { - int mid = left + (right - left) / 2; - - if (sortedList[mid] > target) - { - if (mid > 0 && target > sortedList[mid - 1] && target < sortedList[mid]) - { - result = mid; - break; - } - right = mid - 1; - } - else - { - if (mid < sortedList.Count - 1 && target >= sortedList[mid] && target < sortedList[mid + 1]) - { - result = mid + 1; - break; - } - left = mid + 1; - } - } - - return result; - } - - public float GetRandomForce(float ratio) - { - EventPinballPoint target = m_TbEventPinballPoint.GetOrDefault(m_PinballData.SpinPoint); - EventPinballMain pinballMain = GetCurrentEventPinballMain(); - float failMaxDist = pinballMain.FailMaxDist; - if (ratio <= failMaxDist) - { - return pinballMain.FailMaxForce; - } - int count = target.ForceLv.Count; - - List forceList = target.ForceLv[count - 1]; - ratio = (ratio - failMaxDist) / 1 - failMaxDist; // 归一化到0-1之间 - float subRatio = 1f / count; // 每个等级的比例 - for (int i = 0; i < count; ++i) - { - if (ratio <= subRatio * (i + 1)) - { - forceList = target.ForceLv[i]; - break; - } - } - - count = forceList.Count; - int index = UnityEngine.Random.Range(0, count); - return forceList[index]; - } - - public void InitGameRound() - { - //SetRewardList(); - //CalculateReward(); - ResetMagnification(); - ClearTemporaryData(); - - m_PinballData.Force = 0f; - PinballData.Multiple = 0; - } - - public EventPinballMain GetCurrentEventPinballMain() - { - if (m_PinballData == null) return GetFreshPinballData(); - - return m_TbEventPinballMain.GetOrDefault(m_PinballData.PinballMainID); - } - #endregion - - #region 本地存储数据相关 - public string GetSaveKey(string key) - { - if (m_PinballData == null) return key; - return m_PinballData.EventID + "-" + m_PinballData.PinballMainID + "-" + key; - } - public bool HasSaveKey(string key) - { - return PlayerPrefs.HasKey(GetSaveKey(key)); - } - public void SaveData(string key, string value) - { - PlayerPrefs.SetString(GetSaveKey(key), value); - PlayerPrefs.Save(); - } - #endregion - - #region 红点相关 - public bool IsRedDotDisplayed() - { - if (m_PinballData == null) return false; - return m_PinballData.Token > 0; - } - #endregion - - #region 运行模式相关(模拟数据模式/正常玩家模式) - public bool m_IsSimulatorMode = false; - public bool IsSimulatorMode - { - get => m_IsSimulatorMode; - set - { - if (m_IsSimulatorMode != value) - { - m_IsSimulatorMode = value; - FishingPinballAct.Publish(new EventPinballSyncOperatingModeData() - { - IsSimulatorMode = value - }); - } - } - } - #endregion - - #region IO - public string GetSaveFilepath(string filename) - { - return Path.Combine(Application.persistentDataPath, filename); - } - #endregion - } - - public class EventPinballData - { - public int EventID { get; set; } - public int PinballMainID { get; set; } - public float Force { get; set; } - public int SpinPoint { get; set; } - public int Scores { get; set; } - public int Multiple { get; set; } - - public int Token { get; set; } - public int ConsumedToken { get; set; } - - public float LuckyValue { get; set; } - - public int RewardIndex { get; set; } - - public float InflationRate { get; set; } - - } - - public enum EventPinballBonusType - { - TypeScore, - TypeMultiple - } - - public enum EventPinballTrackType - { - TypeEnter, - TypeExit - } - - public enum EventPinballState - { - Prepare, - Running, - Ended - } - - public enum EventPinballSwitcherState - { - Open, - Close - } - - public class EventPinballSwitcherOpen - { - - } - - public class EventPinballSwitcherClose - { - - } - - public class EventPinballEnergyArrowData - { - public float Energy; - } - - public class EventPinballEnergyArrowRestoreData - { - - } - - public class EventPinballUpdateBonusCircularProgress - { - - } - - public class EventPinballTokenUpdateData - { - - } - - public class EventPinballBasicScore - { - public int Score; - } - public class EventPinballBasicScoreHideData - { - - } - public class EventPinballBasicScoreShowData - { - - } - - public class EventPinballResetMagnification - { - - } - - public class EventPinballRewardUpdateData - { - public int Scores; - } - - public class EventPinballSpringUpdateData - { - public float Ratio; - } - - public class EventPinballPlayArrowBreathAnimData - { - - } - public class EventPinballStopArrowBreathAnimData - { - - } - public class EventPinballPlayLightOnAnimData - { - - } - public class EventPinballResumePelletData - { - - } - - public class EventPinballResetPelletStatusData - { - - } - - public class EventPinballLaunchPelletData - { - public float Force; - } - - public class EventPinballShowPopupData - { - public int Scores; - public EventPinballBonusType BonusType; - public bool IsMultipleMax; - } - public class EventPinballHidePopupData - { - - } - - public class EventPinballShowMultipleTextData - { - public EventPinballBonusType BonusType; - public Vector3 Position; - public string Tips; - public int Scores; - public bool IsMultipleMax; - } - - public class EventPinballRewardDisplayUpdateData - { - public int RewardIndex; - public int TargetScore; - public int LevelScore; - public float FromRatio; - public float TargetRatio; - public int DropId; - public int RewardDisplayDropId; - } - - public class EventPinballSyncOperatingModeData - { - public bool IsSimulatorMode; - } - - public class EventPinballHideWidgetMultipleEffectData - { - - } - - public class EventPinballShowWidgetScoreEffect2Data - { - - } - - public class EventPinballHideFiringPinData - { - - } - - public class EventPinballShowFiringPinData - { - - } - - public class EventPinballHideCircularRotationalAnim - { - - } - - public class EventPinballShowCircularRotationalAnim - { - - } - - public class EventPinballLaunchPelletStatusData - { - - } - - public class EventPinballSetDummyPelletData - { - public PinballPellet Pellet; - } - - public class EventPinballConfig - { - public const string CSVFileName = "pinball.csv"; - - public const string SAVE_DATA_KEY = "epbdk"; // event pinball data key - - public const int MultipleMax = 10; - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/020-EventPotionDataManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/020-EventPotionDataManager.cs.txt deleted file mode 100644 index d58015968..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/020-EventPotionDataManager.cs.txt +++ /dev/null @@ -1,1352 +0,0 @@ -using asap.core; -using Castle.Core.Internal; -using cfg; -using GameCore; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.U2D; - -namespace game -{ - public class EventPotionDataManager - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } -#if UNITY_EDITOR - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 100; -#else - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 0; -#endif - - #region 生命周期 - public bool Init() - { - InitTables(); - return true; - } - #endregion - - #region 图集等 - private SpriteAtlas m_SpriteAtlas; - public SpriteAtlas SpriteAtlas - { - get { return m_SpriteAtlas; } - set { m_SpriteAtlas = value; } - } - #endregion - - #region Table Data - private Tables m_Tables; - private TbEventPotionMain m_TbEventPotionMain; - private TbEventPotionStage m_TbEventPotionStage; - private TbEventPotionBlock m_TbEventPotionBlock; - private TbEventPotionBottle m_TbEventPotionBottle; - private void InitTables() - { - m_Tables = GContext.container.Resolve(); - if (m_Tables == null) return; - m_TbEventPotionMain = m_Tables.TbEventPotionMain; - m_TbEventPotionStage = m_Tables.TbEventPotionStage; - m_TbEventPotionBlock = m_Tables.TbEventPotionBlock; - m_TbEventPotionBottle = m_Tables.TbEventPotionBottle; - } - public EventPotionBottle GetEventPotionBottle(int num) - { - return m_TbEventPotionBottle.GetOrDefault(num); - } - public EventPotionBlock GetEventPotionBlock(int num) - { - EventPotionMain potionMain = GetEventPotionMain(m_PotionData.PotionID); - - foreach (var item in potionMain.BlockResourceID) - { - var potionBlock = m_TbEventPotionBlock.GetOrDefault(item); - if (potionBlock.Count == num) return potionBlock; - } - - return null; - } - public EventPotionMain GetEventPotionMain(int id) - { - return m_TbEventPotionMain.GetOrDefault(id); - } - public EventPotionStage GetEventPotionStage(int id) - { - return m_TbEventPotionStage.GetOrDefault(id); - } - public EventNeoNormalPackData GetEventNeoNormalPackData() - { - if (m_PotionData == null) - return null; - var main = m_TbEventPotionMain.GetOrDefault(m_PotionData.PotionID); - if (main == null) - return null; - return new EventNeoNormalPackData - { - EventId = m_PotionData.EventID, - PackId = main.PackId, - // Panel = main.PackPanel - }; - } - #endregion - - #region 历史参与标记 - private int m_PendingFirstPlayedEventId; - - /// - /// 当前用户是否参与过往期魔药活动(不含当期,跨期持久化,随时可查) - /// - public bool HasEverPlayed - { - get - { - if (m_PotionData == null || m_PotionData.FirstPlayedEventId <= 0) return false; - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - return fishingEvent == null || m_PotionData.FirstPlayedEventId != fishingEvent.ID; - } - } - - public List GetStageList1(EventPotionMain potion) - { - return (HasEverPlayed && potion.ExpStageList1 != null) ? potion.ExpStageList1 : potion.StageList1; - } - - public List GetStageList2(EventPotionMain potion) - { - return (HasEverPlayed && potion.ExpStageList2 != null) ? potion.ExpStageList2 : potion.StageList2; - } - #endregion - - #region 数据相关 - private EventPotionData m_PotionData; - - internal static PlayerDataStorage.PlayerKVPotionState DecodeForKVLoad(IReadOnlyDictionary raw, - PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => PlayerDataStorage.PlayerKVSaveSchema.DecodePotion(raw,errors); - internal void ResetForKVLoad() - { - m_PotionData=null; m_PendingFirstPlayedEventId=0; m_SpriteAtlas=null; m_Tables=null; - m_TbEventPotionMain=null; m_TbEventPotionStage=null; m_TbEventPotionBlock=null; m_TbEventPotionBottle=null; - m_PotionResDict=new Dictionary(); m_WallsBefore=new List(); m_WallsAfter=new List(); - m_UIPanel=m_InfoPanel=m_RewardPopupPanel=null; m_ScrollerDataList=new List(); - } - static PotionItemData MaterializeKVPotionItem(PlayerDataStorage.PlayerKVPotionItem value) => new PotionItemData { - name=value.Name,index=value.Index,isOver=value.IsOver,DataType=(EventPotionDataType)value.DataType, - ColorTypeList=new List(value.Colors),ShelfTypeList=value.Shelves.Select(n=>(EventPotionShelfType)n).ToList(), - GridStateList=value.Grids.Select(n=>(EventPotionGridState)n).ToList(),FromDisplayAreaIndexList=new List(value.FromDisplay) - }; - internal void ReplaceFromKVDecoded(PlayerDataStorage.PlayerKVPotionState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - m_PotionData=!state.IsPresent ? null : new EventPotionData { - EventID=state.EventID, - PotionID=state.PotionID, - StageID=state.StageID, - Stage1TotalLevel=state.Stage1TotalLevel, - Stage2TotalLevel=state.Stage2TotalLevel, - LevelID=state.LevelID, - LevelIndex=state.LevelIndex, - CorrectNum=state.CorrectNum, - SubmitNum=state.SubmitNum, - Token=state.Token, - ConsumedToken=state.ConsumedToken, - Rule=state.Rule, - PreEventID=state.PreEventID, - PrePotionID=state.PrePotionID, - PreStageID=state.PreStageID, - PreLevelID=state.PreLevelID, - Round=state.Round, - FirstPlayedEventId=state.FirstPlayedEventId, - IsOver=state.IsOver, - Name=state.Name, - InflationRate=state.InflationRate, - LevelTargetData=MaterializeKVPotionItem(state.LevelTargetData), - LevelDisplayData=MaterializeKVPotionItem(state.LevelDisplayData), - LevelProcessedList=state.LevelProcessedList.Select(MaterializeKVPotionItem).ToList() - }; - } - internal bool IsInactiveForKVValidation => m_PendingFirstPlayedEventId==0 && m_SpriteAtlas==null && m_Tables==null && - m_TbEventPotionMain==null && m_TbEventPotionStage==null && m_TbEventPotionBlock==null && m_TbEventPotionBottle==null && - m_PotionResDict.Count==0 && m_WallsBefore.Count==0 && m_WallsAfter.Count==0 && m_ScrollerDataList.Count==0 && - m_UIPanel==null && m_InfoPanel==null && m_RewardPopupPanel==null; - public EventPotionData PotionData { get { return m_PotionData; } } - - public void InitLevel() - { - EventPotionStage potionLevel = null; - if (m_PotionData == null) - { - potionLevel = GetFreshPotionLevel(); - } - else - { - potionLevel = GetCurrentPotionLevel(); - } - if (potionLevel == null) return; - - m_PotionResDict.Clear(); - - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(m_PotionData.PotionID); - if (potion == null) return; - - int count = potion.ResourceID.Count; - for (int i = 0; i < count; i++) - { - m_PotionResDict.Add(potion.ResourceID[i], new EventPotionResource - { - TypeIndex = i, - TypeCount = count, - ItemResName = potion.ItemResource[i], - PaintResName = potion.PaintResource[i] - }); - } - - InitUIData(); - } - List SetPattern(List arr, int pattern, bool ColorProb) - { - if (ColorProb) - { - //1-7之间不放回的随机取count个数 - List ints = new List(); - for (int i = 1; i < 8; i++) - { - ints.Insert(UnityEngine.Random.Range(0, ints.Count + 1), i); - } - for (int i = 0; i < arr.Count; i++) - { - arr[i] = ints[i]; - } - } - - GameDebug.Log("魔药 pattern == " + pattern); - int count = arr.Count; - if (pattern == -1) - { - int randomIndex = UnityEngine.Random.Range(0, count); - int value = arr[randomIndex]; - for (int i = 0; i < count; i++) - { - arr[i] = value; - } - } - else if (pattern > 0) - { - arr = ConstructValidPermutation(arr, pattern); - } - - return arr; - } - private void ProcessSorting(EventPotionStage potionLevel) - { - EventPotionBottle potionBottle = m_TbEventPotionBottle.GetOrDefault(potionLevel.Number); - - int count = potionBottle.Color.Count; - - bool isSkip = false; - - List arr = potionBottle.Color; - - // display数据洗牌 - m_PotionData.LevelDisplayData.isOver = false; - m_PotionData.LevelDisplayData.ColorTypeList.Clear(); - - // target数据洗牌 - m_PotionData.LevelTargetData.ColorTypeList.Clear(); - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(m_PotionData.PotionID); - bool isRandom = HasEverPlayed || potionLevel.ID != GetStageList1(potion)[0]; - bool WeightRandom = true; - bool ColorProb = false; - if (isRandom) - { - ColorProb = potionLevel.ColorProb >= UnityEngine.Random.value; - arr = SetPattern(arr, potionLevel.Pattern, ColorProb); - - // 随机排序 - m_PotionData.LevelDisplayData.ColorTypeList.AddRange(arr); - ShuffleList(m_PotionData.LevelDisplayData.ColorTypeList, isSkip); - - m_PotionData.LevelTargetData.ColorTypeList.AddRange(m_PotionData.LevelDisplayData.ColorTypeList.ToArray()); - if (isSkip == false) - { - ShuffleList(m_PotionData.LevelTargetData.ColorTypeList); - } - - // target 权重数据处理 - int totalWeight = potionLevel.WeightRandom + potionLevel.WeightLimit; - int random = UnityEngine.Random.Range(0, totalWeight); - - if (random >= potionLevel.WeightRandom && isSkip == false) - { - WeightRandom = false; - m_PotionData.Rule = 2; - List tmpList = new List(); - int tmpCount = 0; - // 处理LimitParam - - // 逆向检测 - tmpList.Clear(); - int tmpLast = count - 1; - for (int i = 0; i < count; i++) - { - if (m_PotionData.LevelDisplayData.ColorTypeList[tmpLast - i] == m_PotionData.LevelTargetData.ColorTypeList[i]) - { - tmpList.Add(i); - } - } - // 逆向处理 - tmpCount = tmpList.Count; - if (tmpCount >= potionBottle.LimitHitNum) - { - for (int i = 0; i < tmpCount; i += 2) - { - if (i + 1 < tmpCount) - { - int tmp = m_PotionData.LevelTargetData.ColorTypeList[tmpList[i]]; - m_PotionData.LevelTargetData.ColorTypeList[tmpList[i]] = m_PotionData.LevelTargetData.ColorTypeList[tmpList[i + 1]]; - m_PotionData.LevelTargetData.ColorTypeList[tmpList[i + 1]] = tmp; - } - } - } - - // 正向检测 - tmpList.Clear(); - for (int i = 0; i < count; i++) - { - if (m_PotionData.LevelTargetData.ColorTypeList[i] == m_PotionData.LevelDisplayData.ColorTypeList[i]) - { - tmpList.Add(i); - } - } - // 正向处理 - tmpCount = tmpList.Count; - if (tmpCount >= potionBottle.LimitHitNum) - { - for (int i = 0; i < tmpCount; i += 2) - { - if (i + 1 < tmpCount) - { - int tmp = m_PotionData.LevelTargetData.ColorTypeList[tmpList[i]]; - m_PotionData.LevelTargetData.ColorTypeList[tmpList[i]] = m_PotionData.LevelTargetData.ColorTypeList[tmpList[i + 1]]; - m_PotionData.LevelTargetData.ColorTypeList[tmpList[i + 1]] = tmp; - } - } - } - } - else - { - m_PotionData.Rule = 1; - } - } - else - { - // 指定排序 - m_PotionData.Rule = 3; - - m_PotionData.LevelTargetData.ColorTypeList = new List() { 1, 2, 3 }; - m_PotionData.LevelDisplayData.ColorTypeList = new List() { 1, 3, 2 }; - } - - for (int i = 0; i < count; ++i) - { - m_PotionData.LevelDisplayData.ShelfTypeList.Add(EventPotionShelfType.Shelf_Default); - m_PotionData.LevelDisplayData.GridStateList.Add(EventPotionGridState.GridState_Empty); - m_PotionData.LevelDisplayData.FromDisplayAreaIndexList.Add(-1); - } - - // 处理processed数据 - m_PotionData.LevelProcessedList.Clear(); - PotionItemData processedData = new PotionItemData(); - processedData.Clear(); - processedData.DataType = EventPotionDataType.Data_ItemAndOperation; - processedData.name = "ProcessSorting_" + DateTime.Now.Ticks; - processedData.index = m_PotionData.LevelProcessedList.Count; - processedData.isOver = false; - - for (int i = 0; i < count; i++) - { - processedData.ColorTypeList.Add(-1); - processedData.ShelfTypeList.Add(EventPotionShelfType.Shelf_Default); - processedData.GridStateList.Add(EventPotionGridState.GridState_Empty); - processedData.FromDisplayAreaIndexList.Add(-1); - } - - m_PotionData.LevelProcessedList.Add(processedData); - GameDebug.Log("魔药:" + string.Join(",", PotionData.LevelTargetData.ColorTypeList) - + " || " - + string.Join(",", PotionData.LevelDisplayData.ColorTypeList) - + " 顺序随机 " + WeightRandom - + " 颜色随机 " + ColorProb); - } - - // 构造一个满足条件的排列 - private List ConstructValidPermutation(List numbers, int param) - { - int length = numbers.Count; - if (param > length / 2) - { - param = length / 2; - } - ShuffleList(numbers); - for (int i = 0; i < param; i++) - { - numbers[i] = numbers[(i + param) % length]; - } - return numbers; - } - - // 计算两个数组中相同位置相同值的数量 - private int CountMatches(int[] arr1, int[] arr2) - { - int count = 0; - for (int i = 0; i < arr1.Length; i++) - { - if (arr1[i] == arr2[i]) - { - count++; - } - } - return count; - } - - private Dictionary m_PotionResDict = new Dictionary(); - public EventPotionResource GetPotionResource(int id) - { - m_PotionResDict.TryGetValue(id, out EventPotionResource potionRes); - return potionRes; - } - /// - /// 获取的是 m_PotionData.LevelDisplayData.ItemTypeList 的索引列表 - /// - /// - public List GetValidDisplayDataList() - { - List list = new List(); - int count = m_PotionData.LevelDisplayData.ColorTypeList.Count; - for (int i = 0; i < count; ++i) - { - if (m_PotionData.LevelDisplayData.ColorTypeList[i] > EventPotionConfig.PotionItemType_Empty && - m_PotionData.LevelDisplayData.GridStateList[i] != EventPotionGridState.GridState_Over) - { - list.Add(i); - } - } - return list; - } - public int GetValidDisplayDataListCount() - { - int num = 0; - int count = m_PotionData.LevelDisplayData.ColorTypeList.Count; - for (int i = 0; i < count; ++i) - { - if (m_PotionData.LevelDisplayData.ColorTypeList[i] > EventPotionConfig.PotionItemType_Empty && - m_PotionData.LevelDisplayData.GridStateList[i] != EventPotionGridState.GridState_Over) - { - num++; - } - } - return num; - } - - private List m_WallsBefore = new List(); - private List m_WallsAfter = new List(); - public int WallBeforeCount { get { return m_WallsBefore.Count; } } - public void InitWalls(int totalNums) - { - int wallNum = totalNums - 2; - m_WallsBefore.Clear(); - for (int i = 0; i < wallNum; ++i) - { - PotionItemData tmpWallDataBefore = new PotionItemData() - { - DataType = EventPotionDataType.Data_Wall - }; - tmpWallDataBefore.name = "InitWalls_Before_" + i + "_" + DateTime.Now.Ticks; - tmpWallDataBefore.index = i; - tmpWallDataBefore.isOver = true; - m_WallsBefore.Add(tmpWallDataBefore); - } - - wallNum = 1; - m_WallsAfter.Clear(); - PotionItemData tmpWallDataAfter = new PotionItemData() - { - DataType = EventPotionDataType.Data_Wall - }; - tmpWallDataAfter.name = "InitWalls_After_" + DateTime.Now.Ticks; - tmpWallDataAfter.index = 0; - tmpWallDataAfter.isOver = true; - m_WallsAfter.Add(tmpWallDataAfter); - } - - public void ClearData() - { - m_WallsBefore.Clear(); - m_WallsAfter.Clear(); - m_ScrollerDataList.Clear(); - - ClearUIData(); - - m_SpriteAtlas = null; - } - - public void ActivateEvent(FishingEvent fishingEvent) - { - if (fishingEvent == null) return; - - if (!Init()) return; - - if (m_PotionData != null) - { - m_PendingFirstPlayedEventId = m_PotionData.FirstPlayedEventId > 0 - ? m_PotionData.FirstPlayedEventId - : m_PotionData.EventID; - } - else - { - m_PendingFirstPlayedEventId = fishingEvent.ID; - } - - if (m_PotionData != null) - FixPotionData(); - if (m_PotionData == null) - GetFreshPotionLevel(); - } - - public void GetDataFromServer(string json) - { - if (json.IsNullOrEmpty()) - { - GameDebug.LogWarning("EventPotion get data from server has encountered empty data."); - return; - } - - try - { - m_PotionData = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - } - catch (Exception e) - { - GameDebug.LogWarning("EventPotion deserialize data has failed. Exception: " + e.ToString()); - return; - } - - if (!Init()) return; - } - - public TimeSpan RemainingTime - { - get => DateTime.Parse((m_Tables.TbFishingEvent[m_PotionData.EventID].TimeDefinition as LimitedTime).EndTime) - - ZZTimeHelper.UtcNow(); - } - - public int FixPotionData() - { - if (m_PotionData == null) return 0; - - // 获取当前开放并符合解锁条件的魔药活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - if (fishingEvent == null) return ClearPotionData(); - int eventID = fishingEvent.ID; - int potionID = fishingEvent.RedirectID; - if (potionID < 0) return ClearPotionData(); - - if (eventID != m_PotionData.EventID || potionID != m_PotionData.PotionID) return ClearPotionData(); - - return 0; - } - public int ClearPotionData() - { - if (m_PotionData == null) return 0; - - m_PotionData.Clear(); - m_PotionData = null; - return 0; - } - public void SyncData() - { - if (!m_IsSyncData) return; - playerSaveStore.Write(EventPotionConfig.SAVE_DATA_KEY, Newtonsoft.Json.JsonConvert.SerializeObject(m_PotionData)).RequireAccepted(); - } - public PotionItemData GetOperationItemData() - { - foreach (var potionItemData in m_PotionData.LevelProcessedList) - { - if (potionItemData.DataType == EventPotionDataType.Data_ItemAndOperation) - { - return potionItemData; - } - } - return null; - } - #endregion - - #region UI 设置相关 - private UIType m_UIPanel = null, m_InfoPanel = null, m_RewardPopupPanel = null; - public void ClearUIData() - { - m_UIPanel = null; - m_InfoPanel = null; - m_RewardPopupPanel = null; - } - public void InitUIData() - { - ClearUIData(); - - GetUIPanel(); - GetInfoPanel(); - GetRewardPopupPanel(); - } - public UIType GetUIPanel() - { - if (m_UIPanel == null) - { - var data = GetEventPotionMain(m_PotionData.PotionID); - m_UIPanel = new UIType(data.UIPanel); - } - return m_UIPanel; - } - public UIType GetInfoPanel() - { - if (m_InfoPanel == null) - { - var data = GetEventPotionMain(m_PotionData.PotionID); - m_InfoPanel = new UIType(data.InfoPanel); - } - return m_InfoPanel; - } - public UIType GetRewardPopupPanel() - { - if (m_RewardPopupPanel == null) - { - var data = GetEventPotionMain(m_PotionData.PotionID); - m_RewardPopupPanel = new UIType(data.RewardPanel); - } - return m_RewardPopupPanel; - } - #endregion - - #region 本地存储数据相关 - public string GetPotionIDSaveKey(string key) - { - if (m_PotionData == null) return key; - return m_PotionData.EventID + "-" + m_PotionData.PotionID + "-" + key; - } - public bool HasPotionIDSaveKey(string key) - { - return PlayerPrefs.HasKey(GetPotionIDSaveKey(key)); - } - public void SavePotionIDData(string key, string value) - { - PlayerPrefs.SetString(GetPotionIDSaveKey(key), value); - PlayerPrefs.Save(); - } - public void ClearPostionIDData(string key) - { - PlayerPrefs.DeleteKey(GetPotionIDSaveKey(key)); - } - #endregion - - #region 展示区相关 - public void ResetDisplayAreaGridState(EventPotionGridState gridState) - { - if (m_PotionData == null || m_PotionData.LevelDisplayData == null) return; - - int count = m_PotionData.LevelDisplayData.GridStateList.Count; - for (int i = 0; i < count; ++i) - { - m_PotionData.LevelDisplayData.GridStateList[i] = gridState; - } - } - #endregion - - #region 操作数据相关 - private List m_ScrollerDataList = new List(); - public List ScrollerDataList { get { return m_ScrollerDataList; } } - public void InitScrollerDataList() - { - m_ScrollerDataList.Clear(); - RefreshScrollerDataList(); - } - - private void RefreshScrollerDataList() - { - m_ScrollerDataList.Clear(); - - // 上方墙壁 - int count = m_WallsBefore.Count; - foreach (var item in m_WallsBefore) - { - m_ScrollerDataList.Add(item); - } - - // 操作数据 - count = m_PotionData.LevelProcessedList.Count; - foreach (var item in m_PotionData.LevelProcessedList) - { - m_ScrollerDataList.Add(item); - } - - // 下方墙壁 - count = m_WallsAfter.Count; - foreach (var item in m_WallsAfter) - { - m_ScrollerDataList.Add(item); - } - } - #endregion - - #region 关卡相关 - public int GetPreLevelCountInCurRound() - { - if (m_PotionData.PrePotionID < 0) return -1; - - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(m_PotionData.PrePotionID); - if (m_PotionData.PreStageID == 1) - { - return GetStageList1(potion).Count; - } - return GetStageList2(potion).Count; - } - public int GetLevelCountInCurRound() - { - if (m_PotionData.StageID == 1) - return m_PotionData.Stage1TotalLevel; - return m_PotionData.Stage2TotalLevel; - } - public EventPotionStage GetLastStageInCurRound() - { - if (m_PotionData == null) return null; - - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(m_PotionData.PotionID); - if (potion == null) return null; - - int levelID = 0; - if (m_PotionData.StageID == 1) levelID = GetStageList1(potion)[m_PotionData.Stage1TotalLevel - 1]; - else levelID = GetStageList2(potion)[m_PotionData.Stage2TotalLevel - 1]; - - return m_TbEventPotionStage.GetOrDefault(levelID); - } - public EventPotionStage GetFreshPotionLevel() - { - // 获取当前开放并符合解锁条件的魔药活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int potionID = fishingEvent.RedirectID; - if (potionID < 0) return null; - - // 获取当前魔药活动数据 - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(potionID); - if (potion == null) return null; - - int token = m_DefaultToken; - if (m_PotionData != null) m_PotionData.ClearAllLocalData(); - - token = GContext.container.Resolve().GetInitWelcomeGift(eventID); - - m_PotionData = new EventPotionData(); - m_PotionData.FirstPlayedEventId = m_PendingFirstPlayedEventId > 0 ? m_PendingFirstPlayedEventId : eventID; - // 获取魔药数据 - var stageList1 = GetStageList1(potion); - var stageList2 = GetStageList2(potion); - int stage1Count = stageList1.Count; - int stage2Count = stageList2.Count; - - int stageID = 1; - int levelIndex = 0; - int levelID = stageList1[levelIndex]; - EventPotionStage level = m_TbEventPotionStage.GetOrDefault(levelID); - if (level == null) return null; - m_PotionData.InflationRate = GContext.container.Resolve().InflationRate; - Debug.Log("m_PotionData.InflationRate " + GContext.container.Resolve().InflationRate); - m_PotionData.EventID = eventID; - m_PotionData.PotionID = potionID; - m_PotionData.StageID = stageID; - m_PotionData.Stage1TotalLevel = stage1Count; - m_PotionData.Stage2TotalLevel = stage2Count; - m_PotionData.LevelID = levelID; - m_PotionData.LevelIndex = levelIndex; - m_PotionData.Round = stageID; - - m_PotionData.LevelTargetData.Clear(); - m_PotionData.LevelProcessedList.Clear(); - m_PotionData.LevelDisplayData.Clear(); - - m_PotionData.IsOver = false; - m_PotionData.Token = token; - m_PotionData.ConsumedToken = 0; - m_PotionData.CorrectNum = 0; - m_PotionData.SubmitNum = 0; - m_PotionData.Rule = 0; - - m_PotionData.PreEventID = -1; - m_PotionData.PrePotionID = -1; - m_PotionData.PreStageID = -1; - m_PotionData.PreLevelID = -1; - - m_PotionData.Name = "GetFreshPotionLevel"; - m_PotionData.LevelTargetData.name = m_PotionData.Name + "_Target_" + DateTime.Now.Ticks; - m_PotionData.LevelDisplayData.name = m_PotionData.Name + "_Display_" + DateTime.Now.Ticks; - - GContext.container.Resolve().SaveTransitionData(m_PotionData.EventID, m_PotionData.Token); - - ProcessSorting(level); - - ClearPostionIDData(EventPotionConfig.key_first_check_wrong); - ClearPostionIDData(EventPotionConfig.key_first_check_combination_wrong); - SetRedPoint(); - // 同步数据 - SyncData(); - return level; - } - - public void GoToPotionLevel(int levelID) - { - // 获取当前开放并符合解锁条件的魔药活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - if (fishingEvent == null) - { - Debug.LogWarning("=== 找不到 魔药 对应的 type=4 & subType=5,且符合条件的活动。"); - return; - } - int eventID = fishingEvent.ID; - int potionID = fishingEvent.RedirectID; - if (potionID < 0) - { - Debug.LogWarning("=== 魔药ID出错,活动ID为:" + eventID + ", 魔药ID:" + potionID); - return; - } - - // 获取当前魔药活动数据 - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(potionID); - if (potion == null) - { - Debug.LogWarning("=== 魔药找不到数据,potionID:" + potionID); - return; - } - if (m_PotionData != null) m_PotionData.ClearAllLocalData(); - m_PotionData = new EventPotionData(); - m_PotionData.FirstPlayedEventId = m_PendingFirstPlayedEventId > 0 ? m_PendingFirstPlayedEventId : eventID; - var stageList1 = GetStageList1(potion); - var stageList2 = GetStageList2(potion); - - int stageID = 0; - if (stageList1.IndexOf(levelID) >= 0) - { - stageID = 1; - } - else if (stageList2.IndexOf(levelID) >= 0) - { - stageID = 2; - } - else - { - Debug.LogWarning("=== 魔药在 EventPotionMain StageList1 和 StageList2 里找不到数据,potionID:" + potionID); - return; - } - - List levelList = null; - if (stageID == 1) levelList = stageList1; - else levelList = stageList2; - - int levelIndex = 0; - int count = levelList.Count; - for (int i = 0; i < count; i++) - { - if (levelList[i] == levelID) - { - levelIndex = i; - break; - } - } - - int token = GContext.container.Resolve().GetInitWelcomeGift(eventID); - - m_PotionData.InflationRate = GContext.container.Resolve().InflationRate; - Debug.Log("m_PotionData.InflationRate " + GContext.container.Resolve().InflationRate); - m_PotionData.EventID = eventID; - m_PotionData.PotionID = potionID; - m_PotionData.StageID = stageID; - m_PotionData.Stage1TotalLevel = stageList1.Count; - m_PotionData.Stage2TotalLevel = stageList2.Count; - m_PotionData.LevelID = levelID; - m_PotionData.LevelIndex = levelIndex; - m_PotionData.Round = stageID; - - m_PotionData.LevelTargetData.Clear(); - m_PotionData.LevelProcessedList.Clear(); - m_PotionData.LevelDisplayData.Clear(); - - m_PotionData.IsOver = false; - m_PotionData.Token = token; - m_PotionData.ConsumedToken = 0; - m_PotionData.CorrectNum = 0; - m_PotionData.SubmitNum = 0; - m_PotionData.Rule = 0; - - m_PotionData.PreEventID = -1; - m_PotionData.PrePotionID = -1; - m_PotionData.PreStageID = -1; - m_PotionData.PreLevelID = -1; - - m_PotionData.Name = "GoToPotionLevel"; - m_PotionData.LevelTargetData.name = m_PotionData.Name + "_Target_" + DateTime.Now.Ticks; - m_PotionData.LevelDisplayData.name = m_PotionData.Name + "_Display_" + DateTime.Now.Ticks; - - EventPotionStage level = m_TbEventPotionStage.GetOrDefault(m_PotionData.LevelID); - - ProcessSorting(level); - - // 同步数据 - SyncData(); - SetRedPoint(); - } - - public bool HaveNextPotionLevel() - { - //if (m_PotionData == null) return false; - - //if (m_PotionData.StageID == 1) return true; - - //if (m_PotionData.LevelIndex < m_PotionData.Stage2TotalLevel - 1) return true; - - return true; - } - - public EventPotionStage GetNextPotionLevel() - { - // 获取当前开放并符合解锁条件的魔药活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int potionID = fishingEvent.RedirectID; - if (potionID < 0) return null; - - if (potionID != m_PotionData.PotionID) return GetFreshPotionLevel(); - - // 获取当前魔药活动数据 - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(potionID); - if (potion == null) return null; - - bool haveNextPotionLevel = HaveNextPotionLevel(); - - if (haveNextPotionLevel == false) return null; // 所有活动结束 - - if (m_PotionData.StageID == 1) - { - if (m_PotionData.LevelIndex < m_PotionData.Stage1TotalLevel - 1) - { - m_PotionData.LevelIndex += 1; - } - else - { - m_PotionData.StageID = 2; - m_PotionData.LevelIndex = 0; - m_PotionData.Round++; - } - } - else - { - if (m_PotionData.LevelIndex < m_PotionData.Stage2TotalLevel - 1) - { - m_PotionData.LevelIndex += 1; - } - else - { - m_PotionData.StageID = 2; - m_PotionData.LevelIndex = 0; - m_PotionData.Round++; - } - } - - int stageID = m_PotionData.StageID; - int levelIndex = m_PotionData.LevelIndex; - - // 获取魔药数据 - var stageList1 = GetStageList1(potion); - var stageList2 = GetStageList2(potion); - int stage1Count = stageList1.Count; - if (stage1Count == 0) return null; - int stage2Count = stageList2.Count; - if (stage2Count == 0) return null; - - int levelID = 0; - if (stageID == 1) - { - levelID = stageList1[levelIndex]; - } - else - { - levelID = stageList2[levelIndex]; - } - - EventPotionStage level = m_TbEventPotionStage.GetOrDefault(levelID); - if (level == null) return null; - - m_PotionData.PreEventID = m_PotionData.EventID; - m_PotionData.PrePotionID = m_PotionData.PotionID; - m_PotionData.PreStageID = m_PotionData.StageID; - m_PotionData.PreLevelID = m_PotionData.LevelID; - - m_PotionData.EventID = eventID; - m_PotionData.PotionID = potionID; - m_PotionData.StageID = stageID; - m_PotionData.Stage1TotalLevel = stage1Count; - m_PotionData.Stage2TotalLevel = stage2Count; - m_PotionData.LevelID = levelID; - m_PotionData.LevelIndex = levelIndex; - - m_PotionData.LevelTargetData.Clear(); - m_PotionData.LevelProcessedList.Clear(); - m_PotionData.LevelDisplayData.Clear(); - - m_PotionData.IsOver = false; - m_PotionData.ConsumedToken = 0; - m_PotionData.CorrectNum = 0; - m_PotionData.SubmitNum = 0; - m_PotionData.Rule = 0; - - ProcessSorting(level); - - // 同步数据 - SyncData(); - return level; - } - - public EventPotionStage GetCurrentPotionLevel() - { - // 获取当前开放并符合解锁条件的魔药活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(4, 5, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int potionID = fishingEvent.RedirectID; - if (potionID < 0) return null; - - if (eventID != m_PotionData.EventID || potionID != m_PotionData.PotionID) return GetFreshPotionLevel(); - - return m_TbEventPotionStage.GetOrDefault(m_PotionData.LevelID); - } - #endregion - - #region 关卡是否固定 - public bool IsCurrentLevelFixed() - { - if (m_PotionData == null) return false; - EventPotionMain potion = m_TbEventPotionMain.GetOrDefault(m_PotionData.PotionID); - if (potion == null) return false; - var stageList1 = GetStageList1(potion); - if (stageList1 == null || stageList1.Count == 0) return false; - return !HasEverPlayed && m_PotionData.LevelID == stageList1[0]; - } - #endregion - - #region 红点相关 - public void SetRedPoint() - { - if (m_PotionData != null) - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Potion, m_PotionData.Token > 0, m_PotionData.Token); - } - else - { - RedPointManager.Instance.SetRedPointState(RedPointName.Home_Potion, false); - } - } - #endregion - - #region 代币相关 - public void AddToken(int count) - { - if (m_PotionData != null) - { - m_PotionData.Token += count; - } - else - { - GetFreshPotionLevel(); - if (m_PotionData == null) return; - m_PotionData.Token += count; - m_PotionData.Name = "AddToken"; - m_PotionData.LevelTargetData.name = m_PotionData.Name + "_Target_" + DateTime.Now.Ticks; - m_PotionData.LevelDisplayData.name = m_PotionData.Name + "_Display_" + DateTime.Now.Ticks; - } - - - SetRedPoint(); - FishingPotionAct.Publish(new EventPotionTokenUpdateData()); - - GContext.container.Resolve().SaveTransitionData(m_PotionData.EventID, m_PotionData.Token); - - SyncData(); - } - - public int GetToken() - { - if (m_PotionData != null) - return m_PotionData.Token; - return 0; - } - - public bool ConsumeTokens(int count) - { - bool isEnough = IsEnough(count); - if (isEnough == false) return false; - - m_PotionData.ConsumedToken += count; - AddToken(-count); - return isEnough; - } - - public bool IsEnough(int spend) - { - if (m_PotionData == null) return false; - return (m_PotionData.Token - spend) >= 0; - } - - #endregion - - #region 工具方法 - public void ShuffleList(List list, bool isSkip = false) - { - if (isSkip == true) return; - - int count = list.Count; - for (int i = count - 1; i >= 0; i--) - { - int randomIndex = UnityEngine.Random.Range(0, i + 1); - int temp = list[randomIndex]; - - list[randomIndex] = list[i]; - list[i] = temp; - } - } - #endregion - } - - public class EventPotionData - { - private const string LocalKey = "epdlk"; // EventPotionData LocalKey, 首字母 - - public int EventID { get; set; } - public int PotionID { get; set; } - public int StageID { get; set; } - public int Stage1TotalLevel { get; set; } - public int Stage2TotalLevel { get; set; } - public int LevelID { get; set; } - public int LevelIndex { get; set; } - - public int CorrectNum { get; set; } - public int SubmitNum { get; set; } - - public PotionItemData LevelTargetData { get; set; } // 每一关上方的目标颜色排序 - public List LevelProcessedList { get; set; } // 每一关的操作记录 - public PotionItemData LevelDisplayData { get; set; } // 每一关下方的花瓶颜色排序 - - public bool IsOver { get; set; } - public int Token { get; set; } - public int ConsumedToken { get; set; } - - public string Name { get; set; } - public int Rule { get; set; } - - public int PreEventID { get; set; } - public int PrePotionID { get; set; } - public int PreStageID { get; set; } - public int PreLevelID { get; set; } - - public int Round { get; set; } - public float InflationRate { get; set; } - public int FirstPlayedEventId { get; set; } - - public EventPotionData() - { - EventID = -1; - PotionID = -1; - StageID = -1; - Stage1TotalLevel = -1; - Stage2TotalLevel = -1; - LevelID = -1; - LevelIndex = -1; - Round = -1; - - LevelTargetData = new PotionItemData(); - LevelProcessedList = new List(); - LevelDisplayData = new PotionItemData(); - - IsOver = false; - Token = 0; - ConsumedToken = 0; - CorrectNum = 0; - SubmitNum = 0; - Rule = 0; - - PreEventID = -1; - PrePotionID = -1; - PreStageID = -1; - PreLevelID = -1; - } - - public void Clear() - { - LevelTargetData.Clear(); - LevelProcessedList.Clear(); - LevelDisplayData.Clear(); - } - - public void ClearAllLocalData() - { - //if (PlayerPrefs.HasKey(LocalKey) == false) return; - //PlayerPrefs.DeleteKey(LocalKey); - } - } - - public struct EventPotionResource - { - public int TypeIndex { get; set; } - public int TypeCount { get; set; } - public string ItemResName { get; set; } - public string PaintResName { get; set; } - } - - public class PotionItemData - { - public string name; - public int index; - public bool isOver = true; - - public EventPotionDataType DataType = EventPotionDataType.Data_Wall; - public List ColorTypeList = new List(); // -1:已使用; 0:空; <100:sp_potion_1001; >100:sp_paint_1001 - public List ShelfTypeList = new List(); - public List GridStateList = new List(); - public List FromDisplayAreaIndexList = new List(); - - public int GetColorType(int index) - { - return ColorTypeList[index]; - } - public void SetColorType(int index, int type) - { - ColorTypeList[index] = type; - } - public EventPotionGridState GetGridState(int index) - { - return GridStateList[index]; - } - public void SetGridState(int index, EventPotionGridState state) - { - GridStateList[index] = state; - } - public int GetFromDisplayAreaIndex(int index) - { - return FromDisplayAreaIndexList[index]; - } - public void SetFromDisplayAreaIndex(int index, int value) - { - FromDisplayAreaIndexList[index] = value; - } - public void ResetFromDisplayAreaIndexList(int value) - { - int count = FromDisplayAreaIndexList.Count; - for (int i = 0; i < count; ++i) - { - FromDisplayAreaIndexList[i] = value; - } - } - public int GetValidColorTypeNum() - { - int num = 0; - int count = ColorTypeList.Count; - for (int i = 0; i < count; ++i) - { - if (ColorTypeList[i] > 0) - { - num++; - } - } - return num; - } - public void Log(string pre) - { - //Debug.LogError("--- PotionItemData " + pre + ", type:"+ DataType - // +", colorList:"+ Newtonsoft.Json.JsonConvert.SerializeObject(ColorTypeList) - // + ", fromList:"+ Newtonsoft.Json.JsonConvert.SerializeObject(FromDisplayAreaIndexList) - // + ", stateList:"+ Newtonsoft.Json.JsonConvert.SerializeObject(GridStateList)); - } - public void Clear() - { - index = -1; - isOver = true; - ColorTypeList.Clear(); - ShelfTypeList.Clear(); - GridStateList.Clear(); - FromDisplayAreaIndexList.Clear(); - } - } - - public class EventPotionConfig - { - public const string AtlasName = "event_potion_atlas"; - public const string SAVE_DATA_KEY = "epdk"; // event potion data key - - public const int PotionItemType_Used = -1; // 已使用 - public const int PotionItemType_Empty = 0; // 空 - - public const string spine_potion_idle = "potion_idle"; // spine 动画 - public const string spine_potion_shake_01_2 = "potion_shake_01_2"; // spine 动画 - public const string spine_potion_shake_01_1 = "potion_shake_01_1"; // spine 动画 - public const string spine_potion_shake_02 = "potion_shake_02"; // spine 动画 - public const string spine_potion_shake_03 = "potion_shake_03"; // spine 动画 - public const string spine_potion_pour_L = "potion_pour_L"; // spine 动画 - public const string spine_potion_pour_R = "potion_pour_R"; // spine 动画 - public const string spine_potion_fly = "potion_fly"; // spine 动画 - - public const string anim_gild_show = "gild_show"; // animation 动画 - public const string anim_gild_jump = "gild_jump"; // animation 动画 - public const string anim_gild_jump_down = "gild_jump_down"; // animation 动画 - public const string anim_gild_success = "gild_success"; // animation 动画 - public const string anim_gild_wrong = "gild_wrong"; // animation 动画 - public const string anim_gild_settlement = "gild_settlement"; // animation 动画 - public const string anim_gild_gap = "gild_gap"; // animation 动画 - - public const int Token_Consume_Num = 1; // 每次消耗代币数量 - public const int Token_Return_Num = -1; // 每次返还代币数量 - - public const string key_first_check_wrong = "potion_kfcw"; // 第一次检测错误,本地存储数据key - public const string key_first_check_combination_wrong = "potion_kfccw"; // 第一次组合检测错误,本地存储数据key - } - public enum EventPotionDataType - { - Data_Wall, // 墙壁 - Data_Item, // 数据 - Data_ItemAndOperation // 数据并添加到操作区域 - } - public enum EventPotionShelfType - { - Shelf_Default, // 置物架默认状态 - Shelf_Success // 置物架成功状态 - } - - public enum EventPotionGridState - { - GridState_Invalid, // 无效 - GridState_Empty, // 空 - GridState_Occupied, // 占用中 - GridState_Ok, // 对比成功 - GridState_Wrong, // 对比失败 - GridState_Over, // 已结束 - } - public class EventPotionTokenUpdateData { } - public class EventPotionCloseCameraData { } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/021-EventScratchTicketDataManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/021-EventScratchTicketDataManager.cs.txt deleted file mode 100644 index 6e675e89f..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/021-EventScratchTicketDataManager.cs.txt +++ /dev/null @@ -1,957 +0,0 @@ -using asap.core; -using cfg; -using GameCore; -using System; -using System.Collections.Generic; -using System.Linq; -using UniRx; -using UnityEngine; -using UnityEngine.AddressableAssets; -using UnityEngine.U2D; -using UnityEngine.UI; - -namespace game -{ - public class EventScratchTicketDataManager - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } -#if UNITY_EDITOR - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 100; -#else - private bool m_IsCheckCondition = true; - private bool m_IsSyncData = true; - private int m_DefaultToken = 0; -#endif - - #region 埋点相关 - public int TempRecordRewardTaskID { get; set; } = 0; - public int TempRecordRewardTaskConsumedToken { get; set; } = 0; - public void SyncTempRecordData() - { - ClearRecordList(); - - TempRecordRewardTaskID = m_ScratchTicketData.EventScratchRewardTaskID; - TempRecordRewardTaskConsumedToken = m_ScratchTicketData.RewardTaskConsumedToken; - } - public void RecordStatisticalData() - { - int fromToken = TempRecordRewardTaskConsumedToken; - - int taskID = TempRecordRewardTaskID; - EventScratchReward curScratchReward = GetEventScratchReward(taskID); - - int count = m_RecordList.Count; - - for (int i = 0; i < count; i++) - { - var data = m_RecordList[i]; - fromToken += 1; - if (fromToken >= curScratchReward.TokenRequired) - { - data.MilestoneTask = curScratchReward.TaskID; - - fromToken = 0; - - taskID = curScratchReward.NextTask; - curScratchReward = GetEventScratchReward(taskID); - } - -#if AGG - using (var e = GEvent.GameEvent("event_scratchticket")) - { - e.AddContent("ticket_id", data.TicketID) - .AddContent("ticketfinish_id", data.TicketFinishID) - .AddContent("scratch_type", ScratchTicketData.magIndex + 1) - .AddContent("milestone_task", data.MilestoneTask); - } -#endif - } - -#if UNITY_EDITOR - Debug.Log("--- RecordStatisticalData m_RecordList: " + Newtonsoft.Json.JsonConvert.SerializeObject(m_RecordList)); -#endif - } - private List m_RecordList = new List(); - public void InitRecordList() - { - ClearRecordList(); - } - public void ClearRecordList() - { - m_RecordList?.Clear(); - TempRecordRewardTaskID = 0; - TempRecordRewardTaskConsumedToken = 0; - } - public EventScratchTicketRecordData AddRecordData() - { - EventScratchTicketRecordData data = new EventScratchTicketRecordData(); - m_RecordList.Add(data); - return data; - } - - #endregion - - #region 数据相关 - private EventScratchTicketData m_ScratchTicketData; - internal bool IsInactiveForKVValidation => m_Tables==null && m_TbEventScratchMain==null && m_TbEventScratchCard==null && - m_TbEventScratchReward==null && m_ChainPackData==null && m_NormalPackData==null && m_SpriteAtlas==null && m_SpriteDict==null && - m_UIPanel==null && m_InfoPanel==null && m_RewardPanel==null && m_ChainPackPanel==null && m_PackPanel==null && - m_RecordList.Count==0 && m_PointWeightList.Count==0 && m_ScratchStampList.Count==0 && - TempRecordRewardTaskID==0 && TempRecordRewardTaskConsumedToken==0; - - internal static game.PlayerDataStorage.PlayerKVScratchState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeScratch(raw,snapshot,errors); - internal void ResetForKVLoad() - { - m_ScratchTicketData=null; TempRecordRewardTaskID=TempRecordRewardTaskConsumedToken=0; m_RecordList=new List(); - m_PointWeightList=new List(); m_ScratchStampList=new List(); m_ChainPackData=null; m_NormalPackData=null; - m_UIPanel=m_InfoPanel=m_RewardPanel=m_ChainPackPanel=m_PackPanel=null; m_SpriteAtlas=null; m_SpriteDict=null; - m_Tables=null; m_TbEventScratchMain=null; m_TbEventScratchCard=null; m_TbEventScratchReward=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVScratchState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - m_ScratchTicketData=!state.IsPresent ? null : new EventScratchTicketData - { - EventID=state.EventID, - ScratchMainID=state.ScratchMainID, - ChainPackID=state.ChainPackID, - Token=state.Token, - ConsumedToken=state.ConsumedToken, - RewardTaskConsumedToken=state.RewardTaskConsumedToken, - EventScratchRewardTaskID=state.EventScratchRewardTaskID, - EventScratchCardID=state.EventScratchCardID, - TotalConsumedToken=state.TotalConsumedToken, - ChainPackProgress=state.ChainPackProgress, - magIndex=state.magIndex, - IsOver=state.IsOver, - LuckyValue=state.LuckyValue, - InflationRate=state.InflationRate, - StampRewardList=new List(state.StampRewardList), - StampRewardDict=state.StampRewardDict.ToDictionary(p=>p.Key,p=>new EventScratchTicketOwnedStampRewardData { EventScratchCardID=p.Value.EventScratchCardID,Count=p.Value.Count }) - }; - } - public EventScratchTicketData ScratchTicketData { get { return m_ScratchTicketData; } } - public EventScratchMain GetFreshScratchTicketData() - { - // 获取当前开放并符合解锁条件的刮刮乐活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(7, 3, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int scratchMainID = fishingEvent.RedirectID; - if (scratchMainID < 0) return null; - - // 获取当前刮刮乐活动数据 - EventScratchMain scratchMain = m_TbEventScratchMain.GetOrDefault(scratchMainID); - if (scratchMain == null) return null; - - int token = m_DefaultToken; - if (m_ScratchTicketData != null) m_ScratchTicketData.Clear(); - m_ScratchTicketData = null; - - token = GContext.container.Resolve().GetInitWelcomeGift(eventID); - - m_ScratchTicketData = new EventScratchTicketData(); - m_ScratchTicketData.InflationRate = GContext.container.Resolve().InflationRate; - Debug.Log("m_PinballData.InflationRate " + GContext.container.Resolve().InflationRate); - m_ScratchTicketData.EventID = eventID; - m_ScratchTicketData.ScratchMainID = scratchMainID; - - m_ScratchTicketData.IsOver = false; - m_ScratchTicketData.Token = token; - m_ScratchTicketData.ConsumedToken = 0; - - m_ScratchTicketData.LuckyValue = 0f; - m_ScratchTicketData.EventScratchCardID = 0; - - m_ScratchTicketData.TotalConsumedToken = 0; - m_ScratchTicketData.ChainPackProgress = 0; - - m_ScratchTicketData.StampRewardDict = new Dictionary(); - - EventScratchReward eventScratchReward = m_TbEventScratchReward.DataList[0]; - m_ScratchTicketData.EventScratchRewardTaskID = eventScratchReward.TaskID; - m_ScratchTicketData.RewardTaskConsumedToken = 0; - if (FishingEventData.Condition_NoRechargeDay()) - { - m_ScratchTicketData.ChainPackID = scratchMain.AdPackId; - } - else - { - m_ScratchTicketData.ChainPackID = scratchMain.PackId; - } - m_ScratchTicketData.StampRewardList.Clear(); - - ClearSaveData(EventScratchTicketConfig.key_first_in); - - GContext.container.Resolve().SaveTransitionData(m_ScratchTicketData.EventID, m_ScratchTicketData.Token); - - UpdateLuckyValueAndWeight(); - - foreach (var item in scratchMain.GuidanceGroupList) - { - GContext.container.Resolve().ClearGuide(item); - } - - // 同步数据 - SyncData(); - return scratchMain; - } - - public EventScratchMain GetNextScratchTicketData() - { - // 获取当前开放并符合解锁条件的刮刮乐活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(7, 3, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int scratchMainID = fishingEvent.RedirectID; - if (scratchMainID < 0) return null; - - // 获取当前刮刮乐活动数据 - EventScratchMain scratchMain = m_TbEventScratchMain.GetOrDefault(scratchMainID); - if (scratchMain == null) return null; - - m_ScratchTicketData.EventID = eventID; - m_ScratchTicketData.ScratchMainID = scratchMainID; - - m_ScratchTicketData.IsOver = false; - m_ScratchTicketData.ConsumedToken = 0; - - UpdateLuckyValueAndWeight(); - - // 同步数据 - SyncData(); - return scratchMain; - } - public EventScratchMain ContinueGame() - { - if (m_ScratchTicketData == null) return GetFreshScratchTicketData(); - - // 获取当前开放并符合解锁条件的刮刮乐活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(7, 3, m_IsCheckCondition); - if (fishingEvent == null) return null; - int eventID = fishingEvent.ID; - int scratchMainID = fishingEvent.RedirectID; - if (scratchMainID < 0) return null; - - if (eventID != m_ScratchTicketData.EventID || scratchMainID != m_ScratchTicketData.ScratchMainID) return GetFreshScratchTicketData(); - - // 获取当前刮刮乐活动数据 - EventScratchMain scratchMain = m_TbEventScratchMain.GetOrDefault(scratchMainID); - if (scratchMain == null) return null; - - return scratchMain; - } - public List m_PointWeightList = new List(); - public EventScratchCard UpdateLuckyValueAndWeight() - { - if (m_TbEventScratchCard == null) return null; - - m_PointWeightList.Clear(); - - float luckyValue = m_ScratchTicketData.LuckyValue; - int count = m_TbEventScratchCard.DataList.Count; - - float total = 0; - for (int i = 0; i < count; ++i) - { - EventScratchCard item = m_TbEventScratchCard.DataList[i]; - - float weight = item.Weight + luckyValue * item.LuckParameter; - total += weight; - float tmp = total; - m_PointWeightList.Add(tmp); - } - - float randomValue = UnityEngine.Random.Range(0f, total); - int index = FindInsertionIndex(m_PointWeightList, randomValue); - - EventScratchCard target = m_TbEventScratchCard.DataList[index]; - if (float.MaxValue - target.DeltaLuck <= m_ScratchTicketData.LuckyValue) - { - m_ScratchTicketData.LuckyValue = 0; - } - else - { - m_ScratchTicketData.LuckyValue += target.DeltaLuck; - if (m_ScratchTicketData.LuckyValue < 0f) - { - m_ScratchTicketData.LuckyValue = 0f; - } - } - - m_ScratchTicketData.EventScratchCardID = target.ID; - - return target; - } - public EventScratchCard GetCurrentEventScratchCard() - { - if (m_ScratchTicketData == null) return null; - return GetEventScratchCard(m_ScratchTicketData.EventScratchCardID); - } - public int FindInsertionIndex(List sortedList, float target) - { - if (sortedList == null || sortedList.Count == 0) - { - Debug.LogError("---- EventScratchTicketDataManager->FindInsertionIndex 数组为空"); - return -1; - } - - if (target < sortedList[0]) - { - return 0; - } - - if (target >= sortedList[sortedList.Count - 1]) - { - return -1; - } - - // 使用二分查找算法 - int left = 0; - int right = sortedList.Count - 1; - int result = -1; - - while (left <= right) - { - int mid = left + (right - left) / 2; - - if (sortedList[mid] > target) - { - if (mid > 0 && target > sortedList[mid - 1] && target < sortedList[mid]) - { - result = mid; - break; - } - right = mid - 1; - } - else - { - if (mid < sortedList.Count - 1 && target >= sortedList[mid] && target < sortedList[mid + 1]) - { - result = mid + 1; - break; - } - left = mid + 1; - } - } - - return result; - } - public EventScratchMain GetCurrentEventScratchMain() - { - if (m_ScratchTicketData == null) return GetFreshScratchTicketData(); - - return m_TbEventScratchMain.GetOrDefault(m_ScratchTicketData.ScratchMainID); - } - private EventScratchTicketChainPackData m_ChainPackData; - public EventScratchTicketChainPackData GetChainPackData() - { - if (m_ChainPackData == null) - { - EventScratchMain scratchMain = GetCurrentEventScratchMain(); - if (scratchMain == null) return null; - int packId = m_ScratchTicketData.ChainPackID; - if (packId == 0) - { - packId = scratchMain.PackId; - } - var chainList = m_Tables.TbEventPackManager[packId].VIPPackList[0]; - - var expireTime = GetExpireTime; - - var chainListIdSet = chainList.ToHashSet(); - var packs = m_Tables.TbPack.DataList.Where(p => chainListIdSet.Contains(p.ID)).ToArray(); - - m_ChainPackData = new EventScratchTicketChainPackData(chainList, expireTime, packs, m_ScratchTicketData.EventID, m_ScratchTicketData.ChainPackProgress); - RedPointManager.Instance.SetRedPointState(m_ChainPackData.RedPointKey, m_ChainPackData.DoNeedPackRedPoint, m_ChainPackData.RedPointIndex); - } - return m_ChainPackData; - } - public void InitChainPackData() - { - ClearChainPackData(); - } - public void ClearChainPackData() - { - if (m_ChainPackData != null) - { - m_ChainPackData = null; - } - } - private EventBreakNormalPackInfo m_NormalPackData; - public EventBreakNormalPackInfo GetNormalPackData() - { - if (m_NormalPackData == null) - { - EventScratchMain scratchMain = GetCurrentEventScratchMain(); - if (scratchMain == null) return null; - - var expireTime = GetExpireTime; - - var packList = m_Tables.TbEventPackManager[scratchMain.PackId2].VIPPackList[0]; - - m_NormalPackData = new EventBreakNormalPackInfo - { - EventId = m_ScratchTicketData.EventID, - PackLeft = m_Tables.TbPack[packList[0]], - PackRight = m_Tables.TbPack[packList[1]], - ExpireTime = expireTime, - }; - } - - return m_NormalPackData; - } - private void InitNormalPackData() - { - ClearNormalPackDatas(); - } - private void ClearNormalPackDatas() - { - m_NormalPackData = null; - } - public void InitRewardBagData() - { - GContext.container.Resolve().Reset(); - } - - public void SetChainProgress(int progress) - { - m_ScratchTicketData.ChainPackProgress = progress; - SyncData(); - } - public int GetChainProgress() - { - return m_ScratchTicketData.ChainPackProgress; - } - public void AddStampReward(int cardID) - { - m_ScratchTicketData.StampRewardList.Add(cardID); - SyncData(); - } - public int GetStampRewardNum() - { - return m_ScratchTicketData.StampRewardList.Count; - } - public EventScratchCard GetFirstStampReward() - { - return GetEventScratchCard(m_ScratchTicketData.StampRewardList[0]); - } - public void RemoveFirstStampReward() - { - m_ScratchTicketData.StampRewardList.RemoveAt(0); - SyncData(); - } - - private List m_ScratchStampList = new List(); - public List ScratchStampList { get { return m_ScratchStampList; } } - private void InitScratchStampList() - { - m_ScratchStampList.Clear(); - } - public void ClearScratchStampList() - { - m_ScratchStampList.Clear(); - } - public void AddScratchStamp(int cardID) - { - m_ScratchStampList.Add(cardID); - } - public EventScratchCard GetFirstScratchStamp() - { - return GetEventScratchCard(m_ScratchStampList[0]); - } - #endregion - - #region 代币相关 - public int GetToken() - { - if (m_ScratchTicketData != null) - return m_ScratchTicketData.Token; - return 0; - } - public int GetRedCount() - { - if (m_ScratchTicketData != null) - { - //+礼包红点 - if (m_ChainPackData != null) - { - return m_ScratchTicketData.Token + m_ChainPackData.RedPointIndex; - - } - return m_ScratchTicketData.Token; - } - return 0; - } - public void AddToken(int count) - { - if (m_ScratchTicketData != null) - { - m_ScratchTicketData.Token += count; - } - else - { - if (m_ScratchTicketData == null) return; - m_ScratchTicketData.Token += count; - } - - if (m_ScratchTicketData.Token > 0) RedPointManager.Instance.SetRedPointState(RedPointName.Home_ScratchTicket, true, GetRedCount()); - else RedPointManager.Instance.SetRedPointState(RedPointName.Home_ScratchTicket, false); - - FishingScratchTicketAct.Publish(new EventScratchTicketTokenUpdateData()); - - GContext.container.Resolve().SaveTransitionData(m_ScratchTicketData.EventID, m_ScratchTicketData.Token); - - SyncData(); - } - public bool ConsumeTokens(int count) - { - bool isEnough = IsEnough(count); - if (isEnough == false) return false; - - m_ScratchTicketData.ConsumedToken += count; - m_ScratchTicketData.TotalConsumedToken += count; - AddToken(-count); - return isEnough; - } - - public bool IsEnough(int spend) - { - if (m_ScratchTicketData == null) return false; - return (m_ScratchTicketData.Token - spend) >= 0; - } - #endregion - - #region 活动相关 - public void ActivateEvent(FishingEvent fishingEvent) - { - if (fishingEvent == null) return; - - if (!Init()) return; - - if (m_ScratchTicketData == null) GetFreshScratchTicketData(); - else FixScratchTicketData(); - } - - public void GetDataFromServer(string json) - { - if (string.IsNullOrEmpty(json)) - { - GameDebug.LogWarning("EventScratchTicket get data from server has encountered empty data."); - return; - } - - try - { - m_ScratchTicketData = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - } - catch (Exception e) - { - GameDebug.LogWarning("EventScratchTicket deserialize data has failed. Exception: " + e.ToString()); - return; - } - - if (!Init()) return; - } - public int FixScratchTicketData() - { - if (m_ScratchTicketData == null) return 0; - - // 获取当前开放并符合解锁条件的刮刮乐活动ID - FishingEventData fishingEventData = GContext.container.Resolve(); - FishingEvent fishingEvent = fishingEventData.GetEventByTypeAndSubType(7, 3, m_IsCheckCondition); - if (fishingEvent == null) return ClearData(); - int eventID = fishingEvent.ID; - int scratchMainID = fishingEvent.RedirectID; - if (scratchMainID < 0) return ClearData(); - - if (eventID != m_ScratchTicketData.EventID || scratchMainID != m_ScratchTicketData.ScratchMainID) return ClearData(); - - return 0; - } - public DateTime GetExpireTime - { - get => DateTime.Parse((m_Tables.TbFishingEvent[m_ScratchTicketData.EventID].TimeDefinition as LimitedTime).EndTime); - } - public TimeSpan RemainingTime - { - get => GetExpireTime - ZZTimeHelper.UtcNow(); - } - public int ClearData() - { - if (m_ScratchTicketData == null) return 0; - - m_ScratchTicketData.Clear(); - m_ScratchTicketData = null; - return 0; - } - public void SyncData() - { - if (!m_IsSyncData) return; - playerSaveStore.Write(EventScratchTicketConfig.SAVE_DATA_KEY, Newtonsoft.Json.JsonConvert.SerializeObject(m_ScratchTicketData)).RequireAccepted(); - } - - List magList = new List() { 1, 5, 10, 20 }; - - public int ChangeScratchMag() - { - ScratchTicketData.magIndex++; - if (ScratchTicketData.magIndex >= magList.Count) - { - ScratchTicketData.magIndex = 0; - } - SyncData(); - return magList[ScratchTicketData.magIndex]; - } - public int GetScratchMag() - { - return magList[ScratchTicketData.magIndex]; - } - public bool IsMaxMag() - { - return ScratchTicketData.magIndex == magList.Count - 1; - } - #endregion - - #region 生命周期 - public bool Init() - { - InitTables(); - return true; - } - public void StartData() - { - ClearUIData(); - InitUIData(); - InitChainPackData(); - InitNormalPackData(); - InitRewardBagData(); - InitSpriteDict(); - InitScratchStampList(); - InitRecordList(); - } - public void StopData() - { - ClearUIData(); - ClearChainPackData(); - ClearNormalPackDatas(); - ClearSpriteAtlas(); - ClearSpriteDict(); - ClearScratchStampList(); - ClearRecordList(); - } - #endregion - - #region UI 设置相关 - private UIType m_UIPanel = null, m_InfoPanel = null, m_RewardPanel = null, m_ChainPackPanel = null, m_PackPanel = null; - public void ClearUIData() - { - m_UIPanel = null; - m_InfoPanel = null; - m_RewardPanel = null; - m_ChainPackPanel = null; - m_PackPanel = null; - } - public void InitUIData() - { - GetUIPanel(); - GetInfoPanel(); - GetChainPackPanel(); - GetPackPanel(); - } - public UIType GetUIPanel() - { - if (m_UIPanel == null) - { - var data = GetCurrentEventScratchMain(); - m_UIPanel = new UIType(data.UIPanel); - } - return m_UIPanel; - } - public UIType GetRewardPanel() - { - if (m_RewardPanel == null) - { - var data = GetCurrentEventScratchMain(); - m_RewardPanel = new UIType(data.RewardPanel); - } - return m_RewardPanel; - } - public UIType GetInfoPanel() - { - if (m_InfoPanel == null) - { - var data = GetCurrentEventScratchMain(); - m_InfoPanel = new UIType(data.InfoPanel); - } - return m_InfoPanel; - } - public UIType GetChainPackPanel() - { - if (m_ChainPackPanel == null) - { - var data = GetCurrentEventScratchMain(); - m_ChainPackPanel = new UIType(data.ChainPackPanel); - } - return m_ChainPackPanel; - } - public UIType GetPackPanel() - { - if (m_PackPanel == null) - { - var data = GetCurrentEventScratchMain(); - m_PackPanel = new UIType(data.PackPanel); - } - return m_PackPanel; - } - #endregion - - #region 图集等 - private SpriteAtlas m_SpriteAtlas; - public SpriteAtlas SpriteAtlas - { - get { return m_SpriteAtlas; } - set { m_SpriteAtlas = value; } - } - public void ClearSpriteAtlas() - { - m_SpriteAtlas = null; - } - private Dictionary m_SpriteDict; - private void InitSpriteDict() - { - if (m_SpriteDict != null) - { - m_SpriteDict.Clear(); - m_SpriteDict = null; - } - m_SpriteDict = new Dictionary(); - } - public void AddSprite(string name, Sprite sprite) - { - m_SpriteDict.Add(name, sprite); - } - public Sprite GetSprite(string name) - { - return m_SpriteDict[name]; - } - private void ClearSpriteDict() - { - if (m_SpriteDict == null) return; - - foreach (var pair in m_SpriteDict) - { - Addressables.Release(pair.Value); - } - - m_SpriteDict.Clear(); - m_SpriteDict = null; - } - #endregion - - #region Table Data - private Tables m_Tables; - private TbEventScratchMain m_TbEventScratchMain; - private TbEventScratchCard m_TbEventScratchCard; - private TbEventScratchReward m_TbEventScratchReward; - - private void InitTables() - { - m_Tables = GContext.container.Resolve(); - if (m_Tables == null) return; - - m_TbEventScratchMain = m_Tables.TbEventScratchMain; - m_TbEventScratchCard = m_Tables.TbEventScratchCard; - m_TbEventScratchReward = m_Tables.TbEventScratchReward; - } - - public EventScratchReward GetEventScratchReward(int taskID) - { - return m_TbEventScratchReward.GetOrDefault(taskID); - } - public EventScratchReward GetEventScratchFinalReward() - { - int count = m_TbEventScratchReward.DataList.Count; - return m_TbEventScratchReward.DataList[count - 1]; - } - public EventScratchCard GetEventScratchCard(int cardID) - { - return m_TbEventScratchCard.GetOrDefault(cardID); - } - #endregion - - #region 本地存储数据相关 - public string GetSaveKey(string key) - { - if (m_ScratchTicketData == null) return key; - return m_ScratchTicketData.EventID + "-" + m_ScratchTicketData.ScratchMainID + "-" + key; - } - public bool HasSaveKey(string key) - { - return PlayerPrefs.HasKey(GetSaveKey(key)); - } - public void SaveData(string key, string value) - { - PlayerPrefs.SetString(GetSaveKey(key), value); - PlayerPrefs.Save(); - } - public void ClearSaveData(string key) - { - PlayerPrefs.DeleteKey(GetSaveKey(key)); - } - - #endregion - - #region 红点相关 - public bool IsRedDotDisplayed() - { - if (m_ScratchTicketData == null) return false; - return m_ScratchTicketData.Token > 0; - } - #endregion - } - public enum EventScratchTicketScratchType - { - TypeInvalid, - TypeScratch1, - TypeScratch5,//5不是代表5次 表示多数 - TypeTemporary - } - public class EventScratchTicketData - { - public int EventID { get; set; } - public int ScratchMainID { get; set; } - public int ChainPackID { get; set; } - public bool IsOver { get; set; } - public int Token { get; set; } - public int ConsumedToken { get; set; } - - public int RewardTaskConsumedToken { get; set; } - public int EventScratchRewardTaskID { get; set; } - - public int EventScratchCardID { get; set; } - public float LuckyValue { get; set; } - - public int TotalConsumedToken { get; set; } - public int ChainPackProgress { get; set; } - - public List StampRewardList = new List(); - public float InflationRate { get; set; } - - public Dictionary StampRewardDict { get; set; } - public int magIndex { get; set; } - public void Clear() - { - if (StampRewardDict != null) - { - StampRewardDict.Clear(); - } - StampRewardList.Clear(); - } - - } - public class EventScratchTicketConfig - { - public const string SAVE_DATA_KEY = "estdk"; // event scratch ticket data key - public const string key_first_in = "scratch_kfcw"; // 本地存储数据key - - public static Vector2 ScreenToGraphicLocalPoint(Graphic graphic, Vector2 screenPoint) - { - var canvas = graphic.canvas.rootCanvas; - var camera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera; - var rt = graphic.rectTransform; - - return RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, screenPoint, camera, out var result) ? result : default; - } - } - - public class EventScratchTicketTokenUpdateData - { - - } - public class EventScratchTicketRewardTaskUpdateData - { - public EventScratchTicketScratchType ScratchType; - public int Token; - } - public class EventScratchTicketRewardDisplayUpdateData - { - public int TaskID; - public int FromToken; - public int TargetToken; - public int LevelToken; - public float FromRatio; - public float TargetRatio; - public EventScratchReward Reward; - } - public class EventScratchTicketChangeScratchTypeData - { - public EventScratchTicketScratchType ScratchType; - } - public class EventScratchTicketRevealedAllData - { - public EventScratchTicketScratchType ScratchType; - } - public class EventScratchTicketStampRewardUpdateData - { - - } - public class EventScratchTicketStartStampRewardCountUpdateData - { - - } - public class EventScratchTicketStopStampRewardCountUpdateData - { - - } - public class EventScratchTicketOwnedStampRewardData - { - public int EventScratchCardID; - public int Count; - } - public class EventScratchTicketStampRewardFlyData - { - public EventScratchTicketScratchType ScratchType; - public Vector3 SrcPosition; - //public Vector3 DestPosition; - public Vector3 LocalScale; - public float IconSize; - } - public class EventScratchTicketRewardEmptyData - { - public EventScratchTicketScratchType ScratchType; - } - public class EventScratchTicketUpdateEventScratchCardData - { - - } - public class EventScratchTicketPanelPlayEndAnimData - { - public EventScratchTicketScratchType ScratchType; - } - public class EventScratchTicketPlayScratchType5 - { - - } - public class EventScratchTicketStartMaskData - { - - } - public class EventScratchTicketOutData - { - public EventScratchTicketScratchType ScratchType; - } - public class EventScratchTicketRecordData - { - public int TicketID; - public int TicketFinishID; - public int MilestoneTask; - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/022-FishingChallengeManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/022-FishingChallengeManager.cs.txt deleted file mode 100644 index 63d91899a..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/022-FishingChallengeManager.cs.txt +++ /dev/null @@ -1,1114 +0,0 @@ -using asap.core; -using cfg; -using game; -using GameCore; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine; - -public class FishingChallengeData -{ - public bool FirstOpen; - // 记录当前EventID - public int EventId; - // 已经通关轮数,完成之后更新, - public int RankTierLevel; - // 记录当前已经结算,防止改表的问题 - public int Finished; - // 记录当前的表单号,获取争取的 EventData - public int RedirectID; - // 积分 - public int Score; - // 未处理积分,进入场景后显示的积分增长 - public int ProcessedScore; - // 当前的阶段,完成了的部分 - public int step; // 最多是7关 - // 界面上显示 的部分 - public int uiStep; - - public int index; // 根据权重判断的索引 - public DateTime StartTime; - // 结束时间 - public DateTime EndTime; - public List eliminateNumber; //每个阶段的排除人数 - public List robotAccountList; //机器人列表 - public float InflationRate; //通货膨胀率 -} - -public class FishingChallengeManager -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore SaveStore { get; set; } - - // - private const string SaveKey = "FishingChallengeData"; - - [Inject] public Tables _tables { get; set; } - public string PrefabName { get; private set; } - private int TopRankTier { get; set; } - public int Rank { get; private set; } - private FishingEvent CurFishingEventData { get; set; } - public int EventItemId => eventChallengeConfig?.Item ?? 0; - - public int FullStep; - // 全部竞赛玩家数量 - public int PlayerFullNumber; - // Btn 上显示用 - public int PreScore; - // 开始时间 - private DateTime StartTime; - // 结束时间 - private DateTime EndTime; - // - public FishingChallengeData fishingChallengeData { get; private set; } - internal bool IsInactiveForKVValidation => !IsInit && CurFishingEventData==null && eventChallengeMain==null && - eventChallengeConfig==null && challengeMapData==null && _stageDropList.Count==0 && _eliminateListScore.Count==0; - - internal static game.PlayerDataStorage.PlayerKVChallengeState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeChallenge(raw,snapshot,errors); - internal void ResetForKVLoad() - { - fishingChallengeData=null; IsInit=false; PrefabName=null; -#if UNITY_EDITOR - _cheatingScore=0; -#endif - TopRankTier=Rank=FullStep=PlayerFullNumber=PreScore=0; - CurFishingEventData=null; StartTime=EndTime=default; eventChallengeMain=null; eventChallengeConfig=null; challengeMapData=null; itemDataList=null; - _stageDropList.Clear(); _eliminateListScore.Clear(); _eventTrackStageList=new List(); _eventTrackNormalRewardList=new List(); InVisibleReason=string.Empty; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVChallengeState state) - { - if(state==null) throw new ArgumentNullException(nameof(state)); - fishingChallengeData=!state.IsPresent || state.IsExplicitNull ? null : new FishingChallengeData - { - FirstOpen=state.FirstOpen, - EventId=state.EventId, - RankTierLevel=state.RankTierLevel, - Finished=state.Finished, - RedirectID=state.RedirectID, - Score=state.Score, - ProcessedScore=state.ProcessedScore, - step=state.step, - uiStep=state.uiStep, - index=state.index, - StartTime=state.StartTime, - EndTime=state.EndTime, - eliminateNumber=new List(state.eliminateNumber), - robotAccountList=new List(state.robotAccountList), - InflationRate=state.InflationRate - }; - } - public EventChallengeMain eventChallengeMain { get; private set; } - public EventChallengeConfig eventChallengeConfig { get; private set; } - public MapData challengeMapData { get; private set; } - public List itemDataList { get; private set; } - // - private readonly List _stageDropList = new(); - // - // 打点数据 - private List _eventTrackStageList; - private List _eventTrackNormalRewardList; - private bool IsInit { get; set; } = false; - - public bool IsFirstOpen - { - get { return fishingChallengeData.FirstOpen; } - set - { - if (fishingChallengeData.FirstOpen) - { - fishingChallengeData.FirstOpen = false; - DoSave(); - } - } - } - // 进入的第一步,设置数据 - - // public bool IsUpdateCamera { get; set; } = false; - - public void SetupEventData(FishingEvent fishingEvent) - { - ELog($"SetupEventData -> {fishingEvent}"); - // if (CurFishingEventData == null || (CurFishingEventData.ID != fishingEvent?.ID)) - { - CurFishingEventData = fishingEvent; - } - //UpdateTimeData(); - } - - public string InVisibleReason { get; set; } = string.Empty; - - - public bool ShouldOpen() - { - ELog("ShouldOpen"); - - if (fishingChallengeData == null) - { - InVisibleReason = $"fishingChallengeData Failed {ZZTimeHelper.UtcNow()}"; - return false; - } - - - // 是否时间允许 - if (!IsTimeAllow()) - { - InVisibleReason = $"IsTimeAllow Failed {ZZTimeHelper.UtcNow()} {fishingChallengeData?.StartTime} {fishingChallengeData?.EndTime}"; - return false; - } - - // 判断是否通关 - if (IsClearAllLevel()) - { - InVisibleReason = $"IsClearAllLevel Failed {ZZTimeHelper.UtcNow()} {fishingChallengeData?.RankTierLevel} {TopRankTier}"; - return false; - } - - InVisibleReason = string.Empty; - ELog("ShouldOpen true"); - return true; - } - - public bool IsTimeAllow() - { - var now = ZZTimeHelper.UtcNow(); - - var startTime = fishingChallengeData.StartTime; - var endTime = fishingChallengeData.EndTime; -#if UNITY_EDITOR - - var timeOpened = (now - startTime).TotalSeconds; - var timeEnded = (endTime - now).TotalSeconds; - ELog($"StartTime: {startTime} Now: {now} EndTime:{endTime} TimeOpened:{timeOpened} TimeToEnd:{timeEnded} Other: {1800000 - timeOpened} IsTimeAllow => {now <= endTime}"); -#endif - return now >= startTime && now <= endTime; - } - - public void ClearFishingChallengeData() - { - fishingChallengeData = null; - _stageDropList.Clear(); - IsInit = false; - DoSave(); - } - - public bool IsStepFinished(int step) - { - var finalStep = _eliminateListScore.Count; - var isFinish = step == finalStep; - ELog($"IsStepFinished() -> {step} {finalStep} {isFinish}"); - return isFinish; - } - // 当前轮所有是否完成 - private bool IsFinishCurLevel() - { - return IsStepFinished(fishingChallengeData.step); - } - // 是否全部通关 - private bool IsClearAllLevel() - { - // 时间限制要不要加上,需要跟胡后续判定 - if (fishingChallengeData.RankTierLevel <= TopRankTier) - { - return true; - } - - return false; - } - public void InitChallengeData(string str) - { - ELog($"InitChallengeData -> {str}"); - fishingChallengeData = JsonConvert.DeserializeObject(str); - } - - private void InitBaseData() - { - var limitedTime = (LimitedTime)CurFishingEventData.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - - fishingChallengeData.FirstOpen = true; - fishingChallengeData.RankTierLevel = int.MaxValue; - fishingChallengeData.RedirectID = CurFishingEventData.RedirectID; - fishingChallengeData.EventId = CurFishingEventData.ID; - fishingChallengeData.StartTime = startTime; - fishingChallengeData.EndTime = endTime; - fishingChallengeData.InflationRate = GContext.container.Resolve().InflationRate; - ELog($"fishingChallengeData.EventId -> {fishingChallengeData.EventId}"); - } - - public void CheckInit() - { - ELog("CheckInit"); - ProcessLastChallenge(); - Init(); - } - - public void Init() - { - ELog("Init"); - // 设置数据 - TopRankTier = _tables.TbEventChallengeMain.DataList[0].RankTier; - _stageDropList.Clear(); - - if (CurFishingEventData != null && fishingChallengeData != null && CurFishingEventData.ID != fishingChallengeData.EventId) - { - ClearFishingChallengeData(); - } - - if (fishingChallengeData == null) - { - if (CurFishingEventData == null) // 不存在Event - { - return; - } - fishingChallengeData = new FishingChallengeData(); - InitBaseData(); - InitChallengeData(); - } - - if (!IsInit) - { - // 设置比赛数据实体 - UpdateChallengeMainAndConfig(); - UpdateTimeData(); - UpdateLocalData(); - IsInit = true; - } - OnChallengeStatus();// 设置状态以及表现 - } - - public void ProcessLastChallenge() - { - UpdateTimeData(); - if (fishingChallengeData != null) - { - if (!IsTimeAllow()) - { - // 未完成 - if (fishingChallengeData.Finished == 0) - { - UpdateChallengeMainAndConfig(); - var status = ChallengeState(); - OnFinish(status); - } - ClearFishingChallengeData(); - } - } - } - private void OnChallengeStatus() - { - var status = ChallengeState(); - ELog($"OnChallengeStatus -> {status}"); - if (IsTimeAllow()) - { - if (status is 0 or 2) - { - // GContext.container.Resolve().AddFaceCustomUIData(UITypes.EventChallengeFacePopupPanel, true); - } - } - else - { - OnFinish(status); - } - } - - // 结束的时候调用 - // 倒计时结束最好也有个调用出发到这里 - private void OnFinish(int status) - { - ELog($"OnFinish ->{status}"); - if (status == 0) - { - ELog("未开始比赛 -- 不应该进入"); - } - else if (status == 1) - { - ELog($" RankTierLevel {fishingChallengeData.RankTierLevel} "); - var service = GContext.container.Resolve(); - ELog($"service -> {service}"); - var rewardList = GetRewardByScore(fishingChallengeData.ProcessedScore, fishingChallengeData.Score); - GContext.Publish(new DeferredRewardStashService.EventStashItems { Items = rewardList }); - } - else if (status == 2) - { - ELog($" RankTierLevel {fishingChallengeData.RankTierLevel} "); - // var rewardList = GetRewardByScore(fishingChallengeData.ProcessedScore,fishingChallengeData.Score); - // GContext.Publish(new DeferredRewardStashService.EventStashItems { Items = rewardList }); - } - ClearFishingChallengeData(); - } - // 0- 6 阶段奖励 - // 7 最终奖励 - // 获得未处理的道具 - private List GetRewardByScore(int processedScore, int score) - { - var playerItemData = GContext.container.Resolve(); - var listItemDatas = new List(); - var curIndex = GetStepByScore(processedScore, true); - var endIndex = GetStepByScore(score, true); - - var minEndIndex = Math.Min(endIndex, GetFullStep() - 1); - for (var i = curIndex; i < minEndIndex; ++i) - { - var itemDatas = - playerItemData.GetItemDataByDropIdLureInflation(fishingChallengeData.InflationRate, eventChallengeMain.StageReward[i]); - listItemDatas.AddRange(itemDatas); - } - ChangeSource changeSource = new ChangeSource(fishingChallengeData.EventId, "Event_Minigame4", "Event_Minigame4_Challenge", "StageReward"); - for (int i = 0; i < listItemDatas.Count; ++i) - { - listItemDatas[i].changeSource = changeSource; - } - - if (endIndex >= GetFullStep() - 1) - { - var index = fishingChallengeData.index; - var reward = eventChallengeMain.FinalReward.ElementAtOrDefault(index); - var datas = playerItemData.GetItemDataByDropIdLureInflation(fishingChallengeData.InflationRate, reward); - listItemDatas.AddRange(datas); - - ChangeSource changeSource1 = new ChangeSource(fishingChallengeData.EventId, "Event_Minigame4", "Event_Minigame4_Challenge", "GrandReward"); - for (int i = 0; i < datas.Count; ++i) - { - datas[i].changeSource = changeSource1; - } - } - ELog($"GetRewardByScore ->{processedScore} -> {score} {listItemDatas}"); - return listItemDatas; - } - - - // 剩余人数 - public int GetCurResidualNumber() - { - var newStep = fishingChallengeData.step; - return CalcResidualNumber(newStep); - } - - public int CalcResidualNumber(int step) - { - var eliminateNumber = fishingChallengeData.eliminateNumber; - var newEliminate = 0; - for (var i = step; i < eliminateNumber.Count; i++) - { - newEliminate += eliminateNumber[i]; - } - return newEliminate; - } - public void SetCurRank() - { - if (fishingChallengeData.Score == 0) - { - Rank = eventChallengeMain.RobotNumber + 1; - return; - } - // - var newStep = fishingChallengeData.step; - //剩余人数 - var eliminateNumber = fishingChallengeData.eliminateNumber; - var newEliminate = CalcResidualNumber(newStep + 1); - // newStep = Math.Min(newStep, eliminateNumber.Count - 1); - var newRank = newEliminate + UnityEngine.Random.Range(1, eliminateNumber[newStep]); - Rank = newRank < Rank ? newRank : Rank; - ELog($"SetCurRank -> {newStep} {Rank}"); - } - - public int GetMaxScoreByStep(int curStep) - { - var eliminateListScore = _eliminateListScore; - - if (curStep >= 0 && curStep < eliminateListScore.Count) - { - return eliminateListScore[curStep]; - } - ELog($"Error {curStep} : {eliminateListScore.Count}"); - return 0; - } - - public int GetFullStep() - { - var eliminateScore = eventChallengeMain.EliminateScore; - return eliminateScore.Count; - } - - public int GetNewStep() - { - var eliminateListScore = _eliminateListScore; - var newStep = eliminateListScore.Count; - var score = fishingChallengeData.Score; - for (int i = 0; i < eliminateListScore.Count; i++) - { - if (score < eliminateListScore[i]) - { - newStep = i; - break; - } - } - ELog($"GetNewStep() -> {newStep}"); - return newStep; - } - - public int GetBeginScore(int score, bool asNewLine) - { - int step = GetStepByScore(score, asNewLine); - return GetMaxScoreByStep(step - 1); - } - - public float GetFillAmount(int score, bool asNewLine) - { - int step = GetStepByScore(score, asNewLine); - if (step < eventChallengeMain.EliminateScore.Count) - { - int beginScore = GetBeginScore(score, asNewLine); - int diffScore = score - beginScore; - int newScore = eventChallengeMain.EliminateScore[step]; - newScore = GContext.container.Resolve().IntInflation(newScore, fishingChallengeData.InflationRate); - return (float)diffScore / newScore; - } - return 0f; - } - - public int GetStepByScore(int score, bool asNewLine) - { - var newStep = _eliminateListScore.Count; - for (int i = 0; i < _eliminateListScore.Count; i++) - { - if (asNewLine) - { - if (score < _eliminateListScore[i]) - { - newStep = i; - break; - } - } - else - { - if (score <= _eliminateListScore[i]) - { - newStep = i; - break; - } - } - - } - // ELog($"GetStepByScore() -> {newStep}"); - return newStep; - } - public void CheckAutoOpenPanel() - { - // if (!IsOpen) - // { - // return; - // } - var status = ChallengeState(); - if (status is 0 or 3) return; - // 异常状态,直接进入结算 - if ((status == 1 && !IsTimeAllow()) || status == 2) - { - InChallenge(); - } - } - - public async void InChallenge() - { - ELog("InChallenge()"); - - var challengeState = ChallengeState(); - if (challengeState == 0) - { - FishingChallengeAct.CloudType = 1; - } - else - { - FishingChallengeAct.CloudType = 0; - } - - var loadResourceService = GContext.container.Resolve(); - var isCanEnter = await loadResourceService.Load("FishingChallengeAct"); - if (isCanEnter) - { - ELog($"InChallenge() 开始挑战 -> {eventChallengeMain.ID}"); - GContext.Publish(new UnloadActToNextAct("FishingChallengeAct", transitionPanel: new UIType(eventChallengeConfig.MatchPanel))); - } - else - { - var panel = await UIManager.Instance.ShowUI(UITypes.CloudTransitionPanel); - panel.GetComponent().SetBtn(true, - () => GContext.Publish(new UnloadActToNextAct("FishingChallengeAct", - transitionPanel: new UIType(eventChallengeConfig.MatchPanel)))); - } - } - - /// - /// 刷新地图 - /// - /// - private void SetupNextLevelDataAndSave() - { - ELog("SetupNextLevelDataAndSave()"); - InitChallengeData(); - UpdateLocalData(); - MatchComplete(); - DoSave(); - } - - private void ZeroChallengeData() - { - fishingChallengeData.uiStep = 0; - fishingChallengeData.step = 0; - fishingChallengeData.Score = 0; - // fishingChallengeData.energy = 0; - fishingChallengeData.ProcessedScore = 0; - } - // 重置 data 数据 - private void InitChallengeData() - { - ELog("InitChallengeData() -> "); - ZeroChallengeData(); - // fishingChallengeData.mapId = GetRandomMap(); - } - - private void UpdateLocalData() - { - ELog("UpdateLocalData() -> "); - if (fishingChallengeData == null || eventChallengeConfig == null || eventChallengeMain == null) - return; - PreScore = fishingChallengeData.Score; // 记录积分 - PlayerFullNumber = eventChallengeMain.RobotNumber + 1; - PrefabName = eventChallengeConfig.ScenePanel; - // //-TODO: - // if (PrefabName == "ChallengeRoadScene") - // { - // PrefabName = "challenge_road"; - // } - - _stageDropList.Clear(); - Rank = eventChallengeMain.RobotNumber + 1; - } - - // 更新等级数据,确定开始 - private void UpdateLevelData(bool isSuccess) - { - if (isSuccess) - { - fishingChallengeData.RankTierLevel = eventChallengeMain.RankTier; - fishingChallengeData.Finished = fishingChallengeData.RankTierLevel <= TopRankTier ? 1 : 0; - } - } - - public void AddFlyEvent(float oldScore, float newScore) - { - GContext.Publish(new TargetAddData(eventChallengeConfig.Item, (int)oldScore, (int)newScore)); - } - public void AddScoreByQuality(int quality, float proficiencyExtra,int fishId) - { - ELog($"AddScoreByQuality -> {quality} {proficiencyExtra} {fishId}"); - - if (fishingChallengeData == null) - return; - // - var challengeState = ChallengeState(); - if (challengeState is 0 or 3) - { - return; - } - - if (!IsTimeAllow()) - return; - var extra = GContext.container.Resolve().GetMagnification(); - var qualityScore = GetQualityScoreWithExtra(quality, extra); - var oldScore = fishingChallengeData.Score; - if (qualityScore > 0) - { - fishingChallengeData.Score += qualityScore; - // fishingChallengeData.energy += extra; - ELog($"AddScoreByQuality -> {quality} {proficiencyExtra}, score:{qualityScore}"); - AddFlyEvent(oldScore, qualityScore); -#if AGG - using (var e = GEvent.GameEvent("event_challenge_getpoints")) - { - e.AddContent("event_id", fishingChallengeData.EventId) - .AddContent("tiler", eventChallengeMain?.ID) - .AddContent("stage_list", fishingChallengeData.step) - .AddContent("multiple", extra) - .AddContent("fish_id", fishId) - .AddContent("points", qualityScore); - - } -#endif - DoSave(); - } - } - -#if UNITY_EDITOR - private int _cheatingScore; - public void SetQualityScore(int cheatingScore) - { - _cheatingScore = cheatingScore; - } -#endif - private int GetQualityScoreWithExtra(int quality, float extra) - { -#if UNITY_EDITOR - if (_cheatingScore != 0) - { - return _cheatingScore; - } -#endif - return (int)(GetQualityScore(quality) * extra); - } - - public List GetFinalReward() - { - var playerItemData = GContext.container.Resolve(); - var itemList = playerItemData.GetItemDataByDropIdLureInflation(fishingChallengeData.InflationRate, eventChallengeMain.WinnerReward); - return itemList; - } - - public int GetQualityScore(int quality) - { - var pointsGet = eventChallengeConfig?.PointsGet; - if (pointsGet == null) - return 0; - if (quality > pointsGet.Count || quality < 1) // quality 在 1-5 之间有效, - return 0; - var qualityIndex = quality - 1; - ELog($"GetQualityScore({qualityIndex}, {pointsGet[qualityIndex]})"); - return (pointsGet[qualityIndex]); - } - - public ItemData GetStageRewardByStep(int step) - { - // - // ItemData itemData; - var playerItemData = GContext.container.Resolve(); - if (step >= 0 && step < GetFullStep() - 1) - { - var itemDatas = - playerItemData.GetItemDataByDropIdLureInflation(fishingChallengeData.InflationRate, eventChallengeMain.StageReward[step]); - return itemDatas.FirstOrDefault(); - } - - return null; - } - - public void AddStageReward(int stageIndex) - { - // stageIndex = newStep -1 == oldStep - ELog($"AddStageReward({stageIndex})"); - if (stageIndex >= 0 && stageIndex < GetFullStep() - 1) - { - _stageDropList.Add(eventChallengeMain.StageReward[stageIndex]); - _eventTrackStageList.Add(stageIndex + 1); - } - } - - public bool PlayGetStageReward() - { - ELog("PlayGetStageReward -> "); - var playerItemData = GContext.container.Resolve(); - if (_stageDropList.Count > 0) - { - ChangeSource changeSource = new ChangeSource(fishingChallengeData.EventId, "Event_Minigame4", "Event_Minigame4_Challenge", "StageReward"); - - playerItemData.AddItemByDropListLureInflation(fishingChallengeData.InflationRate, _stageDropList, changeSource); - GContext.Publish(new ShowData()); - _stageDropList.Clear(); - return true; - } - return false; - } - - - public void SetStep(int step) - { - fishingChallengeData.step = step; - DoSave(); - } - - public void SetUIStep(int step) - { - fishingChallengeData.uiStep = step; - DoSave(); - } - - public void SetProcessedScore(int score) - { - fishingChallengeData.ProcessedScore = score; - DoSave(); - } - /// - /// 当匹配完成的时候,开始倒计时 - /// - public void MatchComplete() - { - ELog("MatchComplete()"); - UpdateFishIndex(); - // 最后剩余人数 - var M = eventChallengeMain.FinalPlayer[fishingChallengeData.index]; - int Count = eventChallengeMain.EliminateScore.Count; - int first_number = UnityEngine.Random.Range(eventChallengeConfig.RandomSequenceConfig1[0], - eventChallengeConfig.RandomSequenceConfig1[1]); - - int residualNumber = eventChallengeMain.RobotNumber + 1 - first_number - M; - - int RandomSequence = eventChallengeConfig.RandomSequenceConfig2; - int a = 0; - for (int i = 0; i < RandomSequence; i++) - { - a += i + 1; - } - - residualNumber -= a; - //中间淘汰人数 - int eliminate; - List eliminateNumber = new List - { - first_number - }; - List weight = new List(); - for (int i = 0; i < RandomSequence; i++) - { - weight.Add(UnityEngine.Random.Range(residualNumber / Count, residualNumber)); - } - - float allWeight2 = weight.Sum(); - for (int i = 0; i < RandomSequence; i++) - { - eliminate = Mathf.FloorToInt((weight[i] / allWeight2) * residualNumber); - residualNumber -= eliminate; - eliminateNumber.Add(eliminate); - } - - // eliminateNumber.Add(residualNumber); - eliminateNumber.Sort((a, b) => b.CompareTo(a)); - for (var i = 0; i < RandomSequence; i++) - { - eliminateNumber[i + 1] += (RandomSequence - i); - } - - var leftNum = Count - 2 - RandomSequence; - while (leftNum-- > 0) - { - var num = UnityEngine.Random.Range(1, residualNumber); - eliminateNumber.Add(num); - residualNumber -= num; - } - - eliminateNumber.Add(residualNumber); - //最后剩余人数 放到淘汰列表 所有淘汰之后 最后一个 - eliminateNumber.Add(M); - fishingChallengeData.eliminateNumber = eliminateNumber; - fishingChallengeData.robotAccountList = new List(); - //随机机器人 - //随机位置 - var robotAccountList = new List(eventChallengeMain.RobotAccountList); - for (int i = 0; i < 100; i++) - { - if (robotAccountList.Count <= 0) - { - break; - } - - var index = UnityEngine.Random.Range(0, robotAccountList.Count); - fishingChallengeData.robotAccountList.Add(robotAccountList[index]); - robotAccountList.RemoveAt(index); - } - - ZeroChallengeData(); - PreScore = fishingChallengeData.Score; - Rank = eventChallengeMain.RobotNumber + 1; - } - - private void UpdateFishIndex() - { - var finalWeight = eventChallengeMain.FinalWeight; - var allWeight = finalWeight.Sum(); - var rand = UnityEngine.Random.Range(0, allWeight); - for (int i = 0; i < finalWeight.Count; i++) - { - rand -= finalWeight[i]; - if (rand < 0) - { - fishingChallengeData.index = i; - break; - } - } - } - - /// - /// 结算 - /// - public void OnSettle() - { - ELog("OnSettle()"); - itemDataList = null; - if (fishingChallengeData != null) - { - Log($"OnSettle() -> 结算 -> {fishingChallengeData.RankTierLevel}"); - SetCurRank(); - var playerItemData = GContext.container.Resolve(); - if (IsFinishCurLevel()) - { - //成功,瓜分奖励 - ChangeSource changeSource = new ChangeSource(fishingChallengeData.EventId, "Event_Minigame4", "Event_Minigame4_Challenge", "GrandReward"); - itemDataList = playerItemData.GetItemDataByDropIdLureInflation(fishingChallengeData.InflationRate, eventChallengeMain.FinalReward[fishingChallengeData.index]); - playerItemData.AddItem(itemDataList, changeSource); - UpdateLevelData(true); - } - else - { - ELog("失败了"); - UpdateLevelData(false); - } - GContext.Publish(new ConditionTypeEvent { type = ConditionType.CompleteChallengeCount, count = 1 }); - } - } - - /// - /// 全部结算处理逻辑的时候, - /// - public void OnSettleFinished(bool isSuccess) - { - ELog($"OnSettleFinished() -> {isSuccess}"); - if (!isSuccess) - { - fishingChallengeData = null; - DoSave(); - } - else - { - UpdateChallengeMainAndConfig(); - SetupNextLevelDataAndSave(); - } - - } - private static void Log(object t) - { - Debug.Log($"FishingChallengeManager -> {t} "); - } - - private static void ELog(string t) - { -#if UNITY_EDITOR - Debug.Log($"FishingChallengeManager -> {t} "); -#endif - } - - public void EventTracking() - { - // _eventTrackNormalRewardList = _stageDropList.ToList(); - - var tier = eventChallengeMain?.RankTier ?? -1; - var stageList = _eventTrackStageList; - var maxStage = fishingChallengeData.step; - var normalRewardList = _stageDropList.ToList(); ; - var combineId = (6 - tier) * 100 + maxStage; -#if AGG - using (var e = GEvent.TackEvent("event_challenge")) - { - e.AddContent("tier", tier); - e.AddContent("stage_list", string.Join(",", stageList)); - e.AddContent("max_stage", maxStage); - e.AddContent("normal_reward_list", string.Join(',', normalRewardList)); - if (IsFinishCurLevel()) - { - var finalRewardList = eventChallengeMain?.FinalReward? - .ElementAtOrDefault(fishingChallengeData?.index ?? -1) ?? -1; - var finalPlayer = eventChallengeMain?.FinalPlayer? - .ElementAtOrDefault(fishingChallengeData?.index ?? -1) ?? -1; - e.AddContent("final_reward_list", string.Join(',', finalRewardList)); - e.AddContent("final_player", finalPlayer); - } - e.AddContent("combine_id", combineId); - } -#endif - var sb = new StringBuilder(); - sb.Append($"tier: {tier},") - .Append($"max_stage: {maxStage}") - .Append($"stage_list: {string.Join(',', stageList)}") - .Append($"normal_reward_list:{string.Join(',', normalRewardList)}") - .Append($"combine_id: {combineId}"); - - if (IsFinishCurLevel()) - { - var finalRewardList = eventChallengeMain?.FinalReward? - .ElementAtOrDefault(fishingChallengeData?.index ?? -1) ?? -1; - var finalPlayer = eventChallengeMain?.FinalPlayer? - .ElementAtOrDefault(fishingChallengeData?.index ?? -1) ?? -1; - sb.Append($"final_reward_list:{string.Join(',', finalRewardList)}"); - sb.Append($"finalPlayer:{finalPlayer}"); - } - - ELog($"EventTracking: -> {sb}"); - _eventTrackStageList.Clear(); - // _eventTrackNormalRewardList.Clear(); - - } - private void UpdateTimeData() - { - if (CurFishingEventData == null) - { - if (fishingChallengeData != null) - { - fishingChallengeData.StartTime = ZZTimeHelper.UtcNow(); - fishingChallengeData.EndTime = ZZTimeHelper.UtcNow().AddDays(-1); - } - } - else - { - var limitedTime = (LimitedTime)CurFishingEventData.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow().AddDays(-1)); - StartTime = startTime; - EndTime = endTime; - if (fishingChallengeData != null) - { - fishingChallengeData.StartTime = startTime; - fishingChallengeData.EndTime = endTime; - } - } - } - // 获取当前可用的数值,以及初始化 - private void UpdateChallengeMainAndConfig() - { - ELog("UpdateChallengeMainAndConfig()"); - - var redirectId = fishingChallengeData.RedirectID; - // 未满足的情况 - // 选择当前 Config - var configList = _tables.TbEventChallengeConfig.DataList; - foreach (var eventChallenge in configList.Where(eventChallenge => eventChallenge.ID == redirectId)) - { - eventChallengeConfig = eventChallenge; - break; - } - // 选择当前的 Main - var challengeMatchMains = _tables.TbEventChallengeMain.DataList; - var rankTierLevel = fishingChallengeData.RankTierLevel; - eventChallengeMain = challengeMatchMains.LastOrDefault(); - for (var i = challengeMatchMains.Count - 1; i >= 0; i--) - { - if (rankTierLevel > challengeMatchMains[i].RankTier) - { - eventChallengeMain = challengeMatchMains[i]; - break; - } - } - UpdateEliminateListScore(); - } - - // - private readonly List _eliminateListScore = new(); - public void UpdateEliminateListScore() - { - _eliminateListScore.Clear(); - var orElmScore = eventChallengeMain.EliminateScore; - var elem = 0; - PlayerItemData playerItemData = GContext.container.Resolve(); - foreach (var i in orElmScore) - { - elem += playerItemData.IntInflation(i, fishingChallengeData.InflationRate); - _eliminateListScore.Add(elem); - } - // Log(_eliminateListScore); - } - - public List GetEliminateListScore() - { - return _eliminateListScore; - } - - public List GetOriEliminateListScore() - { - return eventChallengeMain.EliminateScore; - } - /// - /// 当前钓鱼争霸赛的状态,进入此函数认为已经确认过时间 - /// - /// 0,未开始匹配 1,开始中 2,当前轮已经结算 3.关卡清空 - public int ChallengeState() - { - // Log("ChallengeState"); - - int state; - // 未开始|未到开始时间 - if (fishingChallengeData == null) - { - state = 0; - } - else - { - if (IsClearAllLevel()) - { - state = 3; - } - else if (fishingChallengeData.eliminateNumber == null || fishingChallengeData.robotAccountList == null) - { - state = 0; - } - // 未完成当前轮 - else if (!IsFinishCurLevel()) - { - state = 1; - } - else - { - state = 2; - } - } - ELog($"ChallengeState() -> {state}"); - return state; - } - - public bool IsSettleState() - { - var status = ChallengeState(); - // 超时或者结束,都进入结算 - return (status == 1 && !IsTimeAllow()) || status == 2; - } - /// - /// 获取倒计时,距离截至时间 - /// - /// - public TimeSpan GetTimeSpan() - { - if (fishingChallengeData != null) - { - return fishingChallengeData.EndTime - ZZTimeHelper.UtcNow(); - } - // 活动未开始 - return EndTime - ZZTimeHelper.UtcNow(); - } - - private void DoSave() - { - SaveStore.Write(SaveKey, JsonConvert.SerializeObject(fishingChallengeData)).RequireAccepted(); - } - - public string GetOpenEventKey() - { - if (fishingChallengeData != null) - { - return fishingChallengeData?.EventId + "_LL_FIRST_OPEN"; - } - return ""; - } - - public bool IfHasReward() - { - var step = fishingChallengeData.step; - var newStep = GetStepByScore(fishingChallengeData.Score, true); - return step != newStep; - } - - public void OnChallengeSceneEnter() - { - _stageDropList.Clear(); - _eventTrackStageList = new(); - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/023-FishingEventData_OneOne.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/023-FishingEventData_OneOne.cs.txt deleted file mode 100644 index 9070bd98c..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/023-FishingEventData_OneOne.cs.txt +++ /dev/null @@ -1,84 +0,0 @@ -using asap.core; -using cfg; -using LitJson; -using System; -namespace GameCore -{ - public partial class FishingEventData - { - string Pack1A1DataKey = "Pack1A1Data"; - public TriggerPackBuyData Pack1A1Data; - void GiftFace1A1(int packType, int eventID) - { - if (Pack1A1Data == null || Pack1A1Data.index < 2 || Pack1A1Data.lastID != eventID) - { - GContext.container.Resolve().AddGiftFaceUI(eventID, UITypes.GiftPopupPanel_10, packType); - } - } - public void SetPack1A1(FishingEvent t) - { - if (Pack1A1Data == null) - { - Pack1A1Data = ReadEventArchive(Pack1A1DataKey); - } - EventPackManager eventPackDataRead = _tables.TbEventPackManager.DataMap[t.RedirectID]; - GiftFace1A1(eventPackDataRead.PackType, t.ID); - if (Pack1A1Data != null && Pack1A1Data.lastID == t.ID) - { - return; - } - - Pack1A1Data = new TriggerPackBuyData() - { - ID = eventPackDataRead.ID, - lastID = t.ID,//活动id - index = 0, - vipLevel = GContext.container.Resolve().PriceLv, - mapID = GContext.container.Resolve().lastMapId, - }; - RedPointManager.Instance.SetRedPointState(HomeBtnOneOnePack.redKey, false); - - playerSaveStore.Write(Pack1A1DataKey, JsonMapper.ToJson(Pack1A1Data)).RequireAccepted(); - } - public void SetPack1A1Index(int index) - { - if (Pack1A1Data == null || index < Pack1A1Data.index) - { - return; - } - - Pack1A1Data.index = index; - if (Pack1A1Data.index >= 2) - { - //购买完 特殊处理 - GContext.Publish(new TargetEvent(Pack1A1Data.lastID, 3, 11)); - } - RedPointManager.Instance.SetRedPointState(HomeBtnOneOnePack.redKey, Pack1A1Data.index == 1); - playerSaveStore.Write(Pack1A1DataKey, JsonMapper.ToJson(Pack1A1Data)).RequireAccepted(); - } - public int GetPack1A1Index() - { - if (Pack1A1Data == null) - { - return 100; - } - return Pack1A1Data.index; - } - public EventPackManager Get1A1EventPackManager() - { - if (Pack1A1Data == null) - { - return null; - } - return _tables.TbEventPackManager.DataMap[Pack1A1Data.ID]; - } - public DateTime GetEvent1A1EndTime() - { - if (Pack1A1Data == null) - { - return ZZTimeHelper.UtcNow().UtcNowOffset(); - } - return GetEventEndTime(Pack1A1Data.lastID); - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/024-FishingEventData_OneTwo.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/024-FishingEventData_OneTwo.cs.txt deleted file mode 100644 index 1b5901848..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/024-FishingEventData_OneTwo.cs.txt +++ /dev/null @@ -1,165 +0,0 @@ -using asap.core; -using cfg; -using LitJson; -using System; -using System.Collections.Generic; -namespace GameCore -{ - public class Pack1A2Data - { - public Pack1A2Data(int ID, - //活动id - int eventId, - int vipLevel) - { - this.ID = ID; - this.lastID = eventId; - this.index = 0; - this.vipLevel = vipLevel; - } - public int ID; - //领取第几个 - public int index; - public int lastID; - //触发当时VIP等级 - public int vipLevel; - public int rodDstId; - public int rodSrcId; - } - public partial class FishingEventData - { - string Pack1A2DataKey = "Pack1A2Data"; - public Pack1A2Data Pack1A2Data; - void GiftFace1A2(EventPackManager packManager, int eventID) - { - if (Pack1A2Data == null) - { - GContext.container.Resolve().AddGiftFaceUI(eventID, UITypes.GiftPopupPanel_11, packManager.PackType); - } - else - { - List packIDs = packManager.VIPPackList[Pack1A2Data.vipLevel]; - if (Pack1A2Data.lastID != eventID || packIDs.Count > Pack1A2Data.index) - { - GContext.container.Resolve().AddGiftFaceUI(eventID, UITypes.GiftPopupPanel_11, packManager.PackType); - } - - } - } - public void SetPack1A2(FishingEvent t) - { - if (Pack1A2Data == null) - { - Pack1A2Data = ReadEventArchive(Pack1A2DataKey); - } - EventPackManager eventPackDataRead = _tables.TbEventPackManager.DataMap[t.RedirectID]; - - GiftFace1A2(eventPackDataRead, t.ID); - if (Pack1A2Data != null && Pack1A2Data.lastID == t.ID) - { - SetType(); - SetChainPackRed(); - return; - } - - Pack1A2Data = new Pack1A2Data( - eventPackDataRead.ID, - t.ID,//活动id - GContext.container.Resolve().PriceLv - ); - SetType(); - SetRodDstId(); - SetChainPackRed(); - playerSaveStore.Write(Pack1A2DataKey, JsonMapper.ToJson(Pack1A2Data)).RequireAccepted(); - } - void SetType() - { - EventPackManager eventPackManager = Get1A2EventPackManager(); - if (eventPackManager != null) - { - UITypes.GiftPopupPanel_11.SetType(eventPackManager.Panel); - } - } - void SetRodDstId() - { - Pack1A2Data.rodSrcId = 330040000; - Item item = _tables.TbItem.GetOrDefault(Pack1A2Data.rodSrcId); - Drop drop = _tables.TbDrop.GetOrDefault(item.RedirectID); - List rodIDs = drop.DropList.DropIDList; - int level = -1; - PlayerFishData playerFishData = GContext.container.Resolve(); - for (int i = 0; i < rodIDs.Count; i++) - { - int curLevel = playerFishData.GetRodLevel(rodIDs[i]); - if (curLevel > level) - { - level = curLevel; - Pack1A2Data.rodDstId = rodIDs[i]; - } - } - } - public void SetPack1A2Index() - { - if (Pack1A2Data == null) - { - return; - } - Pack1A2Data.index++; - playerSaveStore.Write(Pack1A2DataKey, JsonMapper.ToJson(Pack1A2Data)).RequireAccepted(); - SetChainPackRed(); - } - void SetChainPackRed() - { - bool isRed = false; - EventPackManager eventPackManager = Get1A2EventPackManager(); - List packIDs = eventPackManager.VIPPackList[Pack1A2Data.vipLevel]; - if (packIDs.Count > Pack1A2Data.index) - { - var pack = _tables.TbPack.GetOrDefault(packIDs[Pack1A2Data.index]); - isRed = _tables.TbIAPItemList.GetOrDefault(pack.IAPID) == null; - } - else - { - //购买完 特殊处理 - GContext.Publish(new TargetEvent(Pack1A2Data.lastID, 6, 1)); - } - RedPointManager.Instance.SetRedPointState(HomeBtnOneTwoPack.redKey, isRed); - } - public int GetPack1A2Index() - { - if (Pack1A2Data == null) - { - return 100; - } - return Pack1A2Data.index; - } - public EventPackManager Get1A2EventPackManager() - { - if (Pack1A2Data == null) - { - return null; - } - return _tables.TbEventPackManager.DataMap[Pack1A2Data.ID]; - } - public DateTime GetEvent1A2EndTime() - { - if (Pack1A2Data == null) - { - return ZZTimeHelper.UtcNow().UtcNowOffset(); ; - } - return GetEventEndTime(Pack1A2Data.lastID); - } - public List Get1A2ItemDatasBuyPack(int dropID) - { - List itemDatas = GContext.container.Resolve().GetItemDataByDropIdLureInflation(null, dropID); - for (int i = 0; i < itemDatas.Count; i++) - { - if (itemDatas[i].id == Pack1A2Data.rodSrcId) - { - itemDatas[i].id = Pack1A2Data.rodDstId; - } - } - return itemDatas; - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/025-FishingEvent_PVPData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/025-FishingEvent_PVPData.cs.txt deleted file mode 100644 index 2c5994b5d..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/025-FishingEvent_PVPData.cs.txt +++ /dev/null @@ -1,282 +0,0 @@ -using asap.core; -using cfg; -using System; -using System.Collections.Generic; -using UnityEngine; -namespace GameCore -{ - public partial class FishingEventData : IDisposable - { - // void GetTransitionDataPVP(int subType = 0) - // { - // FishingEvent fishingEvent = null; - // if (transitionDataDic != null) - // { - // foreach (var item in transitionDataDic) - // { - // FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(item.Key); - // if (fe != null && (subType == fe.SubType || subType == 0) && fe.Type == 5 && !Condition(fe)) - // { - // fishingEvent = fe; - // int count = transitionDataDic[fishingEvent.ID]; - // if (count > 0) - // { - // PvpEventCycleItem cycle = _tables.TbPvpEventCycleItem. - // DataList.Find(x => x.Type == fe.Type && x.SubType == fe.SubType); - // if (cycle != null) - // { - // SetTransitionData(fishingEvent.ID, cycle.EventName_l10n_key, cycle.ItemId, cycle.EventEndSettlement); - // } - // } - // else - // { - // transitionDataDic.Remove(fishingEvent.ID); - // SaveTransitionData(); - // } - // break; - // } - // } - // } - // } - public int GetInitWelcomeGiftPVP(int eventID) - { - int welcomeGift = 0; - if (eventID > 0) - { - FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(eventID); - if (fe != null) - { - PvpEventCycleItem cycle = _tables.TbPvpEventCycleItem. - DataList.Find(x => x.Type == fe.Type && x.SubType == fe.SubType); - if (cycle != null) - { - welcomeGift = cycle.WelcomeGift; - } - } - } - return welcomeGift; - } - public int GetRedDotPVP(int eventID) - { - int redDot = 10; - if (eventID > 0) - { - FishingEvent fe = _tables.TbFishingEvent.GetOrDefault(eventID); - if (fe != null) - { - PvpEventCycleItem cycle = _tables.TbPvpEventCycleItem. - DataList.Find(x => x.Type == fe.Type && x.SubType == fe.SubType); - if (cycle != null) - { - redDot = cycle.RedDot; - } - } - } - return redDot; - } - #region SoloData - public DuelData duelData { get; private set; } - int rankTierChangeState = 0; - EventSolomain curSolomain; - public int PVPToken { private set; get; }//pvp商店代币 - - public void SetRankTierChange(EventSolomain beforeSolomain, EventSolomain eventSolomain) - { - rankTierChangeState = beforeSolomain.RankTier > eventSolomain.RankTier ? 1 : 2; - this.curSolomain = beforeSolomain; - } - public async void ShowRankTierChange() - { - var store = playerSaveStore; - if (!store.IsCurrent) return; - if (rankTierChangeState > 0 && curSolomain != null) - { - GameObject go = await UIManager.Instance.ShowUI(UITypes.EventFishingDuelRankChangePopupPanel); - if (!store.IsCurrent) return; - EventFishingDuelRankChangePopupPanel changePopupPanel = go.GetComponent(); - changePopupPanel.SetRank(rankTierChangeState == 1, curSolomain); - rankTierChangeState = 0; - curSolomain = null; - } - } - public void SoloCheckClaimReward() - { - var loaded = ReadEventArchive(FishingDuelManager.SoloDataKey); - if (loaded != null) - { - duelData = loaded; - int fishingEventID = GContext.container.Resolve().GetEvent(5, 1); - if (duelData.rewardEventID > 0 && duelData.preProgress > 0 && duelData.rewardEventID != fishingEventID) - { - GContext.container.Resolve().AddFaceCustomUIData(UITypes.EventFishingDuelSettlementPanel, true); - //_ = UIManager.Instance.ShowUI(UITypes.EventFishingDuelSettlementPanel); - } - //GetTransitionDataPVP(1); - } - } - //领取赛季奖励 - public void ClaimReward() - { - if (duelData.rewardEventID > 0 && duelData.preProgress > 0) - { - duelData.soloTimes = 0; - duelData.rewardEventID = 0; - duelData.preProgress = 0; - string json_duelData = Newtonsoft.Json.JsonConvert.SerializeObject(duelData); - playerSaveStore.Write(FishingDuelManager.SoloDataKey, json_duelData).RequireAccepted(); - } - } - public void GMAddSoloProgress(int count) - { - if (duelData != null) - { - duelData.progress = count; - SaveDuelData(); - } - } - public void InitSoloData(FishingEvent t) - { - var loaded = ReadEventArchive(FishingDuelManager.SoloDataKey); - if (loaded != null) - { - duelData = loaded; - } - else - { - duelData = new DuelData(); - duelData.progress = _tables.TbEventSoloConfig.InitTrophy; - } - - if (t.ID != duelData.eventID) - { - duelData.eventID = t.ID; - int min = GetInitWelcomeGiftPVP(t.ID); - if (duelData.tickets < min) - { - duelData.tickets = min; - } - duelData.soloTimes = 0; - duelData.rePVPToken = 0; - duelData.buyItem.Clear(); - int reset = duelData.progress - _tables.TbEventSoloConfig.MinTrophy; - if (reset > 0) - { - //duelData.progress = _tables.TbEventSoloConfig.SettlementTrophy + - // (int)(reset * _tables.TbEventSoloConfig.SettlementTrophyMultiplier); - - var data = _tables.TbEventSolomain.DataList; - var solomain = data[0]; - if (duelData.progress > 0) - { - for (int i = data.Count - 1; i >= 0; i--) - { - if (duelData.progress >= data[i].TrophyRange[0]) - { - solomain = data[i]; - break; - } - } - } - duelData.progress -= solomain.SettleDeducTrophy; - } - //duelData.progress /= _tables.TbEventSoloConfig.TrophyMutiple; - //duelData.progress *= _tables.TbEventSoloConfig.TrophyMutiple; - if (duelData.progress < _tables.TbEventSoloConfig.MinTrophy) - { - duelData.progress = _tables.TbEventSoloConfig.MinTrophy; - } - //GContext.Publish(new TargetEvent(t.ID, 5, 1)); - SaveDuelData(); - } - } - public void AddDuelTickets(int tickets) - { - if (duelData != null) - { - if (tickets < 0) - { - duelData.soloTimes++; - if (duelData.soloTimes >= _tables.TbEventSoloConfig.ClaimRewardMatchCount) - { - duelData.rewardEventID = duelData.eventID; - duelData.preProgress = duelData.progress; - } - } - duelData.tickets += tickets; - //SaveTransitionData(duelData.eventID, duelData.tickets); - SaveDuelData(); - } - } - public int GetDuelTickets() - { - if (duelData != null) - { - return duelData.tickets; - } - return 0; - } - - public bool BuyPVPItem(int id) - { - if (duelData != null && !duelData.buyItem.ContainsKey(id)) - { - duelData.buyItem[id] = 1; - SaveDuelData(); - return true; - } - return false; - } - public bool IsBuyPVPItem(int id) - { - if (duelData != null && duelData.buyItem.ContainsKey(id)) - { - return true; - } - return false; - } - - public DateTime SetPVPShopTime() - { - DateTime dateTime = ZZTimeHelper.UtcNow().UtcNowOffset().Date; - int offfset = (int)dateTime.DayOfWeek - 1; - - if (offfset < 0) - { - offfset = -offfset; - } - else - { - offfset = 7 - offfset; - } - DateTime endTime = dateTime.AddDays(offfset); - if (endTime.DayOfYear != duelData.pvpShopTimeDay) - { - if (duelData.pvpShopTimeDay != -1) - { - duelData.buyItem.Clear(); - } - duelData.inflation = GContext.container.Resolve().InflationRate; - duelData.pvpShopTimeDay = endTime.DayOfYear; - SaveDuelData(); - } - return endTime; - } - - public void AddPVPToken(int value) - { - PVPToken += value; - playerSaveStore.Write("PVPToken", PVPToken.ToString()).RequireAccepted(); - if (value < 0 && duelData != null) - { - duelData.rePVPToken -= value; - SaveDuelData(); - } - } - public void SaveDuelData() - { - string json_duelData = Newtonsoft.Json.JsonConvert.SerializeObject(duelData); - playerSaveStore.Write(FishingDuelManager.SoloDataKey, json_duelData).RequireAccepted(); - } - #endregion SoloData - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/026-OfferChainsChestManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/026-OfferChainsChestManager.cs.txt deleted file mode 100644 index e21d41220..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/026-OfferChainsChestManager.cs.txt +++ /dev/null @@ -1,573 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using asap.core; -using cfg; -using game; -using GameCore; -using Newtonsoft.Json; -using UnityEngine; - -namespace DataCenter -{ - // 锁链礼包 - - public class TOfferChainsData - { - public class TItem - { - public int Id; - public int Item; - public int Number; - // 0 可选,1 高亮 2 糊了 ,锁链隐藏 应该转换成Enum - public int Status; - // public int SKUId; - } - public bool FirstOpen; // 是否首次打开 - public int EventId; // 默认存一下ID - public DateTime StartTime; // 开始时间 - public DateTime EndTime;// 结束时间 - public int ItemId = -1; - // 当前抽奖次数,必须抽了才会更新 - public int LotteryNum; - public List Items; - public bool Finished; - public int ChestReward; - public List RewardList; // 当前获得的奖励Item - - - } - - public class OfferChainsChestManager - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - - public const string SaveKey = "OfferChainsChestData"; - [Inject] public Tables _tables { get; set; } - // 计入当前Event - private FishingEvent _fishingEvent; - // - public EventOfferChainsChestMain OfferChainsChestMain { get; set; } - public List OfferChainsChestRewards { get; set; } - // 当前可保存数据 - public TOfferChainsData OfferChainsData { get; private set; } - - internal static game.PlayerDataStorage.PlayerKVOfferState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeOffer(raw,false,snapshot,errors); - internal void ResetForKVLoad() - { - OfferChainsData=null; ValidIds=new List(); _fishingEvent=null; _isInit=false; - OfferChainsChestMain=null; OfferChainsChestRewards=null; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVOfferState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - OfferChainsData=!state.IsPresent ? null : new TOfferChainsData - { - FirstOpen=state.FirstOpen,EventId=state.EventId,StartTime=state.StartTime,EndTime=state.EndTime, - ItemId=state.ItemId,LotteryNum=state.LotteryNum, - Items=state.Items.Select(item=>new TOfferChainsData.TItem { - Id=item.Id,Item=item.Item,Number=item.Number,Status=item.Status }).ToList(), - RewardList=new List(state.RewardList),Finished=state.Finished,ChestReward=state.ChestReward - }; - } - internal bool IsInactiveForKVValidation => !_isInit && _fishingEvent == null; - public List ValidIds; - - public bool IsFirstOpen - { - get => OfferChainsData.FirstOpen; - set - { - if (OfferChainsData.FirstOpen) - { - OfferChainsData.FirstOpen = false; - SaveData(); - } - } - } - public void UpdateEventData(FishingEvent fishingEvent) - { - ELog($"UpdateEventData - > {fishingEvent}"); - _fishingEvent = fishingEvent; - UpdateLocalData(); - } - private void UpdateLocalData() - { - //选择当前的 Main - var redirectId = _fishingEvent.RedirectID; - var configList = _tables.TbEventOfferChainsChestMain.DataList; - foreach (var eventChallenge in configList.Where(eventChallenge => eventChallenge.ID == redirectId)) - { - OfferChainsChestMain = eventChallenge; - break; - } - OfferChainsChestRewards = _tables.TbEventOfferChainsChestRewards.DataList; - // SkuIds = OfferChainsChestMain.IapList; - - - - } - - private bool _isInit = false; - - public void Init() - { - ELog("Init-> "); - - if (_fishingEvent == null) - return; - //- - if (_fishingEvent.ID != OfferChainsData?.EventId) - { - ClearOfferChainsData(); - } - - if (_isInit) - return; - - if (OfferChainsData == null) - { - if (_fishingEvent == null) // 不存在Event - { - return; - } - InitOfferChainsData(); - // CreateNewData(); - } - UpdateOfferChainsData(); - //UpdateData() - _isInit = true; - ELog("初始化完成-> "); - } - // - private void ProcessLastOne() - { - ELog("ProcessLastOne-> "); - if (OfferChainsData != null) - { - Settle(); - // if (!IsTimeAllow()) - // { - // Settle(); - // // ClearOfferChainsData(); - // } - // // else if (IsCanGetFinalReward()) - // else - // { - // Settle(); // 补充一下最终大奖 - // } - } - } - - private void UpdateOfferChainsData() - { - ELog("UpdateOfferChainsData"); - // 更新可用数据 - UpdateTime(); - UpdateOfferChainsItems(); - UpdateValidIds(); - GetLotteryItemId(); - //- - if (_fishingEvent != null && OfferChainsData != null) - { - GContext.container.Resolve().AddGiftFaceUI(_fishingEvent.ID, new UIType(OfferChainsChestMain.UIPanel), 0); - } - } - - private void UpdateValidIds() - { - var lotteryNum = OfferChainsData.LotteryNum; - ValidIds = (from item in OfferChainsData?.Items where item.Status == 0 select item.Id).ToList(); - } - - - private void InitOfferChainsData() - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - - - OfferChainsData = new TOfferChainsData - { - FirstOpen = true, - EventId = _fishingEvent.ID, - StartTime = startTime, - EndTime = endTime, - Items = new List(), - RewardList = new List(), - ChestReward = OfferChainsChestMain.ChestReward, // 最终大奖存储下,方便额外的处理 - }; - - for (var i = 0; i < OfferChainsChestRewards.Count; ++i) - { - var item = new TOfferChainsData.TItem - { - Id = OfferChainsChestRewards[i].ID, - Item = OfferChainsChestRewards[i].Item, - Number = OfferChainsChestRewards[i].Number, - Status = 0, - // SKUId = OfferChainsChestMain.IapList[i], - }; - OfferChainsData.Items.Add(item); - } - - } - - public bool IsTimeAllow() - { - var now = ZZTimeHelper.UtcNow(); - - var startTime = OfferChainsData.StartTime; - var endTime = OfferChainsData.EndTime; -#if UNITY_EDITOR - var timeOpened = (now - startTime).TotalSeconds; - var timeEnded = (endTime - now).TotalSeconds; - ELog($"StartTime: {startTime} Now: {now} EndTime:{endTime} TimeOpened:{timeOpened} TimeToEnd:{timeEnded} Other: {1800000 - timeOpened} IsTimeAllow => {now <= endTime}"); -#endif - return now >= startTime && now <= endTime; - } - public void CheckInit() - { - ELog("CheckInit -> "); - - ProcessLastOne(); - Init(); - } - - // ReSharper disable Unity.PerformanceAnalysis - private static void Log(object t) - { - Debug.Log($"OfferChainsChestManager -> {t} "); - } - - private static void ELog(object t) - { -#if UNITY_EDITOR - Debug.Log($"OfferChainsChestManager -> {t} "); -#endif - } - - public bool CheckOpen() - { - // - if (OfferChainsData == null) return false; - // - if (!IsTimeAllow()) return false; - - if (OfferChainsChestMain == null) - { - return false; - } - - if (IsFinished()) - { - return false; - } - return true; - } - - public bool IsFinished() - { - return OfferChainsData?.Finished ?? false; - } - - private void SaveData() - { - ELog($"SaveData-> {JsonConvert.SerializeObject(OfferChainsData)}"); - playerSaveStore.Write(SaveKey, JsonConvert.SerializeObject(OfferChainsData)).RequireAccepted(); - } - - public void LoadData(string dataValue) - { - ELog($"LoadData -> {dataValue}"); - OfferChainsData = JsonConvert.DeserializeObject(dataValue); - } - - // 进入游戏舞台 - public async void OnEnterGameAct() - { - if (!playerSaveStore.IsCurrent) return; - Log("OnEnterGameAct()"); - IsFirstOpen = false; - await UIManager.Instance.ShowUI(new UIType(OfferChainsChestMain.UIPanel)); - } - - public static T WeightedRandom(Dictionary weightTable) - { - // 1. 计算总权重 - var totalWeight = weightTable.Values.Sum(); - // 2. 生成随机数 - var randomValue = UnityEngine.Random.Range(0, totalWeight); - - // 3. 线性遍历选择 - var currentWeight = 0; - foreach (var (key, value) in weightTable) - { - currentWeight += value; - if (randomValue < currentWeight) - return key; - } - return default; // 理论上不会执行到这里 - } - - // 活动当前的抽奖索引 - private int CalcLotteryItemId() - { - var lotteryNum = OfferChainsData.LotteryNum; - if (ValidIds.Count <= 0) - { - return -1; - } - if (OfferChainsChestRewards == null) - { - return -1; - } - - // - - // while (true) - // { - var dict = OfferChainsChestRewards.Where( - item => ValidIds.Contains(item.ID) && item.LimitConfig <= lotteryNum) - .ToDictionary(elem => (elem.ID, elem.LimitConfig), elem => elem.Weight); - var (elemId, limitConfig) = WeightedRandom(dict); - Log($"CalcLotteryItemId -> {lotteryNum} {elemId} {limitConfig}"); - // if (limitConfig >0 && lotteryNum > limitConfig ) - return elemId; - // } - } - - - public int GetLotteryItemId() - { - ELog($"GetLotteryItemId -> {OfferChainsData.ItemId}"); - if (OfferChainsData.ItemId == -1 || !ValidIds.Contains(OfferChainsData.ItemId)) - { - UpdateLotteryItemId(); - } - return OfferChainsData.ItemId; - } - - private void UpdateOfferChainsItems() - { - if (OfferChainsData != null && _fishingEvent != null && OfferChainsData.EventId == _fishingEvent.ID) - { - var items = OfferChainsData.Items; - if (OfferChainsChestRewards is { Count: > 0 }) - { - for (int i = 0; i < items.Count; ++i) - { - EventOfferChainsChestRewards reward = null; - if (i < OfferChainsChestRewards.Count) - { - reward = OfferChainsChestRewards[i]; - } - if (reward != null) - { - items[i].Id = reward.ID; - items[i].Item = reward.Item; - items[i].Number = reward.Number; - } - } - } - - if (OfferChainsChestMain != null) - { - OfferChainsData.ChestReward = OfferChainsChestMain.ChestReward; - } - } - - // for (var i = 0; i < OfferChainsChestRewards.Count; ++i) - // { - // var item = new TOfferChainsData.TItem - // { - // Id = OfferChainsChestRewards[i].ID, - // Item = OfferChainsChestRewards[i].Item, - // Number = OfferChainsChestRewards[i].Number, - // Status = 0, - // }; - // OfferChainsData.Items.Add(item); - // } - } - - private void UpdateTime() - { - if (OfferChainsData != null && _fishingEvent != null && OfferChainsData.EventId == _fishingEvent.ID) - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow().AddDays(-1)); - OfferChainsData.StartTime = startTime; - OfferChainsData.EndTime = endTime; - } - } - - private void UpdateLotteryItemId() - { - var targetId = CalcLotteryItemId(); - ELog($"UpdateLotteryItemId -> {OfferChainsData.ItemId} => {targetId}"); - OfferChainsData.ItemId = targetId; - SaveData(); - } - - //- 结束当前 - public void FinishLottery(int targetId) - { - Log($"FinishLottery -> {targetId}"); - var lastItem = OfferChainsData.Items.SingleOrDefault(it => it.Id == targetId); - if (lastItem is { Status: not 2 }) - { - lastItem.Status = 2; - } - } - - //- 开始下一轮数据 - public void UpdateForNextLottery() - { - UpdateValidIds(); - UpdateLotteryItemId(); - } - - public bool IsCanGetFinalReward() - { - var ret = OfferChainsData.LotteryNum >= OfferChainsData.Items.Count - && !OfferChainsData.Finished; - - ELog($"IsCanGetFinalReward {ret} : {OfferChainsData.LotteryNum} {OfferChainsData.Items.Count} {OfferChainsData.Finished}"); - return ret; - } - - public void ClearOfferChainsData() - { - OfferChainsData = null; - _isInit = false; - SaveData(); - } - - public TOfferChainsData.TItem GetTItemById(int targetId) - { - var lastItem = OfferChainsData.Items.FirstOrDefault(it => it.Id == targetId); - return lastItem; - } - - public int GetDropIdById(int id) - { - var item = GetTItemById(id); - var itemData = _tables.TbItem.GetOrDefault(item.Item); - return itemData.RedirectID; - } - public void OnGetFinalReward() - { - ELog("OnGetFinalReward()-> "); - - // var item = _tables.TbItem.GetOrDefault(OfferChainsChestMain.ChestReward); - var item = _tables.TbItem.GetOrDefault(OfferChainsData.ChestReward); - var itemFinal = GContext.container.Resolve() - .GetItemDropItemList(item.RedirectID, 1); - GContext.container.Resolve().LureInflation(itemFinal, null); - GContext.container.Resolve().AddItem(itemFinal, null); - GContext.Publish(new ShowData(itemFinal)); - GContext.Publish(new ShowData()); - OfferChainsData.Finished = true; - SaveData(); - GContext.Publish(new OfferChainsRefreshEvent()); - } - public float GetProbability(int id) - { - var theIdWeight = OfferChainsChestRewards.FirstOrDefault(item => item.ID == id)?.Weight ?? 0; - var weightTable = OfferChainsChestRewards - .Where(item => !IsItemFinished(item.ID)) - .Select(item => item.Weight).ToList(); - var totalWeight = weightTable.Sum(); - return (float)Math.Round((float)theIdWeight / totalWeight * 100, 2); - } - - private bool IsItemFinished(int itemID) - { - var lastItem = OfferChainsData.Items.SingleOrDefault(it => it.Id == itemID); - return lastItem?.Status == 2; - } - - public TimeSpan GetTimeRemain() - { - if (OfferChainsData != null) - { - return OfferChainsData.EndTime - ZZTimeHelper.UtcNow(); - } - // 活动未开始 - return ZZTimeHelper.UtcNow().AddDays(-1) - ZZTimeHelper.UtcNow(); - } - public void Settle() - { - ELog("Settle"); - if (IsCanGetFinalReward()) - { - OnGetFinalReward(); - } - } - - public bool UIRunning { get; set; } = false; - public void OnBuySuccess() - { - Log("OnBuySuccess -> "); - OfferChainsData.RewardList.Add(OfferChainsData.ItemId); - OfferChainsData.LotteryNum += 1; - // 为了处理打点 - if (IsCanGetFinalReward()) - { - OfferChainsData.RewardList.Add(OfferChainsData.ChestReward); - } - FinishLottery(OfferChainsData.ItemId); - SaveData(); // -存 - EventTracking(); - - - //NEXT TURN - if (UIRunning) - { // 播放动画逻辑,交给UI - return; - } - UpdateForNextLottery(); - Settle(); - } - - public void EventTracking() - { - //var price = GetPayAmountById(OfferChainsData.ItemId); - var price = GetIapItemListThisTime(OfferChainsData.LotteryNum - 1)?.PaymentAmount ?? 0F; - var itemEnt = GetTItemById(OfferChainsData.ItemId); - var rewardStr = string.Join(',', OfferChainsData.RewardList); - var number = OfferChainsData.LotteryNum; -#if AGG - using (var e = GEvent.TackEvent("offer_chainchest")) - { - e.AddContent("event_id", OfferChainsData.EventId); - e.AddContent("number", number); - e.AddContent("price", price); - e.AddContent("reward", OfferChainsData.ItemId); - e.AddContent("reward_claimed_list", rewardStr); - } -#endif - Log($"EventTracking: event_id: {OfferChainsData.EventId} number: {number} price: {price} " + - $"reward :{OfferChainsData.ItemId} reward_claimed_list :{rewardStr}"); - } - - public IAPItemList GetIapItemListThisTime() - { - return GetIapItemListThisTime(OfferChainsData.LotteryNum); - } - - private IAPItemList GetIapItemListThisTime(int index) - { - // var index = OfferChainsData.LotteryNum; - index = Mathf.Clamp(index, 0, OfferChainsChestMain.IapList.Count - 1); - var iapId = OfferChainsChestMain.IapList[index]; - var iAPItemList = _tables.TbIAPItemList.GetOrDefault(iapId); - return iAPItemList; - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/027-OfferDiscoPartyManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/027-OfferDiscoPartyManager.cs.txt deleted file mode 100644 index 595bd3e30..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/027-OfferDiscoPartyManager.cs.txt +++ /dev/null @@ -1,588 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using asap.core; -using cfg; -using GameCore; -using Newtonsoft.Json; -using UnityEngine; - -namespace DataCenter -{ - // 数据保存 - public enum TItemStatues - { - Valid = 0, - HighLight = 1, - Done = 2, - } - public class TOfferDiscoPartyData - { - public class TItem - { - public int Id; - public int Item; - public int Number; - - // 0 可选,1 高亮 2 糊了 ,锁链隐藏 应该转换成Enum - public TItemStatues Status; - } - - public bool FirstOpen; // 是否首次打开 - public int EventId; // 默认存一下ID - public DateTime StartTime; // 开始时间 - public DateTime EndTime; // 结束时间 - public int ItemId = -1; - public int LotteryNum; - // public bool Finished; - - // 这个看看能否删掉,只保留状态 - public List Items; - public List RewardList; // 当前获得的奖励Item - } - - // Disco Manager - public class OfferDiscoPartyManager - { - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - public const string SaveKey = "OfferDiscoPartyManager"; - - // 免费抽奖次数 - public int FreeTime = 1; - - [Inject] public Tables _tables { get; set; } - - #region 数据 - - private FishingEvent _fishingEvent; - - public EventOfferDiscoParty OfferDiscoParty { get; private set; } - - public List OfferDiscoPartyRewards { get; private set; } - - public TOfferDiscoPartyData OfferDiscoPartyData { get; private set; } - - internal static game.PlayerDataStorage.PlayerKVOfferState DecodeForKVLoad(IReadOnlyDictionary raw, - game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot,game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodeOffer(raw,true,snapshot,errors); - internal void ResetForKVLoad() - { - OfferDiscoPartyData=null; ValidIds=new List(); _fishingEvent=null; _isInit=false; - OfferDiscoParty=null; OfferDiscoPartyRewards=null; FreeTime=1; - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVOfferState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - OfferDiscoPartyData=!state.IsPresent ? null : new TOfferDiscoPartyData - { - FirstOpen=state.FirstOpen,EventId=state.EventId,StartTime=state.StartTime,EndTime=state.EndTime, - ItemId=state.ItemId,LotteryNum=state.LotteryNum, - Items=state.Items.Select(item=>new TOfferDiscoPartyData.TItem { - Id=item.Id,Item=item.Item,Number=item.Number,Status=(TItemStatues) item.Status }).ToList(), - RewardList=new List(state.RewardList) - }; - } - internal bool IsInactiveForKVValidation => !_isInit && _fishingEvent == null; - - - public List ValidIds; // - - #endregion - - public bool IsFirstOpen - { - get => OfferDiscoPartyData?.FirstOpen?? false; - set - { - if (OfferDiscoPartyData?.FirstOpen??false) - { - OfferDiscoPartyData.FirstOpen = false; - SaveData(); - } - } - } - - public void UpdateEventData(FishingEvent fishingEvent) - { - ELog($"UpdateEventData - > {fishingEvent}"); - _fishingEvent = fishingEvent; - UpdateLocalData(); - } - - private void UpdateLocalData() - { - //选择当前的 Main - var redirectId = _fishingEvent.RedirectID; - var configList = _tables.TbEventOfferDiscoParty.DataList; - foreach (var eventChallenge in configList.Where(eventChallenge => eventChallenge.ID == redirectId)) - { - OfferDiscoParty = eventChallenge; - break; - } - - FreeTime = OfferDiscoParty.Free; - - var rewardList = OfferDiscoParty.RewardList; - // OfferDiscoPartyRewards = _tables.TbEventOfferDiscoPartyReward.DataList; - var list = _tables.TbEventOfferDiscoPartyReward.DataList; - //TODO:LF 这个筛选未应用到程序中,看策划的应用 - // - OfferDiscoPartyRewards = list.Where(item => rewardList.Contains(item.ID)).ToList(); - OfferDiscoPartyRewards.Sort((a,b) => a.ID.CompareTo(b.ID)); - - //添加拍脸 - - // _tables.TbEventOfferDiscoParty - } - - private bool _isInit = false; - public void Init() - { - ELog("Init-> "); - if (_fishingEvent == null) - return; - - if (_fishingEvent.ID != OfferDiscoPartyData?.EventId) - { - ClearOfferDiscoPartyData(); - } - - if (_isInit) - return; - - - if (OfferDiscoPartyData == null) - { - if (_fishingEvent == null) // 不存在Event - { - return; - } - - InitOfferDiscoPartyData(); - } - UpdateOfferDiscoPartyData(); - _isInit = true; - ELog("初始化完成-> "); - } - - private void ProcessLastOne() - { - if (OfferDiscoPartyData != null) - { - Settle(); - // if (!IsTimeAllow()) - // { - // Settle(); - // ClearOfferDiscoPartyData(); - // } - // else if (IsFinished()) - // { - // Settle(); // 补充一下最终大奖 - // } - - } - } - - private void InitOfferDiscoPartyData() - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow()); - - - OfferDiscoPartyData = new TOfferDiscoPartyData - { - FirstOpen = true, - EventId = _fishingEvent.ID, - StartTime = startTime, - EndTime = endTime, - Items = new List(), - RewardList = new List() - }; - - for (var i = 0; i < OfferDiscoPartyRewards.Count; ++i) - { - var item = new TOfferDiscoPartyData.TItem - { - Id = OfferDiscoPartyRewards[i].ID, - Item = OfferDiscoPartyRewards[i].Item, - Number = OfferDiscoPartyRewards[i].Number, - Status = 0, - }; - OfferDiscoPartyData.Items.Add(item); - } - } - - private void UpdateOfferDiscoPartyData() - { - ELog("UpdateOfferDiscoPartyData"); - // 更新可用数据 - OfferDiscoPartyData.EventId = _fishingEvent?.ID ?? OfferDiscoPartyData.EventId; - - UpdateTime(); - UpdateOfferDiscoPartyItems(); - UpdateValidIds(); - // UpdateLotteryItemId(); - GetLotteryItemId(); - - if (_fishingEvent != null) - { - GContext.container.Resolve().AddGiftFaceUI(_fishingEvent.ID, new UIType(OfferDiscoParty.UIPanel), 0); - } - } - - public bool IsTimeAllow() - { - var now = ZZTimeHelper.UtcNow(); - - var startTime = OfferDiscoPartyData.StartTime; - var endTime = OfferDiscoPartyData.EndTime; -#if UNITY_EDITOR - var timeOpened = (now - startTime).TotalSeconds; - var timeEnded = (endTime - now).TotalSeconds; - ELog( - $"StartTime: {startTime} Now: {now} EndTime:{endTime} TimeOpened:{timeOpened} TimeToEnd:{timeEnded} Other: {1800000 - timeOpened} IsTimeAllow => {now <= endTime}"); -#endif - return now >= startTime && now <= endTime; - } - - public void CheckInit() - { - ELog("CheckInit-> "); - ProcessLastOne(); - Init(); - } - - private static void Log(object t) - { - Debug.Log($"OfferDiscoPartyManager -> {t} "); - } - private static void ELog(object t) - { -#if UNITY_EDITOR - Debug.Log($"OfferDiscoPartyManager -> {t} "); -#endif - } - - public bool CheckOpen() - { - // - if (OfferDiscoPartyData == null) return false; - // - if (!IsTimeAllow()) return false; - - if (OfferDiscoParty == null) - { - return false; - } - - if (IsFinished()) - { - return false; - } - - return true; - } - - public bool IsFinished() - { - // return OfferDiscoPartyData?.Finished ?? false; - return OfferDiscoPartyData.LotteryNum >= OfferDiscoPartyData.Items.Count; - } - - private void SaveData() - { - playerSaveStore.Write(SaveKey, JsonConvert.SerializeObject(OfferDiscoPartyData)).RequireAccepted(); - } - - public void LoadData(string dataValue) - { - ELog($"LoadData- {dataValue}"); - - OfferDiscoPartyData = JsonConvert.DeserializeObject(dataValue); - // - // if (true) - // { - // OfferDiscoPartyData.EventId = 1001; - // SaveData(); - // } - } - - public async void OnEnterGameAct() - { - if (!playerSaveStore.IsCurrent) return; - ELog("OnEnterGameAct()"); - IsFirstOpen = false; - await UIManager.Instance.ShowUI(new UIType(OfferDiscoParty.UIPanel)); - } - - public static T WeightedRandom(Dictionary weightTable) - { - // 1. 计算总权重 - var totalWeight = weightTable.Values.Sum(); - // 2. 生成随机数 - var randomValue = UnityEngine.Random.Range(0, totalWeight); - - // 3. 线性遍历选择 - var currentWeight = 0; - foreach (var (key, value) in weightTable) - { - currentWeight += value; - if (randomValue < currentWeight) - return key; - } - - return default; // 理论上不会执行到这里 - } - - private int CalcLotteryItemId() - { - // UpdateValidIds(); - var lotteryNum = OfferDiscoPartyData.LotteryNum; - if (ValidIds.Count <= 0) - { - return -1; - } - - if (OfferDiscoPartyRewards == null) - { - return -1; - } - - // - - // while (true) - // { - var dict = OfferDiscoPartyRewards - .Where(item => ValidIds.Contains(item.ID) && lotteryNum >= (item.LimitConfig - 1)) - .ToDictionary(elem => (elem.ID, elem.LimitConfig), elem => elem.Weight); - - if (dict?.Count <= 0) - return -1; - - var (elemId, limitConfig) = WeightedRandom(dict); - ELog($"CalcLotteryItemId -> {lotteryNum} {elemId} {limitConfig}"); - // if (limitConfig >0 && lotteryNum > limitConfig ) - return elemId; - // } - } - - private void UpdateValidIds() - { - - ValidIds = (from item in OfferDiscoPartyData?.Items where item.Status == 0 select item.Id).ToList(); - // return lotteryNum; - } - - public int GetLotteryItemId() - { - ELog($"GetLotteryItemId -> {OfferDiscoPartyData.ItemId}"); - if (OfferDiscoPartyData.ItemId == -1 || !ValidIds.Contains(OfferDiscoPartyData.ItemId)) - { - UpdateLotteryItemId(); - } - return OfferDiscoPartyData.ItemId; - } - - private void UpdateOfferDiscoPartyItems() - { - ELog("UpdateOfferDiscoPartyItems-> "); - if (OfferDiscoPartyData != null && _fishingEvent != null && OfferDiscoPartyData.EventId == _fishingEvent.ID) - { - var items = OfferDiscoPartyData.Items; - if (OfferDiscoPartyRewards is { Count: > 0 }) - { - for (int i = 0; i < items.Count; ++i) - { - EventOfferDiscoPartyReward reward = null; - if (i < OfferDiscoPartyRewards.Count) - { - reward = OfferDiscoPartyRewards[i]; - } - - if (reward != null) - { - items[i].Id = reward.ID; - items[i].Item = reward.Item; - items[i].Number = reward.Number; - } - } - } - } - } - - private void UpdateTime() - { - if (OfferDiscoPartyData != null && _fishingEvent != null && OfferDiscoPartyData.EventId == _fishingEvent.ID) - { - var limitedTime = (LimitedTime)_fishingEvent.TimeDefinition; - var startTime = GlobalUtils.TryParseDateTime(limitedTime.StartTime, ZZTimeHelper.UtcNow()); - var endTime = GlobalUtils.TryParseDateTime(limitedTime.EndTime, ZZTimeHelper.UtcNow().AddDays(-1)); - OfferDiscoPartyData.StartTime = startTime; - OfferDiscoPartyData.EndTime = endTime; - } - } - - private void UpdateLotteryItemId() - { - var targetId = CalcLotteryItemId(); - OfferDiscoPartyData.ItemId = targetId; - SaveData(); - - ELog($"UpdateLotteryItemId -> {targetId}"); - } - - public void FinishLottery(int targetId) - { - ELog($"FinishLottery -> {targetId}"); - var lastItem = OfferDiscoPartyData.Items.SingleOrDefault(it => it.Id == targetId); - if (lastItem is { Status: not TItemStatues.Done }) - { - lastItem.Status = TItemStatues.Done; - UpdateForNextLottery(); - } - } - //- 开始下一轮数据 - public void UpdateForNextLottery() - { - UpdateValidIds(); - UpdateLotteryItemId(); - } - - - public void ClearOfferDiscoPartyData() - { - OfferDiscoPartyData = null; - _isInit = false; - SaveData(); - } - - public TOfferDiscoPartyData.TItem GetTItemById(int targetId) - { - var lastItem = OfferDiscoPartyData.Items.FirstOrDefault(it => it.Id == targetId); - return lastItem; - } - - public int GetDropIdById(int id) - { - var item = GetTItemById(id); - var itemData = _tables.TbItem.GetOrDefault(item.Item); - return itemData.RedirectID; - } - - public void OnSettleFinalEvent() - { - // var item = _tables.TbItem.GetOrDefault(OfferDiscoParty.ChestReward); - // var item = _tables.TbItem.GetOrDefault(OfferDiscoPartyData.ChestReward); - // var itemFinal = GContext.container.Resolve() - // .GetItemDropPackageItemList(item.RedirectID, 1); - // GContext.container.Resolve().LureInflation(itemFinal, null); - // GContext.container.Resolve().AddItem(itemFinal); - // GContext.Publish(new ShowData(itemFinal)); - // GContext.Publish(new ShowData()); - // OfferDiscoPartyData.Finished = true; - SaveData(); - GContext.Publish(new OfferDiscoPartyRefreshEvent()); - } - - public float GetProbability(int id) - { - var theIdWeight = OfferDiscoPartyRewards.FirstOrDefault(item => item.ID == id)?.Weight ?? 0; - var weightTable = OfferDiscoPartyRewards - .Where(item => !IsItemFinished(item.ID)) - .Select(item => item.Weight).ToList(); - var totalWeight = weightTable.Sum(); - return (float)Math.Round((float)theIdWeight / totalWeight * 100, 2); - } - - private bool IsItemFinished(int itemID) - { - var lastItem = OfferDiscoPartyData.Items.SingleOrDefault(it => it.Id == itemID); - return lastItem?.Status == TItemStatues.Done; - } - - public TimeSpan GetTimeRemain() - { - if (OfferDiscoPartyData != null) - { - return OfferDiscoPartyData.EndTime - ZZTimeHelper.UtcNow(); - } - - // 活动未开始 - return ZZTimeHelper.UtcNow().AddDays(-1) - ZZTimeHelper.UtcNow(); - } - - public void Settle() - { - if (IsFinished()) - { - OnSettleFinalEvent(); - } - } - - public bool UIRunning { get; set; } = false; - - // private bool IsCanGetFinalReward() - // { - // // return OfferDiscoPartyData.LotteryNum >= OfferDiscoPartyData.Items.Count; - // // && !OfferDiscoPartyData.Finished; - // } - - public void OnBuySuccess() - { - ELog("OnBuySuccess -> "); - OfferDiscoPartyData.RewardList.Add(OfferDiscoPartyData.ItemId); - OfferDiscoPartyData.LotteryNum += 1; - FinishLottery(OfferDiscoPartyData.ItemId); - SaveData(); - EventTracking(); - //NEXT TURN - if (UIRunning) - { - // 播放动画逻辑,交给UI - return; - } - - // FinishLottery(OfferDiscoPartyData.ItemId); - UpdateForNextLottery(); - Settle(); - } - - public void EventTracking() - { - var iapItemIdx = OfferDiscoPartyData.LotteryNum - 1 - FreeTime; - var price = GetIapItemListThisTime(iapItemIdx)?.PaymentAmount ?? 0F; - // var itemEnt = GetTItemById(OfferDiscoPartyData.ItemId); - // var rewardStr = string.Join(',', OfferDiscoPartyData.RewardList); - var number = OfferDiscoPartyData.LotteryNum; -#if AGG - using (var e = GEvent.TackEvent("offer_discoparty")) - { - e.AddContent("event_id", OfferDiscoPartyData.EventId); - e.AddContent("number",number); - e.AddContent("price", price); - e.AddContent("reward",OfferDiscoPartyData.ItemId); - } -#endif - ELog($"EventTracking: event_id: {OfferDiscoPartyData.EventId} number: {number} price: {price} " + - $"reward :{OfferDiscoPartyData.ItemId} "); - } - - public IAPItemList GetIapItemListThisTime() - { - return GetIapItemListThisTime(OfferDiscoPartyData.LotteryNum - FreeTime); - } - - private IAPItemList GetIapItemListThisTime(int index) - { - // index -= FreeTime; - // index = Mathf.Clamp(index, 0, OfferDiscoParty.IapList.Count - 1); - if (index < 0 || index > OfferDiscoParty.IapList.Count - 1) - return null; - - var iapId = OfferDiscoParty.IapList[index]; - var iAPItemList = _tables.TbIAPItemList.GetOrDefault(iapId); - return iAPItemList; - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/028-PiggyBankPackData.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/028-PiggyBankPackData.cs.txt deleted file mode 100644 index b3cd6df1e..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/028-PiggyBankPackData.cs.txt +++ /dev/null @@ -1,247 +0,0 @@ -using asap.core; -using GameCore; -using cfg; -using UnityEngine; -using System.Collections.Generic; -using System; -using game; -using System.Linq; -public class PiggyBankPackData -{ - [asap.core.Inject] public game.PlayerDataStorage.IPlayerSaveStore playerSaveStore { get; set; } - private readonly Tables _tables = GContext.container.Resolve(); - private readonly TbEventPackManager _epm - = GContext.container.Resolve().TbEventPackManager; - private struct Data - { - public int currentEventID; - public int purchaseCount; - public int VIPLvlWhenEventActivate; - public bool doNeedTrigger; - public bool isTriggered; - public int savingProgress; - public int redirectID; - public float inflation; - public Data(int eventID = 0, int v = 0, bool b = false, int rid = 0, float inflation = 0) - { - currentEventID = eventID; - purchaseCount = 0; - VIPLvlWhenEventActivate = v; - doNeedTrigger = b; - savingProgress = 0; - isTriggered = false; - redirectID = rid; - this.inflation = inflation; - } - } - private Data _data; - - private bool _kvLoadPresent; - internal bool KVLoadPresent => _kvLoadPresent; - internal static game.PlayerDataStorage.PlayerKVPiggyBankState DecodeForKVLoad( - IReadOnlyDictionary raw, game.PlayerDataStorage.PlayerKVSchemaSnapshot snapshot, - game.PlayerDataStorage.PlayerKVSchemaDiagnostics errors) => - game.PlayerDataStorage.PlayerKVSaveSchema.DecodePiggyBank(raw, snapshot, errors); - - internal void ResetForKVLoad() - { - _kvLoadPresent = false; - _data = default(Data); - } - internal void ReplaceFromKVDecoded(game.PlayerDataStorage.PlayerKVPiggyBankState state) - { - if (state == null) throw new ArgumentNullException(nameof(state)); - if (!state.IsPresent) { ResetForKVLoad(); return; } - var replacement = new Data - { - currentEventID = state.currentEventID, - purchaseCount = state.purchaseCount, - VIPLvlWhenEventActivate = state.VIPLvlWhenEventActivate, - savingProgress = state.savingProgress, - redirectID = state.redirectID, - doNeedTrigger = state.doNeedTrigger, - isTriggered = state.isTriggered, - inflation = state.inflation, - }; - _data = replacement; - _kvLoadPresent = true; - } - internal game.PlayerDataStorage.PlayerKVPiggyBankState SnapshotForKVValidation() => - new game.PlayerDataStorage.PlayerKVPiggyBankState(_kvLoadPresent, _data.currentEventID, _data.purchaseCount, _data.VIPLvlWhenEventActivate, _data.savingProgress, _data.redirectID, _data.doNeedTrigger, _data.isTriggered, _data.inflation); - public bool IsWithinEventTime - { - get - { - var fishingEvent = _tables.TbFishingEvent.GetOrDefault(_data.currentEventID); - if (!(fishingEvent?.TimeDefinition is LimitedTime time)) return false; - var et = DateTime.Parse(time.EndTime); - var st = DateTime.Parse(time.StartTime); - return ZZTimeHelper.UtcNow() >= st && ZZTimeHelper.UtcNow() < et; - } - } - public bool IsPackActivated { get => _data.isTriggered && _tables.TbFishingEvent.DataMap.Keys.Contains(_data.currentEventID) && IsWithinEventTime && _data.purchaseCount < _epm[RedirectID].MaxCount; } - public bool DoNeedUpdate { get => _data.doNeedTrigger; set => _data.doNeedTrigger = value; } - public int CurrentEventID { get => _data.currentEventID; } - public int PurchaseCount { get => _data.purchaseCount; } - public int VIPLvlWhenEventActivated { get => _data.VIPLvlWhenEventActivate; } - public int Progress { get => _data.savingProgress; } - public float Inflation { get => _data.inflation; } - public bool IsFull { get => _data.savingProgress >= Target; } - public int ActivateItemId - { - get => _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]] - .ActivateItemId; - } - public string ActiveItemImg - { - get => _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]].ActiveItemImg; - } - - public int EventItemId - { - get - { - SpecialPack specialPack = GetSpecialPack(); - if (specialPack != null) - { - return specialPack.EventItemId; - } - return 0; - } - } - SpecialPack GetSpecialPack() - { - var TbEventPackManager = _tables.TbEventPackManager.GetOrDefault(_data.redirectID); - if (TbEventPackManager == null) - { - return null; - } - return _tables.TbSpecialPack.GetOrDefault(TbEventPackManager.VIPPackList[_data.VIPLvlWhenEventActivate][0]); - } - public int Target - { - get - { - int count = _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]] - .EventItemRequire[0]; - PlayerItemData playerItemData = GContext.container.Resolve(); - count = playerItemData.IntInflation(count, _data.inflation); - return count; - } - } - public int CanBuyCount - { - get - { - int count = _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]] - .CanBuyCount; - PlayerItemData playerItemData = GContext.container.Resolve(); - count = playerItemData.IntInflation(count, _data.inflation); - return count; - } - } - //public int RedirectID { get => _tables.TbFishingEvent[_data.currentEventID].RedirectID; } - public int RedirectID { get => _data.redirectID; } - public int RewardDropID - { - get => _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]] - .DropID[0]; - } - public List FishingScoreList - { - get => _tables.TbSpecialPack[_epm[RedirectID].VIPPackList[_data.VIPLvlWhenEventActivate][0]] - .EventItemGet; - } - public TimeSpan RemainingTime - { - get - { - return DateTime.Parse((_tables.TbFishingEvent[_data.currentEventID].TimeDefinition as LimitedTime).EndTime) - - ZZTimeHelper.UtcNow(); - } - } - public int MaxCount { get => _epm[RedirectID].MaxCount; } - public void LoadData(string s) - { - _data = Newtonsoft.Json.JsonConvert.DeserializeObject(s); - - //_data.redirectID = 0; - if (_data.redirectID == 0) - { - _data.redirectID = 4055001; - } - } - public void UpdateData(cfg.FishingEvent e) - { - if (_epm[_tables.TbFishingEvent[e.ID].RedirectID].PackType != 2) - { - Debug.LogError($"Fishing event ID {e.ID} is not a piggyBank event."); - return; - } - if (_data.currentEventID != e.ID) - _data = new Data(e.ID, GContext.container.Resolve().PriceLv, true, e.RedirectID, GContext.container.Resolve().InflationRate); - if (_data.redirectID != e.RedirectID) - { - _data.redirectID = e.RedirectID; - Debug.Log("working!!!!!!!!!!"); - } - SaveData(); - } - public void SaveData() - { - playerSaveStore.Write("PiggyBankPackData", - Newtonsoft.Json.JsonConvert.SerializeObject(_data)).RequireAccepted(); - } - public bool AddProgress(int fishTier, int magnification) - { - if (!IsPackActivated || fishTier < 1 || fishTier > 5) - { - //Debug.LogError($"Fish Tier {fishTier} not defined in TbSpedialPack"); - return false; - } - var TbSpecialPack = _tables.TbSpecialPack[_epm[RedirectID].VIPPackList[_data.VIPLvlWhenEventActivate][0]]; - int progress = TbSpecialPack.EventItemGet[fishTier - 1] * magnification; - if (progress > 0 && _data.savingProgress < Target) - { - int curProgress = _data.savingProgress; - _data.savingProgress += progress; - GContext.Publish(new TargetAddData(TbSpecialPack.EventItemId, curProgress, progress)); - if (_data.savingProgress >= Target) - { - GContext.container.Resolve().AddGiftFaceUIForce(_data.currentEventID, UITypes.GiftPiggyBankPopupPanel); - _data.savingProgress = Target; - SaveData(); - return true; - } - SaveData(); - } - return false; - } - public void AddPurchase() - { - _data.purchaseCount++; - SaveData(); - } - public void TriggerPack() - { - DoNeedUpdate = false; - _data.isTriggered = true; - int EventItemCountFirst = _tables.TbSpecialPack[_epm[RedirectID] - .VIPPackList[_data.VIPLvlWhenEventActivate][0]].EventItemCountFirst; - PlayerItemData playerItemData = GContext.container.Resolve(); - EventItemCountFirst = playerItemData.IntInflation(EventItemCountFirst, _data.inflation); - _data.savingProgress += EventItemCountFirst; - SaveData(); - } -} -public class PiggyBankProgressEvent -{ - public int type;//0: 初始化 1:增加动画 - public int addProgress; -} - diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/029-PlayerFishDataRod.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/029-PlayerFishDataRod.cs.txt deleted file mode 100644 index ea6328ae1..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/029-PlayerFishDataRod.cs.txt +++ /dev/null @@ -1,681 +0,0 @@ -using asap.core; -using cfg; -using LitJson; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.UI; - -namespace GameCore -{ - public class RodGSAData - { - public int GloveID; - public Dictionary RodToSkin = new Dictionary(); - public List GloveIds = new List(); - public List SkinIds = new List(); - - public List GloveNewIds = new List(); - public List SkinNewIds = new List(); - } - public partial class PlayerFishData - { - #region 鱼杆皮肤 - public RodGSAData rodAccessoriesData; - string InitRodAccessoriesDataKey = "InitRodAccessoriesData"; - public GloveData GetGloveData - { - get - { - return _tables.TbGloveData.GetOrDefault(rodAccessoriesData.GloveID); - } - } - public void InitRodAccessoriesData() - { - if (rodAccessoriesData == null || rodAccessoriesData.GloveID == 0) - { - rodAccessoriesData = new RodGSAData(); - rodAccessoriesData.GloveID = _tables.TbGlobalConfig.InitGloveID; - rodAccessoriesData.GloveIds = new List() { _tables.TbGlobalConfig.InitGloveID }; - } - } - /// - /// 获取鱼杆对应的皮肤 - /// - /// - /// - public int GetRodSkin(int rodId) - { - if (rodAccessoriesData.RodToSkin.ContainsKey(rodId)) - { - return rodAccessoriesData.RodToSkin[rodId]; - } - return rodId; - } - /// - /// 设置鱼杆对应的皮肤 - /// - /// - /// - public void SetRodSkin(int rodId, int skinId) - { - if (skinId <= 0) - { - skinId = rodId; - } - rodAccessoriesData.RodToSkin[rodId] = skinId; - SaveInitRodAccessoriesData(); - } - public void InitRodAccessoriesData(string value) - { - rodAccessoriesData = Newtonsoft.Json.JsonConvert.DeserializeObject(value); - } - public void SaveInitRodAccessoriesData() - { - string value = Newtonsoft.Json.JsonConvert.SerializeObject(rodAccessoriesData); - playerSaveStore.Write(InitRodAccessoriesDataKey, value).RequireAccepted(); - } - /// - /// 手是否解锁 - /// - /// - /// - public bool IsGloveUnlocked(int gloveId) - { - return rodAccessoriesData.GloveIds.Contains(gloveId); - } - /// - /// 皮肤是否解锁 - /// - /// - /// - public bool IsSkinUnlocked(int skinId) - { - return rodAccessoriesData.SkinIds.Contains(skinId); - } - /// - /// 解锁手 - /// - /// - public void UnlockGlove(int gloveId) - { - if (!IsGloveUnlocked(gloveId)) - { - rodAccessoriesData.GloveIds.Add(gloveId); - rodAccessoriesData.GloveNewIds.Add(gloveId); - SaveInitRodAccessoriesData(); - } - else - { - Debug.LogError("手投放重复:" + gloveId); - } - } - /// - /// 解锁皮肤 - /// - /// - public void UnlockSkin(int skinId) - { - if (!IsSkinUnlocked(skinId)) - { - rodAccessoriesData.SkinIds.Add(skinId); - rodAccessoriesData.SkinNewIds.Add(skinId); - SaveInitRodAccessoriesData(); - } - else - { - Debug.LogError("鱼杆皮肤投放重复:" + skinId); - } - } - /// - /// 获取是否是没查看过的手 - /// - /// - /// - public bool IsNewGlove(int skinId) - { - return rodAccessoriesData.GloveNewIds.Contains(skinId); - } - /// - /// 是否是没查看过的皮肤 - /// - /// - /// - public bool IsNewSkin(int skinId) - { - bool isNew = rodAccessoriesData.SkinNewIds.Contains(skinId); - if (isNew) - { - rodAccessoriesData.SkinNewIds.Remove(skinId); - } - return isNew; - } - /// - /// 取消new标记 手 - /// - /// - public void RemoveGloveNewId() - { - if (rodAccessoriesData.GloveNewIds.Count > 0) - { - rodAccessoriesData.GloveNewIds.Clear(); - SaveInitRodAccessoriesData(); - } - } - #endregion 鱼杆皮肤 - #region 鱼杆升级 - //合成或强化鱼竿 - bool EnhanceConsumed(int quality, int fragmentID, int rquiredFragments) - { - if (rodData.TryGetValue(fragmentID, out int rodCount) && rodCount >= rquiredFragments) - { - rodData[fragmentID] -= rquiredFragments; -#if AGG - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", fragmentID) - .AddContent("state_info", "cost") - .AddContent("change_num", rquiredFragments); - } -#endif - return true; - } - else - { - rquiredFragments -= rodCount; - RodFragmentExchange rodFragmentExchange = _tables.TbRodFragmentExchange.GetOrDefault(quality); - int fragment = 0; - if (rodFragmentExchange != null) - { - rquiredFragments *= rodFragmentExchange.ExchangeRate; - fragment = GContext.container.Resolve().GetRodPiece(rodFragmentExchange.GeneralFragmentID); - } - if (fragment >= rquiredFragments) - { - if (rodData.ContainsKey(fragmentID)) - { - rodData[fragmentID] = 0; - } - rodData[rodFragmentExchange.GeneralFragmentID] -= rquiredFragments; -#if AGG - - if (rodCount > 0) - { - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", fragmentID) - .AddContent("state_info", "cost") - .AddContent("change_num", rodCount); - } - } - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", rodFragmentExchange.GeneralFragmentID) - .AddContent("state_info", "cost") - .AddContent("change_num", rquiredFragments); - } -#endif - return true; - } - } - return false; - } - public void AscendRod(int id) - { - RodData _rodData = _tables.TbRodData.GetOrDefault(id); - if (_rodData != null) - { - bool isUp = false; - RodAscend rodAscend = _tables.TbRodAscend.GetOrDefault(_rodData.AscendID); - int rquiredFragments; - int fragmentID = rodAscend.FragmentID; - int quality = _rodData.Quality; - if (rodData.ContainsKey(id)) - { - rquiredFragments = rodAscend.AscentTransformed[rodData[id] + 1]; - - if (rodData[id] < rodAscend.AscentTransformed.Count - 1 && EnhanceConsumed(quality, fragmentID, rquiredFragments)) - { - isUp = true; - rodData[id] += 1; - } - } - else - { - rquiredFragments = rodAscend.AscentTransformed[0]; - - if (rodData.TryGetValue(fragmentID, out int rodCount) && rodCount >= rquiredFragments) - { - rodData[fragmentID] -= rquiredFragments; -#if AGG - using (var e = GEvent.GameEvent("item_change", gaSend: true)) - { - e.AddContent("item_id", fragmentID) - .AddContent("state_info", "cost") - .AddContent("change_num", rquiredFragments); - } -#endif - isUp = true; - rodData.Add(id, 0); - } - } - if (isUp) - { -#if AGG - using (var e = GEvent.GameEvent("rod_upgrade")) - { - e.AddContent("rod_id", id) - .AddContent("rod_level", GetRodLevel(id)) - .AddContent("resin_consume", 0) - .AddContent("rod_star", rodData[id]) - .AddContent("rod_chips_consume", rquiredFragments); - } -#endif - playerSaveStore.Write("RodData", JsonMapper.ToJson(rodData)).RequireAccepted(); - //鱼竿红点数据修改 - CheckRodRedPointUp(); - //合成鱼竿 - CheckAllRodUpLevel(); - } - } - } - #endregion - #region 荣耀等级 - - Dictionary _honorlevel = new Dictionary(); - public int GetHonorLevel(int honorId) - { - if (_honorlevel.TryGetValue(honorId, out int level)) - { - return level; - } - return 0; - } - public int GetHonorLevelAttribute(int quality, int starAdd = 0) - { - RodRodLevelPeak rodLevelPeak = _tables.TbRodRodLevelPeak.GetOrDefault(quality); - //星级对属性的加成 某几个属性加多少加到多少星 - int level = GetHonorLevel(quality) + starAdd; - if (rodLevelPeak != null && level > 0) - { - List peakBasicStats = rodLevelPeak.PeakBasicStats; - int value; - int count = peakBasicStats.Count; - if (level > count) - { - value = peakBasicStats[count - 1]; - value += (level - count) * (peakBasicStats[count - 1] - peakBasicStats[count - 2]); - } - else - { - value = peakBasicStats[level - 1]; - } - return value; - } - return 0; - } - public void HonorLevelUp(RodData rodData) - { - PlayerData playerData = GContext.container.Resolve(); - RodAscend rodAscend = _tables.TbRodAscend.GetOrDefault(rodData.AscendID); - int quality = rodData.Quality; - int fragmentID = rodAscend.FragmentID; - RodRodLevelPeak rodLevelPeak = _tables.TbRodRodLevelPeak.GetOrDefault(rodData.Quality); - if (rodLevelPeak == null) - { - Debug.LogError($"[FishingRodHonorlevelPanel]OnClickUpGray: No RodRodLevelPeak data found for Quality {quality}"); - return; - } - int currentHonorLevel = GetHonorLevel(rodData.Quality); - if (currentHonorLevel >= rodLevelPeak.ItemConsume.Count) - { - currentHonorLevel = rodLevelPeak.ItemConsume.Count - 1; - } - int requiredItems = rodLevelPeak.ItemConsume[currentHonorLevel]; - int fragmentItems = rodLevelPeak.FragmentConsume[currentHonorLevel]; - if (playerData.pearl >= requiredItems && EnhanceConsumed(quality, fragmentID, fragmentItems)) - { - playerData.SetPearl(playerData.pearl - requiredItems); - if (_honorlevel.ContainsKey(quality)) - { - _honorlevel[quality]++; - } - else - { - _honorlevel[quality] = 1; - } - SaveHonorLevelData(); - } - } - - string HonorLevelDataKey = "HonorLevelData"; - - public void SaveHonorLevelData() - { - string value = Newtonsoft.Json.JsonConvert.SerializeObject(_honorlevel); - playerSaveStore.Write(HonorLevelDataKey, value).RequireAccepted(); - } - - #endregion 荣耀等级 - - #region 鱼杆词条星级相关 - - //计算升级和强化后的属性 - public List GetRodAttribute(int id, bool isMax = false, int levelAdd = 0, int starAdd = 0) - { - RodData rodData = _tables.TbRodData.GetOrDefault(id); - RodAscend rodAscend = _tables.TbRodAscend.GetOrDefault(rodData.AscendID); - RodLevelup rodLevelup = _tables.TbRodLevelup.GetOrDefault(rodData.LevelupID); - int star = isMax ? rodAscend.MaxAscent : GetRodPiece(rodData.ID) + starAdd; - int level = isMax ? rodLevelup.MaxLevel - 1 : GetRodLevel(rodData.ID) + levelAdd; - List list = new List(); - for (int i = 0; i < rodData.InitialBasicStats.Count; i++) - { - list.Add(0); - } - //星级对属性的加成 某几个属性加多少加到多少星 - var AscentBasicStats = rodAscend.AscentBasicStat; - var AscentBasicStatList = rodAscend.AscentBasicStatList; - int index; - for (int i = 0; i < star; i++) - { - var AscentBasicStat = AscentBasicStats[i]; - int count = AscentBasicStat.Count; - for (int j = 0; j < count; j++) - { - //InitialBasicStats 中第 AscentBasicStat[j] 个值加 i 星的值 累加 - index = AscentBasicStat[j] - 1; - list[index] = AscentBasicStatList[i][j]; - } - } - //等级对属性的加成 每个属性升到多少级 - var levelupBasicStats = rodLevelup.LevelupBasicStats; - for (int j = 0; j < list.Count; j++) - { - list[j] += levelupBasicStats[j][level] + rodData.InitialBasicStats[j]; - } - list[0] += GetHonorLevelAttribute(rodData.Quality); - return list; - } - #region 工具 - //获取鱼竿某一星级各个词条的等级 - public int[] GetPerkLevel(int perkIDListCount, int star, List DefaultPerk, List PerkUnlockOrder) - { - int[] lv = new int[perkIDListCount]; - for (int i = 0; i < DefaultPerk.Count; i++) - { - lv[DefaultPerk[i] - 1]++; - } - for (int i = 0; i < star; i++) - { - if (PerkUnlockOrder[i] <= perkIDListCount) - { - //每一星升级的是第几个特性 - lv[PerkUnlockOrder[i] - 1]++; - } - } - return lv; - } - //获取鱼竿某一星级能解锁的词条ID及值 - public Dictionary GetRodDuelPerk(int id, int star) - { - RodData rodData = _tables.TbRodData.GetOrDefault(id); - RodAscend curRodAscend = _tables.TbRodAscend.GetOrDefault(rodData.AscendID); - int perkIDListCount = curRodAscend.PerkIDList.Count; - int[] lv = GetPerkLevel(perkIDListCount, star, curRodAscend.DefaultPerk, curRodAscend.PerkUnlockOrder); - Dictionary RodPerkDic = new Dictionary(); - for (int i = 0; i < perkIDListCount; i++) - { - int level = lv[i]; - if (level > 0) - { - var rodEngancePerk = _tables.TbRodAscendPerk.GetOrDefault(curRodAscend.PerkIDList[i]); - - if (rodEngancePerk.DuelPerk) - { - List PerkDataList = curRodAscend.PerkDataList[i]; - if (level > PerkDataList.Count) - { - Debug.LogError($"GetRodPerk: rod {id} perkID {curRodAscend.PerkIDList[i]} level {level} is out of range (1 - {PerkDataList.Count})"); - } - else - { - RodPerkDic[curRodAscend.PerkIDList[i]] = PerkDataList[level - 1]; - } - } - } - } - return RodPerkDic; - } - //获取鱼竿某一星级能解锁的词条类型及值 - public Dictionary GetRodPerk(int id, int star) - { - RodData rodData = _tables.TbRodData.GetOrDefault(id); - RodAscend curRodAscend = _tables.TbRodAscend.GetOrDefault(rodData.AscendID); - int perkIDListCount = curRodAscend.PerkIDList.Count; - int[] lv = GetPerkLevel(perkIDListCount, star, curRodAscend.DefaultPerk, curRodAscend.PerkUnlockOrder); - Dictionary RodPerkDic = new Dictionary(); - for (int i = 0; i < curRodAscend.PerkDataList.Count; i++) - { - int level = lv[i]; - if (level > 0) - { - var rodEngancePerk = _tables.TbRodAscendPerk.GetOrDefault(curRodAscend.PerkIDList[i]); - //第i条第lv[i]级 直接读数值 - List PerkDataList = curRodAscend.PerkDataList[i]; - if (level > PerkDataList.Count) - { - Debug.LogError($"GetRodPerk: rod {id} perkID {curRodAscend.PerkIDList[i]} level {level} is out of range (1 - {PerkDataList.Count})"); - } - else - { - RodPerkDic[rodEngancePerk.PerkType] = PerkDataList[level - 1]; - } - } - } - return RodPerkDic; - } - //获取鱼竿某一星级能解锁的词条类型及等级 - public Dictionary GetRodPerkLevel(int id, int star) - { - RodData rodData = _tables.TbRodData.GetOrDefault(id); - RodAscend curRodAscend = _tables.TbRodAscend.GetOrDefault(rodData.AscendID); - int perkIDListCount = curRodAscend.PerkIDList.Count; - int[] lv = GetPerkLevel(perkIDListCount, star, curRodAscend.DefaultPerk, curRodAscend.PerkUnlockOrder); - Dictionary RodPerkDic = new Dictionary(); - for (int i = 0; i < perkIDListCount; i++) - { - int level = lv[i]; - if (level > 0) - { - var rodEngancePerk = _tables.TbRodAscendPerk.GetOrDefault(curRodAscend.PerkIDList[i]); - RodPerkDic[rodEngancePerk.PerkType] = (curRodAscend.PerkIDList[i], level); - } - } - return RodPerkDic; - } - - - //解析词条的值 - public float GetRodPerkValue(RodPerkType rodPerkType, Dictionary RodPerkDic) - { - if (RodPerkDic.TryGetValue(rodPerkType, out string perk)) - { - if (perk.Contains('|')) - { - Debug.LogError($"GetRodPerkValue: rodPerkType {rodPerkType} perk {perk} cannot convert to float directly"); - string[] values = perk.Split('|'); - return float.Parse(values[0]); - } - return float.Parse(perk); - } - return 0; - } - - public static string GetPerkDesc(RodPerkType rodPerkType, string des, string value) - { - var values = value.Split('|'); - string str = LocalizationMgr.GetText(des); - try - { - switch (rodPerkType) - { - case RodPerkType.BattlePerk_AllToAtkSpeed: - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(values[0]).ToPercentageString(), values[1], float.Parse(values[2]).ToPercentageString()); - break; - case RodPerkType.BattlePerk_ComboToExDmg: - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(values[0]).ToPercentageString(), values[1]); - break; - case RodPerkType.BattlePerk_FishSkillToAtkSpeed: - case RodPerkType.BattlePerk_FishEscapeToAtkSpeed: - str = LocalizationMgr.GetFormatTextValue(des, values[0], float.Parse(values[1]).ToPercentageString()); - break; - case RodPerkType.BattlePerk_PiercingAddDamage: - str = LocalizationMgr.GetFormatTextValue(des, values[1], float.Parse(values[0]).ToPercentageString()); - break; - case RodPerkType.BattlePerk_PiercingToCombo: - case RodPerkType.BattlePerk_TensionToCrit: - case RodPerkType.BattlePerk_PiercingCritDmg: - - case RodPerkType.FactoryLabel_ScaleG: - case RodPerkType.FactoryLabel_Ilmarinen: - case RodPerkType.FactoryLabel_ChromaCast: - case RodPerkType.FactoryLabel_Victoria: - case RodPerkType.FactoryLabel_Sakura: - case RodPerkType.FactoryLabel_Titan: - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(values[0]).ToPercentageString(), float.Parse(values[1]).ToPercentageString()); - break; - case RodPerkType.BattlePerk_ComboToCombo: - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(values[0]).ToPercentageString(), float.Parse(values[1]).ToPercentageString(), float.Parse(values[2]).ToPercentageString()); - break; - case RodPerkType.NewPiercingZone: - break; - default: - if (!value.Contains('|')) - { - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(value).ToPercentageString()); - } - else - { - str = LocalizationMgr.GetFormatTextValue(des, float.Parse(values[0]).ToPercentageString(), float.Parse(values[1]).ToPercentageString()); - Debug.LogError($"GetPerkDesc error: no case for rodPerkType: {rodPerkType}, des: {des}, value: {value}"); - } - break; - } - } - catch (Exception e) - { - Debug.LogError($"GetPerkDesc error: {e.Message}, rodPerkType: {rodPerkType}, des: {des}, value: {value}"); - } - return str; - } - /// - /// 设置星级展示 - /// - /// - /// - /// - /// - /// - /// - /// - public static int SetRodStar(int star, - int MaxAscent, - List star_empty_list, - List star_empty_image, - List starList, bool isUp = false) - { - if (star > MaxAscent || star < 0) - { - Debug.LogError($"SetRodStar: star {star} is out of range (0 - {MaxAscent})"); - star = MaxAscent; - } - int Quality = MaxAscent / 3; - if (MaxAscent > 15) - { - Debug.LogError("MaxAscent >> show == 15"); - Quality = MaxAscent / 4; - } - if (Quality > 5) - { - Debug.LogError("MaxAscent >> show == 20"); - Quality = 5; - } - - int show = star; - int startIndex = 0; - if (star > Quality * 3) - { - show = star - Quality * 3; - startIndex = 3; - } - else if (star > Quality * 2) - { - show = star - Quality * 2; - startIndex = 2; - } - else if (star > Quality) - { - show = star - Quality; - startIndex = 1; - } - - int index = startIndex; - for (int i = 0; i < starList.Count; i++) - { - starList[i].gameObject.SetActive(i < Quality); - star_empty_list[i].SetActive(i < Quality); - if (i < show) - { - starList[i].SetStar(startIndex + 1); - } - else if (i < Quality) - { - starList[i].SetStar(startIndex); - } - if (star_empty_image != null) - { - if (index > 0) - { - if (index > 3) - { - Debug.LogError("SetRodStar index > 3, index = " + index); - index = 3; - } - star_empty_image[i].gameObject.SetActive(true); - star_empty_image[i].sprite = starList[i].Star[index - 1].sprite; - } - else - { - star_empty_image[i].gameObject.SetActive(false); - } - } - } - if (isUp) - { - if (show > 0) - { - starList[show - 1].PlayAni(); - if (star_empty_image != null) - { - index = startIndex; - if (index > 0) - { - star_empty_image[show - 1].gameObject.SetActive(true); - star_empty_image[show - 1].sprite = starList[show - 1].Star[index - 1].sprite; - } - else - { - star_empty_image[show - 1].gameObject.SetActive(false); - } - } - } - } - return Quality; - } - #endregion 工具 - #endregion 鱼杆词条星级相关 - - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/030-PlayerItemData_Inflation.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/030-PlayerItemData_Inflation.cs.txt deleted file mode 100644 index ea062f86d..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/030-PlayerItemData_Inflation.cs.txt +++ /dev/null @@ -1,258 +0,0 @@ -using asap.core; -using cfg; -using game; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -namespace GameCore -{ - public partial class PlayerItemData - { - /// - /// 获得膨胀体力后的物品显示 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - /// - /// - public ItemData GetItemDataOneLureInflation(float? inflate, int dropId, int index = 0) - { - DropPackageList dropPackageList = _tables.TbDrop.GetOrDefault(dropId)?.DropList; - if (dropPackageList == null) - { - GameDebug.LogError("null dropID" + dropId); - return null; - } - int len = dropPackageList.DropIDList.Count; - int len2 = dropPackageList.DropCountList.Count; - if (len != len2) - { - if (len > len2) - { - len = len2; - } - Debug.LogError($"[PlayerItemData]GetItemDataByDropIdAndType: DropPackageList count not equal [DropId]=={dropId}"); - } - if (index >= len) - { - return null; - } - ItemData itemData = new ItemData() - { - id = dropPackageList.DropIDList[index], - count = dropPackageList.DropCountList[index] - }; - - ItemTransition(itemData); - if (inflate == null) - { - inflate = GContext.container.Resolve().InflationRate;//等级膨胀系数 - } - itemData.inflate = (float)inflate; - if (itemData.id == 1001) - { - ItemInflation(itemData, inflate); - } - return itemData; - } - /// - /// 获得膨胀体力后的物品显示 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - public List GetItemDataByDropIdAndTypeLureInflation(float? inflate, int dropId, int mapId = -1) - { - List itemDataList = GetItemDataByDropIdAndType(dropId, mapId); - LureInflation(itemDataList, inflate); - return itemDataList; - } - /// - /// 获得膨胀体力后的物品显示 处理有选定地图鱼卡的情况 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - public List GetItemDataByDropIdLureInflation(float? inflate, int dropId, int mapId = -1, bool afterAdding = false) - { - List itemDataList = GetItemDataByDropId(dropId, mapId, afterAdding); - LureInflation(itemDataList, inflate); - return itemDataList; - } - - /// - /// 获得膨胀体力后的物品显示 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - /// - /// - public List GetItemByDropListLureInflation(float? inflate, List dropIDList) - { - if (dropIDList == null || dropIDList.Count == 0) - { - return null; - } - List itemDataList = new List(); - foreach (var t in dropIDList) - { - List itemDatas = GetItemDataByDropIdAndType(t); - if (itemDatas != null && itemDatas.Count > 0) - { - itemDataList.AddRange(itemDatas); - } - } - //itemDataList不需要重复合并 - if (itemDataList.Count == 0) - { - return null; - } - - LureInflation(itemDataList, inflate); - return itemDataList; - } - /// - /// 发放物品 并且膨胀体力 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - /// - /// - /// - public List AddItemByDropLureInflation(float? inflate, int dropID, ChangeSource changeSource, bool isShow = true, RewardType rewardType = RewardType.Normal) - { - List itemDataList = GetItemDataByDropIdAndType(dropID); - if (itemDataList != null) - { - LureInflation(itemDataList, inflate); - if (isShow) - { - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataList, rewardType))); - } - AddItem(itemDataList, changeSource); - } - return itemDataList; - } - - /// - /// 发放物品 并且膨胀体力 - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - /// - /// - public List AddItemByDropListLureInflation(float? inflate, List dropIDList, ChangeSource changeSource, bool isShow = true, RewardType rewardType = RewardType.Normal) - { - if (dropIDList == null || dropIDList.Count == 0) - { - return null; - } - List itemDataList = new List(); - foreach (var t in dropIDList) - { - List itemDatas = GetItemDataByDropIdAndType(t); - if (itemDatas != null && itemDatas.Count > 0) - { - itemDataList.AddRange(itemDatas); - } - } - //itemDataList不需要重复合并 - if (itemDataList.Count == 0) - { - return null; - } - - LureInflation(itemDataList, inflate); - if (isShow) - { - game.PlayerDataStorage.PlayerSaveAction.Present(() => GContext.Publish(new ShowData(itemDataList, rewardType))); - } - AddItem(itemDataList, changeSource); - return itemDataList; - } - /// - /// 对 itemDataList 中的体力进行膨胀 - /// - /// - /// 体力膨胀系数 == null 当前实时系数 - public void LureInflation(List itemDataList, float? inflate) - { - if (inflate == null) - { - inflate = GContext.container.Resolve().InflationRate;//等级膨胀系数 - } - for (int i = 0; i < itemDataList.Count; i++) - { - ItemData itemData = itemDataList[i]; - itemData.inflate = (float)inflate; - if (itemData.id == 1001) - { - itemData.origin = itemData.count; - itemData.count = IntInflation(itemData.count, inflate); - } - } - } - - /// - /// 智能处理itemData.count的膨胀 - /// - /// - /// - /// True if it needs inflation. - public bool LureInflation(ItemData itemData, float? inflate) - { - if (itemData.id != 1001) - return false; - ItemInflation(itemData, inflate); - return true; - } - - /// - /// 对itemData.count进行膨胀 - /// - /// - /// 体力膨胀系数 == null 当前实时系数 - public void ItemInflation(ItemData itemData, float? inflate) - { - itemData.origin = itemData.count; - if (inflate == null) - { - inflate = GContext.container.Resolve().InflationRate;//等级膨胀系数 - } - itemData.inflate = (float)inflate; - itemData.count = IntInflation(itemData.count, inflate); - } - /// - /// 对数字进行膨胀 - /// - /// - /// 体力膨胀系数 == null 当前实时系数 - /// - public int IntInflation(int origin, float? inflate) - { - if (inflate == null) - { - inflate = GContext.container.Resolve().InflationRate;//等级膨胀系数 - } - if (inflate > 0) - { - float count = origin * (1 + inflate.Value); - var roundingStep = _tables.TbGlobalConfig.LureScaleRoundingStep; - int stepCount = roundingStep.Count / 2; - int step = roundingStep[stepCount * 2]; - for (int i = 0; i < stepCount; i++) - { - if (count <= roundingStep[i]) - { - step = roundingStep[i + stepCount]; - break; - } - } - - float a = count / step; - var b = Math.Round(a, MidpointRounding.AwayFromZero); - origin = (int)b * step; - } - return origin; - } - } -} \ No newline at end of file diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/031-TotalRechargeManager.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/031-TotalRechargeManager.cs.txt deleted file mode 100644 index 0e45c095c..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/031-TotalRechargeManager.cs.txt +++ /dev/null @@ -1,183 +0,0 @@ -using asap.core; -using cfg; -using game; -using LitJson; -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace GameCore -{ - public class TotalRechargeData - { - public int eventID; - public int progress; - public int vip; - public int oldProgress; - } - public class TotalRechargeManager - { - readonly game.PlayerDataStorage.IPlayerSaveStore saveStore = GContext.container.Resolve(); - - public const string TotalRechargeDataKey = "EventTotalRecharge"; - public TotalRechargeData GetEventData() - { - var totalRechargeData = new TotalRechargeData(); - - string data = saveStore.Read(TotalRechargeDataKey).ValueOrThrow(); - if (data != null) - { - try - { - totalRechargeData = Newtonsoft.Json.JsonConvert.DeserializeObject(data) ?? throw new Newtonsoft.Json.JsonSerializationException("Null TotalRechargeData save."); - if (totalRechargeData.vip > 10) - { - totalRechargeData.vip = 10; - } - } - catch (Exception e) - { - Debug.LogError(e); - throw; - } - } - FishingEvent tr = GContext.container.Resolve().GetEventByTypeAndSubType(12, 1); - - if (tr != null && totalRechargeData.eventID != tr.ID) - { - totalRechargeData = new TotalRechargeData(); - totalRechargeData.eventID = tr.ID; - totalRechargeData.vip = GContext.container.Resolve().PriceLv; - if (totalRechargeData.vip > 10) - { - totalRechargeData.vip = 10; - } - SaveTotalRechargeData(totalRechargeData); - } - return totalRechargeData; - } - - public void GetTotalReward(RewardType rewardType, string textValue) - { - var totalRechargeData = GetEventData(); - List rewardIDs = new List(); - var tables = GContext.container.Resolve(); - var eventTotalRecharge = GetEventTotalRecharge(totalRechargeData); - var taskIds = eventTotalRecharge.TaskList; - var vip = totalRechargeData.vip; - int oldProgress = totalRechargeData.oldProgress; - int newProgress = totalRechargeData.progress; - int taskCount = taskIds.Count; - for (int i = 0; i < taskCount; i++) - { - int taskId = taskIds[i]; - CommonTask commonTask = tables.TbCommonTask.GetOrDefault(taskId); - if (commonTask == null) - { - continue; - } - int iapid = commonTask.TaskParam[vip]; - var iap = tables.TbIAPItemList.GetOrDefault(iapid); - if (oldProgress < iap.VIPPoint && newProgress >= iap.VIPPoint) - { - int rewardID = commonTask.TaskReward[vip]; - rewardIDs.Add(rewardID); -#if AGG - using (var e = GEvent.GameEvent("event_totalrecharge")) - { - e.AddContent("task_id", taskId) - .AddContent("reward_id", rewardID); - } -#endif - } - } - if (rewardIDs.Count > 0) - { - PlayerItemData playerItemData = GContext.container.Resolve(); - var itemData = playerItemData.GetItemByDropListLureInflation(null, rewardIDs); - var showData = new ShowData(itemData, rewardType); - showData.textValue = textValue; - GContext.Publish(showData); - playerItemData.AddItem(itemData, null); - } - totalRechargeData.oldProgress = totalRechargeData.progress; - SaveTotalRechargeData(totalRechargeData); - } - - public void AddProgress(int progress) - { - TotalRechargeData totalRechargeData = GetEventData(); - if (CheckTotalRechargeOpen(totalRechargeData)) - { - totalRechargeData.progress += progress; - SaveTotalRechargeData(totalRechargeData); - } - } - public bool CheckTotalRechargeOpen() - { - TotalRechargeData totalRechargeData = GetEventData(); - return CheckTotalRechargeOpen(totalRechargeData); - } - EventTotalRecharge GetEventTotalRecharge(TotalRechargeData totalRechargeData) - { - if (totalRechargeData == null || totalRechargeData.eventID == 0) - { - return null; - } - var _tables = GContext.container.Resolve(); - FishingEvent fishingEvent = _tables.TbFishingEvent.GetOrDefault(totalRechargeData.eventID); - if (fishingEvent == null) - { - return null; - } - return _tables.TbEventTotalRecharge[fishingEvent.RedirectID]; - } - public bool CheckTotalRechargeOpen(TotalRechargeData totalRechargeData) - { - if (totalRechargeData == null || totalRechargeData.eventID == 0) - { - return false; - } - var _tables = GContext.container.Resolve(); - FishingEvent fishingEvent = _tables.TbFishingEvent.GetOrDefault(totalRechargeData.eventID); - if (fishingEvent == null) - { - return false; - } - LimitedTime limitedTime = fishingEvent.TimeDefinition as LimitedTime; - var startTime = DateTime.Parse(limitedTime.StartTime); - var endTime = DateTime.Parse(limitedTime.EndTime); - var curTime = ZZTimeHelper.UtcNow(); - if (curTime < startTime || curTime > endTime) - { - if (totalRechargeData.oldProgress != totalRechargeData.progress) - { - RewardType rewardType = RewardType.FishBoxFlyRestore; - string textValue = LocalizationMgr.GetText("UI_FishingRewardPanel_101042"); - GetTotalReward(rewardType, textValue); - } - return false; - } - var eventTotalRecharge = GetEventTotalRecharge(totalRechargeData); - var taskIds = eventTotalRecharge.TaskList; - var vip = totalRechargeData.vip; - int oldProgress = totalRechargeData.oldProgress; - int taskCount = taskIds.Count; - int taskId = taskIds[^1]; - CommonTask commonTask = _tables.TbCommonTask.GetOrDefault(taskId); - if (commonTask == null) - { - return false; - } - int iapid = commonTask.TaskParam[vip]; - var iap = _tables.TbIAPItemList.GetOrDefault(iapid); - - return totalRechargeData.oldProgress < iap.VIPPoint; - } - - void SaveTotalRechargeData(TotalRechargeData totalRechargeData) - { - saveStore.Write(TotalRechargeDataKey, JsonMapper.ToJson(totalRechargeData)).RequireAccepted(); - } - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/032-DebugFunc.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/032-DebugFunc.cs.txt deleted file mode 100644 index 8ba5db7bf..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/032-DebugFunc.cs.txt +++ /dev/null @@ -1,942 +0,0 @@ -using asap.core; -using game; -using GameCore; -using IngameDebugConsole; -using System; -using System.Linq; -using UI.HookWheel; -using UniRx; -using UnityEngine; -using UnityEngine.AddressableAssets; -using UnityEngine.Rendering; -using UnityEngine.Rendering.Universal; -using UnityEngine.SceneManagement; - -public class DebugFunc -{ - public static void Init() - { - var config = GContext.container.Resolve(); - if (config != null && (config.Get("DEBUG", "0") == "1" || config.Get("GM", "0") == "1")) - { - DebugLogConsole.AddCommand("Go.show", "Shows a GameObject", ShowGO); - DebugLogConsole.AddCommand("Go.hide", "Shows a GameObject", HideGO); - - DebugLogConsole.AddCommand("Render.quality", "change quality", SetQuality); - DebugLogConsole.AddCommand("Render.scale", "Set render scale [0.1-2]", SetRendererScale); - DebugLogConsole.AddCommand("Render.aa", "anti aliasing", SetAntiAliasing); - DebugLogConsole.AddCommand("Render.ShadowToggle", "Toggle Shadow", ToggleShadow); - DebugLogConsole.AddCommand("Render.Pipline", "light num", SetRenderPipline); - - DebugLogConsole.AddCommand("info.GPU", "GPU Info", GpuInfo); - DebugLogConsole.AddCommand("info.CPU", "CPU Info", CpuInfo); - DebugLogConsole.AddCommand("info.Support", "Device Support", SupportInfo); - - DebugLogConsole.AddCommand("FPS", "Toggle FPS", Fps); - DebugLogConsole.AddCommand("LTPL", "开关 Leviathan Timeline 性能日志(不影响 FPS 浮层)", ToggleLeviathanTimelinePerf); - DebugLogConsole.AddCommand("LTCW", "设置 CatchUp 消费等待(ms) 1~50", SetLeviathanCatchUpWaitMs); - DebugLogConsole.AddCommand("LTCW?", "查询 CatchUp 消费等待(ms)", GetLeviathanCatchUpWaitMs); - - DebugLogConsole.AddCommand("Render.antiAliasing", "change antiAliasing", SetRTAntiAliasing); - DebugLogConsole.AddCommand("T.hotupdate", "hot update test", HotUpdateTest); - DebugLogConsole.AddCommand("UI.hide", "Hide UI", ToggleUI); - DebugLogConsole.AddCommand("Misc.tg", "Hide misc", ToggleMisc); - DebugLogConsole.AddCommand("aihelp", "open aihelp", OpenAIHelp); - DebugLogConsole.AddCommand("review", "open review", OpenReview); - - DebugLogConsole.AddCommand("Pay.sku", "sku list", GetSKUs); - DebugLogConsole.AddCommand("ad.debug", "Active Ad Debug", ActiveAdDebug); - DebugLogConsole.AddCommand("ad.media", "Active Ad Media Debug", ActiveAdMedia); - - DebugLogConsole.AddCommand("notify.send", "Local Notify Test", NotifyTest); - DebugLogConsole.AddCommand("notify.setting", " Notify set", NotifySettingTest); - DebugLogConsole.AddCommand("notify.status", " Notify Status", NotificationStatus); - DebugLogConsole.AddCommand("notify.time", "Notify at certain time", NotifyAtTime); - - - DebugLogConsole.AddCommand("mail.status", "Print cache mail", PrintMail); - DebugLogConsole.AddCommand("mail.fetch", "fetch mail to cache", FetchMail); - DebugLogConsole.AddCommand("rt.test", "test realtime", RtTest); - - DebugLogConsole.AddCommand("account.loginTime", "login time - 1day", LoginTime); - DebugLogConsole.AddCommand("account.info", "account info", AccoutInfo); - DebugLogConsole.AddCommand("account.authortest", "author test", AuthorTest); - - DebugLogConsole.AddCommand("aihelp.test", "aihelp test", AIHelpTest); - - DebugLogConsole.AddCommand("open.washing", "Open Washing Activity", OpenWashingActivity); - - DebugLogConsole.AddCommand("deeplink.test", "Test if deeplink connects. If so, returns pid and uid.", TestDeepLink); - - DebugLogConsole.AddCommand("PotionGoTo", "Potion Go To", PotionGoTo); - DebugLogConsole.AddCommand("potion.clear", "Potion Go To", PotionClear); - - DebugLogConsole.AddCommand("pinball.clear", "Clear Pinball Data", PinballDataClear); - DebugLogConsole.AddCommand("pinball.fire", "Launch Pinball Pellet", PinballFirePellet); - - DebugLogConsole.AddCommand("scratch.clear", "Clear Scratch Ticket Data", ScratchTicketDataClear); - - DebugLogConsole.AddCommand("shooting.go", "Goto", ShootingRangeDebug); - DebugLogConsole.AddCommand("eventpartner.activate", "Activate a temp event", EventPartnerDebugActivate); - DebugLogConsole.AddCommand("bingo.ts", "OpenTestScene", ShowTestBingoPanel); - DebugLogConsole.AddCommand("bingo.seeds", "TestBingoSeedPickingRng", TestBingoSeedPickingRng); - DebugLogConsole.AddCommand("bingo.instant", "Instant Bingo.", TestBingoInstantBingo); - - DebugLogConsole.AddCommand("srp.fswave", "toggle fullscreen wave", ToggleFSWave); - DebugLogConsole.AddCommand("ib.lvl", "infinitebuilding level", SetInfiniteBuildLvl); - DebugLogConsole.AddCommand("srp.fsblur", "toggle fullscreen blur", ToggleFSBlur); - - DebugLogConsole.AddCommand("stash", "test reward stash service", TestRewardStashService); - DebugLogConsole.AddCommand("guide.clear", "clear guide data", ClearGuide); - DebugLogConsole.AddCommand("pinataAct", "load pinata Act", LoadPinataAct); - DebugLogConsole.AddCommand("lastpayment.clear", "Clear Last Payment Time", ClearLastPaymentTime); - DebugLogConsole.AddCommand("HookWheelForecActive", "Hook Wheel Forec Active", HookWheelForecActive); - - DebugLogConsole.AddCommand("eps.invitecount", "GetInvitationCount", PrintEventPartnerStatueInvitationCount); - DebugLogConsole.AddCommand("eps.sendbot", "Start recommending bots", EventPartnerStatueActivateBotInvitation); - DebugLogConsole.AddCommand("eps.bot", "Peek Robot Data", EventPartnerStatuePeekRobot); - DebugLogConsole.AddCommand("eps.pool", "Peek Player Info Pool", EventPartnerStatuePeekPlayerInfoPool); - DebugLogConsole.AddCommand("eps.score", "Peek Score", EventPartnerStatuePeekScore); - DebugLogConsole.AddCommand("eps.rt", "Test rt", EventPartnerStatueTestRt); - DebugLogConsole.AddCommand("eps.i", "Peek inflationrate", EventPartnerStatuePeekInflationRate); - - DebugLogConsole.AddCommand("sr.set", "Set Social Rush Progress", SocialRushTest); - DebugLogConsole.AddCommand("sr.reset", "Reset Social Rush", SocialRushReset); - DebugLogConsole.AddCommand("sr.peek", "Peek Social Rush", SocialRushPeek); - DebugLogConsole.AddCommand("mft.guide", "Mow For Treasure Clear Guide", EventMowForTreasureGuideClear); - - DebugLogConsole.AddCommand("osc.peek", "Peek Offer Story Chain", OfferStoryChainPeek); - DebugLogConsole.AddCommand("osc.reset", "Reset Offer Story Chain", OfferStoryChainReset); - - DebugLogConsole.AddCommand("ota.peek", "Peek Offer treasure ascent", OfferTreasureAscentPeek); - DebugLogConsole.AddCommand("ota.reset", "Reset Offer treasure ascent", OfferTreasureAscentReset); - - DebugLogConsole.AddCommand("pu.bk", "Block Pinball Kick if input is not 0. If input is 0, unblock.", PinballUncountableBlockKick); - } - } - - private static void TestDeepLink() - { - var res = AFHelper.Instance.GetDLReferer(out var pid, out var uid); - Debug.Log($"DidReceiveDeepLink: {AFHelper.Instance.DidReceivedDeepLink}"); - Debug.Log($"IsFirstLaunch: {AFHelper.Instance.IsFirstLaunch}"); - - if (AFHelper.Instance.DeepLinkParamsDictionary is not null) - { - Debug.Log($"DeepLinkParamsDic:"); - foreach (var kvp in AFHelper.Instance.DeepLinkParamsDictionary) - { - Debug.Log($"{kvp.Key}: {kvp.Value}"); - } - } - else - { - Debug.Log($"DeepLinkParamsDic: Empty."); - } - var message = res ? $"Deeplink success with pid: {pid}, uid: {uid}" : "Deeplink fail."; - Debug.Log(message); - } - - private static void NotifyAtTime(string time) - { - var now = ZZTimeHelper.UtcNow(); - var fireTime = DateTime.SpecifyKind(DateTime.Parse(time), DateTimeKind.Utc); - fireTime = fireTime.AddDays(now <= fireTime ? 0 : 1); - var service = GContext.container.Resolve(); - service.ScheduleOneTimeNotification(434200, fireTime.ToLocalTime(), "Test Note at Time", - $"Test Notification @ {fireTime}."); - } - - private static void NotifyTest() - { - ILocalNotificationService service = GContext.container.Resolve(); - service.ScheduleOneTimeNotification(434200, DateTime.Now + TimeSpan.FromSeconds(3), "Notification", - "Test Notification "); - } - - private static void NotifySettingTest() - { - ILocalNotificationService service = GContext.container.Resolve(); - service.OpenSettings(); - } - - private static string NotificationStatus() - { -#if UNITY_ANDROID - return Unity.Notifications.Android.AndroidNotificationCenter.UserPermissionToPost.ToString(); -#else - return Unity.Notifications.iOS.iOSNotificationCenter.GetNotificationSettings().AuthorizationStatus.ToString(); -#endif - } - - private static string HotUpdateTest() - { - return "hot update test Ver 0.6 - 2024-03-26:1434"; - } - - private static string ToggleUI(string path) - { - GameObject homePanelGo = UIManager.Instance.gameObject.transform.Find("HomePanel").gameObject; - if (homePanelGo == null) - { - return "UI not found."; - } - - GameObject go = homePanelGo.transform.Find(path).gameObject; - if (go == null) - { - return "path not found"; - } - - go.SetActive(!go.activeSelf); - return $"UI {go} toggled to {go.activeSelf}."; - } - - private static string ToggleMisc(int idx) - { - GameObject go = GetGOFromPath("Env_101(Clone)/Misc"); - int childCount = go.transform.childCount; - if (idx >= childCount) - return $"index {idx} exceeds children count{childCount}"; - var child = go.transform.GetChild(idx).gameObject; - if (child == null) - return $"child {idx} not found"; - child.SetActive(!child.activeSelf); - return $"{child} toggled to {child.activeSelf}."; - } - - private static void OpenAIHelp() - { - AIHelp.AIHelpSupport.Show("E001"); - } - - private static void OpenReview() - { - var config = GContext.container.Resolve(); - tysdk.AppRequestReview.RequestReview(config.Get(GConstant.K_APP_Store_URL, string.Empty)); - } - - private static string ShowGO(string path) - { - GameObject go = GetGOFromPath(path); - if (go != null) - { - go.SetActive(true); - } - - return $"GameObject not found"; - } - - private static string HideGO(string path) - { - GameObject go = GetGOFromPath(path); - if (go != null) - { - go.SetActive(false); - return $"{go.name} has been hidden"; - } - - return $"GameObject not found"; - } - - private static string SetQuality(int level) - { - QualityManager.ChangeQuality(level); - zzwater.URPHelper.RendererFeatureSetActive(false, "FSBlur"); - zzwater.URPHelper.RendererFeatureSetActive(false, "FSWave"); - return $"quality set to {QualitySettings.names[QualitySettings.GetQualityLevel()]}"; - } - - private static void SetRTAntiAliasing(int level) - { - var rt = new RenderTexture((int)125, (int)125, 24, RenderTextureFormat.ARGB32); - rt.antiAliasing = level; - } - - private static string SetRendererScale(float ratio) - { - if (ratio == 0) - { - return $"Render scale {CurrentRenderPipeline.renderScale}"; - } - - ratio = Mathf.Clamp(ratio, 0.1f, 2f); - var uprAsset = CurrentRenderPipeline; - if (uprAsset == null) return "No UniversalRenderPipelineAsset"; - var preValue = uprAsset.renderScale; - uprAsset.renderScale = ratio; - return $"Render scale {preValue} set to {ratio}"; - } - - private static string SetAntiAliasing(int count) - { - var uprAsset = CurrentRenderPipeline; - if (uprAsset == null) return "No UniversalRenderPipelineAsset"; - var preValue = uprAsset.msaaSampleCount; - uprAsset.msaaSampleCount = count; - return $"Render scale {preValue} set to {count}"; - } - - private static string SetRenderPipline(string name) - { - var currentPiplineName = GraphicsSettings.currentRenderPipeline.name; - if (name == "?") - { - return $"Pipline set to {currentPiplineName}"; - } - else if (name == "-") - { - QualitySettings.renderPipeline = null; - } - else - { - var pipelineAsset = Addressables.LoadAssetAsync(name).WaitForCompletion(); - QualitySettings.renderPipeline = pipelineAsset; - } - - var newPipelineName = GraphicsSettings.currentRenderPipeline.name; - return $"{currentPiplineName} set to {newPipelineName}"; - } - - - private static string ToggleShadow() - { - var cam = Camera.main; - if (cam != null) - { - var comp = cam.GetComponent(); - var preValue = comp.renderShadows; - comp.renderShadows = !preValue; - return $"Shadow {preValue} set to {comp.renderShadows}"; - } - - return "Camera not found"; - } - - private static string CpuInfo() - { - var props = typeof(SystemInfo).GetProperties() - .Where(x => x.Name.StartsWith("processor")); - var sb = new System.Text.StringBuilder(); - sb.AppendLine(); - foreach (var prop in props) - { - sb.AppendLine($"{prop.Name}: {prop.GetValue(null)}"); - } - - return sb.ToString(); - } - - private static string GpuInfo() - { - var props = typeof(SystemInfo).GetProperties() - .Where(x => x.Name.StartsWith("graphics")); - var sb = new System.Text.StringBuilder(); - sb.AppendLine(); - foreach (var prop in props) - { - sb.AppendLine($"{prop.Name}: {prop.GetValue(null)}"); - } - - return sb.ToString(); - } - - private static string SupportInfo() - { - var props = typeof(SystemInfo).GetProperties() - .Where(x => x.Name.StartsWith("support")); - var sb = new System.Text.StringBuilder(); - sb.AppendLine(); - foreach (var prop in props) - { - sb.AppendLine($"{prop.Name}: {prop.GetValue(null)}"); - } - - return sb.ToString(); - } - - private static void Fps() - { - game.RootCtx.showFPS = !game.RootCtx.showFPS; - } - - private static void ToggleLeviathanTimelinePerf() - { - var on = !LeviathanLogConfig.EnableTimelineVideoPerfLog; - LeviathanLogConfig.EnableTimelineVideoPerfLog = on; - PlayerPrefs.SetInt("LeviathanTimelinePerf", on ? 1 : 0); - PlayerPrefs.Save(); - UnityEngine.Debug.Log($"[Debug] Leviathan Timeline 性能日志 = {on}(Logcat 搜 LeviathanTimeline)"); - } - - private static void SetLeviathanCatchUpWaitMs(int ms) - { - var decoders = UnityEngine.Object.FindObjectsOfType(true); - if (decoders == null || decoders.Length == 0) - { - UnityEngine.Debug.Log("[Debug] LTCW: 未找到活跃的 LeviathanVideoDecoderBase 实例"); - return; - } - foreach (var d in decoders) - { - d.CatchUpConsumePerFrameWaitMs = ms; - } - UnityEngine.Debug.Log($"[Debug] LTCW: 已将 {decoders.Length} 个解码器 CatchUpConsumePerFrameWaitMs 设为 {ms}ms"); - } - - private static void GetLeviathanCatchUpWaitMs() - { - var decoders = UnityEngine.Object.FindObjectsOfType(); - if (decoders == null || decoders.Length == 0) - { - UnityEngine.Debug.Log("[Debug] LTCW?: 未找到活跃的 LeviathanVideoDecoderBase 实例"); - return; - } - foreach (var d in decoders) - { - UnityEngine.Debug.Log($"[Debug] LTCW? {d.name}: CatchUpConsumePerFrameWaitMs={d.CatchUpConsumePerFrameWaitMs}ms"); - } - } - - - private static UniversalRenderPipelineAsset CurrentRenderPipeline - { - get - { - return GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset; - //return (UniversalRenderPipelineAsset) QualitySettings.renderPipeline; - } - } - - private static async void GetSKUs() - { - var iapService = GContext.container.Resolve(); - if (iapService == null) - { - UnityEngine.Debug.Log("iapService is null"); - ; - return; - } - - var sb = new System.Text.StringBuilder(); - sb.AppendLine(); - var skus = await iapService.GetSKUs(); - foreach (var sku in skus) - { - sb.AppendLine(); - sb.Append($" {sku.price} code {sku.price_currency_code} "); - sb.AppendLine(); - } - - UnityEngine.Debug.Log(sb.ToString()); - } - - private static void ActiveAdDebug() - { - MaxSdk.SetVerboseLogging(true); - MaxSdk.ShowCreativeDebugger(); - } - - private static void ActiveAdMedia() - { - MaxSdk.ShowMediationDebugger(); - } - - private static GameObject GetGOFromPath(string path) - { - var root = SceneManager.GetActiveScene().GetRootGameObjects(); - var splitPath = path.Split('/'); - var rootName = splitPath[0]; - var rootGo = root.FirstOrDefault(x => x.name == rootName); - if (rootGo == null) return null; - if (splitPath.Length == 1) return rootGo; - var childPath = string.Join("/", splitPath.Skip(1)); - return rootGo.transform.Find(childPath)?.gameObject; - } - - private static void PrintMail() - { - var mailService = GContext.container.Resolve() as InGameMailService; - mailService.PrintCacheMail(); - } - - private static void FetchMail() - { - GContext.container.Resolve().FetchMail(); - } - - private static void RtTest() - { - var rtService = GContext.container.Resolve() as SignalRService; - rtService.Test(); - } - - private static void LoginTime(int hours) - { - var userService = GContext.container.Resolve() as game.PlayFabUserService; - if (userService == null) return; - - var loginTime = userService.LoginTime; - var newLoginTime = loginTime.AddHours(hours); - var prop = userService.GetType().GetProperty("LoginTime"); - prop.SetValue(userService, newLoginTime); - Debug.Log($"loginTime: {loginTime} newLoginTime: {newLoginTime} prop: {userService.LoginTime}"); - } - - private static void AccoutInfo() - { - var userService = GContext.container.Resolve() as game.PlayFabUserService; - if (userService == null) return; - Debug.Log($"pfid: {userService.UserId} tyid: {userService.CustomId} lastLogin: {userService.LoginTime}"); - - if (PlayerPrefs.HasKey("KEY_ACCOUNT_INFO")) - { - Debug.Log("Saved account info: " + PlayerPrefs.GetString("KEY_ACCOUNT_INFO")); - } - else - { - Debug.Log("No saved account info"); - } - } - - private static async void AuthorTest() - { - var svr = GContext.container.Resolve(); - var result = await svr.GetStringAsync("account/authortest"); - Debug.Log($"AuthorTest {result}"); - } - - private static void AIHelpTest() - { - RedPointManager.Instance.SetRedPointState(RedPointName.AIHelp_Msg, true, 1); - } - - private static void OpenWashingActivity() - { - ToggleUI("safearea/RightPanel/layout/btn_washing"); - } - - private static void PotionClear() - { - GContext.container.Resolve().ClearPotionData(); - Debug.Log("--- Potion Clear ok"); - } - - private static void PotionGoTo(int levelID) - { - GContext.container.Resolve().GoToPotionLevel(levelID); - Debug.Log("--- PotionGoTo levelID:" + levelID + ", ok"); - } - - private static void PinballDataClear() - { - GContext.container.Resolve().ClearData(); - Debug.Log("--- PinballDataClear ok"); - } - - private static void PinballFirePellet(float force) - { - FishingPinballAct.Publish(new EventPinballLaunchPelletData() - { - Force = force - }); - Debug.Log("--- PinballFirePellet ok, force:" + force); - } - - private static void ScratchTicketDataClear() - { - GContext.container.Resolve().ClearData(); - Debug.Log("--- Scratch Ticket Data Clear ok"); - } - - private static void ShootingRangeDebug(int n) - { - GContext.Publish(new EventShootingRangeDebug { StageIdx = n }); - Debug.Log($"Switch to {n}."); - } - - private static void EventPartnerDebugActivate() - { - // var d = GContext.container.Resolve(); - // if (d is null) - // { - // Debug.Log( $"[EventPartner] No data found, cannot activate."); - // return; - // } - // _ = d.LoadDataDebug(); - Debug.Log($"[EventPartner] This function is obsoleted for now."); - } - - private static void ToggleFSWave() - { - var feature = zzwater.URPHelper.FindAndCacheRendererFeature("FSWave"); - if (feature == null) - Debug.LogError($"Feature FSWave not found"); - else - feature.SetActive(!feature.isActive); - } - - private static void SetInfiniteBuildLvl(int level) - { - var s = GContext.container.Resolve().InfiniteBuildingData; - if (s == null) - { - Debug.LogError($"No ib data found."); - return; - } - var data = new InfiniteBuildingData(); - data.Deserialize(s); - var delta = level - data.Lvl; - data.Lvl = level; - for (int i = 0; i < data.Record.Count; i++) - { - var r = data.Record[i]; - r.Pos += Vector2.up * delta; - data.Record[i] = r; - } - data.UploadData(); - Debug.Log($"Done."); - } - - private static void ToggleFSBlur() - { - var feature = zzwater.URPHelper.FindAndCacheRendererFeature("FSBlur"); - if (feature == null) - Debug.LogError($"Feature FSWave not found"); - else - feature.SetActive(!feature.isActive); - } - - private static void ShowTestBingoPanel() - { - GContext.container.Register().AsSingleton(); - GContext.container.Resolve().InitTest(); - GContext.Publish(new UnloadActToNextAct { actId = "EventBingoAct", TransitionPanel = UITypes.CloudTransitionPanel }); - } - - private static void TestBingoSeedPickingRng() - { - var dataList = GContext.container.Resolve().TbEventBingoMain.DataList; - var tc = new EventBingoTableContext(40701); - int[] stat = { 0, 0, 0, 0 }; - int seed, statCount = 10000; - var sb = new System.Text.StringBuilder(); - for (int i = 0; i < statCount; i++) - { - seed = tc.PickSeed(roundCount: 10086); - for (int j = 0; j < 4; j++) - { - if (dataList[j].SeedID.Contains(seed)) - { - stat[j]++; - break; - } - } - sb.AppendLine($"{seed}, "); - } - Debug.Log($"[EventBingo] Test Result:\n1Bingo:{stat[0] / (float)statCount * 100}%,\n2Bingo: {stat[1] / (float)statCount * 100}%,\n3Bingo: {stat[2] / (float)statCount * 100}%,\n4Bingo: {stat[3] / (float)statCount * 100}%"); - Debug.Log("[EventBingo] Seeds: \n" + sb.ToString()); - } - - private static void TestBingoInstantBingo() - { - var model = GContext.container.Resolve(); - if (model == null) - { - Debug.Log("[EventBingo] Bingo model not found!"); - return; - } - model.ActivateInstantBingo(); - Debug.Log("[EventBingo] Instant Bingo activated."); - } - - private static void TestRewardStashService(string cmd) - { - const string reset = "reset", upload = "upload", load = "load", flush = "flush", add = "add"; - var service = GContext.container.Resolve(); - switch (cmd) - { - case reset: - service.Reset(); - Debug.Log("Reset Done."); - break; - case upload: - service.UploadData(); - Debug.Log("Upload Done."); - break; - case load: - service.LoadData(); - Debug.Log("Load Done."); - break; - case flush: - service.Flush(); - Debug.Log("Flush Done."); - break; - case add: - GContext.Publish(new DeferredRewardStashService.EventStashItem - { - Item = new ItemData(1001, 100) - }); - Debug.Log("Add Done."); - break; - default: - Debug.Log("Invalid command. Available commands:\n" + - "- reset: Clear all stash data\n" + - "- add: Add 1001 * 100\n" + - "- upload: Upload stash data to playfab\n" + - "- load: Load stash data from playfab\n" + - "- flush: Process and clear all pending rewards"); - break; - } - } - static void ClearGuide() - { - GContext.container.Resolve().GMClearGuide(); - UIManager.Instance.DestroyUI(UITypes.GuidancePanel); - } - static void LoadPinataAct() - { - GContext.Publish(new UnloadActToNextAct { actId = "PinataPackAct_Pony" }); - GContext.OnEvent().Subscribe((actLoadedEvent) => - { - var Act = GContext.container.ResolveAct("PinataPackAct_Pony"); - if (Act is PinataPackAct pinataPackAct) - { - Debug.Log($"jsd Act is PinataPackAct pinataPackAct"); - var rigidBody = pinataPackAct.GetComponentsInChildren(); - foreach (var r in rigidBody) - { - r.useGravity = false; - } - var gameObject = GetGOFromPath("PinataPackAct_Pony(Clone)/Stage1"); - gameObject.transform.localPosition = new Vector3(0, 0, 0.2f); - gameObject.transform.localRotation = Quaternion.Euler(-21, 0, 0); - } - - var ui = UIManager.Instance.GetContainedUI(UITypes.PinataPack_PonySettlementPanel); - ui.FindChildGameObject("btn_scene")?.SetActive(false); - ui.FindChildGameObject("btn_close")?.SetActive(true); - }); - } - static void ClearLastPaymentTime() - { - GContext.container.Resolve().Write("LastPaymentTime", "").RequireAccepted(); - } - static void HookWheelForecActive() - { - GContext.container.Resolve()?.ForceActive(); - } - - static void PrintEventPartnerStatueInvitationCount() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - Debug.Log($"InvitationCount: {arc.InvitationData.InvitationCount}, DoRecommendBot: {arc.InvitationData.DoRecommendBot}"); - } - - static void EventPartnerStatueActivateBotInvitation() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - arc.InvitationData.SetInvitationCount(1999); - Debug.Log($"Bot invitation count set to 1999"); - } - - // static void EventPartnerStatueRefreshInvitation() - // { - // var arc = GContext.container.Resolve(); - // if (arc == null) - // { - // Debug.Log("EventPartnerStatueArc not found"); - // return; - // } - // arc.InvitationData.RefreshInvitation(); - // Debug.Log("RefreshInvitation Done"); - // } - - static void EventPartnerStatuePeekRobot() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - var str = Newtonsoft.Json.JsonConvert.SerializeObject(arc.RobotData.RobotInvitationBuffer); - Debug.Log("RobotBuffer: " + str); - str = Newtonsoft.Json.JsonConvert.SerializeObject(arc.RobotData.RobotList.Select(kv => kv.Value.ActionQ)); - Debug.Log("RobotActionQ: " + str); - } - - static void EventPartnerStatuePeekPlayerInfoPool() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - var bufferStr = Newtonsoft.Json.JsonConvert.SerializeObject(arc.PlayerInfoPool.PlayerInfoDic); - Debug.Log("PlayerInfoCache:" + bufferStr); - } - - static void EventPartnerStatuePeekScore() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - var s = new System.Text.StringBuilder(); - foreach (var c in arc.Model.ComponentList) - { - s.AppendLine($"Partner{c.PartnerId}: self display:{c.ScoreSelfDisplay}, self actual:{c.ScoreSelfActual}, partner display:{c.ScorePartnerDisplay}, partner actual:{c.ScorePartnerActual}\n"); - } - Debug.Log(s.ToString()); - } - - static void EventPartnerStatueTestRt(int scoreAdd) - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - var partnerId = arc.Model.ComponentList[0].PartnerId; - var newScore = arc.Model.ComponentList[0].ScorePartnerActual + scoreAdd; - var se = new EventPartnerGatherRequests.EventPartnerGatherScoreEvt - { - PartnerId = partnerId, - Score = newScore, - }; - var pe = new EventPartnerGatherRequests.EventPartnerGatherPartnerEvt - { - PartnerInfo = new PlayerInfo - { - AvatarUrl = "", - DisplayName = "TestRt", - Level = 1, - PlayFabId = "TestRt", - }, - EvtType = 0, - SlotId = 1 - }; - arc.RtSystem.TestRt(se, pe); - } - - static void EventPartnerStatuePeekInflationRate() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("EventPartnerStatueArc not found"); - return; - } - Debug.Log($"InflationRate: {arc.Model.LureInflationRate}"); - } - - static void SocialRushTest(int progress) - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("SocialRushArchitechture not found"); - return; - } - arc.Model.SetProgress(progress); - Debug.Log($"[SocialRush]Actual progress set to {progress}"); - } - - static void SocialRushReset() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("SocialRushArchitechture not found"); - return; - } - arc.Model.Reset(); - Debug.Log($"[SocialRush]Reset Done."); - } - static void SocialRushPeek() - { - var arc = GContext.container.Resolve(); - if (arc == null) - { - Debug.Log("SocialRushArchitechture not found"); - return; - } - Debug.Log($"[SocialRush] Display: {arc.Model.ProgressDisplay}, Actual {arc.Model.ProgressActual}, inflation rate: {arc.Model.InflationRate}, event Id: {arc.EventId}"); - } - static void EventMowForTreasureGuideClear() - { - GContext.container.Resolve()?.ClearGuide(); - } - - static void OfferStoryChainReset() - { - var manager = GContext.container.Resolve(); - if (manager == null) - { - Debug.Log("OfferStoryChain.Manager not found"); - return; - } - manager.Reset(); - } - - static void OfferStoryChainPeek() - { - var manager = GContext.container.Resolve(); - if (manager == null) - { - Debug.Log("OfferStoryChain.Manager not found"); - return; - } - var str = "EventId: " + manager.EventId + "\n" + "Progress: " + manager.Progress + "\n" + "VipLevel: " + manager.VipLevel + "\n" + "RoundCount: " + manager.RoundCount; - Debug.Log("OfferStoryChain.Manager:" + str); - } - - static void OfferTreasureAscentPeek() - { - var manager = GContext.container.Resolve(); - if (manager == null) - { - Debug.Log("OfferTreasureAscent.Manager not found"); - return; - } - Debug.Log($"[OfferTreasureAscent] eventId: {manager.EventId}, status: {manager.Status}, roundCount: {manager.RoundCount}"); - } - - static void OfferTreasureAscentReset() - { - var manager = GContext.container.Resolve(); - if (manager == null) - { - Debug.Log("OfferTreasureAscent.Manager not found"); - return; - } - manager.Reset(); - Debug.Log($"[OfferTreasureAscent] Reset Done."); - } - - static void PinballUncountableBlockKick(int block) - { - var manager = GContext.container.Resolve(); - if (manager == null) - { - Debug.Log("PinballUncountable.Manager not found"); - return; - } - manager.EventAggregator.Publish(new PinballUncountable.EventBlockKick { Block = block != 0 }); - } -} diff --git a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/033-EventFishingDuelPanel.cs.txt b/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/033-EventFishingDuelPanel.cs.txt deleted file mode 100644 index a05cc5382..000000000 --- a/CodexOutput/upserver/B3BatchMigration/M2/C2d修改前快照/033-EventFishingDuelPanel.cs.txt +++ /dev/null @@ -1,829 +0,0 @@ -using asap.core; -using cfg; -using game; -using GameCore; -using Newtonsoft.Json.Linq; -using PlayFab; -using PlayFab.MultiplayerModels; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using TMPro; -using UniRx; -using UnityEngine; -using UnityEngine.AddressableAssets; -using UnityEngine.UI; - -public class EventFishingDuelPanel : BasePanel -{ - Tables tables; - Button btn_close; - GameObject btn_close_image; - Animation anim; - - GameObject MiddlePanel; - TMP_Text text_time; - Image icon_rank; - TMP_Text text_rank; - Button btn_questionmark1; - Button btn_questionmark; - GameObject bg_bar; - Image bar; - TMP_Text text_progress; - Button btn_reward; - List rewardItemNews; - TMP_Text win_text_num; - TMP_Text loss_text_num; - TMP_Text middle_text_time; - Button icon_ticket; - Button btn_confirm; - GameObject loading; - GameObject p_text; - TMP_Text text_num; - - //GameObject effect_beilv_loop; - Button btn_beilv; - //Image btn_beilv_image; - Button btn_beilv_max; - //private Image btn_beilv_max_image; - - TMP_Text text_beilv; - TMP_Text text_beilv_max; - TMP_Text text_beilv_show; - - - GameObject matchingPanel; - DuelMatchPlayer myself; - DuelMatchPlayer enemy; - GameObject fx_ui_matchingPanel_match_glow_01; - TMP_Text match_text_time; - Button but_stop; - Coroutine matchIng; - FishingDuelManager FDM; - Sound audio_matchingloop; - AudioClip audio_ui_fishingduel_matchingloop; - IUIService uiService; - Timer timer; - FishingEventData fishingEventData; - - Button btn_advert; - - DuelRandomMapPanel randomMapPanel; - - GameObject fishConfrimPanel; - - TicketTips ticket_tips; - - IDisposable disRequestSvrTime; - float MatchPlayerProb; - private void Awake() - { - fishingEventData = GContext.container.Resolve(); - uiService = GContext.container.Resolve(); - tables = GContext.container.Resolve(); - btn_close = transform.Find("bottom/btn_close").GetComponent