Class: Boy2Man::Janken

Inherits:
Object
  • Object
show all
Defined in:
lib/Boy2Man/janken.rb

Overview

Returns the history of player’s hand.

Returns:

  • (Array)

    the history of player’s hand

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeJanken

Returns a new instance of Janken.



38
39
40
# File 'lib/Boy2Man/janken.rb', line 38

def initialize
  @history = Array.new
end

Instance Attribute Details

#historyArray (readonly)

Returns the history of player’s hand.

Returns:

  • (Array)

    the history of player’s hand



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/Boy2Man/janken.rb', line 35

class Janken
  attr_reader :history
  
  def initialize
    @history = Array.new
  end

  def history
    # retrun deep copy of history, to prevent history to be changed.
    Marshal.load(Marshal.dump(@history))
  end

  # @return [Array] resets history
  def reset
    @history.clear
  end

  # @return [String]
  def pon(hand)
    case hand
    when *HANDS
      # 先に手を決めておかないと後出しになる
      selected = case predict
      when "グー"   then "パー"
      when "チョキ" then "グー"
      when "パー"   then "チョキ"
      end
      @history.push hand
      selected
    else
    end
  end
  
  alias :hoi :pon
  alias :ぽん :pon
  alias :ほい :hoi

  private
  def predict
    possible_hands = Array.new

    if @history.length >= 3
      @history.each_with_index do |hand, i|
        # 最後に出されたと、その前の手から、次の手を予想する
        if hand == @history.last(2)[0] && @history[i+1] == @history.last
          possible_hands.push @history[i+2] if @history[i+2] != nil
        end
      end        
    end

    if possible_hands.empty? || (1 < @history.length && @history.length < 3)
      @history.each_with_index do |hand, i|
        # 最後に出された手から、次の手を予想する
        if hand == @history.last
          possible_hands.push @history[i+1] if @history[i+1] != nil
        end
      end        
    end

    possible_hands.empty? ? %w(グー チョキ パー).sample : possible_hands.sample
  end

end

Instance Method Details

#pon(hand) ⇒ String Also known as: hoi, ぽん

Returns:

  • (String)


53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/Boy2Man/janken.rb', line 53

def pon(hand)
  case hand
  when *HANDS
    # 先に手を決めておかないと後出しになる
    selected = case predict
    when "グー"   then "パー"
    when "チョキ" then "グー"
    when "パー"   then "チョキ"
    end
    @history.push hand
    selected
  else
  end
end

#resetArray

Returns resets history.

Returns:

  • (Array)

    resets history



48
49
50
# File 'lib/Boy2Man/janken.rb', line 48

def reset
  @history.clear
end