From ac1790f76d843ed125ffeac6962f50504f1bf559 Mon Sep 17 00:00:00 2001 From: David Gay Date: Sun, 23 May 2021 19:01:19 -0400 Subject: Send achievement channel text messsage when someone levels up --- app/models/character.rb | 6 +++++- app/models/character_skill.rb | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) (limited to 'app/models') diff --git a/app/models/character.rb b/app/models/character.rb index fd0f540..a6e8ff6 100644 --- a/app/models/character.rb +++ b/app/models/character.rb @@ -93,7 +93,11 @@ class Character < ApplicationRecord def add_skill_xp(skill, amount) skill = Skill.find_by_gid(skill) if skill.is_a? String - CharacterSkill.find_by(skill: skill).increment!(:xp, amount) + Character.transaction do + cs = CharacterSkill.find_by(skill: skill) + cs.xp += amount + cs.save! + end end def skill_level(skill) diff --git a/app/models/character_skill.rb b/app/models/character_skill.rb index 189f386..20468c3 100644 --- a/app/models/character_skill.rb +++ b/app/models/character_skill.rb @@ -4,6 +4,8 @@ class CharacterSkill < ApplicationRecord validates :skill_id, uniqueness: { scope: :character_id } validates :xp, numericality: { greater_than_or_equal_to: 0, only_integer: true } + before_update :send_chat_message_if_leveled_up + scope :ordered_by_skill_name, -> { includes(:skill).order("skills.name") } XP_TOTALS_PER_LEVEL = [ @@ -24,6 +26,14 @@ class CharacterSkill < ApplicationRecord 1459475733, 1680697391, 1935475040, 2228899094 ].freeze + def self.level_for_xp(xp) + XP_TOTALS_PER_LEVEL.each_with_index do |total, index| + if total > xp + return index + end + end + end + def level XP_TOTALS_PER_LEVEL.each_with_index do |total, index| return index if total > self.xp @@ -42,4 +52,15 @@ class CharacterSkill < ApplicationRecord def xp_required_for_level(level) level <= 120 ? XP_TOTALS_PER_LEVEL[level - 1] : nil end + + def send_chat_message_if_leveled_up + if CharacterSkill.level_for_xp(self.xp_was) < CharacterSkill.level_for_xp(self.xp) + chat_message = ChatMessage.new(body: "reached #{self.skill.name} level #{self.level}!", + target: self.character, + chat_room: ChatRoom.find_by_gid("achievement")) + if chat_message.save + ChatRoomChannel.broadcast_chat_message(chat_message) + end + end + end end -- cgit v1.2.3