165 lines
5.8 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 System.Collections;
using System.IO;
using UnityEngine;
/// <summary>
/// Система управления выдачей призов и ведения статистики игры.
/// Отвечает за процесс выдачи призов, подсчет запусков и наград.
/// </summary>
public class PrizeSystem : MonoBehaviour
{
public static string key_starts = "STARTS";
public static string key_startsNul = "STARTSNUL";
public static string key_prizesgiven = "PRIZESGIVEN";
public static string key_prizesgivenNul = "PRIZESGIVENNUL";
private static PrizeSystem instance;
private static Coroutine prizeCoroutine;
private static bool prizing = false;
//===========================start: PUBLIC API===========================//
/// <summary>
/// Инициализирует систему призов и счетчики статистики.
/// Должен быть вызван один раз при запуске приложения.
/// </summary>
/// <remarks>
/// Выполняет:
/// - Установку статического экземпляра (singleton)
/// - Инициализацию счетчиков в PlayerPrefs если они отсутствуют
/// - Подготовку системы к работе
/// </remarks>
public void Initialize()
{
instance = this;
InitCounters();
}
public static void GivePrize(Prize prize)
{
bool settingEnabled = SettingsManager.instance.GetSettingValue("Выдача призов при игре с ботом") == "Выдавать";
if (!settingEnabled) { Debug.Log("Выдача приза отключена в настройках"); return; }
if (prizing) { Debug.Log("Уже идет выдача приза. Не спамь кнопку."); return; }
Debug.Log($"Поступил заказ приз: {prize}");
PrizeType prizeType = prize.PrizeType;
if (prizeType == PrizeType.None)
{
Debug.Log("Пустой приз. Возврат.");
return;
}
if (prizeType == PrizeType.Hopper)
{
Debug.Log($"Хоппер в количестве {prize.Amount}");
instance.StartCoroutine(instance.HopperPrize(prize.Amount));
}
if (prizeType == PrizeType.Special)
{
//GameManager.instance.stateMachine.ChangeState(new PrizeState());
PlayerPrefs.SetInt("NeedSpecialPrize", 1);
}
if (prizeType == PrizeType.Ticket)
{
instance.StartCoroutine(instance.TicketPrize(prize.Amount));
}
if (prizeType == PrizeType.Marbles)
{
instance.StartCoroutine(instance.MarblesPrize(prize.Amount));
}
}
//===========================end: PUBLIC API===========================//
#region Приватные методы
private IEnumerator HopperPrize(int amount)
{
for (int i = 0; i < amount; i++)
{
bool noPrizWhenError = SettingsManager.instance.GetSettingValue("Выдавать приз при ошибке") == "Выкл";
bool errorRegistred = PlayerPrefs.GetInt(KeyVault.PRIZING_ERROR_REGISTRED, 0) == 1;
if (errorRegistred && noPrizWhenError) yield break;
prizing = true;
float timeout = 10; //сек
Debug.Log("Начинаю выдачу 301");
ComWrapper.Send("301");//включаем мотор
float startTime = Time.time;
bool success = false;
PlayerPrefs.SetInt("PrizeGivenBuffer", 0);//подготовка буфера
while (Time.time - startTime < timeout)
{
if (PlayerPrefs.GetInt("PrizeGivenBuffer", 0) == 1)
{
Debug.Log("Считан приз");
success = true;
IncreasePrizeCounters();
break;
}
yield return null;
}
//Выключаем мотор
Debug.Log("Выключаю мотор");
ComWrapper.Send("HOPPER1 OK");
Debug.Log("Закончил. Успех: " + success);
prizing = false;
if (success)
{
int prizesCount = PlayerPrefs.GetInt(KeyVault.PRIZES_AVAILABLE);
prizesCount = Mathf.Clamp(prizesCount - 1, 0, 9999);
PlayerPrefs.SetInt(KeyVault.PRIZES_AVAILABLE, prizesCount);
}
else
{
PlayerPrefs.SetInt(KeyVault.PRIZING_ERROR_REGISTRED, 1);
// SoundManager.instance.playClip(prizeErrorSound);
}
}
}
private IEnumerator TicketPrize(int amount)
{
for (int i = 0; i < amount; i++)
{
Debug.Log($"Отдаю тикет {i+1}");
yield return null;
}
}
private IEnumerator MarblesPrize(int amount)
{
for (int i = 0; i < amount; i++)
{
Debug.Log($"Отдаю марблс {i + 1}");
yield return null;
}
}
void IncreasePrizeCounters()
{
PlayerPrefs.SetInt(key_prizesgiven, PlayerPrefs.GetInt(key_prizesgiven) + 1);
PlayerPrefs.SetInt(key_prizesgivenNul, PlayerPrefs.GetInt(key_prizesgivenNul) + 1);
}
void InitCounters()
{
if (!PlayerPrefs.HasKey(key_starts)) PlayerPrefs.SetInt(key_starts, 0);
if (!PlayerPrefs.HasKey(key_startsNul)) PlayerPrefs.SetInt(key_startsNul, 0);
if (!PlayerPrefs.HasKey(key_prizesgiven)) PlayerPrefs.SetInt(key_prizesgiven, 0);
if (!PlayerPrefs.HasKey(key_prizesgivenNul)) PlayerPrefs.SetInt(key_prizesgivenNul, 0);
}
#endregion
}