geometry-tower-defense/Assets/GameMain/Scripts/Utility/ShopPriceRuleService.cs

123 lines
4.0 KiB
C#

using System;
using System.Collections.Generic;
using GameFramework.DataTable;
using GeometryTD.DataTable;
using GeometryTD.Definition;
using UnityEngine;
using Random = System.Random;
namespace GeometryTD.CustomUtility
{
public static class ShopPriceRuleService
{
public static int ResolveRandomBuyPrice(IReadOnlyList<DRShopPrice> shopPriceRows, RarityType rarity, Random random)
{
if (!TryFindPriceRow(shopPriceRows, rarity, out DRShopPrice row) || row == null)
{
return 0;
}
int min = Mathf.Max(0, row.MinPrice);
int max = Mathf.Max(min, row.MaxPrice);
return random != null ? random.Next(min, max + 1) : min;
}
public static int ResolveComponentSalePrice(TowerCompItemData component, IDataTable<DRShopPrice> shopPriceTable = null)
{
if (component == null)
{
return 0;
}
return ResolveBasePrice(component.Rarity, shopPriceTable);
}
public static bool TryResolveTowerSalePrice(
TowerItemData tower,
BackpackInventoryData inventory,
out int price,
IDataTable<DRShopPrice> shopPriceTable = null)
{
price = 0;
if (tower == null || inventory == null)
{
return false;
}
if (!TryGetComponentById(inventory.MuzzleComponents, tower.MuzzleComponentInstanceId, out MuzzleCompItemData muzzleComp) ||
!TryGetComponentById(inventory.BearingComponents, tower.BearingComponentInstanceId, out BearingCompItemData bearingComp) ||
!TryGetComponentById(inventory.BaseComponents, tower.BaseComponentInstanceId, out BaseCompItemData baseComp))
{
return false;
}
price = ResolveComponentSalePrice(muzzleComp, shopPriceTable) +
ResolveComponentSalePrice(bearingComp, shopPriceTable) +
ResolveComponentSalePrice(baseComp, shopPriceTable);
return price > 0;
}
public static int ResolveBasePrice(RarityType rarity, IDataTable<DRShopPrice> shopPriceTable = null)
{
IDataTable<DRShopPrice> resolvedTable = shopPriceTable ?? GameEntry.DataTable.GetDataTable<DRShopPrice>();
if (resolvedTable == null)
{
return 0;
}
DRShopPrice[] rows = resolvedTable.GetAllDataRows();
if (!TryFindPriceRow(rows, rarity, out DRShopPrice row) || row == null)
{
return 0;
}
int min = Mathf.Max(0, row.MinPrice);
int max = Mathf.Max(min, row.MaxPrice);
return Mathf.RoundToInt((min + max) * 0.5f);
}
private static bool TryFindPriceRow(IReadOnlyList<DRShopPrice> rows, RarityType rarity, out DRShopPrice result)
{
result = null;
if (rows == null)
{
return false;
}
for (int i = 0; i < rows.Count; i++)
{
DRShopPrice row = rows[i];
if (row != null && row.Rarity == rarity)
{
result = row;
return true;
}
}
return false;
}
private static bool TryGetComponentById<TComp>(IReadOnlyList<TComp> components, long instanceId, out TComp result)
where TComp : TowerCompItemData
{
result = null;
if (components == null || instanceId <= 0)
{
return false;
}
for (int i = 0; i < components.Count; i++)
{
TComp component = components[i];
if (component != null && component.InstanceId == instanceId)
{
result = component;
return true;
}
}
return false;
}
}
}