From 176d6141c87a180b251bacaee656808bad17498b Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 13 Feb 2022 20:54:02 +0100 Subject: refactor: add random number generation abstraction --- src/maze.tpp | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'src/maze.tpp') diff --git a/src/maze.tpp b/src/maze.tpp index 19390cc..2edb60d 100644 --- a/src/maze.tpp +++ b/src/maze.tpp @@ -22,7 +22,9 @@ std::vector> get_neighbours(Matrix *matrix, auto pos_down = (*pos - Vector2(0U, 2U)).copy(); if (matrix->get(*pos_down) != space_element) + { neighbours.push_back(pos_down); + } } if (pos->y() != matrix->rows() - 2U) @@ -30,7 +32,9 @@ std::vector> get_neighbours(Matrix *matrix, auto pos_up = (*pos + Vector2(0U, 2U)).copy(); if (matrix->get(*pos_up) != space_element) + { neighbours.push_back(pos_up); + } } if (pos->x() != 1U) @@ -38,7 +42,9 @@ std::vector> get_neighbours(Matrix *matrix, auto pos_left = (*pos - Vector2(2U, 0U)).copy(); if (matrix->get(*pos_left) != space_element) + { neighbours.push_back(pos_left); + } } if (pos->x() != matrix->columns() - 2U) @@ -46,7 +52,9 @@ std::vector> get_neighbours(Matrix *matrix, auto pos_right = (*pos + Vector2(2U, 0U)).copy(); if (matrix->get(*pos_right) != space_element) + { neighbours.push_back(pos_right); + } } return neighbours; @@ -75,14 +83,19 @@ void pos_to_between(std::shared_ptr between_pos, unsigned int coord, unsigned int away_coord, Vector2 diff) { if (away_coord > coord) + { *between_pos += diff; + } else + { *between_pos -= diff; + } } template void matrix_to_maze(Matrix *matrix, std::shared_ptr start_pos, - Element space_element, std::mt19937 random_gen) + Element space_element, + std::shared_ptr random_gen) { Stack> path_stack(get_maze_size(matrix)); @@ -95,13 +108,14 @@ void matrix_to_maze(Matrix *matrix, std::shared_ptr start_pos, matrix->set(*pos, space_element); - std::vector> neighbours = - get_neighbours(matrix, pos, space_element); + auto neighbours = get_neighbours(matrix, pos, space_element); if (neighbours.empty()) { if (visited_pos_cnt == get_maze_size(matrix) - 1U) + { break; + } // Go back a step path_stack.pop(); @@ -110,18 +124,20 @@ void matrix_to_maze(Matrix *matrix, std::shared_ptr start_pos, visited_pos_cnt++; - auto random_dist = std::uniform_int_distribution( - 0U, static_cast(neighbours.size()) - 1U); - - auto next_pos = neighbours[random_dist(random_gen)]; + auto next_pos = neighbours[random_gen->in_range( + 0U, static_cast(neighbours.size()) - 1U)]; auto between_pos = pos->copy(); if (next_pos->y() != pos->y()) + { pos_to_between(between_pos, pos->y(), next_pos->y(), Vector2(0U, 1U)); + } if (next_pos->x() != pos->x()) + { pos_to_between(between_pos, pos->x(), next_pos->x(), Vector2(1U, 0U)); + } matrix->set(*between_pos, space_element); -- cgit v1.2.3-18-g5258