Skip to content

Instantly share code, notes, and snippets.

@unstoppablecarl
Created August 8, 2014 20:03
Show Gist options
  • Save unstoppablecarl/8e0dec4e9de75aee6a5d to your computer and use it in GitHub Desktop.
Save unstoppablecarl/8e0dec4e9de75aee6a5d to your computer and use it in GitHub Desktop.
var HpPotion = function(settings){
settings = settings || {};
_.extend(this, settings);
};
HpPotion.prototype = {
constructor: HpPotion,
slug: 'hp_potion',
quantity: 1,
// doesn't actually need a load function in this example
load: function(saveData){
},
getSaveData: function(){
return {
isSaveData: true,
slug: this.slug,
quantity: this.quantity
};
}
};
var ItemsBySlug = {
hp_potion: HpPotion
};
var Player = function(settings){
settings = settings || {};
_.extend(this, settings);
this.items = [];
this.sprite = spriteCreator.createSprite(this.race);
if(settings.isSaveData){
this.load(settings);
}
};
Player.prototype = {
constructor: Player,
sprite: null,
race: 'human',
items: null,
addItem: function(item){
this.items.push(item);
},
load: function(saveData){
var items = saveData.items;
for (var i = 0; i < items.length; i++) {
var itemData = items[i],
ItemConstructor = ItemsBySlug[itemData.slug],
item = new ItemConstructor(itemData);
this.addItem(item);
}
},
getSaveData: function(){
var items = [];
for (var i = 0; i < this.items.length; i++) {
items.push(this.items[i].getSaveData());
}
return {
isSaveData: true,
race: this.race,
items: items
};
}
};
var player = new Player();
var playerSaveData = player.getSaveData();
var loadedPlayer = new Player(playerSaveData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment