示例#1
0
def setup():
    config = {}
    print("Where should the next tournament be?")
    config["location"] = input()
    print("When should the next tournament be? (ex. {year})".format(year=datetime.datetime.now().year))
    config["date"] = input()

    while True:
        sound = autoconf_sound()
        sound_options = ["(e)nter manually"]
        keys = "e"

        try:
            which_say = sound["say"]
            sound_options.append("(s)ay ({})".format(sound["say"]))
            keys += "s"
        except KeyError:
            pass

        try:
            which_say = sound["flite"]
            sound_options.append("(f)flite ({})".format(sound["flite"]))
            keys += "f"
        except KeyError:
            pass

        sound_options.append("(n)o sound")
        keys += "n"
        sound_options.append("(r)etry search")
        keys += "r"

        res = input_choice("Enable sound?", sound_options, keys)
        if res == "n":
            config["speak"] = False
            break
        elif res == "e":
            print("Please enter the location of the sound-giving binary:")
            sound_path = input()
        elif res == "s":
            sound_path = libpelita.shlex_unsplit(sound["say"])
        elif res == "f":
            sound_path = libpelita.shlex_unsplit(sound["flite"])
        else:
            continue

        print("Now trying to speak:")
        config["speak"] = True
        config["speaker"] = sound_path
        # must set a few dummy variables
        config["teams"] = []
        config["bonusmatch"] = []
        Config(config).say("Hello my master.")
        success = input_choice("Did you hear any sound? (y/n)", [], "yn")
        if success == "y":
            del config["teams"]
            del config["bonusmatch"]
            break

    print("Specify the folder where we should look for teams (or none)")
    folder = input().strip()
    if folder:
        try:
            subfolders = [
                x.as_posix()
                for x in pathlib.Path(folder).iterdir()
                if x.is_dir() and not x.name.startswith(".") and not x.name.startswith("_")
            ]
            config["teams"] = [{"spec": folder, "members": []} for folder in subfolders]
        except FileNotFoundError:
            print("Invalid path: {}".format(folder))

    res = input_choice("Should a bonus match be played? (y/n/i)", [], "yni")
    if res == "y":
        config["bonusmatch"] = True
    elif res == "n":
        config["bonusmatch"] = False

    def escape(str):
        return "-" + re.sub(r"[\W]", "_", str) if str else ""

    file_name = "tournament{location}{year}.yaml".format(
        location=escape(config["location"]), year=escape(config["date"])
    )

    print("Writing to: {file_name}".format(file_name=file_name))
    with open(file_name, "x") as f:
        yaml.dump(config, f, default_flow_style=False)
