我在下面使用Bitfield结构存储国际象棋的棋盘状态,它是一个32位整数。我正在编码/解码的字段是:


epSquare(63中的0)
半步计数(0到100)
当前玩家(0或1)
4个Castling权利标志


我可以创建和提取“状态”,但在更改给定状态时遇到了麻烦:

/*
    0000 0000 0000 0000 0000 0011 1111 epSquare 0x3f
    0000 0000 0000 0001 1111 1100 0000 halfMoves 0x7f >> 6
    0000 0000 0000 0010 0000 0000 0000 curPlayer 0x1 >> 13;
    0000 0000 0000 0100 0000 0000 0000 Kc 0x4000
    0000 0000 0000 1000 0000 0000 0000 Qc 0x8000
    0000 0000 0001 0000 0000 0000 0000 kc 0x10000
    0000 0000 0010 0000 0000 0000 0000 qc 0x20000
    */

public class State {

   public static int new_state(int epSquare, int halfMoves, int turn, int flags){
        return epSquare | (halfMoves << 6) | (turn << 13) | flags;
  }

   public static int epSquare(int s){
      return s & 0x3f;
   }

   public static int halfMoves(int s){
    return s >> 6 & 0x7f;
  }

  // s state, e new epSquare
  public static int setEPSquare(int s, int e){
     //??
  }

   // s state, h halfMoves value
   public static int setHalfMoves(int s, int e){
   //??
  }

  public static void main (String[] args){
     int s = BoardState.new_state(36, 84, 1, 0);
     System.out.println("ep square: " + epSquare(s)); //36
     System.out.println("half moves: " + halfMoves(s)); //84
     s = setHalfMoves(s, 13);
     System.out.println("half moves: " + halfMoves(s)); //should give 13
  }
 }


如何实现setHalfMoves方法?第一个setEPSquare似乎有效,但是我不知道前一个。谢谢!

最佳答案

好吧,首先,您的#setEPSquare()函数不正确。当我向您展示下面的代码时,您可能会明白为什么,但是我也会解释一下:

public static int setHalfMoves(int s, int e){
     return (
             //mask for e to only the correct bits
             (e & 0x7f)
             //left shifted into position
             << 6)
             //zero out the original value
             | (s & (~(0x7f << 6)));
}
public static void main (String[] args){
   int s = BoardState.new_state(36, 84, 1, 0);
   System.out.println("ep square: " + epSquare(s)); //36
   System.out.println("half moves: " + halfMoves(s)); //84
   //Note that this is fixed to now reassign s
   s = setHalfMoves(s, 13);
   System.out.println("half moves: " + halfMoves(s)); //should give 13
}


因此,您的第一个问题是将新值与旧值进行或运算是错误的操作。您需要将其归零以实现“设置”类型的功能。第二个问题是,在通过s操作它之后,必须重新分配setHalfMoves(int, int)。您也必须修复#setEPSquare(),但我留给您尝试。

09-05 18:35