[Fix] Code visual

This commit is contained in:
2026-02-28 19:25:26 +07:00
parent bee20fd1f8
commit e24b30743b
39 changed files with 2611 additions and 2687 deletions
+115 -116
View File
@@ -4,138 +4,137 @@ using UnityEngine;
namespace YachtDice.Dice namespace YachtDice.Dice
{ {
public class Dice : MonoBehaviour
public sealed class Dice : MonoBehaviour
{
[Serializable]
public struct Entry : IEquatable<Entry>
{ {
[SerializeField] private int value; [Serializable]
[SerializeField] private Transform point; public struct Entry : IEquatable<Entry>
public int Value => value;
public Transform Point => point;
public bool Equals(Entry other) => point == other.point;
public override bool Equals(object obj) => obj is Entry other && Equals(other);
public override int GetHashCode() => point != null ? point.GetHashCode() : 0;
}
[SerializeField] private List<Entry> entries = new();
private HashSet<Entry> entrySet;
private void Awake() => RebuildSet();
private void OnValidate() => RebuildSet();
public void Test()
{
if (!TryGetTopValue(out var top) || !TryGetBottomValue(out var bottom))
return;
Debug.Log($"Top Value: {top}, Bottom Value: {bottom}");
AlignToTopByLocalAngles();
}
private void RebuildSet()
{
entrySet = new HashSet<Entry>();
if (entries == null) return;
for (int i = 0; i < entries.Count; i++) entrySet.Add(entries[i]);
}
public bool TryGetTopValue(out int value) => TryGetExtremeValue(isTop: true, out value);
public bool TryGetBottomValue(out int value) => TryGetExtremeValue(isTop: false, out value);
public int AlignToTopByLocalAngles()
{
var e = GetExtremeEntryByWorldY(isTop: true);
AlignByFaceLocalAngles(e.Point);
return e.Value;
}
public int AlignToBottomByLocalAngles()
{
var e = GetExtremeEntryByWorldY(isTop: false);
AlignByFaceLocalAngles(e.Point);
return e.Value;
}
private bool TryGetExtremeValue(bool isTop, out int value)
{
value = default;
if (entrySet == null || entrySet.Count == 0)
return false;
bool found = false;
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
int best = default;
foreach (var e in entrySet)
{ {
var p = e.Point; [SerializeField] private int value;
if (!p) continue; [SerializeField] private Transform point;
float y = p.position.y; public int Value => value;
if (!found || (isTop ? y > bestY : y < bestY)) public Transform Point => point;
{
found = true; public bool Equals(Entry other) => point == other.point;
bestY = y; public override bool Equals(object obj) => obj is Entry other && Equals(other);
best = e.Value; public override int GetHashCode() => point != null ? point.GetHashCode() : 0;
}
} }
if (!found) return false; [SerializeField] private List<Entry> entries = new();
value = best; private HashSet<Entry> entrySet;
return true;
}
private Entry GetExtremeEntryByWorldY(bool isTop) private void Awake() => RebuildSet();
{ private void OnValidate() => RebuildSet();
if (entrySet == null || entrySet.Count == 0)
throw new InvalidOperationException("Dice: коллекция пуста.");
bool found = false; public void Test()
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
Entry best = default;
foreach (var e in entrySet)
{ {
var p = e.Point; if (!TryGetTopValue(out var top) || !TryGetBottomValue(out var bottom))
if (!p) continue; return;
float y = p.position.y; Debug.Log($"Top Value: {top}, Bottom Value: {bottom}");
if (!found || (isTop ? y > bestY : y < bestY))
{ AlignToTopByLocalAngles();
found = true;
bestY = y;
best = e;
}
} }
if (!found) private void RebuildSet()
throw new InvalidOperationException("Dice: все Transform == null."); {
entrySet = new HashSet<Entry>();
if (entries == null) return;
for (int i = 0; i < entries.Count; i++) entrySet.Add(entries[i]);
}
return best; public bool TryGetTopValue(out int value) => TryGetExtremeValue(isTop: true, out value);
} public bool TryGetBottomValue(out int value) => TryGetExtremeValue(isTop: false, out value);
private static float Norm180(float a) public int AlignToTopByLocalAngles()
{ {
a %= 360f; var e = GetExtremeEntryByWorldY(isTop: true);
return a > 180f ? a - 360f : (a < -180f ? a + 360f : a); AlignByFaceLocalAngles(e.Point);
} return e.Value;
}
private void AlignByFaceLocalAngles(Transform facePoint) public int AlignToBottomByLocalAngles()
{ {
if (!facePoint) throw new InvalidOperationException("Dice: facePoint == null."); var e = GetExtremeEntryByWorldY(isTop: false);
AlignByFaceLocalAngles(e.Point);
return e.Value;
}
transform.localEulerAngles = Vector3.Scale(facePoint.localEulerAngles, new Vector3(-1f, -1f, -1f)); private bool TryGetExtremeValue(bool isTop, out int value)
{
value = default;
var e = transform.localEulerAngles; if (entrySet == null || entrySet.Count == 0)
transform.localEulerAngles = new Vector3(Norm180(e.x), Norm180(e.y), Norm180(e.z)); return false;
bool found = false;
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
int best = default;
foreach (var e in entrySet)
{
var p = e.Point;
if (!p) continue;
float y = p.position.y;
if (!found || (isTop ? y > bestY : y < bestY))
{
found = true;
bestY = y;
best = e.Value;
}
}
if (!found) return false;
value = best;
return true;
}
private Entry GetExtremeEntryByWorldY(bool isTop)
{
if (entrySet == null || entrySet.Count == 0)
throw new InvalidOperationException("Dice: коллекция пуста.");
bool found = false;
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
Entry best = default;
foreach (var e in entrySet)
{
var p = e.Point;
if (!p) continue;
float y = p.position.y;
if (!found || (isTop ? y > bestY : y < bestY))
{
found = true;
bestY = y;
best = e;
}
}
if (!found)
throw new InvalidOperationException("Dice: все Transform == null.");
return best;
}
private static float Norm180(float a)
{
a %= 360f;
return a > 180f ? a - 360f : (a < -180f ? a + 360f : a);
}
private void AlignByFaceLocalAngles(Transform facePoint)
{
if (!facePoint) throw new InvalidOperationException("Dice: facePoint == null.");
transform.localEulerAngles = Vector3.Scale(facePoint.localEulerAngles, new Vector3(-1f, -1f, -1f));
var e = transform.localEulerAngles;
transform.localEulerAngles = new Vector3(Norm180(e.x), Norm180(e.y), Norm180(e.z));
}
} }
} }
}
+125 -126
View File
@@ -5,152 +5,151 @@ using Random = UnityEngine.Random;
namespace YachtDice.Dice namespace YachtDice.Dice
{ {
/// <summary>
/// Красиво подбрасывает и раскручивает кубик, ждёт пока он остановится,
/// плавно доворачивает до ровного положения и сообщает результат.
/// </summary>
public sealed class DiceRoller : MonoBehaviour
{
[Header("References")]
[SerializeField] private Dice dice;
[SerializeField] private Rigidbody rb;
[Header("Throw Settings")]
[Tooltip("Сила подброса вверх")]
[SerializeField] private float throwUpForce = 6f;
[Tooltip("Горизонтальный разброс")]
[SerializeField] private float throwScatter = 1.5f;
[Tooltip("Минимальный крутящий момент")]
[SerializeField] private float torqueMin = 15f;
[Tooltip("Максимальный крутящий момент")]
[SerializeField] private float torqueMax = 30f;
[Header("Settle Detection")]
[Tooltip("Порог скорости, ниже которого кубик считается остановившимся")]
[SerializeField] private float settleSpeed = 0.05f;
[Tooltip("Сколько секунд кубик должен быть неподвижен, чтобы засчитать остановку")]
[SerializeField] private float settleDelay = 0.3f;
[Header("Snap Alignment")]
[Tooltip("Длительность плавного доворота к ровному положению")]
[SerializeField] private float snapDuration = 0.35f;
[SerializeField]
private AnimationCurve snapCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
/// <summary> /// <summary>
/// Вызывается когда кубик полностью остановился. Аргумент — выпавшее значение. /// Красиво подбрасывает и раскручивает кубик, ждёт пока он остановится,
/// плавно доворачивает до ровного положения и сообщает результат.
/// </summary> /// </summary>
public event Action<int> OnRollFinished; public class DiceRoller : MonoBehaviour
/// <summary>
/// Идёт ли сейчас бросок.
/// </summary>
public bool IsRolling { get; private set; }
private Coroutine rollRoutine;
private void Reset()
{ {
dice = GetComponent<Dice>(); [Header("References")]
rb = GetComponent<Rigidbody>(); [SerializeField] private Dice dice;
} [SerializeField] private Rigidbody rb;
[Header("Throw Settings")]
[Tooltip("Сила подброса вверх")]
[SerializeField] private float throwUpForce = 6f;
/// <summary> [Tooltip("Горизонтальный разброс")]
/// Бросить кубик. Повторный вызов во время броска игнорируется. [SerializeField] private float throwScatter = 1.5f;
/// </summary>
public void Roll()
{
if (IsRolling) return;
if (rollRoutine != null) [Tooltip("Минимальный крутящий момент")]
StopCoroutine(rollRoutine); [SerializeField] private float torqueMin = 15f;
rollRoutine = StartCoroutine(RollSequence()); [Tooltip("Максимальный крутящий момент")]
} [SerializeField] private float torqueMax = 30f;
private IEnumerator RollSequence() [Header("Settle Detection")]
{ [Tooltip("Порог скорости, ниже которого кубик считается остановившимся")]
IsRolling = true; [SerializeField] private float settleSpeed = 0.05f;
// ── 1. Подготовка ──────────────────────────────────────────── [Tooltip("Сколько секунд кубик должен быть неподвижен, чтобы засчитать остановку")]
rb.isKinematic = false; [SerializeField] private float settleDelay = 0.3f;
rb.useGravity = true;
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
// ── 2. Импульс: подбросить вверх с лёгким разбросом ───────── [Header("Snap Alignment")]
Vector3 force = new Vector3( [Tooltip("Длительность плавного доворота к ровному положению")]
Random.Range(-throwScatter, throwScatter), [SerializeField] private float snapDuration = 0.35f;
throwUpForce,
Random.Range(-throwScatter, throwScatter)
);
rb.AddForce(force, ForceMode.Impulse);
// ── 3. Случайный крутящий момент — красивое вращение ──────── [SerializeField]
Vector3 torque = Random.onUnitSphere * Random.Range(torqueMin, torqueMax); private AnimationCurve snapCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
rb.AddTorque(torque, ForceMode.Impulse);
// Даём кубику взлететь /// <summary>
yield return new WaitForSeconds(0.2f); /// Вызывается когда кубик полностью остановился. Аргумент — выпавшее значение.
/// </summary>
public event Action<int> OnRollFinished;
// ── 4. Ждём пока кубик успокоится ─────────────────────────── /// <summary>
float stillTimer = 0f; /// Идёт ли сейчас бросок.
float sqrThreshold = settleSpeed * settleSpeed; /// </summary>
public bool IsRolling { get; private set; }
while (stillTimer < settleDelay) private Coroutine rollRoutine;
private void Reset()
{ {
yield return new WaitForFixedUpdate(); dice = GetComponent<Dice>();
rb = GetComponent<Rigidbody>();
bool isSlow = rb.linearVelocity.sqrMagnitude < sqrThreshold
&& rb.angularVelocity.sqrMagnitude < sqrThreshold;
stillTimer = isSlow ? stillTimer + Time.fixedDeltaTime : 0f;
} }
// ── 5. Замораживаем физику и читаем верхнюю грань ───────────
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.isKinematic = true;
if (!dice.TryGetTopValue(out int topValue)) /// <summary>
/// Бросить кубик. Повторный вызов во время броска игнорируется.
/// </summary>
public void Roll()
{ {
Debug.LogWarning("DiceRoller: не удалось определить верхнюю грань."); if (IsRolling) return;
if (rollRoutine != null)
StopCoroutine(rollRoutine);
rollRoutine = StartCoroutine(RollSequence());
}
private IEnumerator RollSequence()
{
IsRolling = true;
// ── 1. Подготовка ────────────────────────────────────────────
rb.isKinematic = false;
rb.useGravity = true;
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
// ── 2. Импульс: подбросить вверх с лёгким разбросом ─────────
Vector3 force = new Vector3(
Random.Range(-throwScatter, throwScatter),
throwUpForce,
Random.Range(-throwScatter, throwScatter)
);
rb.AddForce(force, ForceMode.Impulse);
// ── 3. Случайный крутящий момент — красивое вращение ────────
Vector3 torque = Random.onUnitSphere * Random.Range(torqueMin, torqueMax);
rb.AddTorque(torque, ForceMode.Impulse);
// Даём кубику взлететь
yield return new WaitForSeconds(0.2f);
// ── 4. Ждём пока кубик успокоится ───────────────────────────
float stillTimer = 0f;
float sqrThreshold = settleSpeed * settleSpeed;
while (stillTimer < settleDelay)
{
yield return new WaitForFixedUpdate();
bool isSlow = rb.linearVelocity.sqrMagnitude < sqrThreshold
&& rb.angularVelocity.sqrMagnitude < sqrThreshold;
stillTimer = isSlow ? stillTimer + Time.fixedDeltaTime : 0f;
}
// ── 5. Замораживаем физику и читаем верхнюю грань ───────────
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.isKinematic = true;
if (!dice.TryGetTopValue(out int topValue))
{
Debug.LogWarning("DiceRoller: не удалось определить верхнюю грань.");
IsRolling = false;
yield break;
}
// ── 6. Плавный доворот до ровного положения ─────────────────
Quaternion startRot = transform.rotation;
// Вычисляем целевой поворот через Dice.AlignToTopByLocalAngles
dice.AlignToTopByLocalAngles();
Quaternion targetRot = transform.rotation;
// Откатываемся обратно — будем интерполировать
transform.rotation = startRot;
float elapsed = 0f;
while (elapsed < snapDuration)
{
elapsed += Time.deltaTime;
float t = snapCurve.Evaluate(Mathf.Clamp01(elapsed / snapDuration));
transform.rotation = Quaternion.Slerp(startRot, targetRot, t);
yield return null;
}
transform.rotation = targetRot;
// ── 7. Готово ───────────────────────────────────────────────
IsRolling = false; IsRolling = false;
yield break; OnRollFinished?.Invoke(topValue);
// Debug.Log($"{gameObject.name} | Выпало: <b>{topValue}</b>");
} }
// ── 6. Плавный доворот до ровного положения ─────────────────
Quaternion startRot = transform.rotation;
// Вычисляем целевой поворот через Dice.AlignToTopByLocalAngles
dice.AlignToTopByLocalAngles();
Quaternion targetRot = transform.rotation;
// Откатываемся обратно — будем интерполировать
transform.rotation = startRot;
float elapsed = 0f;
while (elapsed < snapDuration)
{
elapsed += Time.deltaTime;
float t = snapCurve.Evaluate(Mathf.Clamp01(elapsed / snapDuration));
transform.rotation = Quaternion.Slerp(startRot, targetRot, t);
yield return null;
}
transform.rotation = targetRot;
// ── 7. Готово ───────────────────────────────────────────────
IsRolling = false;
OnRollFinished?.Invoke(topValue);
// Debug.Log($"{gameObject.name} | Выпало: <b>{topValue}</b>");
} }
} }
}
+33 -34
View File
@@ -3,46 +3,45 @@ using UnityEngine;
namespace YachtDice.Economy namespace YachtDice.Economy
{ {
public class CurrencyBank : MonoBehaviour
public sealed class CurrencyBank : MonoBehaviour
{
[SerializeField] private int startingBalance = 500;
private int balance;
public int Balance => balance;
public event Action<int> OnBalanceChanged;
private void Awake()
{ {
balance = startingBalance; [SerializeField] private int startingBalance = 500;
}
public void Add(int amount) private int balance;
{
if (amount <= 0) return;
balance += amount; public int Balance => balance;
OnBalanceChanged?.Invoke(balance);
}
public bool Spend(int amount) public event Action<int> OnBalanceChanged;
{
if (amount <= 0) return false;
if (balance < amount) return false;
balance -= amount; private void Awake()
OnBalanceChanged?.Invoke(balance); {
return true; balance = startingBalance;
} }
public bool CanAfford(int amount) => balance >= amount; public void Add(int amount)
{
if (amount <= 0) return;
public void SetBalance(int value) balance += amount;
{ OnBalanceChanged?.Invoke(balance);
balance = Mathf.Max(0, value); }
OnBalanceChanged?.Invoke(balance);
public bool Spend(int amount)
{
if (amount <= 0) return false;
if (balance < amount) return false;
balance -= amount;
OnBalanceChanged?.Invoke(balance);
return true;
}
public bool CanAfford(int amount) => balance >= amount;
public void SetBalance(int value)
{
balance = Mathf.Max(0, value);
OnBalanceChanged?.Invoke(balance);
}
} }
} }
}
-39
View File
@@ -1,39 +0,0 @@
using UnityEngine;
using YachtDice.Scoring;
namespace YachtDice.Game
{
public sealed class DebugGameInput : MonoBehaviour
{
[SerializeField] private GameManager gameManager;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
gameManager.Roll();
// 1-5: toggle lock on dice 0-4
if (Input.GetKeyDown(KeyCode.Alpha1)) gameManager.ToggleDiceLock(0);
if (Input.GetKeyDown(KeyCode.Alpha2)) gameManager.ToggleDiceLock(1);
if (Input.GetKeyDown(KeyCode.Alpha3)) gameManager.ToggleDiceLock(2);
if (Input.GetKeyDown(KeyCode.Alpha4)) gameManager.ToggleDiceLock(3);
if (Input.GetKeyDown(KeyCode.Alpha5)) gameManager.ToggleDiceLock(4);
// Score categories
if (Input.GetKeyDown(KeyCode.F1)) gameManager.ScoreInCategory(YachtCategory.Ones);
if (Input.GetKeyDown(KeyCode.F2)) gameManager.ScoreInCategory(YachtCategory.Twos);
if (Input.GetKeyDown(KeyCode.F3)) gameManager.ScoreInCategory(YachtCategory.Threes);
if (Input.GetKeyDown(KeyCode.F4)) gameManager.ScoreInCategory(YachtCategory.Fours);
if (Input.GetKeyDown(KeyCode.F5)) gameManager.ScoreInCategory(YachtCategory.Fives);
if (Input.GetKeyDown(KeyCode.F6)) gameManager.ScoreInCategory(YachtCategory.Sixes);
if (Input.GetKeyDown(KeyCode.F7)) gameManager.ScoreInCategory(YachtCategory.ThreeOfAKind);
if (Input.GetKeyDown(KeyCode.F8)) gameManager.ScoreInCategory(YachtCategory.FourOfAKind);
if (Input.GetKeyDown(KeyCode.F9)) gameManager.ScoreInCategory(YachtCategory.FullHouse);
if (Input.GetKeyDown(KeyCode.F10)) gameManager.ScoreInCategory(YachtCategory.SmallStraight);
if (Input.GetKeyDown(KeyCode.F11)) gameManager.ScoreInCategory(YachtCategory.LargeStraight);
if (Input.GetKeyDown(KeyCode.F12)) gameManager.ScoreInCategory(YachtCategory.Yacht);
if (Input.GetKeyDown(KeyCode.C)) gameManager.ScoreInCategory(YachtCategory.Chance);
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 982f0996b85edfe419b07ddb36d6e235
+82 -83
View File
@@ -5,104 +5,103 @@ using YachtDice.Dice;
namespace YachtDice.Game namespace YachtDice.Game
{ {
public class DiceManager : MonoBehaviour
public sealed class DiceManager : MonoBehaviour
{
[SerializeField] private List<DiceRoller> diceRollers = new();
public event Action OnAllDiceSettled;
public event Action<int, int> OnDieSettled;
public int DiceCount => diceRollers.Count;
private bool[] locked;
private int[] currentValues;
private int pendingCount;
private void Awake()
{ {
int count = diceRollers.Count; [SerializeField] private List<DiceRoller> diceRollers = new();
locked = new bool[count];
currentValues = new int[count];
}
public bool IsLocked(int index) => locked[index]; public event Action OnAllDiceSettled;
public event Action<int, int> OnDieSettled;
public void ToggleLock(int index) public int DiceCount => diceRollers.Count;
{
locked[index] = !locked[index];
}
public void SetLocked(int index, bool isLocked) private bool[] locked;
{ private int[] currentValues;
locked[index] = isLocked; private int pendingCount;
}
public void UnlockAll() private void Awake()
{
for (int i = 0; i < locked.Length; i++) locked[i] = 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 (locked[i]) continue; int count = diceRollers.Count;
locked = new bool[count];
pendingCount++; currentValues = new int[count];
int capturedIndex = i;
void Handler(int value)
{
diceRollers[capturedIndex].OnRollFinished -= Handler;
currentValues[capturedIndex] = value;
OnDieSettled?.Invoke(capturedIndex, value);
pendingCount--;
if (pendingCount <= 0)
OnAllDiceSettled?.Invoke();
}
diceRollers[i].OnRollFinished += Handler;
diceRollers[i].Roll();
} }
if (pendingCount == 0) public bool IsLocked(int index) => locked[index];
OnAllDiceSettled?.Invoke();
}
public int[] GetCurrentValues() public void ToggleLock(int index)
{ {
int[] copy = new int[currentValues.Length]; locked[index] = !locked[index];
Array.Copy(currentValues, copy, currentValues.Length); }
return copy;
}
public int GetValue(int index) => currentValues[index]; public void SetLocked(int index, bool isLocked)
{
locked[index] = isLocked;
}
public bool IsAnyRolling public void UnlockAll()
{ {
get for (int i = 0; i < locked.Length; i++) locked[i] = false;
}
public void RollUnlocked()
{ {
for (int i = 0; i < diceRollers.Count; i++) for (int i = 0; i < diceRollers.Count; i++)
if (diceRollers[i].IsRolling) return true; if (diceRollers[i].IsRolling) return;
return false;
}
}
public void ReadAllValues() pendingCount = 0;
{
for (int i = 0; i < diceRollers.Count; i++) for (int i = 0; i < diceRollers.Count; i++)
{
if (locked[i]) continue;
pendingCount++;
int capturedIndex = i;
void Handler(int value)
{
diceRollers[capturedIndex].OnRollFinished -= Handler;
currentValues[capturedIndex] = value;
OnDieSettled?.Invoke(capturedIndex, value);
pendingCount--;
if (pendingCount <= 0)
OnAllDiceSettled?.Invoke();
}
diceRollers[i].OnRollFinished += Handler;
diceRollers[i].Roll();
}
if (pendingCount == 0)
OnAllDiceSettled?.Invoke();
}
public int[] GetCurrentValues()
{ {
var diceComponent = diceRollers[i].GetComponent<Dice>(); int[] copy = new int[currentValues.Length];
if (diceComponent != null && diceComponent.TryGetTopValue(out int val)) Array.Copy(currentValues, copy, currentValues.Length);
currentValues[i] = val; return copy;
}
public int GetValue(int index) => currentValues[index];
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<Dice.Dice>();
if (diceComponent != null && diceComponent.TryGetTopValue(out int val))
currentValues[i] = val;
}
} }
} }
} }
}
+85 -86
View File
@@ -4,102 +4,101 @@ using YachtDice.Scoring;
namespace YachtDice.Game namespace YachtDice.Game
{ {
public class GameManager : MonoBehaviour
public sealed class GameManager : MonoBehaviour
{
[Header("References")]
[SerializeField] private DiceManager diceManager;
[SerializeField] private ScoringSystem scoringSystem;
[Header("Settings")]
[SerializeField] private int maxRollsPerTurn = 3;
public int CurrentRoll { get; private set; }
public int CurrentTurn { get; private set; }
public bool CanRoll => CurrentRoll < maxRollsPerTurn && !diceManager.IsAnyRolling;
public bool CanScore => CurrentRoll > 0 && !diceManager.IsAnyRolling;
public bool IsGameOver => scoringSystem.IsComplete;
public event Action<int> OnTurnStarted;
public event Action<int> OnRollComplete;
public event Action<YachtCategory, int> OnScored;
public event Action<int> OnGameOver;
private void Start()
{ {
StartNewGame(); [Header("References")]
} [SerializeField] private DiceManager diceManager;
[SerializeField] private ScoringSystem scoringSystem;
public void StartNewGame() [Header("Settings")]
{ [SerializeField] private int maxRollsPerTurn = 3;
scoringSystem.ResetScorecard();
CurrentTurn = 0;
StartNewTurn();
}
private void StartNewTurn() public int CurrentRoll { get; private set; }
{ public int CurrentTurn { get; private set; }
CurrentTurn++;
CurrentRoll = 0;
diceManager.UnlockAll();
OnTurnStarted?.Invoke(CurrentTurn);
Debug.Log($"=== Turn {CurrentTurn} ===");
}
public void Roll() public bool CanRoll => CurrentRoll < maxRollsPerTurn && !diceManager.IsAnyRolling;
{ public bool CanScore => CurrentRoll > 0 && !diceManager.IsAnyRolling;
if (!CanRoll) return; public bool IsGameOver => scoringSystem.IsComplete;
CurrentRoll++; public event Action<int> OnTurnStarted;
diceManager.OnAllDiceSettled += HandleAllDiceSettled; public event Action<int> OnRollComplete;
diceManager.RollUnlocked(); public event Action<YachtCategory, int> OnScored;
} public event Action<int> OnGameOver;
private void HandleAllDiceSettled() private void Start()
{
diceManager.OnAllDiceSettled -= HandleAllDiceSettled;
int[] values = diceManager.GetCurrentValues();
Debug.Log($"Roll {CurrentRoll}/{maxRollsPerTurn} | Dice: [{string.Join(", ", values)}]");
OnRollComplete?.Invoke(CurrentRoll);
}
public void ToggleDiceLock(int index)
{
if (diceManager.IsAnyRolling) return;
if (CurrentRoll == 0) return;
diceManager.ToggleLock(index);
bool isLocked = diceManager.IsLocked(index);
Debug.Log($"Dice {index + 1} (value={diceManager.GetValue(index)}): {(isLocked ? "LOCKED" : "UNLOCKED")}");
}
public void ScoreInCategory(YachtCategory category)
{
if (!CanScore) return;
if (scoringSystem.IsCategoryUsed(category)) return;
int[] values = diceManager.GetCurrentValues();
ScoreResult result = scoringSystem.ScoreCategory(values, category);
Debug.Log($"Scored {category}: base={result.BaseScore}, " +
$"bonus=+{result.FlatBonus}, mult=x{result.Multiplier:F1}, " +
$"FINAL={result.FinalScore} | Total={scoringSystem.TotalScore}");
OnScored?.Invoke(category, result.FinalScore);
if (scoringSystem.IsComplete)
{ {
int total = scoringSystem.TotalScore; StartNewGame();
Debug.Log($"*** GAME OVER *** Total Score: {total}");
OnGameOver?.Invoke(total);
} }
else
public void StartNewGame()
{ {
scoringSystem.ResetScorecard();
CurrentTurn = 0;
StartNewTurn(); StartNewTurn();
} }
private void StartNewTurn()
{
CurrentTurn++;
CurrentRoll = 0;
diceManager.UnlockAll();
OnTurnStarted?.Invoke(CurrentTurn);
Debug.Log($"=== Turn {CurrentTurn} ===");
}
public void Roll()
{
if (!CanRoll) return;
CurrentRoll++;
diceManager.OnAllDiceSettled += HandleAllDiceSettled;
diceManager.RollUnlocked();
}
private void HandleAllDiceSettled()
{
diceManager.OnAllDiceSettled -= HandleAllDiceSettled;
int[] values = diceManager.GetCurrentValues();
Debug.Log($"Roll {CurrentRoll}/{maxRollsPerTurn} | Dice: [{string.Join(", ", values)}]");
OnRollComplete?.Invoke(CurrentRoll);
}
public void ToggleDiceLock(int index)
{
if (diceManager.IsAnyRolling) return;
if (CurrentRoll == 0) return;
diceManager.ToggleLock(index);
bool isLocked = diceManager.IsLocked(index);
Debug.Log($"Dice {index + 1} (value={diceManager.GetValue(index)}): {(isLocked ? "LOCKED" : "UNLOCKED")}");
}
public void ScoreInCategory(YachtCategory category)
{
if (!CanScore) return;
if (scoringSystem.IsCategoryUsed(category)) return;
int[] values = diceManager.GetCurrentValues();
ScoreResult result = scoringSystem.ScoreCategory(values, category);
Debug.Log($"Scored {category}: base={result.BaseScore}, " +
$"bonus=+{result.FlatBonus}, mult=x{result.Multiplier:F1}, " +
$"FINAL={result.FinalScore} | Total={scoringSystem.TotalScore}");
OnScored?.Invoke(category, result.FinalScore);
if (scoringSystem.IsComplete)
{
int total = scoringSystem.TotalScore;
Debug.Log($"*** GAME OVER *** Total Score: {total}");
OnGameOver?.Invoke(total);
}
else
{
StartNewTurn();
}
}
} }
} }
}
+70 -71
View File
@@ -5,94 +5,93 @@ using YachtDice.Scoring;
namespace YachtDice.Inventory namespace YachtDice.Inventory
{ {
public class InventoryController : MonoBehaviour
public sealed class InventoryController : MonoBehaviour
{
[SerializeField] private InventoryView inventoryView;
[SerializeField] private ScoringSystem scoringSystem;
[SerializeField] private CurrencyBank currencyBank;
private InventoryModel model;
public InventoryModel Model => model;
public void Initialize(InventoryModel inventoryModel)
{ {
model = inventoryModel; [SerializeField] private InventoryView inventoryView;
[SerializeField] private ScoringSystem scoringSystem;
[SerializeField] private CurrencyBank currencyBank;
inventoryView.OnActivateClicked += HandleActivate; private InventoryModel model;
inventoryView.OnDeactivateClicked += HandleDeactivate;
inventoryView.OnSellClicked += HandleSell;
model.OnActiveModifiersChanged += HandleActiveModifiersChanged; public InventoryModel Model => model;
model.OnInventoryChanged += HandleInventoryChanged;
if (scoringSystem != null) public void Initialize(InventoryModel inventoryModel)
scoringSystem.OnCategoryConfirmed += HandleCategoryConfirmed;
RefreshView();
}
private void OnDestroy()
{
if (inventoryView != null)
{ {
inventoryView.OnActivateClicked -= HandleActivate; model = inventoryModel;
inventoryView.OnDeactivateClicked -= HandleDeactivate;
inventoryView.OnSellClicked -= HandleSell; inventoryView.OnActivateClicked += HandleActivate;
inventoryView.OnDeactivateClicked += HandleDeactivate;
inventoryView.OnSellClicked += HandleSell;
model.OnActiveModifiersChanged += HandleActiveModifiersChanged;
model.OnInventoryChanged += HandleInventoryChanged;
if (scoringSystem != null)
scoringSystem.OnCategoryConfirmed += HandleCategoryConfirmed;
RefreshView();
} }
if (model != null) private void OnDestroy()
{ {
model.OnActiveModifiersChanged -= HandleActiveModifiersChanged; if (inventoryView != null)
model.OnInventoryChanged -= HandleInventoryChanged; {
inventoryView.OnActivateClicked -= HandleActivate;
inventoryView.OnDeactivateClicked -= HandleDeactivate;
inventoryView.OnSellClicked -= HandleSell;
}
if (model != null)
{
model.OnActiveModifiersChanged -= HandleActiveModifiersChanged;
model.OnInventoryChanged -= HandleInventoryChanged;
}
if (scoringSystem != null)
scoringSystem.OnCategoryConfirmed -= HandleCategoryConfirmed;
} }
if (scoringSystem != null) private void HandleActivate(ModifierRuntime runtime)
scoringSystem.OnCategoryConfirmed -= HandleCategoryConfirmed; {
} model.TryActivate(runtime);
}
private void HandleActivate(ModifierRuntime runtime) private void HandleDeactivate(ModifierRuntime runtime)
{ {
model.TryActivate(runtime); model.Deactivate(runtime);
} }
private void HandleDeactivate(ModifierRuntime runtime) private void HandleSell(ModifierRuntime runtime)
{ {
model.Deactivate(runtime); if (runtime.Data == null) return;
}
private void HandleSell(ModifierRuntime runtime) int sellPrice = runtime.Data.SellPrice;
{ model.RemoveModifier(runtime);
if (runtime.Data == null) return;
int sellPrice = runtime.Data.SellPrice; if (currencyBank != null)
model.RemoveModifier(runtime); currencyBank.Add(sellPrice);
}
if (currencyBank != null) private void HandleActiveModifiersChanged(System.Collections.Generic.List<ModifierData> activeModifiers)
currencyBank.Add(sellPrice); {
} if (scoringSystem != null)
scoringSystem.SetActiveModifiers(activeModifiers);
}
private void HandleActiveModifiersChanged(System.Collections.Generic.List<ModifierData> activeModifiers) private void HandleInventoryChanged()
{ {
if (scoringSystem != null) RefreshView();
scoringSystem.SetActiveModifiers(activeModifiers); }
}
private void HandleInventoryChanged() private void HandleCategoryConfirmed(YachtCategory category, ScoreResult result)
{ {
RefreshView(); model.ConsumeUseOnActive();
} }
private void HandleCategoryConfirmed(YachtCategory category, ScoreResult result) private void RefreshView()
{ {
model.ConsumeUseOnActive(); if (inventoryView != null && model != null)
} inventoryView.Refresh(model.OwnedModifiers, model.MaxActiveSlots);
}
private void RefreshView()
{
if (inventoryView != null && model != null)
inventoryView.Refresh(model.OwnedModifiers, model.MaxActiveSlots);
} }
} }
}
+106 -107
View File
@@ -4,129 +4,128 @@ using YachtDice.Modifiers;
namespace YachtDice.Inventory namespace YachtDice.Inventory
{ {
public class InventoryModel
public sealed class InventoryModel
{
private readonly List<ModifierRuntime> ownedModifiers = new();
private int maxActiveSlots;
public IReadOnlyList<ModifierRuntime> OwnedModifiers => ownedModifiers;
public int MaxActiveSlots => maxActiveSlots;
public event Action OnInventoryChanged;
public event Action<List<ModifierData>> OnActiveModifiersChanged;
public InventoryModel(int maxActiveSlots = 5)
{ {
this.maxActiveSlots = maxActiveSlots; private readonly List<ModifierRuntime> ownedModifiers = new();
} private int maxActiveSlots;
public int ActiveCount public IReadOnlyList<ModifierRuntime> OwnedModifiers => ownedModifiers;
{ public int MaxActiveSlots => maxActiveSlots;
get
public event Action OnInventoryChanged;
public event Action<List<ModifierData>> OnActiveModifiersChanged;
public InventoryModel(int maxActiveSlots = 5)
{ {
int count = 0; this.maxActiveSlots = maxActiveSlots;
for (int i = 0; i < ownedModifiers.Count; i++)
if (ownedModifiers[i].IsActive) count++;
return count;
}
}
public void SetMaxActiveSlots(int slots)
{
maxActiveSlots = slots;
}
public void AddModifier(ModifierData data)
{
var runtime = ModifierRuntime.Create(data);
ownedModifiers.Add(runtime);
OnInventoryChanged?.Invoke();
}
public void RemoveModifier(ModifierRuntime modifier)
{
if (!ownedModifiers.Contains(modifier)) return;
if (modifier.IsActive)
{
modifier.IsActive = false;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
} }
ownedModifiers.Remove(modifier); public int ActiveCount
OnInventoryChanged?.Invoke();
}
public bool TryActivate(ModifierRuntime modifier)
{
if (modifier.IsActive) return false;
if (!ownedModifiers.Contains(modifier)) return false;
if (ActiveCount >= maxActiveSlots) return false;
modifier.IsActive = true;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
return true;
}
public void Deactivate(ModifierRuntime modifier)
{
if (!modifier.IsActive) return;
modifier.IsActive = false;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
}
public void ConsumeUseOnActive()
{
bool changed = false;
for (int i = ownedModifiers.Count - 1; i >= 0; i--)
{ {
var mod = ownedModifiers[i]; get
if (!mod.IsActive) continue;
if (mod.Data == null) continue;
if (mod.Data.Durability != ModifierDurability.LimitedUses) continue;
mod.ConsumeUse();
if (mod.IsExpired)
{ {
ownedModifiers.RemoveAt(i); int count = 0;
changed = true; for (int i = 0; i < ownedModifiers.Count; i++)
if (ownedModifiers[i].IsActive) count++;
return count;
} }
} }
if (changed) public void SetMaxActiveSlots(int slots)
{ {
maxActiveSlots = slots;
}
public void AddModifier(ModifierData data)
{
var runtime = ModifierRuntime.Create(data);
ownedModifiers.Add(runtime);
OnInventoryChanged?.Invoke();
}
public void RemoveModifier(ModifierRuntime modifier)
{
if (!ownedModifiers.Contains(modifier)) return;
if (modifier.IsActive)
{
modifier.IsActive = false;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
}
ownedModifiers.Remove(modifier);
OnInventoryChanged?.Invoke();
}
public bool TryActivate(ModifierRuntime modifier)
{
if (modifier.IsActive) return false;
if (!ownedModifiers.Contains(modifier)) return false;
if (ActiveCount >= maxActiveSlots) return false;
modifier.IsActive = true;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
return true;
}
public void Deactivate(ModifierRuntime modifier)
{
if (!modifier.IsActive) return;
modifier.IsActive = false;
OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke(); OnInventoryChanged?.Invoke();
} }
}
public List<ModifierData> GetActiveModifierData() public void ConsumeUseOnActive()
{
var result = new List<ModifierData>();
for (int i = 0; i < ownedModifiers.Count; i++)
{ {
if (ownedModifiers[i].IsActive && ownedModifiers[i].Data != null) bool changed = false;
result.Add(ownedModifiers[i].Data);
for (int i = ownedModifiers.Count - 1; i >= 0; i--)
{
var mod = ownedModifiers[i];
if (!mod.IsActive) continue;
if (mod.Data == null) continue;
if (mod.Data.Durability != ModifierDurability.LimitedUses) continue;
mod.ConsumeUse();
if (mod.IsExpired)
{
ownedModifiers.RemoveAt(i);
changed = true;
}
}
if (changed)
{
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
}
} }
return result;
public List<ModifierData> GetActiveModifierData()
{
var result = new List<ModifierData>();
for (int i = 0; i < ownedModifiers.Count; i++)
{
if (ownedModifiers[i].IsActive && ownedModifiers[i].Data != null)
result.Add(ownedModifiers[i].Data);
}
return result;
}
public void LoadState(List<ModifierRuntime> loaded)
{
ownedModifiers.Clear();
if (loaded != null)
ownedModifiers.AddRange(loaded);
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
}
public List<ModifierRuntime> GetAllForSave() => new(ownedModifiers);
} }
public void LoadState(List<ModifierRuntime> loaded)
{
ownedModifiers.Clear();
if (loaded != null)
ownedModifiers.AddRange(loaded);
OnActiveModifiersChanged?.Invoke(GetActiveModifierData());
OnInventoryChanged?.Invoke();
}
public List<ModifierRuntime> GetAllForSave() => new(ownedModifiers);
}
} }
+62 -63
View File
@@ -6,78 +6,77 @@ using YachtDice.Modifiers;
namespace YachtDice.Inventory namespace YachtDice.Inventory
{ {
public class InventorySlotView : MonoBehaviour
public sealed class InventorySlotView : MonoBehaviour
{
[SerializeField] private Image iconImage;
[SerializeField] private TMP_Text nameText;
[SerializeField] private TMP_Text descriptionText;
[SerializeField] private TMP_Text usesText;
[SerializeField] private Button activateButton;
[SerializeField] private Button deactivateButton;
[SerializeField] private Button sellButton;
[SerializeField] private TMP_Text sellPriceText;
[SerializeField] private Image background;
[Header("Colors")]
[SerializeField] private Color activeColor = new(0.7f, 1f, 0.7f);
[SerializeField] private Color inactiveColor = Color.white;
private ModifierRuntime runtime;
public event Action<ModifierRuntime> OnActivateClicked;
public event Action<ModifierRuntime> OnDeactivateClicked;
public event Action<ModifierRuntime> OnSellClicked;
private void Awake()
{ {
if (activateButton != null) [SerializeField] private Image iconImage;
activateButton.onClick.AddListener(() => OnActivateClicked?.Invoke(runtime)); [SerializeField] private TMP_Text nameText;
if (deactivateButton != null) [SerializeField] private TMP_Text descriptionText;
deactivateButton.onClick.AddListener(() => OnDeactivateClicked?.Invoke(runtime)); [SerializeField] private TMP_Text usesText;
if (sellButton != null) [SerializeField] private Button activateButton;
sellButton.onClick.AddListener(() => OnSellClicked?.Invoke(runtime)); [SerializeField] private Button deactivateButton;
} [SerializeField] private Button sellButton;
[SerializeField] private TMP_Text sellPriceText;
[SerializeField] private Image background;
public void Setup(ModifierRuntime modifierRuntime, bool canActivateMore) [Header("Colors")]
{ [SerializeField] private Color activeColor = new(0.7f, 1f, 0.7f);
runtime = modifierRuntime; [SerializeField] private Color inactiveColor = Color.white;
var data = runtime.Data;
if (data == null) return; private ModifierRuntime runtime;
if (nameText != null) nameText.text = data.DisplayName; public event Action<ModifierRuntime> OnActivateClicked;
if (descriptionText != null) descriptionText.text = data.Description; public event Action<ModifierRuntime> OnDeactivateClicked;
if (iconImage != null && data.Icon != null) iconImage.sprite = data.Icon; public event Action<ModifierRuntime> OnSellClicked;
if (usesText != null) private void Awake()
{ {
if (data.Durability == ModifierDurability.LimitedUses) if (activateButton != null)
{ activateButton.onClick.AddListener(() => OnActivateClicked?.Invoke(runtime));
usesText.gameObject.SetActive(true); if (deactivateButton != null)
usesText.text = $"{runtime.RemainingUses}/{data.MaxUses}"; deactivateButton.onClick.AddListener(() => OnDeactivateClicked?.Invoke(runtime));
} if (sellButton != null)
else sellButton.onClick.AddListener(() => OnSellClicked?.Invoke(runtime));
{
usesText.gameObject.SetActive(false);
}
} }
if (sellPriceText != null) sellPriceText.text = data.SellPrice.ToString(); public void Setup(ModifierRuntime modifierRuntime, bool canActivateMore)
bool isActive = runtime.IsActive;
if (activateButton != null)
{ {
activateButton.gameObject.SetActive(!isActive); runtime = modifierRuntime;
activateButton.interactable = canActivateMore; var data = runtime.Data;
if (data == null) return;
if (nameText != null) nameText.text = data.DisplayName;
if (descriptionText != null) descriptionText.text = data.Description;
if (iconImage != null && data.Icon != null) iconImage.sprite = data.Icon;
if (usesText != null)
{
if (data.Durability == ModifierDurability.LimitedUses)
{
usesText.gameObject.SetActive(true);
usesText.text = $"{runtime.RemainingUses}/{data.MaxUses}";
}
else
{
usesText.gameObject.SetActive(false);
}
}
if (sellPriceText != null) sellPriceText.text = data.SellPrice.ToString();
bool isActive = runtime.IsActive;
if (activateButton != null)
{
activateButton.gameObject.SetActive(!isActive);
activateButton.interactable = canActivateMore;
}
if (deactivateButton != null)
deactivateButton.gameObject.SetActive(isActive);
if (background != null)
background.color = isActive ? activeColor : inactiveColor;
} }
if (deactivateButton != null)
deactivateButton.gameObject.SetActive(isActive);
if (background != null)
background.color = isActive ? activeColor : inactiveColor;
} }
} }
}
+58 -59
View File
@@ -7,73 +7,72 @@ using YachtDice.Modifiers;
namespace YachtDice.Inventory namespace YachtDice.Inventory
{ {
public class InventoryView : MonoBehaviour
public sealed class InventoryView : MonoBehaviour
{
[SerializeField] private Transform slotContainer;
[SerializeField] private InventorySlotView slotPrefab;
[SerializeField] private TMP_Text slotCountText;
[SerializeField] private Button closeButton;
private readonly List<InventorySlotView> spawnedSlots = new();
public event Action<ModifierRuntime> OnActivateClicked;
public event Action<ModifierRuntime> OnDeactivateClicked;
public event Action<ModifierRuntime> OnSellClicked;
private void Awake()
{ {
if (closeButton != null) [SerializeField] private Transform slotContainer;
closeButton.onClick.AddListener(Hide); [SerializeField] private InventorySlotView slotPrefab;
} [SerializeField] private TMP_Text slotCountText;
[SerializeField] private Button closeButton;
private void OnDestroy() private readonly List<InventorySlotView> spawnedSlots = new();
{
if (closeButton != null)
closeButton.onClick.RemoveListener(Hide);
}
public void Show() => gameObject.SetActive(true); public event Action<ModifierRuntime> OnActivateClicked;
public void Hide() => gameObject.SetActive(false); public event Action<ModifierRuntime> OnDeactivateClicked;
public bool IsVisible => gameObject.activeSelf; public event Action<ModifierRuntime> OnSellClicked;
public void Refresh(IReadOnlyList<ModifierRuntime> owned, int maxSlots) private void Awake()
{
ClearSlots();
int activeCount = 0;
for (int i = 0; i < owned.Count; i++)
{ {
var runtime = owned[i]; if (closeButton != null)
if (runtime.IsActive) activeCount++; closeButton.onClick.AddListener(Hide);
var slot = Instantiate(slotPrefab, slotContainer);
slot.Setup(runtime, activeCount <= maxSlots);
slot.OnActivateClicked += HandleActivate;
slot.OnDeactivateClicked += HandleDeactivate;
slot.OnSellClicked += HandleSell;
spawnedSlots.Add(slot);
} }
if (slotCountText != null) private void OnDestroy()
slotCountText.text = $"{activeCount}/{maxSlots}";
}
private void ClearSlots()
{
for (int i = 0; i < spawnedSlots.Count; i++)
{ {
spawnedSlots[i].OnActivateClicked -= HandleActivate; if (closeButton != null)
spawnedSlots[i].OnDeactivateClicked -= HandleDeactivate; closeButton.onClick.RemoveListener(Hide);
spawnedSlots[i].OnSellClicked -= HandleSell;
Destroy(spawnedSlots[i].gameObject);
} }
spawnedSlots.Clear();
}
private void HandleActivate(ModifierRuntime runtime) => OnActivateClicked?.Invoke(runtime); public void Show() => gameObject.SetActive(true);
private void HandleDeactivate(ModifierRuntime runtime) => OnDeactivateClicked?.Invoke(runtime); public void Hide() => gameObject.SetActive(false);
private void HandleSell(ModifierRuntime runtime) => OnSellClicked?.Invoke(runtime); public bool IsVisible => gameObject.activeSelf;
}
public void Refresh(IReadOnlyList<ModifierRuntime> owned, int maxSlots)
{
ClearSlots();
int activeCount = 0;
for (int i = 0; i < owned.Count; i++)
{
var runtime = owned[i];
if (runtime.IsActive) activeCount++;
var slot = Instantiate(slotPrefab, slotContainer);
slot.Setup(runtime, activeCount <= maxSlots);
slot.OnActivateClicked += HandleActivate;
slot.OnDeactivateClicked += HandleDeactivate;
slot.OnSellClicked += HandleSell;
spawnedSlots.Add(slot);
}
if (slotCountText != null)
slotCountText.text = $"{activeCount}/{maxSlots}";
}
private void ClearSlots()
{
for (int i = 0; i < spawnedSlots.Count; i++)
{
spawnedSlots[i].OnActivateClicked -= HandleActivate;
spawnedSlots[i].OnDeactivateClicked -= HandleDeactivate;
spawnedSlots[i].OnSellClicked -= HandleSell;
Destroy(spawnedSlots[i].gameObject);
}
spawnedSlots.Clear();
}
private void HandleActivate(ModifierRuntime runtime) => OnActivateClicked?.Invoke(runtime);
private void HandleDeactivate(ModifierRuntime runtime) => OnDeactivateClicked?.Invoke(runtime);
private void HandleSell(ModifierRuntime runtime) => OnSellClicked?.Invoke(runtime);
}
} }
+83 -84
View File
@@ -3,91 +3,90 @@ using YachtDice.Scoring;
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
[CreateAssetMenu(fileName = "NewModifier", menuName = "YachtDice/Modifier Data")]
[CreateAssetMenu(fileName = "NewModifier", menuName = "YachtDice/Modifier Data")] public sealed class ModifierData : ScriptableObject
public sealed class ModifierData : ScriptableObject
{
[SerializeField] private string id;
[SerializeField] private string displayName;
[SerializeField] [TextArea] private string description;
[SerializeField] private ModifierRarity rarity;
[SerializeField] private int shopPrice;
[SerializeField] private int sellPrice;
[SerializeField] private Sprite icon;
[Header("Effect")]
[SerializeField] private ModifierScope scope;
[SerializeField] private ModifierEffectType effectType;
[SerializeField] private ModifierTarget target;
[SerializeField] private float effectValue;
[Header("Durability")]
[SerializeField] private ModifierDurability durability;
[SerializeField] private int maxUses;
public string Id => id;
public string DisplayName => displayName;
public string Description => description;
public ModifierRarity Rarity => rarity;
public int ShopPrice => shopPrice;
public int SellPrice => sellPrice;
public Sprite Icon => icon;
public ModifierScope Scope => scope;
public ModifierEffectType EffectType => effectType;
public ModifierTarget Target => target;
public float EffectValue => effectValue;
public ModifierDurability Durability => durability;
public int MaxUses => maxUses;
public bool IsAdditive =>
effectType == ModifierEffectType.AddPerDieValue ||
effectType == ModifierEffectType.AddFlatToFinalScore;
public bool IsMultiplicative =>
effectType == ModifierEffectType.MultiplyPerDieValue ||
effectType == ModifierEffectType.MultiplyFinalScore;
public bool IsCategoryLevel =>
effectType == ModifierEffectType.AddPerDieValue ||
effectType == ModifierEffectType.MultiplyPerDieValue;
public bool IsFinalScoreLevel =>
effectType == ModifierEffectType.AddFlatToFinalScore ||
effectType == ModifierEffectType.MultiplyFinalScore;
#if UNITY_EDITOR
public static ModifierData CreateForTest(
string id,
ModifierScope scope,
ModifierEffectType effectType,
float effectValue,
int dieValue = 0,
YachtCategory targetCategory = YachtCategory.Ones,
bool hasCategoryFilter = false,
ModifierDurability durability = ModifierDurability.Permanent,
int maxUses = 0,
int shopPrice = 100,
int sellPrice = 50)
{ {
var data = CreateInstance<ModifierData>(); [SerializeField] private string id;
data.id = id; [SerializeField] private string displayName;
data.displayName = id; [SerializeField] [TextArea] private string description;
data.description = id; [SerializeField] private ModifierRarity rarity;
data.scope = scope; [SerializeField] private int shopPrice;
data.effectType = effectType; [SerializeField] private int sellPrice;
data.effectValue = effectValue; [SerializeField] private Sprite icon;
data.target = new ModifierTarget
[Header("Effect")]
[SerializeField] private ModifierScope scope;
[SerializeField] private ModifierEffectType effectType;
[SerializeField] private ModifierTarget target;
[SerializeField] private float effectValue;
[Header("Durability")]
[SerializeField] private ModifierDurability durability;
[SerializeField] private int maxUses;
public string Id => id;
public string DisplayName => displayName;
public string Description => description;
public ModifierRarity Rarity => rarity;
public int ShopPrice => shopPrice;
public int SellPrice => sellPrice;
public Sprite Icon => icon;
public ModifierScope Scope => scope;
public ModifierEffectType EffectType => effectType;
public ModifierTarget Target => target;
public float EffectValue => effectValue;
public ModifierDurability Durability => durability;
public int MaxUses => maxUses;
public bool IsAdditive =>
effectType == ModifierEffectType.AddPerDieValue ||
effectType == ModifierEffectType.AddFlatToFinalScore;
public bool IsMultiplicative =>
effectType == ModifierEffectType.MultiplyPerDieValue ||
effectType == ModifierEffectType.MultiplyFinalScore;
public bool IsCategoryLevel =>
effectType == ModifierEffectType.AddPerDieValue ||
effectType == ModifierEffectType.MultiplyPerDieValue;
public bool IsFinalScoreLevel =>
effectType == ModifierEffectType.AddFlatToFinalScore ||
effectType == ModifierEffectType.MultiplyFinalScore;
#if UNITY_EDITOR
public static ModifierData CreateForTest(
string id,
ModifierScope scope,
ModifierEffectType effectType,
float effectValue,
int dieValue = 0,
YachtCategory targetCategory = YachtCategory.Ones,
bool hasCategoryFilter = false,
ModifierDurability durability = ModifierDurability.Permanent,
int maxUses = 0,
int shopPrice = 100,
int sellPrice = 50)
{ {
DieValue = dieValue, var data = CreateInstance<ModifierData>();
TargetCategory = targetCategory, data.id = id;
HasCategoryFilter = hasCategoryFilter data.displayName = id;
}; data.description = id;
data.durability = durability; data.scope = scope;
data.maxUses = maxUses; data.effectType = effectType;
data.shopPrice = shopPrice; data.effectValue = effectValue;
data.sellPrice = sellPrice; data.target = new ModifierTarget
return data; {
DieValue = dieValue,
TargetCategory = targetCategory,
HasCategoryFilter = hasCategoryFilter
};
data.durability = durability;
data.maxUses = maxUses;
data.shopPrice = shopPrice;
data.sellPrice = sellPrice;
return data;
}
#endif
} }
#endif
}
} }
+45 -46
View File
@@ -3,58 +3,57 @@ using YachtDice.Scoring;
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
public delegate void ModifierHandler(ModifierData data, ref ScoreResult result);
public delegate void ModifierHandler(ModifierData data, ref ScoreResult result); public static class ModifierEffect
public static class ModifierEffect
{
private static readonly Dictionary<ModifierEffectType, ModifierHandler> Handlers = new()
{ {
{ ModifierEffectType.AddPerDieValue, ApplyAddPerDieValue }, private static readonly Dictionary<ModifierEffectType, ModifierHandler> Handlers = new()
{ ModifierEffectType.AddFlatToFinalScore, ApplyAddFlat },
{ ModifierEffectType.MultiplyPerDieValue, ApplyMultiplyPerDieValue },
{ ModifierEffectType.MultiplyFinalScore, ApplyMultiplyFinal }
};
public static void Apply(ModifierData data, ref ScoreResult result)
{
if (Handlers.TryGetValue(data.EffectType, out var handler))
handler(data, ref result);
}
private static void ApplyAddPerDieValue(ModifierData data, ref ScoreResult result)
{
int targetValue = data.Target.DieValue;
int count = 0;
for (int i = 0; i < result.DiceValues.Length; i++)
{ {
if (targetValue == 0 || result.DiceValues[i] == targetValue) { ModifierEffectType.AddPerDieValue, ApplyAddPerDieValue },
count++; { ModifierEffectType.AddFlatToFinalScore, ApplyAddFlat },
{ ModifierEffectType.MultiplyPerDieValue, ApplyMultiplyPerDieValue },
{ ModifierEffectType.MultiplyFinalScore, ApplyMultiplyFinal }
};
public static void Apply(ModifierData data, ref ScoreResult result)
{
if (Handlers.TryGetValue(data.EffectType, out var handler))
handler(data, ref result);
} }
result.FlatBonus += (int)(data.EffectValue * count); private static void ApplyAddPerDieValue(ModifierData data, ref ScoreResult result)
}
private static void ApplyAddFlat(ModifierData data, ref ScoreResult result)
{
result.FlatBonus += (int)data.EffectValue;
}
private static void ApplyMultiplyPerDieValue(ModifierData data, ref ScoreResult result)
{
int targetValue = data.Target.DieValue;
for (int i = 0; i < result.DiceValues.Length; i++)
{ {
if (targetValue == 0 || result.DiceValues[i] == targetValue) int targetValue = data.Target.DieValue;
result.Multiplier *= data.EffectValue; int count = 0;
for (int i = 0; i < result.DiceValues.Length; i++)
{
if (targetValue == 0 || result.DiceValues[i] == targetValue)
count++;
}
result.FlatBonus += (int)(data.EffectValue * count);
}
private static void ApplyAddFlat(ModifierData data, ref ScoreResult result)
{
result.FlatBonus += (int)data.EffectValue;
}
private static void ApplyMultiplyPerDieValue(ModifierData data, ref ScoreResult result)
{
int targetValue = data.Target.DieValue;
for (int i = 0; i < result.DiceValues.Length; i++)
{
if (targetValue == 0 || result.DiceValues[i] == targetValue)
result.Multiplier *= data.EffectValue;
}
}
private static void ApplyMultiplyFinal(ModifierData data, ref ScoreResult result)
{
result.Multiplier *= data.EffectValue;
} }
} }
private static void ApplyMultiplyFinal(ModifierData data, ref ScoreResult result)
{
result.Multiplier *= data.EffectValue;
}
}
} }
+24 -24
View File
@@ -1,30 +1,30 @@
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
public enum ModifierScope public enum ModifierScope
{ {
SelectedCategory, SelectedCategory,
AnyCategoryClosed AnyCategoryClosed
} }
public enum ModifierEffectType public enum ModifierEffectType
{ {
AddPerDieValue, AddPerDieValue,
AddFlatToFinalScore, AddFlatToFinalScore,
MultiplyPerDieValue, MultiplyPerDieValue,
MultiplyFinalScore MultiplyFinalScore
} }
public enum ModifierDurability public enum ModifierDurability
{ {
Permanent, Permanent,
LimitedUses LimitedUses
} }
public enum ModifierRarity public enum ModifierRarity
{ {
Common, Common,
Uncommon, Uncommon,
Rare, Rare,
Epic Epic
} }
} }
+52 -53
View File
@@ -3,65 +3,64 @@ using YachtDice.Scoring;
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
public static class ModifierPipeline
public static class ModifierPipeline
{
// Application order (explicit):
// 1. Category-level additive (AddPerDieValue)
// 2. Category-level multiplicative (MultiplyPerDieValue)
// 3. Final-score additive (AddFlatToFinalScore)
// 4. Final-score multiplicative (MultiplyFinalScore)
public static void Apply(
IReadOnlyList<ModifierData> activeModifiers,
ref ScoreResult result,
ModifierScope currentScope)
{ {
if (activeModifiers == null) return; // Application order (explicit):
// 1. Category-level additive (AddPerDieValue)
// 2. Category-level multiplicative (MultiplyPerDieValue)
// 3. Final-score additive (AddFlatToFinalScore)
// 4. Final-score multiplicative (MultiplyFinalScore)
// Pass 1: Category-level additive public static void Apply(
for (int i = 0; i < activeModifiers.Count; i++) IReadOnlyList<ModifierData> activeModifiers,
ref ScoreResult result,
ModifierScope currentScope)
{ {
var mod = activeModifiers[i]; if (activeModifiers == null) return;
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsCategoryLevel && mod.IsAdditive) // Pass 1: Category-level additive
ModifierEffect.Apply(mod, ref result); for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsCategoryLevel && mod.IsAdditive)
ModifierEffect.Apply(mod, ref result);
}
// Pass 2: Category-level multiplicative
for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsCategoryLevel && mod.IsMultiplicative)
ModifierEffect.Apply(mod, ref result);
}
// Pass 3: Final-score additive
for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsFinalScoreLevel && mod.IsAdditive)
ModifierEffect.Apply(mod, ref result);
}
// Pass 4: Final-score multiplicative
for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsFinalScoreLevel && mod.IsMultiplicative)
ModifierEffect.Apply(mod, ref result);
}
} }
// Pass 2: Category-level multiplicative private static bool ShouldApply(ModifierData mod, ref ScoreResult result, ModifierScope currentScope)
for (int i = 0; i < activeModifiers.Count; i++)
{ {
var mod = activeModifiers[i]; if (mod == null) return false;
if (!ShouldApply(mod, ref result, currentScope)) continue; if (mod.Scope != currentScope) return false;
if (mod.IsCategoryLevel && mod.IsMultiplicative) if (mod.Target.HasCategoryFilter && mod.Target.TargetCategory != result.Category) return false;
ModifierEffect.Apply(mod, ref result); return true;
}
// Pass 3: Final-score additive
for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsFinalScoreLevel && mod.IsAdditive)
ModifierEffect.Apply(mod, ref result);
}
// Pass 4: Final-score multiplicative
for (int i = 0; i < activeModifiers.Count; i++)
{
var mod = activeModifiers[i];
if (!ShouldApply(mod, ref result, currentScope)) continue;
if (mod.IsFinalScoreLevel && mod.IsMultiplicative)
ModifierEffect.Apply(mod, ref result);
} }
} }
private static bool ShouldApply(ModifierData mod, ref ScoreResult result, ModifierScope currentScope)
{
if (mod == null) return false;
if (mod.Scope != currentScope) return false;
if (mod.Target.HasCategoryFilter && mod.Target.TargetCategory != result.Category) return false;
return true;
}
}
} }
+27 -28
View File
@@ -2,37 +2,36 @@ using System;
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
[Serializable]
[Serializable] public class ModifierRuntime
public sealed class ModifierRuntime
{
public string ModifierId;
public bool IsActive;
public int RemainingUses;
[NonSerialized] public ModifierData Data;
public bool IsExpired => Data != null &&
Data.Durability == ModifierDurability.LimitedUses &&
RemainingUses <= 0;
public void ConsumeUse()
{ {
if (Data == null) return; public string ModifierId;
if (Data.Durability != ModifierDurability.LimitedUses) return; public bool IsActive;
public int RemainingUses;
RemainingUses--; [NonSerialized] public ModifierData Data;
}
public static ModifierRuntime Create(ModifierData data) public bool IsExpired => Data != null &&
{ Data.Durability == ModifierDurability.LimitedUses &&
return new ModifierRuntime RemainingUses <= 0;
public void ConsumeUse()
{ {
ModifierId = data.Id, if (Data == null) return;
IsActive = false, if (Data.Durability != ModifierDurability.LimitedUses) return;
RemainingUses = data.Durability == ModifierDurability.LimitedUses ? data.MaxUses : -1,
Data = data RemainingUses--;
}; }
public static ModifierRuntime Create(ModifierData data)
{
return new ModifierRuntime
{
ModifierId = data.Id,
IsActive = false,
RemainingUses = data.Durability == ModifierDurability.LimitedUses ? data.MaxUses : -1,
Data = data
};
}
} }
} }
}
+11 -12
View File
@@ -4,18 +4,17 @@ using YachtDice.Scoring;
namespace YachtDice.Modifiers namespace YachtDice.Modifiers
{ {
[Serializable]
public struct ModifierTarget
{
[Tooltip("Die face value (1-6). 0 = any/all dice.")]
[Range(0, 6)]
public int DieValue;
[Serializable] [Tooltip("Category this modifier targets.")]
public struct ModifierTarget public YachtCategory TargetCategory;
{
[Tooltip("Die face value (1-6). 0 = any/all dice.")]
[Range(0, 6)]
public int DieValue;
[Tooltip("Category this modifier targets.")] [Tooltip("If true, TargetCategory is used as a filter.")]
public YachtCategory TargetCategory; public bool HasCategoryFilter;
}
[Tooltip("If true, TargetCategory is used as a filter.")]
public bool HasCategoryFilter;
}
} }
+14 -15
View File
@@ -3,20 +3,19 @@ using System.Collections.Generic;
namespace YachtDice.Persistence namespace YachtDice.Persistence
{ {
[Serializable]
public sealed class SaveData
{
public int Version = 1;
public int Currency;
public List<ModifierSaveEntry> OwnedModifiers = new();
}
[Serializable] [Serializable]
public sealed class SaveData public sealed class ModifierSaveEntry
{ {
public int Version = 1; public string ModifierId;
public int Currency; public bool IsActive;
public List<ModifierSaveEntry> OwnedModifiers = new(); public int RemainingUses;
} }
[Serializable]
public sealed class ModifierSaveEntry
{
public string ModifierId;
public bool IsActive;
public int RemainingUses;
}
} }
+32 -33
View File
@@ -3,44 +3,43 @@ using UnityEngine;
namespace YachtDice.Persistence namespace YachtDice.Persistence
{ {
public static class SaveSystem
public static class SaveSystem
{
private const string SaveKey = "YachtDice_SaveData";
public static void Save(SaveData data)
{ {
string json = JsonConvert.SerializeObject(data, Formatting.Indented); private const string SaveKey = "YachtDice_SaveData";
PlayerPrefs.SetString(SaveKey, json);
PlayerPrefs.Save();
}
public static SaveData Load() public static void Save(SaveData data)
{
if (!PlayerPrefs.HasKey(SaveKey))
return new SaveData();
string json = PlayerPrefs.GetString(SaveKey);
try
{ {
return JsonConvert.DeserializeObject<SaveData>(json) ?? new SaveData(); string json = JsonConvert.SerializeObject(data, Formatting.Indented);
PlayerPrefs.SetString(SaveKey, json);
PlayerPrefs.Save();
} }
catch (JsonException e)
public static SaveData Load()
{ {
Debug.LogWarning($"Failed to deserialize save data, returning default: {e.Message}"); if (!PlayerPrefs.HasKey(SaveKey))
return new SaveData(); return new SaveData();
string json = PlayerPrefs.GetString(SaveKey);
try
{
return JsonConvert.DeserializeObject<SaveData>(json) ?? new SaveData();
}
catch (JsonException e)
{
Debug.LogWarning($"Failed to deserialize save data, returning default: {e.Message}");
return new SaveData();
}
}
public static void Delete()
{
PlayerPrefs.DeleteKey(SaveKey);
}
public static bool HasSave()
{
return PlayerPrefs.HasKey(SaveKey);
} }
} }
public static void Delete()
{
PlayerPrefs.DeleteKey(SaveKey);
}
public static bool HasSave()
{
return PlayerPrefs.HasKey(SaveKey);
}
}
} }
+69 -70
View File
@@ -2,82 +2,81 @@ using System;
namespace YachtDice.Scoring namespace YachtDice.Scoring
{ {
public static class CategoryScorer
public static class CategoryScorer
{
public static int Calculate(int[] dice, YachtCategory category)
{ {
if (dice == null || dice.Length != 5) public static int Calculate(int[] dice, YachtCategory category)
throw new ArgumentException("Exactly 5 dice values required.");
return category switch
{ {
YachtCategory.Ones => SumOfValue(dice, 1), if (dice == null || dice.Length != 5)
YachtCategory.Twos => SumOfValue(dice, 2), throw new ArgumentException("Exactly 5 dice values required.");
YachtCategory.Threes => SumOfValue(dice, 3),
YachtCategory.Fours => SumOfValue(dice, 4),
YachtCategory.Fives => SumOfValue(dice, 5),
YachtCategory.Sixes => SumOfValue(dice, 6),
YachtCategory.ThreeOfAKind => NOfAKind(dice, 3) ? Sum(dice) : 0,
YachtCategory.FourOfAKind => NOfAKind(dice, 4) ? Sum(dice) : 0,
YachtCategory.FullHouse => IsFullHouse(dice) ? 25 : 0,
YachtCategory.SmallStraight => HasStraightRun(dice, 4) ? 30 : 0,
YachtCategory.LargeStraight => HasStraightRun(dice, 5) ? 40 : 0,
YachtCategory.Yacht => NOfAKind(dice, 5) ? 50 : 0,
YachtCategory.Chance => Sum(dice),
_ => 0
};
}
private static int SumOfValue(int[] dice, int target) return category switch
{ {
int sum = 0; YachtCategory.Ones => SumOfValue(dice, 1),
for (int i = 0; i < dice.Length; i++) YachtCategory.Twos => SumOfValue(dice, 2),
if (dice[i] == target) sum += target; YachtCategory.Threes => SumOfValue(dice, 3),
return sum; YachtCategory.Fours => SumOfValue(dice, 4),
} YachtCategory.Fives => SumOfValue(dice, 5),
YachtCategory.Sixes => SumOfValue(dice, 6),
private static int Sum(int[] dice) YachtCategory.ThreeOfAKind => NOfAKind(dice, 3) ? Sum(dice) : 0,
{ YachtCategory.FourOfAKind => NOfAKind(dice, 4) ? Sum(dice) : 0,
int sum = 0; YachtCategory.FullHouse => IsFullHouse(dice) ? 25 : 0,
for (int i = 0; i < dice.Length; i++) sum += dice[i]; YachtCategory.SmallStraight => HasStraightRun(dice, 4) ? 30 : 0,
return sum; YachtCategory.LargeStraight => HasStraightRun(dice, 5) ? 40 : 0,
} YachtCategory.Yacht => NOfAKind(dice, 5) ? 50 : 0,
YachtCategory.Chance => Sum(dice),
private static bool NOfAKind(int[] dice, int n) _ => 0
{ };
int[] counts = new int[7];
for (int i = 0; i < dice.Length; i++) counts[dice[i]]++;
for (int v = 1; v <= 6; v++)
if (counts[v] >= n) return true;
return false;
}
private static bool IsFullHouse(int[] dice)
{
int[] counts = new int[7];
for (int i = 0; i < dice.Length; i++) counts[dice[i]]++;
bool hasTwo = false, hasThree = false;
for (int v = 1; v <= 6; v++)
{
if (counts[v] == 2) hasTwo = true;
if (counts[v] == 3) hasThree = true;
} }
return hasTwo && hasThree;
}
private static bool HasStraightRun(int[] dice, int runLength) private static int SumOfValue(int[] dice, int target)
{
bool[] present = new bool[7];
for (int i = 0; i < dice.Length; i++) present[dice[i]] = true;
int consecutive = 0;
for (int v = 1; v <= 6; v++)
{ {
consecutive = present[v] ? consecutive + 1 : 0; int sum = 0;
if (consecutive >= runLength) return true; for (int i = 0; i < dice.Length; i++)
if (dice[i] == target) sum += target;
return sum;
}
private static int Sum(int[] dice)
{
int sum = 0;
for (int i = 0; i < dice.Length; i++) sum += dice[i];
return sum;
}
private static bool NOfAKind(int[] dice, int n)
{
int[] counts = new int[7];
for (int i = 0; i < dice.Length; i++) counts[dice[i]]++;
for (int v = 1; v <= 6; v++)
if (counts[v] >= n) return true;
return false;
}
private static bool IsFullHouse(int[] dice)
{
int[] counts = new int[7];
for (int i = 0; i < dice.Length; i++) counts[dice[i]]++;
bool hasTwo = false, hasThree = false;
for (int v = 1; v <= 6; v++)
{
if (counts[v] == 2) hasTwo = true;
if (counts[v] == 3) hasThree = true;
}
return hasTwo && hasThree;
}
private static bool HasStraightRun(int[] dice, int runLength)
{
bool[] present = new bool[7];
for (int i = 0; i < dice.Length; i++) present[dice[i]] = true;
int consecutive = 0;
for (int v = 1; v <= 6; v++)
{
consecutive = present[v] ? consecutive + 1 : 0;
if (consecutive >= runLength) return true;
}
return false;
} }
return false;
} }
} }
}
+20 -21
View File
@@ -3,28 +3,27 @@ using UnityEngine;
namespace YachtDice.Scoring namespace YachtDice.Scoring
{ {
[Serializable]
[Serializable] public struct ScoreResult
public struct ScoreResult
{
public int BaseScore;
public int FlatBonus;
public float Multiplier;
public int[] DiceValues;
public YachtCategory Category;
public int FinalScore => Mathf.FloorToInt((BaseScore + FlatBonus) * Multiplier);
public static ScoreResult Create(int baseScore, int[] diceValues, YachtCategory category)
{ {
return new ScoreResult public int BaseScore;
public int FlatBonus;
public float Multiplier;
public int[] DiceValues;
public YachtCategory Category;
public int FinalScore => Mathf.FloorToInt((BaseScore + FlatBonus) * Multiplier);
public static ScoreResult Create(int baseScore, int[] diceValues, YachtCategory category)
{ {
BaseScore = baseScore, return new ScoreResult
FlatBonus = 0, {
Multiplier = 1f, BaseScore = baseScore,
DiceValues = diceValues, FlatBonus = 0,
Category = category Multiplier = 1f,
}; DiceValues = diceValues,
Category = category
};
}
} }
} }
}
+75 -76
View File
@@ -5,85 +5,84 @@ using YachtDice.Modifiers;
namespace YachtDice.Scoring namespace YachtDice.Scoring
{ {
public class ScoringSystem : MonoBehaviour
public sealed class ScoringSystem : MonoBehaviour
{
public event Action<YachtCategory, int> OnCategoryScored;
public event Action<int> OnAllCategoriesScored;
public event Action<YachtCategory, ScoreResult> OnCategoryConfirmed;
private readonly Dictionary<YachtCategory, int> scorecard = new();
private readonly HashSet<YachtCategory> usedCategories = new();
private List<ModifierData> activeModifierData = new();
public bool IsCategoryUsed(YachtCategory category) => usedCategories.Contains(category);
public int GetCategoryScore(YachtCategory category)
{ {
return scorecard.TryGetValue(category, out int score) ? score : -1; public event Action<YachtCategory, int> OnCategoryScored;
} public event Action<int> OnAllCategoriesScored;
public event Action<YachtCategory, ScoreResult> OnCategoryConfirmed;
public int TotalScore private readonly Dictionary<YachtCategory, int> scorecard = new();
{ private readonly HashSet<YachtCategory> usedCategories = new();
get private List<ModifierData> activeModifierData = new();
public bool IsCategoryUsed(YachtCategory category) => usedCategories.Contains(category);
public int GetCategoryScore(YachtCategory category)
{ {
int total = 0; return scorecard.TryGetValue(category, out int score) ? score : -1;
foreach (var kvp in scorecard) total += kvp.Value; }
return total;
public int TotalScore
{
get
{
int total = 0;
foreach (var kvp in scorecard) total += kvp.Value;
return total;
}
}
public int CategoriesFilledCount => usedCategories.Count;
public int TotalCategoryCount => Enum.GetValues(typeof(YachtCategory)).Length;
public bool IsComplete => CategoriesFilledCount >= TotalCategoryCount;
public void SetActiveModifiers(List<ModifierData> modifiers)
{
activeModifierData = modifiers ?? new List<ModifierData>();
}
public IReadOnlyList<ModifierData> ActiveModifiers => activeModifierData;
public ScoreResult PreviewScore(int[] diceValues, YachtCategory category)
{
int baseScore = CategoryScorer.Calculate(diceValues, category);
ScoreResult result = ScoreResult.Create(baseScore, diceValues, category);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.SelectedCategory);
return result;
}
public ScoreResult ScoreCategory(int[] diceValues, YachtCategory category)
{
if (usedCategories.Contains(category))
throw new InvalidOperationException($"Category {category} has already been scored.");
int baseScore = CategoryScorer.Calculate(diceValues, category);
ScoreResult result = ScoreResult.Create(baseScore, diceValues, category);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.SelectedCategory);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.AnyCategoryClosed);
int finalScore = result.FinalScore;
scorecard[category] = finalScore;
usedCategories.Add(category);
OnCategoryScored?.Invoke(category, finalScore);
OnCategoryConfirmed?.Invoke(category, result);
if (IsComplete)
OnAllCategoriesScored?.Invoke(TotalScore);
return result;
}
public void ResetScorecard()
{
scorecard.Clear();
usedCategories.Clear();
} }
} }
public int CategoriesFilledCount => usedCategories.Count;
public int TotalCategoryCount => Enum.GetValues(typeof(YachtCategory)).Length;
public bool IsComplete => CategoriesFilledCount >= TotalCategoryCount;
public void SetActiveModifiers(List<ModifierData> modifiers)
{
activeModifierData = modifiers ?? new List<ModifierData>();
}
public IReadOnlyList<ModifierData> ActiveModifiers => activeModifierData;
public ScoreResult PreviewScore(int[] diceValues, YachtCategory category)
{
int baseScore = CategoryScorer.Calculate(diceValues, category);
ScoreResult result = ScoreResult.Create(baseScore, diceValues, category);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.SelectedCategory);
return result;
}
public ScoreResult ScoreCategory(int[] diceValues, YachtCategory category)
{
if (usedCategories.Contains(category))
throw new InvalidOperationException($"Category {category} has already been scored.");
int baseScore = CategoryScorer.Calculate(diceValues, category);
ScoreResult result = ScoreResult.Create(baseScore, diceValues, category);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.SelectedCategory);
ModifierPipeline.Apply(activeModifierData, ref result, ModifierScope.AnyCategoryClosed);
int finalScore = result.FinalScore;
scorecard[category] = finalScore;
usedCategories.Add(category);
OnCategoryScored?.Invoke(category, finalScore);
OnCategoryConfirmed?.Invoke(category, result);
if (IsComplete)
OnAllCategoriesScored?.Invoke(TotalScore);
return result;
}
public void ResetScorecard()
{
scorecard.Clear();
usedCategories.Clear();
}
}
} }
+18 -18
View File
@@ -1,22 +1,22 @@
namespace YachtDice.Scoring namespace YachtDice.Scoring
{ {
public enum YachtCategory public enum YachtCategory
{ {
// Upper Section // Upper Section
Ones, Ones,
Twos, Twos,
Threes, Threes,
Fours, Fours,
Fives, Fives,
Sixes, Sixes,
// Lower Section // Lower Section
ThreeOfAKind, ThreeOfAKind,
FourOfAKind, FourOfAKind,
FullHouse, FullHouse,
SmallStraight, SmallStraight,
LargeStraight, LargeStraight,
Yacht, Yacht,
Chance Chance
} }
} }
+13 -14
View File
@@ -4,22 +4,21 @@ using YachtDice.Modifiers;
namespace YachtDice.Shop namespace YachtDice.Shop
{ {
[CreateAssetMenu(fileName = "ShopCatalog", menuName = "YachtDice/Shop Catalog")]
[CreateAssetMenu(fileName = "ShopCatalog", menuName = "YachtDice/Shop Catalog")] public sealed class ShopCatalog : ScriptableObject
public sealed class ShopCatalog : ScriptableObject
{
[SerializeField] private List<ModifierData> availableModifiers = new();
public IReadOnlyList<ModifierData> AvailableModifiers => availableModifiers;
public ModifierData FindById(string id)
{ {
for (int i = 0; i < availableModifiers.Count; i++) [SerializeField] private List<ModifierData> availableModifiers = new();
public IReadOnlyList<ModifierData> AvailableModifiers => availableModifiers;
public ModifierData FindById(string id)
{ {
if (availableModifiers[i] != null && availableModifiers[i].Id == id) for (int i = 0; i < availableModifiers.Count; i++)
return availableModifiers[i]; {
if (availableModifiers[i] != null && availableModifiers[i].Id == id)
return availableModifiers[i];
}
return null;
} }
return null;
} }
} }
}
+41 -42
View File
@@ -4,58 +4,57 @@ using YachtDice.Modifiers;
namespace YachtDice.Shop namespace YachtDice.Shop
{ {
public class ShopController : MonoBehaviour
public sealed class ShopController : MonoBehaviour
{
[SerializeField] private ShopCatalog catalog;
[SerializeField] private ShopView shopView;
[SerializeField] private CurrencyBank currencyBank;
private ShopModel model;
public ShopCatalog Catalog => catalog;
public void Initialize(ShopModel shopModel)
{ {
model = shopModel; [SerializeField] private ShopCatalog catalog;
[SerializeField] private ShopView shopView;
[SerializeField] private CurrencyBank currencyBank;
shopView.OnBuyClicked += HandleBuyClicked; private ShopModel model;
if (currencyBank != null) public ShopCatalog Catalog => catalog;
currencyBank.OnBalanceChanged += HandleCurrencyChanged;
model.OnItemPurchased += HandleItemPurchased; public void Initialize(ShopModel shopModel)
{
model = shopModel;
shopView.Populate(catalog.AvailableModifiers, model); shopView.OnBuyClicked += HandleBuyClicked;
shopView.UpdateCurrencyDisplay(currencyBank != null ? currencyBank.Balance : 0);
}
private void OnDestroy() if (currencyBank != null)
{ currencyBank.OnBalanceChanged += HandleCurrencyChanged;
if (shopView != null)
shopView.OnBuyClicked -= HandleBuyClicked;
if (currencyBank != null) model.OnItemPurchased += HandleItemPurchased;
currencyBank.OnBalanceChanged -= HandleCurrencyChanged;
if (model != null) shopView.Populate(catalog.AvailableModifiers, model);
model.OnItemPurchased -= HandleItemPurchased; shopView.UpdateCurrencyDisplay(currencyBank != null ? currencyBank.Balance : 0);
} }
private void HandleBuyClicked(ModifierData data) private void OnDestroy()
{ {
model.TryPurchase(data); if (shopView != null)
} shopView.OnBuyClicked -= HandleBuyClicked;
private void HandleCurrencyChanged(int newBalance) if (currencyBank != null)
{ currencyBank.OnBalanceChanged -= HandleCurrencyChanged;
shopView.UpdateCurrencyDisplay(newBalance);
shopView.RefreshStates(catalog.AvailableModifiers, model);
}
private void HandleItemPurchased(ModifierData data) if (model != null)
{ model.OnItemPurchased -= HandleItemPurchased;
shopView.RefreshStates(catalog.AvailableModifiers, model); }
private void HandleBuyClicked(ModifierData data)
{
model.TryPurchase(data);
}
private void HandleCurrencyChanged(int newBalance)
{
shopView.UpdateCurrencyDisplay(newBalance);
shopView.RefreshStates(catalog.AvailableModifiers, model);
}
private void HandleItemPurchased(ModifierData data)
{
shopView.RefreshStates(catalog.AvailableModifiers, model);
}
} }
} }
}
+72 -73
View File
@@ -6,87 +6,86 @@ using YachtDice.Modifiers;
namespace YachtDice.Shop namespace YachtDice.Shop
{ {
public class ShopItemView : MonoBehaviour
public sealed class ShopItemView : MonoBehaviour
{
[SerializeField] private Image iconImage;
[SerializeField] private TMP_Text nameText;
[SerializeField] private TMP_Text descriptionText;
[SerializeField] private TMP_Text priceText;
[SerializeField] private TMP_Text rarityText;
[SerializeField] private Button buyButton;
[SerializeField] private TMP_Text buyButtonText;
[SerializeField] private Image background;
[Header("Rarity Colors")]
[SerializeField] private Color commonColor = Color.white;
[SerializeField] private Color uncommonColor = new(0.4f, 0.8f, 0.4f);
[SerializeField] private Color rareColor = new(0.4f, 0.6f, 1f);
[SerializeField] private Color epicColor = new(0.8f, 0.4f, 1f);
private ModifierData data;
public event Action<ModifierData> OnBuyClicked;
private void Awake()
{ {
if (buyButton != null) [SerializeField] private Image iconImage;
buyButton.onClick.AddListener(() => OnBuyClicked?.Invoke(data)); [SerializeField] private TMP_Text nameText;
} [SerializeField] private TMP_Text descriptionText;
[SerializeField] private TMP_Text priceText;
[SerializeField] private TMP_Text rarityText;
[SerializeField] private Button buyButton;
[SerializeField] private TMP_Text buyButtonText;
[SerializeField] private Image background;
public void Setup(ModifierData modifierData, ShopItemState state) [Header("Rarity Colors")]
{ [SerializeField] private Color commonColor = Color.white;
data = modifierData; [SerializeField] private Color uncommonColor = new(0.4f, 0.8f, 0.4f);
[SerializeField] private Color rareColor = new(0.4f, 0.6f, 1f);
[SerializeField] private Color epicColor = new(0.8f, 0.4f, 1f);
if (nameText != null) nameText.text = data.DisplayName; private ModifierData data;
if (descriptionText != null) descriptionText.text = data.Description;
if (priceText != null) priceText.text = data.ShopPrice.ToString();
if (iconImage != null && data.Icon != null) iconImage.sprite = data.Icon;
if (rarityText != null) public event Action<ModifierData> OnBuyClicked;
private void Awake()
{ {
rarityText.text = data.Rarity.ToString(); if (buyButton != null)
rarityText.color = GetRarityColor(data.Rarity); buyButton.onClick.AddListener(() => OnBuyClicked?.Invoke(data));
} }
SetState(state); public void Setup(ModifierData modifierData, ShopItemState state)
}
public void SetState(ShopItemState state)
{
if (buyButton == null) return;
switch (state)
{ {
case ShopItemState.Available: data = modifierData;
buyButton.interactable = true;
if (buyButtonText != null) buyButtonText.text = "Buy"; if (nameText != null) nameText.text = data.DisplayName;
break; if (descriptionText != null) descriptionText.text = data.Description;
case ShopItemState.RepurchaseAvailable: if (priceText != null) priceText.text = data.ShopPrice.ToString();
buyButton.interactable = true; if (iconImage != null && data.Icon != null) iconImage.sprite = data.Icon;
if (buyButtonText != null) buyButtonText.text = "Buy";
break; if (rarityText != null)
case ShopItemState.TooExpensive: {
buyButton.interactable = false; rarityText.text = data.Rarity.ToString();
if (buyButtonText != null) buyButtonText.text = "Buy"; rarityText.color = GetRarityColor(data.Rarity);
break; }
case ShopItemState.Owned:
buyButton.interactable = false; SetState(state);
if (buyButtonText != null) buyButtonText.text = "Owned"; }
break;
public void SetState(ShopItemState state)
{
if (buyButton == null) return;
switch (state)
{
case ShopItemState.Available:
buyButton.interactable = true;
if (buyButtonText != null) buyButtonText.text = "Buy";
break;
case ShopItemState.RepurchaseAvailable:
buyButton.interactable = true;
if (buyButtonText != null) buyButtonText.text = "Buy";
break;
case ShopItemState.TooExpensive:
buyButton.interactable = false;
if (buyButtonText != null) buyButtonText.text = "Buy";
break;
case ShopItemState.Owned:
buyButton.interactable = false;
if (buyButtonText != null) buyButtonText.text = "Owned";
break;
}
}
private Color GetRarityColor(ModifierRarity rarity)
{
return rarity switch
{
ModifierRarity.Common => commonColor,
ModifierRarity.Uncommon => uncommonColor,
ModifierRarity.Rare => rareColor,
ModifierRarity.Epic => epicColor,
_ => commonColor
};
} }
} }
private Color GetRarityColor(ModifierRarity rarity)
{
return rarity switch
{
ModifierRarity.Common => commonColor,
ModifierRarity.Uncommon => uncommonColor,
ModifierRarity.Rare => rareColor,
ModifierRarity.Epic => epicColor,
_ => commonColor
};
}
}
} }
+70 -71
View File
@@ -6,80 +6,79 @@ using YachtDice.Modifiers;
namespace YachtDice.Shop namespace YachtDice.Shop
{ {
public class ShopModel
public sealed class ShopModel
{
private readonly CurrencyBank currencyBank;
private readonly InventoryModel inventoryModel;
private readonly HashSet<string> purchasedPermanentIds = new();
public event Action<ModifierData> OnItemPurchased;
public ShopModel(CurrencyBank currencyBank, InventoryModel inventoryModel)
{ {
this.currencyBank = currencyBank; private readonly CurrencyBank currencyBank;
this.inventoryModel = inventoryModel; private readonly InventoryModel inventoryModel;
private readonly HashSet<string> purchasedPermanentIds = new();
public event Action<ModifierData> OnItemPurchased;
public ShopModel(CurrencyBank currencyBank, InventoryModel inventoryModel)
{
this.currencyBank = currencyBank;
this.inventoryModel = inventoryModel;
}
public bool CanPurchase(ModifierData modifier)
{
if (modifier == null) return false;
if (!currencyBank.CanAfford(modifier.ShopPrice)) return false;
if (modifier.Durability == ModifierDurability.Permanent &&
purchasedPermanentIds.Contains(modifier.Id))
return false;
return true;
}
public bool TryPurchase(ModifierData modifier)
{
if (!CanPurchase(modifier)) return false;
if (!currencyBank.Spend(modifier.ShopPrice)) return false;
if (modifier.Durability == ModifierDurability.Permanent)
purchasedPermanentIds.Add(modifier.Id);
inventoryModel.AddModifier(modifier);
OnItemPurchased?.Invoke(modifier);
return true;
}
public bool IsPermanentOwned(string modifierId) => purchasedPermanentIds.Contains(modifierId);
public ShopItemState GetItemState(ModifierData modifier)
{
if (modifier == null) return ShopItemState.TooExpensive;
if (modifier.Durability == ModifierDurability.Permanent &&
purchasedPermanentIds.Contains(modifier.Id))
return ShopItemState.Owned;
if (!currencyBank.CanAfford(modifier.ShopPrice))
return ShopItemState.TooExpensive;
return modifier.Durability == ModifierDurability.LimitedUses
? ShopItemState.RepurchaseAvailable
: ShopItemState.Available;
}
public void LoadPurchasedPermanentIds(IEnumerable<string> ids)
{
purchasedPermanentIds.Clear();
if (ids != null)
foreach (var id in ids) purchasedPermanentIds.Add(id);
}
public HashSet<string> GetPurchasedPermanentIds() => new(purchasedPermanentIds);
} }
public bool CanPurchase(ModifierData modifier) public enum ShopItemState
{ {
if (modifier == null) return false; Available,
if (!currencyBank.CanAfford(modifier.ShopPrice)) return false; TooExpensive,
Owned,
if (modifier.Durability == ModifierDurability.Permanent && RepurchaseAvailable
purchasedPermanentIds.Contains(modifier.Id))
return false;
return true;
} }
public bool TryPurchase(ModifierData modifier)
{
if (!CanPurchase(modifier)) return false;
if (!currencyBank.Spend(modifier.ShopPrice)) return false;
if (modifier.Durability == ModifierDurability.Permanent)
purchasedPermanentIds.Add(modifier.Id);
inventoryModel.AddModifier(modifier);
OnItemPurchased?.Invoke(modifier);
return true;
}
public bool IsPermanentOwned(string modifierId) => purchasedPermanentIds.Contains(modifierId);
public ShopItemState GetItemState(ModifierData modifier)
{
if (modifier == null) return ShopItemState.TooExpensive;
if (modifier.Durability == ModifierDurability.Permanent &&
purchasedPermanentIds.Contains(modifier.Id))
return ShopItemState.Owned;
if (!currencyBank.CanAfford(modifier.ShopPrice))
return ShopItemState.TooExpensive;
return modifier.Durability == ModifierDurability.LimitedUses
? ShopItemState.RepurchaseAvailable
: ShopItemState.Available;
}
public void LoadPurchasedPermanentIds(IEnumerable<string> ids)
{
purchasedPermanentIds.Clear();
if (ids != null)
foreach (var id in ids) purchasedPermanentIds.Add(id);
}
public HashSet<string> GetPurchasedPermanentIds() => new(purchasedPermanentIds);
}
public enum ShopItemState
{
Available,
TooExpensive,
Owned,
RepurchaseAvailable
}
} }
+58 -59
View File
@@ -7,76 +7,75 @@ using YachtDice.Modifiers;
namespace YachtDice.Shop namespace YachtDice.Shop
{ {
public class ShopView : MonoBehaviour
public sealed class ShopView : MonoBehaviour
{
[SerializeField] private Transform itemContainer;
[SerializeField] private ShopItemView itemPrefab;
[SerializeField] private TMP_Text currencyText;
[SerializeField] private Button closeButton;
private readonly List<ShopItemView> spawnedItems = new();
public event Action<ModifierData> OnBuyClicked;
private void Awake()
{ {
if (closeButton != null) [SerializeField] private Transform itemContainer;
closeButton.onClick.AddListener(Hide); [SerializeField] private ShopItemView itemPrefab;
} [SerializeField] private TMP_Text currencyText;
[SerializeField] private Button closeButton;
private void OnDestroy() private readonly List<ShopItemView> spawnedItems = new();
{
if (closeButton != null)
closeButton.onClick.RemoveListener(Hide);
}
public void Show() => gameObject.SetActive(true); public event Action<ModifierData> OnBuyClicked;
public void Hide() => gameObject.SetActive(false);
public bool IsVisible => gameObject.activeSelf;
public void Populate(IReadOnlyList<ModifierData> catalog, ShopModel model) private void Awake()
{
ClearItems();
for (int i = 0; i < catalog.Count; i++)
{ {
var data = catalog[i]; if (closeButton != null)
if (data == null) continue; closeButton.onClick.AddListener(Hide);
var item = Instantiate(itemPrefab, itemContainer);
var state = model.GetItemState(data);
item.Setup(data, state);
item.OnBuyClicked += HandleBuy;
spawnedItems.Add(item);
} }
}
public void RefreshStates(IReadOnlyList<ModifierData> catalog, ShopModel model) private void OnDestroy()
{
for (int i = 0; i < spawnedItems.Count && i < catalog.Count; i++)
{ {
var state = model.GetItemState(catalog[i]); if (closeButton != null)
spawnedItems[i].SetState(state); closeButton.onClick.RemoveListener(Hide);
} }
}
public void UpdateCurrencyDisplay(int currency) public void Show() => gameObject.SetActive(true);
{ public void Hide() => gameObject.SetActive(false);
if (currencyText != null) public bool IsVisible => gameObject.activeSelf;
currencyText.text = currency.ToString();
}
private void ClearItems() public void Populate(IReadOnlyList<ModifierData> catalog, ShopModel model)
{
for (int i = 0; i < spawnedItems.Count; i++)
{ {
spawnedItems[i].OnBuyClicked -= HandleBuy; ClearItems();
Destroy(spawnedItems[i].gameObject);
}
spawnedItems.Clear();
}
private void HandleBuy(ModifierData data) => OnBuyClicked?.Invoke(data); for (int i = 0; i < catalog.Count; i++)
} {
var data = catalog[i];
if (data == null) continue;
var item = Instantiate(itemPrefab, itemContainer);
var state = model.GetItemState(data);
item.Setup(data, state);
item.OnBuyClicked += HandleBuy;
spawnedItems.Add(item);
}
}
public void RefreshStates(IReadOnlyList<ModifierData> catalog, ShopModel model)
{
for (int i = 0; i < spawnedItems.Count && i < catalog.Count; i++)
{
var state = model.GetItemState(catalog[i]);
spawnedItems[i].SetState(state);
}
}
public void UpdateCurrencyDisplay(int currency)
{
if (currencyText != null)
currencyText.text = currency.ToString();
}
private void ClearItems()
{
for (int i = 0; i < spawnedItems.Count; i++)
{
spawnedItems[i].OnBuyClicked -= HandleBuy;
Destroy(spawnedItems[i].gameObject);
}
spawnedItems.Clear();
}
private void HandleBuy(ModifierData data) => OnBuyClicked?.Invoke(data);
}
} }
+122 -123
View File
@@ -5,157 +5,156 @@ using YachtDice.Modifiers;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public class InventoryModelTests
public sealed class InventoryModelTests
{
private InventoryModel inventory;
[SetUp]
public void SetUp()
{ {
inventory = new InventoryModel(3); private InventoryModel inventory;
}
private ModifierData CreateTestData(string id = "test", [SetUp]
ModifierDurability durability = ModifierDurability.Permanent, int maxUses = 0) public void SetUp()
{
return ModifierData.CreateForTest(id, ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: durability, maxUses: maxUses);
}
[Test]
public void AddModifier_IncreasesCount()
{
inventory.AddModifier(CreateTestData());
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
}
[Test]
public void TryActivate_SucceedsWithinSlotLimit()
{
inventory.AddModifier(CreateTestData("a"));
var mod = inventory.OwnedModifiers[0];
bool result = inventory.TryActivate(mod);
Assert.IsTrue(result);
Assert.IsTrue(mod.IsActive);
Assert.AreEqual(1, inventory.ActiveCount);
}
[Test]
public void TryActivate_FailsWhenSlotsFull()
{
for (int i = 0; i < 3; i++)
{ {
inventory.AddModifier(CreateTestData($"m{i}")); inventory = new InventoryModel(3);
inventory.TryActivate(inventory.OwnedModifiers[i]);
} }
inventory.AddModifier(CreateTestData("extra")); private ModifierData CreateTestData(string id = "test",
var extra = inventory.OwnedModifiers[3]; ModifierDurability durability = ModifierDurability.Permanent, int maxUses = 0)
bool result = inventory.TryActivate(extra); {
return ModifierData.CreateForTest(id, ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: durability, maxUses: maxUses);
}
Assert.IsFalse(result); [Test]
Assert.IsFalse(extra.IsActive); public void AddModifier_IncreasesCount()
Assert.AreEqual(3, inventory.ActiveCount); {
} inventory.AddModifier(CreateTestData());
[Test] Assert.AreEqual(1, inventory.OwnedModifiers.Count);
public void Deactivate_FreesSlot() }
{
inventory.AddModifier(CreateTestData());
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
inventory.Deactivate(mod); [Test]
public void TryActivate_SucceedsWithinSlotLimit()
{
inventory.AddModifier(CreateTestData("a"));
var mod = inventory.OwnedModifiers[0];
Assert.IsFalse(mod.IsActive); bool result = inventory.TryActivate(mod);
Assert.AreEqual(0, inventory.ActiveCount);
}
[Test] Assert.IsTrue(result);
public void RemoveModifier_DeactivatesAndRemoves() Assert.IsTrue(mod.IsActive);
{ Assert.AreEqual(1, inventory.ActiveCount);
inventory.AddModifier(CreateTestData()); }
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
inventory.RemoveModifier(mod); [Test]
public void TryActivate_FailsWhenSlotsFull()
{
for (int i = 0; i < 3; i++)
{
inventory.AddModifier(CreateTestData($"m{i}"));
inventory.TryActivate(inventory.OwnedModifiers[i]);
}
Assert.AreEqual(0, inventory.OwnedModifiers.Count); inventory.AddModifier(CreateTestData("extra"));
Assert.AreEqual(0, inventory.ActiveCount); var extra = inventory.OwnedModifiers[3];
} bool result = inventory.TryActivate(extra);
[Test] Assert.IsFalse(result);
public void ConsumeUseOnActive_DecrementsUses() Assert.IsFalse(extra.IsActive);
{ Assert.AreEqual(3, inventory.ActiveCount);
inventory.AddModifier(CreateTestData("ltd", ModifierDurability.LimitedUses, 3)); }
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
inventory.ConsumeUseOnActive(); [Test]
public void Deactivate_FreesSlot()
{
inventory.AddModifier(CreateTestData());
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
Assert.AreEqual(2, mod.RemainingUses); inventory.Deactivate(mod);
}
[Test] Assert.IsFalse(mod.IsActive);
public void ConsumeUseOnActive_RemovesExpired() Assert.AreEqual(0, inventory.ActiveCount);
{ }
inventory.AddModifier(CreateTestData("ltd", ModifierDurability.LimitedUses, 1));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
inventory.ConsumeUseOnActive(); [Test]
public void RemoveModifier_DeactivatesAndRemoves()
{
inventory.AddModifier(CreateTestData());
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
Assert.AreEqual(0, inventory.OwnedModifiers.Count); inventory.RemoveModifier(mod);
}
[Test] Assert.AreEqual(0, inventory.OwnedModifiers.Count);
public void ConsumeUseOnActive_IgnoresPermanent() Assert.AreEqual(0, inventory.ActiveCount);
{ }
inventory.AddModifier(CreateTestData("perm", ModifierDurability.Permanent));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
inventory.ConsumeUseOnActive(); [Test]
public void ConsumeUseOnActive_DecrementsUses()
{
inventory.AddModifier(CreateTestData("ltd", ModifierDurability.LimitedUses, 3));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
Assert.AreEqual(1, inventory.OwnedModifiers.Count); inventory.ConsumeUseOnActive();
Assert.IsTrue(mod.IsActive);
}
[Test] Assert.AreEqual(2, mod.RemainingUses);
public void GetActiveModifierData_ReturnsOnlyActive() }
{
inventory.AddModifier(CreateTestData("a"));
inventory.AddModifier(CreateTestData("b"));
inventory.TryActivate(inventory.OwnedModifiers[0]);
var active = inventory.GetActiveModifierData(); [Test]
public void ConsumeUseOnActive_RemovesExpired()
{
inventory.AddModifier(CreateTestData("ltd", ModifierDurability.LimitedUses, 1));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
Assert.AreEqual(1, active.Count); inventory.ConsumeUseOnActive();
}
[Test] Assert.AreEqual(0, inventory.OwnedModifiers.Count);
public void SetMaxActiveSlots_AllowsExpansion() }
{
inventory.SetMaxActiveSlots(10);
Assert.AreEqual(10, inventory.MaxActiveSlots); [Test]
} public void ConsumeUseOnActive_IgnoresPermanent()
{
inventory.AddModifier(CreateTestData("perm", ModifierDurability.Permanent));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
[Test] inventory.ConsumeUseOnActive();
public void OnActiveModifiersChanged_FiredOnActivate()
{
bool fired = false;
inventory.OnActiveModifiersChanged += _ => fired = true;
inventory.AddModifier(CreateTestData());
inventory.TryActivate(inventory.OwnedModifiers[0]); Assert.AreEqual(1, inventory.OwnedModifiers.Count);
Assert.IsTrue(mod.IsActive);
}
Assert.IsTrue(fired); [Test]
public void GetActiveModifierData_ReturnsOnlyActive()
{
inventory.AddModifier(CreateTestData("a"));
inventory.AddModifier(CreateTestData("b"));
inventory.TryActivate(inventory.OwnedModifiers[0]);
var active = inventory.GetActiveModifierData();
Assert.AreEqual(1, active.Count);
}
[Test]
public void SetMaxActiveSlots_AllowsExpansion()
{
inventory.SetMaxActiveSlots(10);
Assert.AreEqual(10, inventory.MaxActiveSlots);
}
[Test]
public void OnActiveModifiersChanged_FiredOnActivate()
{
bool fired = false;
inventory.OnActiveModifiersChanged += _ => fired = true;
inventory.AddModifier(CreateTestData());
inventory.TryActivate(inventory.OwnedModifiers[0]);
Assert.IsTrue(fired);
}
} }
} }
}
@@ -5,91 +5,90 @@ using YachtDice.Scoring;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public class ModifierEffectTests
public sealed class ModifierEffectTests
{
private static ModifierData CreateData(
ModifierEffectType effectType, float effectValue,
int dieValue = 0, ModifierScope scope = ModifierScope.SelectedCategory)
{ {
return ModifierData.CreateForTest("test", scope, effectType, effectValue, dieValue); private static ModifierData CreateData(
} ModifierEffectType effectType, float effectValue,
int dieValue = 0, ModifierScope scope = ModifierScope.SelectedCategory)
{
return ModifierData.CreateForTest("test", scope, effectType, effectValue, dieValue);
}
[Test] [Test]
public void AddPerDieValue_CountsMatchingDice() public void AddPerDieValue_CountsMatchingDice()
{ {
var data = CreateData(ModifierEffectType.AddPerDieValue, 10f, dieValue: 1); var data = CreateData(ModifierEffectType.AddPerDieValue, 10f, dieValue: 1);
var result = ScoreResult.Create(5, new[] { 1, 1, 3, 4, 1 }, YachtCategory.Ones); var result = ScoreResult.Create(5, new[] { 1, 1, 3, 4, 1 }, YachtCategory.Ones);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(30, result.FlatBonus); Assert.AreEqual(30, result.FlatBonus);
} }
[Test] [Test]
public void AddPerDieValue_ZeroTarget_CountsAllDice() public void AddPerDieValue_ZeroTarget_CountsAllDice()
{ {
var data = CreateData(ModifierEffectType.AddPerDieValue, 2f, dieValue: 0); var data = CreateData(ModifierEffectType.AddPerDieValue, 2f, dieValue: 0);
var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(10, result.FlatBonus); Assert.AreEqual(10, result.FlatBonus);
} }
[Test] [Test]
public void AddPerDieValue_NoMatches_ZeroBonus() public void AddPerDieValue_NoMatches_ZeroBonus()
{ {
var data = CreateData(ModifierEffectType.AddPerDieValue, 10f, dieValue: 6); var data = CreateData(ModifierEffectType.AddPerDieValue, 10f, dieValue: 6);
var result = ScoreResult.Create(5, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(5, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(0, result.FlatBonus); Assert.AreEqual(0, result.FlatBonus);
} }
[Test] [Test]
public void AddFlatToFinalScore_AddsFlat() public void AddFlatToFinalScore_AddsFlat()
{ {
var data = CreateData(ModifierEffectType.AddFlatToFinalScore, 15f); var data = CreateData(ModifierEffectType.AddFlatToFinalScore, 15f);
var result = ScoreResult.Create(25, new[] { 3, 3, 2, 2, 2 }, YachtCategory.FullHouse); var result = ScoreResult.Create(25, new[] { 3, 3, 2, 2, 2 }, YachtCategory.FullHouse);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(15, result.FlatBonus); Assert.AreEqual(15, result.FlatBonus);
} }
[Test] [Test]
public void MultiplyPerDieValue_MultipliesPerMatch() public void MultiplyPerDieValue_MultipliesPerMatch()
{ {
var data = CreateData(ModifierEffectType.MultiplyPerDieValue, 2f, dieValue: 6); var data = CreateData(ModifierEffectType.MultiplyPerDieValue, 2f, dieValue: 6);
var result = ScoreResult.Create(18, new[] { 6, 6, 6, 1, 2 }, YachtCategory.Sixes); var result = ScoreResult.Create(18, new[] { 6, 6, 6, 1, 2 }, YachtCategory.Sixes);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(8f, result.Multiplier); // 1 * 2 * 2 * 2 = 8 Assert.AreEqual(8f, result.Multiplier); // 1 * 2 * 2 * 2 = 8
} }
[Test] [Test]
public void MultiplyPerDieValue_NoMatches_MultiplierUnchanged() public void MultiplyPerDieValue_NoMatches_MultiplierUnchanged()
{ {
var data = CreateData(ModifierEffectType.MultiplyPerDieValue, 3f, dieValue: 6); var data = CreateData(ModifierEffectType.MultiplyPerDieValue, 3f, dieValue: 6);
var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(1f, result.Multiplier); Assert.AreEqual(1f, result.Multiplier);
} }
[Test] [Test]
public void MultiplyFinalScore_MultipliesOnce() public void MultiplyFinalScore_MultipliesOnce()
{ {
var data = CreateData(ModifierEffectType.MultiplyFinalScore, 1.5f); var data = CreateData(ModifierEffectType.MultiplyFinalScore, 1.5f);
var result = ScoreResult.Create(50, new[] { 6, 6, 6, 6, 6 }, YachtCategory.Yacht); var result = ScoreResult.Create(50, new[] { 6, 6, 6, 6, 6 }, YachtCategory.Yacht);
ModifierEffect.Apply(data, ref result); ModifierEffect.Apply(data, ref result);
Assert.AreEqual(1.5f, result.Multiplier, 0.001f); Assert.AreEqual(1.5f, result.Multiplier, 0.001f);
}
} }
} }
}
@@ -6,137 +6,136 @@ using YachtDice.Scoring;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public class ModifierPipelineTests
public sealed class ModifierPipelineTests
{
[Test]
public void Apply_AdditiveBeforeMultiplicative()
{ {
var addMod = ModifierData.CreateForTest("add", ModifierScope.SelectedCategory, [Test]
ModifierEffectType.AddFlatToFinalScore, 10f); public void Apply_AdditiveBeforeMultiplicative()
var mulMod = ModifierData.CreateForTest("mul", ModifierScope.SelectedCategory, {
ModifierEffectType.MultiplyFinalScore, 2f); var addMod = ModifierData.CreateForTest("add", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f);
var mulMod = ModifierData.CreateForTest("mul", ModifierScope.SelectedCategory,
ModifierEffectType.MultiplyFinalScore, 2f);
var modifiers = new List<ModifierData> { mulMod, addMod }; var modifiers = new List<ModifierData> { mulMod, addMod };
var result = ScoreResult.Create(20, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(20, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
// (20 + 10) * 2 = 60 // (20 + 10) * 2 = 60
Assert.AreEqual(60, result.FinalScore); Assert.AreEqual(60, result.FinalScore);
} }
[Test] [Test]
public void Apply_CategoryLevelBeforeFinalScore() public void Apply_CategoryLevelBeforeFinalScore()
{ {
var perDie = ModifierData.CreateForTest("perDie", ModifierScope.SelectedCategory, var perDie = ModifierData.CreateForTest("perDie", ModifierScope.SelectedCategory,
ModifierEffectType.AddPerDieValue, 5f, dieValue: 1); ModifierEffectType.AddPerDieValue, 5f, dieValue: 1);
var flat = ModifierData.CreateForTest("flat", ModifierScope.SelectedCategory, var flat = ModifierData.CreateForTest("flat", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 100f); ModifierEffectType.AddFlatToFinalScore, 100f);
var modifiers = new List<ModifierData> { flat, perDie }; var modifiers = new List<ModifierData> { flat, perDie };
var result = ScoreResult.Create(3, new[] { 1, 1, 1, 2, 3 }, YachtCategory.Ones); var result = ScoreResult.Create(3, new[] { 1, 1, 1, 2, 3 }, YachtCategory.Ones);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
// FlatBonus = 15 (perDie: 5*3) + 100 (flat) = 115 // FlatBonus = 15 (perDie: 5*3) + 100 (flat) = 115
// FinalScore = (3 + 115) * 1 = 118 // FinalScore = (3 + 115) * 1 = 118
Assert.AreEqual(118, result.FinalScore); Assert.AreEqual(118, result.FinalScore);
} }
[Test] [Test]
public void Apply_ScopeFiltering_SkipsWrongScope() public void Apply_ScopeFiltering_SkipsWrongScope()
{ {
var mod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed, var mod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed,
ModifierEffectType.AddFlatToFinalScore, 50f); ModifierEffectType.AddFlatToFinalScore, 50f);
var modifiers = new List<ModifierData> { mod }; var modifiers = new List<ModifierData> { mod };
var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
Assert.AreEqual(0, result.FlatBonus); Assert.AreEqual(0, result.FlatBonus);
Assert.AreEqual(10, result.FinalScore); Assert.AreEqual(10, result.FinalScore);
} }
[Test] [Test]
public void Apply_CategoryFilter_SkipsWrongCategory() public void Apply_CategoryFilter_SkipsWrongCategory()
{ {
var mod = ModifierData.CreateForTest("fh", ModifierScope.SelectedCategory, var mod = ModifierData.CreateForTest("fh", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 15f, ModifierEffectType.AddFlatToFinalScore, 15f,
targetCategory: YachtCategory.FullHouse, hasCategoryFilter: true); targetCategory: YachtCategory.FullHouse, hasCategoryFilter: true);
var modifiers = new List<ModifierData> { mod }; var modifiers = new List<ModifierData> { mod };
var result = ScoreResult.Create(5, new[] { 1, 1, 1, 1, 1 }, YachtCategory.Ones); var result = ScoreResult.Create(5, new[] { 1, 1, 1, 1, 1 }, YachtCategory.Ones);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
Assert.AreEqual(0, result.FlatBonus); Assert.AreEqual(0, result.FlatBonus);
} }
[Test] [Test]
public void Apply_CategoryFilter_AppliesMatchingCategory() public void Apply_CategoryFilter_AppliesMatchingCategory()
{ {
var mod = ModifierData.CreateForTest("fh", ModifierScope.SelectedCategory, var mod = ModifierData.CreateForTest("fh", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 15f, ModifierEffectType.AddFlatToFinalScore, 15f,
targetCategory: YachtCategory.FullHouse, hasCategoryFilter: true); targetCategory: YachtCategory.FullHouse, hasCategoryFilter: true);
var modifiers = new List<ModifierData> { mod }; var modifiers = new List<ModifierData> { mod };
var result = ScoreResult.Create(25, new[] { 3, 3, 3, 2, 2 }, YachtCategory.FullHouse); var result = ScoreResult.Create(25, new[] { 3, 3, 3, 2, 2 }, YachtCategory.FullHouse);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
Assert.AreEqual(15, result.FlatBonus); Assert.AreEqual(15, result.FlatBonus);
Assert.AreEqual(40, result.FinalScore); Assert.AreEqual(40, result.FinalScore);
} }
[Test] [Test]
public void Apply_MultipleModifiers_CorrectOrder() public void Apply_MultipleModifiers_CorrectOrder()
{ {
var perDieAdd = ModifierData.CreateForTest("pda", ModifierScope.SelectedCategory, var perDieAdd = ModifierData.CreateForTest("pda", ModifierScope.SelectedCategory,
ModifierEffectType.AddPerDieValue, 2f, dieValue: 3); ModifierEffectType.AddPerDieValue, 2f, dieValue: 3);
var perDieMul = ModifierData.CreateForTest("pdm", ModifierScope.SelectedCategory, var perDieMul = ModifierData.CreateForTest("pdm", ModifierScope.SelectedCategory,
ModifierEffectType.MultiplyPerDieValue, 1.5f, dieValue: 3); ModifierEffectType.MultiplyPerDieValue, 1.5f, dieValue: 3);
var flatAdd = ModifierData.CreateForTest("fa", ModifierScope.SelectedCategory, var flatAdd = ModifierData.CreateForTest("fa", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f); ModifierEffectType.AddFlatToFinalScore, 10f);
var finalMul = ModifierData.CreateForTest("fm", ModifierScope.SelectedCategory, var finalMul = ModifierData.CreateForTest("fm", ModifierScope.SelectedCategory,
ModifierEffectType.MultiplyFinalScore, 2f); ModifierEffectType.MultiplyFinalScore, 2f);
var modifiers = new List<ModifierData> { finalMul, flatAdd, perDieMul, perDieAdd }; var modifiers = new List<ModifierData> { finalMul, flatAdd, perDieMul, perDieAdd };
// dice: [3, 3, 3, 1, 2] — 3 threes // dice: [3, 3, 3, 1, 2] — 3 threes
var result = ScoreResult.Create(9, new[] { 3, 3, 3, 1, 2 }, YachtCategory.Threes); var result = ScoreResult.Create(9, new[] { 3, 3, 3, 1, 2 }, YachtCategory.Threes);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
// Pass 1 (cat additive): perDieAdd: +2*3 = +6 FlatBonus // Pass 1 (cat additive): perDieAdd: +2*3 = +6 FlatBonus
// Pass 2 (cat multiplicative): perDieMul: 1.5^3 = 3.375 Multiplier // Pass 2 (cat multiplicative): perDieMul: 1.5^3 = 3.375 Multiplier
// Pass 3 (final additive): flatAdd: +10 FlatBonus → total FlatBonus = 16 // Pass 3 (final additive): flatAdd: +10 FlatBonus → total FlatBonus = 16
// Pass 4 (final multiplicative): finalMul: 3.375 * 2 = 6.75 Multiplier // Pass 4 (final multiplicative): finalMul: 3.375 * 2 = 6.75 Multiplier
// FinalScore = floor((9 + 16) * 6.75) = floor(168.75) = 168 // FinalScore = floor((9 + 16) * 6.75) = floor(168.75) = 168
Assert.AreEqual(6, result.FlatBonus + 10); // just check pipeline ran; full calc below Assert.AreEqual(6, result.FlatBonus + 10); // just check pipeline ran; full calc below
Assert.AreEqual(168, result.FinalScore); Assert.AreEqual(168, result.FinalScore);
} }
[Test] [Test]
public void Apply_NullModifiers_DoesNotThrow() public void Apply_NullModifiers_DoesNotThrow()
{ {
var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
Assert.DoesNotThrow(() => Assert.DoesNotThrow(() =>
ModifierPipeline.Apply(null, ref result, ModifierScope.SelectedCategory)); ModifierPipeline.Apply(null, ref result, ModifierScope.SelectedCategory));
Assert.AreEqual(10, result.FinalScore); Assert.AreEqual(10, result.FinalScore);
} }
[Test] [Test]
public void Apply_EmptyList_NoChange() public void Apply_EmptyList_NoChange()
{ {
var modifiers = new List<ModifierData>(); var modifiers = new List<ModifierData>();
var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance); var result = ScoreResult.Create(10, new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory); ModifierPipeline.Apply(modifiers, ref result, ModifierScope.SelectedCategory);
Assert.AreEqual(10, result.FinalScore); Assert.AreEqual(10, result.FinalScore);
}
} }
} }
}
+68 -69
View File
@@ -5,89 +5,88 @@ using YachtDice.Persistence;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public class SaveSystemTests
public sealed class SaveSystemTests
{
[SetUp]
public void SetUp()
{ {
SaveSystem.Delete(); [SetUp]
} public void SetUp()
[TearDown]
public void TearDown()
{
SaveSystem.Delete();
}
[Test]
public void SaveAndLoad_RoundTrip_PreservesData()
{
var data = new SaveData
{ {
Currency = 999, SaveSystem.Delete();
OwnedModifiers = new List<ModifierSaveEntry> }
[TearDown]
public void TearDown()
{
SaveSystem.Delete();
}
[Test]
public void SaveAndLoad_RoundTrip_PreservesData()
{
var data = new SaveData
{ {
new() { ModifierId = "mod1", IsActive = true, RemainingUses = 3 }, Currency = 999,
new() { ModifierId = "mod2", IsActive = false, RemainingUses = -1 } OwnedModifiers = new List<ModifierSaveEntry>
} {
}; new() { ModifierId = "mod1", IsActive = true, RemainingUses = 3 },
new() { ModifierId = "mod2", IsActive = false, RemainingUses = -1 }
}
};
SaveSystem.Save(data); SaveSystem.Save(data);
var loaded = SaveSystem.Load(); var loaded = SaveSystem.Load();
Assert.AreEqual(999, loaded.Currency); Assert.AreEqual(999, loaded.Currency);
Assert.AreEqual(2, loaded.OwnedModifiers.Count); Assert.AreEqual(2, loaded.OwnedModifiers.Count);
Assert.AreEqual("mod1", loaded.OwnedModifiers[0].ModifierId); Assert.AreEqual("mod1", loaded.OwnedModifiers[0].ModifierId);
Assert.IsTrue(loaded.OwnedModifiers[0].IsActive); Assert.IsTrue(loaded.OwnedModifiers[0].IsActive);
Assert.AreEqual(3, loaded.OwnedModifiers[0].RemainingUses); Assert.AreEqual(3, loaded.OwnedModifiers[0].RemainingUses);
Assert.AreEqual("mod2", loaded.OwnedModifiers[1].ModifierId); Assert.AreEqual("mod2", loaded.OwnedModifiers[1].ModifierId);
Assert.IsFalse(loaded.OwnedModifiers[1].IsActive); Assert.IsFalse(loaded.OwnedModifiers[1].IsActive);
} }
[Test] [Test]
public void Load_MissingKey_ReturnsDefault() public void Load_MissingKey_ReturnsDefault()
{ {
var loaded = SaveSystem.Load(); var loaded = SaveSystem.Load();
Assert.IsNotNull(loaded); Assert.IsNotNull(loaded);
Assert.AreEqual(0, loaded.Currency); Assert.AreEqual(0, loaded.Currency);
Assert.AreEqual(0, loaded.OwnedModifiers.Count); Assert.AreEqual(0, loaded.OwnedModifiers.Count);
} }
[Test] [Test]
public void HasSave_ReturnsFalseWhenEmpty() public void HasSave_ReturnsFalseWhenEmpty()
{ {
Assert.IsFalse(SaveSystem.HasSave()); Assert.IsFalse(SaveSystem.HasSave());
} }
[Test] [Test]
public void HasSave_ReturnsTrueAfterSave() public void HasSave_ReturnsTrueAfterSave()
{ {
SaveSystem.Save(new SaveData { Currency = 100 }); SaveSystem.Save(new SaveData { Currency = 100 });
Assert.IsTrue(SaveSystem.HasSave()); Assert.IsTrue(SaveSystem.HasSave());
} }
[Test] [Test]
public void Delete_RemovesSaveData() public void Delete_RemovesSaveData()
{ {
SaveSystem.Save(new SaveData { Currency = 100 }); SaveSystem.Save(new SaveData { Currency = 100 });
SaveSystem.Delete(); SaveSystem.Delete();
Assert.IsFalse(SaveSystem.HasSave()); Assert.IsFalse(SaveSystem.HasSave());
} }
[Test] [Test]
public void Load_CorruptJson_ReturnsDefault() public void Load_CorruptJson_ReturnsDefault()
{ {
PlayerPrefs.SetString("YachtDice_SaveData", "{invalid json!!!"); PlayerPrefs.SetString("YachtDice_SaveData", "{invalid json!!!");
PlayerPrefs.Save(); PlayerPrefs.Save();
var loaded = SaveSystem.Load(); var loaded = SaveSystem.Load();
Assert.IsNotNull(loaded); Assert.IsNotNull(loaded);
Assert.AreEqual(0, loaded.Currency); Assert.AreEqual(0, loaded.Currency);
}
} }
} }
}
@@ -6,99 +6,98 @@ using YachtDice.Modifiers;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public class ScoringSystemTests
public sealed class ScoringSystemTests
{
private ScoringSystem CreateScoringSystem()
{ {
var go = new GameObject("ScoringSystem"); private ScoringSystem CreateScoringSystem()
return go.AddComponent<ScoringSystem>();
}
[TearDown]
public void TearDown()
{
foreach (var go in Object.FindObjectsByType<ScoringSystem>(FindObjectsSortMode.None))
Object.DestroyImmediate(go.gameObject);
}
[Test]
public void PreviewScore_AppliesOnlySelectedCategoryModifiers()
{
var system = CreateScoringSystem();
var selectedMod = ModifierData.CreateForTest("sel", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f);
var anyCloseMod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed,
ModifierEffectType.AddFlatToFinalScore, 100f);
system.SetActiveModifiers(new List<ModifierData> { selectedMod, anyCloseMod });
var result = system.PreviewScore(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
// Only SelectedCategory mod should apply in preview
Assert.AreEqual(10, result.FlatBonus);
Assert.AreEqual(25, result.FinalScore); // (15 + 10) * 1
}
[Test]
public void ScoreCategory_AppliesBothScopes()
{
var system = CreateScoringSystem();
var selectedMod = ModifierData.CreateForTest("sel", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f);
var anyCloseMod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed,
ModifierEffectType.AddFlatToFinalScore, 20f);
system.SetActiveModifiers(new List<ModifierData> { selectedMod, anyCloseMod });
var result = system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
// Both scopes should apply
Assert.AreEqual(30, result.FlatBonus);
Assert.AreEqual(45, result.FinalScore); // (15 + 30) * 1
}
[Test]
public void ScoreCategory_FiresOnCategoryConfirmed()
{
var system = CreateScoringSystem();
YachtCategory firedCategory = (YachtCategory)(-1);
ScoreResult firedResult = default;
system.OnCategoryConfirmed += (cat, res) =>
{ {
firedCategory = cat; var go = new GameObject("ScoringSystem");
firedResult = res; return go.AddComponent<ScoringSystem>();
}; }
system.ScoreCategory(new[] { 1, 1, 1, 1, 1 }, YachtCategory.Ones); [TearDown]
public void TearDown()
{
foreach (var go in Object.FindObjectsByType<ScoringSystem>(FindObjectsSortMode.None))
Object.DestroyImmediate(go.gameObject);
}
Assert.AreEqual(YachtCategory.Ones, firedCategory); [Test]
Assert.AreEqual(5, firedResult.BaseScore); public void PreviewScore_AppliesOnlySelectedCategoryModifiers()
} {
var system = CreateScoringSystem();
[Test] var selectedMod = ModifierData.CreateForTest("sel", ModifierScope.SelectedCategory,
public void ScoreCategory_PreventsDuplicateCategory() ModifierEffectType.AddFlatToFinalScore, 10f);
{ var anyCloseMod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed,
var system = CreateScoringSystem(); ModifierEffectType.AddFlatToFinalScore, 100f);
system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
Assert.Throws<System.InvalidOperationException>(() => system.SetActiveModifiers(new List<ModifierData> { selectedMod, anyCloseMod });
system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance));
}
[Test] var result = system.PreviewScore(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
public void ScoreCategory_WithNoModifiers_CalculatesBaseOnly()
{
var system = CreateScoringSystem();
var result = system.ScoreCategory(new[] { 6, 6, 6, 6, 6 }, YachtCategory.Yacht);
Assert.AreEqual(50, result.BaseScore); // Only SelectedCategory mod should apply in preview
Assert.AreEqual(0, result.FlatBonus); Assert.AreEqual(10, result.FlatBonus);
Assert.AreEqual(1f, result.Multiplier); Assert.AreEqual(25, result.FinalScore); // (15 + 10) * 1
Assert.AreEqual(50, result.FinalScore); }
[Test]
public void ScoreCategory_AppliesBothScopes()
{
var system = CreateScoringSystem();
var selectedMod = ModifierData.CreateForTest("sel", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f);
var anyCloseMod = ModifierData.CreateForTest("any", ModifierScope.AnyCategoryClosed,
ModifierEffectType.AddFlatToFinalScore, 20f);
system.SetActiveModifiers(new List<ModifierData> { selectedMod, anyCloseMod });
var result = system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
// Both scopes should apply
Assert.AreEqual(30, result.FlatBonus);
Assert.AreEqual(45, result.FinalScore); // (15 + 30) * 1
}
[Test]
public void ScoreCategory_FiresOnCategoryConfirmed()
{
var system = CreateScoringSystem();
YachtCategory firedCategory = (YachtCategory)(-1);
ScoreResult firedResult = default;
system.OnCategoryConfirmed += (cat, res) =>
{
firedCategory = cat;
firedResult = res;
};
system.ScoreCategory(new[] { 1, 1, 1, 1, 1 }, YachtCategory.Ones);
Assert.AreEqual(YachtCategory.Ones, firedCategory);
Assert.AreEqual(5, firedResult.BaseScore);
}
[Test]
public void ScoreCategory_PreventsDuplicateCategory()
{
var system = CreateScoringSystem();
system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance);
Assert.Throws<System.InvalidOperationException>(() =>
system.ScoreCategory(new[] { 1, 2, 3, 4, 5 }, YachtCategory.Chance));
}
[Test]
public void ScoreCategory_WithNoModifiers_CalculatesBaseOnly()
{
var system = CreateScoringSystem();
var result = system.ScoreCategory(new[] { 6, 6, 6, 6, 6 }, YachtCategory.Yacht);
Assert.AreEqual(50, result.BaseScore);
Assert.AreEqual(0, result.FlatBonus);
Assert.AreEqual(1f, result.Multiplier);
Assert.AreEqual(50, result.FinalScore);
}
} }
} }
}
+100 -101
View File
@@ -7,132 +7,131 @@ using YachtDice.Modifiers;
namespace YachtDice.Tests namespace YachtDice.Tests
{ {
public sealed class ShopModelTests
public sealed class ShopModelTests
{
private CurrencyBank bank;
private InventoryModel inventory;
private ShopModel shop;
[SetUp]
public void SetUp()
{ {
var go = new GameObject("Bank"); private CurrencyBank bank;
bank = go.AddComponent<CurrencyBank>(); private InventoryModel inventory;
bank.SetBalance(500); private ShopModel shop;
inventory = new InventoryModel(5); [SetUp]
shop = new ShopModel(bank, inventory); public void SetUp()
} {
var go = new GameObject("Bank");
bank = go.AddComponent<CurrencyBank>();
bank.SetBalance(500);
[TearDown] inventory = new InventoryModel(5);
public void TearDown() shop = new ShopModel(bank, inventory);
{ }
foreach (var go in Object.FindObjectsByType<CurrencyBank>(FindObjectsSortMode.None))
Object.DestroyImmediate(go.gameObject);
}
[Test] [TearDown]
public void TryPurchase_SucceedsWithSufficientCurrency() public void TearDown()
{ {
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory, foreach (var go in Object.FindObjectsByType<CurrencyBank>(FindObjectsSortMode.None))
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100); Object.DestroyImmediate(go.gameObject);
}
bool result = shop.TryPurchase(mod); [Test]
public void TryPurchase_SucceedsWithSufficientCurrency()
{
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
Assert.IsTrue(result); bool result = shop.TryPurchase(mod);
Assert.AreEqual(400, bank.Balance);
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
}
[Test] Assert.IsTrue(result);
public void TryPurchase_FailsWhenBroke() Assert.AreEqual(400, bank.Balance);
{ Assert.AreEqual(1, inventory.OwnedModifiers.Count);
bank.SetBalance(10); }
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
bool result = shop.TryPurchase(mod); [Test]
public void TryPurchase_FailsWhenBroke()
{
bank.SetBalance(10);
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
Assert.IsFalse(result); bool result = shop.TryPurchase(mod);
Assert.AreEqual(10, bank.Balance);
Assert.AreEqual(0, inventory.OwnedModifiers.Count);
}
[Test] Assert.IsFalse(result);
public void TryPurchase_PermanentCannotBeBoughtTwice() Assert.AreEqual(10, bank.Balance);
{ Assert.AreEqual(0, inventory.OwnedModifiers.Count);
var mod = ModifierData.CreateForTest("perm", ModifierScope.SelectedCategory, }
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.Permanent, shopPrice: 100);
shop.TryPurchase(mod); [Test]
bool secondResult = shop.TryPurchase(mod); public void TryPurchase_PermanentCannotBeBoughtTwice()
{
var mod = ModifierData.CreateForTest("perm", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.Permanent, shopPrice: 100);
Assert.IsFalse(secondResult); shop.TryPurchase(mod);
Assert.AreEqual(400, bank.Balance); bool secondResult = shop.TryPurchase(mod);
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
}
[Test] Assert.IsFalse(secondResult);
public void TryPurchase_LimitedCanBeReBought() Assert.AreEqual(400, bank.Balance);
{ Assert.AreEqual(1, inventory.OwnedModifiers.Count);
var mod = ModifierData.CreateForTest("limited", ModifierScope.SelectedCategory, }
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.LimitedUses, maxUses: 3, shopPrice: 100);
shop.TryPurchase(mod); [Test]
bool secondResult = shop.TryPurchase(mod); public void TryPurchase_LimitedCanBeReBought()
{
var mod = ModifierData.CreateForTest("limited", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.LimitedUses, maxUses: 3, shopPrice: 100);
Assert.IsTrue(secondResult); shop.TryPurchase(mod);
Assert.AreEqual(300, bank.Balance); bool secondResult = shop.TryPurchase(mod);
Assert.AreEqual(2, inventory.OwnedModifiers.Count);
}
[Test] Assert.IsTrue(secondResult);
public void TryPurchase_FiresPurchaseEvent() Assert.AreEqual(300, bank.Balance);
{ Assert.AreEqual(2, inventory.OwnedModifiers.Count);
ModifierData purchased = null; }
shop.OnItemPurchased += data => purchased = data;
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory, [Test]
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100); public void TryPurchase_FiresPurchaseEvent()
{
ModifierData purchased = null;
shop.OnItemPurchased += data => purchased = data;
shop.TryPurchase(mod); var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
Assert.IsNotNull(purchased); shop.TryPurchase(mod);
Assert.AreEqual("test", purchased.Id);
}
[Test] Assert.IsNotNull(purchased);
public void GetItemState_Available_WhenCanAfford() Assert.AreEqual("test", purchased.Id);
{ }
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
Assert.AreEqual(ShopItemState.Available, shop.GetItemState(mod)); [Test]
} public void GetItemState_Available_WhenCanAfford()
{
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
[Test] Assert.AreEqual(ShopItemState.Available, shop.GetItemState(mod));
public void GetItemState_TooExpensive_WhenCannotAfford() }
{
bank.SetBalance(10);
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
Assert.AreEqual(ShopItemState.TooExpensive, shop.GetItemState(mod)); [Test]
} public void GetItemState_TooExpensive_WhenCannotAfford()
{
bank.SetBalance(10);
var mod = ModifierData.CreateForTest("test", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f, shopPrice: 100);
[Test] Assert.AreEqual(ShopItemState.TooExpensive, shop.GetItemState(mod));
public void GetItemState_Owned_WhenPermanentPurchased() }
{
var mod = ModifierData.CreateForTest("perm", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.Permanent, shopPrice: 100);
shop.TryPurchase(mod); [Test]
public void GetItemState_Owned_WhenPermanentPurchased()
{
var mod = ModifierData.CreateForTest("perm", ModifierScope.SelectedCategory,
ModifierEffectType.AddFlatToFinalScore, 10f,
durability: ModifierDurability.Permanent, shopPrice: 100);
Assert.AreEqual(ShopItemState.Owned, shop.GetItemState(mod)); shop.TryPurchase(mod);
Assert.AreEqual(ShopItemState.Owned, shop.GetItemState(mod));
}
} }
} }
}
+73 -74
View File
@@ -6,89 +6,88 @@ using YachtDice.Scoring;
namespace YachtDice.UI namespace YachtDice.UI
{ {
public class CategoryRowView : MonoBehaviour
public sealed class CategoryRowView : MonoBehaviour
{
[Header("UI Elements")]
[SerializeField] private TMP_Text categoryNameText;
[SerializeField] private TMP_Text previewText;
[SerializeField] private TMP_Text recordedScoreText;
[SerializeField] private Button selectButton;
[SerializeField] private Image background;
[Header("Colors")]
[SerializeField] private Color normalColor = new Color(0.95f, 0.95f, 0.95f, 1f);
[SerializeField] private Color usedColor = new Color(0.75f, 0.75f, 0.75f, 1f);
[SerializeField] private Color previewPositiveColor = new Color(0.85f, 1f, 0.85f, 1f);
[SerializeField] private Color previewZeroColor = new Color(1f, 0.88f, 0.88f, 1f);
private YachtCategory category;
private bool isUsed;
public event Action<YachtCategory> OnCategorySelected;
public void Initialize(YachtCategory cat, string displayName)
{ {
category = cat; [Header("UI Elements")]
isUsed = false; [SerializeField] private TMP_Text categoryNameText;
categoryNameText.text = displayName; [SerializeField] private TMP_Text previewText;
previewText.text = ""; [SerializeField] private TMP_Text recordedScoreText;
recordedScoreText.text = "-"; [SerializeField] private Button selectButton;
selectButton.onClick.AddListener(HandleClick); [SerializeField] private Image background;
SetInteractable(false);
background.color = normalColor;
}
public void ShowPreview(int previewScore) [Header("Colors")]
{ [SerializeField] private Color normalColor = new Color(0.95f, 0.95f, 0.95f, 1f);
if (isUsed) return; [SerializeField] private Color usedColor = new Color(0.75f, 0.75f, 0.75f, 1f);
previewText.text = previewScore.ToString(); [SerializeField] private Color previewPositiveColor = new Color(0.85f, 1f, 0.85f, 1f);
background.color = previewScore > 0 ? previewPositiveColor : previewZeroColor; [SerializeField] private Color previewZeroColor = new Color(1f, 0.88f, 0.88f, 1f);
}
public void HidePreview() private YachtCategory category;
{ private bool isUsed;
if (isUsed) return;
previewText.text = "";
background.color = normalColor;
}
public void SetRecordedScore(int score) public event Action<YachtCategory> OnCategorySelected;
{
isUsed = true;
recordedScoreText.text = score.ToString();
previewText.text = "";
SetInteractable(false);
background.color = usedColor;
}
public void SetInteractable(bool interactable) public void Initialize(YachtCategory cat, string displayName)
{
if (isUsed)
{ {
selectButton.interactable = false; category = cat;
return; isUsed = false;
categoryNameText.text = displayName;
previewText.text = "";
recordedScoreText.text = "-";
selectButton.onClick.AddListener(HandleClick);
SetInteractable(false);
background.color = normalColor;
} }
selectButton.interactable = interactable;
}
public void ResetRow() public void ShowPreview(int previewScore)
{ {
isUsed = false; if (isUsed) return;
previewText.text = ""; previewText.text = previewScore.ToString();
recordedScoreText.text = "-"; background.color = previewScore > 0 ? previewPositiveColor : previewZeroColor;
SetInteractable(false); }
background.color = normalColor;
}
private void HandleClick() public void HidePreview()
{ {
OnCategorySelected?.Invoke(category); if (isUsed) return;
} previewText.text = "";
background.color = normalColor;
}
private void OnDestroy() public void SetRecordedScore(int score)
{ {
selectButton.onClick.RemoveListener(HandleClick); isUsed = true;
recordedScoreText.text = score.ToString();
previewText.text = "";
SetInteractable(false);
background.color = usedColor;
}
public void SetInteractable(bool interactable)
{
if (isUsed)
{
selectButton.interactable = false;
return;
}
selectButton.interactable = interactable;
}
public void ResetRow()
{
isUsed = false;
previewText.text = "";
recordedScoreText.text = "-";
SetInteractable(false);
background.color = normalColor;
}
private void HandleClick()
{
OnCategorySelected?.Invoke(category);
}
private void OnDestroy()
{
selectButton.onClick.RemoveListener(HandleClick);
}
} }
} }
}
+83 -84
View File
@@ -5,101 +5,100 @@ using TMPro;
namespace YachtDice.UI namespace YachtDice.UI
{ {
public class DicePanelView : MonoBehaviour
public sealed class DicePanelView : MonoBehaviour
{
[Header("Dice Display")]
[SerializeField] private Button[] diceButtons = new Button[5];
[SerializeField] private TMP_Text[] diceValueTexts = new TMP_Text[5];
[SerializeField] private Image[] diceBackgrounds = new Image[5];
[Header("Roll")]
[SerializeField] private Button rollButton;
[SerializeField] private TMP_Text rollButtonText;
[Header("Colors")]
[SerializeField] private Color unlockedColor = Color.white;
[SerializeField] private Color lockedColor = new Color(1f, 0.85f, 0.4f, 1f);
public event Action<int> OnDiceToggled;
public event Action OnRollClicked;
private void Awake()
{ {
for (int i = 0; i < diceButtons.Length; i++) [Header("Dice Display")]
[SerializeField] private Button[] diceButtons = new Button[5];
[SerializeField] private TMP_Text[] diceValueTexts = new TMP_Text[5];
[SerializeField] private Image[] diceBackgrounds = new Image[5];
[Header("Roll")]
[SerializeField] private Button rollButton;
[SerializeField] private TMP_Text rollButtonText;
[Header("Colors")]
[SerializeField] private Color unlockedColor = Color.white;
[SerializeField] private Color lockedColor = new Color(1f, 0.85f, 0.4f, 1f);
public event Action<int> OnDiceToggled;
public event Action OnRollClicked;
private void Awake()
{ {
int capturedIndex = i; for (int i = 0; i < diceButtons.Length; i++)
diceButtons[i].onClick.AddListener(() => OnDiceToggled?.Invoke(capturedIndex)); {
int capturedIndex = i;
diceButtons[i].onClick.AddListener(() => OnDiceToggled?.Invoke(capturedIndex));
}
rollButton.onClick.AddListener(() => OnRollClicked?.Invoke());
for (int i = 0; i < diceValueTexts.Length; i++)
{
diceValueTexts[i].text = "?";
diceBackgrounds[i].color = unlockedColor;
diceButtons[i].interactable = false;
}
SetRollButtonState(true, 0, 3);
} }
rollButton.onClick.AddListener(() => OnRollClicked?.Invoke()); public void SetDieValue(int index, int value)
for (int i = 0; i < diceValueTexts.Length; i++)
{ {
diceValueTexts[i].text = "?"; if (index >= 0 && index < diceValueTexts.Length)
diceBackgrounds[i].color = unlockedColor; diceValueTexts[index].text = value.ToString();
diceButtons[i].interactable = false;
} }
SetRollButtonState(true, 0, 3); public void SetAllDiceValues(int[] values)
}
public void SetDieValue(int index, int value)
{
if (index >= 0 && index < diceValueTexts.Length)
diceValueTexts[index].text = value.ToString();
}
public void SetAllDiceValues(int[] values)
{
for (int i = 0; i < values.Length && i < diceValueTexts.Length; i++)
diceValueTexts[i].text = values[i].ToString();
}
public void SetDieLocked(int index, bool isLocked)
{
if (index >= 0 && index < diceBackgrounds.Length)
diceBackgrounds[index].color = isLocked ? lockedColor : unlockedColor;
}
public void SetDiceInteractable(bool interactable)
{
for (int i = 0; i < diceButtons.Length; i++)
diceButtons[i].interactable = interactable;
}
public void SetRollButtonState(bool interactable, int currentRoll, int maxRolls)
{
rollButton.interactable = interactable;
if (currentRoll >= maxRolls)
rollButtonText.text = "Выберите категорию";
else
rollButtonText.text = $"Бросок {currentRoll + 1}/{maxRolls}";
}
public void ResetForNewTurn()
{
for (int i = 0; i < diceValueTexts.Length; i++)
{ {
diceValueTexts[i].text = "?"; for (int i = 0; i < values.Length && i < diceValueTexts.Length; i++)
diceBackgrounds[i].color = unlockedColor; diceValueTexts[i].text = values[i].ToString();
diceButtons[i].interactable = false;
} }
}
public void ResetForNewGame() public void SetDieLocked(int index, bool isLocked)
{ {
ResetForNewTurn(); if (index >= 0 && index < diceBackgrounds.Length)
SetRollButtonState(true, 0, 3); diceBackgrounds[index].color = isLocked ? lockedColor : unlockedColor;
} }
private void OnDestroy() public void SetDiceInteractable(bool interactable)
{ {
for (int i = 0; i < diceButtons.Length; i++) for (int i = 0; i < diceButtons.Length; i++)
diceButtons[i].onClick.RemoveAllListeners(); diceButtons[i].interactable = interactable;
}
rollButton.onClick.RemoveAllListeners(); public void SetRollButtonState(bool interactable, int currentRoll, int maxRolls)
{
rollButton.interactable = interactable;
if (currentRoll >= maxRolls)
rollButtonText.text = "Выберите категорию";
else
rollButtonText.text = $"Бросок {currentRoll + 1}/{maxRolls}";
}
public void ResetForNewTurn()
{
for (int i = 0; i < diceValueTexts.Length; i++)
{
diceValueTexts[i].text = "?";
diceBackgrounds[i].color = unlockedColor;
diceButtons[i].interactable = false;
}
}
public void ResetForNewGame()
{
ResetForNewTurn();
SetRollButtonState(true, 0, 3);
}
private void OnDestroy()
{
for (int i = 0; i < diceButtons.Length; i++)
diceButtons[i].onClick.RemoveAllListeners();
rollButton.onClick.RemoveAllListeners();
}
} }
} }
}
+311 -312
View File
@@ -11,348 +11,347 @@ using YachtDice.Modifiers;
namespace YachtDice.UI namespace YachtDice.UI
{ {
public class GameController : MonoBehaviour
public sealed class GameController : MonoBehaviour
{
[Header("Model")]
[SerializeField] private GameManager gameManager;
[SerializeField] private ScoringSystem scoringSystem;
[SerializeField] private DiceManager diceManager;
[Header("Views")]
[SerializeField] private ScoreCardView scoreCardView;
[SerializeField] private DicePanelView dicePanelView;
[SerializeField] private GameInfoView gameInfoView;
[Header("Economy & Modifiers")]
[SerializeField] private CurrencyBank currencyBank;
[SerializeField] private ShopController shopController;
[SerializeField] private InventoryController inventoryController;
[Header("Settings")]
[SerializeField] private int maxRollsPerTurn = 3;
[SerializeField] private int maxActiveModifierSlots = 5;
private static readonly YachtCategory[] UpperCategories =
{ {
YachtCategory.Ones, YachtCategory.Twos, YachtCategory.Threes, [Header("Model")]
YachtCategory.Fours, YachtCategory.Fives, YachtCategory.Sixes [SerializeField] private GameManager gameManager;
}; [SerializeField] private ScoringSystem scoringSystem;
[SerializeField] private DiceManager diceManager;
private const int UpperBonusThreshold = 63; [Header("Views")]
private const int UpperBonusValue = 35; [SerializeField] private ScoreCardView scoreCardView;
[SerializeField] private DicePanelView dicePanelView;
[SerializeField] private GameInfoView gameInfoView;
private int totalCategoryCount; [Header("Economy & Modifiers")]
[SerializeField] private CurrencyBank currencyBank;
[SerializeField] private ShopController shopController;
[SerializeField] private InventoryController inventoryController;
private InventoryModel inventoryModel; [Header("Settings")]
private ShopModel shopModel; [SerializeField] private int maxRollsPerTurn = 3;
[SerializeField] private int maxActiveModifierSlots = 5;
// ── Lifecycle ────────────────────────────────────────────── private static readonly YachtCategory[] UpperCategories =
private void Awake()
{
totalCategoryCount = Enum.GetValues(typeof(YachtCategory)).Length;
// Model → Controller
gameManager.OnTurnStarted += HandleTurnStarted;
gameManager.OnRollComplete += HandleRollComplete;
gameManager.OnScored += HandleScored;
gameManager.OnGameOver += HandleGameOver;
diceManager.OnDieSettled += HandleDieSettled;
// View → Controller
scoreCardView.OnCategorySelected += HandleCategorySelected;
dicePanelView.OnRollClicked += HandleRollClicked;
dicePanelView.OnDiceToggled += HandleDiceToggled;
gameInfoView.OnNewGameClicked += HandleNewGameClicked;
gameInfoView.OnShopClicked += HandleShopClicked;
gameInfoView.OnInventoryClicked += HandleInventoryClicked;
// Currency
if (currencyBank != null)
currencyBank.OnBalanceChanged += HandleCurrencyChanged;
InitializeModifierSystems();
}
private void OnDestroy()
{
gameManager.OnTurnStarted -= HandleTurnStarted;
gameManager.OnRollComplete -= HandleRollComplete;
gameManager.OnScored -= HandleScored;
gameManager.OnGameOver -= HandleGameOver;
diceManager.OnDieSettled -= HandleDieSettled;
scoreCardView.OnCategorySelected -= HandleCategorySelected;
dicePanelView.OnRollClicked -= HandleRollClicked;
dicePanelView.OnDiceToggled -= HandleDiceToggled;
gameInfoView.OnNewGameClicked -= HandleNewGameClicked;
gameInfoView.OnShopClicked -= HandleShopClicked;
gameInfoView.OnInventoryClicked -= HandleInventoryClicked;
if (currencyBank != null)
currencyBank.OnBalanceChanged -= HandleCurrencyChanged;
if (inventoryModel != null)
inventoryModel.OnInventoryChanged -= HandleInventoryChangedForSave;
}
// ── Modifier System Init ─────────────────────────────────
private void InitializeModifierSystems()
{
inventoryModel = new InventoryModel(maxActiveModifierSlots);
inventoryModel.OnInventoryChanged += HandleInventoryChangedForSave;
ShopCatalog catalog = shopController != null ? shopController.Catalog : null;
shopModel = new ShopModel(currencyBank, inventoryModel);
LoadSaveData(catalog);
if (inventoryController != null)
inventoryController.Initialize(inventoryModel);
if (shopController != null)
shopController.Initialize(shopModel);
if (currencyBank != null)
gameInfoView.SetCurrencyText(currencyBank.Balance);
}
private void LoadSaveData(ShopCatalog catalog)
{
SaveData save = SaveSystem.Load();
if (currencyBank != null && save.Currency > 0)
currencyBank.SetBalance(save.Currency);
if (catalog != null && save.OwnedModifiers.Count > 0)
{ {
var runtimeList = new List<ModifierRuntime>(); YachtCategory.Ones, YachtCategory.Twos, YachtCategory.Threes,
var permanentIds = new HashSet<string>(); YachtCategory.Fours, YachtCategory.Fives, YachtCategory.Sixes
for (int i = 0; i < save.OwnedModifiers.Count; i++)
{
var entry = save.OwnedModifiers[i];
ModifierData data = catalog.FindById(entry.ModifierId);
if (data == null)
{
Debug.LogWarning($"Modifier '{entry.ModifierId}' not found in catalog, skipping.");
continue;
}
var runtime = new ModifierRuntime
{
ModifierId = entry.ModifierId,
IsActive = entry.IsActive,
RemainingUses = entry.RemainingUses,
Data = data
};
runtimeList.Add(runtime);
if (data.Durability == ModifierDurability.Permanent)
permanentIds.Add(data.Id);
}
inventoryModel.LoadState(runtimeList);
shopModel.LoadPurchasedPermanentIds(permanentIds);
}
}
private void PerformSave()
{
var save = new SaveData
{
Currency = currencyBank != null ? currencyBank.Balance : 0
}; };
var owned = inventoryModel.GetAllForSave(); private const int UpperBonusThreshold = 63;
for (int i = 0; i < owned.Count; i++) private const int UpperBonusValue = 35;
private int totalCategoryCount;
private InventoryModel inventoryModel;
private ShopModel shopModel;
// ── Lifecycle ──────────────────────────────────────────────
private void Awake()
{ {
save.OwnedModifiers.Add(new ModifierSaveEntry totalCategoryCount = Enum.GetValues(typeof(YachtCategory)).Length;
{
ModifierId = owned[i].ModifierId, // Model → Controller
IsActive = owned[i].IsActive, gameManager.OnTurnStarted += HandleTurnStarted;
RemainingUses = owned[i].RemainingUses gameManager.OnRollComplete += HandleRollComplete;
}); gameManager.OnScored += HandleScored;
gameManager.OnGameOver += HandleGameOver;
diceManager.OnDieSettled += HandleDieSettled;
// View → Controller
scoreCardView.OnCategorySelected += HandleCategorySelected;
dicePanelView.OnRollClicked += HandleRollClicked;
dicePanelView.OnDiceToggled += HandleDiceToggled;
gameInfoView.OnNewGameClicked += HandleNewGameClicked;
gameInfoView.OnShopClicked += HandleShopClicked;
gameInfoView.OnInventoryClicked += HandleInventoryClicked;
// Currency
if (currencyBank != null)
currencyBank.OnBalanceChanged += HandleCurrencyChanged;
InitializeModifierSystems();
} }
SaveSystem.Save(save); private void OnDestroy()
}
// ── Model Event Handlers ──────────────────────────────────
private void HandleTurnStarted(int turn)
{
gameInfoView.SetTurnText(turn, totalCategoryCount);
dicePanelView.ResetForNewTurn();
dicePanelView.SetRollButtonState(true, 0, maxRollsPerTurn);
scoreCardView.ClearAllPreviews();
}
private void HandleRollComplete(int rollNumber)
{
bool canRollAgain = gameManager.CanRoll;
dicePanelView.SetRollButtonState(canRollAgain, rollNumber, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(true);
int[] values = diceManager.GetCurrentValues();
dicePanelView.SetAllDiceValues(values);
UpdatePreviewScores(values);
}
private void HandleDieSettled(int index, int value)
{
dicePanelView.SetDieValue(index, value);
}
private void HandleScored(YachtCategory category, int finalScore)
{
scoreCardView.SetCategoryScored(category, finalScore);
UpdateTotalDisplay();
PerformSave();
}
private void HandleGameOver(int totalScore)
{
dicePanelView.SetRollButtonState(false, maxRollsPerTurn, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(false);
scoreCardView.SetAllInteractable(false);
int displayTotal = CalculateDisplayTotal();
gameInfoView.ShowGameOver(displayTotal);
PerformSave();
}
// ── View Event Handlers ───────────────────────────────────
private void HandleRollClicked()
{
if (!gameManager.CanRoll) return;
dicePanelView.SetRollButtonState(false, gameManager.CurrentRoll, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(false);
scoreCardView.SetAllInteractable(false);
gameManager.Roll();
}
private void HandleDiceToggled(int index)
{
if (gameManager.CurrentRoll == 0) return;
if (diceManager.IsAnyRolling) return;
gameManager.ToggleDiceLock(index);
bool isLocked = diceManager.IsLocked(index);
dicePanelView.SetDieLocked(index, isLocked);
}
private void HandleCategorySelected(YachtCategory category)
{
if (!gameManager.CanScore) return;
if (scoringSystem.IsCategoryUsed(category)) return;
gameManager.ScoreInCategory(category);
}
private void HandleNewGameClicked()
{
gameInfoView.HideGameOver();
scoreCardView.ResetAll();
dicePanelView.ResetForNewGame();
gameManager.StartNewGame();
}
private void HandleShopClicked()
{
if (shopController != null)
{ {
var shopView = shopController.GetComponentInChildren<ShopView>(true); gameManager.OnTurnStarted -= HandleTurnStarted;
if (shopView != null) gameManager.OnRollComplete -= HandleRollComplete;
gameManager.OnScored -= HandleScored;
gameManager.OnGameOver -= HandleGameOver;
diceManager.OnDieSettled -= HandleDieSettled;
scoreCardView.OnCategorySelected -= HandleCategorySelected;
dicePanelView.OnRollClicked -= HandleRollClicked;
dicePanelView.OnDiceToggled -= HandleDiceToggled;
gameInfoView.OnNewGameClicked -= HandleNewGameClicked;
gameInfoView.OnShopClicked -= HandleShopClicked;
gameInfoView.OnInventoryClicked -= HandleInventoryClicked;
if (currencyBank != null)
currencyBank.OnBalanceChanged -= HandleCurrencyChanged;
if (inventoryModel != null)
inventoryModel.OnInventoryChanged -= HandleInventoryChangedForSave;
}
// ── Modifier System Init ─────────────────────────────────
private void InitializeModifierSystems()
{
inventoryModel = new InventoryModel(maxActiveModifierSlots);
inventoryModel.OnInventoryChanged += HandleInventoryChangedForSave;
ShopCatalog catalog = shopController != null ? shopController.Catalog : null;
shopModel = new ShopModel(currencyBank, inventoryModel);
LoadSaveData(catalog);
if (inventoryController != null)
inventoryController.Initialize(inventoryModel);
if (shopController != null)
shopController.Initialize(shopModel);
if (currencyBank != null)
gameInfoView.SetCurrencyText(currencyBank.Balance);
}
private void LoadSaveData(ShopCatalog catalog)
{
SaveData save = SaveSystem.Load();
if (currencyBank != null && save.Currency > 0)
currencyBank.SetBalance(save.Currency);
if (catalog != null && save.OwnedModifiers.Count > 0)
{ {
if (shopView.IsVisible) shopView.Hide(); var runtimeList = new List<ModifierRuntime>();
else shopView.Show(); var permanentIds = new HashSet<string>();
for (int i = 0; i < save.OwnedModifiers.Count; i++)
{
var entry = save.OwnedModifiers[i];
ModifierData data = catalog.FindById(entry.ModifierId);
if (data == null)
{
Debug.LogWarning($"Modifier '{entry.ModifierId}' not found in catalog, skipping.");
continue;
}
var runtime = new ModifierRuntime
{
ModifierId = entry.ModifierId,
IsActive = entry.IsActive,
RemainingUses = entry.RemainingUses,
Data = data
};
runtimeList.Add(runtime);
if (data.Durability == ModifierDurability.Permanent)
permanentIds.Add(data.Id);
}
inventoryModel.LoadState(runtimeList);
shopModel.LoadPurchasedPermanentIds(permanentIds);
} }
} }
}
private void HandleInventoryClicked() private void PerformSave()
{
if (inventoryController != null)
{ {
var inventoryView = inventoryController.GetComponentInChildren<InventoryView>(true); var save = new SaveData
if (inventoryView != null)
{ {
if (inventoryView.IsVisible) inventoryView.Hide(); Currency = currencyBank != null ? currencyBank.Balance : 0
else inventoryView.Show(); };
var owned = inventoryModel.GetAllForSave();
for (int i = 0; i < owned.Count; i++)
{
save.OwnedModifiers.Add(new ModifierSaveEntry
{
ModifierId = owned[i].ModifierId,
IsActive = owned[i].IsActive,
RemainingUses = owned[i].RemainingUses
});
}
SaveSystem.Save(save);
}
// ── Model Event Handlers ──────────────────────────────────
private void HandleTurnStarted(int turn)
{
gameInfoView.SetTurnText(turn, totalCategoryCount);
dicePanelView.ResetForNewTurn();
dicePanelView.SetRollButtonState(true, 0, maxRollsPerTurn);
scoreCardView.ClearAllPreviews();
}
private void HandleRollComplete(int rollNumber)
{
bool canRollAgain = gameManager.CanRoll;
dicePanelView.SetRollButtonState(canRollAgain, rollNumber, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(true);
int[] values = diceManager.GetCurrentValues();
dicePanelView.SetAllDiceValues(values);
UpdatePreviewScores(values);
}
private void HandleDieSettled(int index, int value)
{
dicePanelView.SetDieValue(index, value);
}
private void HandleScored(YachtCategory category, int finalScore)
{
scoreCardView.SetCategoryScored(category, finalScore);
UpdateTotalDisplay();
PerformSave();
}
private void HandleGameOver(int totalScore)
{
dicePanelView.SetRollButtonState(false, maxRollsPerTurn, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(false);
scoreCardView.SetAllInteractable(false);
int displayTotal = CalculateDisplayTotal();
gameInfoView.ShowGameOver(displayTotal);
PerformSave();
}
// ── View Event Handlers ───────────────────────────────────
private void HandleRollClicked()
{
if (!gameManager.CanRoll) return;
dicePanelView.SetRollButtonState(false, gameManager.CurrentRoll, maxRollsPerTurn);
dicePanelView.SetDiceInteractable(false);
scoreCardView.SetAllInteractable(false);
gameManager.Roll();
}
private void HandleDiceToggled(int index)
{
if (gameManager.CurrentRoll == 0) return;
if (diceManager.IsAnyRolling) return;
gameManager.ToggleDiceLock(index);
bool isLocked = diceManager.IsLocked(index);
dicePanelView.SetDieLocked(index, isLocked);
}
private void HandleCategorySelected(YachtCategory category)
{
if (!gameManager.CanScore) return;
if (scoringSystem.IsCategoryUsed(category)) return;
gameManager.ScoreInCategory(category);
}
private void HandleNewGameClicked()
{
gameInfoView.HideGameOver();
scoreCardView.ResetAll();
dicePanelView.ResetForNewGame();
gameManager.StartNewGame();
}
private void HandleShopClicked()
{
if (shopController != null)
{
var shopView = shopController.GetComponentInChildren<ShopView>(true);
if (shopView != null)
{
if (shopView.IsVisible) shopView.Hide();
else shopView.Show();
}
} }
} }
}
private void HandleCurrencyChanged(int newBalance) private void HandleInventoryClicked()
{
gameInfoView.SetCurrencyText(newBalance);
PerformSave();
}
private void HandleInventoryChangedForSave()
{
PerformSave();
}
// ── Helpers ────────────────────────────────────────────────
private void UpdatePreviewScores(int[] diceValues)
{
var previews = new Dictionary<YachtCategory, int>();
var categories = (YachtCategory[])Enum.GetValues(typeof(YachtCategory));
for (int i = 0; i < categories.Length; i++)
{ {
if (scoringSystem.IsCategoryUsed(categories[i])) continue; if (inventoryController != null)
{
ScoreResult result = scoringSystem.PreviewScore(diceValues, categories[i]); var inventoryView = inventoryController.GetComponentInChildren<InventoryView>(true);
previews[categories[i]] = result.FinalScore; if (inventoryView != null)
{
if (inventoryView.IsVisible) inventoryView.Hide();
else inventoryView.Show();
}
}
} }
scoreCardView.UpdatePreviews(previews); private void HandleCurrencyChanged(int newBalance)
}
private void UpdateTotalDisplay()
{
int upperSum = 0;
for (int i = 0; i < UpperCategories.Length; i++)
{ {
int catScore = scoringSystem.GetCategoryScore(UpperCategories[i]); gameInfoView.SetCurrencyText(newBalance);
if (catScore >= 0) upperSum += catScore; PerformSave();
} }
bool hasBonus = upperSum >= UpperBonusThreshold; private void HandleInventoryChangedForSave()
int displayTotal = CalculateDisplayTotal();
scoreCardView.UpdateTotalDisplay(displayTotal, upperSum, hasBonus);
}
private int CalculateDisplayTotal()
{
int total = scoringSystem.TotalScore;
int upperSum = 0;
for (int i = 0; i < UpperCategories.Length; i++)
{ {
int catScore = scoringSystem.GetCategoryScore(UpperCategories[i]); PerformSave();
if (catScore >= 0) upperSum += catScore;
} }
if (upperSum >= UpperBonusThreshold) // ── Helpers ────────────────────────────────────────────────
total += UpperBonusValue;
return total; private void UpdatePreviewScores(int[] diceValues)
{
var previews = new Dictionary<YachtCategory, int>();
var categories = (YachtCategory[])Enum.GetValues(typeof(YachtCategory));
for (int i = 0; i < categories.Length; i++)
{
if (scoringSystem.IsCategoryUsed(categories[i])) continue;
ScoreResult result = scoringSystem.PreviewScore(diceValues, categories[i]);
previews[categories[i]] = result.FinalScore;
}
scoreCardView.UpdatePreviews(previews);
}
private void UpdateTotalDisplay()
{
int upperSum = 0;
for (int i = 0; i < UpperCategories.Length; i++)
{
int catScore = scoringSystem.GetCategoryScore(UpperCategories[i]);
if (catScore >= 0) upperSum += catScore;
}
bool hasBonus = upperSum >= UpperBonusThreshold;
int displayTotal = CalculateDisplayTotal();
scoreCardView.UpdateTotalDisplay(displayTotal, upperSum, hasBonus);
}
private int CalculateDisplayTotal()
{
int total = scoringSystem.TotalScore;
int upperSum = 0;
for (int i = 0; i < UpperCategories.Length; i++)
{
int catScore = scoringSystem.GetCategoryScore(UpperCategories[i]);
if (catScore >= 0) upperSum += catScore;
}
if (upperSum >= UpperBonusThreshold)
total += UpperBonusValue;
return total;
}
} }
} }
}
+55 -56
View File
@@ -5,69 +5,68 @@ using TMPro;
namespace YachtDice.UI namespace YachtDice.UI
{ {
public class GameInfoView : MonoBehaviour
public sealed class GameInfoView : MonoBehaviour
{
[Header("Turn Info")]
[SerializeField] private TMP_Text turnText;
[Header("Currency")]
[SerializeField] private TMP_Text currencyText;
[Header("Navigation")]
[SerializeField] private Button shopButton;
[SerializeField] private Button inventoryButton;
[Header("Game Over Overlay")]
[SerializeField] private GameObject gameOverPanel;
[SerializeField] private TMP_Text finalScoreText;
[SerializeField] private Button newGameButton;
public event Action OnNewGameClicked;
public event Action OnShopClicked;
public event Action OnInventoryClicked;
private void Awake()
{ {
newGameButton.onClick.AddListener(() => OnNewGameClicked?.Invoke()); [Header("Turn Info")]
gameOverPanel.SetActive(false); [SerializeField] private TMP_Text turnText;
if (shopButton != null) [Header("Currency")]
shopButton.onClick.AddListener(() => OnShopClicked?.Invoke()); [SerializeField] private TMP_Text currencyText;
if (inventoryButton != null)
inventoryButton.onClick.AddListener(() => OnInventoryClicked?.Invoke());
}
public void SetTurnText(int turn, int maxTurns) [Header("Navigation")]
{ [SerializeField] private Button shopButton;
turnText.text = $"Ход {turn} / {maxTurns}"; [SerializeField] private Button inventoryButton;
}
public void SetCurrencyText(int amount) [Header("Game Over Overlay")]
{ [SerializeField] private GameObject gameOverPanel;
if (currencyText != null) [SerializeField] private TMP_Text finalScoreText;
currencyText.text = amount.ToString(); [SerializeField] private Button newGameButton;
}
public void ShowGameOver(int finalScore) public event Action OnNewGameClicked;
{ public event Action OnShopClicked;
gameOverPanel.SetActive(true); public event Action OnInventoryClicked;
finalScoreText.text = $"Итого: {finalScore}";
}
public void HideGameOver() private void Awake()
{ {
gameOverPanel.SetActive(false); newGameButton.onClick.AddListener(() => OnNewGameClicked?.Invoke());
} gameOverPanel.SetActive(false);
private void OnDestroy() if (shopButton != null)
{ shopButton.onClick.AddListener(() => OnShopClicked?.Invoke());
newGameButton.onClick.RemoveAllListeners(); if (inventoryButton != null)
inventoryButton.onClick.AddListener(() => OnInventoryClicked?.Invoke());
}
if (shopButton != null) public void SetTurnText(int turn, int maxTurns)
shopButton.onClick.RemoveAllListeners(); {
if (inventoryButton != null) turnText.text = $"Ход {turn} / {maxTurns}";
inventoryButton.onClick.RemoveAllListeners(); }
public void SetCurrencyText(int amount)
{
if (currencyText != null)
currencyText.text = amount.ToString();
}
public void ShowGameOver(int finalScore)
{
gameOverPanel.SetActive(true);
finalScoreText.text = $"Итого: {finalScore}";
}
public void HideGameOver()
{
gameOverPanel.SetActive(false);
}
private void OnDestroy()
{
newGameButton.onClick.RemoveAllListeners();
if (shopButton != null)
shopButton.onClick.RemoveAllListeners();
if (inventoryButton != null)
inventoryButton.onClick.RemoveAllListeners();
}
} }
} }
}
+89 -90
View File
@@ -6,109 +6,108 @@ using YachtDice.Scoring;
namespace YachtDice.UI namespace YachtDice.UI
{ {
public class ScoreCardView : MonoBehaviour
public sealed class ScoreCardView : MonoBehaviour
{
[Header("Category Rows (in YachtCategory enum order)")]
[SerializeField] private List<CategoryRowView> categoryRows = new();
[Header("Summary")]
[SerializeField] private TMP_Text upperSumText;
[SerializeField] private TMP_Text upperBonusText;
[SerializeField] private TMP_Text totalScoreText;
public event Action<YachtCategory> OnCategorySelected;
private static readonly string[] CategoryNames =
{ {
"Единицы", [Header("Category Rows (in YachtCategory enum order)")]
"Двойки", [SerializeField] private List<CategoryRowView> categoryRows = new();
"Тройки",
"Четвёрки",
"Пятёрки",
"Шестёрки",
"Тройка",
"Каре",
"Фулл-хаус",
"Малый стрит",
"Большой стрит",
"Яхта",
"Шанс"
};
private YachtCategory[] allCategories; [Header("Summary")]
[SerializeField] private TMP_Text upperSumText;
[SerializeField] private TMP_Text upperBonusText;
[SerializeField] private TMP_Text totalScoreText;
private void Awake() public event Action<YachtCategory> OnCategorySelected;
{
allCategories = (YachtCategory[])Enum.GetValues(typeof(YachtCategory));
for (int i = 0; i < categoryRows.Count && i < allCategories.Length; i++) private static readonly string[] CategoryNames =
{ {
categoryRows[i].Initialize(allCategories[i], CategoryNames[i]); "Единицы",
categoryRows[i].OnCategorySelected += HandleCategorySelected; "Двойки",
"Тройки",
"Четвёрки",
"Пятёрки",
"Шестёрки",
"Тройка",
"Каре",
"Фулл-хаус",
"Малый стрит",
"Большой стрит",
"Яхта",
"Шанс"
};
private YachtCategory[] allCategories;
private void Awake()
{
allCategories = (YachtCategory[])Enum.GetValues(typeof(YachtCategory));
for (int i = 0; i < categoryRows.Count && i < allCategories.Length; i++)
{
categoryRows[i].Initialize(allCategories[i], CategoryNames[i]);
categoryRows[i].OnCategorySelected += HandleCategorySelected;
}
UpdateTotalDisplay(0, 0, false);
} }
UpdateTotalDisplay(0, 0, false); public void UpdatePreviews(Dictionary<YachtCategory, int> previews)
}
public void UpdatePreviews(Dictionary<YachtCategory, int> previews)
{
for (int i = 0; i < categoryRows.Count && i < allCategories.Length; i++)
{ {
if (previews.TryGetValue(allCategories[i], out int preview)) for (int i = 0; i < categoryRows.Count && i < allCategories.Length; i++)
{ {
categoryRows[i].ShowPreview(preview); if (previews.TryGetValue(allCategories[i], out int preview))
categoryRows[i].SetInteractable(true); {
categoryRows[i].ShowPreview(preview);
categoryRows[i].SetInteractable(true);
}
} }
} }
}
public void ClearAllPreviews() public void ClearAllPreviews()
{
for (int i = 0; i < categoryRows.Count; i++)
{ {
categoryRows[i].HidePreview(); for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].SetInteractable(false); {
categoryRows[i].HidePreview();
categoryRows[i].SetInteractable(false);
}
}
public void SetCategoryScored(YachtCategory category, int score)
{
int index = (int)category;
if (index >= 0 && index < categoryRows.Count)
categoryRows[index].SetRecordedScore(score);
}
public void SetAllInteractable(bool interactable)
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].SetInteractable(interactable);
}
public void UpdateTotalDisplay(int totalScore, int upperSum, bool hasUpperBonus)
{
totalScoreText.text = totalScore.ToString();
upperSumText.text = $"{upperSum} / 63";
upperBonusText.text = hasUpperBonus ? "+35" : "---";
}
public void ResetAll()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].ResetRow();
UpdateTotalDisplay(0, 0, false);
}
private void HandleCategorySelected(YachtCategory category)
{
OnCategorySelected?.Invoke(category);
}
private void OnDestroy()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].OnCategorySelected -= HandleCategorySelected;
} }
} }
public void SetCategoryScored(YachtCategory category, int score)
{
int index = (int)category;
if (index >= 0 && index < categoryRows.Count)
categoryRows[index].SetRecordedScore(score);
}
public void SetAllInteractable(bool interactable)
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].SetInteractable(interactable);
}
public void UpdateTotalDisplay(int totalScore, int upperSum, bool hasUpperBonus)
{
totalScoreText.text = totalScore.ToString();
upperSumText.text = $"{upperSum} / 63";
upperBonusText.text = hasUpperBonus ? "+35" : "---";
}
public void ResetAll()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].ResetRow();
UpdateTotalDisplay(0, 0, false);
}
private void HandleCategorySelected(YachtCategory category)
{
OnCategorySelected?.Invoke(category);
}
private void OnDestroy()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].OnCategorySelected -= HandleCategorySelected;
}
}
} }