diff --git a/src/engine/moneySystem.js b/src/engine/moneySystem.js new file mode 100644 index 0000000..7c8206a --- /dev/null +++ b/src/engine/moneySystem.js @@ -0,0 +1,20 @@ +// ==================== 银两系统 ==================== + +export function applyDailyIncome(state, amount) { + state.money += amount; + if (state.money < 0) { + state.money = 0; + } +} + +export function canAfford(state, cost) { + return state.money >= cost; +} + +export function spendMoney(state, amount) { + if (!canAfford(state, amount)) { + return false; + } + state.money -= amount; + return true; +} diff --git a/test/moneySystem.test.js b/test/moneySystem.test.js new file mode 100644 index 0000000..6f810f2 --- /dev/null +++ b/test/moneySystem.test.js @@ -0,0 +1,72 @@ +// ==================== 银两系统测试 ==================== + +import { applyDailyIncome, canAfford, spendMoney } from '../src/engine/moneySystem.js'; + +let passCount = 0; +let failCount = 0; + +function assert(condition, message) { + if (condition) { + passCount++; + } else { + failCount++; + console.error('FAIL:', message); + } +} + +function testApplyDailyIncome() { + // 正收入 + const state1 = { money: 100 }; + applyDailyIncome(state1, 50); + assert(state1.money === 150, 'positive income should add to money'); + + // 负收入 + const state2 = { money: 100 }; + applyDailyIncome(state2, -30); + assert(state2.money === 70, 'negative income should subtract from money'); + + // 负收入导致归零 + const state3 = { money: 20 }; + applyDailyIncome(state3, -50); + assert(state3.money === 0, 'negative income below zero should clamp to 0'); +} + +function testCanAfford() { + // 足够 + const state1 = { money: 100 }; + assert(canAfford(state1, 50) === true, 'should afford when money >= cost'); + + // 不足够 + const state2 = { money: 30 }; + assert(canAfford(state2, 50) === false, 'should not afford when money < cost'); + + // 刚好相等 + const state3 = { money: 50 }; + assert(canAfford(state3, 50) === true, 'should afford when money === cost'); +} + +function testSpendMoney() { + // 成功消费 + const state1 = { money: 100 }; + const result1 = spendMoney(state1, 40); + assert(result1 === true, 'spendMoney should return true on success'); + assert(state1.money === 60, 'money should decrease after spending'); + + // 余额不足 + const state2 = { money: 30 }; + const result2 = spendMoney(state2, 50); + assert(result2 === false, 'spendMoney should return false when insufficient funds'); + assert(state2.money === 30, 'money should remain unchanged when spending fails'); +} + +// 运行测试 +testApplyDailyIncome(); +testCanAfford(); +testSpendMoney(); + +if (failCount === 0) { + console.log('All moneySystem tests PASS'); +} else { + console.log(`${passCount} passed, ${failCount} failed`); + process.exit(1); +}