summaryrefslogtreecommitdiffhomepage
path: root/entity_manager.rb
blob: 177ce1a49bf7096b776ca39e7938b671a9c8f39c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class FelFlame
  class Entities
    attr_accessor :id

    def initialize(*signature)
      final_signature = 0
      signature.each do |sig|
        final_signature += sig
      end
      @id = Entities.generate_new_id
      self.class.all.push self
      self.class.signatures.push final_signature
      Components.entity_created(@id)
    end

    class <<self
      # All entities that exist
      def all
        @all ||= []
      end

      def id_queue
        @id_queue ||= []
      end

      def generate_new_id
        if id_queue.empty?
          all.size
        else
          id_queue.shift
        end
      end

      # What components a given entity uses
      def signatures
        @signatures ||= []
      end

      def destroy_entity(entity_id)
        if all[entity_id].nil?
          puts 'Entity can not be destroyed, id out of bounds'
        elsif entity_id < all.size - 1
          Components.constants.each do |constant|
            unless (signatures[entity_id] & Components::const_get(constant).id).zero?
              Components::const_get(constant).delete(entity_id)
            end
          end
          all[entity_id] = nil
          signatures[entity_id] = nil
          id_queue.push entity_id
        elsif entity_id == all.size - 1
          Components.constants.each do |constant|
            unless (signatures[entity_id] & Components::const_get(constant).id).zero?
              Components::const_get(constant).delete(entity_id)
            end
          end
          all.pop
          signatures.pop
        else
          puts 'Unknown error with destroy_entity, entity not destroyed'
        end
      end
    end
  end
end