Making a console-app game, how would I randomly generate the positions of Rooms?

泄露秘密 提交于 2021-01-29 15:18:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!