読者です 読者をやめる 読者になる 読者になる

オブジェクト指向じゃんけんゲームの Ruby 移植版

Ruby

前回エントリの C# バージョンの、Ruby 移植版です。
 

module JankenAsobi
  def play
    player1 = Cp.new
    player2 = Man.new
    judge = Judge.new(player1, player2)
    5.times {|i| judge.game(i + 1)}
    judge.winner
  end
  module_function :play

  class Player
    def initialize
      @wincount = 0
    end
    attr_reader :wincount, :name
    
    def count
      @wincount += 1
    end
  end

  class Cp < Player
    def initialize
      @name = "Computer"
      super
    end
    
    def show_hand
      rand(3)
    end
  end
  
  class Man < Player
    def initialize
      print "あなたの名前を入力して下さい:"
      @name = gets.chomp
      @name = "名無し" if !@name or @name.empty?
      super
    end
    
    def show_hand
      begin
        print "#{@name}の手を入力して下さい(0:グー, 1:チョキ, 2:パー):"
        n = gets.chomp
      end until n == "0" or n == "1" or n == "2"
      n.to_i
    end
  end

  class Judge
    Hand = ["グー", "チョキ", "パー"]
    
    def initialize(p1, p2)
      @player1 = p1
      @player2 = p2
      puts "#{@player1.name} 対 #{@player2.name} :じゃんけん開始\n "
    end
    
    def game(n)
      puts "*** #{n}回戦 ***"
      hand1 = @player1.show_hand
      hand2 = @player2.show_hand
      judgement(hand1, hand2)
    end
    
    def judgement(h1, h2)
      winner = @player1
      print "#{Hand[h1]} 対 #{Hand[h2]}で "
      if h1 == h2
        puts "引き分けです。"
        return
      elsif (h1 - h2) % 3 == 1
        winner = @player2
      end
      puts "#{winner.name}の勝ちです。"
      winner.count
    end
    private :judgement
    
    def winner
      p1 = @player1.wincount
      p2 = @player2.wincount
      finalwinner = @player1
      print "\n*** 最終結果 ***\n#{p1}#{p2} で "
      if p1 == p2
        puts "引き分けです。"
        return
      elsif p1 < p2
        finalwinner = @player2
      end
      puts "#{finalwinner.name}の勝ちです。"
    end
  end
end

JankenAsobi.play