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 Login_Time = 300 # time for LOGIN
30 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
31 Release.concat("-") if (Release == "")
32 Revision = "$Revision$".gsub(/[^\.\d]/, '')
43 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
129 @write_queue = Queue::new
133 attr_accessor :name, :password, :socket, :status
134 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
135 attr_accessor :main_thread, :writer_thread, :write_queue
138 Thread::kill(@main_thread) if @main_thread
142 if (@status != "finished")
144 log_message(sprintf("user %s finish", @name))
145 Thread::kill(@writer_thread) if @writer_thread
147 @socket.close if (! @socket.closed?)
149 log_message(sprintf("user %s finish failed", @name))
155 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
159 while (str = @write_queue.pop)
160 @socket.write_safe(str)
165 if ((status == "game_waiting") ||
166 (status == "agree_waiting") ||
169 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
170 elsif (@sente == false)
171 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
172 elsif (@sente == nil)
173 return sprintf("%s %s %s %s +-", @name, @protocol, @status, @game_name)
176 return sprintf("%s %s %s", @name, @protocol, @status)
181 @socket.write_safe('##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"')
188 (login, @name, @password, ext) = str.split
194 @main_thread = Thread::current
195 @writer_thread = Thread::start do
201 write_safe(sprintf("LOGIN:%s OK\n", @name))
202 if (@protocol != "CSA")
203 log_message(sprintf("user %s run in %s mode", @name, @protocol))
204 write_safe(sprintf("##[LOGIN] +OK %s\n", @protocol))
206 log_message(sprintf("user %s run in CSA mode", @name))
207 csa_1st_str = "%%GAME #{Default_Game_Name} +-"
210 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
217 if (@write_queue.size > Max_Write_Queue_Size)
218 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
222 if (@status == "finished")
225 str.chomp! if (str.class == String)
227 when /^[\+\-%][^%]/, :timeout
228 if (@status == "game")
229 s = @game.handle_one_move(str, self)
230 return if (s && @protocol == "CSA")
233 if (@status == "agree_waiting")
235 return if (@protocol == "CSA")
237 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
240 if (@status == "agree_waiting")
241 @status = "start_waiting"
242 if ((@game.sente.status == "start_waiting") &&
243 (@game.gote.status == "start_waiting"))
245 @game.sente.status = "game"
246 @game.gote.status = "game"
249 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
251 when /^%%SHOW\s+(\S+)/
253 if (LEAGUE.games[game_id])
254 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
256 write_safe("##[SHOW] +OK\n")
257 when /^%%MONITORON\s+(\S+)/
259 if (LEAGUE.games[game_id])
260 LEAGUE.games[game_id].monitoron(self)
261 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
262 write_safe("##[MONITOR][#{game_id}] +OK\n")
264 when /^%%MONITOROFF\s+(\S+)/
266 if (LEAGUE.games[game_id])
267 LEAGUE.games[game_id].monitoroff(self)
271 when /^%%GAME\s+(\S+)\s+([\+\-]+)$/
274 if (! good_game_name?(game_name))
275 write_safe(sprintf("##[ERROR] bad game name\n"))
276 elsif ((@status == "connected") || (@status == "game_waiting"))
277 @status = "game_waiting"
279 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
281 @status = "game_waiting"
283 if (sente_str == "+")
286 elsif (sente_str == "-")
293 rival = LEAGUE.get_player("game_waiting", @game_name, rival_sente, self)
294 rival = LEAGUE.get_player("game_waiting", @game_name, nil, self) if (! rival)
304 elsif (rival_sente == nil)
311 rival.sente = rival_sente
312 Game::new(@game_name, self, rival)
313 self.status = "agree_waiting"
314 rival.status = "agree_waiting"
316 when /^%%CHAT\s+(.+)/
318 LEAGUE.players.each do |name, player|
319 if (player.protocol != "CSA")
320 s = player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
321 player.status = "zombie" if (! s)
326 LEAGUE.games.each do |id, game|
327 buf.push(sprintf("##[LIST] %s\n", id))
329 buf.push("##[LIST] +OK\n")
333 LEAGUE.players.each do |name, player|
334 buf.push(sprintf("##[WHO] %s\n", player.to_s))
336 buf.push("##[WHO] +OK\n")
339 @status = "connected"
340 write_safe("LOGOUT:completed\n")
343 ## ignore null string
345 write_safe(sprintf("##[ERROR] unknown command %s\n", str))
355 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
356 def initialize(name, sente)
361 attr_accessor :name, :promoted, :sente
386 @sente_hands = Array::new
387 @gote_hands = Array::new
388 @array = [[], [], [], [], [], [], [], [], [], []]
390 attr_accessor :array, :sente_hands, :gote_hands
393 @array[1][1] = Piece::new("KY", false)
394 @array[2][1] = Piece::new("KE", false)
395 @array[3][1] = Piece::new("GI", false)
396 @array[4][1] = Piece::new("KI", false)
397 @array[5][1] = Piece::new("OU", false)
398 @array[6][1] = Piece::new("KI", false)
399 @array[7][1] = Piece::new("GI", false)
400 @array[8][1] = Piece::new("KE", false)
401 @array[9][1] = Piece::new("KY", false)
402 @array[2][2] = Piece::new("KA", false)
403 @array[8][2] = Piece::new("HI", false)
404 @array[1][3] = Piece::new("FU", false)
405 @array[2][3] = Piece::new("FU", false)
406 @array[3][3] = Piece::new("FU", false)
407 @array[4][3] = Piece::new("FU", false)
408 @array[5][3] = Piece::new("FU", false)
409 @array[6][3] = Piece::new("FU", false)
410 @array[7][3] = Piece::new("FU", false)
411 @array[8][3] = Piece::new("FU", false)
412 @array[9][3] = Piece::new("FU", false)
414 @array[1][9] = Piece::new("KY", true)
415 @array[2][9] = Piece::new("KE", true)
416 @array[3][9] = Piece::new("GI", true)
417 @array[4][9] = Piece::new("KI", true)
418 @array[5][9] = Piece::new("OU", true)
419 @array[6][9] = Piece::new("KI", true)
420 @array[7][9] = Piece::new("GI", true)
421 @array[8][9] = Piece::new("KE", true)
422 @array[9][9] = Piece::new("KY", true)
423 @array[2][8] = Piece::new("HI", true)
424 @array[8][8] = Piece::new("KA", true)
425 @array[1][7] = Piece::new("FU", true)
426 @array[2][7] = Piece::new("FU", true)
427 @array[3][7] = Piece::new("FU", true)
428 @array[4][7] = Piece::new("FU", true)
429 @array[5][7] = Piece::new("FU", true)
430 @array[6][7] = Piece::new("FU", true)
431 @array[7][7] = Piece::new("FU", true)
432 @array[8][7] = Piece::new("FU", true)
433 @array[9][7] = Piece::new("FU", true)
436 def get_piece_from_hands(hands, name)
446 def handle_one_move(str)
448 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
456 if ((x1 == 0) || (y1 == 0))
459 elsif (str =~ /^%KACHI/)
461 elsif (str =~ /^%TORYO/)
475 if (@array[x1][y1] == sente) # this is mine
477 elsif (@array[x1][y1].name == "OU")
480 hands.push(@array[x1][y1])
483 if ((x0 == 0) && (y0 == 0))
484 p = get_piece_from_hands(hands, name)
485 return "illegal" if (! p) # i don't have this one
490 if (@array[x0][y0] == nil)
493 if (@array[x0][y0].name != name) # promoted ?
494 return "illegal" if (@array[x0][y0].promoted_name != name) # can't promote
495 @array[x0][y0].promoted = true
497 @array[x1][y1] = @array[x0][y0]
500 return "normal" # legal move
510 a.push(sprintf("P%d", y))
522 a.push(sprintf("\n"))
525 if (! sente_hands.empty?)
527 sente_hands.each do |p|
528 a.push("00" + p.name)
532 if (! gote_hands.empty?)
534 gote_hands.each do |p|
535 a.push("00" + p.name)
545 def initialize(game_name, player0, player1)
546 @monitors = Array::new
547 @game_name = game_name
548 if (@game_name =~ /:(\d+):(\d+)/)
549 @total_time = $1.to_i
560 @current_player = @sente
569 @sente.status = "agree_waiting"
570 @gote.status = "agree_waiting"
571 @id = sprintf("%s+%s+%s+%s+%s",
572 LEAGUE.event, @game_name, @sente.name, @gote.name,
573 Time::new.strftime("%Y%m%d%H%M%S"))
575 LEAGUE.games[@id] = self
578 log_message(sprintf("game created %s %s %s", game_name, sente.name, gote.name))
580 @logfile = @id + ".csa"
588 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
589 attr_accessor :last_move, :current_turn
591 def monitoron(monitor)
592 @monitors.delete(monitor)
593 @monitors.push(monitor)
596 def monitoroff(monitor)
597 @monitors.delete(monitor)
601 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
602 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
607 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
609 elsif (@current_player == killer)
616 log_message(sprintf("game finished %s %s %s", game_name, sente.name, gote.name))
617 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
622 @sente.status = "connected"
623 @gote.status = "connected"
625 if (@current_player.protocol == "CSA")
626 @current_player.finish
628 if (@next_player.protocol == "CSA")
631 @monitors = Array::new
634 @current_player = nil
636 LEAGUE.games.delete(@id)
639 def handle_one_move(str, player)
641 if (@current_player == player)
642 @end_time = Time::new
643 t = (@end_time - @start_time).ceil
644 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
647 if ((@current_player.mytime - t <= 0) && (@total_time > 0))
649 elsif (str == :timeout)
650 return false # time isn't expired. players aren't swapped. continue game
652 move_status = @board.handle_one_move(str)
653 if (move_status == "illegal")
654 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
656 if ((move_status == "normal") || (move_status == "outori"))
657 @sente.write_safe(sprintf("%s,T%d\n", str, t))
658 @gote.write_safe(sprintf("%s,T%d\n", str, t))
659 @fh.printf("%s\nT%d\n", str, t)
660 @last_move = sprintf("%s,T%d", str, t)
661 @current_turn = @current_turn + 1
663 @monitors.each do |monitor|
664 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
665 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
670 if (@current_player.mytime - t < @byoyomi)
671 @current_player.mytime = @byoyomi
673 @current_player.mytime = @current_player.mytime - t
676 if (@next_player.status != "game") # rival is logout or disconnected
678 elsif (status == :timeout)
680 elsif (move_status == "illegal")
682 elsif (move_status == "kachi")
684 elsif (move_status == "toryo")
686 elsif (move_status == "outori")
691 finish() if finish_flag
692 (@current_player, @next_player) = [@next_player, @current_player]
693 @start_time = Time::new
699 @current_player.status = "connected"
700 @next_player.status = "connected"
701 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
702 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
703 @fh.printf("%%TORYO\n")
704 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
705 @monitors.each do |monitor|
706 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
711 @current_player.status = "connected"
712 @next_player.status = "connected"
713 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
714 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
715 @fh.printf("%%TORYO\n")
716 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
717 @monitors.each do |monitor|
718 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
723 @current_player.status = "connected"
724 @next_player.status = "connected"
725 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
726 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
727 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
728 @monitors.each do |monitor|
729 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
734 @current_player.status = "connected"
735 @next_player.status = "connected"
736 @current_player.write_safe("#TIME_UP\n#LOSE\n")
737 @next_player.write_safe("#TIME_UP\n#WIN\n")
738 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
739 @monitors.each do |monitor|
740 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
745 @current_player.status = "connected"
746 @next_player.status = "connected"
747 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
748 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
749 @fh.printf("%%KACHI\n")
750 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
751 @monitors.each do |monitor|
752 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
757 @current_player.status = "connected"
758 @next_player.status = "connected"
759 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
760 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
761 @fh.printf("%%TORYO\n")
762 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
763 @monitors.each do |monitor|
764 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
769 @current_player.status = "connected"
770 @next_player.status = "connected"
771 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
772 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
773 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
774 @monitors.each do |monitor|
775 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
780 log_message(sprintf("game started %s %s %s", game_name, sente.name, gote.name))
781 @sente.write_safe(sprintf("START:%s\n", @id))
782 @gote.write_safe(sprintf("START:%s\n", @id))
783 @sente.mytime = @total_time
784 @gote.mytime = @total_time
785 @start_time = Time::new
790 @fh = open(@logfile, "w")
794 @fh.printf("N+%s\n", @sente.name)
795 @fh.printf("N-%s\n", @gote.name)
796 @fh.printf("$EVENT:%s\n", @id)
798 @sente.write_safe(propose_message("+"))
799 @gote.write_safe(propose_message("-"))
801 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
803 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
804 P2 * -HI * * * * * -KA *
805 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
809 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
810 P8 * +KA * * * * * +HI *
811 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
830 Total_Time:#{@total_time}
832 Remaining_Time+:#{@sente.mytime}
833 Remaining_Time-:#{@gote.mytime}
834 Last_Move:#{@last_move}
835 Current_Turn:#{@current_turn}
836 Least_Time_Per_Move:#{Least_Time_Per_Move}
839 Jishogi_Declaration:1.1
847 return str0 + @board.to_s + str1
850 def propose_message(sg_flag)
864 Total_Time:#{@total_time}
866 Least_Time_Per_Move:#{Least_Time_Per_Move}
869 Jishogi_Declaration:1.1
870 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
871 P2 * -HI * * * * * -KA *
872 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
876 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
877 P8 * +KA * * * * * +HI *
878 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
892 shogi-server - server for CSA server protocol
895 shogi-server event_name port_number
898 server for CSA server protocol
902 specify filename for logging process ID
905 this file is distributed under GPL version2 and might be compiled by Exerb
918 printf("%s message: %s\n", Time::new.to_s, str)
922 printf("%s warning: %s\n", Time::new.to_s, str)
926 printf("%s error: %s\n", Time::new.to_s, str)
930 def parse_command_line
932 parser = GetoptLong.new
933 parser.ordering = GetoptLong::REQUIRE_ORDER
935 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
939 parser.each_option do |name, arg|
941 options[name] = arg.dup
945 raise parser.error_message
950 def good_game_name?(str)
951 if ((str =~ /^(.+):\d+:\d+$/) &&
952 (good_identifier?($1)))
959 def good_identifier?(str)
960 if ((str =~ /\A[\w\d_@\-\.]+\z/) &&
961 (str.length < Max_Identifier_Length))
970 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
971 (tokens[0] == "LOGIN") &&
972 (good_identifier?(tokens[1])))
979 def write_pid_file(file)
980 open(file, "w") do |fh|
981 fh.print Process::pid, "\n"
985 def mutex_watchdog(mutex, sec)
994 log_error("mutex watchdog timeout")
1003 mutex_watchdog($mutex, 10)
1006 $options = parse_command_line
1007 if (ARGV.length != 2)
1012 LEAGUE.event = ARGV.shift
1015 write_pid_file($options["pid-file"]) if ($options["pid-file"])
1018 Thread.abort_on_exception = true
1020 server = TCPserver.open(port)
1021 log_message("server started")
1024 Thread::start(server.accept) do |client|
1027 while (str = client.gets_timeout(Login_Time))
1032 if (good_login?(str))
1033 player = Player::new(str, client)
1034 if (LEAGUE.players[player.name])
1035 if ((LEAGUE.players[player.name].password == player.password) &&
1036 (LEAGUE.players[player.name].status != "game"))
1037 log_message(sprintf("user %s login forcely", player.name))
1038 LEAGUE.players[player.name].kill
1040 client.write_safe("LOGIN:incorrect" + eol)
1041 client.write_safe(sprintf("username %s is already connected%s", player.name, eol)) if (str.split.length >= 4)
1049 client.write_safe("LOGIN:incorrect" + eol)
1050 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
1060 log_message(sprintf("user %s login", player.name))
1065 player.game.kill(player)
1068 LEAGUE.delete(player)
1069 log_message(sprintf("user %s logout", player.name))
1078 LEAGUE = League::new