Maze_generator.cpp 2.24 KiB
#include <vector>
#include <iostream>
static void pop(std::vector<std::vector<size_t>>& coords, size_t y, size_t x) {	//удаляет из вектора точку с координатами x, y
	for (auto it = coords.begin(); it != coords.end(); ++it) {
		if (it->at(0) == y && it->at(1) == x) {
			coords.erase(it);
			return;
static void wall_builder(std::vector<std::vector<bool>>& field, std::vector<std::vector<size_t>>& coords, const size_t& dir, size_t& x, size_t& y) {
	do {	//0 - верх, 1 - право, 2 - низ, 3 - влево
		switch (dir) {
		case 0:
			field.at(y - 1).at(x) = 1;
			y -= 2;
			break;
		case 1:
			field.at(y).at(x + 1) = 1;
			x += 2;
			break;
		case 2:
			field.at(y + 1).at(x) = 1;
			y += 2;
			break;
		case 3:
			field.at(y).at(x - 1) = 1;
			x -= 2;
			break;
		if (x <= 0 || y <= 0 || x > field.at(0).size() - 2 || y > field.size() - 2 || field.at(y).at(x) == 1) {
			break;
		else {
			field.at(y).at(x) = 1;
			pop(coords, y, x);
	} while (rand() % 100 < 50);
static auto generate(size_t height, size_t width) {
	std::vector<std::vector<bool>> field(height + 2, std::vector<bool>(width + 2));
	for (size_t i = 0; i < height + 2; ++i) {
		field.at(i).at(0) = 1;
		field.at(i).at(width + 1) = 1;
	for (size_t j = 0; j < width + 2; ++j) {
		field.at(0).at(j) = 1;
		field.at(height + 1).at(j) = 1;
	std::vector<std::vector<size_t>> coords;
	for (size_t i = 2; i < height; i += 2) {
		for (size_t j = 2; j < width; j += 2) {
			std::vector<size_t> pair = { i,j };
			coords.push_back(pair);
	while (!coords.empty()) {
		size_t y = coords.front().at(0), x = coords.front().at(1);
		if (field.at(y).at(x)) {
			continue;
		pop(coords, y, x);
71727374757677787980818283848586
field.at(y).at(x) = 1; size_t dir = rand() % 4; wall_builder(field, coords, dir, x, y); //строим стену в этом направлении } return field; } static size_t room_number(const std::vector<bool>& row, size_t ind) { //по индексу в строке поля возвращает номер комнаты в векторе size_t num = 0; for (size_t i = 0; i < ind; ++i) { //не включаем ind, чтобы получить именно индекс комнаты if (row.at(i)==0) ++num; } return num; }