ruben654

ComputerCraft maze generator

Nov 10th, 2012
802
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.10 KB | None | 0 0
  1. location=vector.new(1,0)
  2. dir=0
  3. tArgs={...}
  4. if #tArgs<1 then
  5. print("Usage: mazegen <width> [length]")
  6. return
  7. end
  8. width=tonumber(tArgs[1])
  9. height=tonumber(tArgs[2]) or width
  10. print("Making maze ",width,"x",height)
  11. cells={}
  12.  
  13. for i=0,width+1 do
  14.  cells[i]={}
  15.  for j=0,height+1 do
  16.   cells[i][j]={visited=true,parent=vector.new(),pos=vector.new(i,j),finish=false}
  17.  end
  18. end
  19.  
  20. for i=1,width do
  21. for j=1,height do
  22.  cells[i][j].visited=false
  23. end
  24. end
  25.  
  26. cells[width][height+1].finish=true
  27. cells[width][height+1].visited=false
  28.  
  29. function go(goto)
  30.  local goDir=goto-location
  31.  local tardir=0
  32.  if goDir.x>0 then
  33.   tardir=1
  34.  elseif goDir.x<0 then
  35.   tardir=3
  36.  end
  37.  if goDir.y>0 then
  38.   tardir=0
  39.  elseif goDir.y<0 then
  40.   tardir=2
  41.  end
  42.  while dir~=tardir do
  43.   turtle.turnRight()
  44.   dir=(dir+1)%4
  45.  end
  46.  print(tardir)
  47.  turtle.dig()
  48.  turtle.forward()
  49.  turtle.digUp()
  50.  turtle.dig()
  51.  turtle.forward()
  52.  turtle.digUp()
  53.  cells[goto.x][goto.y].visited=true
  54.  location=goto
  55. end
  56.  
  57. function mazegen(nextpoint)
  58.  cells[nextpoint.x][nextpoint.y].parent=location
  59.  print("Moving forward")
  60.  go(nextpoint)
  61.  if cells[location.x][location.y].finish==true then
  62.   turtle.placeUp()
  63.   print("Found finish")
  64.  else
  65.   local neighbours={cells[nextpoint.x-1][nextpoint.y],cells[nextpoint.x+1][nextpoint.y],cells[nextpoint.x][nextpoint.y-1],cells[nextpoint.x][nextpoint.y+1]}
  66.   local unvisited={}
  67.   for i,v in ipairs(neighbours) do
  68.    if v.visited==false then
  69.     table.insert(unvisited,v)
  70.    end
  71.   end
  72.   while #unvisited>0 do
  73.    local randomnum=math.random(1,#unvisited)
  74.    if cells[unvisited[randomnum].pos.x][unvisited[randomnum].pos.y].visited==false then
  75.     print("New branch at "..tostring(unvisited[randomnum].pos))
  76.     mazegen(unvisited[randomnum].pos)
  77.    end
  78.    table.remove(unvisited,randomnum)
  79.    print(#unvisited .." left")
  80.   end
  81.  end
  82.  print("Backtracking to "..tostring(cells[location.x][location.y].parent))
  83.  go(cells[location.x][location.y].parent)
  84. end
  85.  
  86. mazegen(vector.new(1,1))
  87. turtle.turnRight()
  88. turtle.turnRight()
  89. file=fs.open("mazeblueprint","w")
  90. file.write(textutils.serialize(cells))
  91. file.close()
Advertisement
Add Comment
Please, Sign In to add comment