3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2012 Daigo Moriwaki (daigo at debian dot org)
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 require 'shogi_server/util'
28 return least_diff_pairing
31 def sort_by_rate_with_randomness
32 return [LogPlayers.new,
33 ExcludeSacrificeGps500.new,
35 SortByRateWithRandomness.new(1200, 2400),
36 StartGameWithoutHumans.new]
40 return [LogPlayers.new,
41 ExcludeSacrificeGps500.new,
44 StartGameWithoutHumans.new]
48 return [LogPlayers.new,
49 ExcludeSacrificeGps500.new,
52 StartGameWithoutHumans.new]
55 def least_diff_pairing
56 return [LogPlayers.new,
57 ExcludeSacrificeGps500.new,
60 StartGameWithoutHumans.new]
64 logics = default_factory
65 logics.inject(players) do |result, item|
73 # Make matches among players.
74 # @param players an array of players, which should be updated destructively
75 # to pass the new list to subsequent logics.
79 log_message("Floodgate: %s" % [self.class.to_s])
82 def include_newbie?(players)
83 return players.find{|a| a.rate == 0} == nil ? false : true
86 def less_than_one?(players)
88 log_warning("Floodgate: There should be at least one player.")
95 def log_players(players)
96 str_array = players.map do |one|
104 log_message("Floodgate: [Players] Nobody found.")
106 log_message("Floodgate: [Players] %s." % [str_array.join(", ")])
112 class LogPlayers < Pairing
119 class AbstractStartGame < Pairing
120 def start_game(p1, p2)
121 log_message("Floodgate: Starting a game: BLACK %s vs WHITE %s" % [p1.name, p2.name])
126 Game.new(p1.game_name, p1, p2, board)
129 def start_game_shuffle(pair)
131 start_game(pair.first, pair.last)
135 class StartGame < AbstractStartGame
139 log_warning("Floodgate: There should be more than one player (%d)." % [players.size])
143 log_warning("Floodgate: There are odd players (%d). %s will not be matched." %
144 [players.size, players.last.name])
148 while (players.size >= 2) do
149 pair = players.shift(2)
150 start_game_shuffle(pair)
155 # This tries to avoid a human-human match
157 class StartGameWithoutHumans < AbstractStartGame
162 log_warning("Floodgate: There should be more than one player (%d)." % [players.size])
164 elsif players.size == 2
165 start_game_shuffle(players)
170 humans = get_human_indexes(players)
171 log_message("Floodgate: There are (still) %d humans." % [humans.size])
172 break if humans.size < 2
174 pairing_possible = false
175 for i in 0..(humans.size-2) # -2
176 next if humans[i].odd?
177 if humans[i]+1 == humans[i+1]
178 pairing_possible = humans[i]
182 unless pairing_possible
183 log_message("Floodgate: No possible human-human match found")
187 current_index = pairing_possible
188 j = [0, current_index - 2].max
189 while j < players.size
190 break if players[j].is_computer?
196 # no computer player found
197 pairing_indexes << current_index << current_index+1
199 # a comupter player found
200 pairing_indexes << current_index << j
204 pair << players.delete_at(pairing_indexes.max)
205 pair << players.delete_at(pairing_indexes.min)
206 start_game_shuffle(pair)
209 while (players.size >= 2) do
210 pair = players.shift(2)
211 start_game_shuffle(pair)
217 def get_human_indexes(players)
219 for i in 0..(players.size-1)
220 ret << i if players[i].is_human?
226 class Randomize < Pairing
229 log_message("Floodgate: Randomize... before")
232 log_message("Floodgate: Randomized after")
237 class SortByRate < Pairing
240 log_message("Floodgate: Ordered by rate")
241 players.sort! {|a,b| a.rate <=> b.rate} # decendent order
246 class SortByRateWithRandomness < Pairing
247 def initialize(rand1, rand2, desc=false)
249 @rand1, @rand2 = rand1, rand2
256 players.each{|a| cur_rate[a] = a.rate ? a.rate + rand(@rand1) : rand(@rand2)}
257 players.sort!{|a,b| cur_rate[a] <=> cur_rate[b]}
258 players.reverse! if @desc
259 log_players(players) do |one|
260 "%s %d (+ randomness %d)" % [one.name, one.rate, cur_rate[one] - one.rate]
265 class Swiss < Pairing
269 log_message("Floodgate: players are small enough to skip Swiss pairing: %d" % [players.size])
273 path = ShogiServer::League::Floodgate.history_file_path(players.first.game_name)
274 history = ShogiServer::League::Floodgate::History.factory(path)
278 winners = players.find_all {|pl| history.last_win?(pl.player_id)}
280 rest = players - winners
282 log_message("Floodgate: Ordering %d winners..." % [winners.size])
283 sbrwr_winners = SortByRateWithRandomness.new(800, 2500, true)
284 sbrwr_winners.match(winners)
286 log_message("Floodgate: Ordering the rest (%d)..." % [rest.size])
287 sbrwr_losers = SortByRateWithRandomness.new(200, 400, true)
288 sbrwr_losers.match(rest)
291 [winners, rest].each do |group|
292 group.each {|pl| players << pl}
297 class DeletePlayerAtRandom < Pairing
300 return if less_than_one?(players)
302 log_message("Floodgate: Deleted %s at random" % [one.name])
308 class DeletePlayerAtRandomExcept < Pairing
309 def initialize(except)
316 log_message("Floodgate: Deleting a player at rondom except %s" % [@except.name])
317 players.delete(@except)
318 DeletePlayerAtRandom.new.match(players)
319 players.push(@except)
323 class DeleteMostPlayingPlayer < Pairing
326 one = players.max_by {|a| a.win + a.loss}
327 log_message("Floodgate: Deleted the most playing player: %s (%d)" % [one.name, one.win + one.loss])
333 class DeleteLeastRatePlayer < Pairing
336 one = players.min_by {|a| a.rate}
337 log_message("Floodgate: Deleted the least rate player %s (%d)" % [one.name, one.rate])
343 class ExcludeSacrifice < Pairing
344 attr_reader :sacrifice
346 # @sacrifice a player id to be eliminated
347 def initialize(sacrifice)
349 @sacrifice = sacrifice
356 players.find{|a| a.player_id == @sacrifice}
357 log_message("Floodgate: Deleting the sacrifice %s" % [@sacrifice])
358 players.delete_if{|a| a.player_id == @sacrifice}
362 end # class ExcludeSacrifice
364 class ExcludeSacrificeGps500 < ExcludeSacrifice
366 super("gps500+e293220e3f8a3e59f79f6b0efffaa931")
370 class MakeEven < Pairing
373 return if players.size.even?
374 log_message("Floodgate: There are odd players (%d). Deleting one of them..." %
376 DeletePlayerAtRandom.new.match(players)
380 # This pairing algorithm aims to minimize the total differences of
381 # matching players' rates. It also includes penalyties when a match is
382 # same as the previous one or a match is between human players.
383 # It is based on a discussion with Yamashita-san on
384 # http://www.sgtpepper.net/kaneko/diary/20120511.html.
386 class LeastDiff < Pairing
387 def random_match(players)
391 # Returns a player's rate value.
392 # 1. If it has a valid rate, return the rate.
393 # 2. If it has no valid rate, return average of the following values:
394 # a. For games it won, the opponent's rate + 100
395 # b. For games it lost, the opponent's rate - 100
396 # (if the opponent has no valid rate, count out the game)
397 # (if there are not such games, return 2150 (default value)
399 def get_player_rate(player, history)
400 return player.rate if player.rate != 0
401 return 2150 unless history
406 history.win_games(player.player_id).each do |g|
407 next unless g[:loser]
408 name = g[:loser].split("+")[0]
409 p = $league.find(name)
415 history.loss_games(player.player_id).each do |g|
416 next unless g[:winner]
417 name = g[:winner].split("+")[0]
418 p = $league.find(name)
425 estimate = (count == 0 ? 2150 : sum/count)
426 log_message("Floodgate: Estimated rate of %s is %d" % [player.name, estimate])
430 def calculate_diff_with_penalty(players, history)
432 players.each_slice(2) do |pair|
440 # 1. Diff of players rate
441 pairs.each do |p1,p2|
442 ret += (get_player_rate(p1,history) - get_player_rate(p2,history)).abs
446 pairs.each do |p1,p2|
449 (history.last_opponent(p1.player_id) == p2.player_id ||
450 history.last_opponent(p2.player_id) == p1.player_id))
455 if p1.is_human? && p2.is_human?
466 log_message("Floodgate: players are small enough to skip LeastDiff pairing: %d" % [players.size])
473 path = ShogiServer::League::Floodgate.history_file_path(players.first.game_name)
474 history = ShogiServer::League::Floodgate::History.factory(path)
476 m = random_match(players)
478 scores << calculate_diff_with_penalty(m, history)
482 #scores.each_with_index do |s,i|
484 # print s, ": ", matches[i].map{|p| p.name}.join(", "), "\n"
487 # Select a match of the least score
489 min_score = scores.first
490 scores.each_with_index do |s,i|
496 log_message("Floodgate: the least score %d (%d per player) [%s]" % [min_score, min_score/players.size, scores.join(" ")])
498 players.replace(matches[min_index])