用于C++中的循环的组合
Combining for-loops in C++
我正在制作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;
}
无法测试它,因为我没有元素。试试看,如果你喜欢它,我可以详细说明
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- 将多个 for 循环组合成单个迭代器
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 通过字符串迭代并将每个循环中的先前字符组合在一起
- 如何将一个 while 循环与 for 循环组合在一起?
- 高速解决方案以循环浏览不同变量的所有组合,并使用启动步骤停止方案(C )
- 在循环中组合元组
- 为循环嵌套的变量快速生成数字组合
- 嵌套c++11范围循环,用于查找组合
- 用于C++中的循环的组合
- C++可能的硬币组合使用while循环
- 可能的组合和循环
- 在for循环中获得所有组合的最快方法是什么
- 如何将查找组合的几个循环代码转换为递归方法
- 如何处理c++中的循环组合?
- 用于组合组的'for'循环
- 组合和循环依赖
- 算法循环组合
- 通过只循环一次来组合c++标准算法