二维数组表示

发布于 2024-09-29 23:43:31 字数 432 浏览 0 评论 0原文

这个问题与特定的编程语言无关,而是与简约的代码和抽象相关。

我有一个 3 行 3 列的数组 - 想象一下您可以在其中玩 Tic-Tac-Toe(或零和十字)的棋盘。

当按下某个键(在电话上)时,将在与按下的键对应的位置(键 9 为 board[2][2])将 0 或 1 的值添加到数组(1 表示 X,0 表示 O) 。

在构建 GUI 时,我需要将数组坐标映射到像素,这样如果: [0][0] - 10,10 [0][1] - 10,50 [0][2] - 10,90 ... [2][2] - 90,90

绘图将在嵌套循环中遍历数组时进行,但我陷入了如何用尽可能少的代码行编写 0 = 10、1 = 50 和2 = 90。

一种方法是对每种情况使用一个开关。另一种方法是使用 if。

还有其他想法可以用更少的行数来写这个吗?

谢谢!

The question is not tied to a specific programming language, but rather to minimalistic code and abstraction.

I have this array of 3 rows and 3 columns - imagine a board in which you'd play Tic-Tac-Toe (or naughts and crosses).

When a key(on the Phone) is pressed a value of 0 or 1 is added to the array(1 for X and 0 for O) in the position corresponding to the key pressed(key 9 being board[2][2]).

In building the GUI, I need to map the array coordinates to pixels, such that if:
[0][0] - 10,10
[0][1] - 10,50
[0][2] - 10,90
...
[2][2] - 90,90

the drawing will take place while traversing the array in a nested loop, but I got stuck on how to write in fewest lines of code as possible the mapping between 0 = 10, 1 = 50 and 2 = 90.

One way to go would be to use a switch for each case. Another would be using an if.

Any other ideas to write this in fewer possible lines?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橙幽之幻 2024-10-06 23:43:31
for ( y = 0; y < 3; ++y )
{
    for ( x = 0; x < 3; ++x )
    {
        pos_x = x * 40 + 10;
        pos_y = y * 40 + 10;
        // Draw...
    }
}
for ( y = 0; y < 3; ++y )
{
    for ( x = 0; x < 3; ++x )
    {
        pos_x = x * 40 + 10;
        pos_y = y * 40 + 10;
        // Draw...
    }
}
枫林﹌晚霞¤ 2024-10-06 23:43:31
for(var i = 0; i < 3; i++) {
 for(var j = 0; j < 3; j++) {
  int xPos = i * 40 + 10;
  int yPos = j * 40 + 10;
  //set accordingly
 }
}
for(var i = 0; i < 3; i++) {
 for(var j = 0; j < 3; j++) {
  int xPos = i * 40 + 10;
  int yPos = j * 40 + 10;
  //set accordingly
 }
}
述情 2024-10-06 23:43:31

使用您的指数值作为乘数,即 90 = 2 * 40 + 10, 50 = 1 * 40 + 10

Use your index value as multiplicator i.e. 90 = 2 * 40 + 10, 50 = 1 * 40 + 10

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文