SamsonGame/Assets/Scripts/Game/Session.cs

139 lines
3.3 KiB
C#
Raw Normal View History

2021-12-29 20:50:11 +03:00
using System;
using System.Collections;
using game;
using UnityEngine;
namespace RND
{
public class Session : MonoBehaviour
{
public event Action OnLevelStarted;
public event Action<EnumLevelResult> OnLevelEnded;
public event Action OnLevelSkip;
public Level Level { get; private set; }
public int EarnedCoins => _earnedCoinsAmount;
public GameObject LevelHolder { get; private set; }
private int _earnedCoinsAmount;
public void Init()
{
}
private IEnumerator Launch()
{
_earnedCoinsAmount = 0;
Level.Play();
yield return null;
}
private IEnumerator LoadLevel()
{
UI.Show<MainWindow>();
var coinsWindow = UI.GetOrCreate<CoinsCounterWindow>();
coinsWindow.SyncCoinsCounter();
coinsWindow.Show();
TryClear();
CreateLevelById(Save.Progress.LevelId);
Level.OnEnded += OnLevelEndedHandler;
Level.Init();
yield return null;
}
private void TryClear()
{
if (LevelHolder == null)
return;
Level.OnEnded -= OnLevelEndedHandler;
foreach (Transform child in LevelHolder.transform)
Destroy(child.gameObject);
Destroy(LevelHolder.gameObject);
}
private void CreateLevelById(uint level)
{
if (LevelHolder == null)
LevelHolder = new GameObject("LevelHolder");
GameObject prefab = LevelSettings.GetPrefabByID(level);
GameObject created = Instantiate(prefab, LevelHolder.transform);
created.transform.name = $"Level {level}";
Level = created.GetComponent<Level>();
}
public void AddEarnedCoins(int amount) => _earnedCoinsAmount += amount;
public void MultiplyEarnedCoins(int multiplier) => _earnedCoinsAmount *= multiplier;
public void SaveEarnedCoins()
{
Save.Inventory.AddConsumableItem(EnumConsumable.COIN, (uint) EarnedCoins);
_earnedCoinsAmount = 0;
}
private void OnLevelEndedHandler(EnumLevelResult result)
{
if (result == EnumLevelResult.WIN)
Save.Progress.IncreaseLevel();
OnLevelEnded?.Invoke(result);
}
public static Session Create()
{
return new GameObject("Session").AddComponent<Session>();
}
public void CreateLevel()
{
StartCoroutine(LoadLevel());
}
public void LaunchLevel()
{
StartCoroutine(Launch());
OnLevelStarted?.Invoke();
}
public void CreateAndLaunchLevel()
{
StartCoroutine(ForceLaunch());
}
private IEnumerator ForceLaunch()
{
yield return LoadLevel();
LaunchLevel();
}
public void SkipLevel()
{
OnLevelSkip?.Invoke();
Save.Progress.IncreaseLevel();
BuildLevel();
}
public void Restart()
{
BuildLevel();
}
public void BuildLevel()
{
UI.HideVisibleStack();
CreateLevel();
}
}
}