Map.lua 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. -- ================
  2. -- Private helpers
  3. -- ================
  4. local setmetatable = setmetatable
  5. -- Internal class constructor
  6. local class = function(...)
  7. local klass = {}
  8. klass.__index = klass
  9. klass.__call = function(_,...) return klass:new(...) end
  10. function klass:new(...)
  11. local instance = setmetatable({}, klass)
  12. klass.__init(instance, ...)
  13. return instance
  14. end
  15. return setmetatable(klass,{__call = klass.__call})
  16. end
  17. local Map = class()
  18. Map.__tostring = function(m) return ('Map %dx%d'):format(m.width, m.height) end
  19. function Map:__init(w, h)
  20. self.width, self.height = w, h
  21. self.tiles = {}
  22. for y=0,h-1 do
  23. self.tiles[y] = {}
  24. for x=0,w-1 do
  25. self.tiles[y][x] = 1
  26. end
  27. end
  28. end
  29. function Map:print()
  30. for y=0,self.height-1 do
  31. line = ''
  32. for x=0,self.width-1 do
  33. if self.tiles[y][x] == 1 then
  34. line = line..'#'
  35. elseif self.tiles[y][x] == 2 then
  36. line = line..'.'
  37. else
  38. line = line..' '
  39. end
  40. end
  41. print(line)
  42. end
  43. end
  44. function Map:carve(room)
  45. local rx, ry = math.floor(room.x), math.floor(room.y)
  46. if rx <= 0 or ry <= 0 or rx >= self.width-room.width-1 or ry >= self.height-room.height-1 then return end
  47. self.tiles[ry][rx] = 2
  48. for y=ry, ry+room.height-1 do
  49. for x=rx, rx+room.width-1 do
  50. self.tiles[y][x] = 0
  51. end
  52. end
  53. end
  54. function Map:toArray()
  55. local a = {}
  56. for y=0,self.height do
  57. for x=0,self.width do
  58. table.insert(a, self.tiles[y][x])
  59. end
  60. end
  61. return a
  62. end
  63. return Map