From 6d6292cc9d2da6b570a3a44ede78b098fccd7537 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Sun, 1 Jul 2018 23:50:52 +0200 Subject: Actually break loop in Board::forEachMove --- board.h | 55 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 27 deletions(-) (limited to 'board.h') diff --git a/board.h b/board.h index 1ab0646..3b0895d 100644 --- a/board.h +++ b/board.h @@ -3,6 +3,7 @@ #include #include #include +#include #include using namespace std; @@ -37,8 +38,33 @@ struct Board { // F should have a signature compatible with bool F(Move mv). // If the callback returns true, iteration is stopped. // Callback should not modify this Board instance. - template - void forEachMove(int player, F callback) const; + template ::value>> + void forEachMove(int player, F callback) const { + static const int deltas[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; + + for (int y = 0; y < N; y++) + for (int x = 0; x < N; x++) { + uint8_t v = cells[N * y + x]; + if (player == 1 ? v != WHITE && v != KING : v != BLACK) continue; + + for (int i = 0; i < 4; i++) { + int x2 = x + deltas[i][0], y2 = y + deltas[i][1]; + while (x2 >= 0 && x2 < N && y2 >= 0 && y2 < N) { + if (cells[N * y2 + x2] != EMPTY) break; + if (N * y2 + x2 != BOARDMID) { + bool ret = callback(Move(N * y + x, N * y2 + x2)); + if (ret) goto stop_iteration; + } + + x2 += deltas[i][0]; + y2 += deltas[i][1]; + } + } + } + + stop_iteration: ; + } private: Board(); @@ -51,28 +77,3 @@ private: ostream& operator<<(ostream &os, const Move &mv); ostream& operator<<(ostream &os, const Board &bd); - - -template -void Board::forEachMove(int player, F callback) const { - static const int deltas[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; - - for (int y = 0; y < N; y++) - for (int x = 0; x < N; x++) { - uint8_t v = cells[N * y + x]; - if (player == 1 ? v != WHITE && v != KING : v != BLACK) continue; - - for (int i = 0; i < 4; i++) { - int x2 = x + deltas[i][0], y2 = y + deltas[i][1]; - while (x2 >= 0 && x2 < N && y2 >= 0 && y2 < N) { - if (cells[N * y2 + x2] != EMPTY) break; - if (N * y2 + x2 != BOARDMID) { - callback(Move(N * y + x, N * y2 + x2)); - } - - x2 += deltas[i][0]; - y2 += deltas[i][1]; - } - } - } -} -- cgit v1.2.3-70-g09d2