我正在用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 :(得分: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;
};
答案 1 :(得分: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;
答案 2 :(得分: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;
};