OSDN Git Service

Merge remote-tracking branch 'origin/wdoor-stable'
authorDaigo Moriwaki <daigo@debian.org>
Fri, 22 Nov 2013 12:47:59 +0000 (21:47 +0900)
committerDaigo Moriwaki <daigo@debian.org>
Fri, 22 Nov 2013 12:47:59 +0000 (21:47 +0900)
Conflicts:
changelog

20 files changed:
changelog
mk_game_results
mk_rate
mk_rate-from-grep [new file with mode: 0755]
mk_rate-grep [new file with mode: 0755]
shogi-server
shogi_server.rb
shogi_server/board.rb
shogi_server/buoy.rb
shogi_server/command.rb
shogi_server/game.rb
shogi_server/league/floodgate.rb
shogi_server/pairing.rb
shogi_server/time_clock.rb [new file with mode: 0644]
test/TC_ALL.rb
test/TC_command.rb
test/TC_floodgate.rb
test/TC_fork.rb [new file with mode: 0644]
test/TC_pairing.rb
test/TC_time_clock.rb [new file with mode: 0644]

index 949397c..a6d5f64 100644 (file)
--- a/changelog
+++ b/changelog
@@ -1,3 +1,78 @@
+2013-11-04  Daigo Moriwaki <daigo at debian dot org>
+
+       * [mk_rate]
+         - Added a new option, --ignore, which is imported from
+           mk_rate-from-grep.
+       * [mk_game_results]
+         - Flush after each output line.
+       * Rleased: Revision "20131104"
+
+2013-09-08  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - shogi_server/{game,time_clock}.rb:
+           When StopWatchClock is used, "Time_Unit:" of starting messages
+           in CSA protocol supplies "1min".
+
+2013-04-07  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - shogi_server/{game,time_clock}.rb:
+           Adds variations of thinking time calculation: ChessClock
+           (current) and StopWatchClock (new).
+           StopWatchClock, which is usually used at official games of human
+           professional players, is a clock where thiking time less than a
+           miniute is regarded as zero.
+           To select StopWatchClock, use a special game name with "060"
+           byoyomi time. ex. "gamename_1500_060".
+
+2013-03-31  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - %%FORK command: %%FORK <source_game> [<new_buoy_game>] [<nth-move>]
+           The new_buoy_game parameter is now optional. If it is not
+           supplied, Shogi-server generates a new buoy game name from
+           source_game.
+         - command.rb: More elaborate error messages for the %%GAME command.
+
+2013-03-20  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - New pairing algorithm: ShogiServer::Pairing::LeastDiff
+           This pairing algorithm aims to minimize the total differences of
+           matching players' rates. It also includes penalyties when a match
+           is same as the previous one or a match is between human players.
+           It is based on a discussion with Yamashita-san on
+           http://www.sgtpepper.net/kaneko/diary/20120511.html.
+
+2013-02-23  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - New command: %%FORK <source_game> <new_buoy_game> [<nth-move>]
+           Fork a new game from the posistion where the n-th (starting from
+           one) move of a source game is played. The new game should be a
+           valid buoy game name. The default value of n is the position
+           where the previous position of the last one.
+           - The objective of this command: The shogi-server may be used as
+           the back end server of computer-human match where a human player
+           plays with a real board and someone, or a proxy, inputs moves to
+           the shogi-server. If the proxy happens to enter a wrong move,
+           with this command you can restart a new buoy game from the
+           previous stable position.
+           ex. %%FORK server-denou-14400-60+p1+p2+20130223185013 buoy_denou-14400-60
+
+2012-12-30  Daigo Moriwaki <daigo at debian dot org>
+
+       * [shogi-server]
+         - Backported a5c94012656902e73e00f46e7a4c7004b24d4578:
+           test/TC_logger.rb depeneded on a specific directory where it was
+           running on. This issues has been fixed.
+         - Backported 87d145bd1f1a14a33f5f6fbc78b63a1952f1ca90 and
+           2df8c798aeb7f0e77735e893fd1370c2c6f15c4d:
+           shogi_server/floodgate.rb: Generating next time around the new
+           year day by reading configuration files did not work correctly.
+           This issue has been fixed.
+
 2012-12-28  Daigo Moriwaki <daigo at debian dot org>
 
        * [shogi-server]
index 6b205a2..2a8dbb2 100755 (executable)
@@ -89,6 +89,7 @@ def grep(file)
       puts [time, state, black_mark, black_id, white_id, white_mark, file].join("\t")
     end
   end
+  $stdout.flush
 end
 
 # Show Usage
diff --git a/mk_rate b/mk_rate
index bddbb73..fcfe3e7 100755 (executable)
--- a/mk_rate
+++ b/mk_rate
 #   m [days] (default  7)
 #   after m days, the half-life effect works
 #
+# --ignore::
+#   m [days] (default  365*2)
+#   old results will be ignored
+#
 # --fixed-rate-player::
 #   player whose rate is fixed at the rate
 #
@@ -660,6 +664,11 @@ def parse(line)
   return if state == "abnormal"
   time = Time.parse(time)
   return if $options["base-date"] < time
+  how_long_days = ($options["base-date"] - time)/(3600*24)
+  if (how_long_days > $options["ignore"])
+    return
+  end
+
   black_id = identify_id(black_id)
   white_id = identify_id(white_id)
 
@@ -697,6 +706,8 @@ OPTOINS:
   --half-life         n [days] (default 60)
   --half-life-ignore  m [days] (default  7)
                       after m days, half-life effect works
+  --ignore            n [days] (default 730 [=365*2]).
+                      Results older than n days from the 'base-date' are ignored.
   --fixed-rate-player player whose rate is fixed at the rate
   --fixed-rate        rate 
   --skip-draw-games   skip draw games. [default: draw games are counted in
@@ -712,6 +723,7 @@ def main
     ["--half-life",         GetoptLong::REQUIRED_ARGUMENT],
     ["--half-life-ignore",  GetoptLong::REQUIRED_ARGUMENT],
     ["--help", "-h",        GetoptLong::NO_ARGUMENT],
+    ["--ignore",            GetoptLong::REQUIRED_ARGUMENT],
     ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
     ["--fixed-rate",        GetoptLong::REQUIRED_ARGUMENT],
     ["--skip-draw-games",   GetoptLong::NO_ARGUMENT])
@@ -744,6 +756,8 @@ def main
   $options["half-life"] = $options["half-life"].to_i
   $options["half-life-ignore"] ||= 7
   $options["half-life-ignore"] = $options["half-life-ignore"].to_i
+  $options["ignore"] ||= 365*2
+  $options["ignore"] = $options["ignore"].to_i
   $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
 
   if ARGV.empty?
