How do I search for the player's room from another room?

  1. What do you want to achieve?
    I want to find the player’s room from a specific room by looping through the possible ways to get there.

  2. What is the issue?
    I need to use recursion for that, but it keeps failing and I’m not sure what to do :frowning:

  3. What solutions have you tried so far?
    I tried searching for recursion tutorials but have found none that answer my question.

Since it sounds confusing, the rooms that I’m talking about are not actually 3D spaces, but rather blocks of code that have possible “pathways” to get to other rooms.

Here’s an example:
Room1 is a room, and the player can pass onto the following rooms:

  • Room2
  • Hallway1

Room2 is also a room, and the player can pass onto these ones:

  • Room1
  • Hallway2

image

Every room’s pathway is an attribute that leads to the other room.
Example:

Room1 = {
	"Room2",
	"Hallway1"
}

Room2 = {
	"Room1",
	"Hallway2"
}

Hallway1 = {
	"Room1"
}

Hallway2 = {
	"Room2"
}

Let’s say that the player’s current room is Hallway1, and I want a script to find the path to that room from Room2.
What it will do is search through the possible ways Room2 offers, check through every room if the path is available, and if not proceed to the next possible room.

for RoomName,Value in pairs(CurrentRoom:GetChildren()) do
	local PassageRoom = Rooms:FindFirstChild(RoomName)
	if PassageRoom then
		if PassageRoom == PlayerRoom then
			return PassageRoom -- Found the player's room!!
		else
			SearchNextRoom(PassageRoom) -- Search the current room in the loop for the next rooms that can lead to the player's room.
		end
	end
end

TL;DR:
How do I find the current room of the player, by starting from a specific room and looping through the possible rooms the script can go through?

Am I doing something wrong in the recursion?
Is this even recursion at all and I’m using the term in the wrong way?

Thanks for reading :slight_smile:

1 Like

Apparently I had to check if the room was found instead of instantly returning it, and it worked out by talking about it with my friend :slight_smile:
I guess the “Talk to the duck” technique really works!

local function SearchPlayerRoom(CurrentRoom,SearchedRooms)
	table.insert(SearchedRooms,CurrentRoom)
	for RoomName,Value in pairs(CurrentRoom:GetAttributes()) do
		local PassageRoom = Fold_Rooms:FindFirstChild(RoomName)
		if PassageRoom and not table.find(SearchedRooms,PassageRoom) then
			if PassageRoom == Room then
				return PassageRoom
			else
				local FoundRoom = SearchPlayerRoom(PassageRoom,SearchedRooms)
				if FoundRoom then
					print(PassageRoom)
					return FoundRoom
				end
			end
		end
	end
end