diff --git a/README.md b/README.md index a867411..b254485 100644 --- a/README.md +++ b/README.md @@ -138,3 +138,70 @@ Il va falloir préciser vers quelle table doit pointer la foreign key, pour ça On remplacera aussi le `null: false` de la référence `winner` pour supporter de ne pas en avoir. +Question 3.1 : + +On ajoute la méthode baston! sur les combats et on teste en console. La méthode modifie les instances de créature mais ne sauvegarde pas. + +Pour une domination : + +```ruby +❯ rails console +Loading development environment (Rails 7.0.4.3) +irb(main):001:0> c1 = Creature.first +... +irb(main):003:0> c1.to_label +=> "Thrall (489)" +irb(main):004:0> c2 = Creature.last +... +irb(main):005:0> c2.to_label +=> "Big Chongus (35)" +irb(main):006:0> combat = Combat.new(name: "L'orc vs le lapin", left_fighter: c1, right_fighter: c2) +=> # +irb(main):007:0> combat.baston! +=> :domination +irb(main):008:0> combat.winner +=> +# +irb(main):009:0> combat.right_fighter +=> +# +``` + +Pour un draw : + +```ruby +irb(main):011:0> c2.reload # permet de recharger le record depuis la base +... +=> +# +irb(main):012:0> c3 = Creature.create!(name: "Big Chungus", health_points: 35) +... +irb(main):013:0> combat2 = Combat.new(name: "Le fake vs le vrai", left_fighter: c2, right_fighter: c3) +=> # combat2.baston! +=> :draw +irb(main):015:0> combat2.winner +=> nil +irb(main):016:0> c2.to_label +=> "Big Chongus (0)" +irb(main):017:0> c3.to_label +=> "Big Chungus (0)" +``` diff --git a/app/models/combat.rb b/app/models/combat.rb index 26d62d2..71f7cc4 100644 --- a/app/models/combat.rb +++ b/app/models/combat.rb @@ -4,4 +4,25 @@ class Combat < ApplicationRecord belongs_to :left_fighter, class_name: 'Creature' belongs_to :right_fighter, class_name: 'Creature' belongs_to :winner, class_name: 'Creature' + + def baston! + return if left_fighter.nil? || right_fighter.nil? + + # on récupère les PVs d'abord, sinon l'ordre de l'attaque va affecter le résultat + left_hp = left_fighter.health_points + right_hp = right_fighter.health_points + + left_fighter.health_points -= right_hp + right_fighter.health_points -= right_hp + + if left_fighter.alive? + self.winner = left_fighter + self.result = :domination + elsif right_fighter.alive? + self.winner = right_fighter + self.result = :domination + else + self.result = :draw + end + end end diff --git a/app/models/creature.rb b/app/models/creature.rb index 272d106..70eecdf 100644 --- a/app/models/creature.rb +++ b/app/models/creature.rb @@ -3,10 +3,19 @@ class Creature < ApplicationRecord enum :size, [:small, :big, :giant] + def alive? + self.health_points > 0 + end + def to_label "#{name} (#{health_points})" end + def get_hit(damage) + self.health_points -= damage + self.health_points = 0 if self.health_points < 0 + end + before_create do self.size = case health_points when 0..10