Last active
December 19, 2015 13:49
-
-
Save necoco/5965328 to your computer and use it in GitHub Desktop.
actor-role system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
どのようなコードイメージになるかを考える | |
テーマ: | |
アクションゲーム用 | |
最初はCreateJSシリーズを使う | |
*/ | |
var ars = function(){ | |
function createMethodsFromRoles(proto, roles){ | |
var methodNames = listUpMethodNames(roles); | |
for(var methodName in methodNames){ | |
proto[methodName] = createMethod(methodName, methodNames[methodName]); | |
} | |
} | |
function listUpMethodNames(roles){ | |
var result = {}; | |
for(var roleName in roles){ | |
var role = roles[roleName]; | |
for(var name in role.prototype){ | |
if(role.prototype.hasOwnProperty(name) && (typeof role.prototype[name] === 'function')){ | |
if(!result[name]){ | |
result[name] = []; | |
} | |
result[name].push(roleName); | |
} | |
} | |
} | |
return result; | |
} | |
function createMethod(methodName, table){ | |
return function(){ | |
for(var n = 0, l = table.length; n < l; ++n){ | |
var role = this.roles[table[n]]; | |
role[methodName].apply(role, arguments); | |
} | |
}; | |
} | |
function createActor(roles){ | |
function ActorBase(){ | |
var key; | |
this.roles = {}; | |
for(key in roles){ | |
var role = new roles[key]; | |
this.roles[key] = role; | |
this[key] = role; | |
} | |
for(key in roles){ | |
for(var key2 in roles){ | |
this[key][key2] = this[key2]; | |
} | |
this[key].actor = this; | |
} | |
} | |
createMethodsFromRoles(ActorBase.prototype, roles); | |
ActorBase.prototype.destroy = function(){ | |
var c = ActorBase.collection; | |
c.splice(c.indexOf(this)); | |
}; | |
ActorBase.collection = []; | |
ActorBase.forEach = function(unary){ | |
for(var n = 0; n < ActorBase.collection.length; ++n){ | |
unary(ActorBase.collection[n]) | |
} | |
}; | |
return ActorBase; | |
} | |
return { | |
actor: function(roles){ | |
return createActor(roles); | |
}, | |
role: function(role){ | |
function RoleBase(){ | |
if(role.init){ | |
role.init.apply(this, arguments); | |
} | |
} | |
for(var key in role){ | |
if(key !== "init"){ | |
RoleBase.prototype[key] = role[key]; | |
} | |
} | |
return RoleBase; | |
} | |
}; | |
}(); | |
window.onload = function(){ | |
var Controller = ars.role({ | |
init: function(){ | |
}, | |
update: function(){ | |
console.log("update"); | |
}, | |
remove: function(){ | |
this.actor.destroy(); | |
} | |
}); | |
var Player = ars.actor({ | |
controller: Controller | |
}); | |
var p = new Player(); | |
Player.forEach(function(actor){ | |
actor.update(); | |
}); | |
p.remove(); | |
Player.forEach(function(){ | |
console.log("nothing"); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment