用于C++中的循环的组合

Combining for-loops in C++

本文关键字:循环 组合 C++ 用于      更新时间:2023-10-16

我正在制作GoBoard,想检查黑人玩家是否赢得了游戏。我做了四个for循环来检查,是否有5块石头水平、垂直或对角排列。不过,我想将它们组合起来,以节省一些代码行。怎么做?是否可以简单地使用相同的循环来检查白人玩家,或者我应该为白人玩家制作一个新的bool?

class goBoard {
private:
  boardSquare* entrance; // A pointer containing the address of the boardSquare-object at the top left of the grid.
  void zip (boardSquare*, boardSquare*);
  boardSquare* makeRow (); //(int amount)?
  int m, n;
public:
  //goBoard ();
  goBoard (int numberOfRows, int numberOfColumns);
  ~goBoard ();
  void build ();
  void computer (char colour);
  bool squareEmpty (int x, int y);
  void human (char colour);
  void print ();
  bool done ();
  bool won ();
  void makeMove (int x, int y, char colour);
};//class goBoardbool
goBoard::wonBlack () {
   boardSquare* currentSquare = entrance; //assuming that the player starts at the entrance
   bool nextSquare = true;
   if ((*currentSquare).colour == 'B') {
      for (int i = 0; i <= 4; i++) {
         if (nextSquare == true) {
            currentSquare = (*currentSquare).neighbours[2]; //.neighbours[2] is a pointer to the square to the right of the current square
            if ((*currentSquare).colour != 'B')
               nextSquare = false;
            }
      }
      for (int i = 0; i <= 4; i++) {
         if (nextSquare == true) {
            currentSquare = (*currentSquare).neighbours[4];
            if ((*currentSquare).colour != 'B')
               nextSquare = false;
            }
      }
      for (int i = 0; i <= 4; i++) {
         if (nextSquare == true) {
            currentSquare = (*(*currentSquare).neighbours[2]).neighbours[4];
            if ((*currentSquare).colour != 'B')
               nextSquare = false;
            }
      }
      for (int i = 0; i <= 4; i++) {
         if (nextSquare == true) {
            currentSquare = (*(*currentSquare).neighbours[6]).neighbours[4];
            if ((*currentSquare).colour != 'B')
               nextSquare = false;
            }
      }
      if (nextSquare == true)
         return true;
   }
   return false;
}//goBoard::won

如果你想减少行数,我会选择以下行:

enum class Direction {vertical, horizontal, downRight, upRight};
enum class Sign {negative, zero, positive}
enum class Semen {white, black};
template <typename Elem>
unsigned int howManyInARow(Direction direction, Sign sign, Elem elem, Semen semen){
    unsigned int ret = 0;
    if(elem == semen){
        ret = 1;
    }
    if(negative != sign)
        ret += howManInARow(direction, positive, elem.getNeighbour(direction, positive), semen);
    if(positive != sign)
        ret += howManInARow(direction, negative, elem.getNeighbour(direction, negative), semen);
    return ret;
}

无法测试它,因为我没有元素。试试看,如果你喜欢它,我可以详细说明