chip-gameV3/Assets/Scripts/Common/GameManager.cs

328 lines
9.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 CharacterSystem;
using PrizeSystem;
using System;
using System.Collections;
using UnityEngine;
public enum GameMode { pve, pvp }
public class GameManager : MonoBehaviour
{
public static event Action<GameMode> OnGameStarted;
public static event Action<GameMode> OnGameFinished;
public event Action OnRoundStarted;
public PlayerStatsService StatsService;
public int botsAmount = 5;
[Header("General")]
public static GameManager Instance;
public GameObject AdminPanel, NumberPanel;
public TimerManager timerManager;
public RulesController rulesController;
public ChipPointer chipPointer;
[Header("Menu")]
public GameMode gameMode;
[HideInInspector] public Team currentPlayer = Team.Player2;
[Header("Scores")]
public int player1score = 0, player2score = 0, vsBotScore = 0;
private bool increaseVsBotTimer = false;
public int vsBotMoves;
public float vsBotThinkTime;
[HideInInspector]
public CheckResult lastResult;
[Header("Gameplay")]
public GameObject player1Chip;
public GameObject player2Chip;
public GameObject botChip;
public Chip chipPrefab;
[HideInInspector] public Chip currentChip;
public bool canReturnToMenu = false; //todo: разобраться нафига эта переменная
[Header("Панели ввода")]
public TextInput nameInput;
public Leaderboard leaderboard;
public GameObject CharactersConfigurator;
[Header("Переходы")]
[SerializeField] private MenuGameplayTransit menuGameplayTransit;
[SerializeField] TurnManager turnManager;
[SerializeField] private FieldCleaner _fieldCleaner;
public EndGameHandler endGameHandler;
public TurnTracker turnTracker;
public GameObject setPasswordPanel;
//public EnterPasswordPanel enterPasswordPanel;
public VitrinaPanel vitrinaPanel;
public QrPanel qrPanel;
public TakeOrRiskPanel takeOrRiskPanel;
private bool _isLeavingGameplay;
public void Initialize()
{
if (Instance == null)
{
Instance = this;
}
ComWrapper.PaymentReceived += ProcessDifficultyCounter;
ProcessDifficultyCounter();
SettingsManager.OnSettingsChanged+=ProcessDifficultyCounter;
StatsService = new();
StatsService.Initialize();
StartCoroutine(AddBotRecordEvery2Days());// добавлять каждые 2 дня запись
//stateMachine.ChangeState(new MenuState());
}
public void TryEnterGame(GameMode mode)
{
//ДЛЯ ОТЛАДКИ
//if (!PaymentSystem.TryPayForMode(mode))
// return;
SetMode(mode);
_isLeavingGameplay = false;
menuGameplayTransit.GameplayOpened += OnGameplayOpened;
menuGameplayTransit.GotoGameplay();
ControlsPerformer.Instance.SetControlable(null);
}
void OnGameplayOpened()
{
menuGameplayTransit.GameplayOpened -= OnGameplayOpened;
OnGameStarted?.Invoke(gameMode);
if (gameMode == GameMode.pve)
{
_fieldCleaner.Clear();
CharactersController.I.StartSession(StartRound);
}
else
StartRound();
}
private void OnApplicationQuit() => ComNativeWrapper.Serial_CloseAll();
private void Update()
{
if (increaseVsBotTimer)
vsBotThinkTime += Time.deltaTime;
}
public void GotoMenu()
{
if (_isLeavingGameplay)
return;
_isLeavingGameplay = true;
ControlsPerformer.Instance.SetControlable(null);
VideoUtility.CrossFadeToMenu();
_fieldCleaner.Clear();
if (gameMode == GameMode.pve)
{
CharactersController.I.HideCharacter();
CharactersController.ResetSystem();
}
OnGameFinished?.Invoke(gameMode);
menuGameplayTransit.GotoMenu();
}
public void StartVsBotTimer() => increaseVsBotTimer = true;
public void StopVsBotTimer() => increaseVsBotTimer = false;
public void SwitchPlayer()
{
currentPlayer = currentPlayer == Team.Player1 ? Team.Player2 : Team.Player1;
}
public void SetMode(GameMode mode) => gameMode = mode;
public void PerformRevenge()
=> ContinueAfterPveLoss();
public void PerformDrawRevenge()
=> ContinueAfterPveDraw();
public void ContinueAfterPveWin()
{
int nextCharacterIndex = CharactersController.CharacterIndex + 1;
if (nextCharacterIndex >= CharactersController.CharactersAmount)
{
GotoMenu();
return;
}
StartPveRound(nextCharacterIndex);
}
public void ContinueAfterPveLoss()
{
int previousCharacterIndex = Mathf.Max(CharactersController.CharacterIndex - 1, 0);
StartPveRound(previousCharacterIndex);
}
public void ContinueAfterPveDraw()
=> StartPveRound(CharactersController.CharacterIndex);
public void IncreaseScore(Team player)
{
if (player == Team.Player1)
player1score += 1;
else
player2score += 1;
}
public void ProcessDifficultyCounter()//вызывается каждый раз, когда приходит COIN с платы или обновились настройки
{
string previous = PlayerPrefs.GetString("PreviousBaseBotDifficulty", "Прохождение");
string difficultyType = SettingsManager.GetString(SettingKey.DIFFICULTY_MODE);
//Инициализация
if (!PlayerPrefs.HasKey("PulsesToResetDifficulty"))
PlayerPrefs.SetInt("PulsesToResetDifficulty", 100);
//если переход с повышенной на обычную - сброс счетчика
if (previous == "Заработок" && difficultyType != previous)
{
PaymentSystem.ResetPulsesCounter();
}
PlayerPrefs.SetString("PreviousBaseBotDifficulty", difficultyType);
if (difficultyType == "Заработок")
{
int pulses = PaymentSystem.PulsesCounter;
int pulsesToResetDifficulty = PlayerPrefs.GetInt("PulsesToResetDifficulty", 10);
//todo: разобраться
//if (pulses >= pulsesToResetDifficulty)
//{
// PaymentSystem.ResetPulsesCounter();
//Setting difficultySetting = SettingsManager.Container.TryGetSetting(SettingKeys.DIFFICULTY_MODE);
// difficultySetting.StringValue = "Прохождение";
// SettingsManager.OnSettingsChanged?.Invoke();
// SettingsManager.SaveContainerToFile();
// AdminPanel.GetComponent<SettingsScreen>().RefreshViews();
// print("Сложность сброшена");
//}
}
}
public void PrepareRound(Team firstPlayer)
{
currentPlayer = firstPlayer;
timerManager.SetupTimers(gameMode);
if (gameMode == GameMode.pve)
{
timerManager.SetActiveTimer(Team.Player1);
}
else if (gameMode == GameMode.pvp)
DualAvatarController.Instance.ShowCharacters();
VitrinaView.Instance.ActivateIfNeed();
DetermineNextTurn(switchPlayer: false);
}
public void DetermineNextTurn(bool switchPlayer = true)
{
if (switchPlayer) SwitchPlayer();
//spawnChip();
if (gameMode == GameMode.pvp)//переключаем таймеры только в pvp
{
timerManager.SetActiveTimer(currentPlayer);
LightSystem.Player(currentPlayer);
}
}
public void ResetGameSession()
{
vsBotThinkTime = 0;
StopVsBotTimer();
vsBotMoves = 0;
//movesAndTimeCounter.SetVisibility(false);
CharactersController.I.HideCharacter();
CharactersController.I.SetAllCharactersPrizeAvailable();
DualAvatarController.Instance?.HideCharacters();
CharactersController.ResetSystem();
player1score = 0;
player2score = 0;
vsBotScore = 0;
VitrinaView.Instance.Deactivate();
canReturnToMenu = true;
}
private void StartPveRound(int characterIndex)
{
_fieldCleaner.Clear();
CharactersController.I.ShowCharacter(characterIndex, StartRound);
}
private void StartRound()
{
turnTracker.ResetTracking();
turnTracker.EnableTimer(true);
turnManager.StartGame(gameMode);
PrepareRound(Team.Player1);
OnRoundStarted?.Invoke();
}
public void upgradeFeeshkaDifficulty()
{
string difficultyMode = SettingsManager.GetString(SettingKey.DIFFICULTY_MODE);
//todo: разобраться
//if (difficultyMode == "Прохождение")
//{
// PaymentSystem.ResetPulsesCounter();
// Setting difficultySetting = SettingsManager.Container.TryGetSetting(SettingKeys.DIFFICULTY_MODE);
// difficultySetting.StringValue = "Заработок";
// SettingsManager.OnSettingsChanged?.Invoke();
// SettingsManager.SaveContainerToFile();
// GameManager.instance.AdminPanel.GetComponent<SettingsScreen>().RefreshViews();
// print("Сложность повышена");
//}
}
IEnumerator AddBotRecordEvery2Days()
{
while (true)
{
yield return new WaitForSeconds(3600f); // ✅ Проверка каждый час
double lastRecordTime = PlayerPrefs.GetFloat("LastBotRecord", 0);
double currentTime = (DateTime.UtcNow - new System.DateTime(1970, 1, 1)).TotalSeconds;
if (currentTime - lastRecordTime >= 172800f)
{
StatsService.AddDailyRecord();
PlayerPrefs.SetFloat("LastBotRecord", (float)currentTime);
PlayerPrefs.Save();
}
}
}
}