Шукати в цьому блозі

Генерація випадкового лабіринту

Синтаксис: Lua
labirint=""
line = {}
math.randomseed(os.time())
--------------------------------------------
width, height = 20,20    -- розмір лабіринту
--------------------------------------------
for i = 1, width, 1 do
 labirint=labirint.."._"                    -- write the top line
 line[i] = {left = i, right = i } -- init the linked lists
end

labirint=labirint..".\n"

line[width+1] = {left = tonumber(width)} -- secure a border case behavior

for j = 1, height, 1 do
   labirint=labirint.."|" -- ліва стінка
  for i = 1, width, 1 do
    right, down = "|", " " -- defaults, no change to the list structure
    if line[i+1].left ~= i then
      -- consider skipping a wall here, as that won't make a cycle
      if (== tonumber(height) and line[i].left == i) or
         math.random() < 0.5 then
        right = "."
        -- join the lists of i and i+1
        -- the combined list will be circularly ordered; that's not true
        -- for such lists in general, but follows here from
        -- nontrivial properties of the two lists deriving from their
        -- meaning (they can't "interleave")
        line[line[i+1].left].right = line[i].right
        line[line[i].right].left = line[i+1].left
        line[i].right, line[i+1].left = i+1, i
      end
    end
    if j == tonumber(height) -- last line
       or (line[i].left ~= i and math.random() < 0.5) then
      down = "_"
      -- tear this cell out of its list
      line[line[i].left].right = line[i].right
      line[line[i].right].left = line[i].left
      line[i].left, line[i].right = i, i
    end
 labirint=labirint..(down..right)
  end
 labirint=labirint.."\n"
end

print(labirint)

лабіринт виведено в консоль
Код:
_._._._._._._._._._._._._._._._._._._._.
| |_. ._| . | ._._._. ._. ._._| |_. . . |
| | | . . | | | |_. |_|_. |_. |_. | |_| |
|_. |_| | | ._| | . | . . | | | . ._| |_|
| | |_. |_| | | . | |_| |_. | . |_. |_. |
|_. | ._|_._._._|_| ._| ._|_|_|_. | ._| |
| . | ._._| |_. ._| | |_| |_. . | |_. . |
| |_._. | ._| | . |_. | | ._._| ._._|_| |
| | | | . | | | |_._. . ._|_._. | |_. . |
|_|_. | |_| ._|_. | |_|_. ._._|_._| |_|_|
| | |_. ._|_._. |_|_._. ._| . ._| | |_. |
| | | | | |_. | ._| | | | |_| | | ._| | |
| . . ._. . | . . | . ._. . | | . | ._| |
| |_| . |_| | | |_._| |_._|_. ._| | | | |
| ._|_|_._| |_| . | . ._. |_. |_._._. ._|
|_| | | | | |_. | |_| ._|_. | ._| ._|_| |
|_. | |_._._| |_|_._|_| | |_| . | | | ._|
| |_. . | |_. ._. | | | |_._._| . | | | |
| | ._|_._._| | |_._| | | | . | | ._|_. |
|_. . |_. | | ._. | | . | | |_. |_. | | |
|_._|_._._._._._|_._._|_._._._|_._|_._._|

Немає коментарів:

Дописати коментар