gpt4 book ai didi

c++ - 在 C++ 中组合 for 循环

转载 作者:太空宇宙 更新时间:2023-11-04 13:58:08 25 4
gpt4 key购买 nike

我正在制作一个 GoBoard 并想检查黑人玩家是否赢得了比赛。我做了四个 for 循环来检查是否有 5 个石头水平、垂直或对角线排成一行。但是,我想将它们组合起来,以节省一些代码行。怎么做?是否可以使用相同的 for 循环简单地检查白方玩家,或者我应该为白方玩家创建一个新的 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++ - 在 C++ 中组合 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com