2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

#7 【攻略】RubyWarrior Level7

2
Last updated at Posted at 2016-11-16

RubyWarrior Level7の攻略
今回は、独力で考えたスパゲッティコードと、参考サイトからインスパイアしたメソッド利用法を使ったスクリプトの両方を紹介したいと思います。

概要

今回はwarriorが壁にぶち当たっていて、出口はその反対の後方にあります。feel.wall?で壁の判定をしてからpivot!で回転することで進行方向自体を変更することができます。

そのあとは前回通り。

スクリプト(独力編)

class Player
  def initialize()
    @health = 20
  end
  
  def play_turn(warrior)
    if warrior.feel.wall?
      warrior.pivot!
    else
      if warrior.feel.empty?
        if @health > warrior.health
          if warrior.health < 7
            warrior.walk!(:backward)
          else
            warrior.walk!
          end
        else
          if warrior.health < 16
            warrior.rest!
          else
            warrior.walk!
          end
        end
        
      else
        if warrior.health < 7
          warrior.walk!(:backward)
        else
          warrior.attack!
        end
      end
      @health = warrior.health
    end
  end
end

if文が多い(ロジックは組めてるけど...)
共同開発の場だと、まず他の人が読めないし、部分的に変更してと頼まれても自分でも変更しにくいと思うので、次回からは「誰が見てもわかる綺麗なコード」を目指そうと思う。

スクリプト(インスパイア編)

class Player
  def initialize()
    @health = 20
  end
  
  def play_turn(warrior)
    if warrior.feel.wall?
      warrior.pivot!
    else
      if warrior.feel.empty?
        if @health > warrior.health
          if escape?(warrior)
            warrior.walk!(:backward)
          else
            warrior.walk!
          end
        else
          if rest?(warrior)
            warrior.rest!
          else
            warrior.walk!
          end
        end
        
      else
        if escape?(warrior)
          warrior.walk!(:backward)
        else
          warrior.attack!
        end
      end
    end
    
    def escape?(warrior)
      escape_health = 7
      dying = warrior.health < escape_health
      attacked = @health > warrior
      return attacked && dying
    end

    def rest?(warrior)
      health_line = 16
      cheerful = warrior.health > health_line
      attacked = @health > warrior
      return !(cheerful || attacked)
    end
    
    @health = warrior.health
  end
end

長くはなったけど、ほんの少しだけ分かりやすくなった...ような気がする。
条件をescape!とrest!に収めたので、そこの条件は他人が見ても分かりやすいし、修正もしやすいと思う。参考にした人は「攻撃されている」という条件もメソッドにしていて、全体的にもリーダブルコードだった。まだまだ自分のコードは改善の余地がありそう。

解説

壁を向いてる時はpivot!という条件を追加するくらいなのであまり新しい要素はない。
Level6のコードをwarrior.feel.wall?の偽の条件の方に入れてあげるだけ。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?