PJ/Assets/scripts/dotfs_scripts/MANAGER_Shop.cs

163 lines
No EOL
4.9 KiB
C#
Raw Permalink 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.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
public class MANAGER_Shop : MonoBehaviour
{
public static MANAGER_Shop Instance { get; private set; }
[SerializeField] private string shopUrl = "ТУТ_ТВОЯ_ССЫЛКА_НА_JSON";
public ShopConfig ShopData { get; private set; }
public bool IsDataLoaded { get; private set; } = false;
private void Awake()
{
//PlayerPrefs.DeleteAll();
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else Destroy(gameObject);
}
private void Start()
{
StartCoroutine(LoadShopData());
}
private IEnumerator LoadShopData()
{
IsDataLoaded = false;
if (string.IsNullOrEmpty(shopUrl))
{
yield break;
}
using (UnityWebRequest req = UnityWebRequest.Get(shopUrl))
{
// Установим таймаут 10 секунд, чтобы запрос не висел вечно
req.timeout = 10;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.ConnectionError)
{
}
else if (req.result == UnityWebRequest.Result.ProtocolError)
{
}
else if (req.result == UnityWebRequest.Result.Success)
{
string json = req.downloadHandler.text;
try
{
ShopData = JsonConvert.DeserializeObject<ShopConfig>(json);
if (ShopData != null && ShopData.shops != null)
{
IsDataLoaded = true;
MANAGER_GameEvents.TriggerUIUpdate();
}
else
{
}
}
catch (Exception e)
{
}
}
else
{
}
}
}
// Получаем товары, которые: 1) Нужного типа 2) Выполнили условия 3) ЕЩЕ НЕ КУПЛЕНЫ
public List<ShopItem> GetAvailableItems(string shopType)
{
if (!IsDataLoaded || ShopData == null || ShopData.shops == null)
{
return new List<ShopItem>();
}
List<ShopItem> filtered = new List<ShopItem>();
foreach (var item in ShopData.shops)
{
// Исправлено: добавлена проверка и пропуск, если item пустой
if (item == null) continue;
bool typeMatch = string.Equals(item.shop_type?.Trim(), shopType.Trim(), StringComparison.OrdinalIgnoreCase);
bool visible = IsItemVisible(item);
bool purchased = IsItemPurchased(item.id);
if (typeMatch && visible && !purchased)
{
filtered.Add(item);
}
}
return filtered;
} // Скобка закрывает метод
private bool IsItemVisible(ShopItem item)
{
if (item.availableFromStart) return true;
if (item.conditions == null || item.conditions.Count == 0) return true;
return true;
}
public bool CanPlayerAfford(ShopItem item)
{
if (item.isGift) return true;
// ЗАГЛУШКА: Замени на реальное получение валюты из своего кошелька
int playerGold = PlayerPrefs.GetInt("Currency_Gold", 1000);
int playerIron = PlayerPrefs.GetInt("Currency_Iron", 500);
if (item.currency_type.Trim().Equals("Gold", StringComparison.OrdinalIgnoreCase))
return playerGold >= item.FinalPrice;
if (item.currency_type.Trim().Equals("Iron", StringComparison.OrdinalIgnoreCase))
return playerIron >= item.FinalPrice;
return false;
}
public bool IsItemPurchased(string itemId)
{
return PlayerPrefs.GetInt($"Shop_Purchased_{itemId}", 0) == 1;
}
// Возвращает true, если покупка удалась
public void BuyItem(ShopItem item)
{
if (IsItemPurchased(item.id)) return;
// TODO: Здесь добавь списание валюты через твой MANAGER_Economy
// Помечаем как купленное
PlayerPrefs.SetInt($"Shop_Purchased_{item.id}", 1);
PlayerPrefs.Save();
// Оповещаем UI, что нужно обновиться (это заставит список пересобраться)
MANAGER_GameEvents.TriggerUIUpdate();
}
}