캐릭터의 움직임과 관련된 게임에서 코드의 일부를 작성했으며이 코드는 매우 반복적입니다 (거의 4 방향 모두 동일).반복적 인 코드 만들기
'if'조건의 테스트로 인해서 어떻게하면 더 간단하게 만들 수 있는지 알 수 없습니다. 다른 경우에는 양수/음수 변수가있는 시스템을 만들어서 위치 변경.
도움 주셔서 감사합니다. 이 라인을 따라
for (var i = 0; i < boxArray.length; i++) {
var box = boxArray[i];
if (controller.left && currentLevel[this.id - this.moveHorizontal] != 1) {
// Enregistrement de la position dans le tableau d'undo/redo
this.index++;
var array = [this.x, this.y, this.id];
this.undoArray.push(array);
// Si box à côté et pas de collision possible
if (box.id == this.id - this.moveHorizontal && currentLevel[this.id - this.moveHorizontal * 2] != 1 && currentLevel[this.id - this.moveHorizontal * 2] != 2) {
// Décalage de la position du player
this.x -= this.boxWidth;
this.id -= this.moveHorizontal;
currentLevel[this.id] = 8;
currentLevel[this.id + this.moveHorizontal] = 0;
// Décalage de la position de la box
box.x -= this.boxWidth;
box.id -= this.moveHorizontal;
currentLevel[this.id - this.moveHorizontal] = 2;
controller.left = false;
}
// Sinon si aucun objet à côté
else if (currentLevel[this.id - this.moveHorizontal] == 0 || currentLevel[this.id - this.moveHorizontal] == 3) {
// Décalage de la position du player
this.x -= this.boxWidth;
this.id -= this.moveHorizontal;
currentLevel[this.id] = 8;
// Décalage de la position du sol
currentLevel[this.id + this.moveHorizontal] = 0;
controller.left = false;
}
}
else if (controller.right && currentLevel[this.id + this.moveHorizontal] != 1) {
this.index++;
var array = [this.x, this.y, this.id];
this.undoArray.push(array);
if (box.id == this.id + this.moveHorizontal && currentLevel[this.id + this.moveHorizontal * 2] != 1 && currentLevel[this.id + this.moveHorizontal * 2] != 2) {
this.x += this.boxWidth;
this.id += this.moveHorizontal;
currentLevel[this.id] = 8;
currentLevel[this.id - this.moveHorizontal] = 0;
box.x += this.boxWidth;
box.id += this.moveHorizontal;
currentLevel[this.id + this.moveHorizontal] = 2;
controller.right = false;
}
else if (currentLevel[this.id + this.moveHorizontal] == 0 || currentLevel[this.id + this.moveHorizontal] == 3) {
this.x += this.boxWidth;
this.id += this.moveHorizontal;
currentLevel[this.id] = 8;
currentLevel[this.id - this.moveHorizontal] = 0;
controller.right = false;
}
}
당신이 포장 할 부분? –
어쩌면, 문제는 내가 좋은 생각이라면 나는 항상 같은 무게의 코드를 갖게된다는 것입니다. – Karz
분리 된 기능의 목적은 반복적 인 코드를 최소화하는 것입니다. 나는 자바 스크립트에서 sematics를 전달하는 것에 대해 확신하지 못한다. 자바 스크립트에서 패스 - 바이 - 레퍼런스 (Pass-by-Reference) 또는 패스 바이 값 (Pass-by-Value)을 사용하고 있는가? 참조 기준 전달이 있으면 반복 코드를 줄일 수 있습니다. –