def main(args): try: options = parseargs(args) except ValueError: print "Command not understood %s" % (" ".join(args)) sys.exit(2) config = SafeConfigParser() try: config.readfp(open('gameroom.cfg', 'rU')) except IOError: print "Could not open 'gameroom.cfg' this file must be readable and contain the configuration for connecting to the gameroom." sys.exit(1) aeilog = logging.getLogger("gameroom.aei") if config.has_section("Logging"): logdir = config.get("Logging", "directory") if not os.path.exists(logdir): print "Log directory '%s' not found, attempting to create it." % (logdir) os.makedirs(logdir) logfilename = "%s-%s.log" % (time.strftime("%Y%m%d-%H%M"), str(os.getpid()), ) logfilename = os.path.join(logdir, logfilename) if config.has_option("Logging", "level"): loglevel = str_loglevel(config.get("Logging", "level")) else: loglevel = logging.WARN logging.basicConfig(level = loglevel, filename = logfilename, datefmt="%Y-%m-%d %H:%M:%S", format="%(asctime)s %(levelname)s:%(name)s:%(message)s", ) if (config.has_option("Logging", "console") and config.getboolean("Logging", "console")): global console console = logging.StreamHandler() if config.has_option("Logging", "console_level"): conlevel = str_loglevel(config.get("Logging", "console_level")) else: conlevel = logging.INFO console.setLevel(conlevel) logging.getLogger('').addHandler(console) if config.has_option("Logging", "net_level"): netlevel = str_loglevel(config.get("Logging", "net_level")) netlog.setLevel(netlevel) if config.has_option("Logging", "engine_level"): enginelevel = str_loglevel(config.get("Logging", "engine_level")) enginelog.setLevel(enginelevel) if config.has_option("Logging", "aei_level"): aeilog.setLevel(str_loglevel(config.get("Logging", "aei_level"))) positionlog.setLevel(logging.ERROR) if (config.has_option("Logging", "log_position") and config.getboolean("Logging", "log_position")): positionlog.setLevel(logging.INFO) run_dir = config.get("global", "run_dir") if not os.path.exists(run_dir): log.warn("Run file directory '%s' not found, attempting to create it." % (run_dir)) os.makedirs(run_dir) bot_count = how_many_bots(run_dir) if bot_count >= config.getint("global", "max_bots"): log.info("Max number of bot limit %d reached, need to wait until some bots finish." % (config.getint("global", "max_bots"))) return bot_section = config.get("global", "default_engine") com_method = config.get(bot_section, "communication_method").lower() enginecmd = config.get(bot_section, "cmdline") games_num = config.getint(bot_section, "games_num") games_played = 0 while games_num == 0 or games_played < games_num: unknowns_caught = 0 gameid_or_opponent = options['against'] #while True: try: if com_method == "2008cc": engine_ctl = EngineController(SocketEngine(enginecmd, legacy_mode=True)) elif com_method == "socket": engine_ctl = EngineController(SocketEngine(enginecmd, log=aeilog)) elif com_method == "stdio": engine_ctl = EngineController(StdioEngine(enginecmd, log=aeilog)) else: raise ValueError("Unrecognized communication method, %s" % (com_method)) except OSError, exc: log.error("Could not start the engine; exception thrown: %s", exc) sys.exit(1) for option in config.options(bot_section): if option.startswith("bot_"): value = config.get(bot_section, option) engine_ctl.setoption(option[4:], value) log.info("Setting bot option %s = %s", option[4:], value) engine_ctl.isready() bot_username = config.get(bot_section, "username") bot_password = config.get(bot_section, "password") bot_greeting = config.get(bot_section, "greeting") gameroom = GameRoom(config.get("global", "gameroom_url")) gameroom.login(bot_username, bot_password) side = options['side'] table = None if gameid_or_opponent == "": log.info("Starting a new game") if side == "": side = 'b' tc = config.get(bot_section, "timecontrol") rated = config.getboolean(bot_section, "rated") log.info("Will play on side %s, using timecontrol %s" % (side, tc)) table = gameroom.newgame(side, tc, rated) else: # look through my games for correct opponent and side games = gameroom.mygames() for game in games: if (gameid_or_opponent == game['player'].lower() or gameid_or_opponent == game['gid']): if (side == "" or side == game['side'] and not already_playing(run_dir, game['gid'], game['side'])): table = Table(gameroom, game) log.info("Found in progress game") break if table == None: games = gameroom.opengames() for game in games: if (gameid_or_opponent == game['player'].lower() or gameid_or_opponent == game['gid']): if (side == "" or side == game['side'] and not already_playing(run_dir, game['gid'], game['side'])): table = Table(gameroom, game) log.info("Found game to join") break if table == None: log.error("Could not find game against %s with side '%s'", gameid_or_opponent, side) break # Set the game to play in to current game id in case of a restart gameid_or_opponent = table.gid if options['against'] != "": joinmsg = "Joined game gid=%s side=%s; against %s" % (table.gid, table.side, options['against']) else: joinmsg = "Created game gid=%s side=%s; waiting for opponent" % (table.gid, table.side) log.info(joinmsg) if console is None: print joinmsg if config.has_option(bot_section, "ponder"): table.ponder = config.getboolean(bot_section, "ponder") if table.ponder: log.info("Set pondering on.") else: log.info("Set pondering off.") else: table.ponder = False if config.has_option("global", "min_move_time"): table.min_move_time = config.getint("global", "min_move_time") log.info("Set minimum move time to %d seconds.", table.min_move_time) else: table.min_move_time = 5 if config.has_option("global", "min_time_left"): table.min_timeleft = config.getint("global", "min_time_left") log.info("Setting emergency stop time to %d seconds" % table.min_timeleft) else: table.min_timeleft = 5 try: try: log.info("Joining game on %s side", table.side) table.reserveseat() table.sitdown() table.updatestate() try: touch_run_file(run_dir, "%s%s.bot" % (table.gid, table.side)) time.sleep(1) # Give the server a small break. log.info("Starting play") table.playgame(engine_ctl, bot_greeting, options['onemove']) finally: log.info("Leaving game") remove_run_files(run_dir, "%s%s.bot" % (table.gid, table.side)) table.leave() #break games_played += 1 continue #Tomas changed from break finally: try: engine_ctl.quit() except (socket.error, IOError): pass for i in range(30): if engine_ctl.engine.proc.poll() is not None: break time.sleep(1) else: log.warn("Engine did not exit in 30 seconds, terminating process") try: if sys.platform == 'win32': import ctypes handle = int(engine_ctl.engine.proc._handle) ctypes.windll.kernel32.TerminateProcess(handle, 0) else: os.kill(engine_ctl.engine.proc.pid, signal.SIGTERM) except os.error: # don't worry about errors when trying to kill the engine pass engine_ctl.cleanup() time.sleep(1) except (KeyboardInterrupt, SystemExit): raise except EngineCrashException, exc: log.error("Bot engine crashed (%s), restarting.", exc.args[0]) time.sleep(1)
eng.go() while True: try: resp = eng.get_response(10) if resp.type == "info": print resp.message elif resp.type == "log": print "log: %s" % resp.message elif resp.type == "bestmove": print "bestmove: %s" % resp.move break except socket.timeout: pass eng.quit() stop_waiting = time.time() + 60 while time.time() < stop_waiting: try: resp = eng.get_response(1) if resp.type == "info": print resp.message elif resp.type == "log": print "log: %s" % (resp.message) except socket.timeout: pass if eng.engine.proc.poll() is not None: break eng.cleanup()
def main(args): try: options = parseargs(args) except ValueError: print "Command not understood %s" % (" ".join(args)) sys.exit(2) config = SafeConfigParser() try: config.readfp(open('gameroom.cfg', 'rU')) except IOError: print "Could not open 'gameroom.cfg' this file must be readable and contain the configuration for connecting to the gameroom." sys.exit(1) aeilog = logging.getLogger("gameroom.aei") if config.has_section("Logging"): logdir = config.get("Logging", "directory") if not os.path.exists(logdir): print "Log directory '%s' not found, attempting to create it." % ( logdir) os.makedirs(logdir) logfilename = "%s-%s.log" % ( time.strftime("%Y%m%d-%H%M"), str(os.getpid()), ) logfilename = os.path.join(logdir, logfilename) if config.has_option("Logging", "level"): loglevel = str_loglevel(config.get("Logging", "level")) else: loglevel = logging.WARN logging.basicConfig( level=loglevel, filename=logfilename, datefmt="%Y-%m-%d %H:%M:%S", format="%(asctime)s %(levelname)s:%(name)s:%(message)s", ) if (config.has_option("Logging", "console") and config.getboolean("Logging", "console")): global console console = logging.StreamHandler() if config.has_option("Logging", "console_level"): conlevel = str_loglevel(config.get("Logging", "console_level")) else: conlevel = logging.INFO console.setLevel(conlevel) logging.getLogger('').addHandler(console) if config.has_option("Logging", "net_level"): netlevel = str_loglevel(config.get("Logging", "net_level")) netlog.setLevel(netlevel) if config.has_option("Logging", "engine_level"): enginelevel = str_loglevel(config.get("Logging", "engine_level")) enginelog.setLevel(enginelevel) if config.has_option("Logging", "aei_level"): aeilog.setLevel(str_loglevel(config.get("Logging", "aei_level"))) positionlog.setLevel(logging.ERROR) if (config.has_option("Logging", "log_position") and config.getboolean("Logging", "log_position")): positionlog.setLevel(logging.INFO) run_dir = config.get("global", "run_dir") if not os.path.exists(run_dir): log.warn( "Run file directory '%s' not found, attempting to create it." % (run_dir)) os.makedirs(run_dir) bot_count = how_many_bots(run_dir) if bot_count >= config.getint("global", "max_bots"): log.info( "Max number of bot limit %d reached, need to wait until some bots finish." % (config.getint("global", "max_bots"))) return bot_section = config.get("global", "default_engine") com_method = config.get(bot_section, "communication_method").lower() enginecmd = config.get(bot_section, "cmdline") games_num = config.getint(bot_section, "games_num") games_played = 0 while games_num == 0 or games_played < games_num: unknowns_caught = 0 gameid_or_opponent = options['against'] #while True: try: if com_method == "2008cc": engine_ctl = EngineController( SocketEngine(enginecmd, legacy_mode=True)) elif com_method == "socket": engine_ctl = EngineController( SocketEngine(enginecmd, log=aeilog)) elif com_method == "stdio": engine_ctl = EngineController( StdioEngine(enginecmd, log=aeilog)) else: raise ValueError("Unrecognized communication method, %s" % (com_method)) except OSError, exc: log.error("Could not start the engine; exception thrown: %s", exc) sys.exit(1) for option in config.options(bot_section): if option.startswith("bot_"): value = config.get(bot_section, option) engine_ctl.setoption(option[4:], value) log.info("Setting bot option %s = %s", option[4:], value) engine_ctl.isready() bot_username = config.get(bot_section, "username") bot_password = config.get(bot_section, "password") bot_greeting = config.get(bot_section, "greeting") gameroom = GameRoom(config.get("global", "gameroom_url")) gameroom.login(bot_username, bot_password) side = options['side'] table = None if gameid_or_opponent == "": log.info("Starting a new game") if side == "": side = 'b' tc = config.get(bot_section, "timecontrol") rated = config.getboolean(bot_section, "rated") log.info("Will play on side %s, using timecontrol %s" % (side, tc)) table = gameroom.newgame(side, tc, rated) else: # look through my games for correct opponent and side games = gameroom.mygames() for game in games: if (gameid_or_opponent == game['player'].lower() or gameid_or_opponent == game['gid']): if (side == "" or side == game['side'] and not already_playing( run_dir, game['gid'], game['side'])): table = Table(gameroom, game) log.info("Found in progress game") break if table == None: games = gameroom.opengames() for game in games: if (gameid_or_opponent == game['player'].lower() or gameid_or_opponent == game['gid']): if (side == "" or side == game['side'] and not already_playing( run_dir, game['gid'], game['side'])): table = Table(gameroom, game) log.info("Found game to join") break if table == None: log.error("Could not find game against %s with side '%s'", gameid_or_opponent, side) break # Set the game to play in to current game id in case of a restart gameid_or_opponent = table.gid if options['against'] != "": joinmsg = "Joined game gid=%s side=%s; against %s" % ( table.gid, table.side, options['against']) else: joinmsg = "Created game gid=%s side=%s; waiting for opponent" % ( table.gid, table.side) log.info(joinmsg) if console is None: print joinmsg if config.has_option(bot_section, "ponder"): table.ponder = config.getboolean(bot_section, "ponder") if table.ponder: log.info("Set pondering on.") else: log.info("Set pondering off.") else: table.ponder = False if config.has_option("global", "min_move_time"): table.min_move_time = config.getint("global", "min_move_time") log.info("Set minimum move time to %d seconds.", table.min_move_time) else: table.min_move_time = 5 if config.has_option("global", "min_time_left"): table.min_timeleft = config.getint("global", "min_time_left") log.info("Setting emergency stop time to %d seconds" % table.min_timeleft) else: table.min_timeleft = 5 try: try: log.info("Joining game on %s side", table.side) table.reserveseat() table.sitdown() table.updatestate() try: touch_run_file(run_dir, "%s%s.bot" % (table.gid, table.side)) time.sleep(1) # Give the server a small break. log.info("Starting play") table.playgame(engine_ctl, bot_greeting, options['onemove']) finally: log.info("Leaving game") remove_run_files(run_dir, "%s%s.bot" % (table.gid, table.side)) table.leave() #break games_played += 1 continue #Tomas changed from break finally: try: engine_ctl.quit() except (socket.error, IOError): pass for i in range(30): if engine_ctl.engine.proc.poll() is not None: break time.sleep(1) else: log.warn( "Engine did not exit in 30 seconds, terminating process" ) try: if sys.platform == 'win32': import ctypes handle = int(engine_ctl.engine.proc._handle) ctypes.windll.kernel32.TerminateProcess(handle, 0) else: os.kill(engine_ctl.engine.proc.pid, signal.SIGTERM) except os.error: # don't worry about errors when trying to kill the engine pass engine_ctl.cleanup() time.sleep(1) except (KeyboardInterrupt, SystemExit): raise except EngineCrashException, exc: log.error("Bot engine crashed (%s), restarting.", exc.args[0]) time.sleep(1)
eng.setposition(pos) eng.go() while True: try: resp = eng.get_response(10) if resp.type == "info": print resp.message elif resp.type == "log": print "log: %s" % resp.message elif resp.type == "bestmove": print "bestmove: %s" % resp.move break except socket.timeout: pass eng.quit() stop_waiting = time.time() + 60 while time.time() < stop_waiting: try: resp = eng.get_response(1) if resp.type == "info": print resp.message elif resp.type == "log": print "log: %s" % (resp.message) except socket.timeout: pass if eng.engine.proc.poll() is not None: break eng.cleanup()