【问题标题】:Easier way to represent indicies in a 2D array在二维数组中表示索引的更简单方法
【发布时间】:2021-03-20 00:38:01
【问题描述】:

我是编程新手,我创建了一个简单的 tic-tac-toe 游戏。它输入了二维数组的行和列。但是,我想让它更简单,并使用 1-9 的值来表示板上的每个方格。

我处理这个问题的方法似乎相当漫长而复杂。很抱歉格式错误,因为我想节省空间。

if (pos >= 0 && pos <= 9) { //checks if number is a valid position on the board
    if (pos == 1 && board[0][0] == ' ') { board[0][0] = xo; return true; }
    if (pos == 2 && board[0][1] == ' ') { board[0][1] = xo; return true; }
    if (pos == 3 && board[0][2] == ' ') { board[0][2] = xo; return true; }
    if (pos == 4 && board[1][0] == ' ') { board[1][0] = xo; return true; }
    if (pos == 5 && board[1][1] == ' ') { board[1][1] = xo; return true; }
    if (pos == 6 && board[1][2] == ' ') { board[1][2] = xo; return true; }
    if (pos == 7 && board[2][0] == ' ') { board[2][0] = xo; return true; }
    if (pos == 8 && board[2][1] == ' ') { board[2][1] = xo; return true; }
    if (pos == 9 && board[2][2] == ' ') { board[2][2] = xo; return true; }
}
return false;

内部 if 语句检查索引是否为空,然后根据输入的数字分配 xo。如果有人知道任何“更清洁”和更简单的方法,将不胜感激。

【问题讨论】:

    标签: java arrays multidimensional-array array-indexing


    【解决方案1】:

    Assignment, Arithmetic, and Unary Operators

    • / - 除法运算符
    • % - 余数运算符

    您可以在不使用循环的情况下获取单元格[i][j] 的坐标,只使用19 范围内的一个变量pos

    public static boolean isValid(int pos, char xo) {
        int i = (pos - 1) / 3; // row
        int j = (pos - 1) % 3; // column
        if (board[i][j] == ' ') {
            board[i][j] = xo;
            return true;
        }
        return false;
    }
    

    【讨论】:

      【解决方案2】:

      使用数组来处理这些事情要方便得多。我会这样做:

      int p = 1;
      for (int i = 0; i < 3; i++) {
          for (int j = 0; i < 3; i++) {
              if (p == pos && board[i][j] == ' ') {
                  board[i][j] = xo;
                  return true;
                  p += 1;
              }
          }
      }
      return false;
      

      【讨论】:

        【解决方案3】:
        int count = 1; //value of pos
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                char ch = board[i][j]; //setting that board value to ch
                if (pos == count && ch == ' ') {
                    board[i][j] = xo; //that board value becomes xo
                    return true; //returns true
                }
                count++;
            }
        }
        return false;
        

        【讨论】:

          猜你喜欢
          • 2011-06-14
          • 1970-01-01
          • 2018-06-25
          • 1970-01-01
          • 1970-01-01
          • 2020-07-30
          • 2020-06-11
          • 1970-01-01
          • 2023-03-07
          相关资源
          最近更新 更多