sea-battle/Assets/Scripts/CreditSystem.cs

99 lines
4.6 KiB
C#
Raw 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 UnityEngine;
using UnityEngine.Events;
/// <summary>
/// Хранит и управляет балансом кредитов обоих игроков.
/// Инициализируется всегда — независимо от режима ввода (клавиатура или COM).
/// COM-плата пишет монеты через CreditSystem.AddCredit(), а не напрямую в UI.
/// </summary>
public class CreditSystem : MonoBehaviour
{
[SerializeField] private bool saveMoneyBetweenSessions;
// ── События ──────────────────────────────────────────────────────────────
/// <summary>Вызывается при добавлении кредита: (playerId, новый_баланс)</summary>
public static UnityEvent<int, int> onCoinAdded;
/// <summary>Вызывается при списании кредита: (playerId, новый_баланс)</summary>
public static UnityEvent<int, int> onCoinRemoved;
/// <summary>
/// Вызывается один раз после инициализации — UI-компоненты подписываются здесь
/// на события монет. Срабатывает в обоих режимах (клавиатура и COM).
/// </summary>
public static System.Action OnInitialize;
// ── Приватные данные ──────────────────────────────────────────────────────
private static int _creditsPlayer1;
private static int _creditsPlayer2;
// ── Инициализация ─────────────────────────────────────────────────────────
/// <summary>Вызывается из Inici.Start() всегда, независимо от режима ввода.</summary>
public void Initialize()
{
onCoinAdded = new UnityEvent<int, int>();
onCoinRemoved = new UnityEvent<int, int>();
if (!saveMoneyBetweenSessions)
{
PlayerPrefs.SetInt("Player1_Coins", 0);
PlayerPrefs.SetInt("Player2_Coins", 0);
}
_creditsPlayer1 = PlayerPrefs.GetInt("Player1_Coins", 0);
_creditsPlayer2 = PlayerPrefs.GetInt("Player2_Coins", 0);
OnInitialize?.Invoke();
}
// ── Публичный API ─────────────────────────────────────────────────────────
/// <summary>Добавляет кредиты игроку. Вызывается ComWrapper при получении COIN.</summary>
public static void AddCredit(int coins = 1, int playerId = 1)
{
if (playerId == 1)
{
_creditsPlayer1 += coins;
PlayerPrefs.SetInt("Player1_Coins", _creditsPlayer1);
onCoinAdded?.Invoke(playerId, _creditsPlayer1);
}
else if (playerId == 2)
{
_creditsPlayer2 += coins;
PlayerPrefs.SetInt("Player2_Coins", _creditsPlayer2);
onCoinAdded?.Invoke(playerId, _creditsPlayer2);
}
// Счётчики запусков для системы призов
PlayerPrefs.SetInt(PrizeSystem.key_starts, PlayerPrefs.GetInt(PrizeSystem.key_starts) + 1);
PlayerPrefs.SetInt(PrizeSystem.key_startsNul, PlayerPrefs.GetInt(PrizeSystem.key_startsNul) + 1);
}
/// <summary>Списывает кредиты за старт игры. Возвращает false если денег нет.</summary>
public static bool Pay(int coins = 1, int playerId = 1)
{
if (SettingsManager.instance.GetSettingValue("Бесплатная игра") == "Вкл") return true;
ref int credits = ref (playerId == 1 ? ref _creditsPlayer1 : ref _creditsPlayer2);
string key = playerId == 1 ? "Player1_Coins" : "Player2_Coins";
if (credits > 0)
{
credits -= coins;
PlayerPrefs.SetInt(key, credits);
onCoinRemoved?.Invoke(playerId, credits);
return true;
}
return false;
}
/// <summary>Возвращает текущий баланс игрока.</summary>
public static int GetPlayerCredits(int playerId = 1)
{
return playerId == 1 ? _creditsPlayer1 : _creditsPlayer2;
}
}