Author Topic: Maze generator [CMLua]  (Read 2218 times)

Cybermonkey

  • Administrator
  • *****
  • Posts: 0
Maze generator [CMLua]
« on: March 10, 2014, 04:51:32 PM »
Yep, another one from me. Converted from a Pascal program.
Code: [Select]
-- maze.lua
-- just a test

width = 55
height = 41

function init_maze()
     for y = 0 , height - 1 do
         for x = 0 , width - 1 do
            maze[x][y] = 1
         end
  end
end

function carve_maze(x, y)
local      x1, y1 ,x2, y2 , dx, dy, dir, cnt
      dir = int (rnd()*3)+1
      cnt = 0
   while cnt < 4 do
       dx = 0
       dy = 0
       if dir == 0 then
              dx = 1
        elseif dir == 1 then
               dy = 1
         elseif dir == 2 then
                dx = -1
          else  dy = -1
         end
         x1 = x + dx
         y1 = y + dy
         x2 = x1 + dx
         y2 = y1 + dy
         if (x2 > 0) and (x2 < width) and (y2 > 0) and (y2 < height) and (maze[x1][y1] == 1) and (maze[x2][y2] == 1) then
           maze[x1][y1]=0
           maze[x2][y2]=0
            carve_maze(x2, y2)
         end
         dir = (dir + 1) % 4;
         cnt = cnt + 1
      end
   end

function generate_maze()
      maze[1][1] = 0
      carve_maze(1, 1)
      maze[1][0]=0
      maze[width - 1][height - 10]=0
end

function show_maze()
    for j = 0, height - 1 do
         for i = 0, width -1  do
            if maze[i][j] == 0 then
             ink (hrgb (200,200,200))
fillrectangle (i*16,j*16,i*16+16,j*16+16)
            else
               ink (hrgb (20,20,20))
fillrectangle (i*16,j*16,i*16+16,j*16+16)
         end
      end
  end
  ink (hrgb (255,0,0))
  fillrectangle (1*16,0*16,1*16+16,0*16+16)
  ink (0)
  drawtext (1*16,0*16,"S")
  ink (hrgb (0,255,0))
  fillrectangle ((width-1)*16,(height-10)*16,(width-1)*16+16,(height-10)*16+16)
  ink (0)
  drawtext ((width-1)*16,(height-10)*16,"F")
end

maze = {}
for i=0,width do
maze [i]={}
end

repeat
cls()
init_maze()
generate_maze()
show_maze()
ink (65535)
drawtext (0,680,"Press any key for a new maze. Press x to exit.")
key=inkey()
until key == "x"
exit()
Now, guess, what I'll do next ... yes, use the maze generator with the raycaster.  8)