[英]How to create instances of complex class in a better practice?
作為一個新手,我正在開發一款游戲,但卻對創造復雜物體的更好方法感到困惑。 這個問題可以是關於OOP,設計模式和SOLID原則 。對於這些問題,編程語言的限制很少。
情況很明顯:
我正在使用帶有TypeScript的Pixi.js開發基於瀏覽器的2D游戲。 以下類繼承自Sprite或Container,Pixi.js的本機類,但為了清除和重點,我在下面的代碼中省略了這些擴展子句。
我可以簡單地想出下面的Barrel,Shield和Body的代碼:(在TypeScript中,但與Java和C#幾乎沒有區別,不是嗎?)
class Barrel {
constructor(texture, x, y, rotation){
/*...*/
}
}
class Shield {
constructor(texture, x, y, rotation){
/*...*/
}
}
class Body {
constructor(texture, x, y, rotation){
/*...*/
}
}
這就是問題 ,炮塔和軍艦怎么樣?
粗略地,1個炮塔= 1個盾牌+ N個槍管,1個戰艦= 1個身體+ N個炮塔。
如果沒有進一步的詳細思考,可以輕松獲得以下代碼:
class Turret {
private shield: Shield
private barrels: Barrel[]
constructor(x, y, rotation, shieldCfg, barrelCfgList) {
/*...*/
this.shield = new Shield(shieldCfg.texture, shieldCfg.x, shieldCfg.y, shieldCfg.rotation)
for(let cfg of barrelCfgList){
const barrel = new Barrel(cfg.texture, cfg.x, cfg.y, cfg.rotation)
this.barrels.push(barrel)
}
}
}
class Warship {
private body: Body
private turrets: Turret[]
constructor(x, y, rotation, bodyCfg, turretCfgList) {
/*...*/
this.body = new Body(bodyCfg.texture, bodyCfg.x, bodyCfg.y, bodyCfg.rotation)
for(let cfg of turretCfgList){
const turret = new Turret(cfg.x, cfg.y, cfg.rotation, cfg.shieldCfg, cfg.barrelCfgList)
this.turrets.push(turret)
}
}
}
並且不難想象turretCfgList有多復雜。
const turretCfgList = [
{
x: 1,
y: 2,
rotation: 3.14,
shieldCfg: {
texture: 'gun-shield'
x: 4,
y: 5,
rotation: 6.28
},
barrelCfgList: [
{
texture: 'gun-barrel'
x: 7,
y: 8,
rotation: 9.42
},
/*...*/
]
},
/*...*/
]
非常感謝你。
我不確定是否使用下面的代碼。 僅供參考。
class Turret {
// constructor(texture, x, y, rotation, shieldCfg, barrelCfgList) {}
constructor(cfg) {
/*...*/
this.shield = new Shield(cfg.shieldCfg.texture, cfg.shieldCfg.x, shieldCfg.y, cfg.shieldCfg.rotation)
for(let barrelCfg of barrelCfgList){
const barrel = new Barrel(cfg.barrelCfg.texture, cfg.barrelCfg.x, cfg.barrelCfg.y, cfg.barrelCfg.rotation)
this.barrels.push(barrel)
}
}
}
class Turret {
// constructor(texture, x, y, rotation, shieldCfg, barrelCfgList) {}
constructor(x, y, rotation, shield, barrels) {
/*...*/
this.shield = shield
this.barrels = barrels
}
}
??
最好的方法是使用實體組件系統 。 它是游戲開發的最佳選擇,讓您有機會在一個單元/建築/其他游戲對象中組合系統的不同部分。 您可以使用任何方式組合它:特定類,工廠或構建器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.