-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrency.js
More file actions
96 lines (79 loc) · 2.59 KB
/
currency.js
File metadata and controls
96 lines (79 loc) · 2.59 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Currency {
constructor(initialBalance = 0) {
this.balance = initialBalance;
this.transactionHistory = [];
this.onBalanceChange = null; // Callback for balance changes
}
// Set callback for when balance changes
setOnBalanceChangeCallback(callback) {
this.onBalanceChange = callback;
}
// Add coins to balance
addCoins(amount, reason = "unspecified") {
if (amount <= 0) return false;
this.balance += amount;
// Record transaction
this.transactionHistory.push({
type: 'credit',
amount: amount,
reason: reason,
timestamp: new Date(),
balance: this.balance
});
// Trigger callback if defined
if (this.onBalanceChange) {
this.onBalanceChange(this.balance, amount, 'credit', reason);
}
console.log(`Added ${amount} coins (${reason}). New balance: ${this.balance}`);
return true;
}
// Attempt to spend coins (returns true if successful)
spendCoins(amount, reason = "unspecified") {
if (amount <= 0 || this.balance < amount) return false;
this.balance -= amount;
// Record transaction
this.transactionHistory.push({
type: 'debit',
amount: amount,
reason: reason,
timestamp: new Date(),
balance: this.balance
});
// Trigger callback if defined
if (this.onBalanceChange) {
this.onBalanceChange(this.balance, amount, 'debit', reason);
}
console.log(`Spent ${amount} coins (${reason}). New balance: ${this.balance}`);
return true;
}
// Add this method to the Currency class
resetBalance(amount) {
this.balance = amount;
if (this.onBalanceChangeCallback) {
this.onBalanceChangeCallback(this.balance, amount, "reset", "Game reset");
}
console.log(`Currency reset to ${amount}`);
}
// Get current balance
getBalance() {
return this.balance;
}
// Get nicely formatted balance with commas for thousands
getFormattedBalance() {
return this.balance.toLocaleString();
}
// Check if can afford an amount
canAfford(amount) {
return this.balance >= amount;
}
// Get last N transactions (default 5)
getRecentTransactions(count = 5) {
return this.transactionHistory
.slice(-count)
.reverse(); // Most recent first
}
// Award pet interaction bonus
awardInteractionBonus(amount = 5) {
return this.addCoins(amount, "pet interaction");
}
}