using System; using System.Collections.Generic; using UnityEngine; using YachtDice.Dice; namespace YachtDice.Game { public class DiceManager : MonoBehaviour { [SerializeField] private List diceRollers = new(); public event Action OnAllDiceSettled; public event Action OnDiceSettled; public int DiceCount => diceRollers.Count; private DiceInstance[] _diceInstances; private int _pendingCount; private void Awake() { int count = diceRollers.Count; _diceInstances = new DiceInstance[count]; for (int i = 0; i < count; i++) { var definition = diceRollers[i].Definition; _diceInstances[i] = new DiceInstance(definition); } } public bool IsLocked(int index) => _diceInstances[index].IsLocked; public void ToggleLock(int index) { _diceInstances[index].IsLocked = !_diceInstances[index].IsLocked; } public void SetLocked(int index, bool isLocked) { _diceInstances[index].IsLocked = isLocked; } public void UnlockAll() { for (int i = 0; i < _diceInstances.Length; i++) _diceInstances[i].IsLocked = false; } public void RollUnlocked() { for (int i = 0; i < diceRollers.Count; i++) if (diceRollers[i].IsRolling) return; _pendingCount = 0; for (int i = 0; i < diceRollers.Count; i++) { if (_diceInstances[i].IsLocked) continue; _pendingCount++; int capturedIndex = i; void Handler(int value) { diceRollers[capturedIndex].OnRollFinished -= Handler; _diceInstances[capturedIndex].Value = value; OnDiceSettled?.Invoke(capturedIndex, value); _pendingCount--; if (_pendingCount <= 0) OnAllDiceSettled?.Invoke(); } diceRollers[i].OnRollFinished += Handler; diceRollers[i].Roll(); } if (_pendingCount == 0) OnAllDiceSettled?.Invoke(); } /// Возвращает абстрактный список дайсов (основной API). public IReadOnlyList GetDice() => _diceInstances; /// Возвращает копию текущих значений (обратная совместимость). public int[] GetCurrentValues() { int[] values = new int[_diceInstances.Length]; for (int i = 0; i < _diceInstances.Length; i++) values[i] = _diceInstances[i].Value; return values; } public int GetValue(int index) => _diceInstances[index].Value; public bool IsAnyRolling { get { for (int i = 0; i < diceRollers.Count; i++) if (diceRollers[i].IsRolling) return true; return false; } } public void ReadAllValues() { for (int i = 0; i < diceRollers.Count; i++) { var diceComponent = diceRollers[i].GetComponent(); if (diceComponent != null && diceComponent.TryGetTopValue(out int val)) _diceInstances[i].Value = val; } } } }