|
1
|
|
|
/** |
|
2
|
|
|
reaction |
|
3
|
|
|
Service that processes a reaction i.e. it converts reactants to products. |
|
4
|
|
|
Many phenomenons, including decay, redox and reactions, use the react function. |
|
5
|
|
|
|
|
6
|
|
|
@namespace Services |
|
7
|
|
|
*/ |
|
8
|
|
|
'use strict'; |
|
9
|
|
|
|
|
10
|
|
|
angular |
|
11
|
|
|
.module('game') |
|
12
|
|
|
.service('reaction', ['state','util','data', |
|
13
|
|
|
function(state, util, data) { |
|
14
|
|
|
// FIXME: move to util? |
|
15
|
|
|
function isReactionCostMet (number, reaction, playerData) { |
|
16
|
|
|
let keys = Object.keys(reaction.reactant); |
|
17
|
|
|
for (let i = 0; i < keys.length; i++) { |
|
18
|
|
|
let available = playerData.resources[keys[i]].number; |
|
19
|
|
|
let required = number * reaction.reactant[keys[i]]; |
|
20
|
|
|
if (required > available) { |
|
21
|
|
|
return false; |
|
22
|
|
|
} |
|
23
|
|
|
} |
|
24
|
|
|
return true; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/* Transforms reactants to products */ |
|
28
|
|
|
this.react = function(number, reaction, playerData) { |
|
29
|
|
|
if (!Number.isInteger(number) || number <= 0 || |
|
30
|
|
|
!reaction.reactant || !reaction.product) { |
|
31
|
|
|
return; |
|
32
|
|
|
} |
|
33
|
|
|
if (isReactionCostMet(number, reaction, playerData)) { |
|
34
|
|
|
let elements = []; |
|
35
|
|
|
for (let resource in reaction.reactant) { |
|
36
|
|
|
let required = number * reaction.reactant[resource]; |
|
37
|
|
|
playerData.resources[resource].number -= required; |
|
38
|
|
|
playerData.resources[resource].number = playerData.resources[resource].number; |
|
39
|
|
|
// We track which elements produced the products, for the statistics |
|
40
|
|
|
for(let elem of Object.keys(data.resources[resource].elements)){ |
|
41
|
|
|
if(elements.indexOf(elem) === -1) elements.push(elem); |
|
|
|
|
|
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
for (let resource in reaction.product) { |
|
45
|
|
|
let produced = number * reaction.product[resource]; |
|
46
|
|
|
util.addResource(playerData, elements, resource, produced, state); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
}; |
|
50
|
|
|
} |
|
51
|
|
|
]); |
|
52
|
|
|
|
Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.
Consider:
If you or someone else later decides to put another statement in, only the first statement will be executed.
In this case the statement
b = 42will always be executed, while the logging statement will be executed conditionally.ensures that the proper code will be executed conditionally no matter how many statements are added or removed.