2 ## -*-Ruby-*- $RCSfile$ $Revision$ $Name$
4 ## Copyright (C) 2004 nanami@2ch
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 Max_Write_Queue_Size = 1000
21 Max_Identifier_Length = 32
22 Default_Timeout = 60 # for single socket operation
24 Default_Game_Name = "default:1500:0"
27 Least_Time_Per_Move = 1
28 Watchdog_Time = 30 # time for ping
29 Login_Time = 300 # time for LOGIN
31 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
32 Release.concat("-") if (Release == "")
33 Revision = "$Revision$".gsub(/[^\.\d]/, '')
44 TCPSocket.do_not_reverse_lookup = true
47 def gets_timeout(t = Default_Timeout)
58 def gets_safe(t = nil)
79 return self.write(str)
93 attr_accessor :players, :games, :event
96 @players[player.name] = player
99 @players.delete(player.name)
101 def get_player(status, game_name, sente, searcher=nil)
102 @players.each do |name, player|
103 if ((player.status == status) &&
104 (player.game_name == game_name) &&
105 ((player.sente == nil) || (player.sente == sente)) &&
106 ((searcher == nil) || (player != searcher)))
115 def initialize(str, socket)
119 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
121 @protocol = nil # CSA or x1
122 @eol = "\m" # favorite eol code
125 @mytime = 0 # set in start method also
127 @watchdog_thread = nil
130 @write_queue = Queue::new
134 attr_accessor :name, :password, :socket, :status
135 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
136 attr_accessor :main_thread, :watchdog_thread, :writer_thread, :write_queue
139 Thread::kill(@main_thread) if @main_thread
143 if (@status != "finished")
145 log_message(sprintf("user %s finish", @name))
146 Thread::kill(@watchdog_thread) if @watchdog_thread
147 Thread::kill(@writer_thread) if @writer_thread
148 @socket.close if (! @socket.closed?)
153 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
157 while (str = @write_queue.pop)
158 @socket.write_safe(str)
165 Ping.pingecho(@socket.addr[3])
173 if ((status == "game_waiting") ||
174 (status == "agree_waiting") ||
177 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
178 elsif (@sente == false)
179 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
180 elsif (@sente == nil)
181 return sprintf("%s %s %s %s +-", @name, @protocol, @status, @game_name)
184 return sprintf("%s %s %s", @name, @protocol, @status)
189 @socket.write_safe('##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"')
196 (login, @name, @password, ext) = str.split
202 @main_thread = Thread::current
203 @watchdog_thread = Thread::start do
204 watchdog(Watchdog_Time)
206 @writer_thread = Thread::start do
212 write_safe(sprintf("LOGIN:%s OK\n", @name))
213 if (@protocol != "CSA")
214 log_message(sprintf("user %s run in %s mode", @name, @protocol))
215 write_safe(sprintf("##[LOGIN] +OK %s\n", @protocol))
217 log_message(sprintf("user %s run in CSA mode", @name))
218 csa_1st_str = "%%GAME #{Default_Game_Name} +-"
221 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
228 if (@write_queue.size > Max_Write_Queue_Size)
229 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
232 if (@status == "finished")
235 str.chomp! if (str.class == String)
237 when /^[\+\-%][^%]/, :timeout
238 if (@status == "game")
239 s = @game.handle_one_move(str, self)
240 return if (s && @protocol == "CSA")
243 if (@status == "agree_waiting")
245 return if (@protocol == "CSA")
247 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
250 if (@status == "agree_waiting")
251 @status = "start_waiting"
252 if ((@game.sente.status == "start_waiting") &&
253 (@game.gote.status == "start_waiting"))
255 @game.sente.status = "game"
256 @game.gote.status = "game"
259 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
261 when /^%%MONITORON\s+(\S+)/
263 if (LEAGUE.games[game_name])
264 LEAGUE.games[game_name].monitoron(self)
266 when /^%%MONITOROFF\s+(\S+)/
268 if (LEAGUE.games[game_name])
269 LEAGUE.games[game_name].monitoroff(self)
273 when /^%%GAME\s+(\S+)\s+([\+\-]+)$/
276 if (! good_game_name?(game_name))
277 write_safe(sprintf("##[ERROR] bad game name\n"))
278 elsif ((@status == "connected") || (@status == "game_waiting"))
279 @status = "game_waiting"
281 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
283 @status = "game_waiting"
285 if (sente_str == "+")
288 elsif (sente_str == "-")
295 rival = LEAGUE.get_player("game_waiting", @game_name, rival_sente, self)
296 rival = LEAGUE.get_player("game_waiting", @game_name, nil, self) if (! rival)
306 elsif (rival_sente == nil)
313 rival.sente = rival_sente
314 Game::new(@game_name, self, rival)
315 self.status = "agree_waiting"
316 rival.status = "agree_waiting"
318 when /^%%CHAT\s+(.+)/
320 LEAGUE.players.each do |name, player|
321 if (player.protocol != "CSA")
322 s = player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
323 player.status = "zombie" if (! s)
328 LEAGUE.games.each do |id, game|
329 buf.push(sprintf("##[LIST] %s\n", id))
331 buf.push("##[LIST] +OK\n")
333 when /^%%SHOW\s+(\S+)/
335 if (LEAGUE.games[id])
336 write_safe(LEAGUE.games[id].board.to_s.gsub(/^/, '##[SHOW] '))
338 write_safe("##[SHOW] +OK\n")
341 LEAGUE.players.each do |name, player|
342 buf.push(sprintf("##[WHO] %s\n", player.to_s))
344 buf.push("##[WHO] +OK\n")
347 @status = "connected"
348 write_safe("LOGOUT:completed\n")
351 write_safe(sprintf("##[ERROR] unknown command %s\n", str))
361 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
362 def initialize(name, sente)
367 attr_accessor :name, :promoted, :sente
392 @sente_hands = Array::new
393 @gote_hands = Array::new
394 @array = [[], [], [], [], [], [], [], [], [], []]
396 attr_accessor :array, :sente_hands, :gote_hands
399 @array[1][1] = Piece::new("KY", false)
400 @array[2][1] = Piece::new("KE", false)
401 @array[3][1] = Piece::new("GI", false)
402 @array[4][1] = Piece::new("KI", false)
403 @array[5][1] = Piece::new("OU", false)
404 @array[6][1] = Piece::new("KI", false)
405 @array[7][1] = Piece::new("GI", false)
406 @array[8][1] = Piece::new("KE", false)
407 @array[9][1] = Piece::new("KY", false)
408 @array[2][2] = Piece::new("KA", false)
409 @array[8][2] = Piece::new("HI", false)
410 @array[1][3] = Piece::new("FU", false)
411 @array[2][3] = Piece::new("FU", false)
412 @array[3][3] = Piece::new("FU", false)
413 @array[4][3] = Piece::new("FU", false)
414 @array[5][3] = Piece::new("FU", false)
415 @array[6][3] = Piece::new("FU", false)
416 @array[7][3] = Piece::new("FU", false)
417 @array[8][3] = Piece::new("FU", false)
418 @array[9][3] = Piece::new("FU", false)
420 @array[1][9] = Piece::new("KY", true)
421 @array[2][9] = Piece::new("KE", true)
422 @array[3][9] = Piece::new("GI", true)
423 @array[4][9] = Piece::new("KI", true)
424 @array[5][9] = Piece::new("OU", true)
425 @array[6][9] = Piece::new("KI", true)
426 @array[7][9] = Piece::new("GI", true)
427 @array[8][9] = Piece::new("KE", true)
428 @array[9][9] = Piece::new("KY", true)
429 @array[2][8] = Piece::new("HI", true)
430 @array[8][8] = Piece::new("KA", true)
431 @array[1][7] = Piece::new("FU", true)
432 @array[2][7] = Piece::new("FU", true)
433 @array[3][7] = Piece::new("FU", true)
434 @array[4][7] = Piece::new("FU", true)
435 @array[5][7] = Piece::new("FU", true)
436 @array[6][7] = Piece::new("FU", true)
437 @array[7][7] = Piece::new("FU", true)
438 @array[8][7] = Piece::new("FU", true)
439 @array[9][7] = Piece::new("FU", true)
442 def get_piece_from_hands(hands, name)
452 def handle_one_move(str)
453 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
460 elsif (str =~ /^%KACHI/)
462 elsif (str =~ /^%TORYO/)
474 if (@array[x1][y1] == sente) # this is mine
476 elsif (@array[x1][y1].name == "OU")
479 hands.push(@array[x1][y1])
482 if ((x0 == 0) && (y0 == 0))
483 p = get_piece_from_hands(hands, name)
484 return "illegal" if (! p) # i don't have this one
489 @array[x1][y1] = @array[x0][y0]
491 if (@array[x1][y1].name != name) # promoted ?
492 return "illegal" if (@array[x1][y1].promoted_name != name) # can't promote
493 @array[x1][y1].promoted = true
496 return "normal" # legal move
503 a.push(sprintf("P%d", y))
515 a.push(sprintf("\n"))
518 if (! sente_hands.empty?)
520 sente_hands.each do |p|
521 a.push("00" + p.name)
525 if (! gote_hands.empty?)
527 gote_hands.each do |p|
528 a.push("00" + p.name)
537 def initialize(game_name, player0, player1)
538 @monitors = Array::new
539 @game_name = game_name
540 if (@game_name =~ /:(\d+):(\d+)/)
541 @total_time = $1.to_i
552 @current_player = @sente
558 @sente.status = "agree_waiting"
559 @gote.status = "agree_waiting"
560 @id = sprintf("%s+%s+%s+%s+%s",
561 LEAGUE.event, @game_name, @sente.name, @gote.name,
562 Time::new.strftime("%Y%m%d%H%M%S"))
564 LEAGUE.games[@id] = self
567 log_message(sprintf("game created %s %s %s", game_name, sente.name, gote.name))
569 @logfile = @id + ".csa"
577 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
579 def monitoron(monitor)
580 @monitors.delete(monitor)
581 @monitors.push(monitor)
582 monitor.write_safe(@board.to_s.gsub(/^/, "##[MONITOR][#{@id}] "))
583 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
586 def monitoroff(monitor)
587 @monitors.delete(monitor)
591 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
592 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
597 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
599 elsif (@current_player == killer)
605 log_message(sprintf("game finished %s %s %s", game_name, sente.name, gote.name))
606 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
611 @sente.status = "connected"
612 @gote.status = "connected"
614 if (@current_player.protocol == "CSA")
615 @current_player.finish
617 if (@next_player.protocol == "CSA")
620 @monitors = Array::new
623 @current_player = nil
625 LEAGUE.games.delete(@id)
628 def handle_one_move(str, player)
630 if (@current_player == player)
631 @end_time = Time::new
632 t = @end_time - @start_time
633 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
636 if ((@current_player.mytime - t <= 0) && (@total_time > 0))
638 elsif (str == :timeout)
639 return false # time isn't expired. players aren't swapped. continue game
641 move_status = @board.handle_one_move(str)
642 if (move_status == "normal")
643 @sente.write_safe(sprintf("%s,T%d\n", str, t))
644 @gote.write_safe(sprintf("%s,T%d\n", str, t))
645 @fh.printf("%s\nT%d\n", str, t)
647 @monitors.each do |monitor|
648 monitor.write_safe(sprintf("##[MONITOR][%s] %s\n", @id, str))
649 monitor.write_safe(@board.to_s.gsub(/^/, "##[MONITOR][#{@id}] "))
650 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
652 elsif (move_status == "illegal")
653 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
657 if (@current_player.mytime - t < @byoyomi)
658 @current_player.mytime = @byoyomi
660 @current_player.mytime = @current_player.mytime - t
663 if (@next_player.status != "game") # rival is logout or disconnected
665 elsif (status == :timeout)
667 elsif (move_status == "illegal")
669 elsif (move_status == "kachi")
671 elsif (move_status == "toryo")
673 elsif (move_status == "outori")
678 finish() if finish_flag
679 (@current_player, @next_player) = [@next_player, @current_player]
680 @start_time = Time::new
686 @current_player.status = "connected"
687 @next_player.status = "connected"
688 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
689 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
690 @monitors.each do |monitor|
691 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
696 @current_player.status = "connected"
697 @next_player.status = "connected"
698 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
699 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
700 @monitors.each do |monitor|
701 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
706 @current_player.status = "connected"
707 @next_player.status = "connected"
708 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
709 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
710 @monitors.each do |monitor|
711 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
716 @current_player.status = "connected"
717 @next_player.status = "connected"
718 @current_player.write_safe("#TIME_UP\n#LOSE\n")
719 @next_player.write_safe("#TIME_UP\n#WIN\n")
720 @monitors.each do |monitor|
721 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
726 @current_player.status = "connected"
727 @next_player.status = "connected"
728 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
729 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
730 @monitors.each do |monitor|
731 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
736 @current_player.status = "connected"
737 @next_player.status = "connected"
738 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
739 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
740 @monitors.each do |monitor|
741 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
746 @current_player.status = "connected"
747 @next_player.status = "connected"
748 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
749 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
750 @monitors.each do |monitor|
751 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
756 log_message(sprintf("game started %s %s %s", game_name, sente.name, gote.name))
757 @sente.write_safe(sprintf("START:%s\n", @id))
758 @gote.write_safe(sprintf("START:%s\n", @id))
759 @sente.mytime = @total_time
760 @gote.mytime = @total_time
761 @start_time = Time::new
766 @fh = open(@logfile, "w")
770 @fh.printf("N+%s\n", @sente.name)
771 @fh.printf("N-%s\n", @gote.name)
772 @fh.printf("$EVENT:%s\n", @id)
774 @sente.write_safe(propose_message("+"))
775 @gote.write_safe(propose_message("-"))
777 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
779 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
780 P2 * -HI * * * * * -KA *
781 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
785 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
786 P8 * +KA * * * * * +HI *
787 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
793 def propose_message(sg_flag)
807 Total_Time:#{@total_time}
809 Least_Time_Per_Move:#{Least_Time_Per_Move}
812 Jishogi_Declaration:1.1
813 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
814 P2 * -HI * * * * * -KA *
815 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
819 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
820 P8 * +KA * * * * * +HI *
821 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
835 shogi-server - server for CSA server protocol
838 shogi-server event_name port_number
841 server for CSA server protocol
845 specify filename for logging process ID
848 this file is distributed under GPL version2 and might be compiled by Exerb
861 printf("%s message: %s\n", Time::new.to_s, str)
865 printf("%s warning: %s\n", Time::new.to_s, str)
869 printf("%s error: %s\n", Time::new.to_s, str)
873 def parse_command_line
875 parser = GetoptLong.new
876 parser.ordering = GetoptLong::REQUIRE_ORDER
878 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
882 parser.each_option do |name, arg|
884 options[name] = arg.dup
888 raise parser.error_message
895 def good_game_name?(str)
896 if ((str =~ /^(.+):\d+:\d+$/) &&
897 (good_identifier?($1)))
904 def good_identifier?(str)
905 if ((str =~ /\A[\w\d_@\-\.]+\z/) &&
906 (str.length < Max_Identifier_Length))
915 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
916 (tokens[0] == "LOGIN") &&
917 (good_identifier?(tokens[1])))
924 def write_pid_file(file)
925 open(file, "w") do |fh|
926 fh.print Process::pid, "\n"
930 def mutex_watchdog(mutex, sec)
938 log_error("mutex watchdog timeout")
947 mutex_watchdog($mutex, 10)
950 $options = parse_command_line
951 if (ARGV.length != 2)
956 LEAGUE.event = ARGV.shift
959 write_pid_file($options["pid-file"]) if ($options["pid-file"])
962 Thread.abort_on_exception = true
964 server = TCPserver.open(port)
965 log_message("server started")
968 Thread::start(server.accept) do |client|
971 while (str = client.gets_timeout(Login_Time))
976 if (good_login?(str))
977 player = Player::new(str, client)
978 if (LEAGUE.players[player.name])
979 if ((LEAGUE.players[player.name].password == player.password) &&
980 (LEAGUE.players[player.name].status != "game"))
981 log_message(sprintf("user %s login forcely", player.name))
982 LEAGUE.players[player.name].kill
984 client.write_safe("LOGIN:incorrect" + eol)
985 client.write_safe(sprintf("username %s is already connected%s", player.name, eol)) if (str.split.length >= 4)
993 client.write_safe("LOGIN:incorrect" + eol)
994 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
1004 log_message(sprintf("user %s login", player.name))
1009 player.game.kill(player)
1012 LEAGUE.delete(player)
1013 log_message(sprintf("user %s logout", player.name))