attack.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # This class models an attack performed by a thing/being/player/npc/foe
  2. class Attack
  3. # The underlying thing that is used to model the attack
  4. attr_reader :my_thing
  5. # The underlying thing that is attacking
  6. attr_reader :att_thing
  7. # Creates a new attack for the given attacker's thing.
  8. def initialize(attacking_thing, w, h, offset_x = 0, offset_y = 0)
  9. @att_thing = attacking_thing
  10. p "Initialize attack: #{w} #{h}"
  11. x, y, w, h = @att_thing.rectangle_in_front(w, h)
  12. p "Attack area: #{x} #{y} #{w} #{h}"
  13. x += offset_x
  14. y += offset_y
  15. z = @att_thing.z
  16. name = "#{attacking_thing.name}_attack_#{self.class.serno}"
  17. @my_thing = Thing.make(name, Thing::Kind::ATTACK, x, y, z, w, h)
  18. @my_thing.hull_flags = Thing::Flag::SENSOR
  19. @my_thing.group = @att_thing.group
  20. @done = false
  21. @timer = Timer.make(3.0) do | timer |
  22. @done = true
  23. p "Attack done by timer."
  24. # update the attacks
  25. Attack.update
  26. true
  27. end
  28. end
  29. def done?
  30. return @done
  31. end
  32. def delete
  33. @my_thing.delete
  34. @my_thing = nil
  35. @att_thing = nil
  36. @timer.done!
  37. end
  38. def self.serno
  39. @serno ||= 0
  40. @serno += 1
  41. return @serno
  42. end
  43. def self.register(attack)
  44. @attacks ||= []
  45. @attacks << attack
  46. end
  47. # Purge attacks that are over through the update.
  48. def self.update
  49. @attacks ||= []
  50. done = []
  51. @attacks.each do | attack |
  52. done << attack if attack.done?
  53. end
  54. done.each do | attack |
  55. @attacks.delete(attack)
  56. attack.delete
  57. end
  58. end
  59. # Purge attacks that are over due to sprite event
  60. def self.on_sprite(thing_id)
  61. @attacks ||= []
  62. done = []
  63. @attacks.each do | attack |
  64. done << attack if attack.att_thing.id == thing_id
  65. end
  66. done.each do | attack |
  67. @attacks.delete(attack)
  68. attack.delete
  69. end
  70. end
  71. def self.make(attacking_thing, w, h, offset_x = 0, offset_y = 0)
  72. attack = self.new(attacking_thing, w, h, offset_x, offset_y)
  73. self.register(attack)
  74. p "Made attack #{attack}"
  75. return attack
  76. end
  77. end