REFACTOR: Развязал функциональность кошелька и ComWrapper

This commit is contained in:
_sega 2026-02-19 12:18:50 +03:00
parent db1b1fc364
commit f06c484c91
18 changed files with 147 additions and 115 deletions

View File

@ -15,18 +15,18 @@ public class CoinCounter : MonoBehaviour
SetRevengePriceVisibility(false);
UpdateCoins(PlayerPrefs.GetInt("CoinsCount", 0));
ComWrapper.onCoinAdded.AddListener(UpdateCoins);
ComWrapper.onCoinRemoved.AddListener(UpdateCoins);
SingleWallet.onCoinAdded.AddListener(UpdateCoins);
SingleWallet.onCoinRemoved.AddListener(UpdateCoins);
SettingsManager.OnSettingsChanged.AddListener(UpdateCoins);
}
private void OnDisable()
{
ComWrapper.onCoinAdded.RemoveListener(UpdateCoins);
ComWrapper.onCoinRemoved.AddListener(UpdateCoins);
SingleWallet.onCoinAdded.RemoveListener(UpdateCoins);
SingleWallet.onCoinRemoved.AddListener(UpdateCoins);
}
private void UpdateCoins() => UpdateCoins(ComWrapper.Balance);
private void UpdateCoins() => UpdateCoins(SingleWallet.Balance);
public void UpdateCoins(int newCount)
{

View File

@ -15,16 +15,16 @@ public class SettingsActions : MonoBehaviour
private void OnEnable()
{
SettingsManager.OnSettingsChanged?.AddListener(RefreshUI);
ComWrapper.onCoinAdded?.AddListener(RefreshUI);
ComWrapper.onCoinRemoved?.AddListener(RefreshUI);
SingleWallet.onCoinAdded?.AddListener(RefreshUI);
SingleWallet.onCoinRemoved?.AddListener(RefreshUI);
RefreshUI();
}
private void OnDisable()
{
SettingsManager.OnSettingsChanged?.RemoveListener(RefreshUI);
ComWrapper.onCoinAdded?.RemoveListener(RefreshUI);
ComWrapper.onCoinRemoved?.RemoveListener(RefreshUI);
SingleWallet.onCoinAdded?.RemoveListener(RefreshUI);
SingleWallet.onCoinRemoved?.RemoveListener(RefreshUI);
}
public void ResetCoinsCounter()
@ -70,7 +70,7 @@ public class SettingsActions : MonoBehaviour
public void ScreenTest() => ScreenTester.SetActive(true);
public void ResetBalance()
{
ComWrapper.Balance = 0;
SingleWallet.Balance = 0;
PlayerPrefs.SetInt("CoinsCount", 0);
SettingsManager.OnSettingsChanged?.Invoke();
}

View File

@ -240,7 +240,7 @@ public class MenuState : IState
{
int creditsPrice = gm.gameMode == GameMode.pve ? PlayerPrefs.GetInt("PricePVE", 10) : PlayerPrefs.GetInt("PricePVP", 10);
if (ComWrapper.Pay(creditsPrice))
if (SingleWallet.Pay(creditsPrice))
{//оплата успешно - закрываем меню
subState = MenuSubStates.ClosingMenu;
}

View File

@ -186,7 +186,7 @@ public class PositioningState : IState
if (exitPressed && !gm.moveMade)
{
gm.stateMachine.ChangeState(new ClearFieldState(toMenu: true, CellState.Player1));
ComWrapper.ReturnCredits(gm.gameMode);
SingleWallet.ReturnCredits(gm.gameMode);
GameManager.instance.timerManager.StopAllTimers();
}
}

View File

@ -329,7 +329,7 @@ public class ShowWinnerState : IState
if (ComWrapper.Pay(creditsPrice))
if (SingleWallet.Pay(creditsPrice))
{
subState = ShowWinnerSubstates.PanelRising;
}

View File

@ -453,7 +453,10 @@ public class GameManager : MonoBehaviour
GetComponent<Logger>().Initialize();
GetComponent<ComWrapper>().Initialize();
ComWrapper.onPulseRecieved.AddListener(ProcessDifficultyCounter);
SingleWallet.Initialize();
ComWrapper.PaymentReceived.AddListener(ProcessDifficultyCounter);
SettingsManager.OnSettingsChanged.AddListener(ProcessDifficultyCounter);
soundManager.Initialize();

View File

@ -14,15 +14,15 @@ public class GameModeAvailableActualizator : MonoBehaviour
private void OnEnable()
{
RefreshState();
ComWrapper.onCoinAdded.AddListener(RefreshState);
ComWrapper.onCoinRemoved.AddListener(RefreshState);
SingleWallet.onCoinAdded.AddListener(RefreshState);
SingleWallet.onCoinRemoved.AddListener(RefreshState);
SettingsManager.OnSettingsChanged.AddListener(RefreshState);
}
private void OnDisable()
{
ComWrapper.onCoinAdded.RemoveListener(RefreshState);
ComWrapper.onCoinRemoved.RemoveListener(RefreshState);
SingleWallet.onCoinAdded.RemoveListener(RefreshState);
SingleWallet.onCoinRemoved.RemoveListener(RefreshState);
SettingsManager.OnSettingsChanged.RemoveListener(RefreshState);
}
@ -40,7 +40,7 @@ public class GameModeAvailableActualizator : MonoBehaviour
private bool GameModeAvailable()
{
if (SettingsManager.GetBool("Freeplay", false)) return true;
return ComWrapper.Balance >= PlayerPrefs.GetInt(PriceKey, 10);
return SingleWallet.Balance >= PlayerPrefs.GetInt(PriceKey, 10);
}
private void RefreshState(int a = 0) => RefreshState();
private void RefreshState()

View File

@ -11,20 +11,16 @@ using System.Threading;
public class ComWrapper : MonoBehaviour
{
//Настраиваем из инспектора
[SerializeField] bool saveMoneyBetweenSessions;
[SerializeField] bool enablePrizeChecking = false; // Если хопер с проверкой наличия приза ставим true
[SerializeField] bool keepAlive = true;
public static UnityEvent onPulseRecieved;
public static UnityEvent<int> onCoinAdded;
public static UnityEvent<int> onCoinRemoved;
public static UnityEvent PaymentReceived;
public static UnityEvent<string> onInputRecieved;
private const string REQUEST_INPUT = "91";
private static int h;//идентификатор хэндла
private static byte[] buf = new byte[1024]; //Байт-буфер куда будут приходить данные с порта
public static int Balance;
bool boardEncrypted = false;
string encString;
@ -38,61 +34,10 @@ public class ComWrapper : MonoBehaviour
public void Initialize()
{
//добавить проверку флага инициализации
//Создаем ивенты
onCoinAdded = new UnityEvent<int>();
onCoinRemoved = new UnityEvent<int>();
onInputRecieved = new UnityEvent<string>();
onPulseRecieved = new UnityEvent();
//Начальная настройка
if (!saveMoneyBetweenSessions) PlayerPrefs.SetInt("CoinsCount", 0);
Balance = PlayerPrefs.GetInt("CoinsCount", 0);
onInputRecieved?.AddListener(InputRecievedCather);
StartCoroutine(SetupBoard());
}
public static void AddCredit()
{
int recieved = PlayerPrefs.GetInt("ValutaPerImpulse", 10);
Balance = Balance + recieved;
PlayerPrefs.SetInt("CoinsCount", Balance);
//Счетчики выручки
PlayerPrefs.SetInt(PrizeSystem.key_cash, PlayerPrefs.GetInt(PrizeSystem.key_cash) + recieved);
PlayerPrefs.SetInt(PrizeSystem.key_cashNul, PlayerPrefs.GetInt(PrizeSystem.key_cashNul) + recieved);
if (SettingsManager.GetString("BaseBotDifficulty", "Фиксированная") == "Повышенная")
{
int nowPulses = PlayerPrefs.GetInt("PulsesCounter", 0) + 1;
PlayerPrefs.SetInt("PulsesCounter", nowPulses);
}
onPulseRecieved?.Invoke();
onCoinAdded?.Invoke(Balance);
}
public static void AddCreditNoCounters(int amount)
{
Balance = Balance + amount;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinAdded?.Invoke(Balance);
}
public static void ReturnCredits(GameMode gameMode)
{
string gamemodePriceKey = gameMode == GameMode.pvp ? "PricePVP" : "PricePVE";
int gamemodePrice = PlayerPrefs.GetInt(gamemodePriceKey, 10);
Balance += gamemodePrice;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinAdded?.Invoke(Balance);
PaymentReceived = new UnityEvent();
}
public static void Send(string message)
@ -100,32 +45,12 @@ public class ComWrapper : MonoBehaviour
try
{
int w = ComNativeWrapper.Serial_WriteStringUTF8(h, message, 1); //w-количество записаных символов в порт. можно обработать
//Debug.Log("Wrote: " + w);
}
catch { Debug.LogError("Ошибка отправки строкового сигнала."); }
}
public static bool Pay(int amount)
{
//блок проверки оплаты
if (SettingsManager.GetBool("Freeplay", false))
{
return true;
}
if (Balance >= amount)
{
Balance -= amount;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinRemoved?.Invoke(Balance);
return true;
}
return false;
}
//===========================end: PUBLIC API===========================//
@ -180,7 +105,7 @@ public class ComWrapper : MonoBehaviour
{
Debug.LogError("COM: " + comInput);
if (comInput == "COIN") AddCredit();
if (comInput == "COIN") PaymentReceived?.Invoke();
if (comInput.StartsWith("INPUT")) onInputRecieved?.Invoke(comInput.Substring(5));
if (comInput.StartsWith("ENC:")) encString = comInput;
if (comInput.StartsWith("ACTIVATED:")) confirmString = comInput;
@ -203,7 +128,7 @@ public class ComWrapper : MonoBehaviour
private void initPort()
{
Logger.Instance.Log("Инициализация порта");
ComNativeWrapper.Serial_CloseAll();
ComNativeWrapper.Serial_CloseAll();//или все таки h?
//ComNativeWrapper.Serial_Close(h);
var ports = ComNativeWrapper.ListPorts();
@ -244,7 +169,6 @@ public class ComWrapper : MonoBehaviour
if (read > 0)
{
var s = Encoding.UTF8.GetString(buf, 0, read);
//DebugWindow.Message($"ReadLine len={read} data=[{s}]");
return s;
}
else if (read < 0)
@ -294,15 +218,13 @@ public class ComWrapper : MonoBehaviour
{
Debug.Log("COM: " + comInput);
if (comInput == "COIN") AddCredit();
if (comInput == "COIN") SingleWallet.AddCredit();
if (comInput.StartsWith("INPUT")) onInputRecieved?.Invoke(comInput.Substring(5)); //инвокаю сразу без префикса "INPUT"
if (comInput.StartsWith("ENC:")) encString = comInput;
if (comInput.StartsWith("ACTIVATED:")) confirmString = comInput;
}
}
private IEnumerator SetupBoard()
{
if (keepAliveCoroutine != null) StopCoroutine(keepAliveCoroutine);

View File

@ -1,5 +1,6 @@
using UnityEngine;
//Зависит от ComWrapper
public static class LightUtility
{
private const string LIGHT_COMMAND_PREFIX = "80";
@ -143,8 +144,6 @@ public static class LightUtility
return LIGHT_COMMAND_PREFIX + lightsingal;
}
}
public enum LightMode
{

View File

@ -8,7 +8,7 @@ public class PaymentEmulator : MonoBehaviour
void Update()
{
if (Input.GetKeyDown(key)) ComWrapper.AddCredit();
if (Input.GetKeyDown(key)) SingleWallet.AddCredit();
}
}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c4608a10f3808084bb6aafa0a58d3c53
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,89 @@
using UnityEngine;
using UnityEngine.Events;
/// <summary>
///Кошелек. При использовании предполагается что это единственный глобальный кошелек для всей игры.<br/>
///Зависимости:<br/>
///- ComWrapper<br/>
///- SettingsManager<br/>
/// </summary>
public static class SingleWallet
{
static bool saveMoneyBetweenSessions = true; //это надо из конфига тянуть!
public static int Balance;
public static UnityEvent<int> onCoinAdded;
public static UnityEvent<int> onCoinRemoved;
public static void Initialize()
{
if (!saveMoneyBetweenSessions) PlayerPrefs.SetInt("CoinsCount", 0);
Balance = PlayerPrefs.GetInt("CoinsCount", 0);
onCoinAdded = new UnityEvent<int>();
onCoinRemoved = new UnityEvent<int>();
ComWrapper.PaymentReceived.AddListener(AddCredit);
}
public static bool Pay(int amount)
{
//блок проверки оплаты
if (SettingsManager.GetBool("Freeplay", false))
{
return true;
}
if (Balance >= amount)
{
Balance -= amount;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinRemoved?.Invoke(Balance);
return true;
}
return false;
}
public static void AddCredit()
{
int recieved = PlayerPrefs.GetInt("ValutaPerImpulse", 10);
Balance = Balance + recieved;
PlayerPrefs.SetInt("CoinsCount", Balance);
//Счетчики выручки
PlayerPrefs.SetInt(PrizeSystem.key_cash, PlayerPrefs.GetInt(PrizeSystem.key_cash) + recieved);
PlayerPrefs.SetInt(PrizeSystem.key_cashNul, PlayerPrefs.GetInt(PrizeSystem.key_cashNul) + recieved);
if (SettingsManager.GetString("BaseBotDifficulty", "Фиксированная") == "Повышенная")
{
int nowPulses = PlayerPrefs.GetInt("PulsesCounter", 0) + 1;
PlayerPrefs.SetInt("PulsesCounter", nowPulses);
}
onCoinAdded?.Invoke(Balance);
}
public static void AddCreditNoCounters(int amount)
{
Balance = Balance + amount;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinAdded?.Invoke(Balance);
}
public static void ReturnCredits(GameMode gameMode)
{
string gamemodePriceKey = gameMode == GameMode.pvp ? "PricePVP" : "PricePVE";
int gamemodePrice = PlayerPrefs.GetInt(gamemodePriceKey, 10);
Balance += gamemodePrice;
PlayerPrefs.SetInt("CoinsCount", Balance);
onCoinAdded?.Invoke(Balance);
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0eae011cb79e7554d8d7c2d4ee2dc4c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -8,7 +8,7 @@ public class EffectActivator : MonoBehaviour
private void Start()
{
ComWrapper.onCoinRemoved.AddListener(Activate);
SingleWallet.onCoinRemoved.AddListener(Activate);
}

View File

@ -8,7 +8,7 @@ public class EffectActivator1 : MonoBehaviour
private void Start()
{
ComWrapper.onCoinAdded.AddListener(Activate);
SingleWallet.onCoinAdded.AddListener(Activate);
}

View File

@ -367,7 +367,7 @@ public class WebServer : MonoBehaviour
}
private void OnAddCoins(int amount) => ComWrapper.AddCreditNoCounters(amount);
private void OnAddCoins(int amount) => SingleWallet.AddCreditNoCounters(amount);
// =========================
// LEGACY /upd (как было)

View File

@ -11,14 +11,14 @@ public class DifficultyView : MonoBehaviour
private void OnEnable()
{
SettingsManager.OnSettingsChanged.AddListener(RefreshView);
ComWrapper.onCoinAdded.AddListener(RefreshView);
SingleWallet.onCoinAdded.AddListener(RefreshView);
sb = new StringBuilder();
RefreshView();
}
private void OnDisable()
{
SettingsManager.OnSettingsChanged.RemoveListener(RefreshView);
ComWrapper.onCoinAdded.RemoveListener(RefreshView);
SingleWallet.onCoinAdded.RemoveListener(RefreshView);
}
private void RefreshView()

View File

@ -70,8 +70,8 @@ public class SoundManager : MonoBehaviour
player2LandClip = Player2Land.GetComponent<AudioSource>().clip;
player2LandDuration = player2LandClip.length;
ComWrapper.onCoinAdded.AddListener(playAddCoin);
ComWrapper.onCoinRemoved.AddListener(playRemoveCoin);
SingleWallet.onCoinAdded.AddListener(playAddCoin);
SingleWallet.onCoinRemoved.AddListener(playRemoveCoin);
GameManager.instance.OnNoMoney.AddListener(playNoMoney);
ApplySettings();