1

I've been trying to create a Procedurally Generated Dungeon, as seen in this article. But that was a little to hard for me to understand the working this type of algorithm. So instead, I've been using this as a guide to at least understand the room placement.

The program used in the article is made in Java, so I made some adaptations to my "reality", and tried to emulate the same results in Python 3.5.

My code is as follows:

from random import randint


class Room:

    """docstring for Room"""

    def __init__(self, x, y, w, h):
        """[summary]

        [description]

        Arguments:
                x {int} -- bottom-left horizontal anchorpoint of the room
                y {int} -- bottom-left vertical anchor point of the room
                w {int} -- width of the room
                h {int} -- height of the room
        """
        self.x1 = x
        self.x2 = x + w
        self.y1 = y
        self.y2 = y + h
        self.w = w
        self.h = h
        self.center = ((self.x1 + self.x2)/2, (self.y1 + self.y2)/2)

    def intersects(self, room):
        """[summary]

        Verifies if the rooms overlap

        Arguments:
                room {Room} -- a room object
        """
        return(self.x1 <= room.x2 and self.x2 >= room.x1 and \
               self.y1 <= room.y2 and self.y2 >= room.y1)

    def __str__(self):
        room_info = ("Coords: (" + str(self.x1) + ", " + str(self.y1) +
                     ") | (" + str(self.x2) + ", " + str(self.y2) + ")\n")
        room_info += ("Center: " + str(self.center) + "\n")
        return(room_info)

MIN_ROOM_SIZE = 10
MAX_ROOM_SIZE = 20
MAP_WIDTH = 400
MAP_HEIGHT = 200
MAX_NUMBER_ROOMS = 20

dungeon_map = [[None] * MAP_WIDTH for i in range(MAP_HEIGHT)]
# print(dungeon_map)


def crave_room(room):
    """[summary]

    "saves" a room in the dungeon map by making everything inside it's limits 1

    Arguments:
            room {Room} -- the room to crave in the dungeon map
    """
    for x in xrange(min(room.x1, room.x2), max(room.x1, room.x2) + 1):
        for y in xrange(min(room.y1, room.y2), max(room.y1, room.y2) + 1):
            print(x, y)  # debug
            dungeon_map[x][y] = 1
    print("Done")  # dungeon


def place_rooms():

    rooms = []

    for i in xrange(0, MAX_NUMBER_ROOMS):
        w = MIN_ROOM_SIZE + randint(0, MAX_ROOM_SIZE - MIN_ROOM_SIZE + 1)
        h = MIN_ROOM_SIZE + randint(0, MAX_ROOM_SIZE - MIN_ROOM_SIZE + 1)
        x = randint(0, MAP_WIDTH - w) + 1
        y = randint(0, MAP_HEIGHT - h) + 1

        new_room = Room(x, y, w, h)
        fail = False
        for other_room in rooms:
            if new_room.intersects(other_room):
                fail = True
                break
        if not fail:
            print(new_room)
            crave_room(new_room)  # WIP
            new_center = new_room.center
            # rooms.append(new_room)
            if len(rooms) != 0:
                prev_center = rooms[len(rooms) - 1].center

                if(randint(0, 1) == 1):
                    h_corridor(prev_center[0], new_center[0], prev_center[1])
                    v_corridor(prev_center[1], new_center[1], prev_center[0])
                else:
                    v_corridor(prev_center[1], new_center[1], prev_center[0])
                    h_corridor(prev_center[0], new_center[0], prev_center[1])
        if not fail:
            rooms.append(new_room)
    for room in rooms:
        print(room)


def h_corridor(x1, x2, y):
    for x in xrange(min(x1, x2), max(x1, x2) + 1):
        dungeon_map[x][y] = 1


def v_corridor(y1, y2, x):
    for y in xrange(min(y1, y2), max(y1, y2) + 1):
        dungeon_map[x][y] = 1

place_rooms()

but whenever I run it, I get the following error:

Traceback (most recent call last):
  File "/home/user/dungeon.py", line 114, in <module>
    place_rooms()
  File "/home/user/dungeon.py", line 87, in place_rooms
    crave_room(new_room)  
  File "/home/user/dungeon.py", line 65, in crave_room
    dungeon_map[x][y] = 1
