Files
bl/modules/config/service/pet_fusion_service.go
昔念 09a295db34
All checks were successful
ci/woodpecker/push/my-first-workflow Pipeline was successful
```
feat(utils): 添加基于权重的概率随机函数

添加了两个泛型函数用于实现权重随机选择功能:
- RandomByIntProbs: 核心函数,支持任意类型元素数组和int型概率数组
- RandomByProbs: 封装函数,兼容string型概率数组输入

函数特性:
- 支持泛型,可处理任意类型的数据
- 实现权重随机算法,通过前缀和匹配随机值
- 包含完整的参数校验和错误
2026-02-05 00:29:19 +08:00

90 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"blazing/common/utils"
"blazing/cool"
"blazing/modules/config/model"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/util/grand"
)
// PetFusionService 宠物融合配方主表Service对应pet_fusion表
type PetFusionService struct {
*cool.Service // 嵌入通用Service继承基础CRUD方法
}
// NewPetFusionService 创建PetFusionService实例
func NewPetFusionService() *PetFusionService {
return &PetFusionService{
&cool.Service{
Model: model.NewPetFusion(), // 绑定PetFusion模型
//Cache: gcache.New(),
PageQueryOp: &cool.QueryOp{FieldEQ: []string{"is_enable", "main_pet_id", "sub_pet_id", "result_pet_id"}},
},
}
}
//获取主副精灵融合的id,如果不存在,那就给一个保底的id
func (s *PetFusionService) Data(p1, p2, rand uint32) uint32 {
if !grand.Meet(int((rand)/2), 100) {
return 0
}
pet := s.getData(p1, p2)
if len(pet) != 0 {
var pets, props []int
for _, v := range pet {
pets = append(pets, int(v.ResultPetID))
props = append(props, int(v.Probability))
}
utils.RandomByIntProbs(pets, props)
//说明是失败,直接返回失败
} else {
pets := s.def()
res := pets[grand.Intn(len(pets))]
rr := grand.Intn(100)
if rr < int(res.Probability+int32(rand)) {
return uint32(res.ResultPetID)
}
//到这里相当于直接失败
return 0
}
return 0
}
func (s *PetFusionService) getData(p1, p2 uint32) []model.PetFusion {
//cacheKey := strings.Join([]string{fmt.Sprintf("%d", p1), fmt.Sprintf("%d", p2)}, ":")
m := dbm(s.Model)
var pet []model.PetFusion //一个特性应该是唯一的,但是我们要获取默认随机特性
m.Where("main_pet_id", p1).Wheref(`sub_pet_ids @> ARRAY[?]::integer[]`, p2).
Where("is_enable", 1).Scan(&pet)
return pet
}
func (s *PetFusionService) def() []model.PetFusion {
var pets []model.PetFusion
m := cool.DBM(s.Model)
m.Where("is_enable", 1).Where("is_default", 1).Cache(gdb.CacheOption{
// Duration: time.Hour,
Force: false,
}).Scan(&pets)
return pets
// return ret.Interface().([]model.PetFusion)
}