chenxin
2020-12-25 adb0dae8a82a7eabb4e686bc0e83c8859bf6445f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
 
namespace Core.Economy
{
    /// <summary>
    /// A basic model for in game currency
    /// </summary>
    public class Currency
    {
        /// <summary>
        /// How much currency there currently is
        /// </summary>
        public int currentCurrency { get; private set; }
 
        public int lastCurrency { get; private set; }
 
        /// <summary>
        /// Occurs when currency changed.
        /// </summary>
        public event Action currencyChanged;
 
        /// <summary>
        /// Initializes a new instance of the <see cref="Core.Economy.Currency" /> class.
        /// </summary>
        public Currency(int startingCurrency)
        {
            ChangeCurrency(startingCurrency);
        }
 
        /// <summary>
        /// Adds the currency.
        /// </summary>
        /// <param name="increment">the change in currency</param>
        public void AddCurrency(int increment)
        {
            if (increment == 0) return;
 
            ChangeCurrency(increment);
        }
 
        /// <summary>
        /// Method for trying to purchase, returns false for insufficient funds
        /// </summary>
        /// <returns><c>true</c>, if purchase was successful i.e. enough currency <c>false</c> otherwise.</returns>
        public bool TryPurchase(int cost)
        {
            // Cannot afford this item
            if (!CanAfford(cost))
            {
                return false;
            }
            ChangeCurrency(-cost);
            return true;
        }
 
        /// <summary>
        /// Determines if the specified cost is affordable.
        /// </summary>
        /// <returns><c>true</c> if this cost is affordable; otherwise, <c>false</c>.</returns>
        public bool CanAfford(int cost)
        {
            return currentCurrency >= cost;
        }
 
        /// <summary>
        /// Changes the currency.
        /// </summary>
        /// <param name="increment">the change in currency</param>
        protected void ChangeCurrency(int increment)
        {
            if (increment != 0)
            {
                lastCurrency = currentCurrency;
                currentCurrency += increment;
                if (currencyChanged != null)
                {
                    currencyChanged();
                }
            }
        }
    }
}