Ellen Lee | bbfd78e | 2017-10-27 10:57:24 +0800 | [diff] [blame] | 1 | |
arch | a9c66d3 | 2017-10-31 17:46:33 +0800 | [diff] [blame] | 2 | class Hero |
Ellen Lee | bbfd78e | 2017-10-27 10:57:24 +0800 | [diff] [blame] | 3 | |
| 4 | attr_accessor :hp, :name |
| 5 | |
| 6 | @@heroes = [] # 用來儲存所有 heroes 的 array # 讓外部的 method 也可以抓到這兩個 variables |
| 7 | |
| 8 | def initialize(name, hp, ap) |
| 9 | @name = name |
arch | a9c66d3 | 2017-10-31 17:46:33 +0800 | [diff] [blame] | 10 | @hp = hp |
| 11 | @ap = ap |
Ellen Lee | bbfd78e | 2017-10-27 10:57:24 +0800 | [diff] [blame] | 12 | @alive = true # 英雄剛被創造,所以預設為 true,表示英雄被創造時一定是活著的 |
| 13 | |
| 14 | # 印出被創造的英雄的 attributes |
| 15 | puts "你的英雄 #{@name} 已經誕生了!" |
| 16 | puts "生命力(HP):#{@hp}" |
| 17 | puts "攻擊力(AP):#{@ap}" |
| 18 | puts "" |
| 19 | |
| 20 | @@heroes << self # 把新建立的這個 hero 加入 array 裡 |
| 21 | end |
| 22 | |
| 23 | def is_alive? |
| 24 | return @alive |
| 25 | end |
| 26 | |
| 27 | def attack(enemy) |
| 28 | damage = rand(@ap/2..@ap) # 傷害會隨機取攻擊力的一半(AP/2)至 AP 中的數字 |
| 29 | enemy.hp = enemy.hp - damage # 新的生命力是生命力減去傷害 |
| 30 | |
| 31 | # 印出攻擊的過程 |
| 32 | puts "#{@name} 攻擊!" |
| 33 | puts "#{enemy.name} 受到 #{damage} 點傷害" |
| 34 | puts "#{enemy.name} 剩下 #{enemy.hp} 點 HP" |
| 35 | puts "" |
| 36 | |
arch | a9c66d3 | 2017-10-31 17:46:33 +0800 | [diff] [blame] | 37 | if enemy.hp < 1 # 生命值小於 1,代表死亡(戰敗) |
| 38 | enemy.die # 敵人死亡 |
Ellen Lee | bbfd78e | 2017-10-27 10:57:24 +0800 | [diff] [blame] | 39 | end |
| 40 | end |
| 41 | |
arch | a9c66d3 | 2017-10-31 17:46:33 +0800 | [diff] [blame] | 42 | def die # 代表死亡(戰敗) |
Ellen Lee | bbfd78e | 2017-10-27 10:57:24 +0800 | [diff] [blame] | 43 | @alive = false |
| 44 | puts "#{@name} 被打倒了" |
| 45 | end |
| 46 | |
| 47 | def self.count |
| 48 | return @@heroes.length # 回傳英雄們的數量 |
| 49 | end |
| 50 | |
| 51 | def self.all |
| 52 | return @@heroes # 回傳包含所有 hero 的 array |
| 53 | end |
arch | a9c66d3 | 2017-10-31 17:46:33 +0800 | [diff] [blame] | 54 | end |