2016-02-22 43 views
0

我正在用JavaScript編寫基本的基於瀏覽器的遊戲。這是我對可播放字符的控制方法:該代碼如何分解以減少重複(並且應該如此)?

obj.update = function(){ 
     if (this.keyPressed === 'right'){ 
      this.x += 100; 
     } 
     if (this.keyPressed === 'left'){ 
      this.x += -100; 
     } 
     if (this.keyPressed === 'up'){ 
      this.y -= 100; 
     } 
     if (this.keyPressed === 'down'){ 
      this.y -= -100; 
     } 
     // reset key press 
     this.keyPressed = null; 
    }; 

我意識到我在這裏重複代碼。我應該把重複的元素分解出來嗎?如果是的話,那麼最好的辦法是什麼?

+0

不相關的,但可能增加100對y下降會更清楚嗎? –

回答

2

如若是見仁見智。接聽可以部分,我可能會使用一個switch

obj.update = function(){ 
    switch (this.keyPressed) { 
     case 'right': 
      this.x += 100; 
      break; 
     case 'left': 
      this.x += -100; 
      break; 
     case 'up': 
      this.y -= 100; 
      break; 
     case 'down': 
      this.y -= -100; 
      break; 
    } 
    // reset key press 
    this.keyPressed = null; 
}; 

...並可能使100一個常數(ES2015/ES6)或可變我沒有改變(在ES5和更早)。

雖然它也很有誘惑力的使用對象(或ES2015/ES6一個Map)查找表:

var table = { 
    right: {x: 100, y: 0}, 
    left: {x: -100, y: 0}, 
    up: {x: 0, y: -100}, 
    down: {x: 0, y: 100} 
}; 
obj.update = function(){ 
    var entry = table[this.keyPressed]; 
    if (entry) { 
     this.x += entry.x; 
     this.y += entry.y; 
    } 
    // reset key press 
    this.keyPressed = null; 
}; 
+0

我喜歡第二部分。第一部分不是將多個元素分解出來,但我可以看到一個開關更乾淨。 – andydavies

+0

@DizzyEgg:是的,'switch'基本上就是將價值來自哪裏的因素考慮在內,這在這裏不會給我們太多的收益。 –

1

你或許可以使這一帶switch聲明更具可讀性:

switch (this.keyPressed) { 
    case 'right': this.x += 100; break; 
    case 'left' : this.x += -100; break; 
    case 'up' : this.y -= 100; break; 
    case 'down' : this.y -= -100; break; 
} 
this.keyPressed = null; 
1

你可以創建一個對象,並與this調用它。

這個解決方案的智能部分,它可以爲更多的命令打開,比如保存狀態或其他。

var op = { 
    right: function (t) { t.x += 100; }, 
    left: function (t) { t.x -= 100; }, 
    up: function (t) { t.y -= 100; }, 
    down: function (t) { t.y += 100; } 
}; 

obj.update = function() { 
    var f = op[this.keyPressed]; 
    f && f(this); 
    this.keyPressed = null; 
};