示例#2
0
def run_match(config, teams):
    team1, team2 = teams

    ctx = zmq.Context()
    reply_addr = "ipc://tournament-reply#{pid}".format(pid=os.getpid())
    reply_sock = ctx.socket(zmq.PAIR)
    reply_sock.bind(reply_addr)

    rounds = ['--rounds', str(config.rounds)] if config.rounds else []
    filter = ['--filter', config.filter] if config.filter else []
    viewer = ['--' + config.viewer] if config.viewer else []
    if config.tournament_log_folder:
        dumpfile = os.path.join(config.tournament_log_folder, "dump-{time}".format(time=time.strftime('%Y%m%d-%H%M%S')))
        dump = ['--dump', dumpfile]
    else:
        dump = []

    cmd = [libpelita.get_python_process()] + ["./pelitagame"] + [config.team_spec(team1), config.team_spec(team2),
                              '--reply-to', reply_addr,
                              '--seed', str(random.randint(0, sys.maxsize)),
                              *dump,
                              *filter,
                              *rounds,
                              *viewer]

    _logger.debug("Executing: {}".format(libpelita.shlex_unsplit(cmd)))

    # We use the environment variable PYTHONUNBUFFERED here to retrieve stdout without buffering
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            universal_newlines=True, env=dict(os.environ, PYTHONUNBUFFERED='x'))


    #if ARGS.dry_run:
    #    print("Would run: {cmd}".format(cmd=cmd))
    #    print("Choosing winner at random.")
    #    return random.choice([0, 1, 2])


    poll = zmq.Poller()
    poll.register(reply_sock, zmq.POLLIN)
    poll.register(proc.stdout.fileno(), zmq.POLLIN)
    poll.register(proc.stderr.fileno(), zmq.POLLIN)

    with io.StringIO() as stdout_buf, io.StringIO() as stderr_buf:
        final_game_state = None

        while True:
            evts = dict(poll.poll(1000))

            if not evts and proc.poll() is not None:
                # no more events and proc has finished.
                # we give up
                break

            stdout_ready = (not proc.stdout.closed) and evts.get(proc.stdout.fileno(), False)
            if stdout_ready:
                line = proc.stdout.readline()
                if line:
                    print(line, end='', file=stdout_buf)
                else:
                    poll.unregister(proc.stdout.fileno())
                    proc.stdout.close()
            stderr_ready = (not proc.stderr.closed) and evts.get(proc.stderr.fileno(), False)
            if stderr_ready:
                line = proc.stderr.readline()
                if line:
                    print(line, end='', file=stderr_buf)
                else:
                    poll.unregister(proc.stderr.fileno())
                    proc.stderr.close()
            socket_ready = evts.get(reply_sock, False)
            if socket_ready:
                try:
                    pelita_status = json.loads(reply_sock.recv_string())
                    game_state = pelita_status['__data__']['game_state']
                    finished = game_state.get("finished", None)
                    team_wins = game_state.get("team_wins", None)
                    game_draw = game_state.get("game_draw", None)
                    if finished:
                        final_game_state = game_state
                        break
                except json.JSONDecodeError:
                    pass
                except KeyError:
                    pass

        return (final_game_state, stdout_buf.getvalue(), stderr_buf.getvalue())
示例#3
0
def run_match(config, teams):
    team1, team2 = teams

    ctx = zmq.Context()
    reply_addr = "ipc://tournament-reply#{pid}".format(pid=os.getpid())
    reply_sock = ctx.socket(zmq.PAIR)
    reply_sock.bind(reply_addr)

    rounds = ['--rounds', str(config.rounds)] if config.rounds else []
    filter = ['--filter', config.filter] if config.filter else []
    viewer = ['--' + config.viewer] if config.viewer else []
    if config.tournament_log_folder:
        dumpfile = os.path.join(config.tournament_log_folder, "dump-{time}".format(time=time.strftime('%Y%m%d-%H%M%S')))
        dump = ['--dump', dumpfile]
    else:
        dump = []

    cmd = [libpelita.get_python_process()] + ["./pelitagame"] + [config.team_spec(team1), config.team_spec(team2),
                              '--reply-to', reply_addr,
                              '--seed', str(random.randint(0, sys.maxsize)),
                              *dump,
                              *filter,
                              *rounds,
                              *viewer]

    _logger.debug("Executing: {}".format(libpelita.shlex_unsplit(cmd)))

    # We use the environment variable PYTHONUNBUFFERED here to retrieve stdout without buffering
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            universal_newlines=True, env=dict(os.environ, PYTHONUNBUFFERED='x'))


    #if ARGS.dry_run:
    #    print("Would run: {cmd}".format(cmd=cmd))
    #    print("Choosing winner at random.")
    #    return random.choice([0, 1, 2])


    poll = zmq.Poller()
    poll.register(reply_sock, zmq.POLLIN)
    poll.register(proc.stdout.fileno(), zmq.POLLIN)
    poll.register(proc.stderr.fileno(), zmq.POLLIN)

    with io.StringIO() as stdout_buf, io.StringIO() as stderr_buf:
        final_game_state = None

        while True:
            evts = dict(poll.poll(1000))

            if not evts and proc.poll() is not None:
                # no more events and proc has finished.
                # we give up
                break

            stdout_ready = (not proc.stdout.closed) and evts.get(proc.stdout.fileno(), False)
            if stdout_ready:
                line = proc.stdout.readline()
                if line:
                    print(line, end='', file=stdout_buf)
                else:
                    poll.unregister(proc.stdout.fileno())
                    proc.stdout.close()
            stderr_ready = (not proc.stderr.closed) and evts.get(proc.stderr.fileno(), False)
            if stderr_ready:
                line = proc.stderr.readline()
                if line:
                    print(line, end='', file=stderr_buf)
                else:
                    poll.unregister(proc.stderr.fileno())
                    proc.stderr.close()
            socket_ready = evts.get(reply_sock, False)
            if socket_ready:
                try:
                    pelita_status = json.loads(reply_sock.recv_string())
                    game_state = pelita_status['__data__']['game_state']
                    finished = game_state.get("finished", None)
                    team_wins = game_state.get("team_wins", None)
                    game_draw = game_state.get("game_draw", None)
                    if finished:
                        final_game_state = game_state
                        break
                except json.JSONDecodeError:
                    pass
                except KeyError:
                    pass

        return (final_game_state, stdout_buf.getvalue(), stderr_buf.getvalue())
