package ludo import ( "crypto/rand" "encoding/binary" "fmt" "math/big" "server/msg" ) func randomSz() int32 { // 生成0-5的随机数 n, err := rand.Int(rand.Reader, big.NewInt(6)) if err != nil { panic(err) // 在实际应用中应该更优雅地处理错误 } // 转换为int32并加1得到1-6的范围 return int32(n.Int64()) + 1 } func roleIndexOf(arr []*msg.ColorData, target *msg.ColorData) int { for i, v := range arr { if v == target { // 比较指针地址 return i } } return -1 // 未找到 } func getRandomItem[T any](slice []T) T { if len(slice) == 0 { var zero T return zero } // 生成加密安全的随机数 n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(slice)))) return slice[n.Int64()] } // 随机获取一个人机名字 func getRandomRobotName(existingNames []string) string { allNames := []string{ "张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", } return getRandomName(allNames, existingNames) } func getRandomName(allNames []string, existingNames []string) string { // 1. 创建剩余名字的切片 remainingNames := make([]string, 0) // 2. 构建已存在名字的映射(提高查找效率) existingMap := make(map[string]bool) for _, name := range existingNames { existingMap[name] = true } // 3. 筛选出未使用的名字 for _, name := range allNames { if !existingMap[name] { remainingNames = append(remainingNames, name) } } // 4. 如果没有剩余名字,返回空字符串 if len(remainingNames) == 0 { return "" } // 5. 使用 crypto/rand 生成安全的随机索引 n, err := rand.Int(rand.Reader, big.NewInt(int64(len(remainingNames)))) if err != nil { // 如果出现错误,作为后备方案使用不太安全但更可靠的方案 var fallbackSeed int64 binary.Read(rand.Reader, binary.LittleEndian, &fallbackSeed) if fallbackSeed < 0 { fallbackSeed = -fallbackSeed } return remainingNames[fallbackSeed%int64(len(remainingNames))] } // 6. 返回随机选择的名字 return remainingNames[n.Int64()] } // 随机获取一个人机头像 func getRandomRobotHead() string { n, err := rand.Int(rand.Reader, big.NewInt(13)) if err != nil { panic(err) // 在实际应用中应该更优雅地处理错误 } return fmt.Sprintf("3_%d", n) } // 随机获取一个人机金币 func getRandomRobotCoin() int32 { n, err := rand.Int(rand.Reader, big.NewInt(1000)) if err != nil { panic(err) // 在实际应用中应该更优雅地处理错误 } return int32(n.Int64()) + 1000 } func GetNextRole(currentRole msg.RoleType) msg.RoleType { // 定义角色顺序 roleOrder := []msg.RoleType{ msg.RoleType_GREEN, msg.RoleType_YELLOW, msg.RoleType_BLUE, msg.RoleType_RED, } // 查找当前角色在顺序中的位置 for i, role := range roleOrder { if role == currentRole { // 如果是最后一个角色,返回第一个角色(循环) if i == len(roleOrder)-1 { return roleOrder[0] } return roleOrder[i+1] } } return msg.RoleType_ROLE_TYPE_UNKNOWN }