I'm working with AngularJS on a browser game and I have a bunch of "business" constants.
These constants will be often updated during game testing (game balancing) and are used by different modules/features.
I'm currently managing them in a single file like that:
constants.js
var gameConstants = {
BASE_COST: 100,
MULTIPLIER_COST: 1.07
};
myFactory.js
app.factory('MyFactory', function () {
return {
getRealCost: function() {
return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
}
}
});
But I'm thinking about a service provider for game constants. Something like:
constantServices.js
app.factory('ConstantServices', function () {
var baseCost: 100, //Should I use UPPER_SNAKECASE here too?
multiplierCost: 1.07
return {
getCost: function() {
return baseCost;
}
getMultiplierCost: function() {
return multiplierCost;
}
}
});
myFactory.js
app.factory('MyFactory', ['ConstantServices' function (ConstantServices) {
return {
getRealCost: function() {
return ConstantServices.getCost() * ConstantServices.getMultiplierCost();
}
}
});
What do you think about it? Is it a good idea to create a service provider for constants only (i. e. call a service without any logic)? Do you think about a better way to manage these constants?
-
If your game balance constants are stored in client side JavaScript, you should be prepared for people to discover and alter those values.Dan Pichelman– Dan Pichelman2015年09月04日 14:08:34 +00:00Commented Sep 4, 2015 at 14:08
-
@DanPichelman You're right, it's intended. The game has to be full client-side.Allan Quatermain– Allan Quatermain2015年09月04日 14:10:43 +00:00Commented Sep 4, 2015 at 14:10
-
edit: re-worded; I see no reason why you shouldn't encapsule the gameConstants object inside the 'ConstantServices' factory and just expose it's values via the public interface of the service...Neil Hibbert– Neil Hibbert2015年09月04日 14:17:50 +00:00Commented Sep 4, 2015 at 14:17
1 Answer 1
Just use the constant service from AngularJS:
app.constant('gameConstants, [
{ BASE_COST: 100 },
{ MULTIPLIER_COST: 1.07 }
]);
And then inject the gameConstants wherever you need them:
app.factory('MyFactory', ['gameConstants', function (gameConstants) {
return {
getRealCost: function() {
return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
}
}
}]);