Files
vampire-like/Assets/GameMain/Scripts/Runtime/UIBase/Shop/ShopUseCase.cs
T

456 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using SepCore.Components;
using SepCore.Definition;
using SepCore.Entity;
using SepCore.CustomUtility;
using UnityEngine;
using UnityGameFramework.Runtime;
using Random = UnityEngine.Random;
namespace SepCore.UI
{
public class ShopUseCase : IUIUseCase
{
public const int ShopRerollBaseCost = 1;
private readonly Player _player;
private readonly Func<int> _getCurrentLevel;
private int _currentLevel;
private readonly Action _onShopFinish;
private readonly IReadOnlyList<GoodsConfig> _allGoods;
private readonly List<GoodsConfig> _validGoods = new();
private readonly Dictionary<Rarity, List<GoodsConfig>> _goodsByRarity = new();
private readonly List<ShopGoodsSelection> _selections = new();
private int _rollTimesInThisShop;
public int CurrentLevel => _getCurrentLevel != null ? _getCurrentLevel() : _currentLevel;
public int RollTimesInThisShop => _rollTimesInThisShop;
public IReadOnlyList<ShopGoodsSelection> Selections => _selections;
public ShopUseCase(Player player, Func<int> getCurrentLevel, Action onShopFinish)
{
_player = player;
_getCurrentLevel = getCurrentLevel;
_currentLevel = getCurrentLevel != null ? getCurrentLevel() : 1;
_onShopFinish = onShopFinish;
_allGoods = GameEntry.Luban.GetTable<GoodsConfig>();
BuildGoodsRarityPools();
}
public ShopUseCase(Player player, int currentLevel, Action onShopFinish)
: this(player, () => currentLevel, onShopFinish)
{
}
public static int CalculateRefreshPrice(int wave, int rollTimes)
{
return ShopRerollBaseCost + (Mathf.Max(1, wave) * 1) + (Mathf.Max(0, rollTimes) * 2);
}
public ShopRawData CreateInitialModel()
{
_currentLevel = _getCurrentLevel != null ? _getCurrentLevel() : _currentLevel;
_rollTimesInThisShop = 0;
int initialRefreshPrice = CalculateRefreshPrice(_currentLevel, _rollTimesInThisShop);
return new ShopRawData
{
CurrentLevel = _currentLevel,
RefreshPrice = initialRefreshPrice,
PlayerCoin = _player.Coin,
GoodsItems = RefreshGoodsSlots(GameEntry.Luban.Global.ShopGoodsCount),
PropItems = _player.Props,
PropMaxCount = GameEntry.Luban.Global.PropMaxCount,
WeaponItems = _player.Weapons,
WeaponMaxCount = _player.WeaponCapacity,
StatRawData = CreateStatRawData()
};
}
public StatRawData CreateStatRawData()
{
var rawData = new StatRawData();
StatComponent statComponent = _player.StatComponent;
if (statComponent == null)
{
Log.Error("ShopUseCase.CreateStatRawData: Player StatComponent is null.");
return rawData;
}
foreach (StatType statType in (StatType[])Enum.GetValues(typeof(StatType)))
{
if (statType == StatType.None)
{
continue;
}
rawData.SetValue(statType, statComponent.GetStatValue(statType));
}
return rawData;
}
public ShopRefreshResult TryRefresh(int cost)
{
if (_player.Coin < cost)
{
return null;
}
_player.Coin -= cost;
_rollTimesInThisShop++;
int nextRefreshPrice = CalculateRefreshPrice(_currentLevel, _rollTimesInThisShop);
return new ShopRefreshResult
{
GoodsItems = RefreshGoodsSlots(GameEntry.Luban.Global.ShopGoodsCount),
RefreshPrice = nextRefreshPrice
};
}
public bool ToggleLock(int goodsIndex)
{
if (goodsIndex < 0 || goodsIndex >= _selections.Count)
{
Log.Error("ShopUseCase::ToggleLock: Invalid goodsIndex {0}.", goodsIndex);
return false;
}
ShopGoodsSelection selection = _selections[goodsIndex];
if (selection == null)
{
return false;
}
selection.IsLocked = !selection.IsLocked;
return selection.IsLocked;
}
public async UniTask<ShopPurchaseResult> TryPurchaseAsync(int goodsIndex)
{
if (goodsIndex < 0 || goodsIndex >= _selections.Count)
{
Log.Error("ShopFormUseCase::TryPurchase: Invalid index");
return null;
}
ShopGoodsSelection selection = _selections[goodsIndex];
if (selection == null)
{
Log.Warning("ShopFormUseCase::TryPurchase: Item already purchased.");
return null;
}
if (_player.Coin < selection.Price)
{
return null;
}
DisplayItemRawData displayItem = await ApplyGoodsPurchaseAsync(selection);
if (displayItem == null)
{
return null;
}
_player.Coin -= selection.Price;
_selections[goodsIndex] = null;
return new ShopPurchaseResult
{
GoodsIndex = goodsIndex,
DisplayItem = displayItem,
StatRawData = CreateStatRawData()
};
}
public void Continue()
{
_onShopFinish?.Invoke();
}
private List<GoodsItemRawData> RefreshGoodsSlots(int count)
{
if (_allGoods.Count == 0)
{
Log.Error("ShopUseCase::RefreshGoodsSlots(): _allGoods is empty");
return null;
}
int finalCount = Mathf.Min(count, _allGoods.Count);
while (_selections.Count < finalCount)
{
_selections.Add(null);
}
int currentLevel = _currentLevel;
float priceRandomPercent = GameEntry.Luban.Global.ShopPriceRandomPercent;
List<GoodsItemRawData> goodsItems = new List<GoodsItemRawData>(finalCount);
for (int i = 0; i < finalCount; i++)
{
ShopGoodsSelection existing = _selections[i];
if (existing != null && existing.IsLocked)
{
goodsItems.Add(CreateGoodsItemRawData(existing));
continue;
}
Rarity rarity = RollRarity(currentLevel);
GoodsConfig goodsConfig = PickGoodsByRarity(rarity);
if (goodsConfig == null)
{
Log.Error("ShopUseCase::RefreshGoodsSlots: No available goods for selection.");
break;
}
int price;
object dataRow;
ItemType itemType;
if (goodsConfig.GoodsType == GoodsType.Prop)
{
PropConfig propConfig = GameEntry.Luban.Get<PropConfig>(goodsConfig.RefId);
int basePrice = propConfig.Price;
price = CalculateRandomizedPrice(basePrice, priceRandomPercent);
itemType = ItemType.Prop;
rarity = propConfig.Rarity;
dataRow = propConfig;
}
else if (goodsConfig.GoodsType == GoodsType.Weapon)
{
WeaponConfig weaponConfig = GameEntry.Luban.Get<WeaponConfig>(goodsConfig.RefId);
int basePrice = weaponConfig.Price;
price = CalculateRandomizedPrice(basePrice, priceRandomPercent);
itemType = ItemType.Weapon;
rarity = weaponConfig.Rarity;
dataRow = weaponConfig;
}
else
{
Log.Warning(
$"ShopUseCase::RefreshGoodsSlots: Unsupported goods type = {goodsConfig.GoodsType}");
continue;
}
_selections[i] = new ShopGoodsSelection
{
GoodsType = goodsConfig.GoodsType,
RefId = goodsConfig.RefId,
Price = price,
IsLocked = false
};
goodsItems.Add(new GoodsItemRawData
{
Price = price,
Rarity = rarity,
ItemType = itemType,
DataRow = dataRow,
IsLocked = false
});
}
return goodsItems;
}
private GoodsItemRawData CreateGoodsItemRawData(ShopGoodsSelection selection)
{
GoodsItemRawData item = new GoodsItemRawData
{
Price = selection.Price,
IsLocked = selection.IsLocked
};
if (selection.GoodsType == GoodsType.Prop)
{
PropConfig propConfig = GameEntry.Luban.Get<PropConfig>(selection.RefId);
item.ItemType = ItemType.Prop;
item.Rarity = propConfig.Rarity;
item.DataRow = propConfig;
}
else if (selection.GoodsType == GoodsType.Weapon)
{
WeaponConfig weaponConfig = GameEntry.Luban.Get<WeaponConfig>(selection.RefId);
item.ItemType = ItemType.Weapon;
item.Rarity = weaponConfig.Rarity;
item.DataRow = weaponConfig;
}
return item;
}
private void BuildGoodsRarityPools()
{
_goodsByRarity.Clear();
_validGoods.Clear();
foreach (GoodsConfig goods in _allGoods)
{
if (!TryGetGoodsRarity(goods, out Rarity rarity))
{
continue;
}
_validGoods.Add(goods);
if (!_goodsByRarity.TryGetValue(rarity, out List<GoodsConfig> list))
{
list = new List<GoodsConfig>();
_goodsByRarity.Add(rarity, list);
}
list.Add(goods);
}
}
private GoodsConfig PickGoodsByRarity(Rarity rarity)
{
if (_goodsByRarity.TryGetValue(rarity, out List<GoodsConfig> list) && list.Count > 0)
{
return list[Random.Range(0, list.Count)];
}
if (_validGoods.Count > 0)
{
return _validGoods[Random.Range(0, _validGoods.Count)];
}
return null;
}
private bool TryGetGoodsRarity(GoodsConfig goods, out Rarity rarity)
{
rarity = Rarity.None;
if (goods.GoodsType == GoodsType.Prop)
{
PropConfig propConfig = GameEntry.Luban.Get<PropConfig>(goods.RefId);
rarity = propConfig.Rarity;
return true;
}
if (goods.GoodsType == GoodsType.Weapon)
{
WeaponConfig weaponConfig = GameEntry.Luban.Get<WeaponConfig>(goods.RefId);
rarity = weaponConfig.Rarity;
return true;
}
Log.Error("ShopUseCase.TryGetGoodsRarity: Unsupported goods type '{0}'.", goods.GoodsType);
return false;
}
private Rarity RollRarity(int level)
{
float luck = _player?.StatComponent != null ? _player.StatComponent.GetStatValue(StatType.Luck) : 0f;
return RarityUtility.SelectRarityForLevel(level, luck);
}
private static int CalculateRandomizedPrice(int basePrice, float priceRandomPercent)
{
float offsetPercent = Random.Range(-priceRandomPercent, priceRandomPercent);
int finalPrice = Mathf.RoundToInt(basePrice * (1f + offsetPercent));
return Mathf.Max(GameEntry.Luban.Global.ShopMinPrice, finalPrice);
}
private async UniTask<DisplayItemRawData> ApplyGoodsPurchaseAsync(ShopGoodsSelection goods)
{
if (goods.GoodsType == GoodsType.Prop)
{
PropConfig propConfig = GameEntry.Luban.Get<PropConfig>(goods.RefId);
_player.AddProp(new PropItem(propConfig));
return new DisplayItemRawData
{
IconAssetName = propConfig.Sprite,
Rarity = propConfig.Rarity,
IsWeapon = false
};
}
if (goods.GoodsType == GoodsType.Weapon)
{
if (_player.Weapons.Count >= _player.WeaponCapacity)
{
Log.Warning("ShopFormUseCase::ApplyGoodsPurchase: Weapon capacity is full.");
return null;
}
WeaponConfig weaponConfig = GameEntry.Luban.Get<WeaponConfig>(goods.RefId);
int id = GameEntry.Entity.NextId();
var weaponData = EntityDataFactory.Create(id, weaponConfig, _player.Id, CampType.Player);
WeaponBase weapon = await _player.AddWeaponAsync(weaponData);
if (weapon == null)
{
Log.Warning(
$"ShopFormUseCase::ApplyGoodsPurchase: Show weapon failed, weapon type id = {goods.RefId}");
return null;
}
return new DisplayItemRawData
{
IconAssetName = weaponConfig.Sprite,
Rarity = weaponConfig.Rarity,
IsWeapon = true
};
}
return null;
}
public bool TryRecycleWeapon(int argsIndex, int argsPrice)
{
var weapons = _player.Weapons;
if (weapons.Count <= 1)
{
Log.Warning("ShopFormUseCase::TryRecycleWeapon: Can not recycle the last weapon.");
return false;
}
var weapon = weapons[argsIndex];
int recyclePrice = Mathf.Max(0, argsPrice);
if (!_player.RemoveWeapon(weapon))
{
Log.Warning("ShopFormUseCase::TryRecycleWeapon: Remove weapon failed.");
return false;
}
_player.Coin += recyclePrice;
return true;
}
public int CalculateRecyclePrice(int basePrice)
{
return Mathf.FloorToInt(basePrice * GameEntry.Luban.Global.WeaponRecycleRate);
}
public bool CanCombineWeapon(int index, out int matchIndex, out WeaponConfig nextTierConfig)
{
return _player.CanCombineWeapon(index, out matchIndex, out nextTierConfig);
}
public async UniTask<bool> TryCombineWeaponAsync(int index)
{
if (!_player.CanCombineWeapon(index, out int matchIndex, out WeaponConfig nextTierConfig))
{
Log.Warning("ShopUseCase.TryCombineWeaponAsync: Cannot combine weapon at index {0}.", index);
return false;
}
var weapons = _player.Weapons;
WeaponBase weaponA = weapons[index];
WeaponBase weaponB = weapons[matchIndex];
WeaponBase newWeapon = await _player.CombineWeaponsAsync(weaponA, weaponB, nextTierConfig);
return newWeapon != null;
}
}
}