有没有更优雅的方法来找到正确的数字?
我有一个二维数组,用作国际象棋游戏的棋盘。我希望用户输入采用 Smith Notation 格式。我的数组的设置方式是,如果用户说他们想要将一个棋子移入或移出第 8 行(从用户的角度来看是最上面的一行),他们就会与 row[0]
在数组中。因此,为了处理这个问题,我编写了一个函数,将用户的输入转换为数组的正确行。然而,它似乎有点笨重,我想知道有更多经验的程序员如何解决这个问题。
int convertToCorrectRow(int row)
{
int newRow;
switch (row) {
case 1:
newRow = 7;
break;
case 2:
newRow = 6;
break;
case 3:
newRow = 5;
break;
case 4:
newRow = 4;
break;
case 5:
newRow = 3;
break;
case 6:
newRow = 2;
break;
case 7:
newRow = 1;
break;
case 8:
newRow = 0;
break;
default:
assert(false);
break;
}
return newRow;
}
我确实考虑过翻转数组并将其反向显示给用户,这样当用户与第 8 行交互时,他们实际上是与数组中的 row[7]
交互,这样就消除了这种需要对于这个功能。但是,我仍然想知道解决这个问题的其他方法。 预先感谢您的回复。
I have a 2D array that acts as a board for a chess game. I expect user input to be in the Smith Notation. The way my array is set up is if the user says they want a piece to move to or from the 8th row (the top one from the user's point of view), they are interacting with row[0]
in the array. So to handle this I wrote a function that converts the user's input into the correct row for the array. However, it seems a little clunky and I was wondering how programmers with more experience would solve this problem.
int convertToCorrectRow(int row)
{
int newRow;
switch (row) {
case 1:
newRow = 7;
break;
case 2:
newRow = 6;
break;
case 3:
newRow = 5;
break;
case 4:
newRow = 4;
break;
case 5:
newRow = 3;
break;
case 6:
newRow = 2;
break;
case 7:
newRow = 1;
break;
case 8:
newRow = 0;
break;
default:
assert(false);
break;
}
return newRow;
}
I did think of having flipping the array and displaying it in reverse to the user so that when the user interacts with row 8 they are actually interact with row[7]
in the array and that would eliminate the need for this function. However, I would still like to know other ways to solve this problem.
Thanks in advance for your response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来这简化为:
如果
row
来自用户输入而没有进一步验证,那么我不会使用断言。It looks like this simplifies to:
If
row
comes from user input without further validation, I wouldn't use an assert, though.为什么不只是...
Why not just...