summaryrefslogtreecommitdiff
path: root/app/models/monster_spawn.rb
blob: 42db98a4f01d28ddde515bbf0b4f3036721b82d0 (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
class MonsterSpawn < ApplicationRecord
  belongs_to :monster
  belongs_to :location
  has_many :monster_spawn_combats

  after_initialize :set_starting_hp
  after_create :send_chat_message

  validates :starting_hp, presence: true, numericality: { greater_than_or_equal_to: 1, only_integer: true }
  validate :one_living_leviathan_per_location, on: :create

  def alive?
    self.remaining_hp > 0
  end

  def remaining_hp
    self.starting_hp - MonsterSpawnCombat.where(monster_spawn: self).sum(:hp_lost)
  end

  private
    def set_starting_hp
      self.starting_hp = monster.max_hp
    end

    def send_chat_message
      chat_message = ChatMessage.new(body: "A leviathan has appeared in #{location.name}!",
                                     chat_room: ChatRoom.find_by_gid("news"))
      if chat_message.save
        ChatRoomChannel.broadcast_chat_message(chat_message)
      end
    end

    def one_living_leviathan_per_location
      # TODO: Don't load into memory
      if location.monster_spawns.find { |ms| ms.alive? && ms != self }
        errors.add(:chat, "A location can only have one monster spawn at a time.")
      end
    end
end