[Fix] Refactor project

This commit is contained in:
2026-03-02 12:49:12 +07:00
parent f65976796d
commit f52131f755
44 changed files with 449 additions and 404 deletions
@@ -18,17 +18,18 @@ namespace YachtDice.Categories
public CategoryDefinition FindById(string id)
{
for (int i = 0; i < categories.Count; i++)
foreach (var t in categories)
{
if (categories[i] != null && categories[i].Id == id)
return categories[i];
if (t != null && t.Id == id)
return t;
}
return null;
}
public int IndexOf(CategoryDefinition def)
{
for (int i = 0; i < categories.Count; i++)
for (var i = 0; i < categories.Count; i++)
{
if (categories[i] == def)
return i;
@@ -12,9 +12,11 @@ namespace YachtDice.Categories
{
public override int Calculate(IReadOnlyList<IDice> dice)
{
int sum = 0;
for (int i = 0; i < dice.Count; i++)
sum += dice[i].Value;
var sum = 0;
foreach (var t in dice)
sum += t.Value;
return sum;
}
@@ -17,9 +17,11 @@ namespace YachtDice.Categories
public override int Calculate(IReadOnlyList<IDice> dice)
{
int sum = 0;
for (int i = 0; i < dice.Count; i++)
if (dice[i].Value == TargetValue) sum += TargetValue;
var sum = 0;
foreach (var t in dice)
if (t.Value == TargetValue) sum += TargetValue;
return sum;
}
+51 -23
View File
@@ -10,68 +10,96 @@ namespace YachtDice.Categories
/// </summary>
public static class DiceCheckUtility
{
/// <summary>Извлекает массив значений из абстрактных дайсов.</summary>
/// <summary>
/// Извлекает массив значений из абстрактных дайсов.
/// </summary>
public static int[] ExtractValues(IReadOnlyList<IDice> dice)
{
int[] values = new int[dice.Count];
var values = new int[dice.Count];
for (int i = 0; i < dice.Count; i++)
values[i] = dice[i].Value;
return values;
}
/// <summary>Сумма дайсов, показывающих конкретное значение.</summary>
/// <summary>
/// Сумма дайсов, показывающих конкретное значение.
/// </summary>
public static int SumOfValue(int[] values, int target)
{
int sum = 0;
for (int i = 0; i < values.Length; i++)
if (values[i] == target) sum += target;
var sum = 0;
foreach (var t in values)
if (t == target) sum += target;
return sum;
}
/// <summary>Сумма всех дайсов.</summary>
/// <summary>
/// Сумма всех дайсов.
/// </summary>
public static int Sum(int[] values)
{
int sum = 0;
for (int i = 0; i < values.Length; i++) sum += values[i];
var sum = 0;
foreach (var t in values)
sum += t;
return sum;
}
/// <summary>Есть ли N или более одинаковых значений.</summary>
/// <summary>
/// Есть ли N или более одинаковых значений.
/// </summary>
public static bool NOfAKind(int[] values, int n)
{
int[] counts = new int[7];
for (int i = 0; i < values.Length; i++) counts[values[i]]++;
var counts = new int[7];
foreach (var t in values)
counts[t]++;
for (int v = 1; v <= 6; v++)
if (counts[v] >= n) return true;
return false;
}
/// <summary>Проверяет фулл-хаус (3 + 2 одинаковых).</summary>
/// <summary>
/// Проверяет фулл-хаус (3 + 2 одинаковых).
/// </summary>
public static bool IsFullHouse(int[] values)
{
int[] counts = new int[7];
for (int i = 0; i < values.Length; i++) counts[values[i]]++;
var counts = new int[7];
foreach (var v in values)
counts[v]++;
bool hasTwo = false, hasThree = false;
for (int v = 1; v <= 6; v++)
for (var i = 1; i <= 6; i++)
{
if (counts[v] == 2) hasTwo = true;
if (counts[v] == 3) hasThree = true;
if (counts[i] == 2) hasTwo = true;
if (counts[i] == 3) hasThree = true;
}
return hasTwo && hasThree;
}
/// <summary>Есть ли последовательность заданной длины.</summary>
/// <summary>
/// Есть ли последовательность заданной длины.
/// </summary>
public static bool HasStraightRun(int[] values, int runLength)
{
bool[] present = new bool[7];
for (int i = 0; i < values.Length; i++) present[values[i]] = true;
var present = new bool[7];
foreach (var t in values)
present[t] = true;
int consecutive = 0;
for (int v = 1; v <= 6; v++)
var consecutive = 0;
for (var v = 1; v <= 6; v++)
{
consecutive = present[v] ? consecutive + 1 : 0;
if (consecutive >= runLength) return true;
}
return false;
}
}
+17 -23
View File
@@ -23,22 +23,15 @@ namespace YachtDice.Dice
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]);
foreach (var t in entries)
_entrySet.Add(t);
}
public bool TryGetTopValue(out int value) => TryGetExtremeValue(isTop: true, out value);
@@ -65,8 +58,8 @@ namespace YachtDice.Dice
if (_entrySet == null || _entrySet.Count == 0)
return false;
bool found = false;
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
var found = false;
var bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
int best = default;
foreach (var e in _entrySet)
@@ -94,22 +87,23 @@ namespace YachtDice.Dice
if (_entrySet == null || _entrySet.Count == 0)
throw new InvalidOperationException("Dice: коллекция пуста.");
bool found = false;
float bestY = isTop ? float.NegativeInfinity : float.PositiveInfinity;
var found = false;
var 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;
}
var y = p.position.y;
if (found && (isTop ? !(y > bestY) : !(y < bestY))) continue;
found = true;
bestY = y;
best = e;
}
if (!found)
+4 -3
View File
@@ -12,11 +12,12 @@ namespace YachtDice.Dice
public DiceDefinition FindById(string id)
{
for (int i = 0; i < dice.Count; i++)
foreach (var t in dice)
{
if (dice[i] != null && dice[i].Id == id)
return dice[i];
if (t != null && t.Id == id)
return t;
}
return null;
}
+6 -2
View File
@@ -20,10 +20,14 @@ namespace YachtDice.Dice
public bool IsRepurchasable => false;
/// <summary>Количество граней.</summary>
/// <summary>
/// Количество граней.
/// </summary>
public abstract int FaceCount { get; }
/// <summary>Возвращает массив всех возможных значений граней.</summary>
/// <summary>
/// Возвращает массив всех возможных значений граней.
/// </summary>
public abstract int[] GetFaceValues();
#if UNITY_EDITOR
+3 -3
View File
@@ -103,8 +103,8 @@ namespace YachtDice.Dice
yield return new WaitForSeconds(0.2f);
// ── 4. Ждём пока кубик успокоится ───────────────────────────
float stillTimer = 0f;
float sqrThreshold = settleSpeed * settleSpeed;
var stillTimer = 0f;
var sqrThreshold = settleSpeed * settleSpeed;
while (stillTimer < settleDelay)
{
@@ -138,7 +138,7 @@ namespace YachtDice.Dice
// Откатываемся обратно — будем интерполировать
transform.rotation = startRot;
float elapsed = 0f;
var elapsed = 0f;
while (elapsed < snapDuration)
{
elapsed += Time.deltaTime;
+6 -2
View File
@@ -6,10 +6,14 @@ namespace YachtDice.Dice
/// </summary>
public interface IDice
{
/// <summary>Текущее значение верхней грани.</summary>
/// <summary>
/// Текущее значение верхней грани.
/// </summary>
int Value { get; }
/// <summary>Определение типа дайса (ScriptableObject).</summary>
/// <summary>
/// Определение типа дайса (ScriptableObject).
/// </summary>
DiceDefinition Definition { get; }
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ namespace YachtDice.Dice
public override int[] GetFaceValues()
{
int[] copy = new int[faceValues.Length];
var copy = new int[faceValues.Length];
System.Array.Copy(faceValues, copy, faceValues.Length);
return copy;
}
+10 -12
View File
@@ -7,41 +7,39 @@ namespace YachtDice.Economy
{
[SerializeField] private int startingBalance = 500;
private int _balance;
public int Balance => _balance;
public int Balance { get; private set; }
public event Action<int> OnBalanceChanged;
private void Awake()
{
_balance = startingBalance;
Balance = startingBalance;
}
public void Add(int amount)
{
if (amount <= 0) return;
_balance += amount;
OnBalanceChanged?.Invoke(_balance);
Balance += amount;
OnBalanceChanged?.Invoke(Balance);
}
public bool Spend(int amount)
{
if (amount <= 0) return false;
if (_balance < amount) return false;
if (Balance < amount) return false;
_balance -= amount;
OnBalanceChanged?.Invoke(_balance);
Balance -= amount;
OnBalanceChanged?.Invoke(Balance);
return true;
}
public bool CanAfford(int amount) => _balance >= amount;
public bool CanAfford(int amount) => Balance >= amount;
public void SetBalance(int value)
{
_balance = Mathf.Max(0, value);
OnBalanceChanged?.Invoke(_balance);
Balance = Mathf.Max(0, value);
OnBalanceChanged?.Invoke(Balance);
}
}
}
+18 -13
View File
@@ -19,7 +19,7 @@ namespace YachtDice.Game
private void Awake()
{
int count = diceRollers.Count;
var count = diceRollers.Count;
_diceInstances = new DiceInstance[count];
for (int i = 0; i < count; i++)
@@ -43,14 +43,14 @@ namespace YachtDice.Game
public void UnlockAll()
{
for (int i = 0; i < _diceInstances.Length; i++)
_diceInstances[i].IsLocked = false;
foreach (var t in _diceInstances)
t.IsLocked = false;
}
public void RollUnlocked()
{
for (int i = 0; i < diceRollers.Count; i++)
if (diceRollers[i].IsRolling) return;
foreach (var t in diceRollers)
if (t.IsRolling) return;
_pendingCount = 0;
@@ -59,7 +59,7 @@ namespace YachtDice.Game
if (_diceInstances[i].IsLocked) continue;
_pendingCount++;
int capturedIndex = i;
var capturedIndex = i;
void Handler(int value)
{
@@ -80,14 +80,18 @@ namespace YachtDice.Game
OnAllDiceSettled?.Invoke();
}
/// <summary>Возвращает абстрактный список дайсов (основной API).</summary>
/// <summary>
/// Возвращает абстрактный список дайсов (основной API).
/// </summary>
public IReadOnlyList<IDice> GetDice() => _diceInstances;
/// <summary>Возвращает копию текущих значений (обратная совместимость).</summary>
/// <summary>
/// Возвращает копию текущих значений (обратная совместимость).
/// </summary>
public int[] GetCurrentValues()
{
int[] values = new int[_diceInstances.Length];
for (int i = 0; i < _diceInstances.Length; i++)
var values = new int[_diceInstances.Length];
for (var i = 0; i < _diceInstances.Length; i++)
values[i] = _diceInstances[i].Value;
return values;
}
@@ -98,15 +102,16 @@ namespace YachtDice.Game
{
get
{
for (int i = 0; i < diceRollers.Count; i++)
if (diceRollers[i].IsRolling) return true;
foreach (var t in diceRollers)
if (t.IsRolling) return true;
return false;
}
}
public void ReadAllValues()
{
for (int i = 0; i < diceRollers.Count; i++)
for (var i = 0; i < diceRollers.Count; i++)
{
var diceComponent = diceRollers[i].GetComponent<Dice.Dice>();
if (diceComponent != null && diceComponent.TryGetTopValue(out int val))
+3 -3
View File
@@ -62,7 +62,7 @@ namespace YachtDice.Game
{
_diceManager.OnAllDiceSettled -= HandleAllDiceSettled;
int[] values = _diceManager.GetCurrentValues();
var values = _diceManager.GetCurrentValues();
Debug.Log($"Roll {CurrentRoll}/{maxRollsPerTurn} | Dice: [{string.Join(", ", values)}]");
OnRollComplete?.Invoke(CurrentRoll);
@@ -74,7 +74,7 @@ namespace YachtDice.Game
if (CurrentRoll == 0) return;
_diceManager.ToggleLock(index);
bool isLocked = _diceManager.IsLocked(index);
var isLocked = _diceManager.IsLocked(index);
Debug.Log($"Dice {index + 1} (value={_diceManager.GetValue(index)}): {(isLocked ? "LOCKED" : "UNLOCKED")}");
}
@@ -94,7 +94,7 @@ namespace YachtDice.Game
if (_scoringSystem.IsComplete)
{
int total = _scoringSystem.TotalScore;
var total = _scoringSystem.TotalScore;
Debug.Log($"*** GAME OVER *** Total Score: {total}");
OnGameOver?.Invoke(total);
}
@@ -77,7 +77,7 @@ namespace YachtDice.Inventory
{
if (instance.Definition == null) return;
int sellPrice = instance.Definition.SellPrice;
var sellPrice = instance.Definition.SellPrice;
_model.RemoveModifier(instance);
if (_currencyBank != null)
+3 -2
View File
@@ -40,8 +40,9 @@ namespace YachtDice.Inventory
{
var result = new List<ModifierDefinition>();
var active = _registry.Active;
for (int i = 0; i < active.Count; i++)
result.Add(active[i].Definition);
foreach (var t in active)
result.Add(t.Definition);
return result;
}
}
@@ -64,7 +64,7 @@ namespace YachtDice.Inventory
if (sellPriceText != null) sellPriceText.text = def.SellPrice.ToString();
bool isActive = _instance.IsActive;
var isActive = _instance.IsActive;
if (activateButton != null)
{
+8 -8
View File
@@ -40,11 +40,10 @@ namespace YachtDice.Inventory
{
ClearSlots();
int activeCount = 0;
var activeCount = 0;
for (int i = 0; i < owned.Count; i++)
foreach (var inst in owned)
{
var inst = owned[i];
if (inst.IsActive) activeCount++;
var slot = Instantiate(slotPrefab, slotContainer);
@@ -61,13 +60,14 @@ namespace YachtDice.Inventory
private void ClearSlots()
{
for (int i = 0; i < _spawnedSlots.Count; i++)
foreach (var t in _spawnedSlots)
{
_spawnedSlots[i].OnActivateClicked -= HandleActivate;
_spawnedSlots[i].OnDeactivateClicked -= HandleDeactivate;
_spawnedSlots[i].OnSellClicked -= HandleSell;
Destroy(_spawnedSlots[i].gameObject);
t.OnActivateClicked -= HandleActivate;
t.OnDeactivateClicked -= HandleDeactivate;
t.OnSellClicked -= HandleSell;
Destroy(t.gameObject);
}
_spawnedSlots.Clear();
}
@@ -18,10 +18,10 @@ namespace YachtDice.Modifiers.Conditions
{
if (context.DiceValues == null) return false;
int count = 0;
for (int i = 0; i < context.DiceValues.Length; i++)
var count = 0;
foreach (var t in context.DiceValues)
{
if (targetValue == 0 || context.DiceValues[i] == targetValue)
if (targetValue == 0 || t == targetValue)
count++;
}
return count >= minCount;
@@ -15,10 +15,10 @@ namespace YachtDice.Modifiers.Conditions
{
if (context.DiceValues == null) return false;
int count = 0;
for (int i = 0; i < context.DiceValues.Length; i++)
var count = 0;
foreach (var t in context.DiceValues)
{
if (context.DiceValues[i] == targetValue)
if (t == targetValue)
count++;
}
return count >= minCount;
@@ -15,13 +15,19 @@ namespace YachtDice.Modifiers.Core
public float Multiplier = 1f;
public float PostMultiplier = 1f;
/// <summary>Абстрактные дайсы (основной API).</summary>
/// <summary>
/// Абстрактные дайсы (основной API).
/// </summary>
public IReadOnlyList<IDice> Dice;
/// <summary>Значения дайсов (обратная совместимость с существующими модификаторами).</summary>
/// <summary>
/// Значения дайсов (обратная совместимость с существующими модификаторами).
/// </summary>
public int[] DiceValues;
/// <summary>Категория, в которую записывается результат.</summary>
/// <summary>
/// Категория, в которую записывается результат.
/// </summary>
public CategoryDefinition Category;
// Game state (read-only snapshot)
@@ -2,9 +2,9 @@ namespace YachtDice.Modifiers.Core
{
public enum ModifierRarity
{
Common,
Uncommon,
Rare,
Epic,
Common = 1,
Uncommon = 2,
Rare = 3,
Epic = 4,
}
}
@@ -17,11 +17,12 @@ namespace YachtDice.Modifiers.Definition
public bool EvaluateConditions(ModifierContext context, ModifierInstance instance)
{
for (int i = 0; i < conditions.Count; i++)
foreach (var t in conditions)
{
if (conditions[i] != null && !conditions[i].Evaluate(context, instance))
if (t != null && !t.Evaluate(context, instance))
return false;
}
return true;
}
@@ -12,11 +12,12 @@ namespace YachtDice.Modifiers.Definition
public ModifierDefinition FindById(string id)
{
for (int i = 0; i < modifiers.Count; i++)
foreach (var t in modifiers)
{
if (modifiers[i] != null && modifiers[i].Id == id)
return modifiers[i];
if (t != null && t.Id == id)
return t;
}
return null;
}
}
@@ -19,13 +19,13 @@ namespace YachtDice.Modifiers.Editor
return;
}
int errorCount = 0;
int warnCount = 0;
var errorCount = 0;
var warnCount = 0;
var usedIds = new Dictionary<string, string>(); // id -> asset path
for (int i = 0; i < guids.Length; i++)
foreach (var t in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
var path = AssetDatabase.GUIDToAssetPath(t);
var def = AssetDatabase.LoadAssetAtPath<ModifierDefinition>(path);
if (def == null)
@@ -19,10 +19,10 @@ namespace YachtDice.Modifiers.Effects
{
if (context.DiceValues == null) return UniTask.CompletedTask;
int count = 0;
for (int i = 0; i < context.DiceValues.Length; i++)
var count = 0;
foreach (var t in context.DiceValues)
{
if (targetDiceValue == 0 || context.DiceValues[i] == targetDiceValue)
if (targetDiceValue == 0 || t == targetDiceValue)
count++;
}
@@ -19,9 +19,9 @@ namespace YachtDice.Modifiers.Effects
{
if (context.DiceValues == null) return UniTask.CompletedTask;
for (int i = 0; i < context.DiceValues.Length; i++)
foreach (var t in context.DiceValues)
{
if (targetDiceValue == 0 || context.DiceValues[i] == targetDiceValue)
if (targetDiceValue == 0 || t == targetDiceValue)
context.Multiplier *= multiplierPerDice;
}
@@ -17,7 +17,7 @@ namespace YachtDice.Modifiers.Pipeline
public int Compare(EffectEntry a, EffectEntry b)
{
int cmp = a.Effect.Phase.CompareTo(b.Effect.Phase);
var cmp = a.Effect.Phase.CompareTo(b.Effect.Phase);
if (cmp != 0) return cmp;
cmp = a.Effect.Priority.CompareTo(b.Effect.Priority);
@@ -56,14 +56,12 @@ namespace YachtDice.Modifiers.Pipeline
var activeSnapshot = _registry.Active;
// Gather eligible effects
for (int i = 0; i < activeSnapshot.Count; i++)
foreach (var inst in activeSnapshot)
{
var inst = activeSnapshot[i];
var behaviors = inst.Definition.Behaviors;
for (int b = 0; b < behaviors.Count; b++)
foreach (var behavior in behaviors)
{
var behavior = behaviors[b];
if (behavior == null) continue;
if (behavior.Trigger != trigger) continue;
@@ -45,9 +45,8 @@ namespace YachtDice.Modifiers.Pipeline
{
var sb = new StringBuilder();
sb.AppendLine($"[ModifierPipeline] Trigger: {Trigger}");
for (int i = 0; i < Entries.Count; i++)
foreach (var e in Entries)
{
var e = Entries[i];
if (e.EffectApplied != null)
{
sb.AppendLine($" EFFECT [{e.Phase}] {e.ModifierId} -> {e.EffectApplied}");
@@ -38,8 +38,9 @@ namespace YachtDice.Modifiers.Runtime
get
{
int count = 0;
for (int i = 0; i < _instances.Count; i++)
if (_instances[i].IsActive) count++;
foreach (var t in _instances)
if (t.IsActive) count++;
return count;
}
}
@@ -62,7 +63,7 @@ namespace YachtDice.Modifiers.Runtime
{
if (!_instances.Contains(instance)) return;
bool wasActive = instance.IsActive;
var wasActive = instance.IsActive;
instance.IsActive = false;
_instances.Remove(instance);
_activeCacheDirty = true;
@@ -98,9 +99,9 @@ namespace YachtDice.Modifiers.Runtime
public void ConsumeChargesOnActive()
{
bool changed = false;
var changed = false;
for (int i = _instances.Count - 1; i >= 0; i--)
for (var i = _instances.Count - 1; i >= 0; i--)
{
var inst = _instances[i];
if (!inst.IsActive) continue;
@@ -115,20 +116,18 @@ namespace YachtDice.Modifiers.Runtime
}
}
if (changed)
{
_activeCacheDirty = true;
OnActiveModifiersChanged?.Invoke(Active);
OnChanged?.Invoke();
}
if (!changed) return;
_activeCacheDirty = true;
OnActiveModifiersChanged?.Invoke(Active);
OnChanged?.Invoke();
}
public List<ModifierSaveEntry> GetSaveData()
{
var entries = new List<ModifierSaveEntry>();
for (int i = 0; i < _instances.Count; i++)
foreach (var inst in _instances)
{
var inst = _instances[i];
var entry = new ModifierSaveEntry
{
modifierId = inst.Definition.Id,
@@ -158,9 +157,8 @@ namespace YachtDice.Modifiers.Runtime
if (entries == null) return;
for (int i = 0; i < entries.Count; i++)
foreach (var entry in entries)
{
var entry = entries[i];
var definition = catalog.FindById(entry.modifierId);
if (definition == null)
+8 -6
View File
@@ -29,19 +29,21 @@ namespace YachtDice.Player
public bool OwnsById(string id)
{
for (int i = 0; i < _ownedDice.Count; i++)
foreach (var t in _ownedDice)
{
if (_ownedDice[i] != null && _ownedDice[i].Id == id)
if (t != null && t.Id == id)
return true;
}
return false;
}
public List<string> GetSaveData()
{
var ids = new List<string>();
for (int i = 0; i < _ownedDice.Count; i++)
ids.Add(_ownedDice[i].Id);
foreach (var t in _ownedDice)
ids.Add(t.Id);
return ids;
}
@@ -55,9 +57,9 @@ namespace YachtDice.Player
return;
}
for (int i = 0; i < diceIds.Count; i++)
foreach (var t in diceIds)
{
var def = catalog.FindById(diceIds[i]);
var def = catalog.FindById(t);
if (def != null)
_ownedDice.Add(def);
}
+3 -2
View File
@@ -123,7 +123,7 @@ namespace YachtDice.Scoring
if (_usedCategories.Contains(category))
throw new InvalidOperationException($"Category {category.DisplayName} has already been scored.");
int baseScore = category.Calculate(dice);
var baseScore = category.Calculate(dice);
ModifierContext context = null;
if (_eventBus != null && _modifierRegistry != null)
@@ -137,12 +137,13 @@ namespace YachtDice.Scoring
}
ScoreResult result;
if (context != null)
result = context.ToScoreResult();
else
result = ScoreResult.Create(baseScore, dice, category);
int finalScore = result.FinalScore;
var finalScore = result.FinalScore;
_scorecard[category] = finalScore;
_usedCategories.Add(category);
+4 -4
View File
@@ -3,8 +3,8 @@ using UnityEngine;
namespace YachtDice.Shop
{
/// <summary>
/// Any item that can appear in the shop.
/// Implemented by ScriptableObject definitions (ModifierDefinition, DiceDefinitionSO).
/// Любой предмет, который может появиться в магазине.
/// Реализовано с помощью определений ScriptableObject (ModifierDefinition, DiceDefinitionSO).
/// </summary>
public interface IShopItem
{
@@ -15,8 +15,8 @@ namespace YachtDice.Shop
int ShopPrice { get; }
/// <summary>
/// Whether this item can be repurchased after being owned (e.g. consumable modifiers).
/// If false, the shop marks it as "Owned" once purchased.
/// Можно ли повторно приобрести этот предмет после того, как он уже был в собственности (например, расходуемые модификаторы).
/// Если значение равно false, магазин помечает его как «В собственности» после покупки.
/// </summary>
bool IsRepurchasable { get; }
}
+2 -2
View File
@@ -33,9 +33,9 @@ namespace YachtDice.Shop
private void RebuildCache()
{
_cachedItems = new List<IShopItem>();
for (int i = 0; i < items.Count; i++)
foreach (var t in items)
{
if (items[i] is IShopItem shopItem)
if (t is IShopItem shopItem)
_cachedItems.Add(shopItem);
}
}
+1 -2
View File
@@ -38,9 +38,8 @@ namespace YachtDice.Shop
{
ClearItems();
for (int i = 0; i < catalog.Count; i++)
foreach (var def in catalog)
{
var def = catalog[i];
if (def == null) continue;
var item = Instantiate(itemPrefab, itemContainer);
@@ -7,12 +7,12 @@ namespace YachtDice.Tests
{
public sealed class DiceCollectionTests
{
private DiceCollection collection;
private DiceCollection _collection;
[SetUp]
public void SetUp()
{
collection = new DiceCollection();
_collection = new DiceCollection();
}
[Test]
@@ -20,9 +20,9 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
_collection.Add(die);
Assert.AreEqual(1, collection.OwnedDice.Count);
Assert.AreEqual(1, _collection.OwnedDice.Count);
}
[Test]
@@ -30,18 +30,18 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
collection.Add(die);
_collection.Add(die);
_collection.Add(die);
Assert.AreEqual(1, collection.OwnedDice.Count);
Assert.AreEqual(1, _collection.OwnedDice.Count);
}
[Test]
public void Add_Null_Ignored()
{
collection.Add(null);
_collection.Add(null);
Assert.AreEqual(0, collection.OwnedDice.Count);
Assert.AreEqual(0, _collection.OwnedDice.Count);
}
[Test]
@@ -49,15 +49,15 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
_collection.Add(die);
Assert.IsTrue(collection.OwnsById("standard_d6"));
Assert.IsTrue(_collection.OwnsById("standard_d6"));
}
[Test]
public void OwnsById_ReturnsFalseWhenNotOwned()
{
Assert.IsFalse(collection.OwnsById("standard_d6"));
Assert.IsFalse(_collection.OwnsById("standard_d6"));
}
[Test]
@@ -65,10 +65,10 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
collection.Remove(die);
_collection.Add(die);
_collection.Remove(die);
Assert.AreEqual(0, collection.OwnedDice.Count);
Assert.AreEqual(0, _collection.OwnedDice.Count);
}
[Test]
@@ -76,9 +76,9 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
_collection.Add(die);
var ids = collection.GetSaveData();
var ids = _collection.GetSaveData();
Assert.AreEqual(1, ids.Count);
Assert.AreEqual("standard_d6", ids[0]);
}
@@ -90,10 +90,10 @@ namespace YachtDice.Tests
var catalog = DiceCatalog.CreateForTest(new List<DiceDefinition> { die });
var ids = new List<string> { "standard_d6" };
collection.LoadSaveData(ids, catalog);
_collection.LoadSaveData(ids, catalog);
Assert.AreEqual(1, collection.OwnedDice.Count);
Assert.AreEqual("standard_d6", collection.OwnedDice[0].Id);
Assert.AreEqual(1, _collection.OwnedDice.Count);
Assert.AreEqual("standard_d6", _collection.OwnedDice[0].Id);
}
[Test]
@@ -102,9 +102,9 @@ namespace YachtDice.Tests
var catalog = DiceCatalog.CreateForTest(new List<DiceDefinition>());
var ids = new List<string> { "nonexistent" };
collection.LoadSaveData(ids, catalog);
_collection.LoadSaveData(ids, catalog);
Assert.AreEqual(0, collection.OwnedDice.Count);
Assert.AreEqual(0, _collection.OwnedDice.Count);
}
[Test]
@@ -112,20 +112,20 @@ namespace YachtDice.Tests
{
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
collection.Clear();
_collection.Add(die);
_collection.Clear();
Assert.AreEqual(0, collection.OwnedDice.Count);
Assert.AreEqual(0, _collection.OwnedDice.Count);
}
[Test]
public void Add_FiresOnChanged()
{
bool fired = false;
collection.OnChanged += () => fired = true;
_collection.OnChanged += () => fired = true;
var die = StandardDice.CreateStandardD6ForTest();
collection.Add(die);
_collection.Add(die);
Assert.IsTrue(fired);
}
@@ -1,5 +1,4 @@
using NUnit.Framework;
using UnityEngine;
using YachtDice.Inventory;
using YachtDice.Modifiers.Definition;
using YachtDice.Modifiers.Runtime;
@@ -8,14 +7,14 @@ namespace YachtDice.Tests
{
public class InventoryModelTests
{
private ModifierRegistry registry;
private InventoryModel inventory;
private ModifierRegistry _registry;
private InventoryModel _inventory;
[SetUp]
public void SetUp()
{
registry = new ModifierRegistry(3);
inventory = new InventoryModel(registry);
_registry = new ModifierRegistry(3);
_inventory = new InventoryModel(_registry);
}
private ModifierDefinition CreateTestDef(string id = "test",
@@ -28,22 +27,22 @@ namespace YachtDice.Tests
[Test]
public void AddModifier_IncreasesCount()
{
inventory.AddModifier(CreateTestDef());
_inventory.AddModifier(CreateTestDef());
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
Assert.AreEqual(1, _inventory.OwnedModifiers.Count);
}
[Test]
public void TryActivate_SucceedsWithinSlotLimit()
{
inventory.AddModifier(CreateTestDef("a"));
var mod = inventory.OwnedModifiers[0];
_inventory.AddModifier(CreateTestDef("a"));
var mod = _inventory.OwnedModifiers[0];
bool result = inventory.TryActivate(mod);
bool result = _inventory.TryActivate(mod);
Assert.IsTrue(result);
Assert.IsTrue(mod.IsActive);
Assert.AreEqual(1, inventory.ActiveCount);
Assert.AreEqual(1, _inventory.ActiveCount);
}
[Test]
@@ -51,53 +50,53 @@ namespace YachtDice.Tests
{
for (int i = 0; i < 3; i++)
{
inventory.AddModifier(CreateTestDef($"m{i}"));
inventory.TryActivate(inventory.OwnedModifiers[i]);
_inventory.AddModifier(CreateTestDef($"m{i}"));
_inventory.TryActivate(_inventory.OwnedModifiers[i]);
}
inventory.AddModifier(CreateTestDef("extra"));
var extra = inventory.OwnedModifiers[3];
bool result = inventory.TryActivate(extra);
_inventory.AddModifier(CreateTestDef("extra"));
var extra = _inventory.OwnedModifiers[3];
bool result = _inventory.TryActivate(extra);
Assert.IsFalse(result);
Assert.IsFalse(extra.IsActive);
Assert.AreEqual(3, inventory.ActiveCount);
Assert.AreEqual(3, _inventory.ActiveCount);
}
[Test]
public void Deactivate_FreesSlot()
{
inventory.AddModifier(CreateTestDef());
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
_inventory.AddModifier(CreateTestDef());
var mod = _inventory.OwnedModifiers[0];
_inventory.TryActivate(mod);
inventory.Deactivate(mod);
_inventory.Deactivate(mod);
Assert.IsFalse(mod.IsActive);
Assert.AreEqual(0, inventory.ActiveCount);
Assert.AreEqual(0, _inventory.ActiveCount);
}
[Test]
public void RemoveModifier_DeactivatesAndRemoves()
{
inventory.AddModifier(CreateTestDef());
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
_inventory.AddModifier(CreateTestDef());
var mod = _inventory.OwnedModifiers[0];
_inventory.TryActivate(mod);
inventory.RemoveModifier(mod);
_inventory.RemoveModifier(mod);
Assert.AreEqual(0, inventory.OwnedModifiers.Count);
Assert.AreEqual(0, inventory.ActiveCount);
Assert.AreEqual(0, _inventory.OwnedModifiers.Count);
Assert.AreEqual(0, _inventory.ActiveCount);
}
[Test]
public void ConsumeUseOnActive_DecrementsUses()
{
inventory.AddModifier(CreateTestDef("ltd", hasLimitedUses: true, maxUses: 3));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
_inventory.AddModifier(CreateTestDef("ltd", hasLimitedUses: true, maxUses: 3));
var mod = _inventory.OwnedModifiers[0];
_inventory.TryActivate(mod);
inventory.ConsumeUseOnActive();
_inventory.ConsumeUseOnActive();
Assert.AreEqual(2, mod.RemainingUses);
}
@@ -105,36 +104,36 @@ namespace YachtDice.Tests
[Test]
public void ConsumeUseOnActive_RemovesExpired()
{
inventory.AddModifier(CreateTestDef("ltd", hasLimitedUses: true, maxUses: 1));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
_inventory.AddModifier(CreateTestDef("ltd", hasLimitedUses: true, maxUses: 1));
var mod = _inventory.OwnedModifiers[0];
_inventory.TryActivate(mod);
inventory.ConsumeUseOnActive();
_inventory.ConsumeUseOnActive();
Assert.AreEqual(0, inventory.OwnedModifiers.Count);
Assert.AreEqual(0, _inventory.OwnedModifiers.Count);
}
[Test]
public void ConsumeUseOnActive_IgnoresPermanent()
{
inventory.AddModifier(CreateTestDef("perm"));
var mod = inventory.OwnedModifiers[0];
inventory.TryActivate(mod);
_inventory.AddModifier(CreateTestDef("perm"));
var mod = _inventory.OwnedModifiers[0];
_inventory.TryActivate(mod);
inventory.ConsumeUseOnActive();
_inventory.ConsumeUseOnActive();
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
Assert.AreEqual(1, _inventory.OwnedModifiers.Count);
Assert.IsTrue(mod.IsActive);
}
[Test]
public void GetActiveModifierDefinitions_ReturnsOnlyActive()
{
inventory.AddModifier(CreateTestDef("a"));
inventory.AddModifier(CreateTestDef("b"));
inventory.TryActivate(inventory.OwnedModifiers[0]);
_inventory.AddModifier(CreateTestDef("a"));
_inventory.AddModifier(CreateTestDef("b"));
_inventory.TryActivate(_inventory.OwnedModifiers[0]);
var active = inventory.GetActiveModifierDefinitions();
var active = _inventory.GetActiveModifierDefinitions();
Assert.AreEqual(1, active.Count);
}
@@ -142,19 +141,19 @@ namespace YachtDice.Tests
[Test]
public void SetMaxActiveSlots_AllowsExpansion()
{
inventory.SetMaxActiveSlots(10);
_inventory.SetMaxActiveSlots(10);
Assert.AreEqual(10, inventory.MaxActiveSlots);
Assert.AreEqual(10, _inventory.MaxActiveSlots);
}
[Test]
public void OnActiveModifiersChanged_FiredOnActivate()
{
bool fired = false;
inventory.OnActiveModifiersChanged += _ => fired = true;
inventory.AddModifier(CreateTestDef());
_inventory.OnActiveModifiersChanged += _ => fired = true;
_inventory.AddModifier(CreateTestDef());
inventory.TryActivate(inventory.OwnedModifiers[0]);
_inventory.TryActivate(_inventory.OwnedModifiers[0]);
Assert.IsTrue(fired);
}
@@ -5,24 +5,23 @@ using YachtDice.Modifiers.Core;
using YachtDice.Modifiers.Definition;
using YachtDice.Modifiers.Effects;
using YachtDice.Modifiers.Runtime;
using YachtDice.Scoring;
namespace YachtDice.Tests
{
public class ModifierEffectTests
{
private CategoryDefinition testCategory;
private CategoryDefinition _testCategory;
[SetUp]
public void SetUp()
{
testCategory = SumAllCategory.CreateForTest("chance", "Шанс");
_testCategory = SumAllCategory.CreateForTest("chance", "Шанс");
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(testCategory);
Object.DestroyImmediate(_testCategory);
}
private ModifierInstance CreateInstance(string id = "test")
@@ -37,7 +36,7 @@ namespace YachtDice.Tests
{
BaseScore = baseScore,
DiceValues = dice,
Category = testCategory,
Category = _testCategory,
};
}
@@ -14,41 +14,41 @@ namespace YachtDice.Tests
{
public class ModifierPipelineTests
{
private ModifierRegistry registry;
private ModifierPipeline pipeline;
private ModifierRegistry _registry;
private ModifierPipeline _pipeline;
// Тестовые категории
private CategoryDefinition chanceCategory;
private CategoryDefinition fullHouseCategory;
private CategoryDefinition onesCategory;
private CategoryDefinition threesCategory;
private CategoryDefinition foursCategory;
private CategoryDefinition sixesCategory;
private CategoryDefinition _chanceCategory;
private CategoryDefinition _fullHouseCategory;
private CategoryDefinition _onesCategory;
private CategoryDefinition _threesCategory;
private CategoryDefinition _foursCategory;
private CategoryDefinition _sixesCategory;
[SetUp]
public void SetUp()
{
registry = new ModifierRegistry(10);
pipeline = new ModifierPipeline(registry);
pipeline.TracingEnabled = false;
_registry = new ModifierRegistry(10);
_pipeline = new ModifierPipeline(_registry);
_pipeline.TracingEnabled = false;
chanceCategory = SumAllCategory.CreateForTest("chance", "Шанс");
fullHouseCategory = FullHouseCategory.CreateForTest("full_house", "Фулл-хаус");
onesCategory = SumOfValueCategory.CreateForTest("ones", "Единицы", 1);
threesCategory = SumOfValueCategory.CreateForTest("threes", "Тройки", 3);
foursCategory = SumOfValueCategory.CreateForTest("fours", "Четвёрки", 4);
sixesCategory = SumOfValueCategory.CreateForTest("sixes", "Шестёрки", 6);
_chanceCategory = SumAllCategory.CreateForTest("chance", "Шанс");
_fullHouseCategory = FullHouseCategory.CreateForTest("full_house", "Фулл-хаус");
_onesCategory = SumOfValueCategory.CreateForTest("ones", "Единицы", 1);
_threesCategory = SumOfValueCategory.CreateForTest("threes", "Тройки", 3);
_foursCategory = SumOfValueCategory.CreateForTest("fours", "Четвёрки", 4);
_sixesCategory = SumOfValueCategory.CreateForTest("sixes", "Шестёрки", 6);
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(chanceCategory);
Object.DestroyImmediate(fullHouseCategory);
Object.DestroyImmediate(onesCategory);
Object.DestroyImmediate(threesCategory);
Object.DestroyImmediate(foursCategory);
Object.DestroyImmediate(sixesCategory);
Object.DestroyImmediate(_chanceCategory);
Object.DestroyImmediate(_fullHouseCategory);
Object.DestroyImmediate(_onesCategory);
Object.DestroyImmediate(_threesCategory);
Object.DestroyImmediate(_foursCategory);
Object.DestroyImmediate(_sixesCategory);
}
private ModifierDefinition CreateDef(string id,
@@ -63,8 +63,8 @@ namespace YachtDice.Tests
private void RegisterAndActivate(ModifierDefinition def)
{
var inst = registry.Add(def);
registry.TryActivate(inst);
var inst = _registry.Add(def);
_registry.TryActivate(inst);
}
private ModifierContext CreateScoringContext(int baseScore, int[] dice, CategoryDefinition category)
@@ -74,7 +74,7 @@ namespace YachtDice.Tests
BaseScore = baseScore,
DiceValues = dice,
Category = category,
AllActiveModifiers = registry.Active,
AllActiveModifiers = _registry.Active,
};
}
@@ -94,8 +94,8 @@ namespace YachtDice.Tests
RegisterAndActivate(mulDef);
RegisterAndActivate(addDef);
var ctx = CreateScoringContext(20, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(20, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
// (20 + 10) * 2 = 60
Assert.AreEqual(60, result.FinalScore);
@@ -115,8 +115,8 @@ namespace YachtDice.Tests
RegisterAndActivate(postDef);
RegisterAndActivate(mulDef);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
// (10 + 0) * 2 * 3 = 60
Assert.AreEqual(60, result.FinalScore);
@@ -127,7 +127,7 @@ namespace YachtDice.Tests
[Test]
public void Execute_ConditionFails_SkipsEffect()
{
var condition = CategoryCondition.CreateForTest(fullHouseCategory);
var condition = CategoryCondition.CreateForTest(_fullHouseCategory);
var effect = AddFlatScoreEffect.CreateForTest(100);
var def = CreateDef("fh-bonus", TriggerType.OnCategoryScored,
@@ -137,8 +137,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
// Scoring Ones, not FullHouse — condition should fail
var ctx = CreateScoringContext(5, new[] { 1, 1, 1, 1, 1 }, onesCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(5, new[] { 1, 1, 1, 1, 1 }, _onesCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(0, result.FlatBonus);
Assert.AreEqual(5, result.FinalScore);
@@ -147,7 +147,7 @@ namespace YachtDice.Tests
[Test]
public void Execute_ConditionPasses_AppliesEffect()
{
var condition = CategoryCondition.CreateForTest(fullHouseCategory);
var condition = CategoryCondition.CreateForTest(_fullHouseCategory);
var effect = AddFlatScoreEffect.CreateForTest(15);
var def = CreateDef("fh-bonus", TriggerType.OnCategoryScored,
@@ -156,8 +156,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
var ctx = CreateScoringContext(25, new[] { 3, 3, 3, 2, 2 }, fullHouseCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(25, new[] { 3, 3, 3, 2, 2 }, _fullHouseCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(15, result.FlatBonus);
Assert.AreEqual(40, result.FinalScore);
@@ -174,8 +174,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(0, result.FlatBonus);
Assert.AreEqual(10, result.FinalScore);
@@ -206,8 +206,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def1);
// dice: [3, 3, 3, 1, 2] — 3 threes
var ctx = CreateScoringContext(9, new[] { 3, 3, 3, 1, 2 }, threesCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(9, new[] { 3, 3, 3, 1, 2 }, _threesCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(16, result.FlatBonus);
Assert.AreEqual(168, result.FinalScore);
@@ -218,8 +218,8 @@ namespace YachtDice.Tests
[Test]
public void Execute_NoActiveModifiers_NoChange()
{
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(10, result.FinalScore);
Assert.AreEqual(0, result.FlatBonus);
@@ -233,10 +233,10 @@ namespace YachtDice.Tests
var def = CreateDef("inactive", TriggerType.OnCategoryScored, null,
new List<Effect> { effect });
registry.Add(def);
_registry.Add(def);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(0, result.FlatBonus);
Assert.AreEqual(10, result.FinalScore);
@@ -255,8 +255,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(10, result.FlatBonus);
Assert.AreEqual(25, result.CurrencyDelta);
@@ -268,7 +268,7 @@ namespace YachtDice.Tests
[Test]
public void Execute_TracingEnabled_PopulatesDebugLog()
{
pipeline.TracingEnabled = true;
_pipeline.TracingEnabled = true;
var effect = AddFlatScoreEffect.CreateForTest(10);
var def = CreateDef("traced", TriggerType.OnCategoryScored, null,
@@ -276,8 +276,8 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.IsNotNull(result.DebugLog);
Assert.IsTrue(result.DebugLog.Count > 0);
@@ -298,14 +298,14 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
// Only 2 sixes — condition requires 3
var ctx = CreateScoringContext(12, new[] { 6, 6, 1, 2, 3 }, sixesCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(12, new[] { 6, 6, 1, 2, 3 }, _sixesCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(0, result.FlatBonus);
// 3 sixes — condition passes
var ctx2 = CreateScoringContext(18, new[] { 6, 6, 6, 1, 2 }, sixesCategory);
var result2 = pipeline.Execute(TriggerType.OnCategoryScored, ctx2).GetAwaiter().GetResult();
var ctx2 = CreateScoringContext(18, new[] { 6, 6, 6, 1, 2 }, _sixesCategory);
var result2 = _pipeline.Execute(TriggerType.OnCategoryScored, ctx2).GetAwaiter().GetResult();
Assert.AreEqual(100, result2.FlatBonus);
}
@@ -325,14 +325,14 @@ namespace YachtDice.Tests
RegisterAndActivate(def);
// Below threshold
var ctx = CreateScoringContext(15, new[] { 3, 3, 3, 3, 3 }, threesCategory);
var result = pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
var ctx = CreateScoringContext(15, new[] { 3, 3, 3, 3, 3 }, _threesCategory);
var result = _pipeline.Execute(TriggerType.OnCategoryScored, ctx).GetAwaiter().GetResult();
Assert.AreEqual(1f, result.Multiplier);
// At threshold
var ctx2 = CreateScoringContext(20, new[] { 4, 4, 4, 4, 4 }, foursCategory);
var result2 = pipeline.Execute(TriggerType.OnCategoryScored, ctx2).GetAwaiter().GetResult();
var ctx2 = CreateScoringContext(20, new[] { 4, 4, 4, 4, 4 }, _foursCategory);
var result2 = _pipeline.Execute(TriggerType.OnCategoryScored, ctx2).GetAwaiter().GetResult();
Assert.AreEqual(2f, result2.Multiplier);
}
@@ -342,7 +342,7 @@ namespace YachtDice.Tests
[Test]
public void ToScoreResult_ConvertsCorrectly()
{
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, chanceCategory);
var ctx = CreateScoringContext(10, new[] { 1, 2, 3, 4, 5 }, _chanceCategory);
ctx.FlatBonus = 5;
ctx.Multiplier = 2f;
ctx.PostMultiplier = 1.5f;
@@ -352,7 +352,7 @@ namespace YachtDice.Tests
Assert.AreEqual(10, sr.baseScore);
Assert.AreEqual(5, sr.flatBonus);
Assert.AreEqual(3f, sr.multiplier, 0.001f); // 2 * 1.5
Assert.AreEqual(chanceCategory, sr.category);
Assert.AreEqual(_chanceCategory, sr.category);
}
}
}
@@ -9,26 +9,26 @@ namespace YachtDice.Tests
{
public class ScoringSystemTests
{
private CategoryDefinition yachtCategory;
private CategoryDefinition onesCategory;
private CategoryDefinition twosCategory;
private CategoryDefinition chanceCategory;
private CategoryCatalog catalog;
private DiceDefinition standardDice;
private CategoryDefinition _yachtCategory;
private CategoryDefinition _onesCategory;
private CategoryDefinition _twosCategory;
private CategoryDefinition _chanceCategory;
private CategoryCatalog _catalog;
private DiceDefinition _standardDice;
[SetUp]
public void SetUp()
{
standardDice = DiceDefinition.CreateForTest<StandardDice>("d6", "d6");
_standardDice = DiceDefinition.CreateForTest<StandardDice>("d6", "d6");
yachtCategory = NOfAKindCategory.CreateForTest("yacht", "Яхта", 5, fixedScoreMode: true, score: 50);
onesCategory = SumOfValueCategory.CreateForTest("ones", "Единицы", 1);
twosCategory = SumOfValueCategory.CreateForTest("twos", "Двойки", 2);
chanceCategory = SumAllCategory.CreateForTest("chance", "Шанс");
_yachtCategory = NOfAKindCategory.CreateForTest("yacht", "Яхта", 5, fixedScoreMode: true, score: 50);
_onesCategory = SumOfValueCategory.CreateForTest("ones", "Единицы", 1);
_twosCategory = SumOfValueCategory.CreateForTest("twos", "Двойки", 2);
_chanceCategory = SumAllCategory.CreateForTest("chance", "Шанс");
catalog = CategoryCatalog.CreateForTest(new List<CategoryDefinition>
_catalog = CategoryCatalog.CreateForTest(new List<CategoryDefinition>
{
onesCategory, twosCategory, yachtCategory, chanceCategory
_onesCategory, _twosCategory, _yachtCategory, _chanceCategory
});
}
@@ -38,12 +38,12 @@ namespace YachtDice.Tests
foreach (var go in Object.FindObjectsByType<ScoringSystem>(FindObjectsSortMode.None))
Object.DestroyImmediate(go.gameObject);
Object.DestroyImmediate(yachtCategory);
Object.DestroyImmediate(onesCategory);
Object.DestroyImmediate(twosCategory);
Object.DestroyImmediate(chanceCategory);
Object.DestroyImmediate(catalog);
Object.DestroyImmediate(standardDice);
Object.DestroyImmediate(_yachtCategory);
Object.DestroyImmediate(_onesCategory);
Object.DestroyImmediate(_twosCategory);
Object.DestroyImmediate(_chanceCategory);
Object.DestroyImmediate(_catalog);
Object.DestroyImmediate(_standardDice);
}
private ScoringSystem CreateScoringSystem()
@@ -56,7 +56,7 @@ namespace YachtDice.Tests
{
var dice = new DiceInstance[values.Length];
for (int i = 0; i < values.Length; i++)
dice[i] = new DiceInstance(standardDice, values[i]);
dice[i] = new DiceInstance(_standardDice, values[i]);
return dice;
}
@@ -65,7 +65,7 @@ namespace YachtDice.Tests
{
var system = CreateScoringSystem();
var dice = CreateDice(6, 6, 6, 6, 6);
var result = system.ScoreCategory(dice, yachtCategory);
var result = system.ScoreCategory(dice, _yachtCategory);
Assert.AreEqual(50, result.baseScore);
Assert.AreEqual(0, result.flatBonus);
@@ -87,9 +87,9 @@ namespace YachtDice.Tests
};
var dice = CreateDice(1, 1, 1, 1, 1);
system.ScoreCategory(dice, onesCategory);
system.ScoreCategory(dice, _onesCategory);
Assert.AreEqual(onesCategory, firedCategory);
Assert.AreEqual(_onesCategory, firedCategory);
Assert.AreEqual(5, firedResult.baseScore);
}
@@ -98,10 +98,10 @@ namespace YachtDice.Tests
{
var system = CreateScoringSystem();
var dice = CreateDice(1, 2, 3, 4, 5);
system.ScoreCategory(dice, chanceCategory);
system.ScoreCategory(dice, _chanceCategory);
Assert.Throws<System.InvalidOperationException>(() =>
system.ScoreCategory(dice, chanceCategory));
system.ScoreCategory(dice, _chanceCategory));
}
[Test]
@@ -109,7 +109,7 @@ namespace YachtDice.Tests
{
var system = CreateScoringSystem();
var dice = CreateDice(1, 2, 3, 4, 5);
var result = system.PreviewScore(dice, chanceCategory);
var result = system.PreviewScore(dice, _chanceCategory);
Assert.AreEqual(15, result.baseScore);
Assert.AreEqual(0, result.flatBonus);
@@ -120,8 +120,8 @@ namespace YachtDice.Tests
public void TotalScore_SumsAllScoredCategories()
{
var system = CreateScoringSystem();
system.ScoreCategory(CreateDice(1, 1, 1, 1, 1), onesCategory);
system.ScoreCategory(CreateDice(2, 2, 2, 2, 2), twosCategory);
system.ScoreCategory(CreateDice(1, 1, 1, 1, 1), _onesCategory);
system.ScoreCategory(CreateDice(2, 2, 2, 2, 2), _twosCategory);
Assert.AreEqual(15, system.TotalScore); // 5 + 10
}
@@ -130,12 +130,12 @@ namespace YachtDice.Tests
public void ResetScorecard_ClearsAll()
{
var system = CreateScoringSystem();
system.ScoreCategory(CreateDice(1, 1, 1, 1, 1), onesCategory);
system.ScoreCategory(CreateDice(1, 1, 1, 1, 1), _onesCategory);
system.ResetScorecard();
Assert.AreEqual(0, system.TotalScore);
Assert.IsFalse(system.IsCategoryUsed(onesCategory));
Assert.IsFalse(system.IsCategoryUsed(_onesCategory));
}
// ── Category SO Unit Tests ──────────────────────────────────
@@ -165,8 +165,8 @@ namespace YachtDice.Tests
[Test]
public void NOfAKindCategory_Yacht_ReturnsFixedScore()
{
Assert.AreEqual(50, yachtCategory.Calculate(CreateDice(6, 6, 6, 6, 6)));
Assert.AreEqual(0, yachtCategory.Calculate(CreateDice(6, 6, 6, 6, 1)));
Assert.AreEqual(50, _yachtCategory.Calculate(CreateDice(6, 6, 6, 6, 6)));
Assert.AreEqual(0, _yachtCategory.Calculate(CreateDice(6, 6, 6, 6, 1)));
}
[Test]
@@ -206,8 +206,8 @@ namespace YachtDice.Tests
[Test]
public void SumAllCategory_SumsEverything()
{
Assert.AreEqual(15, chanceCategory.Calculate(CreateDice(1, 2, 3, 4, 5)));
Assert.AreEqual(30, chanceCategory.Calculate(CreateDice(6, 6, 6, 6, 6)));
Assert.AreEqual(15, _chanceCategory.Calculate(CreateDice(1, 2, 3, 4, 5)));
Assert.AreEqual(30, _chanceCategory.Calculate(CreateDice(6, 6, 6, 6, 6)));
}
}
}
+42 -42
View File
@@ -12,23 +12,23 @@ namespace YachtDice.Tests
{
public sealed class ShopModelTests
{
private CurrencyBank bank;
private ModifierRegistry registry;
private InventoryModel inventory;
private DiceCollection diceCollection;
private ShopModel shop;
private CurrencyBank _bank;
private ModifierRegistry _registry;
private InventoryModel _inventory;
private DiceCollection _diceCollection;
private ShopModel _shop;
[SetUp]
public void SetUp()
{
var go = new GameObject("Bank");
bank = go.AddComponent<CurrencyBank>();
bank.SetBalance(500);
_bank = go.AddComponent<CurrencyBank>();
_bank.SetBalance(500);
registry = new ModifierRegistry(5);
inventory = new InventoryModel(registry);
diceCollection = new DiceCollection();
shop = new ShopModel(bank, inventory, diceCollection);
_registry = new ModifierRegistry(5);
_inventory = new InventoryModel(_registry);
_diceCollection = new DiceCollection();
_shop = new ShopModel(_bank, _inventory, _diceCollection);
}
[TearDown]
@@ -52,24 +52,24 @@ namespace YachtDice.Tests
{
var mod = CreateDef("test", shopPrice: 100);
bool result = shop.TryPurchase(mod);
bool result = _shop.TryPurchase(mod);
Assert.IsTrue(result);
Assert.AreEqual(400, bank.Balance);
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
Assert.AreEqual(400, _bank.Balance);
Assert.AreEqual(1, _inventory.OwnedModifiers.Count);
}
[Test]
public void TryPurchase_FailsWhenBroke()
{
bank.SetBalance(10);
_bank.SetBalance(10);
var mod = CreateDef("test", shopPrice: 100);
bool result = shop.TryPurchase(mod);
bool result = _shop.TryPurchase(mod);
Assert.IsFalse(result);
Assert.AreEqual(10, bank.Balance);
Assert.AreEqual(0, inventory.OwnedModifiers.Count);
Assert.AreEqual(10, _bank.Balance);
Assert.AreEqual(0, _inventory.OwnedModifiers.Count);
}
[Test]
@@ -77,12 +77,12 @@ namespace YachtDice.Tests
{
var mod = CreateDef("perm", shopPrice: 100);
shop.TryPurchase(mod);
bool secondResult = shop.TryPurchase(mod);
_shop.TryPurchase(mod);
bool secondResult = _shop.TryPurchase(mod);
Assert.IsFalse(secondResult);
Assert.AreEqual(400, bank.Balance);
Assert.AreEqual(1, inventory.OwnedModifiers.Count);
Assert.AreEqual(400, _bank.Balance);
Assert.AreEqual(1, _inventory.OwnedModifiers.Count);
}
[Test]
@@ -90,23 +90,23 @@ namespace YachtDice.Tests
{
var mod = CreateDef("limited", hasLimitedUses: true, maxUses: 3, shopPrice: 100);
shop.TryPurchase(mod);
bool secondResult = shop.TryPurchase(mod);
_shop.TryPurchase(mod);
bool secondResult = _shop.TryPurchase(mod);
Assert.IsTrue(secondResult);
Assert.AreEqual(300, bank.Balance);
Assert.AreEqual(2, inventory.OwnedModifiers.Count);
Assert.AreEqual(300, _bank.Balance);
Assert.AreEqual(2, _inventory.OwnedModifiers.Count);
}
[Test]
public void TryPurchase_FiresPurchaseEvent()
{
IShopItem purchased = null;
shop.OnItemPurchased += item => purchased = item;
_shop.OnItemPurchased += item => purchased = item;
var mod = CreateDef("test", shopPrice: 100);
shop.TryPurchase(mod);
_shop.TryPurchase(mod);
Assert.IsNotNull(purchased);
Assert.AreEqual("test", purchased.Id);
@@ -117,16 +117,16 @@ namespace YachtDice.Tests
{
var mod = CreateDef("test", shopPrice: 100);
Assert.AreEqual(ShopItemState.Available, shop.GetItemState(mod));
Assert.AreEqual(ShopItemState.Available, _shop.GetItemState(mod));
}
[Test]
public void GetItemState_TooExpensive_WhenCannotAfford()
{
bank.SetBalance(10);
_bank.SetBalance(10);
var mod = CreateDef("test", shopPrice: 100);
Assert.AreEqual(ShopItemState.TooExpensive, shop.GetItemState(mod));
Assert.AreEqual(ShopItemState.TooExpensive, _shop.GetItemState(mod));
}
[Test]
@@ -134,9 +134,9 @@ namespace YachtDice.Tests
{
var mod = CreateDef("perm", shopPrice: 100);
shop.TryPurchase(mod);
_shop.TryPurchase(mod);
Assert.AreEqual(ShopItemState.Owned, shop.GetItemState(mod));
Assert.AreEqual(ShopItemState.Owned, _shop.GetItemState(mod));
}
[Test]
@@ -144,11 +144,11 @@ namespace YachtDice.Tests
{
var die = DiceDefinition.CreateForTest<StandardDice>("test_die", shopPrice: 100);
bool result = shop.TryPurchase(die);
bool result = _shop.TryPurchase(die);
Assert.IsTrue(result);
Assert.AreEqual(400, bank.Balance);
Assert.AreEqual(1, diceCollection.OwnedDice.Count);
Assert.AreEqual(400, _bank.Balance);
Assert.AreEqual(1, _diceCollection.OwnedDice.Count);
}
[Test]
@@ -156,12 +156,12 @@ namespace YachtDice.Tests
{
var die = DiceDefinition.CreateForTest<StandardDice>("unique_die", shopPrice: 100);
shop.TryPurchase(die);
bool secondResult = shop.TryPurchase(die);
_shop.TryPurchase(die);
bool secondResult = _shop.TryPurchase(die);
Assert.IsFalse(secondResult);
Assert.AreEqual(400, bank.Balance);
Assert.AreEqual(1, diceCollection.OwnedDice.Count);
Assert.AreEqual(400, _bank.Balance);
Assert.AreEqual(1, _diceCollection.OwnedDice.Count);
}
[Test]
@@ -169,9 +169,9 @@ namespace YachtDice.Tests
{
var die = DiceDefinition.CreateForTest<StandardDice>("die1", shopPrice: 50);
shop.TryPurchase(die);
_shop.TryPurchase(die);
Assert.AreEqual(ShopItemState.Owned, shop.GetItemState(die));
Assert.AreEqual(ShopItemState.Owned, _shop.GetItemState(die));
}
}
}
+5 -2
View File
@@ -95,8 +95,11 @@ namespace YachtDice.UI
private void OnDestroy()
{
for (int i = 0; i < diceButtons.Length; i++)
diceButtons[i].onClick.RemoveAllListeners();
for (var index = 0; index < diceButtons.Length; index++)
{
var t = diceButtons[index];
t.onClick.RemoveAllListeners();
}
rollButton.onClick.RemoveAllListeners();
}
+1 -2
View File
@@ -137,9 +137,8 @@ namespace YachtDice.UI
var entries = new List<ModifierSaveEntry>();
var permanentIds = new HashSet<string>();
for (int i = 0; i < save.ownedModifiers.Count; i++)
foreach (var oldEntry in save.ownedModifiers)
{
var oldEntry = save.ownedModifiers[i];
var def = _modifierCatalog.FindById(oldEntry.modifierId);
if (def == null)
+9 -9
View File
@@ -57,10 +57,10 @@ namespace YachtDice.UI
public void ClearAllPreviews()
{
for (int i = 0; i < categoryRows.Count; i++)
foreach (var t in categoryRows)
{
categoryRows[i].HidePreview();
categoryRows[i].SetInteractable(false);
t.HidePreview();
t.SetInteractable(false);
}
}
@@ -72,8 +72,8 @@ namespace YachtDice.UI
public void SetAllInteractable(bool interactable)
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].SetInteractable(interactable);
foreach (var t in categoryRows)
t.SetInteractable(interactable);
}
public void UpdateTotalDisplay(int totalScore, int upperSum, bool hasUpperBonus)
@@ -85,8 +85,8 @@ namespace YachtDice.UI
public void ResetAll()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].ResetRow();
foreach (var t in categoryRows)
t.ResetRow();
UpdateTotalDisplay(0, 0, false);
}
@@ -98,8 +98,8 @@ namespace YachtDice.UI
private void OnDestroy()
{
for (int i = 0; i < categoryRows.Count; i++)
categoryRows[i].OnCategorySelected -= HandleCategorySelected;
foreach (var t in categoryRows)
t.OnCategorySelected -= HandleCategorySelected;
}
}
}