store.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # some more OO wrappers for the low level store functionality
  2. # How to organise the game state, loaded data, etc in a neat way?
  3. # Use a central repository or per type/class repositories???
  4. # -> use per type registries for ease of use.
  5. # In a central repository it's neccessary to do something like
  6. # Repo[:font_tuffy]
  7. # withe with per-type repos I can say
  8. # Font[:tuffy] with is more compact and clear.
  9. # Store items will have to be maintained both in
  10. # Store by ID and in the relevant subclass
  11. script 'registry.rb'
  12. class Store
  13. attr_reader :id
  14. attr_reader :name
  15. attr_reader :vpath
  16. extend Registry
  17. # Initialize a storage item.
  18. def initialize(id, name, vpath = nil)
  19. @id = id
  20. @name = name
  21. @vpath = vpath
  22. end
  23. # Load helper
  24. def self.load_something(name, vpath, klass = nil, &block)
  25. # Need to drop first or get_unusedid will not cotrrectly reuse the dropped id
  26. Store[name].drop! if Store[name]
  27. id = Eruta::Store.get_unused_id(1000)
  28. return nil if id < 0
  29. res = block.call(id)
  30. return nil unless res
  31. klass ||= self
  32. loaded = klass.new(id, name)
  33. Store.register(loaded, id, name)
  34. return loaded
  35. end
  36. # Loads a tile map
  37. def self.load_tilemap(name, vpath)
  38. load_something(name, vpath) do | nid |
  39. Eruta::Store.load_tilemap(nid, vpath)
  40. end
  41. end
  42. # type numbers
  43. NONE = 0
  44. BITMAP = 1
  45. FONT = 2
  46. AUDIO_STREAM = 3
  47. SAMPLE = 4
  48. CONFIG = 5
  49. OTHER = 8
  50. TILEMAP = 9
  51. # The type number of the stored object
  52. def kind
  53. return Eruta::Store.kind(@id)
  54. end
  55. # Drops this object from storage
  56. def drop!
  57. res = Eruta::Store.drop(@id)
  58. Store.unregister(self)
  59. return res
  60. end
  61. # extend this module to makea class forward it's load, drop! and lookup calls
  62. module Forward
  63. def forward_name(name)
  64. return self.to_s.downcase + '_' + name.to_s
  65. end
  66. def [](name)
  67. return Store[forward_name(name)]
  68. end
  69. def drop!(name)
  70. obj = self[name]
  71. obj.drop! if obj
  72. end
  73. end
  74. end