In a part of the book I am reading I need to rewrite a "Labyrinth" game that uses goto
sentences to another that does not use them.
The labyrinth is very simple, it only has 4 rooms and it starts from room # 1:
---------
| 1 | 2 |
---------
| 3 | 4 |
---------
This is the original version of the book using goto
:
goto room1 -- initial room
::room1:: do
local move = io.read()
if move == "south" then goto room3
elseif move == "east" then goto room2
else
print("invalid move")
goto room1 -- stay in the same room
end
end
::room2:: do
local move = io.read()
if move == "south" then goto room4
elseif move == "west" then goto room1
else
print("invalid move")
goto room2
end
end
::room3:: do
local move = io.read()
if move == "north" then goto room1
elseif move == "east" then goto room4
else
print("invalid move")
goto room3
end
end
::room4:: do
print("Congratulations, you won!")
end
And this is my attempt to rewrite it:
local rooms = {}
rooms[1] = {
south=3,
east=2
}
rooms[2] = {
south=4,
west=1
}
rooms[3] = {
north=1,
east=4
}
currentRoom = 1
repeat
local move = io.read()
local room = rooms[currentRoom][move]
if room == nil then
room = currentRoom
print("Invalid move")
elseif room == 4 then
print("Congratulations, you won!")
end
currentRoom = room or currentRoom
until currentRoom == 4
In this case I found it more appropriate to use repeat
instead of while
although in this specific case I think both work the same.
Is my solution the most optimal or could I change something in my code to improve it?