Module: Mjai::TenhouArchive::Util

Included in:
Mjai::TenhouArchive, TenhouFuro
Defined in:
lib/mjai/tenhou_archive.rb

Constant Summary collapse

YAKU_ID_TO_NAME =
[
  :menzenchin_tsumoho, :reach, :ippatsu, :chankan, :rinshankaiho,
  :haiteiraoyue, :hoteiraoyui, :pinfu, :tanyaochu, :ipeko,
  :jikaze, :jikaze, :jikaze, :jikaze,
  :bakaze, :bakaze, :bakaze, :bakaze,
  :sangenpai, :sangenpai, :sangenpai,
  :double_reach, :chitoitsu, :honchantaiyao, :ikkitsukan, :sanshokudojun,
  :sanshokudoko, :sankantsu, :toitoiho, :sananko, :shosangen, :honroto,
  :ryanpeko, :junchantaiyao, :honiso,
  :chiniso,
  :renho,
  :tenho, :chiho, :daisangen, :suanko, :suanko, :tsuiso,
  :ryuiso, :chinroto, :churenpoton, :churenpoton, :kokushimuso,
  :kokushimuso, :daisushi, :shosushi, :sukantsu,
  :dora, :uradora, :akadora,
]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.compose_pid(type_id, number, cid) ⇒ Object



281
282
283
# File 'lib/mjai/tenhou_archive.rb', line 281

def compose_pid(type_id, number, cid)
  return ((type_id * 9 + (number - 1)) * 4 + cid).to_s()
end

.decompose_pid(pid) ⇒ Object



272
273
274
275
276
277
278
279
# File 'lib/mjai/tenhou_archive.rb', line 272

def decompose_pid(pid)
  pid = pid.to_i()
  return [
    (pid / 4) / 9,
    (pid / 4) % 9 + 1,
    pid % 4,
  ]
end

.get_pai(type_id, number, cid) ⇒ Object



285
286
287
288
289
290
# File 'lib/mjai/tenhou_archive.rb', line 285

def get_pai(type_id, number, cid)
  type = ["m", "p", "s", "t"][type_id]
  # TODO only for games with red 5p
  red = type != "t" && number == 5 && cid == 0
  return Pai.new(type, number, red)
end

.pid_to_pai(pid) ⇒ Object



268
269
270
# File 'lib/mjai/tenhou_archive.rb', line 268

def pid_to_pai(pid)
  return pid ? get_pai(*decompose_pid(pid)) : Pai::UNKNOWN
end

Instance Method Details

#delete_tehai_by_pid(player, pid) ⇒ Object



246
247
248
249
250
251
252
# File 'lib/mjai/tenhou_archive.rb', line 246

def delete_tehai_by_pid(player, pid)
  idx = player.attributes.tenhou_tehai_pids.index(){ |tp| !tp || tp == pid }
  if !idx
    raise("%d not found in %p" % [pid, player.attributes.tenhou_tehai_pids])
  end
  player.attributes.tenhou_tehai_pids.delete_at(idx)
end

#get_points_params(sc_str) ⇒ Object



237
238
239
240
241
242
243
244
# File 'lib/mjai/tenhou_archive.rb', line 237

def get_points_params(sc_str)
  sc_nums = sc_str.split(/,/).map(&:to_i)
  result = {}
  result[:deltas] = (0...4).map(){ |i| sc_nums[2 * i + 1] * 100 }
  result[:scores] =
      (0...4).map(){ |i| sc_nums[2 * i] * 100 + result[:deltas][i] }
  return result
end

#on_tenhou_event(elem, next_elem = nil) ⇒ Object



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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/mjai/tenhou_archive.rb', line 36

