summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/channels/chat_room_channel.rb2
-rw-r--r--app/models/character.rb6
-rw-r--r--app/models/character_skill.rb21
3 files changed, 27 insertions, 2 deletions
diff --git a/app/channels/chat_room_channel.rb b/app/channels/chat_room_channel.rb
index 1e14b35..82084b6 100644
--- a/app/channels/chat_room_channel.rb
+++ b/app/channels/chat_room_channel.rb
@@ -3,7 +3,7 @@ class ChatRoomChannel < ApplicationCable::Channel
ActionCable.server.broadcast "chat_room_channel",
html: ApplicationController.render(partial: "chat_messages/message",
locals: {
- chat: chat_message
+ chat_message: chat_message
})
end
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