问题
Here's what I'm trying to do: I have a class called RandomRoomGenerator, which has a method called GenerateRoom. This GenerateRoom method is called inside my main method based on the grid size(the width or height) multiplied by itself to get the total number of rooms. The method itself creates a new room with parameters chosen randomly from my ItemDB and RandomRoomValues. The problem is, I need a way to generate the room's position without it overlapping previously generated rooms. So far I am only able to return 1 random value, which is copied however many times over and over again. Everything else is fine, but I would like a bit of clarification on how Random works in C#. In my GenerateRandomItems method, when I set the first .Next() parameter to 0, it would never return an item, no matter how large the max value was. Here's my RandomRoomGenerator class:
public class RandomRoomGenerator
{
public Room GenerateRoom(int gridSize, ref List<Room> rooms)
{
RandomRoomDescriptions randomRoomDescriptions = new RandomRoomDescriptions();
ItemDB itemDb = new ItemDB();
string description = randomRoomDescriptions.roomDescriptions[new Random().Next(0, randomRoomDescriptions.roomDescriptions.Count)];
Room room = new Room(description, GenerateXPos, GenerateYPos, new Random().Next(1, 7), new Random().Next(1, 7), new Random().Next(1, 7), GenerateRandomItems(itemDb));
return room;
}
private List<Item> GenerateRandomItems(ItemDB itemDb)
{
List<Item> items = new List<Item>();
for (int i = 0; i < new Random().Next(0, 2); i++)
{
items.Add(itemDb.healItems[new Random().Next(0, itemDb.healItems.Count)]);
}
for (int i = 0; i < new Random().Next(0, 2); i++)
{
items.Add(itemDb.cleanseItems[new Random().Next(0, itemDb.cleanseItems.Count)]);
}
for (int i = 0; i < new Random().Next(0, 2); i++)
{
items.Add(itemDb.foodItems[new Random().Next(0, itemDb.foodItems.Count)]);
}
for (int i = 0; i < new Random().Next(0, 2); i++)
{
items.Add(itemDb.drinkItems[new Random().Next(0, itemDb.drinkItems.Count)]);
}
return items;
}
}
来源:https://stackoverflow.com/questions/61980644/making-a-console-app-game-how-would-i-randomly-generate-the-positions-of-rooms