Bladeren bron

Move the board generation in a dedicated method

Make the code more modular and the default constructor without any argument
DricomDragon 5 jaren geleden
bovenliggende
commit
5ff872b9b9
1 gewijzigde bestanden met toevoegingen van 38 en 20 verwijderingen
  1. 38 20
      main.cc

+ 38 - 20
main.cc

@@ -49,7 +49,7 @@ class World
 		unsigned int h;
 
 		// Size of the array
-		const unsigned int size;
+		unsigned int size;
 
 		// Unidimensional array for tiles
 		int* board;
@@ -58,26 +58,54 @@ class World
 		unsigned int tileQuantity;
 
 	public:
-		// Constructor
-		World(unsigned int l_, unsigned int h_, double p)
-			:l(l_), h(h_), size(l_ * h_), tileQuantity(l_ * h_)
+		// Default constructor
+		World()
+			:l(0), h(0), size(0), board(nullptr), tileQuantity(0)
+		{}
+
+		// Copy constructor
+		World(const World& other)
+			:l(other.l), h(other.h), size(other.size), tileQuantity(other.tileQuantity)
 		{
 			board = new int[size]();
 
+			for (int k(0); k < size; k++) {
+				board[k] = other.board[k];
+			}
+		}
+
+		// Random generation
+		void generate(unsigned int l_, unsigned int h_, double p)
+		{
+			// Error if board exists
+			if (board != nullptr)
+				cerr << "Can't generate world, board already exists" << endl;
+
+			// Initialize attributes
+			l = l_;
+			h = h_;
+			size = l * h;
+			tileQuantity = size;
+
+			board = new int[size]();
+
+			// Add floor everywhere
+			for (unsigned int k(0); k < size; k++)
+				board[k] = FREE;
+
 			// Add walls to the first and last columns
-			for (unsigned int i = 0; i < h; i++)
-			{
+			for (unsigned int i(0); i < h; i++) {
 				markOne(i * l, WALL);
 				markOne(i * l + l - 1, WALL);
 			}
 
 			// Add walls to the first and last lines
-			for (unsigned int j = 0; j < l; j++)
-			{
+			for (unsigned int j = 0; j < l; j++) {
 				markOne(j, WALL);
 				markOne((h - 1) * l + j, WALL);
 			}
 
+			// Randomly add walls
 			for (unsigned int i = 0; i < h; i++)
 			{
 				for (unsigned int j = 0; j < l; j++)
@@ -90,17 +118,6 @@ class World
 			}
 		}
 
-		// Copy constructor
-		World(const World& other)
-			:l(other.l), h(other.h), size(other.size), tileQuantity(other.tileQuantity)
-		{
-			board = new int[size]();
-
-			for (int k(0); k < size; k++) {
-				board[k] = other.board[k];
-			}
-		}
-
 		// Display the world
 		void display()
 		{
@@ -386,7 +403,8 @@ int main()
 	const unsigned int l(DEFAULT_LENGTH), h(DEFAULT_HEIGHT);
 	const double wallProbability(DEFAULT_PROBABILITY);
 
-	World w(l, h, wallProbability);
+	World w;
+	w.generate(l, h, wallProbability);
 
 	unsigned int start(identifyTile(1, 1, l));
 	unsigned int end(identifyTile(h - 2, l - 2, l));