How would I go about making a door opening logic for my game?

Hello,

While making my escape room game I have ran into a problem. I’m stupid :face_with_diagonal_mouth:. Here’s the problem: I have some variables containing conditions (I try to write clean code :confounded:) that need to be checked to open a door. I just can’t find an elegant way of doing that :man_shrugging:.

-- The variables (I have removed the conditions for simplicity)

local doorIsOpen

local powerIsRequired
local powerIsTurnedOn

local doorIsLocked
local playerHasKey

local doorRequiresKeyPad
local keyPadIsUnlocked

All of these variables are available for use, and I need to check all the unique combinations possible :sweat_smile: , e.g.

if not doorIsOpen and powerIsRequired and powerIsTurnedOn and not doorRequiresKeyPad then

	-- Open door

elseif not doorIsOpen and doorRequiresKeyPad and keyPadIsUnlocked and powerIsRequired and powerIsTurnedOn then

	-- Open door

end

I assume that you now see the problem. Any ideas?

You can quit early if a necessary condition isn’t there:

if doorIsOpen then return end
if powerIsRequired and not powerIsTurnedOn then return end
if doorRequiresKeyPad and not keyPadIsUnlocked then return end

-- open door

Otherwise you can nest things and use or cleverly:

if not doorIsOpen then
  if not powerIsRequired or powerIsTurnedOn then
    if not doorRequiresKeyPad or keyPadIsUnlocked then
      -- open door
    end
  end
end

The first way is more readable IMO but it depends

1 Like

A great answer within a decent 5 minutes, bravo sir :star:. I also prefer the first one, because the nesting just clutters the code :face_vomiting:. Thanks for helping :kissing_heart:!