I’m programming a Dungeon Generator for a litte game.
Dungeons are made of rooms. A room has connections to other rooms.
room.connections = [room_a, room_b]
and
room.number = 1 # unique id
Now I need to pick a room by it’s number.
I did this first with a recursive_scan method, which did not work because rooms can lead into circles, which throws a StackOverflowError. So I put an array called already_scanned with the room numbers, which were already picked into the args of the method. Then it didn’t scan all rooms – btw, I have no idea why, by my logical undstandness it should have worked.
Then I tried to put all rooms also in an array and then iterate the array for the wanted room – but here I get the problem, every room is basically connected to every other room, at least with some other rooms betwenn it; so the array gets as big as dungeon_size * array_of_rooms.length.
What I need now is an explicit pointer – I know almost every var in ruby is a pointer, except Fixnums and Float (and maybe some other). Even though, the array gets to big, so I need a real pointer.
(I also tried to setup an array of object_ids and load them via ObectSpace, but sadly – because I often have to load the rooms – the rooms with the wanted object_id are already recycled then, as an error message explains.)
This is my recursive scan method:
def room(number)
recursive_scan(@map, number, []) # @map is the entrance room
end
private
def recursive_scan(room, number, scanned)
scanned << room.room_number
if room.room_number == number
room
else
r = nil
room.connections.each do |next_room|
if !scanned.include?(next_room.room_number)
r = recursive_scan(next_room, number, scanned)
end
end
r
end
end
Everything in Ruby is already a reference.
Why not just maintain a room index?
Then you can get anything with
rooms[i]. I would keep the index up to date incrementally by simply modifying the initialize method of Room.This won’t take up much space because the array is just an index, it doesn’t actually have copies of the rooms. Each reference obtained from the array is essentially the same thing as a reference obtained via any other mechanism in your program, and the only real difference between the reference and a classic pointer is a bit of overhead for garbage collection.
If rooms are ever deleted (other than just before exit) you will want to set the
rooms[x] = nilwhen on deletion.I don’t see why you need to create the data structure first and then index the rooms, but FWIW you should be able to do that recursive enumeration and use the rooms presence in the room index array as the been-here flag. I’m not sure why it didn’t work before but it really has to if written carefully.