diff --git a/mk_rate-from-grep b/mk_rate-from-grep
new file mode 100755 (executable)
index 0000000..3c99c61
--- /dev/null
@@ -0,0 +1,796 @@
+#!/usr/bin/ruby
+# $Id: mk_rate 316 2008-12-28 15:10:10Z beatles $
+#
+# Author:: Daigo Moriwaki
+# Homepage:: http://sourceforge.jp/projects/shogi-server/
+#
+#--
+# Copyright (C) 2006-2008 Daigo Moriwaki <daigo at debian dot org>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#++
+#
+# == Synopsis
+#
+# mk_rate reads CSA files, calculates rating scores of each player, and then
+# outputs a yaml file (players.yaml) that Shogi-server can recognize.
+#
+# == Usage
+#
+# ./mk_rate [options] DIR..
+# 
+# DIR::
+#   CSA files are recursively looked up the directories.
+#
+# --half-life::
+#   n [days] (default 60)
+#   
+# --half-life-ignore::
+#   m [days] (default  7)
+#   after m days, the half-life effect works
+#
+# --ignore::
+#   m [days] (default  365*2)
+#   old files will be ignored
+#
+# --fixed-rate-player::
+#   player whose rate is fixed at the rate
+#
+# --fixed-rate::
+#   rate 
+#
+# --help::
+#   show this message
+#
+# == PREREQUIRE
+#
+# Sample Command lines that isntall prerequires will work on Debian.
+#
+# * Ruby 1.8.7
+#
+#   $ sudo aptitude install ruby1.8
+#
+# * Rubygems
+#
+#   $ sudo aptitude install rubygems
+#
+# * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
+#
+#   $ sudo aptitude install libgsl-ruby1.8
+#
+# * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
+#
+#   $ sudo gem install rgl
+#
+# == Run
+#
+#   $ ./mk_rate . > players.yaml
+#
+# or, if you do not want the file to be update in case of errors, 
+#
+#   $ ./mk_rate . && ./mk_rate . > players.yaml
+#
+# == How players are rated
+#
+# The conditions that games and players are rated as following:
+#
+# * Rated games, which were played by both rated players.
+# * Rated players, who logged in the server with a name followed by a trip: "name,trip".
+# * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games. 
+#
+
+require 'yaml'
+require 'time'
+require 'getoptlong'
+require 'gsl'
+require 'rubygems'
+require 'rgl/adjacency'
+require 'rgl/connected_components'
+
+#################################################
+# Constants
+#
+
+# Count out players who play less games than $GAMES_LIMIT
+$GAMES_LIMIT = $DEBUG ? 0 : 15
+WIN_MARK  = "win"
+LOSS_MARK = "lose"
+DRAW_MARK = "draw"
+
+# Holds players
+$players = Hash.new
+# Holds the last time when a player gamed
+$players_time = Hash.new { Time.at(0) }
+
+
+#################################################
+# Keeps the value of the lowest key
+#
+class Record
+  def initialize
+    @lowest = []
+  end
+
+  def set(key, value)
+    if @lowest.empty? || key < @lowest[0]
+      @lowest = [key, value]
+    end
+  end
+
+  def get
+    if @lowest.empty?
+      nil
+    else
+      @lowest[1]
+    end
+  end
+end
+
+#################################################
+# Calculates rates of every player from a Win Loss GSL::Matrix
+#
+class Rating
+  include Math
+
+  # The model of the win possibility is 1/(1 + 10^(-d/400)).
+  # The equation in this class is 1/(1 + e^(-Kd)).
+  # So, K should be calculated like this.
+  K = Math.log(10.0) / 400.0
+  
+  # Convergence limit to stop Newton method.
+  ERROR_LIMIT = 1.0e-3
+  # Stop Newton method after this iterations.
+  COUNT_MAX = 500
+
+  # Average rate among the players
+  AVERAGE_RATE = 1000
+
+  
+  ###############
+  # Class methods
+  #  
+  
+  ##
+  # Calcurates the average of the vector.
+  #
+  def Rating.average(vector, mean=0.0)
+    sum = Array(vector).inject(0.0) {|sum, n| sum + n}
+    vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
+    vector
+  end
+
+  ##################
+  # Instance methods
+  #
+  def initialize(win_loss_matrix)
+    @record = Record.new
+    @n = win_loss_matrix
+    case @n
+    when GSL::Matrix, GSL::Matrix::Int
+      @size = @n.size1
+    when ::Matrix
+      @size = @n.row_size
+    else
+      raise ArgumentError
+    end
+    initial_rate
+  end
+  attr_reader :rate, :n
+
+  def player_vector
+    GSL::Vector[*
+      (0...@size).collect {|k| yield k}
+    ]
+  end
+
+  def each_player
+    (0...@size).each {|k| yield k}
+  end
+
+  ##
+  # The possibility that the player k will beet the player i.
+  #
+  def win_rate(k,i)
+    1.0/(1.0 + exp(@rate[i]-@rate[k]))
+  end
+
+  ##
+  # Most possible equation
+  #
+  def func_vector
+    player_vector do|k| 
+      sum = 0.0
+      each_player do |i|
+        next if i == k
+        sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i) 
+      end
+      sum * 2.0
+    end
+  end
+
+  ##
+  #           / f0/R0 f0/R1 f0/R2 ... \
+  # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
+  #           \ f2/R0 f2/R1 f2/R2 ... /
+  def d_func(k,j)
+    sum = 0.0
+    if k == j
+      each_player do |i|
+        next if i == k
+        sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
+      end
+      sum *= -2.0
+    else # k != j
+      sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
+    end
+    sum
+  end
+
+  ##
+  # Jacobi matrix of the func().
+  #   m00 m01
+  #   m10 m11
+  #
+  def j_matrix
+    GSL::Matrix[*
+      (0...@size).collect do |k|
+        (0...@size).collect do |j|
+          d_func(k,j)
+        end
+      end
+    ]
+  end
+
+  ##
+  # The initial value of the rate, which is of very importance for Newton
+  # method.  This is based on my huristics; the higher the win probablity of
+  # a player is, the greater points he takes.
+  #
+  def initial_rate
+    possibility = 
+      player_vector do |k|
+        v = GSL::Vector[0, 0]
+        each_player do |i|
+          next if k == i
+          v += GSL::Vector[@n[k,i], @n[i,k]]
+        end
+        v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
+      end
+    rank = possibility.sort_index
+    @rate = player_vector do |k|
+      K*500 * (rank[k]+1) / @size
+    end
+    average!
+  end
+
+  ##
+  # Resets @rate as the higher the current win probablity of a player is, 
+  # the greater points he takes. 
+  #
+  def initial_rate2
+    @rate = @record.get || @rate
+    rank = @rate.sort_index
+    @rate = player_vector do |k|
+      K*@count*1.5 * (rank[k]+1) / @size
+    end
+    average!
+  end
+
+  # mu is the deaccelrating parameter in Deaccelerated Newton method
+  def deaccelrate(mu, old_rate, a, old_f_nrm2)
+    @rate = old_rate - a * mu
+    if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
+      return
+    end
+    if mu < 1e-4
+      @record.set(func_vector.nrm2, @rate)
+      initial_rate2
+      return
+    end
+    $stderr.puts "mu: %f " % [mu] if $DEBUG
+    deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
+  end
+
+  ##
+  # Main process to calculate ratings.
+  #
+  def rating
+    # Counter to stop the process. 
+    # Calulation in Newton method may fall in an infinite loop
+    @count = 0
+
+    # Main loop
+    begin
+      # Solve the equation: 
+      #   J*a=f
+      #   @rate_(n+1) = @rate_(n) - a
+      #
+      # f.nrm2 should approach to zero.
+      f = func_vector
+      j = j_matrix
+
+      # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
+      $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
+
+      # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
+      #a = GSL::Linalg::HH.solve(j, f)
+      a, = GSL::MultiFit::linear(j, f)
+      a = self.class.average(a)
+      # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
+      
+      # Deaccelerated Newton method
+      # GSL::Vector object should be immutable.
+      old_rate   = @rate
+      old_f      = f
+      old_f_nrm2 = old_f.nrm2
+      deaccelrate(1.0, old_rate, a, old_f_nrm2)
+      @record.set(func_vector.nrm2, @rate)
+
+      $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
+
+      @count += 1
+      if @count > COUNT_MAX
+        $stderr.puts "Values seem to oscillate. Stopped the process."
+        $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
+        break
+      end
+
+    end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
+    
+    @rate = @record.get
+    $stderr.puts "resolved f: %s -> %f" %
+      [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
+
+    @rate *= 1.0/K
+    finite!
+    self
+  end
+
+  ##
+  # Make the values of @rate finite.
+  #
+  def finite!
+    @rate = @rate.collect do |a|
+      if a.infinite?
+        a.infinite? * AVERAGE_RATE * 100
+      else
+        a
+      end
+    end
+  end
+
+  ##
+  # Flatten the values of @rate.
+  #
+  def average!(mean=0.0)
+    @rate = self.class.average(@rate, mean)
+  end
+
+  ##
+  # Translate by value
+  #
+  def translate!(value)
+    @rate += value
+  end
+
+  ##
+  # Make the values of @rate integer.
+  #
+  def integer!
+    @rate = @rate.collect do |a|
+      if a.finite?
+        a.to_i
+      elsif a.nan?
+        0
+      elsif a.infinite?
+        a.infinite? * AVERAGE_RATE * 100
+      end
+    end
+  end
+end
+
+#################################################
+# Encapsulate a pair of keys and win loss matrix.
+#   - keys is an array of player IDs; [gps+123, foo+234, ...]
+#   - matrix holds games # where player i (row index) beats player j (column index).
+#     The row and column indexes match with the keys.
+#
+# This object should be immutable. If an internal state is being modified, a
+# new object is always returned.
+#
+class WinLossMatrix
+
+  ###############
+  # Class methods
+  #  
+
+  def self.mk_matrix(players)
+    keys = players.keys.sort
+    size = keys.size
+    matrix =
+      GSL::Matrix[*
+      ((0...size).collect do |k|
+        p1 = keys[k]
+        p1_hash = players[p1]
+        ((0...size).collect do |j|
+          if k == j
+            0
+          else
+            p2 = keys[j]
+            v = p1_hash[p2] || Vector[0,0]
+            v[0]
+          end
+        end)
+      end)]
+    return WinLossMatrix.new(keys, matrix)
+  end
+
+  def self.mk_win_loss_matrix(players)
+    obj = mk_matrix(players)
+    return obj.filter
+  end
+
+  ##################
+  # Instance methods
+  #
+
+  # an array of player IDs; [gps+123, foo+234, ...]
+  attr_reader :keys
+
+  # matrix holds games # where player i (row index) beats player j (column index).
+  # The row and column indexes match with the keys.
+  attr_reader :matrix
+
+  def initialize(keys, matrix)
+    @keys   = keys
+    @matrix = matrix
+  end
+
+  ##
+  # Returns the size of the keys/matrix
+  #
+  def size
+    if @keys
+      @keys.size
+    else
+      nil
+    end
+  end
+
+  ##
+  # Removes players in a rows such as [1,3,5], and then returns a new
+  # object.
+  #
+  def delete_rows(rows)
+    rows = rows.sort.reverse
+
+    copied_cols = []
+    (0...size).each do |i|
+      next if rows.include?(i)
+      row = @matrix.row(i).clone
+      rows.each do |j|
+        row.delete_at(j)
+      end
+      copied_cols << row
+    end
+    if copied_cols.size == 0
+      new_matrix = GSL::Matrix.new
+    else
+      new_matrix = GSL::Matrix[*copied_cols]
+    end
+
+    new_keys = @keys.clone
+    rows.each do |j|
+      new_keys.delete_at(j)
+    end
+
+    return WinLossMatrix.new(new_keys, new_matrix)
+  end
+
+  ##
+  # Removes players who do not pass a criteria to be rated, and returns a
+  # new object.
+  # 
+  def filter
+    $stderr.puts @keys.inspect if $DEBUG
+    $stderr.puts @matrix.inspect if $DEBUG
+    delete = []  
+    (0...size).each do |i|
+      row = @matrix.row(i)
+      col = @matrix.col(i)
+      win  = row.sum
+      loss = col.sum
+      if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
+        delete << i
+      end
+    end
+
+    # The recursion ends if there is nothing to delete
+    return self if delete.empty?
+
+    new_obj = delete_rows(delete)
+    new_obj.filter
+  end
+
+  ##
+  # Cuts self into connecting groups such as each player in a group has at least
+  # one game with other players in the group. Returns them as an array.
+  #
+  def connected_subsets
+    g = RGL::AdjacencyGraph.new
+    (0...size).each do |k|
+      (0...size).each do |i|
+        next if k == i
+        if @matrix[k,i] > 0
+          g.add_edge(k,i)
+        end
+      end
+    end
+
+    subsets = []
+    g.each_connected_component do |c|
+      new_keys = []      
+      c.each do |v|
+        new_keys << keys[v.to_s.to_i]
+      end
+      subsets << new_keys
+    end
+
+    subsets = subsets.sort {|a,b| b.size <=> a.size}
+
+    result = subsets.collect do |keys|
+      matrix =
+        GSL::Matrix[*
+        ((0...keys.size).collect do |k|
+          p1 = @keys.index(keys[k])
+          ((0...keys.size).collect do |j|
+            if k == j
+              0
+            else
+              p2 = @keys.index(keys[j])
+              @matrix[p1,p2] + 0.001
+            end
+          end)
+        end)]
+      WinLossMatrix.new(keys, matrix)
+    end
+
+    return result
+  end
+
+  def to_s
+    "size : #{@keys.size}" + "\n" +
+    @keys.inspect + "\n" + 
+    @matrix.inspect
+  end
+
+end
+
+
+#################################################
+# Main methods
+#
+
+# Half-life effect
+# After NHAFE_LIFE days value will get half.
+# 0.693 is constant, where exp(0.693) ~ 0.5
+def half_life(days)
+  if days < $options["half-life-ignore"]
+    return 1.0
+  else
+    Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
+  end
+end
+
+def _add_win_loss(winner, loser, time)
+  how_long_days = (Time.now - time)/(3600*24)
+  $players[winner] ||= Hash.new { GSL::Vector[0,0] }
+  $players[loser]  ||= Hash.new { GSL::Vector[0,0] }
+  $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
+  $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
+end
+
+def _add_time(player, time)
+  $players_time[player] = time if $players_time[player] < time
+end
+
+def add(black_mark, black_name, white_name, white_mark, time)
+  how_long_days = (Time.now - time)/(3600*24)
+  if (how_long_days > $options["ignore"])
+    return
+  end
+  if black_mark == WIN_MARK && white_mark == LOSS_MARK
+    _add_win_loss(black_name, white_name, time)
+  elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
+    _add_win_loss(white_name, black_name, time)
+  elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
+    return
+  else
+    raise "Never reached!"
+  end
+  _add_time(black_name, time)
+  _add_time(white_name, time)
+end
+
+def identify_id(id)
+  if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
+    return nil
+  end
+  id.gsub(/@.*?\+/,"+")
+end
+
+def grep(str)
+  if /^([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([0-9]+)$/ =~ str.strip then
+    add($1,$2,$3,$4,Time.at($5.to_i))
+  end
+end
+
+def usage
+  $stderr.puts <<-EOF
+USAGE: #{$0} dir [...]
+  EOF
+  exit 1
+end
+
+def validate(yaml)
+  yaml["players"].each do |group_key, group|
+    group.each do |player_key, player|
+      rate = player['rate']
+      next unless rate
+      if rate > 10000 || rate < -10000
+        return false
+      end
+    end
+  end
+  return true
+end
+
+def usage(io)
+    io.puts <<EOF
+USAGE: #{$0} [options] DIR..
+  DIR                where CSA files are looked up recursively
+OPTOINS:
+  --half-life         n [days] (default 60)
+  --half-life-ignore  m [days] (default  7)
+                      after m days, half-life effect works
+  --fixed-rate-player player whose rate is fixed at the rate
+  --fixed-rate        rate 
+  --help              show this message
+EOF
+end
+
+def main
+  $options = Hash::new
+  parser = GetoptLong.new(
+    ["--half-life",         GetoptLong::REQUIRED_ARGUMENT],
+    ["--half-life-ignore",  GetoptLong::REQUIRED_ARGUMENT],
+    ["--ignore",  GetoptLong::REQUIRED_ARGUMENT],
+    ["--help", "-h",        GetoptLong::NO_ARGUMENT],
+    ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
+    ["--fixed-rate",        GetoptLong::REQUIRED_ARGUMENT])
+  parser.quiet = true
+  begin
+    parser.each_option do |name, arg|
+      name.sub!(/^--/, '')
+      $options[name] = arg.dup
+    end
+    if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
+       (!$options["fixed-rate-player"] &&  $options["fixed-rate"]) ||
+       ( $options["fixed-rate-player"] &&  $options["fixed-rate"].to_i <= 0) 
+      usage($stderr)
+      exit 1
+    end
+  rescue
+    usage($stderr)
+    raise parser.error_message
+  end
+  if $options["help"]
+    usage($stdout) 
+    exit 0
+  end
+  $options["half-life"] ||= 60
+  $options["half-life"] = $options["half-life"].to_i
+  $options["half-life-ignore"] ||= 7
+  $options["half-life-ignore"] = $options["half-life-ignore"].to_i
+  $options["ignore"] ||= 365*2
+  $options["ignore"] = $options["ignore"].to_i
+  $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
+
+  while line = $stdin.gets do
+    grep line.strip
+  end
+
+  yaml = {} 
+  yaml["players"] = {}
+  rating_group = 0
+  if $players.size > 0
+    obj = WinLossMatrix::mk_win_loss_matrix($players)
+    obj.connected_subsets.each do |win_loss_matrix|
+      yaml["players"][rating_group] = {}
+
+      rating = Rating.new(win_loss_matrix.matrix)
+      rating.rating
+      rating.average!(Rating::AVERAGE_RATE)
+      rating.integer!
+
+      if $options["fixed-rate-player"]
+        # first, try exact match
+        index = win_loss_matrix.keys.index($options["fixed-rate-player"])
+        # second, try regular match
+        unless index
+          win_loss_matrix.keys.each_with_index do |p, i|
+            if %r!#{$options["fixed-rate-player"]}! =~ p
+              index = i
+            end
+          end
+        end
+        if index
+          the_rate = rating.rate[index]
+          rating.translate!($options["fixed-rate"] - the_rate)
+        end
+      end
+
+      win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
+        win  = win_loss_matrix.matrix.row(i).sum
+        loss = win_loss_matrix.matrix.col(i).sum
+
+        yaml["players"][rating_group][p] = 
+          { 'name' => p.split("+")[0],
+            'rating_group' => rating_group,
+            'rate' => rating.rate[i],
+            'last_modified' => $players_time[p].dup,
+            'win'  => win,
+            'loss' => loss}
+      end
+      rating_group += 1
+    end
+  end
+  rating_group -= 1
+  non_rated_group = 999 # large enough
+  yaml["players"][non_rated_group] = {}
+  $players.each_key do |id|
+    # skip players who have already been rated
+    found = false
+    (0..rating_group).each do |i|
+       found = true if yaml["players"][i][id]
+       break if found
+    end
+    next if found
+
+    v = GSL::Vector[0, 0]
+    $players[id].each_value {|value| v += value}
+    next if v[0] < 1 && v[1] < 1
+
+    yaml["players"][non_rated_group][id] =
+      { 'name' => id.split("+")[0],
+        'rating_group' => non_rated_group,
+        'rate' => 0,
+        'last_modified' => $players_time[id].dup,
+        'win'  => v[0],
+        'loss' => v[1]}
+  end
+  unless validate(yaml)
+    $stderr.puts "Aborted. It did not result in valid ratings."
+    $stderr.puts yaml.to_yaml if $DEBUG
+    exit 10
+  end
+  puts yaml.to_yaml
+end
+
+if __FILE__ == $0
+  main
+end
+
+# vim: ts=2 sw=2 sts=0
diff --git a/mk_rate-grep b/mk_rate-grep
new file mode 100755 (executable)
index 0000000..2f8b748
--- /dev/null
@@ -0,0 +1,747 @@
+#!/usr/bin/ruby
+# $Id: mk_rate 316 2008-12-28 15:10:10Z beatles $
+#
+# Author:: Daigo Moriwaki
+# Homepage:: http://sourceforge.jp/projects/shogi-server/
+#
+#--
+# Copyright (C) 2006-2008 Daigo Moriwaki <daigo at debian dot org>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#++
+#
+# == Synopsis
+#
+# mk_rate reads CSA files, calculates rating scores of each player, and then
+# outputs a yaml file (players.yaml) that Shogi-server can recognize.
+#
+# == Usage
+#
+# ./mk_rate [options] DIR..
+# 
+# DIR::
+#   CSA files are recursively looked up the directories.
+#
+# --half-life::
+#   n [days] (default 60)
+#   
+# --half-life-ignore::
+#   m [days] (default  7)
+#   after m days, the half-life effect works
+#
+# --fixed-rate-player::
+#   player whose rate is fixed at the rate
+#
+# --fixed-rate::
+#   rate 
+#
+# --help::
+#   show this message
+#
+# == PREREQUIRE
+#
+# Sample Command lines that isntall prerequires will work on Debian.
+#
+# * Ruby 1.8.7
+#
+#   $ sudo aptitude install ruby1.8
+#
+# * Rubygems
+#
+#   $ sudo aptitude install rubygems
+#
+# * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
+#
+#   $ sudo aptitude install libgsl-ruby1.8
+#
+# * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
+#
+#   $ sudo gem install rgl
+#
+# == Run
+#
+#   $ ./mk_rate . > players.yaml
+#
+# or, if you do not want the file to be update in case of errors, 
+#
+#   $ ./mk_rate . && ./mk_rate . > players.yaml
+#
+# == How players are rated
+#
+# The conditions that games and players are rated as following:
+#
+# * Rated games, which were played by both rated players.
+# * Rated players, who logged in the server with a name followed by a trip: "name,trip".
+# * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games. 
+#
+
+require 'yaml'
+require 'time'
+require 'getoptlong'
+require 'gsl'
+require 'rubygems'
+require 'rgl/adjacency'
+require 'rgl/connected_components'
+
+#################################################
+# Constants
+#
+
+# Count out players who play less games than $GAMES_LIMIT
+$GAMES_LIMIT = $DEBUG ? 0 : 15
+WIN_MARK  = "win"
+LOSS_MARK = "lose"
+DRAW_MARK = "draw"
+
+# Holds players
+$players = Hash.new
+# Holds the last time when a player gamed
+$players_time = Hash.new { Time.at(0) }
+
+
+#################################################
+# Keeps the value of the lowest key
+#
+class Record
+  def initialize
+    @lowest = []
+  end
+
+  def set(key, value)
+    if @lowest.empty? || key < @lowest[0]
+      @lowest = [key, value]
+    end
+  end
+
+  def get
+    if @lowest.empty?
+      nil
+    else
+      @lowest[1]
+    end
+  end
+end
+
+#################################################
+# Calculates rates of every player from a Win Loss GSL::Matrix
+#
+class Rating
+  include Math
+
+  # The model of the win possibility is 1/(1 + 10^(-d/400)).
+  # The equation in this class is 1/(1 + e^(-Kd)).
+  # So, K should be calculated like this.
+  K = Math.log(10.0) / 400.0
+  
+  # Convergence limit to stop Newton method.
+  ERROR_LIMIT = 1.0e-3
+  # Stop Newton method after this iterations.
+  COUNT_MAX = 500
+
+  # Average rate among the players
+  AVERAGE_RATE = 1000
+
+  
+  ###############
+  # Class methods
+  #  
+  
+  ##
+  # Calcurates the average of the vector.
+  #
+  def Rating.average(vector, mean=0.0)
+    sum = Array(vector).inject(0.0) {|sum, n| sum + n}
+    vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
+    vector
+  end
+
+  ##################
+  # Instance methods
+  #
+  def initialize(win_loss_matrix)
+    @record = Record.new
+    @n = win_loss_matrix
+    case @n
+    when GSL::Matrix, GSL::Matrix::Int
+      @size = @n.size1
+    when ::Matrix
+      @size = @n.row_size
+    else
+      raise ArgumentError
+    end
+    initial_rate
+  end
+  attr_reader :rate, :n
+
+  def player_vector
+    GSL::Vector[*
+      (0...@size).collect {|k| yield k}
+    ]
+  end
+
+  def each_player
+    (0...@size).each {|k| yield k}
+  end
+
+  ##
+  # The possibility that the player k will beet the player i.
+  #
+  def win_rate(k,i)
+    1.0/(1.0 + exp(@rate[i]-@rate[k]))
+  end
+
+  ##
+  # Most possible equation
+  #
+  def func_vector
+    player_vector do|k| 
+      sum = 0.0
+      each_player do |i|
+        next if i == k
+        sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i) 
+      end
+      sum * 2.0
+    end
+  end
+
+  ##
+  #           / f0/R0 f0/R1 f0/R2 ... \
+  # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
+  #           \ f2/R0 f2/R1 f2/R2 ... /
+  def d_func(k,j)
+    sum = 0.0
+    if k == j
+      each_player do |i|
+        next if i == k
+        sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
+      end
+      sum *= -2.0
+    else # k != j
+      sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
+    end
+    sum
+  end
+
+  ##
+  # Jacobi matrix of the func().
+  #   m00 m01
+  #   m10 m11
+  #
+  def j_matrix
+    GSL::Matrix[*
+      (0...@size).collect do |k|
+        (0...@size).collect do |j|
+          d_func(k,j)
+        end
+      end
+    ]
+  end
+
+  ##
+  # The initial value of the rate, which is of very importance for Newton
+  # method.  This is based on my huristics; the higher the win probablity of
+  # a player is, the greater points he takes.
+  #
+  def initial_rate
+    possibility = 
+      player_vector do |k|
+        v = GSL::Vector[0, 0]
+        each_player do |i|
+          next if k == i
+          v += GSL::Vector[@n[k,i], @n[i,k]]
+        end
+        v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
+      end
+    rank = possibility.sort_index
+    @rate = player_vector do |k|
+      K*500 * (rank[k]+1) / @size
+    end
+    average!
+  end
+
+  ##
+  # Resets @rate as the higher the current win probablity of a player is, 
+  # the greater points he takes. 
+  #
+  def initial_rate2
+    @rate = @record.get || @rate
+    rank = @rate.sort_index
+    @rate = player_vector do |k|
+      K*@count*1.5 * (rank[k]+1) / @size
+    end
+    average!
+  end
+
+  # mu is the deaccelrating parameter in Deaccelerated Newton method
+  def deaccelrate(mu, old_rate, a, old_f_nrm2)
+    @rate = old_rate - a * mu
+    if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
+      return
+    end
+    if mu < 1e-4
+      @record.set(func_vector.nrm2, @rate)
+      initial_rate2
+      return
+    end
+    $stderr.puts "mu: %f " % [mu] if $DEBUG
+    deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
+  end
+
+  ##
+  # Main process to calculate ratings.
+  #
+  def rating
+    # Counter to stop the process. 
+    # Calulation in Newton method may fall in an infinite loop
+    @count = 0
+
+    # Main loop
+    begin
+      # Solve the equation: 
+      #   J*a=f
+      #   @rate_(n+1) = @rate_(n) - a
+      #
+      # f.nrm2 should approach to zero.
+      f = func_vector
+      j = j_matrix
+
+      # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
+      $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
+
+      # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
+      #a = GSL::Linalg::HH.solve(j, f)
+      a, = GSL::MultiFit::linear(j, f)
+      a = self.class.average(a)
+      # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
+      
+      # Deaccelerated Newton method
+      # GSL::Vector object should be immutable.
+      old_rate   = @rate
+      old_f      = f
+      old_f_nrm2 = old_f.nrm2
+      deaccelrate(1.0, old_rate, a, old_f_nrm2)
+      @record.set(func_vector.nrm2, @rate)
+
+      $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
+
+      @count += 1
+      if @count > COUNT_MAX
+        $stderr.puts "Values seem to oscillate. Stopped the process."
+        $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
+        break
+      end
+
+    end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
+    
+    @rate = @record.get
+    $stderr.puts "resolved f: %s -> %f" %
+      [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
+
+    @rate *= 1.0/K
+    finite!
+    self
+  end
+
+  ##
+  # Make the values of @rate finite.
+  #
+  def finite!
+    @rate = @rate.collect do |a|
+      if a.infinite?
+        a.infinite? * AVERAGE_RATE * 100
+      else
+        a
+      end
+    end
+  end
+
+  ##
+  # Flatten the values of @rate.
+  #
+  def average!(mean=0.0)
+    @rate = self.class.average(@rate, mean)
+  end
+
+  ##
+  # Translate by value
+  #
+  def translate!(value)
+    @rate += value
+  end
+
+  ##
+  # Make the values of @rate integer.
+  #
+  def integer!
+    @rate = @rate.collect do |a|
+      if a.finite?
+        a.to_i
+      elsif a.nan?
+        0
+      elsif a.infinite?
+        a.infinite? * AVERAGE_RATE * 100
+      end
+    end
+  end
+end
+
+#################################################
+# Encapsulate a pair of keys and win loss matrix.
+#   - keys is an array of player IDs; [gps+123, foo+234, ...]
+#   - matrix holds games # where player i (row index) beats player j (column index).
+#     The row and column indexes match with the keys.
+#
+# This object should be immutable. If an internal state is being modified, a
+# new object is always returned.
+#
+class WinLossMatrix
+
+  ###############
+  # Class methods
+  #  
+
+  def self.mk_matrix(players)
+    keys = players.keys.sort
+    size = keys.size
+    matrix =
+      GSL::Matrix[*
+      ((0...size).collect do |k|
+        p1 = keys[k]
+        p1_hash = players[p1]
+        ((0...size).collect do |j|
+          if k == j
+            0
+          else
+            p2 = keys[j]
+            v = p1_hash[p2] || Vector[0,0]
+            v[0]
+          end
+        end)
+      end)]
+    return WinLossMatrix.new(keys, matrix)
+  end
+
+  def self.mk_win_loss_matrix(players)
+    obj = mk_matrix(players)
+    return obj.filter
+  end
+
+  ##################
+  # Instance methods
+  #
+
+  # an array of player IDs; [gps+123, foo+234, ...]
+  attr_reader :keys
+
+  # matrix holds games # where player i (row index) beats player j (column index).
+  # The row and column indexes match with the keys.
+  attr_reader :matrix
+
+  def initialize(keys, matrix)
+    @keys   = keys
+    @matrix = matrix
+  end
+
+  ##
+  # Returns the size of the keys/matrix
+  #
+  def size
+    if @keys
+      @keys.size
+    else
+      nil
+    end
+  end
+
+  ##
+  # Removes players in a rows such as [1,3,5], and then returns a new
+  # object.
+  #
+  def delete_rows(rows)
+    rows = rows.sort.reverse
+
+    copied_cols = []
+    (0...size).each do |i|
+      next if rows.include?(i)
+      row = @matrix.row(i).clone
+      rows.each do |j|
+        row.delete_at(j)
+      end
+      copied_cols << row
+    end
+    if copied_cols.size == 0
+      new_matrix = GSL::Matrix.new
+    else
+      new_matrix = GSL::Matrix[*copied_cols]
+    end
+
+    new_keys = @keys.clone
+    rows.each do |j|
+      new_keys.delete_at(j)
+    end
+
+    return WinLossMatrix.new(new_keys, new_matrix)
+  end
+
+  ##
+  # Removes players who do not pass a criteria to be rated, and returns a
+  # new object.
+  # 
+  def filter
+    $stderr.puts @keys.inspect if $DEBUG
+    $stderr.puts @matrix.inspect if $DEBUG
+    delete = []  
+    (0...size).each do |i|
+      row = @matrix.row(i)
+      col = @matrix.col(i)
+      win  = row.sum
+      loss = col.sum
+      if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
+        delete << i
+      end
+    end
+
+    # The recursion ends if there is nothing to delete
+    return self if delete.empty?
+
+    new_obj = delete_rows(delete)
+    new_obj.filter
+  end
+
+  ##
+  # Cuts self into connecting groups such as each player in a group has at least
+  # one game with other players in the group. Returns them as an array.
+  #
+  def connected_subsets
+    g = RGL::AdjacencyGraph.new
+    (0...size).each do |k|
+      (0...size).each do |i|
+        next if k == i
+        if @matrix[k,i] > 0
+          g.add_edge(k,i)
+        end
+      end
+    end
+
+    subsets = []
+    g.each_connected_component do |c|
+      new_keys = []      
+      c.each do |v|
+        new_keys << keys[v.to_s.to_i]
+      end
+      subsets << new_keys
+    end
+
+    subsets = subsets.sort {|a,b| b.size <=> a.size}
+
+    result = subsets.collect do |keys|
+      matrix =
+        GSL::Matrix[*
+        ((0...keys.size).collect do |k|
+          p1 = @keys.index(keys[k])
+          ((0...keys.size).collect do |j|
+            if k == j
+              0
+            else
+              p2 = @keys.index(keys[j])
+              @matrix[p1,p2]
+            end
+          end)
+        end)]
+      WinLossMatrix.new(keys, matrix)
+    end
+
+    return result
+  end
+
+  def to_s
+    "size : #{@keys.size}" + "\n" +
+    @keys.inspect + "\n" + 
+    @matrix.inspect
+  end
+
+end
+
+
+#################################################
+# Main methods
+#
+
+# Half-life effect
+# After NHAFE_LIFE days value will get half.
+# 0.693 is constant, where exp(0.693) ~ 0.5
+def half_life(days)
+  if days < $options["half-life-ignore"]
+    return 1.0
+  else
+    Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
+  end
+end
+
+def _add_win_loss(winner, loser, time)
+  how_long_days = (Time.now - time)/(3600*24)
+  $players[winner] ||= Hash.new { GSL::Vector[0,0] }
+  $players[loser]  ||= Hash.new { GSL::Vector[0,0] }
+  $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
+  $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
+end
+
+def _add_time(player, time)
+  $players_time[player] = time if $players_time[player] < time
+end
+
+def add(black_mark, black_name, white_name, white_mark, time)
+  if black_mark == WIN_MARK && white_mark == LOSS_MARK
+    _add_win_loss(black_name, white_name, time)
+  elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
+    _add_win_loss(white_name, black_name, time)
+  elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
+    return
+  else
+    raise "Never reached!"
+  end
+  _add_time(black_name, time)
+  _add_time(white_name, time)
+end
+
+def identify_id(id)
+  if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
+    return nil
+  end
+  id.gsub(/@.*?\+/,"+")
+end
+
+def grep(file)
+  str = File.open(file).read
+
+  if /^N\+(.*)$/ =~ str then black_name = $1.strip end
+  if /^N\-(.*)$/ =~ str then white_name = $1.strip end
+
+  if /^'summary:(.*)$/ =~ str
+    state, p1, p2 = $1.split(":").map {|a| a.strip}    
+    return if state == "abnormal"
+    p1_name, p1_mark = p1.split(" ")
+    p2_name, p2_mark = p2.split(" ")
+    if p1_name == black_name
+      black_name, black_mark = p1_name, p1_mark
+      white_name, white_mark = p2_name, p2_mark
+    elsif p2_name == black_name
+      black_name, black_mark = p2_name, p2_mark
+      white_name, white_mark = p1_name, p1_mark
+    else
+      raise "Never reach!: #{black} #{white} #{p3} #{p2}"
+    end
+  end
+  if /^'\$END_TIME:(.*)$/ =~ str
+    time = Time.parse($1.strip)
+  end
+  if /^'rating:(.*)$/ =~ str
+    black_id, white_id = $1.split(":").map {|a| a.strip}
+    black_id = identify_id(black_id)
+    white_id = identify_id(white_id)
+    if black_id && white_id && (black_id != white_id) &&
+       black_mark && white_mark
+      $stdout.printf("%s %s %s %s %d\n", black_mark, black_id, white_id, white_mark, time)
+      $stdout.flush
+    end
+  end
+end
+
+def usage
+  $stderr.puts <<-EOF
+USAGE: #{$0} dir [...]
+  EOF
+  exit 1
+end
+
+def validate(yaml)
+  yaml["players"].each do |group_key, group|
+    group.each do |player_key, player|
+      rate = player['rate']
+      next unless rate
+      if rate > 10000 || rate < -10000
+        return false
+      end
+    end
+  end
+  return true
+end
+
+def usage(io)
+    io.puts <<EOF
+USAGE: #{$0} [options] DIR..
+  DIR                where CSA files are looked up recursively
+OPTOINS:
+  --half-life         n [days] (default 60)
+  --half-life-ignore  m [days] (default  7)
+                      after m days, half-life effect works
+  --fixed-rate-player player whose rate is fixed at the rate
+  --fixed-rate        rate 
+  --help              show this message
+EOF
+end
+
+def main
+  $options = Hash::new
+  parser = GetoptLong.new(
+    ["--half-life",         GetoptLong::REQUIRED_ARGUMENT],
+    ["--half-life-ignore",  GetoptLong::REQUIRED_ARGUMENT],
+    ["--help", "-h",        GetoptLong::NO_ARGUMENT],
+    ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
+    ["--fixed-rate",        GetoptLong::REQUIRED_ARGUMENT])
+  parser.quiet = true
+  begin
+    parser.each_option do |name, arg|
+      name.sub!(/^--/, '')
+      $options[name] = arg.dup
+    end
+    if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
+       (!$options["fixed-rate-player"] &&  $options["fixed-rate"]) ||
+       ( $options["fixed-rate-player"] &&  $options["fixed-rate"].to_i <= 0) 
+      usage($stderr)
+      exit 1
+    end
+  rescue
+    usage($stderr)
+    raise parser.error_message
+  end
+  if $options["help"]
+    usage($stdout) 
+    exit 0
+  end
+  $options["half-life"] ||= 60
+  $options["half-life"] = $options["half-life"].to_i
+  $options["half-life-ignore"] ||= 7
+  $options["half-life-ignore"] = $options["half-life-ignore"].to_i
+  $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
+
+  if ARGV.empty?
+    while line = $stdin.gets do
+      next unless %r!.*\.csa$! =~ line
+      grep line.strip
+    end
+  else
+    while dir = ARGV.shift do
+      Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
+    end
+  end
+  $stderr.puts "read done."
+end
+
+if __FILE__ == $0
+  main
+end
+
+# vim: ts=2 sw=2 sts=0
index dfef06e..3ac2605 100755 (executable)
@@ -143,9 +143,6 @@ LICENSE
 
 SEE ALSO
 
-RELEASE
-        #{ShogiServer::Release}
-
 REVISION
         #{ShogiServer::Revision}
 
index c957f3d..4ddf963 100644 (file)
@@ -51,8 +51,7 @@ Default_Game_Name = "default-1500-0"
 One_Time = 10
 Least_Time_Per_Move = 1
 Login_Time = 300                # time for LOGIN
-Release  = "$Id$"
-Revision = (r = /Revision: (\d+)/.match("$Revision$") ? r[1] : 0)
+Revision = "20131104"
 
 RELOAD_FILES = ["shogi_server/league/floodgate.rb",
                 "shogi_server/league/persistent.rb",
index 80418c2..3bd01b1 100644 (file)
@@ -43,17 +43,42 @@ EOF
 
   # Split a moves line into an array of a move string.
   # If it fails to parse the moves, it raises WrongMoves.
-  # @param moves a moves line. Ex. "+776FU-3334Fu"
-  # @return an array of a move string. Ex. ["+7776FU", "-3334FU"]
+  # @param moves a moves line. Ex. "+776FU-3334FU" or
+  #              moves with times. Ex "+776FU,T2-3334FU,T5"
+  # @return an array of a move string. Ex. ["+7776FU", "-3334FU"] or
+  #         an array of arrays. Ex. [["+7776FU","T2"], ["-3334FU", "T5"]]
   #
   def Board.split_moves(moves)
     ret = []
 
-    rs = moves.gsub %r{[\+\-]\d{4}\w{2}} do |s|
-           ret << s
-           ""
-         end
-    raise WrongMoves, rs unless rs.empty?
+    i=0
+    tmp = ""
+    while i<moves.size
+      if moves[i,1] == "+" ||
+         moves[i,1] == "-" ||
+         i == moves.size - 1
+        if i == moves.size - 1
+          tmp << moves[i,1]
+        end
+        unless tmp.empty?
+          a = tmp.split(",")
+          if a[0].size != 7
+            raise WrongMoves, a[0]
+          end
+          if a.size == 1 # "+7776FU"
+            ret << a[0]
+          else           # "+7776FU,T2"
+            unless /^T\d+/ =~ a[1] 
+              raise WrongMoves, a[1]
+            end
+            ret << a
+          end
+          tmp = ""
+        end
+      end
+      tmp << moves[i,1]
+      i += 1
+    end
 
     return ret
   end
@@ -242,14 +267,21 @@ EOF
 
   # Set up a board starting with a position after the moves.
   # Failing to parse the moves raises an ArgumentError.
-  # @param moves an array of moves. ex. ["+7776FU", "-3334FU"]
+  # @param moves an array of moves. ex. ["+7776FU", "-3334FU"] or
+  #        an array of arrays. ex. [["+7776FU","T2"], ["-3334FU","T5"]]
   #
   def set_from_moves(moves)
     initial()
     return :normal if moves.empty?
     rt = nil
     moves.each do |move|
-      rt = handle_one_move(move, @teban)
+      rt = nil
+      case move
+      when Array
+        rt = handle_one_move(move[0], @teban)
+      when String
+        rt = handle_one_move(move, @teban)
+      end
       raise ArgumentError, "bad moves: #{moves}" unless rt == :normal
     end
     @initial_moves = moves.dup
index c46c575..e2f88ee 100644 (file)
@@ -21,7 +21,7 @@ module ShogiServer
     end
 
     def ==(rhs)
-      return (@game_name == rhs.game_name && 
+      return (@game_name == rhs.game_name &&
               @moves == rhs.moves &&
               @owner == rhs.owner &&
               @count == rhs.count)
index 02626d3..b09b95a 100644 (file)
@@ -69,6 +69,9 @@ module ShogiServer
         my_sente_str = $3
         cmd = GameChallengeCommand.new(str, player, 
                                        command_name, game_name, my_sente_str)
+      when /^%%(GAME|CHALLENGE)\s+(\S+)/
+        msg = "A turn identifier is required"
+        cmd = ErrorCommand.new(str, player, msg)
       when /^%%CHAT\s+(.+)/
         message = $1
         cmd = ChatCommand.new(str, player, message, $league.players)
@@ -94,6 +97,19 @@ module ShogiServer
       when /^%%GETBUOYCOUNT\s+(\S+)/
         game_name = $1
         cmd = GetBuoyCountCommand.new(str, player, game_name)
+      when /^%%FORK\s+(\S+)\s+(\S+)(.*)/
+        source_game   = $1
+        new_buoy_game = $2
+        nth_move      = nil
+        if $3 && /^\s+(\d+)/ =~ $3
+          nth_move = $3.to_i
+        end
+        cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
+      when /^%%FORK\s+(\S+)$/
+        source_game   = $1
+        new_buoy_game = nil
+        nth_move      = nil
+        cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
       when /^\s*$/
         cmd = SpaceCommand.new(str, player)
       when /^%%%[^%]/
@@ -481,7 +497,16 @@ module ShogiServer
 
     def call
       if (! Login::good_game_name?(@game_name))
-        @player.write_safe(sprintf("##[ERROR] bad game name\n"))
+        @player.write_safe(sprintf("##[ERROR] bad game name: %s.\n", @game_name))
+        if (/^(.+)-\d+-\d+$/ =~ @game_name)
+          if Login::good_identifier?($1)
+            # do nothing
+          else
+            @player.write_safe(sprintf("##[ERROR] invalid identifiers are found or too many characters are used.\n"))
+          end
+        else
+          @player.write_safe(sprintf("##[ERROR] game name should consist of three parts like game-1500-60.\n"))
+        end
         return :continue
       elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
         ## continue
@@ -666,9 +691,9 @@ module ShogiServer
   # Command for an error
   #
   class ErrorCommand < Command
-    def initialize(str, player)
-      super
-      @msg = nil
+    def initialize(str, player, msg=nil)
+      super(str, player)
+      @msg = msg || "unknown command"
     end
     attr_reader :msg
 
@@ -676,7 +701,7 @@ module ShogiServer
       cmd = @str.chomp
       # Aim to hide a possible password
       cmd.gsub!(/LOGIN\s*(\w+)\s+.*/i, 'LOGIN \1...')
-      @msg = "##[ERROR] unknown command %s\n" % [cmd]
+      @msg = "##[ERROR] %s: %s\n" % [@msg, cmd]
       @player.write_safe(@msg)
       log_error(@msg)
       return :continue
@@ -810,4 +835,69 @@ module ShogiServer
     end
   end
 
+  # %%FORK <source_game> <new_buoy_game> [<nth-move>]
+  # Fork a new game from the posistion where the n-th (starting from 1) move
+  # of a source game is played. The new game should be a valid buoy game
+  # name. The default value of n is the position where the previous position
+  # of the last one.
+  #
+  class ForkCommand < Command
+    def initialize(str, player, source_game, new_buoy_game, nth_move)
+      super(str, player)
+      @source_game   = source_game
+      @new_buoy_game = new_buoy_game
+      @nth_move      = nth_move # may be nil
+    end
+    attr_reader :new_buoy_game
+
+    def decide_new_buoy_game_name
+      name       = nil
+      total_time = nil
+      byo_time   = nil
+
+      if @source_game.split("+").size >= 2 &&
+         /^([^-]+)-(\d+)-(\d+)/ =~ @source_game.split("+")[1]
+        name       = $1
+        total_time = $2
+        byo_time   = $3
+      end
+      if name == nil || total_time == nil || byo_time == nil
+        @player.write_safe(sprintf("##[ERROR] wrong source game name to make a new buoy game name: %s\n", @source_game))
+        log_error "Received a wrong source game name to make a new buoy game name: %s from %s." % [@source_game, @player.name]
+        return :continue
+      end
+      @new_buoy_game = "buoy_%s_%d-%s-%s" % [name, @nth_move, total_time, byo_time]
+      @player.write_safe(sprintf("##[FORK]: new buoy game name: %s\n", @new_buoy_game))
+      @player.write_safe("##[FORK] +OK\n")
+    end
+
+    def call
+      game = $league.games[@source_game]
+      unless game
+        @player.write_safe(sprintf("##[ERROR] wrong source game name: %s\n", @source_game))
+        log_error "Received a wrong source game name: %s from %s." % [@source_game, @player.name]
+        return :continue
+      end
+
+      moves = game.read_moves # [["+7776FU","T2"],["-3334FU","T5"]]
+      @nth_move = moves.size - 1 unless @nth_move
+      if @nth_move > moves.size or @nth_move < 1
+        @player.write_safe(sprintf("##[ERROR] number of moves to fork is out of range: %s.\n", moves.size))
+        log_error "Number of moves to fork is out of range: %s [%s]" % [@nth_move, @player.name]
+        return :continue
+      end
+      new_moves_str = ""
+      moves[0...@nth_move].each do |m|
+        new_moves_str << m.join(",")
+      end
+
+      unless @new_buoy_game
+        decide_new_buoy_game_name
+      end
+
+      buoy_cmd = SetBuoyCommand.new(@str, @player, @new_buoy_game, new_moves_str, 1)
+      return buoy_cmd.call
+    end
+  end
+
 end # module ShogiServer
index d187e8d..ec9b702 100644 (file)
@@ -19,6 +19,7 @@
 
 require 'shogi_server/league/floodgate'
 require 'shogi_server/game_result'
+require 'shogi_server/time_clock'
 require 'shogi_server/util'
 
 module ShogiServer # for a namespace
@@ -69,6 +70,8 @@ class Game
     if (@game_name =~ /-(\d+)-(\d+)$/)
       @total_time = $1.to_i
       @byoyomi = $2.to_i
+
+      @time_clock = TimeClock::factory(Least_Time_Per_Move, @game_name)
     end
 
     if (player0.sente)
@@ -87,7 +90,16 @@ class Game
     @sente.game = self
     @gote.game  = self
 
-    @last_move = @board.initial_moves.empty? ? "" : "%s,T1" % [@board.initial_moves.last]
+    @last_move = ""
+    unless @board.initial_moves.empty?
+      last_move = @board.initial_moves.last
+      case last_move
+      when Array
+        @last_move = last_move.join(",")
+      when String
+        @last_move = "%s,T1" % [last_move]
+      end
+    end
     @current_turn = @board.initial_moves.size
 
     @sente.status = "agree_waiting"
@@ -110,6 +122,7 @@ class Game
     $league.games[@game_id] = self
 
     log_message(sprintf("game created %s", @game_id))
+    log_message("    " + @time_clock.to_s)
 
     @start_time = nil
     @fh = open(@logfile, "w")
@@ -118,7 +131,7 @@ class Game
 
     propose
   end
-  attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
+  attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors, :time_clock
   attr_accessor :last_move, :current_turn
   attr_reader   :result, :prepared_time
 
@@ -218,22 +231,16 @@ class Game
       return nil
     end
 
-    finish_flag = true
     @end_time = end_time
-    t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
-    
+    finish_flag = true
     move_status = nil
-    if ((@current_player.mytime - t <= -@byoyomi) && 
-        ((@total_time > 0) || (@byoyomi > 0)))
+
+    if (@time_clock.timeout?(@current_player, @start_time, @end_time))
       status = :timeout
     elsif (str == :timeout)
       return false            # time isn't expired. players aren't swapped. continue game
     else
-      @current_player.mytime -= t
-      if (@current_player.mytime < 0)
-        @current_player.mytime = 0
-      end
-
+      t = @time_clock.process_time(@current_player, @start_time, @end_time)
       move_status = @board.handle_one_move(str, @sente == @current_player)
       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
 
@@ -332,8 +339,14 @@ class Game
     unless @board.initial_moves.empty?
       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
       @board.initial_moves.each do |move|
-        @fh.puts move
-        @fh.puts "T1"
+        case move
+        when Array
+          @fh.puts move[0]
+          @fh.puts move[1]
+        when String
+          @fh.puts move
+          @fh.puts "T1"
+        end
       end
     end
   end
@@ -351,7 +364,7 @@ Name-:#{@gote.name}
 Rematch_On_Draw:NO
 To_Move:+
 BEGIN Time
-Time_Unit:1sec
+Time_Unit:#{@time_clock.time_unit}
 Total_Time:#{@total_time}
 Byoyomi:#{@byoyomi}
 Least_Time_Per_Move:#{Least_Time_Per_Move}
@@ -385,14 +398,21 @@ Your_Turn:#{sg_flag}
 Rematch_On_Draw:NO
 To_Move:#{@board.teban ? "+" : "-"}
 BEGIN Time
-Time_Unit:1sec
+Time_Unit:#{@time_clock.time_unit}
 Total_Time:#{@total_time}
 Byoyomi:#{@byoyomi}
 Least_Time_Per_Move:#{Least_Time_Per_Move}
 END Time
 BEGIN Position
 #{@board.initial_string.chomp}
-#{@board.initial_moves.collect {|m| m + ",T1"}.join("\n")}
+#{@board.initial_moves.collect do |m|
+  case m
+  when Array
+    m.join(",")
+  when String
+    m + ",T1"
+  end
+end.join("\n")}
 END Position
 END Game_Summary
 EOM
@@ -408,6 +428,21 @@ EOM
 
     return false
   end
+
+  # Read the .csa file and returns an array of moves and times.
+  # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
+  #
+  def read_moves
+    ret = []
+    IO.foreach(@logfile) do |line|
+      if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
+        ret << [line.chomp]
+      elsif /^T\d*/ =~ line
+        ret[-1] << line.chomp
+      end
+    end
+    return ret
+  end
   
   private
   
index b5478b9..b7f26f5 100644 (file)
@@ -257,6 +257,18 @@ class League
         return rc[:loser] == player_id
       end
 
+      def last_opponent(player_id)
+        rc = last_valid_game(player_id)
+        return nil unless rc
+        if rc[:black] == player_id
+          return rc[:white]
+        elsif rc[:white] == player_id
+          return rc[:black]
+        else
+          return nil
+        end
+      end
+
       def last_valid_game(player_id)
         records = nil
         @@mutex.synchronize do
@@ -269,6 +281,28 @@ class League
         end
         return rc
       end
+
+      def win_games(player_id)
+        records = nil
+        @@mutex.synchronize do
+          records = @records.reverse
+        end
+        rc = records.find_all do |rc|
+          rc[:winner] == player_id && rc[:loser]
+        end
+        return rc
+      end
+
+      def loss_games(player_id)
+        records = nil
+        @@mutex.synchronize do
+          records = @records.reverse
+        end
+        rc = records.find_all do |rc|
+          rc[:winner] && rc[:loser] == player_id
+        end
+        return rc
+      end
     end # class History
 
 
index d49366d..11f7665 100644 (file)
@@ -25,7 +25,7 @@ module ShogiServer
 
     class << self
       def default_factory
-        return swiss_pairing
+        return least_diff_pairing
       end
 
       def sort_by_rate_with_randomness
@@ -52,6 +52,14 @@ module ShogiServer
                 StartGameWithoutHumans.new]
       end
 
+      def least_diff_pairing
+        return [LogPlayers.new,
+                ExcludeSacrificeGps500.new,
+                MakeEven.new,
+                LeastDiff.new,
+                StartGameWithoutHumans.new]
+      end
+
       def match(players)
         logics = default_factory
         logics.inject(players) do |result, item|
@@ -62,6 +70,10 @@ module ShogiServer
     end # class << self
 
 
+    # Make matches among players.
+    # @param players an array of players, which should be updated destructively
+    #        to pass the new list to subsequent logics.
+    #
     def match(players)
       # to be implemented
       log_message("Floodgate: %s" % [self.class.to_s])
@@ -232,17 +244,18 @@ module ShogiServer
   end
 
   class SortByRateWithRandomness < Pairing
-    def initialize(rand1, rand2)
+    def initialize(rand1, rand2, desc=false)
       super()
       @rand1, @rand2 = rand1, rand2
+      @desc = desc
     end
 
-    def match(players, desc=false)
+    def match(players)
       super(players)
       cur_rate = Hash.new
       players.each{|a| cur_rate[a] = a.rate ? a.rate + rand(@rand1) : rand(@rand2)}
       players.sort!{|a,b| cur_rate[a] <=> cur_rate[b]}
-      players.reverse! if desc
+      players.reverse! if @desc
       log_players(players) do |one|
         "%s %d (+ randomness %d)" % [one.name, one.rate, cur_rate[one] - one.rate]
       end
@@ -267,12 +280,12 @@ module ShogiServer
       rest = players - winners
 
       log_message("Floodgate: Ordering %d winners..." % [winners.size])
-      sbrwr_winners = SortByRateWithRandomness.new(800, 2500)
-      sbrwr_winners.match(winners, true)
+      sbrwr_winners = SortByRateWithRandomness.new(800, 2500, true)
+      sbrwr_winners.match(winners)
 
       log_message("Floodgate: Ordering the rest (%d)..." % [rest.size])
-      sbrwr_losers = SortByRateWithRandomness.new(200, 400)
-      sbrwr_losers.match(rest, true)
+      sbrwr_losers = SortByRateWithRandomness.new(200, 400, true)
+      sbrwr_losers.match(rest)
 
       players.clear
       [winners, rest].each do |group|
@@ -364,4 +377,126 @@ module ShogiServer
     end
   end
 
+  # This pairing algorithm aims to minimize the total differences of
+  # matching players' rates. It also includes penalyties when a match is
+  # same as the previous one or a match is between human players.
+  # It is based on a discussion with Yamashita-san on
+  # http://www.sgtpepper.net/kaneko/diary/20120511.html.
+  #
+  class LeastDiff < Pairing
+    def random_match(players)
+      players.shuffle
+    end
+
+    # Returns a player's rate value.
+    # 1. If it has a valid rate, return the rate.
+    # 2. If it has no valid rate, return average of the following values:
+    #   a. For games it won, the opponent's rate + 100
+    #   b. For games it lost, the opponent's rate - 100
+    #   (if the opponent has no valid rate, count out the game)
+    #   (if there are not such games, return 2150 (default value)
+    #
+    def get_player_rate(player, history)
+      return player.rate if player.rate != 0
+      return 2150 unless history
+
+      count = 0
+      sum = 0
+
+      history.win_games(player.player_id).each do |g|
+        next unless g[:loser]
+        name = g[:loser].split("+")[0]
+        p = $league.find(name)
+        if p && p.rate != 0
+          count += 1
+          sum += p.rate + 100
+        end
+      end
+      history.loss_games(player.player_id).each do |g|
+        next unless g[:winner]
+        name = g[:winner].split("+")[0]
+        p = $league.find(name)
+        if p && p.rate != 0
+          count += 1
+          sum += p.rate - 100
+        end
+      end
+
+      estimate = (count == 0 ? 2150 : sum/count)
+      log_message("Floodgate: Estimated rate of %s is %d" % [player.name, estimate])
+      return estimate
+    end
+
+    def calculate_diff_with_penalty(players, history)
+      pairs = []
+      players.each_slice(2) do |pair|
+        if pair.size == 2
+          pairs << pair
+        end
+      end
+
+      ret = 0
+
+      # 1. Diff of players rate
+      pairs.each do |p1,p2|
+        ret += (get_player_rate(p1,history) - get_player_rate(p2,history)).abs
+      end
+
+      # 2. Penalties
+      pairs.each do |p1,p2|
+        # 2.1. same match
+        if (history &&
+            (history.last_opponent(p1.player_id) == p2.player_id ||
+             history.last_opponent(p2.player_id) == p1.player_id))
+          ret += 400
+        end
+
+        # 2.2 Human vs Human
+        if p1.is_human? && p2.is_human?
+          ret += 800
+        end
+      end
+
+      ret
+    end
+
+    def match(players)
+      super
+      if players.size < 3
+        log_message("Floodgate: players are small enough to skip LeastDiff pairing: %d" % [players.size])
+        return players
+      end
+
+      # 10 trials
+      matches = []
+      scores  = []
+      path = ShogiServer::League::Floodgate.history_file_path(players.first.game_name)
+      history = ShogiServer::League::Floodgate::History.factory(path)
+      10.times do 
+        m = random_match(players)
+        matches << m
+        scores << calculate_diff_with_penalty(m, history)
+      end
+
+      # Debug
+      #scores.each_with_index do |s,i|
+      #  puts
+      #  print s, ": ", matches[i].map{|p| p.name}.join(", "), "\n"
+      #end
+
+      # Select a match of the least score
+      min_index = 0
+      min_score = scores.first
+      scores.each_with_index do |s,i|
+        if s < min_score
+          min_index = i
+          min_score = s
+        end
+      end
+      log_message("Floodgate: the least score %d (%d per player) [%s]" % [min_score, min_score/players.size, scores.join(" ")])
+
+      players.replace(matches[min_index])
+    end
+  end
+
 end # ShogiServer
diff --git a/shogi_server/time_clock.rb b/shogi_server/time_clock.rb
new file mode 100644 (file)
index 0000000..6426fda
--- /dev/null
@@ -0,0 +1,139 @@
+## $Id$
+
+## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
+## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
+##
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 2 of the License, or
+## (at your option) any later version.
+##
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+module ShogiServer # for a namespace
+
+# Abstract class to caclulate thinking time.
+#
+class TimeClock
+
+  def TimeClock.factory(least_time_per_move, game_name)
+    total_time_str = nil
+    byoyomi_str = nil
+    if (game_name =~ /-(\d+)-(\d+)$/)
+      total_time_str = $1
+      byoyomi_str    = $2
+    end
+    total_time = total_time_str.to_i
+    byoyomi    = byoyomi_str.to_i
+    if (byoyomi_str == "060")
+      @time_clock = StopWatchClock.new(least_time_per_move, total_time, byoyomi)
+    else
+      @time_clock = ChessClock.new(least_time_per_move, total_time, byoyomi)
+    end
+  end
+
+  def initialize(least_time_per_move, total_time, byoyomi)
+    @least_time_per_move = least_time_per_move
+    @total_time = total_time
+    @byoyomi     = byoyomi
+  end
+
+  # Returns thinking time duration
+  #
+  def time_duration(start_time, end_time)
+    # implement this
+    return 9999999
+  end
+
+  # Returns what "Time_Unit:" in CSA protocol should provide.
+  #
+  def time_unit
+    return "1sec"
+  end
+
+  # If thinking time runs out, returns true; false otherwise.
+  #
+  def timeout?(player, start_time, end_time)
+    # implement this
+    return true
+  end
+
+  # Updates a player's remaining time and returns thinking time.
+  #
+  def process_time(player, start_time, end_time)
+    t = time_duration(start_time, end_time)
+    
+    player.mytime -= t
+    if (player.mytime < 0)
+      player.mytime = 0
+    end
+
+    return t
+  end
+end
+
+# Calculates thinking time with chess clock.
+#
+class ChessClock < TimeClock
+  def initialize(least_time_per_move, total_time, byoyomi)
+    super
+  end
+
+  def time_duration(start_time, end_time)
+    return [(end_time - start_time).floor, @least_time_per_move].max
+  end
+
+  def timeout?(player, start_time, end_time)
+    t = time_duration(start_time, end_time)
+
+    if ((player.mytime - t <= -@byoyomi) && 
+        ((@total_time > 0) || (@byoyomi > 0)))
+      return true
+    else
+      return false
+    end
+  end
+
+  def to_s
+    return "ChessClock: LeastTimePerMove %d; TotalTime %d; Byoyomi %d" % [@least_time_per_move, @total_time, @byoyomi]
+  end
+end
+
+class StopWatchClock < TimeClock
+  def initialize(least_time_per_move, total_time, byoyomi)
+    super
+  end
+
+  def time_unit
+    return "1min"
+  end
+
+  def time_duration(start_time, end_time)
+    t = [(end_time - start_time).floor, @least_time_per_move].max
+    return (t / @byoyomi) * @byoyomi
+  end
+
+  def timeout?(player, start_time, end_time)
+    t = time_duration(start_time, end_time)
+
+    if (player.mytime <= t)
+      return true
+    else
+      return false
+    end
+  end
+
+  def to_s
+    return "StopWatchClock: LeastTimePerMove %d; TotalTime %d; Byoyomi %d" % [@least_time_per_move, @total_time, @byoyomi]
+  end
+end
+
+end
index 786b8c3..d82277d 100644 (file)
@@ -10,6 +10,7 @@ require 'TC_floodgate'
 require 'TC_floodgate_history'
 require 'TC_floodgate_next_time_generator'
 require 'TC_floodgate_thread.rb'
+require 'TC_fork'
 require 'TC_functional'
 require 'TC_game'
 require 'TC_game_result'
@@ -24,6 +25,7 @@ require 'TC_oute_sennichite'
 require 'TC_pairing'
 require 'TC_player'
 require 'TC_rating'
+require 'TC_time_clock'
 require 'TC_uchifuzume'
 require 'TC_usi'
 require 'TC_util'
index 18f971b..5e231fa 100644 (file)
@@ -228,6 +228,16 @@ class TestFactoryMethod < Test::Unit::TestCase
     assert_instance_of(ShogiServer::GetBuoyCountCommand, cmd)
   end
 
+  def test_fork_command
+    cmd = ShogiServer::Command.factory("%%FORK server-denou-14400-60+p1+p2+20130223185013 buoy_denou-14400-60", @p)
+    assert_instance_of(ShogiServer::ForkCommand, cmd)
+  end
+
+  def test_fork_command2
+    cmd = ShogiServer::Command.factory("%%FORK server-denou-14400-60+p1+p2+20130223185013", @p)
+    assert_instance_of(ShogiServer::ForkCommand, cmd)
+  end
+
   def test_void_command
     cmd = ShogiServer::Command.factory("%%%HOGE", @p)
     assert_instance_of(ShogiServer::VoidCommand, cmd)
@@ -237,29 +247,29 @@ class TestFactoryMethod < Test::Unit::TestCase
     cmd = ShogiServer::Command.factory("should_be_error", @p)
     assert_instance_of(ShogiServer::ErrorCommand, cmd)
     cmd.call
-    assert_match /unknown command should_be_error/, cmd.msg
+    assert_match /unknown command: should_be_error/, cmd.msg
   end
 
   def test_error_login
     cmd = ShogiServer::Command.factory("LOGIN hoge foo", @p)
     assert_instance_of(ShogiServer::ErrorCommand, cmd)
     cmd.call
-    assert_no_match /unknown command LOGIN hoge foo/, cmd.msg
+    assert_no_match /unknown command: LOGIN hoge foo/, cmd.msg
 
     cmd = ShogiServer::Command.factory("LOGin hoge foo", @p)
     assert_instance_of(ShogiServer::ErrorCommand, cmd)
     cmd.call
-    assert_no_match /unknown command LOGIN hoge foo/, cmd.msg
+    assert_no_match /unknown command: LOGIN hoge foo/, cmd.msg
 
     cmd = ShogiServer::Command.factory("LOGIN  hoge foo", @p)
     assert_instance_of(ShogiServer::ErrorCommand, cmd)
     cmd.call
-    assert_no_match /unknown command LOGIN hoge foo/, cmd.msg
+    assert_no_match /unknown command: LOGIN hoge foo/, cmd.msg
 
     cmd = ShogiServer::Command.factory("LOGINhoge foo", @p)
     assert_instance_of(ShogiServer::ErrorCommand, cmd)
     cmd.call
-    assert_no_match /unknown command LOGIN hoge foo/, cmd.msg
+    assert_no_match /unknown command: LOGIN hoge foo/, cmd.msg
   end
 end
 
@@ -939,6 +949,28 @@ end
 
 #
 #
+class TestForkCommand < Test::Unit::TestCase
+  def setup
+    @player = MockPlayer.new
+  end
+
+  def test_new_buoy_game_name
+    src = "%%FORK server+denou-14400-60+p1+p2+20130223185013"
+    c = ShogiServer::ForkCommand.new src, @player, "server+denou-14400-60+p1+p2+20130223185013", nil, 13
+    c.decide_new_buoy_game_name
+    assert_equal "buoy_denou_13-14400-60", c.new_buoy_game
+  end
+
+  def test_new_buoy_game_name2
+    src = "%%FORK server+denou-14400-060+p1+p2+20130223185013"
+    c = ShogiServer::ForkCommand.new src, @player, "server+denou-14400-060+p1+p2+20130223185013", nil, 13
+    c.decide_new_buoy_game_name
+    assert_equal "buoy_denou_13-14400-060", c.new_buoy_game
+  end
+end
+
+#
+#
 class TestGetBuoyCountCommand < BaseTestBuoyCommand
   def test_call
     buoy_game = ShogiServer::BuoyGame.new("buoy_testdeletebuoy-1500-0", "+7776FU", @p.name, 1)
@@ -1051,4 +1083,3 @@ class TestMonitorHandler2 < Test::Unit::TestCase
                  @player.out.join)
   end
 end
-
index 3a1a471..c53d9a1 100644 (file)
@@ -395,6 +395,22 @@ class TestFloodgateHistory < Test::Unit::TestCase
     assert !@history.last_win?("foo")
     assert !@history.last_lose?("hoge")
     assert @history.last_lose?("foo")
+
+    assert_equal("foo", @history.last_opponent("hoge"))
+    assert_equal("hoge", @history.last_opponent("foo"))
+
+    games = @history.win_games("hoge")
+    assert_equal(1, games.size )
+    assert_equal("wdoor+floodgate-900-0-hoge-foo-2", games[0][:game_id])
+    games = @history.win_games("foo")
+    assert_equal(1, games.size )
+    assert_equal("wdoor+floodgate-900-0-hoge-foo-1", games[0][:game_id])
+    games = @history.loss_games("hoge")
+    assert_equal(1, games.size )
+    assert_equal("wdoor+floodgate-900-0-hoge-foo-1", games[0][:game_id])
+    games = @history.loss_games("foo")
+    assert_equal(1, games.size )
+    assert_equal("wdoor+floodgate-900-0-hoge-foo-2", games[0][:game_id])
   end
 end
 
diff --git a/test/TC_fork.rb b/test/TC_fork.rb
new file mode 100644 (file)
index 0000000..7e2b6f3
--- /dev/null
@@ -0,0 +1,131 @@
+$:.unshift File.join(File.dirname(__FILE__), "..")
+$topdir = File.expand_path File.dirname(__FILE__)
+require "baseclient"
+require "shogi_server/buoy.rb"
+
+class TestFork < BaseClient
+  def parse_game_name(player)
+    player.puts "%%LIST"
+    sleep 1
+    if /##\[LIST\] (.*)/ =~ player.message
+      return $1
+    end
+  end
+
+  def test_wrong_game
+    @admin = SocketPlayer.new "dummy", "admin", false
+    @admin.connect
+    @admin.reader
+    @admin.login
+
+    result, result2 = handshake do
+      @admin.puts "%%FORK wronggame-900-0 buoy_WrongGame-900-0"
+      sleep 1
+    end
+
+    assert /##\[ERROR\] wrong source game name/ =~ @admin.message
+    @admin.logout
+  end
+
+  def test_too_short_fork
+    @admin = SocketPlayer.new "dummy", "admin", false
+    @admin.connect
+    @admin.reader
+    @admin.login
+
+    result, result2 = handshake do
+      source_game = parse_game_name(@admin)
+      @admin.puts "%%FORK #{source_game} buoy_TooShortFork-900-0 0"
+      sleep 1
+    end
+
+    assert /##\[ERROR\] number of moves to fork is out of range/ =~ @admin.message
+    @admin.logout
+  end
+
+  def test_fork
+    buoy = ShogiServer::Buoy.new
+    
+    @admin = SocketPlayer.new "dummy", "admin", "*"
+    @admin.connect
+    @admin.reader
+    @admin.login
+    assert buoy.is_new_game?("buoy_Fork-1500-0")
+
+    result, result2 = handshake do
+      source_game = parse_game_name(@admin)
+      @admin.puts "%%FORK #{source_game} buoy_Fork-1500-0"
+      sleep 1
+    end
+
+    assert buoy.is_new_game?("buoy_Fork-1500-0")
+    @p1 = SocketPlayer.new "buoy_Fork", "p1", true
+    @p2 = SocketPlayer.new "buoy_Fork", "p2", false
+    @p1.connect
+    @p2.connect
+    @p1.reader
+    @p2.reader
+    @p1.login
+    @p2.login
+    sleep 1
+    @p1.game
+    @p2.game
+    sleep 1
+    @p1.agree
+    @p2.agree
+    sleep 1
+    assert /^Total_Time:1500/ =~ @p1.message
+    assert /^Total_Time:1500/ =~ @p2.message
+    @p2.move("-3334FU")
+    sleep 1
+    @p1.toryo
+    sleep 1
+    @p2.logout
+    @p1.logout
+
+    @admin.logout
+  end
+
+  def test_fork2
+    buoy = ShogiServer::Buoy.new
+    
+    @admin = SocketPlayer.new "dummy", "admin", "*"
+    @admin.connect
+    @admin.reader
+    @admin.login
+
+    result, result2 = handshake do
+      source_game = parse_game_name(@admin)
+      @admin.puts "%%FORK #{source_game}" # nil for new_buoy_game name
+      sleep 1
+      assert /##\[FORK\]: new buoy game name: buoy_TestFork_1-1500-0/ =~ @admin.message
+    end
+
+    assert buoy.is_new_game?("buoy_TestFork_1-1500-0")
+    @p1 = SocketPlayer.new "buoy_TestFork_1", "p1", true
+    @p2 = SocketPlayer.new "buoy_TestFork_1", "p2", false
+    @p1.connect
+    @p2.connect
+    @p1.reader
+    @p2.reader
+    @p1.login
+    @p2.login
+    sleep 1
+    @p1.game
+    @p2.game
+    sleep 1
+    @p1.agree
+    @p2.agree
+    sleep 1
+    assert /^Total_Time:1500/ =~ @p1.message
+    assert /^Total_Time:1500/ =~ @p2.message
+    @p2.move("-3334FU")
+    sleep 1
+    @p1.toryo
+    sleep 1
+    @p2.logout
+    @p1.logout
+
+    @admin.logout
+  end
+end
index 0902443..90cea15 100644 (file)
@@ -1,11 +1,11 @@
 $:.unshift File.join(File.dirname(__FILE__), "..")
 require 'test/unit'
 require 'shogi_server'
+require 'shogi_server/league.rb'
 require 'shogi_server/player'
 require 'shogi_server/pairing'
 require 'test/mock_log_message'
 
-
 def same_pair?(a, b)
   unless a.size == 2 && b.size == 2
     return false
@@ -327,4 +327,247 @@ class TestStartGameWithoutHumans < Test::Unit::TestCase
   end
 end
 
+class TestLeastDiff < Test::Unit::TestCase
+
+  class MockLeague
+    def initialize
+      @players = []
+    end
+
+    def add(player)
+      @players << player
+    end
+
+    def find(name)
+      @players.find do |p|
+        p.name == name
+      end
+    end
+  end
+
+  def setup
+    $league = MockLeague.new
+
+    @pairing= ShogiServer::LeastDiff.new
+    $paired = []
+    $called = 0
+    def @pairing.start_game(p1,p2)
+      $called += 1
+      $paired << [p1,p2]
+    end
+
+    @file = Pathname.new(File.join(File.dirname(__FILE__), "floodgate_history.yaml"))
+    @history = ShogiServer::League::Floodgate::History.new @file
+
+    @a = ShogiServer::BasicPlayer.new
+    @a.player_id = "a"
+    @a.name = "a"
+    @a.win  = 1
+    @a.loss = 2
+    @a.rate = 500
+    @b = ShogiServer::BasicPlayer.new
+    @b.player_id = "b"
+    @b.name = "b"
+    @b.win  = 10
+    @b.loss = 20
+    @b.rate = 800
+    @c = ShogiServer::BasicPlayer.new
+    @c.player_id = "c"
+    @c.name = "c"
+    @c.win  = 100
+    @c.loss = 200
+    @c.rate = 1000
+    @d = ShogiServer::BasicPlayer.new
+    @d.player_id = "d"
+    @d.name = "d"
+    @d.win  = 1000
+    @d.loss = 2000
+    @d.rate = 1500
+    @e = ShogiServer::BasicPlayer.new
+    @e.player_id = "e"
+    @e.name = "e"
+    @e.win  = 3000
+    @e.loss = 3000
+    @e.rate = 2000
+    @f = ShogiServer::BasicPlayer.new
+    @f.player_id = "f"
+    @f.name = "f"
+    @f.win  = 4000
+    @f.loss = 4000
+    @f.rate = 2150
+    @g = ShogiServer::BasicPlayer.new
+    @g.player_id = "g"
+    @g.name = "g"
+    @g.win  = 5000
+    @g.loss = 5000
+    @g.rate = 2500
+    @h = ShogiServer::BasicPlayer.new
+    @h.player_id = "h"
+    @h.name = "h"
+    @h.win  = 6000
+    @h.loss = 6000
+    @h.rate = 3000
+    @x = ShogiServer::BasicPlayer.new
+    @x.player_id = "x"
+    @x.name = "x"
+
+    $league.add(@a)
+    $league.add(@b)
+    $league.add(@c)
+    $league.add(@d)
+    $league.add(@e)
+    $league.add(@f)
+    $league.add(@g)
+    $league.add(@h)
+    $league.add(@x)
+  end
+
+  def teardown
+    @file.delete if @file.exist?
+  end
+
+  def assert_pairs(x_array, y_array)
+    if (x_array.size != y_array.size)
+      assert_equal(x_array.size, y_array.size)
+      return
+    end
+    i = 0
+
+    if (x_array.size == 1)
+      assert_equal(x_array[0].name, y_array[0].name)
+      return
+    end
+
+    ret = true
+    while i < x_array.size
+      if i == x_array.size-1
+        assert_equal(x_array[i].name, y_array[i].name)
+        break
+      end
+      px1 = x_array[i]
+      px2 = x_array[i+1]
+      py1 = y_array[i]
+      py2 = y_array[i+1]
+
+      if ! ((px1.name == py1.name && px2.name == py2.name) ||
+            (px1.name == py2.name && px2.name == py1.name))
+        ret = false
+      end
+      i += 2
+    end
+
+    assert(ret)
+  end
+
+  def test_match_one_player
+    players = [@a]
+    assert_equal(0, @pairing.calculate_diff_with_penalty(players,nil))
+    r = @pairing.match(players)
+    assert_pairs([@a], r)
+  end
+
+  def test_match_two_players
+    players = [@a,@b]
+    assert_equal(@b.rate-@a.rate, @pairing.calculate_diff_with_penalty([@a,@b],nil))
+    assert_equal(@b.rate-@a.rate, @pairing.calculate_diff_with_penalty([@b,@a],nil))
+    r = @pairing.match(players)
+    assert_pairs([@a,@b], r)
+  end
+
+  def test_match_three_players
+    players = [@h,@a,@b]
+    assert_equal(300,  @pairing.calculate_diff_with_penalty([@a,@b,@h],nil))
+    assert_equal(2200, @pairing.calculate_diff_with_penalty([@b,@h,@a],nil))
+    r = @pairing.match(players)
+    assert_pairs([@a,@b,@h], r)
+    assert_pairs([@a,@b,@h], players)
+  end
+
+  def test_calculate_diff_with_penalty
+    players = [@a,@b]
+    assert_equal(@b.rate-@a.rate, @pairing.calculate_diff_with_penalty(players,nil))
+
+    dummy = nil
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-a-b-1", 
+       :black => "b",  :white => "a",
+       :winner => "a", :loser => "b"}
+    end
+    @history.update(dummy)
+    assert_equal(@b.rate-@a.rate+400, @pairing.calculate_diff_with_penalty(players, @history))
+  end
+
+  def test_calculate_diff_with_penalty2
+    players = [@a,@b,@g,@h]
+    assert_equal(@b.rate-@a.rate+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players,nil))
+  end
+
+  def test_calculate_diff_with_penalty2_1
+    players = [@a,@b,@g,@h]
+    assert_equal(@b.rate-@a.rate+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players,nil))
+    dummy = nil
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-a-b-1", 
+       :black => "b",  :white => "a",
+       :winner => "a", :loser => "b"}
+    end
+    @history.update(dummy)
+    assert_equal(@b.rate-@a.rate+400+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players, @history))
+  end
+
+  def test_calculate_diff_with_penalty2_2
+    players = [@a,@b,@g,@h]
+    assert_equal(@b.rate-@a.rate+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players,nil))
+    dummy = nil
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-a-b-1", 
+       :black => "g",  :white => "h",
+       :winner => "h", :loser => "g"}
+    end
+    @history.update(dummy)
+    assert_equal(@b.rate-@a.rate+400+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players, @history))
+    #assert_equal(@b.rate-@a.rate+400+@h.rate-@g.rate+400, @pairing.calculate_diff_with_penalty(players, [@b,@a,@h,@g]))
+  end
+
+  def test_calculate_diff_with_penalty2_3
+    players = [@a,@b,@g,@h]
+    assert_equal(@b.rate-@a.rate+@h.rate-@g.rate, @pairing.calculate_diff_with_penalty(players,nil))
+    dummy = nil
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-a-b-1", 
+       :black => "g",  :white => "h",
+       :winner => "h", :loser => "g"}
+    end
+    @history.update(dummy)
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-a-b-1", 
+       :black => "b",  :white => "a",
+       :winner => "a", :loser => "b"}
+    end
+    @history.update(dummy)
+    assert_equal(@b.rate-@a.rate+400+@h.rate-@g.rate+400, @pairing.calculate_diff_with_penalty(players, @history))
+  end
+
+  def test_get_player_rate_0
+    assert_equal(2150, @pairing.get_player_rate(@x, @history))
+
+    dummy = nil
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-x-a-1", 
+       :black => "x",  :white => "a",
+       :winner => "x", :loser => "a"}
+    end
+    @history.update(dummy)
+    assert_equal(@a.rate+100, @pairing.get_player_rate(@x, @history))
+
+    def @history.make_record(game_result)
+      {:game_id => "wdoor+floodgate-900-0-x-b-1", 
+       :black => "x",  :white => "b",
+       :winner => "b", :loser => "x"}
+    end
+    @history.update(dummy)
+
+    assert_equal((@a.rate+100+@b.rate-100)/2, @pairing.get_player_rate(@x, @history))
+  end
+end
 