def on_tenhou_event(elem, next_elem = nil)
  verify_tenhou_tehais() if @first_kyoku_started
  case elem.name
    when "SHUFFLE", "GO", "BYE"
      # BYE: log out
      return nil
    when "UN"
      escaped_names = (0...4).map(){ |i| elem["n%d" % i] }
      return :broken if escaped_names.index(nil)  # Something is wrong.
      @names = escaped_names.map(){ |s| URI.decode(s) }
      return nil
    when "TAIKYOKU"
      oya = elem["oya"].to_i()
      log_name = elem["log"] || File.basename(self.path, ".mjlog")
      uri = "http://tenhou.net/0/?log=%s&tw=%d" % [log_name, (4 - oya) % 4]
      @first_kyoku_started = false
      return do_action({:type => :start_game, :uri => uri, :names => @names})
    when "INIT"
      if @first_kyoku_started
        # Ends the previous kyoku. This is here because there can be multiple AGARIs in
        # case of daburon, so we cannot detect the end of kyoku in AGARI.
        do_action({:type => :end_kyoku})
      end
      (kyoku_id, honba, _, _, _, dora_marker_pid) = elem["seed"].split(/,/).map(&:to_i)
      bakaze = Pai.new("t", kyoku_id / 4 + 1)
      kyoku_num = kyoku_id % 4 + 1
      oya = elem["oya"].to_i()
      @first_kyoku_started = true
      tehais_list = []
      for i in 0...4
        if i == 0
          hai_str = elem["hai"] || elem["hai0"]
        else
          hai_str = elem["hai%d" % i]
        end
        pids = hai_str ? hai_str.split(/,/) : [nil] * 13
        self.players[i].attributes.tenhou_tehai_pids = pids
        tehais_list.push(pids.map(){ |s| pid_to_pai(s) })
      end
      do_action({
        :type => :start_kyoku,
        :bakaze => bakaze,
        :kyoku => kyoku_num,
        :honba => honba,
        :oya => self.players[oya],
        :dora_marker => pid_to_pai(dora_marker_pid.to_s()),
        :tehais => tehais_list,
      })
      return nil
    when /^([T-W])(\d+)?$/i
      player_id = ["T", "U", "V", "W"].index($1.upcase)
      pid = $2
      self.players[player_id].attributes.tenhou_tehai_pids.push(pid)
      return do_action({
          :type => :tsumo,
          :actor => self.players[player_id],
          :pai => pid_to_pai(pid),
      })
    when /^([D-G])(\d+)?$/i
      prefix = $1
      pid = $2
      player_id = ["D", "E", "F", "G"].index(prefix.upcase)
      if pid && pid == self.players[player_id].attributes.tenhou_tehai_pids[-1]
        tsumogiri = true
      elsif prefix != prefix.upcase
        tsumogiri = true
      else
        tsumogiri = false
      end
      delete_tehai_by_pid(self.players[player_id], pid)
      return do_action({
          :type => :dahai,
          :actor => self.players[player_id],
          :pai => pid_to_pai(pid),
          :tsumogiri => tsumogiri,
      })
    when "REACH"
      actor = self.players[elem["who"].to_i()]
      case elem["step"]
        when "1"
          return do_action({:type => :reach, :actor => actor})
        when "2"
          deltas = [0, 0, 0, 0]
          deltas[actor.id] = -1000
          # Old Tenhou archive doesn't have "ten" attribute. Calculates it manually.
          scores = (0...4).map() do |i|
            self.players[i].score + deltas[i]
          end
          return do_action({
              :type => :reach_accepted,
              :actor => actor,
              :deltas => deltas,
              :scores => scores,
          })
        else
          raise("should not happen")
      end
    when "AGARI"
      tehais = (elem["hai"].split(/,/) - [elem["machi"]]).map(){ |pid| pid_to_pai(pid) }
      points_params = get_points_params(elem["sc"])
      (fu, hora_points, _) = elem["ten"].split(/,/).map(&:to_i)
      if elem["yakuman"]
        fan = Hora::YAKUMAN_FAN
      else
        fan = elem["yaku"].split(/,/).each_slice(2).map(){ |y, f| f.to_i() }.inject(0, :+)
      end
      uradora_markers = (elem["doraHaiUra"] || "").
          split(/,/).map(){ |pid| pid_to_pai(pid) }

      if elem["yakuman"]
        yakus = elem["yakuman"].
            split(/,/).
            map(){ |y| [YAKU_ID_TO_NAME[y.to_i()], Hora::YAKUMAN_FAN] }
      else
        yakus = elem["yaku"].
            split(/,/).
            enum_for(:each_slice, 2).
            map(){ |y, f| [YAKU_ID_TO_NAME[y.to_i()], f.to_i()] }.
            select(){ |y, f| f != 0 }
      end

      do_action({
        :type => :hora,
        :actor => self.players[elem["who"].to_i()],
        :target => self.players[elem["fromWho"].to_i()],
        :pai => pid_to_pai(elem["machi"]),
        :hora_tehais => tehais,
        :uradora_markers => uradora_markers,
        :fu => fu,
        :fan => fan,
        :yakus => yakus,
        :hora_points => hora_points,
        :deltas => points_params[:deltas],
        :scores => points_params[:scores],
      })
      if elem["owari"]
        do_action({:type => :end_kyoku})
        do_action({:type => :end_game})
      end
      return nil
    when "RYUUKYOKU"
      points_params = get_points_params(elem["sc"])
      tenpais = []
      tehais = []
      for i in 0...4
        name = "hai%d" % i
        if elem[name]
          tenpais.push(true)
          tehais.push(elem[name].split(/,/).map(){ |pid| pid_to_pai(pid) })
        else
          tenpais.push(false)
          tehais.push([Pai::UNKNOWN] * self.players[i].tehais.size)
        end
      end
      reason_map = {
        "yao9" => :kyushukyuhai,
        "kaze4" => :sufonrenta,
        "reach4" => :suchareach,
        "ron3" => :sanchaho,
        "nm" => :nagashimangan,
        "kan4" => :sukaikan,
        nil => :fanpai,
      }
      reason = reason_map[elem["type"]]
      raise("unknown reason") if !reason
      # TODO add actor for some reasons
      do_action({
          :type => :ryukyoku,
          :reason => reason,
          :tenpais => tenpais,
          :tehais => tehais,
          :deltas => points_params[:deltas],
          :scores => points_params[:scores],
      })
      if elem["owari"]
        do_action({:type => :end_kyoku})
        do_action({:type => :end_game})
      end
      return nil
    when "N"
      actor = self.players[elem["who"].to_i()]
      furo = TenhouFuro.new(elem["m"].to_i())
      consumed_pids = furo.type == :kakan ? [furo.taken_pid] : furo.consumed_pids
      for pid in consumed_pids
        delete_tehai_by_pid(actor, pid)
      end
      return do_action(furo.to_action(self, actor))
    when "DORA"
      do_action({:type => :dora, :dora_marker => pid_to_pai(elem["hai"])})
      return nil
    when "FURITEN"
      return nil
    else
      raise("unknown tag name: %s" % elem.name)
  end
end

#pathObject



233
234
235
# File 'lib/mjai/tenhou_archive.rb', line 233

def path
  return nil
end

#verify_tenhou_tehaisObject



254
255
256
257
258
259
260
261
262
263
264
# File 'lib/mjai/tenhou_archive.rb', line 254

def verify_tenhou_tehais()
  for player in self.players
    next if !player.tehais
    tenhou_tehais =
        player.attributes.tenhou_tehai_pids.map(){ |pid| pid_to_pai(pid) }.sort()
    tehais = player.tehais.sort()
    if tenhou_tehais != tehais
      raise("tenhou_tehais != tehais: %p != %p" % [tenhou_tehais, tehais])
    end
  end
end