diff --git a/common/data/share/user.go b/common/data/share/user.go index 8d1ba74b..fc92d40f 100644 --- a/common/data/share/user.go +++ b/common/data/share/user.go @@ -46,7 +46,7 @@ func (m *sessionManager) GetSession(sessionID string) (uint32, error) { // SaveSession 保存会话信息 func (m *sessionManager) SaveSession(sessionID string, userID uint32) error { - return m.sessionStore.Set(gctx.New(), sessionID, userID, time.Hour*24) + return m.sessionStore.Set(gctx.New(), sessionID, userID, time.Hour*1) } // DeleteSession 删除会话 diff --git a/common/socket/kick.go b/common/socket/kick.go index 99cc86bc..c013f70c 100644 --- a/common/socket/kick.go +++ b/common/socket/kick.go @@ -12,9 +12,19 @@ func (h *Server) KickPerson(a int) error { return player.KickPlayer(uint32(a)) } + +// 参数不为0是强制踢出 func (h *Server) QuitSelf(a int) error { //TODO 这里待退出 fmt.Println("检测到退出请求") + h.quit = true + if a != 0 { + player.Mainplayer.Range(func(key uint32, value *player.Player) bool { + value.Kick() + return true + }) + } + return nil } diff --git a/common/utils/help.go b/common/utils/help.go new file mode 100644 index 00000000..a2fdd2b1 --- /dev/null +++ b/common/utils/help.go @@ -0,0 +1,10 @@ +package utils + +func FindWithIndex[T any](slice []T, predicate func(item T) bool) (int, *T, bool) { + for i := range slice { + if predicate(slice[i]) { + return i, &slice[i], true + } + } + return -1, nil, false +} diff --git a/common/utils/limit/LICENSE b/common/utils/limit/LICENSE new file mode 100644 index 00000000..800f2c7c --- /dev/null +++ b/common/utils/limit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 肖其顿 + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/common/utils/limit/NOTICE b/common/utils/limit/NOTICE new file mode 100644 index 00000000..73d68a92 --- /dev/null +++ b/common/utils/limit/NOTICE @@ -0,0 +1,13 @@ + Copyright 2025 肖其顿 + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/common/utils/limit/README.md b/common/utils/limit/README.md new file mode 100644 index 00000000..cb911dba --- /dev/null +++ b/common/utils/limit/README.md @@ -0,0 +1,42 @@ +# limit [![PkgGoDev](https://pkg.go.dev/badge/github.com/xiaoqidun/limit)](https://pkg.go.dev/github.com/xiaoqidun/limit) +一个高性能、并发安全的 Go 语言动态速率限制器 + +# 安装指南 +```shell +go get -u github.com/xiaoqidun/limit +``` + +# 快速开始 +```go +package main + +import ( + "fmt" + + "github.com/xiaoqidun/limit" + "golang.org/x/time/rate" +) + +func main() { + // 1. 创建一个新的 Limiter 实例 + limiter := limit.New() + // 2. 确保在程序退出前优雅地停止后台任务,这非常重要 + defer limiter.Stop() + // 3. 为任意键 "some-key" 获取一个速率限制器 + // - rate.Limit(2): 表示速率为 "每秒2个请求" + // - 2: 表示桶的容量 (Burst),允许瞬时处理2个请求 + rateLimiter := limiter.Get("some-key", rate.Limit(2), 2) + // 4. 模拟3次连续的突发请求 + // 由于速率和容量都为2,只有前两次请求能立即成功 + for i := 0; i < 3; i++ { + if rateLimiter.Allow() { + fmt.Printf("请求 %d: 已允许\n", i+1) + } else { + fmt.Printf("请求 %d: 已拒绝\n", i+1) + } + } +} +``` + +# 授权协议 +本项目使用 [Apache License 2.0](https://github.com/xiaoqidun/limit/blob/main/LICENSE) 授权协议 \ No newline at end of file diff --git a/common/utils/limit/example_test.go b/common/utils/limit/example_test.go new file mode 100644 index 00000000..5f96cbba --- /dev/null +++ b/common/utils/limit/example_test.go @@ -0,0 +1,68 @@ +// Copyright 2025 肖其顿 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package limit_test + +import ( + "fmt" + "time" + + "github.com/xiaoqidun/limit" + "golang.org/x/time/rate" +) + +// ExampleLimiter 演示了 limit 包的基本用法。 +func ExampleLimiter() { + // 创建一个使用默认配置的 Limiter 实例 + limiter := limit.New() + // 程序退出前,优雅地停止后台任务,这非常重要 + defer limiter.Stop() + // 为一个特定的测试键获取一个速率限制器 + // 限制为每秒2个请求,最多允许3个并发(桶容量) + testKey := "testKey" + rateLimiter := limiter.Get(testKey, rate.Limit(2), 3) + // 模拟连续的请求 + for i := 0; i < 5; i++ { + if rateLimiter.Allow() { + fmt.Printf("请求 %d: 已允许\n", i+1) + } else { + fmt.Printf("请求 %d: 已拒绝\n", i+1) + } + time.Sleep(100 * time.Millisecond) + } + // 手动移除一个不再需要的限制器 + limiter.Del(testKey) + // Output: + // 请求 1: 已允许 + // 请求 2: 已允许 + // 请求 3: 已允许 + // 请求 4: 已拒绝 + // 请求 5: 已拒绝 +} + +// ExampleNewWithConfig 展示了如何使用自定义配置。 +func ExampleNewWithConfig() { + // 自定义配置 + config := limit.Config{ + ShardCount: 64, // 分片数量,必须是2的幂 + GCInterval: 5 * time.Minute, // GC 检查周期 + Expiration: 15 * time.Minute, // 限制器过期时间 + } + // 使用自定义配置创建一个 Limiter 实例 + customLimiter := limit.NewWithConfig(config) + defer customLimiter.Stop() + fmt.Println("使用自定义配置的限制器已成功创建") + // Output: + // 使用自定义配置的限制器已成功创建 +} diff --git a/common/utils/limit/go.mod b/common/utils/limit/go.mod new file mode 100644 index 00000000..fed5e3c1 --- /dev/null +++ b/common/utils/limit/go.mod @@ -0,0 +1,5 @@ +module github.com/xiaoqidun/limit + +go 1.18 + +require golang.org/x/time v0.8.0 diff --git a/common/utils/limit/go.sum b/common/utils/limit/go.sum new file mode 100644 index 00000000..d06eb417 --- /dev/null +++ b/common/utils/limit/go.sum @@ -0,0 +1,2 @@ +golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= +golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= diff --git a/common/utils/limit/limit.go b/common/utils/limit/limit.go new file mode 100644 index 00000000..fd89e16f --- /dev/null +++ b/common/utils/limit/limit.go @@ -0,0 +1,278 @@ +// Copyright 2025 肖其顿 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package limit 提供了一个高性能、并发安全的动态速率限制器。 +// 它使用分片锁来减少高并发下的锁竞争,并能自动清理长期未使用的限制器。 +package limit + +import ( + "hash" + "hash/fnv" + "sync" + "sync/atomic" + "time" + + "golang.org/x/time/rate" +) + +// defaultShardCount 是默认的分片数量,设为2的幂可以优化哈希计算。 +const defaultShardCount = 32 + +// Config 定义了 Limiter 的可配置项。 +type Config struct { + // ShardCount 指定分片数量,必须是2的幂。如果为0或无效值,则使用默认值32。 + ShardCount int + // GCInterval 指定GC周期,即检查并清理过期限制器的间隔。如果为0,则使用默认值10分钟。 + GCInterval time.Duration + // Expiration 指定过期时间,即限制器在最后一次使用后能存活多久。如果为0,则使用默认值30分钟。 + Expiration time.Duration +} + +// Limiter 是一个高性能、分片实现的动态速率限制器。 +// 它的实例在并发使用时是安全的。 +type Limiter struct { + // 存储所有分片 + shards []*shard + // 配置信息 + config Config + // 标记限制器是否已停止 + stopped atomic.Bool + // 确保Stop方法只执行一次 + stopOnce sync.Once +} + +// New 使用默认配置创建一个新的 Limiter 实例。 +func New() *Limiter { + return NewWithConfig(Config{}) +} + +// NewWithConfig 根据提供的配置创建一个新的 Limiter 实例。 +func NewWithConfig(config Config) *Limiter { + // 如果未设置,则使用默认值 + if config.ShardCount == 0 { + config.ShardCount = defaultShardCount + } + if config.GCInterval == 0 { + config.GCInterval = 10 * time.Minute + } + if config.Expiration == 0 { + config.Expiration = 30 * time.Minute + } + // 确保分片数量是2的幂,以便进行高效的位运算 + if config.ShardCount <= 0 || (config.ShardCount&(config.ShardCount-1)) != 0 { + config.ShardCount = defaultShardCount + } + l := &Limiter{ + shards: make([]*shard, config.ShardCount), + config: config, + } + // 初始化所有分片 + for i := 0; i < config.ShardCount; i++ { + l.shards[i] = newShard(config.GCInterval, config.Expiration) + } + return l +} + +// Get 获取或创建一个与指定键关联的速率限制器。 +// 如果限制器已存在,它会根据传入的 r (速率) 和 b (并发数) 更新其配置。 +// 如果 Limiter 实例已被 Stop 方法关闭,此方法将返回 nil。 +func (l *Limiter) Get(k string, r rate.Limit, b int) *rate.Limiter { + // 快速路径检查,避免在已停止时进行哈希和查找 + if l.stopped.Load() { + return nil + } + // 定位到具体分片进行操作 + return l.getShard(k).get(k, r, b) +} + +// Del 手动移除一个与指定键关联的速率限制器。 +// 如果 Limiter 实例已被 Stop 方法关闭,此方法不执行任何操作。 +func (l *Limiter) Del(k string) { + // 快速路径检查 + if l.stopped.Load() { + return + } + // 定位到具体分片进行操作 + l.getShard(k).del(k) +} + +// Stop 停止 Limiter 的所有后台清理任务,并释放相关资源。 +// 此方法对于并发调用是安全的,并且可以被多次调用。 +func (l *Limiter) Stop() { + l.stopOnce.Do(func() { + l.stopped.Store(true) + for _, s := range l.shards { + s.stop() + } + }) +} + +// getShard 根据key的哈希值获取对应的分片。 +func (l *Limiter) getShard(key string) *shard { + hasher := fnvHasherPool.Get().(hash.Hash32) + defer func() { + hasher.Reset() + fnvHasherPool.Put(hasher) + }() + _, _ = hasher.Write([]byte(key)) // FNV-1a never returns an error. + // 使用位运算代替取模,提高效率 + return l.shards[hasher.Sum32()&(uint32(l.config.ShardCount)-1)] +} + +// shard 代表 Limiter 的一个分片,它包含独立的锁和数据,以减少全局锁竞争。 +type shard struct { + mutex sync.Mutex + stopCh chan struct{} + limiter map[string]*session + stopOnce sync.Once + waitGroup sync.WaitGroup +} + +// newShard 创建一个新的分片实例,并启动其gc任务。 +func newShard(gcInterval, expiration time.Duration) *shard { + s := &shard{ + // mutex 会被自动初始化为其零值(未锁定状态) + stopCh: make(chan struct{}), + limiter: make(map[string]*session), + } + s.waitGroup.Add(1) + go s.gc(gcInterval, expiration) + return s +} + +// gc 定期清理分片中过期的限制器。 +func (s *shard) gc(interval, expiration time.Duration) { + defer s.waitGroup.Done() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + // 优先检查停止信号,确保能快速响应 + select { + case <-s.stopCh: + return + default: + } + select { + case <-ticker.C: + s.mutex.Lock() + // 再次检查分片是否已停止,防止在等待锁期间被停止 + if s.limiter == nil { + s.mutex.Unlock() + return + } + for k, v := range s.limiter { + // 清理过期的限制器 + if time.Since(v.lastGet) > expiration { + // 将 session 对象放回池中前,重置其状态 + v.limiter = nil + v.lastGet = time.Time{} + sessionPool.Put(v) + delete(s.limiter, k) + } + } + s.mutex.Unlock() + case <-s.stopCh: + // 收到停止信号,退出goroutine + return + } + } +} + +// get 获取或创建一个新的速率限制器,如果已存在则更新其配置。 +func (s *shard) get(k string, r rate.Limit, b int) *rate.Limiter { + s.mutex.Lock() + defer s.mutex.Unlock() + // 检查分片是否已停止 + if s.limiter == nil { + return nil + } + sess, ok := s.limiter[k] + if !ok { + // 从池中获取 session 对象 + sess = sessionPool.Get().(*session) + sess.limiter = rate.NewLimiter(r, b) + s.limiter[k] = sess + } else { + // 如果已存在,则更新其速率和并发数 + sess.limiter.SetLimit(r) + sess.limiter.SetBurst(b) + } + sess.lastGet = time.Now() + return sess.limiter +} + +// del 从分片中移除一个键的速率限制器。 +func (s *shard) del(k string) { + s.mutex.Lock() + defer s.mutex.Unlock() + // 检查分片是否已停止 + if s.limiter == nil { + return + } + if sess, ok := s.limiter[k]; ok { + // 将 session 对象放回池中前,重置其状态 + sess.limiter = nil + sess.lastGet = time.Time{} + sessionPool.Put(sess) + delete(s.limiter, k) + } +} + +// stop 停止分片的gc任务,并同步等待其完成后再清理资源。 +func (s *shard) stop() { + // 使用 sync.Once 确保 channel 只被关闭一次,彻底避免并发风险 + s.stopOnce.Do(func() { + close(s.stopCh) + }) + // 等待 gc goroutine 完全退出 + s.waitGroup.Wait() + // 锁定并进行最终的资源清理 + // 因为 gc 已经退出,所以此时只有 Get/Del 会竞争锁 + s.mutex.Lock() + defer s.mutex.Unlock() + // 检查是否已被清理,防止重复操作 + if s.limiter == nil { + return + } + // 将所有 session 对象放回对象池 + for _, sess := range s.limiter { + sess.limiter = nil + sess.lastGet = time.Time{} + sessionPool.Put(sess) + } + // 清理map,释放内存,并作为停止标记 + s.limiter = nil +} + +// session 存储每个键的速率限制器实例和最后访问时间。 +type session struct { + // 最后一次访问时间 + lastGet time.Time + // 速率限制器 + limiter *rate.Limiter +} + +// sessionPool 使用 sync.Pool 来复用 session 对象,以减少 GC 压力。 +var sessionPool = sync.Pool{ + New: func() interface{} { + return new(session) + }, +} + +// fnvHasherPool 使用 sync.Pool 来复用 FNV-1a 哈希对象,以减少高并发下的内存分配。 +var fnvHasherPool = sync.Pool{ + New: func() interface{} { + return fnv.New32a() + }, +} diff --git a/common/utils/limit/limit_test.go b/common/utils/limit/limit_test.go new file mode 100644 index 00000000..9b5e43e5 --- /dev/null +++ b/common/utils/limit/limit_test.go @@ -0,0 +1,95 @@ +// Copyright 2025 肖其顿 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package limit + +import ( + "fmt" + "sync" + "testing" + "time" + + "golang.org/x/time/rate" +) + +// TestLimiter 覆盖了 Limiter 的主要功能。 +func TestLimiter(t *testing.T) { + // 子测试:验证基本的允许/拒绝逻辑 + t.Run("基本功能测试", func(t *testing.T) { + limiter := New() + defer limiter.Stop() + key := "测试键" + // 创建一个每秒2个令牌,桶容量为1的限制器 + rl := limiter.Get(key, rate.Limit(2), 1) + if rl == nil { + t.Fatal("limiter.Get() 意外返回 nil,测试无法继续") + } + if !rl.Allow() { + t.Error("rl.Allow(): 首次调用应返回 true, 实际为 false") + } + if rl.Allow() { + t.Error("rl.Allow(): 超出突发容量的调用应返回 false, 实际为 true") + } + time.Sleep(500 * time.Millisecond) + if !rl.Allow() { + t.Error("rl.Allow(): 令牌补充后的调用应返回 true, 实际为 false") + } + }) + + // 子测试:验证 Del 方法的功能 + t.Run("删除功能测试", func(t *testing.T) { + limiter := New() + defer limiter.Stop() + key := "测试键" + rl1 := limiter.Get(key, rate.Limit(2), 1) + if !rl1.Allow() { + t.Fatal("获取限制器后的首次 Allow() 调用失败") + } + limiter.Del(key) + rl2 := limiter.Get(key, rate.Limit(2), 1) + if !rl2.Allow() { + t.Error("Del() 后重新获取的限制器未能允许请求") + } + }) + + // 子测试:验证 Stop 方法的功能 + t.Run("停止功能测试", func(t *testing.T) { + limiter := New() + limiter.Stop() + if rl := limiter.Get("任意键", 1, 1); rl != nil { + t.Error("Stop() 后 Get() 应返回 nil, 实际返回了有效实例") + } + // 多次调用 Stop 不应引发 panic + limiter.Stop() + }) + + // 子测试:验证并发安全性 + t.Run("并发安全测试", func(t *testing.T) { + limiter := New() + defer limiter.Stop() + var wg sync.WaitGroup + numGoroutines := 100 + for i := 0; i < numGoroutines; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + key := fmt.Sprintf("并发测试键-%d", i) + if limiter.Get(key, rate.Limit(10), 5) == nil { + t.Errorf("并发获取键 '%s' 时, Get() 意外返回 nil", key) + } + }(i) + } + wg.Wait() + }) +} diff --git a/go.work b/go.work index df7fa9f5..51d741e7 100644 --- a/go.work +++ b/go.work @@ -13,6 +13,7 @@ use ( ./common/utils/go-jsonrpc ./common/utils/go-sensitive-word-1.3.3 ./common/utils/goja + ./common/utils/limit ./common/utils/log ./common/utils/sturc ./common/utils/xml diff --git a/logic/controller/fight.go b/logic/controller/fight.go index 59526ff5..5170662c 100644 --- a/logic/controller/fight.go +++ b/logic/controller/fight.go @@ -157,13 +157,13 @@ func (h Controller) ChangePet(data *fight.ChangePetInboundInfo, c *player.Player // 切换精灵 func (h Controller) Capture(data *fight.CatchMonsterInboundInfo, c *player.Player) (result *info.CatchMonsterOutboundInfo, err errorcode.ErrorCode) { - c.FightC.Capture(c, (data.CapsuleId)) + c.FightC.Capture(c, data.CapsuleId) return nil, -1 } -// 切换精灵 +// 加载进度 func (h Controller) LoadPercent(data *fight.LoadPercentInboundInfo, c *player.Player) (result *info.LoadPercentOutboundInfo, err errorcode.ErrorCode) { - c.FightC.LoadPercent(c, (int32(data.Percent))) + c.FightC.LoadPercent(c, int32(data.Percent)) return nil, -1 } diff --git a/logic/controller/item.go b/logic/controller/item.go index d95fc413..9c8bee58 100644 --- a/logic/controller/item.go +++ b/logic/controller/item.go @@ -50,13 +50,16 @@ func (h Controller) BuyItem(data *item.BuyInboundInfo, c *player.Player) (result if (data.Count * uint32(tt.Price)) <= c.Info.Coins { c.Info.Coins -= data.Count * uint32(tt.Price) - c.ItemAdd(model.SingleItemInfo{ItemId: data.ItemId, ItemCnt: data.Count}) - return &item.BuyOutboundInfo{ - ItemId: data.ItemId, - Level: 1, - Count: data.Count, - Coins: c.Info.Coins, - }, 0 + r := c.ItemAdd(model.SingleItemInfo{ItemId: data.ItemId, ItemCnt: data.Count}) + if len(r) != 0 { + return &item.BuyOutboundInfo{ + ItemId: data.ItemId, + Level: 1, + Count: data.Count, + Coins: c.Info.Coins, + }, 0 + } + } } @@ -77,7 +80,7 @@ func (h Controller) ChangePlayerCloth(data *item.ChangePlayerClothInboundInfo, c result.ClothList = append(result.ClothList, model.PeopleItemInfo{ID: v, Level: 1}) } c.Info.Clothes = result.ClothList - defer space.GetSpace(c.Info.MapID).User.IterCb(func(playerID uint32, player common.PlayerI) { + space.GetSpace(c.Info.MapID).User.IterCb(func(playerID uint32, player common.PlayerI) { // fmt.Println("ChangePlayerCloth", playerID, data.Head.Pack(result)) data.Head.Result = 0 player.SendPack(data.Head.Pack(result)) @@ -140,3 +143,25 @@ func (h Controller) TalkCate(data *item.TalkCateInboundInfo, c *player.Player) ( return result, 0 } +func (h Controller) BuyMItem(data *item.BuyMultiInboundInfo, c *player.Player) (result *item.BuyMultiOutboundInfo, err errorcode.ErrorCode) { + var rrr []model.SingleItemInfo + for _, v := range data.ItemIds { + _, ok := xmlres.ItemsMAP[int(v)] + + if ok { + rrr = append(rrr, model.SingleItemInfo{ItemId: uint32(v), ItemCnt: 1}) + + } + } + r := c.ItemAdd(rrr...) + if len(r) != 0 { + return &item.BuyMultiOutboundInfo{ + + Coins: c.Info.Coins, + }, 0 + } + return &item.BuyMultiOutboundInfo{ + + Coins: c.Info.Coins, + }, 0 +} diff --git a/logic/controller/pet.go b/logic/controller/pet.go index 8aaf3c6b..140a750d 100644 --- a/logic/controller/pet.go +++ b/logic/controller/pet.go @@ -3,6 +3,7 @@ package controller import ( "blazing/common/data/xmlres" "blazing/common/socket/errorcode" + "blazing/common/utils" "blazing/logic/service/pet" "blazing/logic/service/player" @@ -122,7 +123,7 @@ func (h *Controller) PlayerShowPet( func (h *Controller) PetOneCure( data *pet.PetOneCureInboundInfo, c *player.Player) (result *pet.PetOneCureOutboundInfo, err errorcode.ErrorCode) { //这个时候player应该是空的 - _, onpet, ok := FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { + _, onpet, ok := utils.FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { return item.CatchTime == data.CatchTime }) if ok { @@ -158,16 +159,9 @@ func (h *Controller) PetFirst( // FindWithIndex 遍历slice,找到第一个满足条件的元素 // 返回:索引、元素指针、是否找到 -func FindWithIndex[T any](slice []T, predicate func(item T) bool) (int, *T, bool) { - for i := range slice { - if predicate(slice[i]) { - return i, &slice[i], true - } - } - return -1, nil, false -} + func (h Controller) SetPetExp(data *pet.PetSetExpInboundInfo, c *player.Player) (result *pet.PetSetExpOutboundInfo, err errorcode.ErrorCode) { - _, onpet, ok := FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { + _, onpet, ok := utils.FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { return item.CatchTime == data.CatchTime }) if ok { @@ -180,11 +174,11 @@ func (h Controller) SetPetExp(data *pet.PetSetExpInboundInfo, c *player.Player) }, 0 } func (h Controller) SetPetSkill(data *pet.ChangeSkillInfo, c *player.Player) (result *pet.ChangeSkillOutInfo, err errorcode.ErrorCode) { - _, onpet, ok := FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { + _, onpet, ok := utils.FindWithIndex(c.Info.PetList, func(item model.PetInfo) bool { return item.CatchTime == data.CatchTime }) if ok { - for i := 0; i < 4; i++ { + for i := 0; i < len(onpet.SkillList); i++ { if onpet.SkillList[i].ID == data.HasSkill { onpet.SkillList[i].ID = data.ReplaceSkill onpet.SkillList[i].PP = uint32(xmlres.SkillMap[int(onpet.SkillList[i].ID)].MaxPP) diff --git a/logic/controller/task.go b/logic/controller/task.go index c797adc3..97482e8e 100644 --- a/logic/controller/task.go +++ b/logic/controller/task.go @@ -104,7 +104,7 @@ func (h Controller) Complete_Task(data *task.CompleteTaskInboundInfo, c *player. // out_id=1的奖励物品 result.ItemList = append(result.ItemList, task.ItemInfo{ItemId: 300001, ItemCount: 5}, // 普通胶囊x5 - task.ItemInfo{ItemId: 300011, ItemCount: 3}, // 初级体力药剂x3 + task.ItemInfo{ItemId: 300011, ItemCount: 5}, // 初级体力药剂x3 ) // 新手任务4 @@ -548,7 +548,18 @@ func (h Controller) Complete_Task(data *task.CompleteTaskInboundInfo, c *player. for _, v := range result.ItemList { ttt = append(ttt, model.SingleItemInfo{ItemId: v.ItemId, ItemCnt: v.ItemCount}) } - c.ItemAdd(ttt...) + r := c.ItemAdd(ttt...) + tempItemList := make([]task.ItemInfo, 0) + for _, v := range result.ItemList { + for _, v1 := range r { + if v1.ItemId == v.ItemId { + tempItemList = append(tempItemList, task.ItemInfo{ItemId: v.ItemId, ItemCount: v.ItemCount}) + } + + } + + } + result.ItemList = tempItemList //临时变量为了防止报错的时候返回数据没问题 return result, 0 } diff --git a/logic/main.go b/logic/main.go index 84818e11..44ad2155 100644 --- a/logic/main.go +++ b/logic/main.go @@ -10,6 +10,7 @@ import ( _ "blazing/contrib/drivers/pgsql" "blazing/logic/service/fight" + "blazing/logic/service/player" "blazing/cool" @@ -30,6 +31,12 @@ func PprofWeb() { } func signalHandlerForMain(sig os.Signal) { fight.Fightpool.Release() + + player.Mainplayer.Range(func(key uint32, value *player.Player) bool { + value.Save() + + return true + }) fmt.Println("MainProcess is shutting down due to signal:", sig.String()) } diff --git a/logic/service/fight/action/BattleAction.go b/logic/service/fight/action/BattleAction.go index 2d534435..57f4ca96 100644 --- a/logic/service/fight/action/BattleAction.go +++ b/logic/service/fight/action/BattleAction.go @@ -32,9 +32,8 @@ type BattleActionI interface { // SelectSkillAction 选择技能的战斗动作 type SelectSkillAction struct { - ID uint32 //技能ID BaseAction - Skill *info.SkillEntity // 使用的技能 + *info.SkillEntity // 使用的技能 //PetInfo *info.BattlePetEntity // 使用技能的宠物 Attack info.AttackValue } diff --git a/logic/service/fight/action/help.go b/logic/service/fight/action/help.go new file mode 100644 index 00000000..a9d91c91 --- /dev/null +++ b/logic/service/fight/action/help.go @@ -0,0 +1,11 @@ +package action + +func CanUse(s *SelectSkillAction) bool { + if s == nil { + return false + + } + + return s.Info.PP > 0 + +} diff --git a/logic/service/fight/effect/effect_1.go b/logic/service/fight/effect/effect_1.go index 2d54570b..922d04a5 100644 --- a/logic/service/fight/effect/effect_1.go +++ b/logic/service/fight/effect/effect_1.go @@ -2,7 +2,6 @@ package effect import ( "blazing/logic/service/fight/action" - "blazing/logic/service/fight/info" "blazing/logic/service/fight/input" "blazing/logic/service/fight/node" @@ -18,16 +17,19 @@ type Effect1 struct { func init() { ret := &Effect1{} - ret.Effect = ret + input.InitEffect(input.EffectType.Skill, 1, ret) } // 命中之后 -func (e *Effect1) OnHit(opp *input.Input, skill *info.SkillEntity) { +func (e *Effect1) OnSkill(ctx input.Ctx) bool { + if !e.Hit() { + return true + } e.Input.Heal( &action.SelectSkillAction{}, e.Input.DamageZone.Damage.Div(decimal.NewFromInt(2)), ) - + return true } diff --git a/logic/service/fight/effect/effect_10-16_94_99_114.go b/logic/service/fight/effect/effect_10-16_94_99_114.go index c4fca3bd..f1d97912 100644 --- a/logic/service/fight/effect/effect_10-16_94_99_114.go +++ b/logic/service/fight/effect/effect_10-16_94_99_114.go @@ -16,7 +16,6 @@ func newp(t1 info.EnumBattleStatus) *Effect10 { Status: t1, } - t.Effect = t return t } @@ -51,7 +50,7 @@ func init() { input.InitEffect(input.EffectType.Skill, 114, newp(info.PetStatus.Flammable)) } -func (e *Effect10) OnHit(opp *input.Input, skill *info.SkillEntity) { +func (e *Effect10) OnSkill(ctx input.Ctx) bool { t, _, _ := e.Input.Player.Roll(e.EffectNode.SideEffectArgs[0], 100) if t { @@ -61,11 +60,11 @@ func (e *Effect10) OnHit(opp *input.Input, skill *info.SkillEntity) { if eff.ID != 0 { eff.Effect.Duration(int(t1)) - opp.AddEffect(eff) + ctx.AddEffect(eff) } } - + return true } func (e *Effect10) OnMiss(opp *input.Input, skill *info.SkillEntity) { diff --git a/logic/service/fight/effect/effect_3_33_63__85_145.go b/logic/service/fight/effect/effect_3_33_63__85_145.go index a9cc1047..d850b739 100644 --- a/logic/service/fight/effect/effect_3_33_63__85_145.go +++ b/logic/service/fight/effect/effect_3_33_63__85_145.go @@ -13,16 +13,20 @@ type Effect3 struct { Etype info.EnumAbilityOpType } -func (e *Effect3) OnHit(opp *input.Input, skill *info.SkillEntity) { +func (e *Effect3) OnSkill(ctx input.Ctx) bool { + + if !e.Hit() { + return true + } for i := 0; i < 6; i++ { if e.Rev { - opp.SetProp(e.Input, int8(i), e.Level, e.Etype) + ctx.SetProp(e.Input, int8(i), e.Level, e.Etype) } else { - e.Input.SetProp(opp, int8(i), e.Level, e.Etype) + e.Input.SetProp(ctx.Input, int8(i), e.Level, e.Etype) } } - + return true } func neweffect3(rev bool, level int8, etype info.EnumAbilityOpType) *Effect3 { @@ -31,7 +35,7 @@ func neweffect3(rev bool, level int8, etype info.EnumAbilityOpType) *Effect3 { Level: level, Etype: etype, } - ret.Effect = ret + return ret } func init() { diff --git a/logic/service/fight/effect/effect_4_5.go b/logic/service/fight/effect/effect_4_5.go index e6b18922..d5d4a152 100644 --- a/logic/service/fight/effect/effect_4_5.go +++ b/logic/service/fight/effect/effect_4_5.go @@ -20,7 +20,7 @@ func NewEffectStat(b bool) input.Effect { EffectNode: node.EffectNode{}, Etype: b, } - ret.Effect = ret + return ret } @@ -40,11 +40,13 @@ type EffectStat struct { // addrA := unsafe.Pointer(baseAddr + 4) //根据攻击算其他字段 // *(*uint32)(addrA) = 100 // } -func (e *EffectStat) OnHit(opp *input.Input, skill *info.SkillEntity) { - +func (e *EffectStat) OnSkill(ctx input.Ctx) bool { + if !e.Hit() { + return true + } t, _, _ := e.Input.Player.Roll(e.EffectNode.SideEffectArgs[1], 100) if !t { //没触发 - return + return true } ptype := info.AbilityOpType.ADD if e.EffectNode.SideEffectArgs[2] < 0 { @@ -54,7 +56,7 @@ func (e *EffectStat) OnHit(opp *input.Input, skill *info.SkillEntity) { e.Input.SetProp(e.Input, int8(e.EffectNode.SideEffectArgs[0]), int8(e.EffectNode.SideEffectArgs[2]), ptype) } else { //对方 - opp.SetProp(e.Input, int8(e.EffectNode.SideEffectArgs[0]), int8(e.EffectNode.SideEffectArgs[2]), ptype) + ctx.SetProp(e.Input, int8(e.EffectNode.SideEffectArgs[0]), int8(e.EffectNode.SideEffectArgs[2]), ptype) } - + return true } diff --git a/logic/service/fight/effect/effect_62.go b/logic/service/fight/effect/effect_62.go index 0fe5e60d..5a4b5eca 100644 --- a/logic/service/fight/effect/effect_62.go +++ b/logic/service/fight/effect/effect_62.go @@ -1,7 +1,6 @@ package effect import ( - "blazing/logic/service/fight/info" "blazing/logic/service/fight/input" "blazing/logic/service/fight/node" ) @@ -21,12 +20,15 @@ func init() { Owner: true, }, } - t.Effect = t + input.InitEffect(input.EffectType.Skill, 62, t) } -func (e *Effect62) OnHit(*input.Input, *info.SkillEntity) { +func (e *Effect62) OnSkill(ctx input.Ctx) bool { + if !e.Hit() { + return true + } if e.Duration() != 1 { //说明还没到生效节点 e.Hide = true //隐藏效果 } else { @@ -42,7 +44,7 @@ func (e *Effect62) OnHit(*input.Input, *info.SkillEntity) { //否则触发秒杀 在对面使用技能后 //return true } - + return false } // 默认添加回合 diff --git a/logic/service/fight/effect/effect_status.go b/logic/service/fight/effect/effect_status.go index 7ef00dfd..8e4dfc7b 100644 --- a/logic/service/fight/effect/effect_status.go +++ b/logic/service/fight/effect/effect_status.go @@ -19,11 +19,28 @@ type StatusNotSkill struct { } // 不能出手 -func (e *StatusNotSkill) Skill_Hit_Pre(input.Ctx) bool { +func (e *StatusNotSkill) Skill_Hit_Pre(ctx input.Ctx) bool { + if e.EffectStatus.Status == info.PetStatus.Sleep { + + ctx.AddEffect(&input.EffectID{ //对对方添加出手解除效果 + ID: -1, + Effect: &StatusSleep{}, + }) + + } return false } +type StatusSleep struct { //睡眠不能出手 ,这个挂载到对面来实现对方攻击后解除睡眠效果 + node.EffectNode +} + +func (e *StatusSleep) Skill_Useed(input.Ctx) bool { + + return true +} + // 扣血类 type DrainHP struct { EffectStatus @@ -65,9 +82,9 @@ func init() { } input.InitEffect(input.EffectType.Status, int(info.PetStatus.DrainHP), &EffectStatus{}) //寄生种子 - tt(info.PetStatus.Paralysis, &StatusNotSkill{}) - tt(info.PetStatus.Tired, &StatusNotSkill{}) - tt(info.PetStatus.Fear, &StatusNotSkill{}) - tt(info.PetStatus.Petrified, &StatusNotSkill{}) - + tt(info.PetStatus.Paralysis, &StatusNotSkill{}) //麻痹 + tt(info.PetStatus.Tired, &StatusNotSkill{}) //疲惫 + tt(info.PetStatus.Fear, &StatusNotSkill{}) //害怕 + tt(info.PetStatus.Petrified, &StatusNotSkill{}) //石化 + input.InitEffect(input.EffectType.Status, 8, &StatusSleep{}) //睡眠 } diff --git a/logic/service/fight/fightc.go b/logic/service/fight/fightc.go index 26183f0c..0d9353a7 100644 --- a/logic/service/fight/fightc.go +++ b/logic/service/fight/fightc.go @@ -1,11 +1,13 @@ package fight import ( + "blazing/common/utils" "blazing/logic/service/common" "blazing/logic/service/fight/action" "blazing/logic/service/fight/info" "blazing/logic/service/fight/input" "blazing/logic/service/player" + "blazing/modules/blazing/model" "fmt" "math/rand" "reflect" @@ -329,27 +331,12 @@ func (f *FightC) battleLoop() { // 如果后手不是技能,替换成空技能(放弃出手) if _, ok := BattleActionI[1].(*action.SelectSkillAction); !ok { - BattleActionI[1] = &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(BattleActionI[1].GetPlayerID()), - } - f.enterturn(&action.SelectSkillAction{ //双方均放弃出手 - ID: 0, - BaseAction: action.NewBaseAction(BattleActionI[1].GetPlayerID()), - }, - &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(BattleActionI[0].GetPlayerID()), - }) + f.enterturn(nil, nil) //双方都不出手 } else { - - f.enterturn(BattleActionI[1].(*action.SelectSkillAction), //后手方先手,先手方放弃出手 - &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(BattleActionI[0].GetPlayerID()), - }) + //后手方先手,先手方放弃出手 + f.enterturn(BattleActionI[1].(*action.SelectSkillAction), nil) } @@ -385,45 +372,15 @@ func (f *FightC) battleLoop() { fmt.Println("ItemID 不在指定范围内") } - // 回合逻辑:另一方只要不是技能,也放弃出手 - leftAction := BattleActionI[0] - rightAction := BattleActionI[1] - - if _, ok := rightAction.(*action.SelectSkillAction); !ok { - rightAction = &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(rightAction.GetPlayerID()), - } + if _, ok := BattleActionI[1].(*action.SelectSkillAction); !ok { + f.enterturn(nil, nil) + } else { + f.enterturn(BattleActionI[1].(*action.SelectSkillAction), nil) } - if _, ok := leftAction.(*action.SelectSkillAction); !ok { - leftAction = &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(leftAction.GetPlayerID()), - } - } - - f.enterturn(leftAction.(*action.SelectSkillAction), rightAction.(*action.SelectSkillAction)) - default: // 双方都是技能或者默认情况 - leftAction := BattleActionI[0] - rightAction := BattleActionI[1] - // 双方只要不是技能,就放弃出手 - if _, ok := leftAction.(*action.SelectSkillAction); !ok { - leftAction = &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(leftAction.GetPlayerID()), - } - } - if _, ok := rightAction.(*action.SelectSkillAction); !ok { - rightAction = &action.SelectSkillAction{ - ID: 0, - BaseAction: action.NewBaseAction(rightAction.GetPlayerID()), - } - } - - f.enterturn(leftAction.(*action.SelectSkillAction), rightAction.(*action.SelectSkillAction)) + f.enterturn(BattleActionI[0].(*action.SelectSkillAction), BattleActionI[1].(*action.SelectSkillAction)) } } @@ -436,28 +393,28 @@ func (f *FightC) processSkillAttack(attacker, defender *input.Input, a *action.S attacker.Exec(func(t input.Effect) bool { //计算命中 miss改命中 t.Skill_Hit_Pre(input.Ctx{ //调基础命中 - Input: defender, - SkillEntity: a.Skill, + Input: defender, + SelectSkillAction: a, }) //相当于先调整基础命中,不光调整命中,这里还能调整技能属性,暴击率 return true }) - a.Skill.AttackTimeC(attacker.GetProp(5, true)) //计算命中 - defender.Exec(func(t input.Effect) bool { //计算闪避 ,然后修改对方命中),同时相当于计算属性无效这种 + a.AttackTimeC(attacker.GetProp(5, true)) //计算命中 + defender.Exec(func(t input.Effect) bool { //计算闪避 ,然后修改对方命中),同时相当于计算属性无效这种 t.Skill_Hit_to(input.Ctx{ //计算命中后,我方强制改命中效果 - Input: attacker, - SkillEntity: a.Skill, + Input: attacker, + SelectSkillAction: a, }) return true }) - attacker.AttackValue.AttackTime = a.Skill.AttackTime //是否命中赋值 - attacker.Exec(func(t input.Effect) bool { //计算命中 miss改命中 + attacker.AttackValue.AttackTime = a.AttackTime //是否命中赋值 + attacker.Exec(func(t input.Effect) bool { //计算命中 miss改命中 t.Skill_Hit(input.Ctx{ //计算变威力 - Input: attacker, - SkillEntity: a.Skill, + Input: attacker, + SelectSkillAction: a, }) //相当于先调整基础命中,不光调整命中,这里还能调整技能属性,暴击率 return true @@ -466,20 +423,20 @@ func (f *FightC) processSkillAttack(attacker, defender *input.Input, a *action.S //技能miss+效果生效 这里属于强制改命中效果,但是正常来说,技能miss掉后效果也应该失效 //技能失效+效果失效 // 记录技能信息 - attacker.AttackValue.SkillID = uint32(a.Skill.ID) //获取技能ID - if attacker.AttackValue.AttackTime > 0 { //如果命中 - attacker.UseSkill(defender, a.Skill) //暴击计算 - attacker.AttackValue.IsCritical = a.Skill.Crit + attacker.AttackValue.SkillID = uint32(a.ID) //获取技能ID + if attacker.AttackValue.AttackTime > 0 { //如果命中 + attacker.UseSkill(defender, a) //暴击计算 + attacker.AttackValue.IsCritical = a.Crit attacker.Exec(func(t input.Effect) bool { //计算命中 miss改命中 t.Calculate_Pre(input.Ctx{ //计算视为效果 - Input: defender, - SkillEntity: a.Skill, + Input: defender, + SelectSkillAction: a, }) //相当于先调整基础命中,不光调整命中,这里还能调整技能属性,暴击率 return true }) - attacker.DamageZone.Damage = attacker.CalculatePower(defender, a.Skill) + attacker.DamageZone.Damage = attacker.CalculatePower(defender, a.SkillEntity) if attacker.AttackValue.IsCritical == 1 { @@ -488,16 +445,14 @@ func (f *FightC) processSkillAttack(attacker, defender *input.Input, a *action.S } - } else { - } for _, e := range attacker.EffectCache { //这里实现应该参考本地技能是否命中,然后 - e.Hit(a.Skill.AttackTime != 0) //我方效果命中 + e.Hit(a.AttackTime != 0) //我方效果命中 } for _, t := range defender.EffectCache { if t.GetInput() == attacker { //如果取反,说明是给对方添加的回合效果 - t.Hit(a.Skill.AttackTime != 0) + t.Hit(a.AttackTime != 0) } } @@ -505,8 +460,8 @@ func (f *FightC) processSkillAttack(attacker, defender *input.Input, a *action.S attacker.Exec(func(t input.Effect) bool { t.OnSkill(input.Ctx{ - Input: defender, - SkillEntity: a.Skill, + Input: defender, + SelectSkillAction: a, }) //调用伤害计算 return true @@ -516,7 +471,7 @@ func (f *FightC) processSkillAttack(attacker, defender *input.Input, a *action.S Input: attacker, - SkillEntity: a.Skill, + SelectSkillAction: a, DamageZone: &info.DamageZone{ Type: info.DamageType.Red, Damage: attacker.DamageZone.Damage, @@ -533,6 +488,12 @@ func IsNil(x interface{}) bool { rv := reflect.ValueOf(x) return rv.Kind() == reflect.Ptr && rv.IsNil() } +func copyskill(t *action.SelectSkillAction) *action.SelectSkillAction { + + oldskill, _ := deepcopy.Anything(t) //备份技能 + + return oldskill.(*action.SelectSkillAction) +} //回合有先手方和后手方,同时有攻击方和被攻击方 @@ -554,10 +515,9 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { } f.First.InitAttackValue() f.Second.InitAttackValue() - fmt.Println("房主", fattack.ID, "挑战者", sattack.ID) switch { - case sattack.ID != 0: + case sattack != nil: f.Second.Parseskill(f.Second, sattack) //解析到临时数据 @@ -568,7 +528,7 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { return true }) switch { - case fattack.ID != 0: //房主也放弃出手 + case fattack != nil: //房主也放弃出手 //是否miss都应该施加解析effect f.First.Parseskill(f.Second, fattack) //解析到临时数据 @@ -580,11 +540,11 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { }) switch { - case fattack.Skill.Priority < sattack.Skill.Priority: + case fattack.SkillEntity.Priority < sattack.SkillEntity.Priority: fattack, sattack = sattack, fattack //互换先手权 f.First, f.Second = f.Second, f.First - case fattack.Skill.Priority == sattack.Skill.Priority: + case fattack.SkillEntity.Priority == sattack.SkillEntity.Priority: if f.Second.GetProp(4, false) > f.First.GetProp(4, false) { fattack, sattack = sattack, fattack //互换先手权 @@ -615,25 +575,28 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { }) //开始回合操作 for i := 0; i < 2; i++ { - var oldskill interface{} - if i == 0 { // + var oldskill *action.SelectSkillAction //原始技能 + var currentskill *action.SelectSkillAction //当前技能 + if i == 0 { // attacker, defender = f.First, f.Second + oldskill = copyskill(fattack) + currentskill = fattack - oldskill, _ = deepcopy.Anything(fattack.Skill) //备份技能 } else { attacker, defender = f.Second, f.First - oldskill, _ = deepcopy.Anything(sattack.Skill) //备份技能 + oldskill = copyskill(sattack) + currentskill = sattack } canuseskill := true // 实际上攻击方 还有系统选择放弃出手的 - if IsNil(oldskill) || attacker.CurrentPet.Info.Hp <= 0 { + if IsNil(currentskill) || attacker.CurrentPet.Info.Hp <= 0 { // attacker.AttackValue.SkillID = 0 canuseskill = false } else { - if !oldskill.(*info.SkillEntity).CanUse() { + if !action.CanUse(currentskill) { // attacker.AttackValue.SkillID = 0 canuseskill = false } @@ -643,20 +606,21 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { //结算状态 //然后这里还可以处理自爆类 return t.Skill_Hit_Pre(input.Ctx{ - Input: attacker, - SkillEntity: fattack.Skill, + Input: defender, + SelectSkillAction: currentskill, }) //返回本身结算,如果false,说明不能使用技能了 }) if canuseskill && canuseskillok { //可以使用技能 - if i == 0 { // - f.processSkillAttack(attacker, defender, fattack) - fattack.Skill = oldskill.(*info.SkillEntity) //还原技能效果 - fattack.Skill.Info.PP-- //减少PP - } else { - f.processSkillAttack(attacker, defender, sattack) - sattack.Skill = oldskill.(*info.SkillEntity) //还原技能效果 - sattack.Skill.Info.PP-- //减少PP + + f.processSkillAttack(attacker, defender, currentskill) + currentskill = oldskill + _, skill, ok := utils.FindWithIndex(attacker.CurrentPet.Info.SkillList, func(item model.SkillInfo) bool { + return item.ID == currentskill.Info.ID + }) + if ok { + + skill.PP-- } } @@ -668,6 +632,13 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { return true }) + //技能使用后 + attacker.Exec(func(t input.Effect) bool { //技能使用后的我方效果 + t.Skill_Useed(input.Ctx{Input: defender, SelectSkillAction: currentskill}) + + return true + }) + fmt.Println(i, // "玩家技能:", oldskill.(*info.SkillEntity).ID, "玩家技能伤害:", attacker.DamageZone.Damage, @@ -715,6 +686,9 @@ func (f *FightC) enterturn(fattack, sattack *action.SelectSkillAction) { return true }) f.First.AttackValue.RemainHp = int32(f.First.CurrentPet.Info.Hp) + f.First.AttackValue.SkillList = f.First.CurrentPet.Info.SkillList + + f.Second.AttackValue.SkillList = f.Second.CurrentPet.Info.SkillList f.Second.AttackValue.RemainHp = int32(f.Second.CurrentPet.Info.Hp) ret := info.AttackValueS{ FAttack: *f.First.AttackValue, diff --git a/logic/service/fight/info/BattlePetEntity.go b/logic/service/fight/info/BattlePetEntity.go index abf07e6c..b7474a23 100644 --- a/logic/service/fight/info/BattlePetEntity.go +++ b/logic/service/fight/info/BattlePetEntity.go @@ -40,9 +40,11 @@ func CreateBattlePetEntity(info *model.PetInfo, rand *rand.Rand) *BattlePetEntit ret.PetInfo = xmlres.PetMAP[int(info.ID)] //注入精灵信息 ret.Info = info - for i := 0; i < 4; i++ { + for i := 0; i < len(info.SkillList); i++ { //todo 技能信息应该每回合进行深拷贝,保证每次的技能效果都是不一样的 + ret.Skills[i] = CreateSkill(&info.SkillList[i], rand, ret) + } return ret diff --git a/logic/service/fight/info/BattleSkillEntity.go b/logic/service/fight/info/BattleSkillEntity.go index 2d1f52a4..008f38f7 100644 --- a/logic/service/fight/info/BattleSkillEntity.go +++ b/logic/service/fight/info/BattleSkillEntity.go @@ -71,7 +71,7 @@ func CreateSkill(skill *model.SkillInfo, rand *rand.Rand, pet *BattlePetEntity) } ret.Info = skill - + fmt.Printf("技能2 %p\n", ret.Info) return &ret } @@ -189,7 +189,6 @@ func (s *SkillEntity) Criticalrandom() decimal.Decimal { // Accuracy 优化版命中率计算(用绝对值和正负判断处理等级) func (a *SkillEntity) GetAccuracy(level int) uint32 { // 基础参数校验 - if level >= 0 { //强化等级 return uint32(CalculateRealValue((a.Accuracy), level)) diff --git a/logic/service/fight/info/info.go b/logic/service/fight/info/info.go index 295db947..25881655 100644 --- a/logic/service/fight/info/info.go +++ b/logic/service/fight/info/info.go @@ -238,10 +238,10 @@ type ReadyFightPetInfo struct { // 精灵最大HP,@UInt long MaxHp uint32 `fieldDesc:"最大HP" ` - SkillListLen uint32 + SkillListLen uint32 `struc:"sizeof=SkillList"` // 技能信息列表(固定4个元素,技能ID和剩余PP,无技能则为0) // List,初始化容量为4 - SkillList [4]model.SkillInfo `fieldDesc:"技能信息 技能ID跟剩余PP 固定32字节 没有给0" serialize:"fixedLength=4,type=structArray"` + SkillList []model.SkillInfo `fieldDesc:"技能信息 技能ID跟剩余PP 固定32字节 没有给0" serialize:"fixedLength=4,type=structArray"` // 精灵捕获时间,@UInt long CatchTime uint32 `fieldDesc:"精灵捕获时间" ` diff --git a/logic/service/fight/input/ctx.go b/logic/service/fight/input/ctx.go index 07f1f014..be624b8f 100644 --- a/logic/service/fight/input/ctx.go +++ b/logic/service/fight/input/ctx.go @@ -6,8 +6,8 @@ import ( ) type Ctx struct { - *Input //施加方 - *action.BaseAction //action本身 - *info.SkillEntity //技能 - *info.DamageZone //伤害 + *Input //施加方 + *action.SelectSkillAction //action本身 + + *info.DamageZone //伤害 } diff --git a/logic/service/fight/input/fight.go b/logic/service/fight/input/fight.go index 50435860..2c7f4028 100644 --- a/logic/service/fight/input/fight.go +++ b/logic/service/fight/input/fight.go @@ -10,7 +10,7 @@ import ( "github.com/shopspring/decimal" ) -func (u *Input) UseSkill(opp *Input, skill *info.SkillEntity) { +func (u *Input) UseSkill(opp *Input, skill *action.SelectSkillAction) { skill.Crit = 0 if skill.Category() == info.Category.STATUS { //属性技能不用算暴击 diff --git a/logic/service/fight/input/input.go b/logic/service/fight/input/input.go index bf63ca64..fb8a9d87 100644 --- a/logic/service/fight/input/input.go +++ b/logic/service/fight/input/input.go @@ -67,6 +67,7 @@ func (i *Input) InitAttackValue() { if old != nil { i.AttackValue.Prop = old.Prop i.AttackValue.Status = old.Status + i.AttackValue.SkillList = old.SkillList } } @@ -113,9 +114,9 @@ func (i *Input) GetStatusBonus() float64 { // 解析并 施加effect func (i *Input) Parseskill(defender *Input, skill *action.SelectSkillAction) { i.EffectCache = make([]Effect, 0) //先把上一回合数据清空 - temparg := skill.Skill.SideEffectArgS + temparg := skill.SideEffectArgS - for _, v := range skill.Skill.SideEffectS { + for _, v := range skill.SideEffectS { t := Geteffect(EffectType.Skill, v) diff --git a/logic/service/fight/node/PetSwitch.go b/logic/service/fight/node/PetSwitch.go index f50ecfb0..461fd930 100644 --- a/logic/service/fight/node/PetSwitch.go +++ b/logic/service/fight/node/PetSwitch.go @@ -21,7 +21,9 @@ func (e *EffectNode) OnOwnerSwitchIn(ctx input.Ctx) bool { return true } +//自身下场,清除掉技能效果 func (e *EffectNode) OnOwnerSwitchOut(ctx input.Ctx) bool { + e.Input.AttackValue = nil //自身下场清除掉自身的回合效果 //this.GetBattle().Effects[this.GetInput().UserID].RemoveEffect(this) e.NotALive() diff --git a/logic/service/fight/node/node.go b/logic/service/fight/node/node.go index 89c72708..d4981b61 100644 --- a/logic/service/fight/node/node.go +++ b/logic/service/fight/node/node.go @@ -8,7 +8,6 @@ import ( // 检查,激活,延后 // /基础节点 type EffectNode struct { - Effect duration int // 默认为-1 持续回合/次(0 = 即时生效,>0 = 回合数 ,负数是永久) \ Input *input.Input diff --git a/logic/service/fight/node/skill.go b/logic/service/fight/node/skill.go index ee115c96..7735fd1c 100644 --- a/logic/service/fight/node/skill.go +++ b/logic/service/fight/node/skill.go @@ -22,13 +22,13 @@ func (e *EffectNode) Skill_Hit_to(ctx input.Ctx) bool { return true } func (e *EffectNode) OnSkill(ctx input.Ctx) bool { - if e.Effect != nil { - if e.Hit() { //没命中 - e.Effect.OnHit(ctx.Input, ctx.SkillEntity) - } else { - e.Effect.OnMiss(ctx.Input, ctx.SkillEntity) - } - } + // if e.Effect != nil { + // if e.Hit() { //没命中 + // e.Effect.OnHit(ctx.Input, ctx.SkillEntity) + // } else { + // e.Effect.OnMiss(ctx.Input, ctx.SkillEntity) + // } + // } return true } @@ -41,15 +41,16 @@ func (e *EffectNode) Skill_Use(ctx input.Ctx) bool { return true } func (e *EffectNode) Skill_Useed(ctx input.Ctx) bool { - if e.Effect != nil { - if e.Input.CurrentPet.Info.Hp == 0 { - e.OnDefeat(ctx.Input, ctx.SkillEntity) //死亡 + // if e.Effect != nil { + // if e.Input.CurrentPet.Info.Hp == 0 { + // e.OnDefeat(ctx.Input, ctx.SkillEntity) //死亡 - } else { - e.OnAlive(ctx.Input, ctx.SkillEntity) //存活 - } + // } else { + // e.OnAlive(ctx.Input, ctx.SkillEntity) //存活 + // } - } + // } + // return true return true } diff --git a/logic/service/fight/playeraction.go b/logic/service/fight/playeraction.go index a5c4eebf..bf1da594 100644 --- a/logic/service/fight/playeraction.go +++ b/logic/service/fight/playeraction.go @@ -93,11 +93,11 @@ func (f *FightC) UseSkill(c common.PlayerI, id int32) { BaseAction: action.NewBaseAction(c.GetInfo().UserID), } //ret.PetInfo = f.GetInputByPlayer(c, false).CurrentPet - ret.ID = uint32(id) + for _, v := range f.GetInputByPlayer(c, false).CurrentPet.Skills { if v != nil && v.ID == int(id) { - ret.Skill = v + ret.SkillEntity = v break } diff --git a/logic/service/item/buy.go b/logic/service/item/buy.go index c37b697d..680c8f88 100644 --- a/logic/service/item/buy.go +++ b/logic/service/item/buy.go @@ -19,3 +19,12 @@ type BuyOutboundInfo struct { //购买的物品等级 Level uint32 } +type BuyMultiInboundInfo struct { + Head player.TomeeHeader `cmd:"2606" struc:"[0]pad"` + ItemListLen uint32 `struc:"sizeof=ItemIds"` + ItemIds []uint32 `json:"itemIds" description:"购买的物品ID列表"` // @UInt Long对应uint64,List对应切片 +} +type BuyMultiOutboundInfo struct { + //剩余的数量 + Coins uint32 +} diff --git a/logic/service/player/pet.go b/logic/service/player/pet.go index aaab0c0d..728da526 100644 --- a/logic/service/player/pet.go +++ b/logic/service/player/pet.go @@ -57,19 +57,19 @@ func (p *Player) AddPetExp(petinfo *model.PetInfo, addExp uint32, bro bool) { for i := 0; i < 4; i++ { - if petinfo.SkillList[i].ID == 0 { - if len(canLearnSkillList) != 0 { - skid := canLearnSkillList[len(canLearnSkillList)-1] - petinfo.SkillList[i].ID = skid - petinfo.SkillList[i].PP = uint32(xmlres.SkillMap[int(skid)].MaxPP) - petinfo.SkillListLen += 1 - canLearnSkillList = canLearnSkillList[:len(canLearnSkillList)-1] - } + if len(canLearnSkillList) != 0 { + skid := canLearnSkillList[len(canLearnSkillList)-1] + petinfo.SkillList = append(petinfo.SkillList, model.SkillInfo{ + ID: skid, + PP: uint32(xmlres.SkillMap[int(skid)].MaxPP), + }) + + canLearnSkillList = canLearnSkillList[:len(canLearnSkillList)-1] } } - + petinfo.SkillList = petinfo.SkillList[:4] //归正到4 //todo 待实现 // // 发送技能更新消息 // updateSkillInfo := UpdateSkillInfo{ diff --git a/logic/service/player/player.go b/logic/service/player/player.go index 5c23d645..95654ea5 100644 --- a/logic/service/player/player.go +++ b/logic/service/player/player.go @@ -3,7 +3,9 @@ package player import ( "blazing/common/data/share" "blazing/common/data/xmlres" + "blazing/common/socket/errorcode" "blazing/common/utils" + "blazing/cool" "fmt" "math/rand" "strings" @@ -212,24 +214,82 @@ func replaceOneNumber(original [3]int) ([3]int, int, int) { } // 添加物品 -func (p *Player) ItemAdd(t ...model.SingleItemInfo) { +func (p *Player) ItemAdd(t ...model.SingleItemInfo) (result []model.SingleItemInfo) { var ttt []model.SingleItemInfo for _, v := range t { switch v.ItemId { case 1: //塞尔豆 p.Info.Coins = p.Info.Coins + v.ItemCnt + case 3: //累计经验 p.Info.ExpPool = p.Info.ExpPool + v.ItemCnt + + case 5: //金豆ItemAdd + p.Info.GoldBean = p.Info.GoldBean + v.ItemCnt + default: ttt = append(ttt, v) } } - p.Service.ItemAdd(ttt...) + + p.Service.Item(func(rer map[uint32]model.SingleItemInfo) bool { + + for _, v := range ttt { + itemx, ok := xmlres.ItemsMAP[int(v.ItemId)] + if !ok { + cool.Loger.Error(context.TODO(), "物品不存在", v.ItemId) + + t1 := NewTomeeHeader(2601, p.Info.UserID) + t1.Result = uint32(errorcode.ErrorCodes.ErrBaseItemTypeLimit) + + p.SendPack(t1.Pack(nil)) //准备包由各自发,因为协议不一样 + continue + } + itemm, ok := rer[v.ItemId] + + if !ok { + rer[v.ItemId] = v + result = append(result, v) + continue + } + itemm.ItemCnt += v.ItemCnt + if itemm.ItemCnt > uint32(itemx.Max) { + cool.Loger.Error(context.TODO(), "物品超过拥有最大限制", v.ItemId) + t1 := NewTomeeHeader(2601, p.Info.UserID) + t1.Result = uint32(errorcode.ErrorCodes.ErrTooManyOfItem) + + p.SendPack(t1.Pack(nil)) //准备包由各自发,因为协议不一样 + continue + } + result = append(result, v) + rer[v.ItemId] = itemm + + } + return true + }) return } +func (player1 *Player) Kick() { + if player1.IsLogin { + //取成功,否则创建 + //player1.Save() //先保存数据再返回 + head := NewTomeeHeader(1001, player1.Info.UserID) + head.Result = uint32(errorcode.ErrorCodes.ErrAccountLoggedInElsewhere) + //实际上这里有个问题,会造成重复保存问题 + + player1.SendPack(head.Pack(nil)) + player1.MainConn.Context().(*ClientData).CloseChan = make(chan struct{}) + player1.MainConn.Context().(*ClientData).Mu.Lock() + player1.MainConn.Close() + player1.MainConn.Context().(*ClientData).Mu.Unlock() + // clientdata.Player = player + + <-player1.MainConn.Context().(*ClientData).CloseChan + } +} func (p *Player) SendPack(b []byte) error { if _, ok := p.MainConn.Context().(*ClientData); !ok { return fmt.Errorf("链接错误,取消发包") diff --git a/logic/service/player/server.go b/logic/service/player/server.go index ca98d4d6..0f02a4fb 100644 --- a/logic/service/player/server.go +++ b/logic/service/player/server.go @@ -1,8 +1,6 @@ package player import ( - "blazing/common/socket/errorcode" - "github.com/panjf2000/gnet/v2" ) @@ -33,22 +31,7 @@ func KickPlayer(userid uint32) error { //踢出玩家 //TODO 返回错误码 //var player *entity.Player if player1, ok := Mainplayer.Load(userid); ok { - if player1.IsLogin { - //取成功,否则创建 - //player1.Save() //先保存数据再返回 - head := NewTomeeHeader(1001, userid) - head.Result = uint32(errorcode.ErrorCodes.ErrAccountLoggedInElsewhere) - //实际上这里有个问题,会造成重复保存问题 - - player1.SendPack(head.Pack(nil)) - player1.MainConn.Context().(*ClientData).CloseChan = make(chan struct{}) - player1.MainConn.Context().(*ClientData).Mu.Lock() - player1.MainConn.Close() - player1.MainConn.Context().(*ClientData).Mu.Unlock() - // clientdata.Player = player - - <-player1.MainConn.Context().(*ClientData).CloseChan - } + player1.Kick() } diff --git a/login/go.sum b/login/go.sum index 4b36c0e3..74886606 100644 --- a/login/go.sum +++ b/login/go.sum @@ -107,6 +107,7 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +<<<<<<< HEAD github.com/tencent-connect/botgo v0.2.1 h1:+BrTt9Zh+awL28GWC4g5Na3nQaGRWb0N5IctS8WqBCk= github.com/tencent-connect/botgo v0.2.1/go.mod h1:oO1sG9ybhXNickvt+CVym5khwQ+uKhTR+IhTqEfOVsI= github.com/tidwall/gjson v1.9.3 h1:hqzS9wAHMO+KVBBkLxYdkEeeFHuqr95GfClRLKlgK0E= @@ -117,6 +118,10 @@ github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +======= +github.com/xiaoqidun/limit v1.0.1 h1:tJBDRv+JkziRghRCKHUVyxLGSL1CkkY+aPKMorWZJ20= +github.com/xiaoqidun/limit v1.0.1/go.mod h1:9blqqk5PcsnkWyIBwkkPHUQJjlx2p+Cf0TxVGz0MDFg= +>>>>>>> 248a326bb5cc8fb68085c2534a10a1c7e3935d46 go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= @@ -192,6 +197,7 @@ golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +<<<<<<< HEAD golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -209,6 +215,9 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +======= + +>>>>>>> 248a326bb5cc8fb68085c2534a10a1c7e3935d46 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/login/internal/cmd/cmd.go b/login/internal/cmd/cmd.go index 00417601..aa6b77b4 100644 --- a/login/internal/cmd/cmd.go +++ b/login/internal/cmd/cmd.go @@ -12,11 +12,13 @@ import ( "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/gfile" + "github.com/xiaoqidun/limit" "golang.org/x/time/rate" ) var ( - Main = gcmd.Command{ + limiter = limit.New() + Main = gcmd.Command{ Name: "main", Usage: "main", Brief: "start http server", @@ -52,12 +54,12 @@ func beforeServeHook(r *ghttp.Request) { r.Response.CORSDefault() } -var limiter = rate.NewLimiter(rate.Limit(10), 1) - // Limiter is a middleware that implements rate limiting for all HTTP requests. // It returns HTTP 429 (Too Many Requests) when the rate limit is exceeded. func Limiter(r *ghttp.Request) { - if !limiter.Allow() { + rateLimiter := limiter.Get(r.GetClientIp(), rate.Limit(10), 2) + + if !rateLimiter.Allow() { r.Response.WriteStatusExit(429) // Return 429 Too Many Requests r.ExitAll() } diff --git a/login/main.go b/login/main.go index a813b652..f051660b 100644 --- a/login/main.go +++ b/login/main.go @@ -30,7 +30,6 @@ import ( ) func main() { - //Test_kick() cmd.Main.Run(gctx.New()) } diff --git a/modules/base/service/base_sys_login.go b/modules/base/service/base_sys_login.go index 36e55e11..969f3243 100644 --- a/modules/base/service/base_sys_login.go +++ b/modules/base/service/base_sys_login.go @@ -42,7 +42,7 @@ func (s *BaseSysLoginService) Login(ctx context.Context, req *v1.BaseOpenLoginRe baseSysUser = model.NewBaseSysUser() ) - vcode, _ := cool.CacheManager.Get(ctx, captchaId) + vcode, _ := cool.CacheManager.Get(ctx, "login:"+captchaId) if vcode.String() != verifyCode { err = gerror.New("验证码错误") return @@ -82,7 +82,7 @@ func (*BaseSysLoginService) Captcha(req *v1.BaseOpenCaptchaReq) (interface{}, er result.Data = `data:image/svg+xml;base64,` + svgbase64 result.CaptchaId = guid.S() - cool.CacheManager.Set(ctx, result.CaptchaId, captchaText, 1800*time.Second) + cool.CacheManager.Set(ctx, "login:"+result.CaptchaId, captchaText, 1800*time.Second) cool.Loger.Debug(ctx, "验证码", result.CaptchaId, captchaText) return result, err } diff --git a/modules/blazing/model/pet.go b/modules/blazing/model/pet.go index 4a8cb08f..59d357c2 100644 --- a/modules/blazing/model/pet.go +++ b/modules/blazing/model/pet.go @@ -95,9 +95,10 @@ type PetInfo struct { // 速度学习力(@UInt long → uint32) EvSpeed uint32 `fieldDesc:"速度学习力" ` - SkillListLen uint32 + SkillListLen uint32 `struc:"sizeof=SkillList"` + // 技能信息:固定4条,空则赋值0(固定长度List → [4]SkillInfo,零值即符合“赋值0”) - SkillList [4]SkillInfo + SkillList []SkillInfo // 捕捉时间(@UInt long → 若为时间戳用uint32;若需时间类型可改为time.Time,需配合序列化处理) CatchTime uint32 `fieldDesc:"捕捉时间" ` @@ -124,7 +125,7 @@ type PetInfo struct { func (pet *PetInfo) Cure() { pet.Hp = pet.MaxHp - for i := 0; i < 4; i++ { + for i := 0; i < len(pet.SkillList); i++ { maxPP, ok := xmlres.SkillMap[int(pet.SkillList[i].ID)] // 恢复至最大PP值(从配置表获取) if pet.SkillList[i].ID != 0 && ok { @@ -133,15 +134,21 @@ func (pet *PetInfo) Cure() { } } } -func (petinfo *PetInfo) Update() { + +// 传入bool则不升级 +func (petinfo *PetInfo) Update(t ...bool) { + basic := xmlres.PetMAP[int(petinfo.ID)] - // 检查是否可以进化 - if basic.EvolvesTo != 0 && // 有明确的进化 - int(petinfo.Level) >= basic.EvolvingLv && // 有明确的进化等级 - basic.IsLarge == 0 { // 非最终形态 - petinfo.ID = uint32(basic.EvolvesTo) + if len(t) == 0 { + // 检查是否可以进化 + if basic.EvolvesTo != 0 && // 有明确的进化 + int(petinfo.Level) >= basic.EvolvingLv && // 有明确的进化等级 + basic.IsLarge == 0 { // 非最终形态 + petinfo.ID = uint32(basic.EvolvesTo) + basic = xmlres.PetMAP[int(petinfo.ID)] //重新计算 + } } petinfo.LvExp = petinfo.NextLvExp @@ -289,13 +296,12 @@ func GenPetInfo( // ---- 技能学习 ---- skills := LastFourElements(p.GetLevelRangeCanLearningSkills(0, p.Level)) // 最后四个技能 - p.SkillListLen = uint32(len(skills)) - for i := 0; i < len(skills) && i < len(p.SkillList); i++ { + for i := 0; i < len(skills) && i < 4; i++ { skillID := skills[i] if info, ok := xmlres.SkillMap[int(skillID)]; ok { - p.SkillList[i].ID = skillID - p.SkillList[i].PP = uint32(info.MaxPP) + p.SkillList = append(p.SkillList, SkillInfo{ID: skillID, PP: uint32(info.MaxPP)}) + } } @@ -303,7 +309,7 @@ func GenPetInfo( p.CalculatePetPane() p.Hp = p.MaxHp - p.Update() + p.Update(true) return p } diff --git a/modules/blazing/service/item.go b/modules/blazing/service/item.go index e948ce43..0609aa7e 100644 --- a/modules/blazing/service/item.go +++ b/modules/blazing/service/item.go @@ -29,20 +29,5 @@ func (s *UserService) Item(t func(map[uint32]model.SingleItemInfo) bool) { panic(err) } } -func (s *UserService) ItemAdd(t ...model.SingleItemInfo) { - s.Item(func(rer map[uint32]model.SingleItemInfo) bool { - for _, v := range t { - tt, ok := rer[v.ItemId] - if ok { - tt.ItemCnt += v.ItemCnt - rer[v.ItemId] = tt - } else { - rer[v.ItemId] = v - } - - } - return true - }) - -} +// /添加进来的物品一定是保证存在的