diff --git a/test/TC_time_clock.rb b/test/TC_time_clock.rb
new file mode 100644 (file)
index 0000000..151ba81
--- /dev/null
@@ -0,0 +1,92 @@
+$:.unshift File.join(File.dirname(__FILE__), "..")
+require 'test/unit'
+require 'test/mock_player'
+require 'shogi_server/board'
+require 'shogi_server/game'
+require 'shogi_server/player'
+
+class DummyPlayer
+  def initialize(mytime)
+    @mytime = mytime
+  end
+  attr_reader :mytime
+end
+
+class TestTimeClockFactor < Test::Unit::TestCase
+  def test_chess_clock
+    c = ShogiServer::TimeClock::factory(1, "hoge-900-0")
+    assert_instance_of(ShogiServer::ChessClock, c)
+
+    c = ShogiServer::TimeClock::factory(1, "hoge-1500-60")
+    assert_instance_of(ShogiServer::ChessClock, c)
+  end
+
+  def test_stop_watch_clock
+    c = ShogiServer::TimeClock::factory(1, "hoge-1500-060")
+    assert_instance_of(ShogiServer::StopWatchClock, c)
+  end
+end
+
+class TestChessClock < Test::Unit::TestCase
+  def test_time_duration
+    tc = ShogiServer::ChessClock.new(1, 1500, 60)
+    assert_equal(1, tc.time_duration(100.1, 100.9))
+    assert_equal(1, tc.time_duration(100, 101))
+    assert_equal(1, tc.time_duration(100.1, 101.9))
+    assert_equal(2, tc.time_duration(100.1, 102.9))
+    assert_equal(2, tc.time_duration(100, 102))
+  end
+
+  def test_without_byoyomi
+    tc = ShogiServer::ChessClock.new(1, 1500, 0)
+
+    p = DummyPlayer.new 100
+    assert(!tc.timeout?(p, 100, 101))
+    assert(!tc.timeout?(p, 100, 199))
+    assert(tc.timeout?(p, 100, 200))
+    assert(tc.timeout?(p, 100, 201))
+  end
+
+  def test_with_byoyomi
+    tc = ShogiServer::ChessClock.new(1, 1500, 60)
+
+    p = DummyPlayer.new 100
+    assert(!tc.timeout?(p, 100, 101))
+    assert(!tc.timeout?(p, 100, 259))
+    assert(tc.timeout?(p, 100, 260))
+    assert(tc.timeout?(p, 100, 261))
+
+    p = DummyPlayer.new 30
+    assert(!tc.timeout?(p, 100, 189))
+    assert(tc.timeout?(p, 100, 190))
+  end
+
+  def test_with_byoyomi2
+    tc = ShogiServer::ChessClock.new(1, 0, 60)
+
+    p = DummyPlayer.new 0
+    assert(!tc.timeout?(p, 100, 159))
+    assert(tc.timeout?(p, 100, 160))
+  end
+end
+
+class TestStopWatchClock < Test::Unit::TestCase
+  def test_time_duration
+    tc = ShogiServer::StopWatchClock.new(1, 1500, 60)
+    assert_equal(0, tc.time_duration(100.1, 100.9))
+    assert_equal(0, tc.time_duration(100, 101))
+    assert_equal(0, tc.time_duration(100, 159.9))
+    assert_equal(60, tc.time_duration(100, 160))
+    assert_equal(60, tc.time_duration(100, 219))
+    assert_equal(120, tc.time_duration(100, 220))
+  end
+
+  def test_with_byoyomi
+    tc = ShogiServer::StopWatchClock.new(1, 600, 60)
+
+    p = DummyPlayer.new 60
+    assert(!tc.timeout?(p, 100, 159))
+    assert(tc.timeout?(p, 100, 160))
+  end
+end
+