【问题标题】:Combining for-loops in C++在 C++ 中组合 for 循环
【发布时间】:2013-12-10 13:32:31
【问题描述】:

我正在制作 GoBoard,并想检查黑方玩家是否赢得了比赛。我做了四个 for 循环来检查,水平、垂直或对角线是否有 5 块石头。但是,我想将它们结合起来,以节省一些代码行。怎么做?是否可以使用相同的 for 循环简单地检查白棋玩家,还是应该为白棋玩家创建一个新的布尔值?

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

【问题讨论】:

  • 索引i在哪里使用?
  • 无处,这是我使用的循环字母的标准。

标签: c++ for-loop


【解决方案1】:

如果你想减少行数,我会在这条线上做点什么:

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;
}

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

【讨论】:

  • 对不起,我主要是新手,所以我不明白这些类型的变量...你介意我把我的整个 .cc 文件发给你吗?
猜你喜欢
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 2017-08-17
相关资源
最近更新 更多