我有一个switch语句,用于检查棋子中棋子移动的有效性。如果移动看起来有效,我让流程继续,如果移动没有导致语句return false
,则该函数的结束语句为return true
。我有代码来处理主教和城堡移动的检查,但我正在努力找到一种干嘛的方式对女王进行两套测试:
switch (from_piece[0]) {
case this.CASTLE:
if (from[0] === to[0]) {
//continue to run checks
} else if (from[1] === to[1]) {
//continue to run checks
} else {
return false;
};
break;
case this.BISHOP:
if (Math.abs(from[1] - to[1]) === Math.abs(from[0] - to[0])) {
//continue to run checks
} else {
return false;
};
break;
case this.QUEEN:
// run both bishop and castle tests
}
答案 0 :(得分:0)
这个逻辑太复杂了,只能用switch语句。您可以将测试移动到函数中并像这样调用它们:
switch (from_piece[0]) {
case this.CASTLE:
validRook()
break;
case this.BISHOP:
validBishop();
break;
case this.QUEEN:
validRook();
validBishop();
break;
}
function validRook(){
if (from[0] === to[0]) {
return true;
} else if (from[1] === to[1]) {
return true;
} else {
return false;
}
}
function validBishop(){
if (Math.abs(from[1] - to[1]) === Math.abs(from[0] - to[0])) {
return true;
} else {
return false;
}
}