IndexError: list index out of range

For what I understood from my code, the crave_room function should work correctly, since I'm using the min and max functions. And since the h_corridor and v_corridor functions work in a similar way They present the same kind of problem.

I'm not sure if the problem is happening due the fact that I'm using a matrix as a substitute to the canvas used in the original article. I was suspecting a local/global variable problem, but I don't think that's the problem. I'm afraid I'm making a very stupid mistake and not seeing it.

Any code improvement tips or suggestions about better data structures to use will be welcome, and if anyone has, a more clearer/simpler article in the subject, preferably on Python, I saw a lot of the related posts in here, but I'm still kind of lost.

Thanks for any help. :D

inblank
  • 396
  • 1
  • 8
  • 26
  • 5
    Probably not related to your problem, but `dungeon_map = [[None] * MAP_WIDTH] * MAP_HEIGHT` is going to cause trouble later on. For more information, see [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/q/240178/953482) – Kevin Oct 04 '16 at 13:17
  • Wild guess: try making the matrix one row/column taller/wider. `dungeon_map = [[None] * (MAP_WIDTH+1) for _ in range(MAP_HEIGHT+1)] ` – Kevin Oct 04 '16 at 13:23
  • thanks, I wasn't aware of that. I'll update the code. – inblank Oct 04 '16 at 13:23
  • @Kevin that didn't work, I tried it as my first guess, but when I put a debug print in the middle I saw that wasn't the problem. – inblank Oct 04 '16 at 13:26
  • 1
    Just another hint: Use numpy and it's arrays instead lists of lists especially if you plan on doing operations on them later on. – Dschoni Oct 04 '16 at 13:28
  • 2
    All I can say is that your function that is supposed to place the room.x in bound of `dungeon_map` size is not working at all. You've a matrix with 200 rows, while your `room.x` is reaching from 350 - 370. Your `MAP_WIDTH` value is 400 (thats the problem) – Nf4r Oct 04 '16 at 13:28
  • 1
    Maybe you'd be better off with a data structure that lets you assign values to any coordinates without you having to specify spatial boundaries ahead of time. Try `import collections` and `dungeon_map = collections.defaultdict(dict)`. – Kevin Oct 04 '16 at 13:30
  • The `min` and `max` conditions in `crave_room` are useless. By construction, `room.x1 < room.x2` (same for the y-axis). And I think the two `+1` are the reasons of errors. If your room begins at `x1=10` and end at `x2 = 20`, its "indexes" in `dungeon_map` will range from 9 to 19. – Daneel Oct 04 '16 at 13:33
  • @Nf4r thanks for pointing that out, I did transpose the matrix by mistake, so instead of being a 400 * 200 matrix, it was a 200 * 400. – inblank Oct 04 '16 at 13:36
  • so changing it to `collections` worked, at least I'm not getting any errors. But now, the matrix was acting as a "grid" where my rooms and corridors where being placed, will it work in the same way? – inblank Oct 04 '16 at 13:44

1 Answers1

1

You have your dungeon_map declared incorrectly:

dungeon_map = [[None] * MAP_WIDTH] * MAP_HEIGHT

The correct way should be:

dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH

Now that you done that, let's take a look at the second, more serious problem. Let's have an experiment in smaller scale (smaller map):

MAP_WIDTH = 4
MAP_HEIGHT = 2
dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH

print('\nBefore Assignment:')
print(dungeon_map)

dungeon_map[2][1] = 'y'

print('\nAfter Assignment:')
print(dungeon_map)

In this experiment, we created a 4 column x 2 row matrix and we alter the value of one cell, so let's take a look at the output:

Before Assignment:
[[None, None], [None, None], [None, None], [None, None]]

After Assignment:
[[None, 'y'], [None, 'y'], [None, 'y'], [None, 'y']]

What is going on? Essentially, you declare the same list, MAP_WIDTH times. The declaration line below is convenient and clever, but incorrect:

dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH

The correct way to declare such a matrix is:

dungeon_map = [[None for x in range(MAP_HEIGHT)] for y in range(MAP_WIDTH)]
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • Thanks for the answer, I wasn't aware about the addressing problem. Now that's fixed I'll proceed to improve the code and optmize it. – inblank Oct 05 '16 at 00:17