示例#4
0
def setup():
    config = {}
    print("Where should the next tournament be?")
    config['location'] = input()
    print("When should the next tournament be? (ex. {year})".format(year=datetime.datetime.now().year))
    config['date'] = input()

    while True:
        sound = autoconf_sound()
        sound_options = [
            "(e)nter manually",
        ]
        keys = "e"

        try:
            which_say = sound["say"]
            sound_options.append("(s)ay ({})".format(sound["say"]))
            keys += "s"
        except KeyError:
            pass

        try:
            which_say = sound["flite"]
            sound_options.append("(f)flite ({})".format(sound["flite"]))
            keys += "f"
        except KeyError:
            pass

        sound_options.append("(n)o sound")
        keys += "n"
        sound_options.append("(r)etry search")
        keys += "r"

        res = input_choice("Enable sound?", sound_options, keys)
        if res == "n":
            config["speak"] = False
            break
        elif res == "e":
            print("Please enter the location of the sound-giving binary:")
            sound_path = input()
        elif res == "s":
            sound_path = libpelita.shlex_unsplit(sound["say"])
        elif res == "f":
            sound_path = libpelita.shlex_unsplit(sound["flite"])
        else:
            continue

        print("Now trying to speak:")
        config["speak"] = True
        config['speaker'] = sound_path
        # must set a few dummy variables
        config['teams'] = []
        config['bonusmatch'] = []
        Config(config).say("Hello my master.")
        success = input_choice("Did you hear any sound? (y/n)", [], "yn")
        if success == "y":
            del config["teams"]
            del config["bonusmatch"]
            break

    print("Specify the folder where we should look for teams (or none)")
    folder = input().strip()
    if folder:
        try:
            subfolders = [x.as_posix() for x in pathlib.Path(folder).iterdir() if x.is_dir()
                                                                               and not x.name.startswith('.')
                                                                               and not x.name.startswith('_')]
            config["teams"] = [{ 'spec': folder, 'members': []} for folder in subfolders]
        except FileNotFoundError:
            print("Invalid path: {}".format(folder))

    res = input_choice("Should a bonus match be played? (y/n/i)", [], "yni")
    if res == "y":
        config['bonusmatch'] = True
    elif res == "n":
        config['bonusmatch'] = False

    def escape(str):
        return "-" + re.sub(r'[\W]', '_', str) if str else ""

    file_name = "tournament{location}{year}.yaml".format(location=escape(config["location"]),
                                                         year=escape(config["date"]))

    print("Writing to: {file_name}".format(file_name=file_name))
    with open(file_name, "x") as f:
        yaml.dump(config, f, default_flow_style=False)