RubyWarrior Level4の攻略
参考サイト: http://tumiki.hatenablog.jp/entry/2015/06/23/010440
ちょっと難しかったので、参考サイトの解説を少し細かく解説します。
概要
新しく弓矢兵が出てきたので、前回と同じように止まってwarrior.rest!すると遠距離攻撃されて負ける。
ゲーム案内文にある通り、@healthにターン毎に体力の数値を保存して、次ターンのwarrior.healthと比較することで進んで攻撃すべきか、休むかを判断できるロジックを組むといい。
スクリプト
class Player
def play_turn(warrior)
if @health.nil?
@health = 20
end
if @health > warrior.health
if warrior.feel.empty?
warrior.walk!
else
warrior.attack!
end
else
if warrior.health < 15
warrior.rest!
else
if warrior.feel.empty?
warrior.walk!
else
warrior.attack!
end
end
end
@health = warrior.health
end
end
解説
まず、
if @health.nil?
@health = 20
end
ここではプレイヤーの最初の体力を@healthに保存。このインスタンス変数をターン毎に更新しながら条件分岐を進んで行く。
次に
if @health > warrior.health
if warrior.feel.empty?
warrior.walk!
else
warrior.attack!
end
else
・
・
・
end
@health = warrior.health
ここのスクリプトは弓矢兵に対応するためのもの。
これのおかげでwarriorがダメージを受けているか判断できて、「攻撃を受けていたらその場で回復せず、前進して攻撃しろ」という命令ができる。
warriorが自分の行動を終えたあと、ターンを終了する前に@health = warrior.healthでターン終了時の体力を保存する。
で、その後の敵のターンで弓矢兵から攻撃を受けると、次のターン開始時に@healthとwarrior.healthの値に差が出てくる。それを、
if @health > warrior.health
という条件に照らし合わせtrueなら前進して攻撃ができる、ということになる。