feat: 新增矿池机制

This commit is contained in:
chenchun
2024-10-15 18:32:50 +08:00
parent 1c6a795061
commit e8fcab4c6b
13 changed files with 313 additions and 20 deletions

View File

@@ -1,17 +1,28 @@
using Microsoft.AspNetCore.Authorization;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Yi.Framework.DigitalCollectibles.Application.Contracts.Dtos.Collectibles;
using Yi.Framework.DigitalCollectibles.Application.Contracts.Dtos.Market;
using Yi.Framework.DigitalCollectibles.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.DigitalCollectibles.Application.Services;
/// <summary>
/// 藏品应用服务
/// </summary>
public class CollectiblesService:ApplicationService
public class CollectiblesService : ApplicationService
{
private readonly ISqlSugarRepository<CollectiblesUserStoreAggregateRoot> _collectiblesUserStoreRepository;
public CollectiblesService(ISqlSugarRepository<CollectiblesUserStoreAggregateRoot> collectiblesUserStoreRepository)
{
_collectiblesUserStoreRepository = collectiblesUserStoreRepository;
}
/// <summary>
/// 获取当前用户的藏品
/// </summary>
@@ -20,8 +31,16 @@ public class CollectiblesService:ApplicationService
/// <exception cref="NotImplementedException"></exception>
[HttpGet("user")]
[Authorize]
public async Task<PagedResultDto<CollectiblesUserGetOutputDto>> GetForAccountUserAsync(CollectiblesUserGetInput input)
public async Task<PagedResultDto<CollectiblesUserGetOutputDto>> GetForAccountUserAsync(
CollectiblesUserGetInput input)
{
throw new NotImplementedException();
RefAsync<int> total = 0;
var entities = await _collectiblesUserStoreRepository._DbQueryable.WhereIF(
input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var output = entities.Adapt<List<CollectiblesUserGetOutputDto>>();
return new PagedResultDto<CollectiblesUserGetOutputDto>(total, output);
}
}

View File

@@ -1,6 +1,10 @@
using Volo.Abp.Application.Dtos;
using Mapster;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Yi.Framework.DigitalCollectibles.Application.Contracts.Dtos.Market;
using Yi.Framework.DigitalCollectibles.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.DigitalCollectibles.Application.Services;
@@ -9,14 +13,27 @@ namespace Yi.Framework.DigitalCollectibles.Application.Services;
/// </summary>
public class MarketService:ApplicationService
{
private readonly ISqlSugarRepository<MarketGoodsAggregateRoot> _marketGoodsRepository;
public MarketService(ISqlSugarRepository<MarketGoodsAggregateRoot> marketGoodsRepository)
{
_marketGoodsRepository = marketGoodsRepository;
}
/// <summary>
/// 交易市场查询
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<PagedResultDto<MarketGetListOutputDto>> GetListAsync(MarketGetListInput input)
{
throw new NotImplementedException();
RefAsync<int> total = 0;
var entities = await _marketGoodsRepository._DbQueryable.WhereIF(
input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var output = entities.Adapt<List<MarketGetListOutputDto>>();
return new PagedResultDto<MarketGetListOutputDto>(total, output);
}
}

View File

@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Yi.Framework.DigitalCollectibles.Domain.Shared.Consts;
namespace Yi.Framework.DigitalCollectibles.Domain.Shared.Attributes;
public class ProbabilityAttribute : Attribute
{
public double Value { get; set; }
public ProbabilityAttribute(double value)
{
this.Value = value;
}
}

View File

@@ -0,0 +1,9 @@
namespace Yi.Framework.DigitalCollectibles.Domain.Shared.Consts;
public class CacheConst
{
/// <summary>
/// 矿池
/// </summary>
public const string MiningPoolContent = "MiningPool";
}

View File

@@ -1,4 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Yi.Framework.DigitalCollectibles.Domain.Shared.Attributes;
namespace Yi.Framework.DigitalCollectibles.Domain.Shared.Consts;
@@ -7,9 +9,50 @@ namespace Yi.Framework.DigitalCollectibles.Domain.Shared.Consts;
/// </summary>
public enum RarityEnum
{
[Display(Name = "普通")] Ordinary = 0,
[Display(Name = "高级")] Senior = 1,
[Display(Name = "稀有")] Rare = 2,
[Display(Name = "珍品")] Gem = 3,
[Display(Name = "传说")] Legend = 4
[Display(Name = "普通")][Probability(0.8f)] Ordinary = 0,
[Display(Name = "高级")][Probability(0.1f)] Senior = 1,
[Display(Name = "稀有")][Probability(0.06f)] Rare = 2,
[Display(Name = "珍品")][Probability(0.039f)] Gem = 3,
[Display(Name = "传说")][Probability(0.001f)] Legend = 4
}
public static class RarityEnumExtensions
{
private static T GetAttribute<T>(RarityEnum rarity) where T : Attribute
{
var fieldInfo = typeof(RarityEnum).GetField(rarity.ToString());
var attribute = fieldInfo.GetCustomAttribute<T>();
return attribute!;
}
public static decimal GetProbabilityValue(this RarityEnum rarity)
{
var attribute = GetAttribute<ProbabilityAttribute>(rarity);
return attribute.Value.To<decimal>();
}
public static string GetDisplayValue(this RarityEnum rarity)
{
var display = GetAttribute<DisplayAttribute>(rarity);
return display.Name!;
}
public static decimal[] GetProbabilityValues()
{
List<decimal> probabilityList = new List<decimal>();
foreach (var field in typeof(RarityEnum).GetFields())
{
// 获取特性
var attribute = field.GetCustomAttribute<ProbabilityAttribute>();
if (attribute != null)
{
// 将特性值添加到列表
probabilityList.Add(attribute.Value.To<decimal>());
}
}
return probabilityList.ToArray();
}
}

View File

@@ -0,0 +1,50 @@
namespace Yi.Framework.DigitalCollectibles.Domain.Shared.Dtos;
/// <summary>
/// 矿池内容
/// </summary>
public class MiningPoolContent
{
public MiningPoolContent(DateTime startTime, DateTime endTime)
{
StartTime = startTime;
EndTime = endTime;
}
/// <summary>
/// 普通藏品剩余数量
/// </summary>
public int I0_OrdinaryNumber { get; set; }
/// <summary>
/// 高级藏品剩余数量
/// </summary>
public int I1_SeniorNumber { get; set; }
/// <summary>
/// 稀有藏品剩余数量
/// </summary>
public int I2_RareNumber { get; set; }
/// <summary>
/// 珍品藏品剩余数量
/// </summary>
public int I3_GemNumber { get; set; }
/// <summary>
/// 传说藏品剩余数量
/// </summary>
public int I4_LegendNumber { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime StartTime{ get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime EndTime{ get; set; }
}

View File

@@ -10,7 +10,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Dtos\" />
<Folder Include="Enums\" />
<Folder Include="Etos\" />
</ItemGroup>

View File

@@ -19,4 +19,9 @@ public class CollectiblesUserStoreAggregateRoot:FullAuditedAggregateRoot<Guid>
/// 藏品id
/// </summary>
public Guid CollectiblesId { get; set; }
/// <summary>
/// 用户是否已读
/// </summary>
public bool IsRead { get; set; }
}

View File

@@ -1,4 +1,10 @@
using Volo.Abp.Domain.Services;
using Microsoft.Extensions.Caching.Distributed;
using Volo.Abp.Caching;
using Volo.Abp.Domain.Services;
using Volo.Abp.Settings;
using Yi.Framework.DigitalCollectibles.Domain.Shared.Consts;
using Yi.Framework.DigitalCollectibles.Domain.Shared.Dtos;
using Yi.Framework.SettingManagement.Domain;
namespace Yi.Framework.DigitalCollectibles.Domain.Managers;
@@ -6,6 +12,134 @@ namespace Yi.Framework.DigitalCollectibles.Domain.Managers;
/// 矿池领域服务
/// 处理矿池相关业务,例如挖矿等
/// </summary>
public class MiningPoolManager:DomainService
public class MiningPoolManager : DomainService
{
/// <summary>
/// 每次挖矿概率,每天根据特定算法计算
/// </summary>
private static decimal CurrentMiningProbability { get; set; }
private readonly ISettingProvider _settingProvider;
private readonly IDistributedCache<MiningPoolContent> _cache;
public MiningPoolManager(ISettingProvider settingProvider, IDistributedCache<MiningPoolContent> cache)
{
_settingProvider = settingProvider;
this._cache = cache;
}
/// <summary>
/// 最后一次计算挖矿概率的时间如果时间跨了早上10点重新计算
/// </summary>
private static DateTime LastComputeMiningProbabilityTime { get; set; }
/// <summary>
/// 用户进行一次挖矿
/// </summary>
/// <returns></returns>
public Task MiningAsync(Guid userId)
{
//从矿池中开挖
//根据挖矿概率,进行挖掘
//挖到了放到用户仓库即可
//如果概率是挖到了矿,再从矿物中随机选择一个稀有度,再在当前稀有度中的矿物列表,随机选择一个具体的矿物
throw new NotImplementedException();
}
/// <summary>
/// 计算当前挖矿概率
/// </summary>
/// <returns></returns>
public Task ComputeMiningProbabilityAsync()
{
//当前的挖矿期望:当天的所有藏品能被刚好挖完
//保底概率最大不能高过一个值百分之10
//手动挖矿1天可挖10次每次至少间隔6秒
//自动挖矿1天可以挖24次 每次间隔60分钟需要使用自动挖矿卡
//可影响因素:剩余手动挖矿次数+剩余自动挖矿次数
//所有能够挖掘次数
throw new NotImplementedException();
}
/// <summary>
/// 刷新矿池
/// </summary>
/// <returns></returns>
public async Task RefreshMiningPoolAsync()
{
//获取当前最大的限制
var maximumPoolLimit = int.Parse(await _settingProvider.GetOrNullAsync("MaximumPoolLimit"));
DateTime startTime = DateTime.Today.AddHours(10);
DateTime endTime = startTime.AddDays(1);
var probabilityValues = RarityEnumExtensions.GetProbabilityValues();
var result = GenerateDistribution(maximumPoolLimit, probabilityValues);
//根据配置,将不同比例的矿,塞入矿池,
//矿池交给redis
await _cache.SetAsync(CacheConst.MiningPoolContent, new MiningPoolContent(startTime, endTime)
{
I0_OrdinaryNumber = result[0],
I1_SeniorNumber = result[1],
I2_RareNumber = result[2],
I3_GemNumber = result[3],
I4_LegendNumber = result[4]
}, new DistributedCacheEntryOptions
{
AbsoluteExpiration = endTime
});
}
/// <summary>
/// 根据概率生成给对应稀有度藏品
/// </summary>
/// <param name="totalCount"></param>
/// <param name="probabilities"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
private int[] GenerateDistribution(int totalCount, decimal[] probabilities)
{
int[] counts = new int[probabilities.Length];
decimal totalProbability = 0;
// 计算概率总和,确保为 1
foreach (var prob in probabilities)
{
totalProbability += prob;
}
// 检查概率之和是否为 1
if (totalProbability < 0.99m || totalProbability > 1.01m)
{
throw new ArgumentException("概率总和必须接近1");
}
// 生成分布
for (int i = 0; i < probabilities.Length; i++)
{
counts[i] = (int)(totalCount * probabilities[i]);
}
// 处理可能因精度问题导致的总数不足
int sum = 0;
foreach (var count in counts)
{
sum += count;
}
int difference = totalCount - sum;
// 将差值分配给概率最大的一项
if (difference > 0)
{
int maxIndex = Array.IndexOf(counts, Math.Max(counts[0], counts[1]));
counts[maxIndex] += difference;
}
return counts;
}
}

View File

@@ -9,6 +9,7 @@
<ItemGroup>
<ProjectReference Include="..\..\..\framework\Yi.Framework.Mapster\Yi.Framework.Mapster.csproj" />
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />
<ProjectReference Include="..\..\setting-management\Yi.Framework.SettingManagement.Domain\Yi.Framework.SettingManagement.Domain.csproj" />
<ProjectReference Include="..\Yi.Framework.DigitalCollectibles.Domain.Shared\Yi.Framework.DigitalCollectibles.Domain.Shared.csproj" />
</ItemGroup>

View File

@@ -3,12 +3,14 @@ using Volo.Abp.Domain;
using Volo.Abp.Modularity;
using Yi.Framework.DigitalCollectibles.Domain.Shared;
using Yi.Framework.Mapster;
using Yi.Framework.SettingManagement.Domain;
namespace Yi.Framework.DigitalCollectibles.Domain
{
[DependsOn(
typeof(YiFrameworkDigitalCollectiblesDomainSharedModule),
typeof(YiFrameworkSettingManagementDomainModule),
typeof(YiFrameworkMapsterModule),
typeof(AbpDddDomainModule),
typeof(AbpCachingModule)

View File

@@ -4,6 +4,7 @@
<ItemGroup>
<ProjectReference Include="..\..\..\framework\Yi.Framework.Mapster\Yi.Framework.Mapster.csproj" />
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore\Yi.Framework.SqlSugarCore.csproj" />
<ProjectReference Include="..\..\setting-management\Yi.Framework.SettingManagement.SqlSugarCore\Yi.Framework.SettingManagement.SqlSugarCore.csproj" />
<ProjectReference Include="..\Yi.Framework.DigitalCollectibles.Domain\Yi.Framework.DigitalCollectibles.Domain.csproj" />
</ItemGroup>

View File

@@ -1,16 +1,13 @@
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity;
using Yi.Framework.DigitalCollectibles.Domain;
using Yi.Framework.Mapster;
using Yi.Framework.SettingManagement.SqlSugarCore;
using Yi.Framework.SqlSugarCore;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.DigitalCollectibles.SqlsugarCore
{
[DependsOn(
typeof(YiFrameworkDigitalCollectiblesDomainModule),
typeof(YiFrameworkSettingManagementSqlSugarCoreModule),
typeof(YiFrameworkMapsterModule),
typeof(YiFrameworkSqlSugarCoreModule)
)]