如何清空此代码(if-else语句)



让这段代码更枯燥的最佳方法是什么?我想在currentRoom.id相同的地方嵌套if语句,或者通过在条件中添加||部分来浓缩它。但我不确定这些解决方案是否会让代码变得更整洁。

这种东西最合理、最简洁的风格是什么?

if(direction === 'east' && player.currentRoom.id === 1) {
roomNum = '3';
} else if (direction ==='east' && player.currentRoom.id === 4) {
roomNum = '1';
} else if (direction === 'west' && player.currentRoom.id === 1) {
roomNum = '4';
} else if (direction === 'west' && player.currentRoom.id === 3) {
roomNum = '1';
} else if (direction === 'north' && player.currentRoom.id === 5) {
roomNum = '1';
} else if (direction === 'north' && player.currentRoom.id === 1) {
roomNum = '2';
} else if (direction === 'south' && player.currentRoom.id === 1) {
roomNum = '5';
} else if (direction === 'south' && player.currentRoom.id === 2) {
roomNum = '1';
}
}

在没有任何其他程序重构的情况下,您可以通过在由每个子句中的变量数据组成的元组数组上循环,在第一个潜在匹配之后中断,来压缩示例中的重复语法:

for (const [dir, id, num] of [
['east',  1, '3'],
['east',  4, '1'],
['west',  1, '4'],
['west',  3, '1'],
['north', 5, '1'],
['north', 1, '2'],
['south', 1, '5'],
['south', 2, '1'],
]) {
if (direction === dir && player.currentRoom.id === id) {
roomNum = num;
break;
}
}

房间有一个数组意味着你只需要加/减当前的X或Y坐标。类似于:

const rooms = [
[0, 2,0],
[4, 1, 3],
[0, 5, 0],
];
let horizIndex = 1;
let vertIndex = 1;
console.log(rooms[vertIndex][horizIndex]);
const changeRoom = (x, y) => {
if (rooms[vertIndex + y][horizIndex + x]) {
horizIndex = horizIndex + x;
vertIndex = vertIndex + y;
console.log('entered', rooms[vertIndex][horizIndex]);
} else {
console.log('Invalid room');
}
};
const direction = 'south';
if (direction === 'south') {
changeRoom(0, 1);
} else if (direction === 'north') {
changeRoom(0, -1);
} else if (direction === 'east') {
changeRoom(1, 0);
} else if (direction === 'west') {
changeRoom(-1, 0);
}

最新更新