Skip to content

Instantly share code, notes, and snippets.

@lawnsea
Forked from Rich-Harris/Player.js
Last active December 18, 2015 17:19
Show Gist options
  • Save lawnsea/5818224 to your computer and use it in GitHub Desktop.
Save lawnsea/5818224 to your computer and use it in GitHub Desktop.
var Player = (function () {
var Player, generateGuid, maxCoins, secrets, get, set, cashIn;
maxCoins = 100;
// via http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
generateGuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r, v;
r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
secrets = {};
get = function ( player, property ) {
var data = secrets[ player.guid ];
return data[ property ];
};
set = function ( player, property, value ) {
var data = secrets[ player.guid ];
data[ property ] = value;
};
cashIn = function ( player ) {
var coinCount, lifeCount;
coinCount = get( player, 'coinCount' );
lifeCount = get( player, 'lifeCount' );
lifeCount += Math.floor( coinCount / maxCoins );
coinCount %= maxCoins;
set( player, 'coinCount', coinCount );
set( player, 'lifeCount', lifeCount );
};
Player = function () {
this.guid = generateGuid();
secrets[ this.guid ] = {
coinCount: 0,
lifeCount: 3
};
};
Player.prototype = {
addCoin: function () {
coinCount = get( this, 'coinCount' );
set( this, 'coinCount', ++coinCount );
if ( coinCount >= maxCoins ) {
cashIn( this );
}
},
getCoins: function () {
return get(this, 'coinCount');
}
};
return Player;
}());
var player1 = new Player();
var player2 = new Player();
var guid = player1.guid;
player1.guid = player2.guid;
player1.addCoin();
player1.guid = guid;
console.log('Player 1 has', player1.getCoins(), 'coins');
console.log('Player 2 has', player2.getCoins(), 'coins');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment