def learn(self, env, episode_count=1000, gamma=0.9,
              learning_rate=0.1, render=False, report_interval=50):
        """QLearningAgent.learn
        env:環境のデータが格納された変数です。
        episode_count:エピソード回数を指定します。default:1000
        gamma:割引率を指定します。default:0.9
        render:画面に様子を表示するかどうか設定します。default:False
        report_interval:ログを保存する間隔を設定します。default:50"""
        self.init_log()
        actions = list(range(env.action_space.n))
        self.Q = defaultdict(lambda: [0] * len(actions))
        for e in tqdm(range(episode_count)):
            s = env.reset()
            done = False
            while not done:
                if render:
                    cuitools.reset()
                    env.render()
                    time.sleep(0.01)
                a = self.policy(s, actions)
                n_state, reward, done, info = env.step(a)

                gain = reward + gamma * max(self.Q[n_state])
                estimated = self.Q[s][a]
                self.Q[s][a] += learning_rate * (gain - estimated)
                s = n_state

            else:
                self.log(reward)

            if e != 0 and e % report_interval == 0:
                pass
    def learn(self,
              env,
              episode_count=1000,
              gamma=0.9,
              render=False,
              report_interval=50):
        """MonteCarloAgent.learn
env:環境のデータが格納された変数です。
episode_count:エピソード回数を指定します。default:1000
gamma:割引率を指定します。default:0.9
render:画面に様子を表示するかどうか設定します。default:False
report_interval:ログを保存する間隔を設定します。default:50"""
        self.init_log()
        actions = list(range(env.action_space.n))
        self.Q = defaultdict(lambda: [0] * len(actions))
        N = defaultdict(lambda: [0] * len(actions))

        for e in tqdm(range(episode_count)):
            s = env.reset()
            done = False
            # Play until the end of episode.
            experience = []
            while not done:
                if render:
                    cuitools.reset()
                    env.render()
                    time.sleep(0.01)
                a = self.policy(s, actions)
                n_state, reward, done, info = env.step(a)
                experience.append({"state": s, "action": a, "reward": reward})
                s = n_state
            else:
                self.log(reward)

            # Evaluate each state, action.
            for i, x in enumerate(experience):
                s, a = x["state"], x["action"]

                # Calculate discounted future reward of s.
                G, t = 0, 0
                for j in range(i, len(experience)):
                    G += math.pow(gamma, t) * experience[j]["reward"]
                    t += 1

                N[s][a] += 1  # count of s, a pair
                alpha = 1 / N[s][a]
                self.Q[s][a] += alpha * (G - self.Q[s][a])

            if e != 0 and e % report_interval == 0:
                pass
예제 #3
0
    def train(self,
              env,
              episode_count=1000,
              gamma=0.9,
              learning_rate=0.1,
              render=False,
              report_interval=50):
        """actor_critic.train
                env:環境のデータが格納された変数です。
                episode_count:エピソード回数を指定します。default:1000
                gamma:割引率を指定します。default:0.9
                render:画面に様子を表示するかどうか設定します。default:False
                report_interval:ログを保存する間隔を設定します。default:50"""
        actor = self.actor_class(env)
        critic = self.critic_class(env)

        actor.init_log()
        for e in tqdm(range(episode_count)):
            s = env.reset()
            done = False
            while not done:
                if render:
                    cuitools.reset()
                    env.render()
                    time.sleep(0.01)
                a = actor.policy(s)
                n_state, reward, done, info = env.step(a)

                gain = reward + gamma * critic.V[n_state]
                estimated = critic.V[s]
                td = gain - estimated
                actor.Q[s][a] += learning_rate * td
                critic.V[s] += learning_rate * td
                s = n_state

            else:
                actor.log(reward)

            if e != 0 and e % report_interval == 0:
                pass
                # actor.show_reward_log(episode=e)

        return actor, critic
예제 #4
0
def to256_window(title, text, reset=True, background_file=None, place="c"):
    terminal_size = shutil.get_terminal_size()
    if terminal_size[0] < 15:
        cuitools.reset()
        print("\033[1;1HThe screen is too small. Please make it bigger.")
        while terminal_size[0] < 15:
            terminal_size = shutil.get_terminal_size()

    tmp = reload(text)

    if reset:
        cuitools.reset()
    if background_file is not None:
        background(background_file)
    k = ""
    scroll = 0
    while k != "q":
        terminal_size = shutil.get_terminal_size()
        printtext = tmp[0 + scroll:terminal_size[1] - 4 + scroll]
        printtext.insert(0, title)
        printtext.append("")
        lentext = terminal_size[0] - 15
        if place == "c":
            y = int(terminal_size[1] / 2 - len(printtext) / 2)
            x = int(terminal_size[0] / 2 - lentext / 2)
        elif place == "n":
            y = 1
            x = int(terminal_size[0] / 2 - lentext / 2)
        elif place == "nw":
            y = 1
            x = 1
        elif place == "ne":
            y = 1
            x = terminal_size[0] - lentext - 1
        elif place == "e":
            y = int(terminal_size[1] / 2 - len(printtext) / 2)
            x = terminal_size[0] - lentext - 1
        elif place == "w":
            y = int(terminal_size[1] / 2 - len(printtext) / 2)
            x = 1
        elif place == "s":
            y = terminal_size[1] - len(printtext)
            x = int(terminal_size[0] / 2 - lentext / 2)
        elif place == "sw":
            y = terminal_size[1] - len(printtext)
            x = 1
        elif place == "se":
            y = terminal_size[1] - len(printtext)
            x = terminal_size[0] - lentext - 1
        else:
            raise IndexError("placeはc,n,nw,ne,e,w,s,sw,seのみ対応しています")
        for i in range(len(printtext)):
            if i == 0:
                print("\033[" + str(y + i) + ";" + str(x) + "H\033[0m┏" +
                      cuitools.subp.ljust_kana(printtext[i], lentext, "━") +
                      "┓")
            elif i == len(printtext) - 1:
                print("\033[" + str(y + i) + ";" + str(x) + "H┗" +
                      cuitools.subp.ljust_kana(printtext[i], lentext, "━") +
                      "┛")
            else:
                print("\033[" + str(y + i) + ";" + str(x) + "H┃" +
                      cuitools.subp.ljust_kana(printtext[i], lentext, " ") +
                      "┃")

        k = cuitools.Key()
        old_terminal_size = terminal_size
        terminal_size = shutil.get_terminal_size()
        if old_terminal_size != terminal_size:
            if scroll > len(tmp) - terminal_size[1] + 4:
                scroll = len(tmp) - terminal_size[1] + 1
            cuitools.reset()
            tmp = reload(text)
            if background_file is not None:
                background(background_file)
        if k == "\x1b":
            k = cuitools.Key()
            if k == "[":
                k = cuitools.Key()
                if k == "A":
                    if scroll != 0:
                        scroll -= 1
                if k == "B":
                    if scroll < len(tmp) - terminal_size[1] + 4:
                        scroll += 1
예제 #5
0
def plugin(module, lang):
    logger = logging.getLogger("plugin")
    print("\033[0m")
    select = cuitools.printlist(
        lang.lang("プラグインを選択"),
        plugin_text(lang, "name") + [
            lang.lang("バイナリファイルデータの追加・変更"),
            lang.lang("プラグインを追加"),
            lang.lang("前ページへ戻る(ホーム)")
        ])
    if select != -1 and select < len(plugin_text(lang, "name")):
        sselect = 0
        while True:

            printtext = [
                lang.lang("名前:") + plugin_text(lang, "name")[select],
                lang.lang("バージョン:") + plugin_text(lang, "version")[select],
                lang.lang("管理者:") + plugin_text(lang, "author")[select],
                lang.lang("管理者のメールアドレス:") +
                plugin_text(lang, "author_email")[select], ""
            ]
            if sselect == 0:
                printtext.append(">> " + lang.lang("前ページへ戻る(ホーム)"))
                printtext.append("   " + lang.lang("説明を読む"))
            else:
                printtext.append("   " + lang.lang("前ページへ戻る(ホーム)"))
                printtext.append(">> " + lang.lang("説明を読む"))
            # print(printtext)
            cuitools.box(
                lang.lang("詳細情報") + " " + plugin_text(lang, "name")[select],
                printtext)
            k = cuitools.Key()
            if k == "\x1b":
                cuitools.Key()
                k = cuitools.Key()
                if k == "B":
                    if sselect < 1:
                        sselect += 1
                elif k == "A":
                    if sselect > 0:
                        sselect -= 1
            elif k == "\n":
                if sselect == 0:
                    break
                else:
                    cuitools.printlist(
                        lang.lang("説明を読む"),
                        plugin_text(lang, "description")[select].splitlines(),
                        False)
    elif select == len(plugin_text(lang, "name")):
        while True:
            cuitools.reset()
            print(lang.lang("必要なデータをダウンロード中..."))
            data_list = cszp_module.download_file_mem(
                lang,
                "https://raw.githubusercontent.com/kumitatepazuru/Soccer-binary"
                "-files-for-cszp "
                "/master/data.json")
            if data_list is not None:
                data_list = json.loads(data_list)
                text_list = list(map(lambda n: n["text"], data_list))
                folder_list = list(map(lambda n: n["folder"], data_list))
                url_list = list(map(lambda n: n["url"], data_list))
                team_data_list = list(map(lambda n: n["data"], data_list))
                num = cuitools.printlist(lang.lang("バイナリファイルデータの追加・変更"),
                                         text_list + [lang.lang("前ページへ戻る")])
                if num == len(data_list):
                    break
                else:
                    while True:
                        if os.path.isfile("config/" + folder_list[num]):
                            result = button_dialog(
                                title=lang.lang("詳細情報") + "/" + text_list[num],
                                text="download URL:" + url_list[num] + "\n" +
                                lang.lang("インストール済み"),
                                buttons=[(lang.lang('前ページへ戻る'), True),
                                         (lang.lang("削除する"), False),
                                         (lang.lang("選手一覧"), None)]).run()
                            if result:
                                break
                            elif result is None:
                                cuitools.reset()
                                print("\n".join(
                                    json.loads(
                                        cszp_module.download_file_mem(
                                            lang, team_data_list[num]))))
                                input(lang.lang("Enterキーを押して続行..."))
                            else:
                                cuitools.reset()
                                logger.info("removing " + folder_list[num])
                                print(lang.lang("削除中です..."))
                                with open("./config/" +
                                          folder_list[num]) as fl:
                                    id = fl.read().splitlines()[0]
                                    with open("config/hogo.json") as F:
                                        data = json.load(F)
                                        js = []
                                        for i in data:
                                            logger.debug(i + " " +
                                                         str(i.find(id)))
                                            if i.find(id) == -1:
                                                js.append(i)
                                    with open("config/hogo.json", "w") as i:
                                        json.dump(js, i)
                                    shutil.rmtree("teams/" + id)
                                os.remove("./config/" + folder_list[num])
                                logger.debug(id)
                                with module.Open("config/plus.txt") as f:
                                    p = []
                                    for i, j in enumerate(
                                            f.read()[1:].split(",")):
                                        if i % 2 == 0:
                                            p.append([j])
                                        else:
                                            p[-1].append(j)
                                    logger.debug(p)
                                    j = 0
                                    while j < len(p):
                                        i = p[j]
                                        logger.debug(
                                            f"{j} {i} {i[1].find(id)}")
                                        if i[1].find(id) != -1:
                                            del p[j]
                                        else:
                                            j += 1
                                with module.Open("config/plus.txt", "w") as f:
                                    logger.debug("," + ",".join(
                                        list(
                                            map(lambda n: n[0] + "," + n[1],
                                                p))))
                                    tmp = ",".join(
                                        list(
                                            map(lambda n: n[0] + "," + n[1],
                                                p)))
                                    if len(tmp) != 0:
                                        f.write("," + tmp)
                                logger.info("removed.")
                                input("\n" + lang.lang("Enterキーを押して続行..."))
                        else:
                            result = button_dialog(
                                title=lang.lang("詳細情報") + "/" + text_list[num],
                                text="download URL:" + url_list[num] + "\n" +
                                lang.lang("未インストール"),
                                buttons=[(lang.lang('前ページへ戻る'), True),
                                         (lang.lang("インストールする"), False),
                                         (lang.lang("選手一覧"), None)]).run()
                            if result:
                                break
                            elif result is False:
                                cuitools.reset()
                                print(
                                    lang.lang("必要なデータをダウンロード中...") +
                                    lang.lang("これには数分~数十分かかることがあります。") + "\n")
                                print(url_list[num])
                                cszp_module.download_files_progress(
                                    lang, [url_list[num]])
                                print("\n" + lang.lang("データを解凍中...") +
                                      lang.lang("これには数分~数十分かかることがあります。"))
                                h = ""
                                while h == "" or os.path.isdir("teams/" + h):
                                    h = gen_rand_str_hex(8)
                                with zipfile.ZipFile("/tmp/" +
                                                     folder_list[num] +
                                                     ".zip") as existing_zip:
                                    existing_zip.extractall("/tmp")
                                try:
                                    cmd = [
                                        "unzip", "-od", "/tmp",
                                        "/tmp/" + folder_list[num] + ".zip"
                                    ]
                                    print(" ".join(cmd))
                                    subprocess.check_call(cmd)
                                except FileNotFoundError:
                                    while True:
                                        cuitools.box(lang.lang("エラー"), [
                                            lang.lang(
                                                "この機能を使用するにはunzipをインストールする必要があります。"
                                            ),
                                            lang.lang("Enterキーを押して続行...")
                                        ])
                                        if cuitools.Key() == "\n":
                                            break
                                    continue
                                with open(
                                        "/tmp/Soccer-binary-files-for-cszp-" +
                                        folder_list[num] + "/hogo.json") as f:
                                    with open("config/hogo.json") as F:
                                        data = json.load(F)
                                        tmp = json.load(f)
                                        tmp = list(
                                            map(
                                                lambda n:
                                                "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./teams/"
                                                + h + "/libs ./teams/" + h +
                                                "/" + n, tmp))
                                        data += tmp
                                    with open("config/hogo.json", "w") as F:
                                        json.dump(data, F)
                                    with open(
                                            "/tmp/Soccer-binary-files-for-cszp-"
                                            + folder_list[num] +
                                            "/team.json") as F:
                                        tmp2 = json.load(F)
                                        data = ""
                                        for i, j in zip(tmp2, tmp):
                                            data += "," + i + "," + j
                                        F = module.Open(
                                            "./config/plus.txt", "a")
                                        F.write(data)
                                os.mkdir("teams/" + h)
                                print("\n" + lang.lang("データをコピー中..."))
                                for i in tqdm(
                                        glob.glob(
                                            "/tmp/Soccer-binary-files-for-cszp-"
                                            + folder_list[num] + "/teams/*")):
                                    shutil.copytree(
                                        i,
                                        "teams/" + h + "/" + i.split("/")[-1])
                                os.mkdir("teams/" + h + "/libs")
                                for i in tqdm(
                                        glob.glob(
                                            "/tmp/Soccer-binary-files-for-cszp-"
                                            + folder_list[num] + "/libs/*")):
                                    shutil.copy(i, "teams/" + h + "/libs")
                                shutil.copy(
                                    "/tmp/Soccer-binary-files-for-cszp-" +
                                    folder_list[num] + "/hogo.json",
                                    "teams/" + h)
                                with open("config/" + folder_list[num],
                                          "w") as f:
                                    f.write(h)
                                # module = cszp_module.Open()
                                input("\n" + lang.lang("Enterキーを押して続行..."))

                            elif result is None:
                                cuitools.reset()
                                print("\n".join(
                                    json.loads(
                                        cszp_module.download_file_mem(
                                            lang, team_data_list[num]))))
                                input("\n" + lang.lang("Enterキーを押して続行..."))
                cuitools.reset()
                print("")
            else:
                break

        plugin(module, lang)
    elif select == len(plugin_text(lang, "name")) + 1:
        k = ""
        while k != "\n":
            cuitools.box(lang.lang("プラグインを追加"), [
                lang.lang("プラグインの追加を行います。"),
                lang.lang("プラグインの入ったzipファイルを選択してください。"),
                lang.lang("終了したい場合は次の画面に行ってからqキーを押してください。"),
                lang.lang("Enterキーを押して続行...")
            ])
            k = cuitools.Key()
        ok = None
        while ok is None:
            path = cuitools.Inputfilegui(
                lang.lang("プラグインの入ったzipファイルを選択(終了したい場合はQキー)"))
            if path == -1:
                plugin(module, lang)
                break
            elif path == -2:
                raise KeyboardInterrupt()
            else:
                cuitools.reset()
                try:
                    with zipfile.ZipFile(path) as existing_zip:
                        existing_zip.extractall('./plugins/')
                except zipfile.BadZipFile:
                    k = ""
                    while k != "\n":
                        cuitools.box(lang.lang("エラー"), [
                            lang.lang("zipファイルではありません。"),
                            lang.lang("Enterキーを押して続行...")
                        ],
                                     reset_=True)
                        k = cuitools.Key()
                else:
                    k = ""
                    lang = terminal(noenter=True)
                    lang.autostart(lang)
                    while k != "\n":
                        cuitools.box("完了", [
                            lang.lang("正常にプラグインが追加されました。"),
                            lang.lang("正常にプラグインが動作するか確認してください。"),
                            lang.lang("Enterキーを押して続行...")
                        ])
                        k = cuitools.Key()
                    ok = lang
        return ok

    elif select == len(plugin_text(lang, "name")) + 2:
        pass
예제 #6
0
def rrt(lang, module, Input_):
    table = kakunin(module)

    data = module.Open("./config/setting.conf")
    datas = data.read().splitlines()[0]
    data.close()
    datas = datas.split(",")
    datal = []
    for i in range(2, len(datas), 2):
        datal.append((datas[i + 1], datas[i]))
    if len(datal) == 0:
        k = ""
        while k != "\n":
            cuitools.box(lang.lang("エラー"), [
                lang.lang("簡単サッカー実行リストにチームが設定されていないのでこの機能は使用できません。"),
                lang.lang("settingコマンドでチームの追加ができます。詳しくはsettingコマンドを確認してください。"),
                lang.lang("Enterキーを押して続行...")
            ])
            k = cuitools.Key()
    elif yes_no_dialog(
            title=lang.lang("cszp 簡単サッカー実行プログラム") + "/" + lang.lang("設定確認"),
            text=table.draw() + lang.lang("\nEnterキーを押して続行...")).run():
        k = ""
        csv_save = False
        ok = False
        ver = open("./version")
        v = ver.read()
        ver.close()
        kantan_list = list(map(lambda n: n[1], datal))
        kantan_cmd = list(map(lambda n: n[0], datal))
        select = 0
        selector = []
        synch = False
        while k != "\n" or not ok:
            cuitools.reset()
            print("\033[1;1H\033[0m\033[38;5;172m")
            figlet("cszp " + v)
            if select == -1:
                print("\033[1m\033[38;5;9m>  \033[38;5;10m" +
                      lang.lang("前ページへ戻る(ホーム)") + "\033[0m\n")
            else:
                print("   \033[38;5;10m" + lang.lang("前ページへ戻る(ホーム)") +
                      "\033[0m\n")
            print("\033[38;5;12m" + lang.lang("総当たり戦をさせるチームを選択してください。"))
            for i, j in enumerate(kantan_list):
                if i in selector:
                    if select == i:
                        print(
                            "\033[1m\033[38;5;9m>\033[38;5;11m* \033[38;5;10m"
                            + j + "\033[0m")
                    else:
                        print("\033[38;5;11m * \033[38;5;10m" + j + "\033[0m")
                elif select == i:
                    print("\033[1m\033[38;5;9m>  \033[38;5;10m" + j +
                          "\033[0m")
                else:
                    print("   \033[38;5;10m" + j + "\033[0m")
            print("")
            if select == len(kantan_list):
                print("\033[1m\033[38;5;9m>  \033[38;5;14m" +
                      lang.lang("synchモードでの実行") +
                      ":\033[0m\033[4m\033[38;5;14m" + "No" *
                      ((synch - 1) * -1) + "Yes" * synch + "\033[0m")
            else:
                print("   \033[38;5;14m" + lang.lang("synchモードでの実行") +
                      ":\033[0m\033[4m\033[38;5;14m" + "No" *
                      ((synch - 1) * -1) + "Yes" * synch + "\033[0m")
            if select == len(kantan_list) + 1:
                if csv_save is False:
                    print("\033[1m\033[38;5;9m>  \033[38;5;11m" +
                          lang.lang("csvログの保存") + ":\033[0m\033[4m\033["
                          "38;5;14mNo\033[0m")
                else:
                    print("\033[1m\033[38;5;9m>  \033[38;5;11m" +
                          lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14m" + csv_save +
                          "\033[0m")
            else:
                if csv_save is False:
                    print("   \033[38;5;11m" + lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14mNo\033[0m")
                else:
                    print("   \033[38;5;11m" + lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14m" + csv_save +
                          "\033[0m")
            if select == len(kantan_list) + 2 and len(selector) > 1:
                print("\033[1m\033[38;5;9m>  \033[38;5;10m" +
                      lang.lang("サッカーを実行") + "\033[0m")
            elif len(selector) < 2:
                print("   \033[38;5;243m" + lang.lang("サッカーを実行") + "\033[0m")
            else:
                print("   \033[38;5;10m" + lang.lang("サッカーを実行") + "\033[0m")

            table = []
            tmp = [""]
            for i in selector:
                tmp.append(kantan_list[i])
            table.append(tmp)
            for i in selector:
                table.append([kantan_list[i]] + [""] * len(selector))
            print(Texttable().add_rows(table).draw())
            k = cuitools.Key()
            if k == "\x1b":
                k = cuitools.Key()
                if k == "[":
                    k = cuitools.Key()
                    if k == "B":
                        if len(kantan_list) + 2 > select:
                            select += 1
                            if len(kantan_list) + 2 == select and len(
                                    selector) < 2:
                                select -= 1
                    elif k == "A":
                        if -1 < select:
                            select -= 1
            if (k == " " or k == "\n") and select == -1:
                break
            elif (k == " " or k == "\n") and select == len(kantan_list) + 2:
                ok = True
                break
            elif (k == " " or k == "\n") and select == len(kantan_list) + 1:
                tmp = yesno(lang.lang("選択"), [lang.lang("csvログを保存しますか?")])
                if tmp == 0:
                    tmp = Input()
                    tmp = tmp.Input("filename")
                    if len(tmp.split(".")) == 1:
                        tmp += ".csv"
                    csv_save = tmp
                else:
                    csv_save = False
            elif (k == " " or k == "\n") and select == len(kantan_list):
                tmp = yesno(lang.lang("選択"), [lang.lang("synchモードで実行しますか?")])
                if tmp == 0:
                    synch = True
                else:
                    synch = False
            elif (k == " " or k == "\n") and select > -1:
                if select in selector:
                    for i, j in enumerate(selector):
                        if j == select:
                            del selector[i]
                            break
                else:
                    selector.append(select)
        if ok:
            table = []
            tmp = [""]
            for i in selector:
                tmp.append(kantan_list[i])
            table.append(tmp)
            for i in selector:
                table.append([kantan_list[i]] + [""] * len(selector))
            for i in range(len(table)):
                if i != 0:
                    table[i][i] = "N/A"
            tmp = []
            for i in selector:
                for j in selector:
                    if kantan_cmd[i] != kantan_cmd[j] and not [
                            kantan_cmd[j], kantan_cmd[i]
                    ] in tmp:
                        tmp.append([kantan_cmd[i], kantan_cmd[j]])
            tmp2 = []
            for i in selector:
                for j in selector:
                    if kantan_cmd[i] != kantan_cmd[j] and not [
                            kantan_list[j], kantan_list[i]
                    ] in tmp2:
                        tmp2.append([kantan_list[i], kantan_list[j]])
            # print(tmp)
            data = module.Open("./config/config.conf")
            datas = data.read().splitlines()
            data.close()
            datas = datas[0].split(",")
            arg = "server::auto_mode=true server::kick_off_wait=20 server::game_over_wait=20 " \
                  "server::connect_wait=2000 server::game_log_dir=" + datas[7] + " server::text_log_dir=" + datas[
                      7] + " server::game_logging=" + (
                          "true" * (datas[3] == "on") + "false" * (datas[3] == "off")) + " server::text_logging=" + (
                          "true" * (datas[3] == "on") + "false" * (datas[3] == "off"))
            # arg += " server::nr_normal_halfs=1 server::nr_extra_halfs=0 server::penalty_shoot_outs=0 " \
            #        "server::half_time=10"
            s = [0, 1]
            results = []
            for i, j in zip(tmp, tmp2):
                cuitools.reset()
                print("\033[1;1H\033[0m\033[38;5;172m")
                figlet("cszp " + v)
                print("\033[0m")
                print(Texttable().add_rows(table).draw() + "\n" + "━" * 50)
                try:
                    _ = soccer([i[0], i[1], arg], lang, 1, module,
                               [False, False, False, synch], Input_, False,
                               False, False)
                except KeyboardInterrupt:
                    break
                result = _.get_result()
                if len(result) == 0:
                    table[s[0] + 1][s[1] + 1] = "Error"
                else:
                    tmp3 = result[0]
                    tmp3[1] = table[s[0] + 1][0]
                    tmp3[2] = table[0][s[1] + 1]
                    results.append(tmp3)
                    table[s[0] +
                          1][s[1] +
                             1] = str(result[0][3]) + "-" + str(result[0][4])
                s[1] += 1
                if s[1] > len(selector) - 1:
                    s[0] += 1
                    s[1] = 0
                tmp3 = list(map(lambda n: n + 1, s))
                while [j[1], j[0]] != [table[tmp3[0]][0], table[0][tmp3[1]]]:
                    print([table[tmp3[0]][0], table[0][tmp3[1]]], [j[1], j[0]])
                    tmp3[1] += 1
                    if tmp3[1] > len(selector):
                        tmp3[0] += 1
                        tmp3[1] = 0
                if len(result) == 0:
                    table[tmp3[0]][tmp3[1]] = "Error"
                else:
                    table[tmp3[0]][tmp3[1]] = str(result[0][4]) + "-" + str(
                        result[0][3])

                while s[1] <= s[0]:
                    s[1] += 1
                    if s[1] > len(selector):
                        s[0] += 1
                        s[1] = 0
            if csv_save is not False:
                with open(datas[7] + "/" + csv_save, "w") as f:
                    f.write("\n".join(
                        list(map(lambda n: ",".join(map(str, n)), results))))
            cuitools.reset()
            print("\033[1;1H\033[0m\033[38;5;172m")
            figlet("cszp " + v)
            print("\033[0m")
            print("\033[1m\033[38;5;11m" + lang.lang("集計結果") + "\033[0m\n" +
                  "━" * 50 + "\n" + Texttable().add_rows(table).draw())
            tmp = []
            for i in results:
                if not i[1] in list(map(lambda n: n[0], tmp)):
                    tmp.append([i[1], [0, 0, 0]])
                for j, k in enumerate(tmp):
                    if k[0] == i[1]:
                        break
                if i[3] > i[4]:
                    tmp[j][1][0] += 1
                elif i[3] < i[4]:
                    tmp[j][1][1] += 1
                else:
                    tmp[j][1][2] += 1

                if not i[2] in list(map(lambda n: n[0], tmp)):
                    tmp.append([i[2], [0, 0, 0]])
                for j, k in enumerate(tmp):
                    if k[0] == i[2]:
                        break
                if i[4] > i[3]:
                    tmp[j][1][0] += 1
                elif i[4] < i[3]:
                    tmp[j][1][1] += 1
                else:
                    tmp[j][1][2] += 1
            table = [["", "W", "D", "L", "Total"]]
            for i in tmp:
                table.append(
                    [i[0], i[1][0], i[1][2], i[1][1], i[1][0] - i[1][1]])
            print("\n" + "━" * 50 + "\n" + Texttable().add_rows(table).draw())
            Input_.Input(lang.lang("Enterキーを押して続行..."), dot=False)
예제 #7
0
def setting(lang, module, Input_, testmode=False, loopmode=False):
    logger = logging.getLogger("setting")
    data = module.Open("./config/config.conf")
    datas = data.read().splitlines()
    data.close()
    datas = datas[0].split(",")
    table = kakunin(module)

    if yes_no_dialog(
            title=lang.lang("cszp 簡単サッカー実行プログラム") + "/" + lang.lang("設定確認"),
            text=table.draw() + lang.lang("\nEnterキーを押して続行...")).run():
        k = ""
        ok = False
        select = 0
        text = [
            ["\033[38;5;10m" + lang.lang("前ページへ戻る(ホーム)"), False],
            ["\033[38;5;11m" + lang.lang("Team1(黄色)チームのパスを選択"), "None", 0],
            ["\033[38;5;9m" + lang.lang("Team2(赤色)チームのパスを選択"), "None", 0],
            ["\033[38;5;10m" + "─" * shutil.get_terminal_size()[0], None],
            ["\033[38;5;12m" + lang.lang("サーバーの引数を入力(ない場合は空欄)"), "", None],
            ["\033[38;5;10m" + "─" * shutil.get_terminal_size()[0], None],
            ["\033[38;5;9m" + lang.lang("保存先") + " " + datas[7], None],
            ["\033[38;5;11m" + lang.lang("サーバーログの保存"), "No", None],
            ["\033[38;5;11m" + lang.lang("プレイヤーログの保存"), "No", None],
            ["\033[38;5;11m" + lang.lang("csvログの保存"), "No", None],
            ["\033[38;5;10m" + "─" * shutil.get_terminal_size()[0], None],
            ["\033[38;5;14m" + lang.lang("synchモードでの実行"), "No", None],
            ["\033[38;5;14m" + lang.lang("サーバーの起動"), "Yes", None],
        ]
        if loopmode:
            text += [[
                "\033[38;5;10m" + "─" * shutil.get_terminal_size()[0], None
            ], ["\033[38;5;15m" + lang.lang("ループ回数を指定"), 3, 1]]
        if testmode:
            text += [["", None],
                     ["\033[38;5;11m" + lang.lang("*テストモードで実行しています"), None]]
        else:
            text += [["", None]]
        text += [["\033[38;5;243m" + lang.lang("サッカーを実行"), False]]
        ver = open("./version")
        v = ver.read()
        ver.close()
        while k != "\n" or ok is False:
            cuitools.reset()
            print("\033[1;1H\033[0m\033[38;5;172m")
            figlet("cszp " + v)
            for i, j in enumerate(text):
                if j[1] is False:
                    if i == select:
                        print("\033[1m\033[38;5;9m> " + j[0] + "\033[0m")
                    else:
                        print("  " + j[0] + "\033[0m")
                elif j[1] is not None:
                    if j[2] is None:
                        if i == select:
                            print("\033[1m\033[38;5;9m> " + j[0] +
                                  ":\033[0m\033[4m\033[38;5;14m" + str(j[1]) +
                                  "\033[0m")
                        else:
                            print("  " + j[0] +
                                  ":\033[0m\033[4m\033[38;5;14m" + str(j[1]) +
                                  "\033[0m")
                    else:
                        if i == select:
                            print("\033[1m\033[38;5;9m> " + j[0] +
                                  ":\033[0m\033[4m\033[38;5;14m" + str(j[1]) +
                                  "\033[0m " +
                                  ("\033[38;5;9m✖" * ((j[2] - 1) * -1) +
                                   "\033[38;5;10m✔" * j[2]) + "\033[0m ")
                        else:
                            print("  " + j[0] +
                                  ":\033[0m\033[4m\033[38;5;14m" + str(j[1]) +
                                  "\033[0m " +
                                  ("\033[38;5;9m✖" * ((j[2] - 1) * -1) +
                                   "\033[38;5;10m✔" * j[2]) + "\033[0m ")
                else:
                    print(j[0])
            print("\n")

            k = cuitools.Key()
            if k == "\n":
                if select == 0:
                    break
                elif select == 1 or select == 2:
                    tmp = yesno(lang.lang("選択"),
                                [lang.lang("簡単サッカー実行リストから選択しますか?")])
                    if tmp == 0:
                        data = module.Open("./config/setting.conf")
                        datas = data.read().splitlines()[0]
                        data.close()
                        datas = datas.split(",")
                        datal = []
                        for i in range(2, len(datas), 2):
                            datal.append((datas[i + 1], datas[i]))
                        if len(datal) == 0:
                            k = ""
                            while k != "\n":
                                cuitools.box(lang.lang("エラー"), [
                                    lang.lang(
                                        "簡単サッカー実行リストにチームが設定されていないのでこの機能は使用できません。"
                                    ),
                                    lang.lang(
                                        "settingコマンドでチームの追加ができます。詳しくはsettingコマンドを確認してください。"
                                    ),
                                    lang.lang("Enterキーを押して続行...")
                                ])
                                k = cuitools.Key()
                        else:
                            tmp = Input()
                            tmp = tmp.Input(lang.lang(
                                "簡単サッカー実行リストで設定した名前を指定(Tabで一覧が確認できます)"),
                                            word=list(
                                                map(lambda n: n[1], datal)))
                            text[select][1] = "None"
                            text = check_path(text, module)
                            for i in datal:
                                if i[1] == tmp:
                                    text[select][1] = i[0]
                                    text = check_path(text, module)
                                    break
                    else:
                        if select == 1:
                            tmp = cuitools.Inputfilegui(
                                lang.lang("Team1(黄色)チームのパスを選択") +
                                lang.lang("(選択方法の変更・終了はQキー)"))
                        else:
                            tmp = cuitools.Inputfilegui(
                                lang.lang("Team2(赤色)チームのパスを選択") +
                                lang.lang("(選択方法の変更・終了はQキー)"))
                        if tmp == -1:
                            pass
                        elif tmp == -2:
                            raise KeyboardInterrupt
                        else:
                            text[select][1] = tmp
                            text = check_path(text, module)
                elif select == 4:
                    tmp = Input()
                    text[select][1] = tmp.Input(
                        lang.lang("サーバーの引数を入力(ない場合は空欄)"))

                elif select == 7:
                    if text[select][1] == "No":
                        text[select][1] = "Yes"
                    else:
                        text[select][1] = "No"
                elif select == 8:
                    if text[select][1] == "No":
                        text[select][1] = "Yes"
                    else:
                        text[select][1] = "No"
                elif select == 9:
                    tmp = yesno(lang.lang("選択"), [lang.lang("csvログを保存しますか?")])
                    if tmp == 0:
                        tmp = Input()
                        tmp = tmp.Input("filename")
                        if len(tmp.split(".")) == 1:
                            tmp += ".csv"
                        text[select][1] = tmp
                    else:
                        text[select][1] = "No"
                elif select == 11:
                    if text[select][1] == "No":
                        text[select][1] = "Yes"
                    else:
                        text[select][1] = "No"
                elif select == 12:
                    if text[select][1] == "No":
                        text[select][1] = "Yes"
                    else:
                        text[select][1] = "No"
                elif select == 14 and loopmode:
                    tmp = Input()
                    tmp = tmp.Input(lang.lang("ループ回数を指定"))
                    try:
                        text[select][1] = int(tmp)
                    except ValueError:
                        text[select][1] = 0
                    if text[select][1] == 0:
                        text[select][2] = 0
                    else:
                        text[select][2] = 1
                elif select == len(text) - 1:
                    ok = True
            s = True
            text[-1][0] = "\033[38;5;10m" + lang.lang("サッカーを実行")
            for i in text:
                if len(i) == 3:
                    if i[2] == 0:
                        s = False
                        text[-1][0] = "\033[38;5;243m" + lang.lang("サッカーを実行")
                        break

            if k == "\x1b":
                k = cuitools.Key()
                if k == "[":
                    k = cuitools.Key()
                    if k == "B":
                        if len(text) - 1 > select:
                            select += 1
                            while text[select][1] is None:
                                select += 1
                            if not s and select == len(text) - 1:
                                select -= 2
                    elif k == "A":
                        if 0 < select:
                            select -= 1
                            while text[select][1] is None:
                                select -= 1

        if ok:
            data = module.Open("./config/config.conf")
            datas = data.read().splitlines()
            data.close()
            datas = datas[0].split(",")
            arg = text[4][1]
            arg += "server::auto_mode=true server::kick_off_wait=20 server::game_over_wait=20 " \
                   "server::connect_wait=2000 server::game_log_dir=" + datas[7] + " server::text_log_dir=" + datas[
                       7] + " server::game_logging=" + (
                           "true" * (datas[3] == "on") + "false" * (datas[3] == "off")) + " server::text_logging=" + (
                           "true" * (datas[3] == "on") + "false" * (datas[3] == "off"))

            if testmode:
                arg += " server::nr_normal_halfs=1 server::nr_extra_halfs=0 server::penalty_shoot_outs=0 " \
                       "server::half_time=10"
            if loopmode:
                loop = text[14][1]
            else:
                loop = 1
            if text[12][1] == "Yes":
                s = True
            else:
                s = False
            if text[11][1] == "Yes":
                synch = True
            else:
                synch = False
            if text[9][1] == "Yes":
                tmp1 = True
            else:
                tmp1 = False
            if text[8][1] == "Yes":
                tmp2 = True
            else:
                tmp2 = False
            if text[7][1] == "Yes":
                tmp3 = True
            else:
                tmp3 = False
            soccer([text[2][1], text[1][1], arg], lang, loop, module,
                   [tmp3, tmp2, tmp1, synch], Input_, s)
예제 #8
0
    def __init__(self,
                 cmd,
                 lang,
                 loop,
                 module,
                 logs2,
                 Input,
                 s_start,
                 reset=True,
                 exit=True):
        sys.path.append(os.getcwd())
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
        if module is None:
            module = cszp_module.Open()
        if lang is None:
            if not os.path.isfile("lang"):
                file = open("language/lang.json")
                lang_list = json.load(file)
                file.close()
                langf = open("lang", "w")
                langn = [
                    k for k, n in lang_list.items()
                    if n == locale.getlocale()[0].lower() + ".lang"
                ]
                if len(langn) == 1:
                    langf.write(langn[0])
                else:
                    langf.write("1")
                langf.close()
            lang = cszp_lang.lang()
        global result
        result = ""
        self.result_list = []
        if reset:
            cuitools.reset()

        sc = "rcssserver " + cmd[2]
        wc = "soccerwindow2 > /dev/null 2>&1"
        if logs2[3]:
            sc += " server::synch_mode=true"
        print("\033[1m\033[38;5;172m" +
              datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
        print("\033[38;5;2mTeam1-CMD : " + cmd[0])
        print("Team2-CMD : " + cmd[1])
        print("\033[38;5;2mSERVER-CMD : " + sc)
        print("WINDOW-CMD : " + wc + "\033[0m")
        error = 0
        list_time = []
        if loop > 1 and s_start:
            server = threading.Thread(target=self.server)
            server.setDaemon(True)
            server.start()

        try:
            for i in range(loop):
                print("\033[38;5;4m[INFO]\033[0mLOOP:", i + 1, "/", loop)
                tmp_time = time.time()
                logs = "" + datetime.now().strftime(
                    "%Y/%m/%d %H:%M:%S") + "\n" + "SERVER-CMD : " + sc + "\n"
                logt1 = "" + datetime.now().strftime(
                    "%Y/%m/%d %H:%M:%S") + "\n"
                logt2 = "" + datetime.now().strftime(
                    "%Y/%m/%d %H:%M:%S") + "\n"
                cszp_module.killsoccer()

                data = module.Open("./config/config.conf")
                datas = data.read().splitlines()[0]
                data.close()
                datas = datas.split(",")

                if datas[1] == "on":
                    try:
                        subprocess.Popen(wc, shell=True)
                    except subprocess.CalledProcessError as e:
                        print("\033[38;5;3m[WARNING]\033[0m" +
                              "SOCCERWINDOW2_ERROR" + str(e))

                try:
                    with ThreadPoolExecutor(max_workers=10) as executor:
                        t1 = executor.submit(run_and_capture, "rcssserver", sc)
                        time.sleep(1)
                        t2 = executor.submit(run_and_capture, "team1", cmd[0])
                        time.sleep(1)
                        t3 = executor.submit(run_and_capture, "team2", cmd[1])
                    logtemp1 = t1.result()
                    logtemp2 = t2.result()
                    logtemp3 = t3.result()
                    try:
                        stderr = logtemp2[1].decode("utf-8")
                        stdout = logtemp2[0].decode("utf-8")
                    except UnicodeDecodeError as e:
                        print("\033[38;5;3m[WARNING]\033[0m\t" + str(e))
                        stderr = logtemp2[1].decode("utf-8", "replace")
                        stdout = logtemp2[0].decode("utf-8", "replace")
                    logt1 += stdout + stderr
                    logt1 += "\n"
                    print("\033[38;5;4m[INFO]\033[0mreturncode:" +
                          str(logtemp2[2].returncode))
                    if logtemp2[2].returncode != 0:
                        print("\033[38;5;9m\033[1m[ERR]\033[0m" +
                              lang.lang("コマンド実行中にエラーが発生しました。"))
                        error = 1
                        continue

                    try:
                        stderr = logtemp3[1].decode("utf-8")
                        stdout = logtemp3[0].decode("utf-8")
                    except UnicodeDecodeError as e:
                        print("\033[38;5;3m[WARNING]\033[0m\t" + str(e))
                        stderr = logtemp3[1].decode("utf-8", "replace")
                        stdout = logtemp3[0].decode("utf-8", "replace")
                    logt2 += stdout + stderr
                    logt2 += "\n"
                    print("\033[38;5;4m[INFO]\033[0mreturncode:" +
                          str(logtemp3[2].returncode))
                    if logtemp3[2].returncode != 0:
                        print("\033[38;5;9m\033[1m[ERR]\033[0m" +
                              lang.lang("コマンド実行中にエラーが発生しました。"))
                        error = 1
                        continue

                    try:
                        stderr = logtemp1[1].decode("utf-8")
                        stdout = logtemp1[0].decode("utf-8")
                    except UnicodeDecodeError as e:
                        print("\033[38;5;3m[WARNING]\033[0m\t" + str(e))
                        stderr = logtemp1[1].decode("utf-8", "replace")
                        stdout = logtemp1[0].decode("utf-8", "replace")
                    logs += stdout + stderr
                    logs += "\n"
                    print("\033[38;5;4m[INFO]\033[0mreturncode:" +
                          str(logtemp1[2].returncode))
                    if logtemp1[2].returncode != 0:
                        print("\033[38;5;9m\033[1m[ERR]\033[0m" +
                              lang.lang("コマンド実行中にエラーが発生しました。"))
                        error = 1
                        continue

                except (subprocess.CalledProcessError, FileNotFoundError) as e:
                    print(
                        "\033[38;5;9m\033[1m[ERR]\033[0m" +
                        lang.lang("コマンド実行中にエラーが発生しました。\n"), e)
                    cszp_module.killsoccer(False)
                    error = 1
                    continue
                except (EOFError, KeyboardInterrupt):
                    cszp_module.killsoccer(False)
                    error = 1
                    if not exit:
                        raise KeyboardInterrupt
                    break

                logs += datetime.now().strftime("%Y/%m/%d %H:%M:%S")
                logt1 += datetime.now().strftime("%Y/%m/%d %H:%M:%S")
                logt2 += datetime.now().strftime("%Y/%m/%d %H:%M:%S")
                exittime = datetime.now().strftime("%Y%m%d_%H%M%S")
                cszp_module.killsoccer(False)
                soccer = cszp_log.log(logs)
                result += "\n" + exittime + "," + soccer[0] + "," + soccer[1] + "," + soccer[2] + "," + soccer[
                    3] + "," + \
                          str(int(soccer[2]) - int(soccer[3])) + "," + str(int(soccer[3]) - int(soccer[2]))
                self.result_list.append([
                    exittime, soccer[0], soccer[1],
                    int(soccer[2]),
                    int(soccer[3]),
                    int(soccer[2]) - int(soccer[3]),
                    int(soccer[3]) - int(soccer[2])
                ])

                if logs2[0]:
                    data = module.Open("./config/config.conf")
                    df = data.read()
                    # print(df)
                    temp = open(
                        df.split(",")[7] + "/" + exittime + "_server.log", "w")
                    temp.write(logs)
                    temp.close()

                if logs2[1]:
                    data = module.Open("./config/config.conf")
                    df = data.read()
                    # print(df.split("'"))
                    temp = open(
                        df.split(",")[7] + "/" + exittime + "_team1.log", "w")
                    temp.write(logt1)
                    temp.close()
                    temp = open(
                        df.split(",")[7] + "/" + exittime + "_team2.log", "w")
                    temp.write(logt2)
                    temp.close()

                if logs2[2]:
                    data = module.Open("./config/config.conf")
                    df = data.read()
                    # print(df.split(",")[9] + "/" + file)
                    temp = open(df.split(",")[7] + "/" + logs2[2], "w")
                    soccer = cszp_log.log(logs)
                    temp.write("\n" + exittime + "," + soccer[0] + "," +
                               soccer[1] + "," + soccer[2] + "," + soccer[3] +
                               "," + str(int(soccer[2]) - int(soccer[3])) +
                               "," + str(int(soccer[3]) - int(soccer[2])))
                    temp.close()

                list_time.append(time.time() - tmp_time)
                print(
                    "━" * 50 + "\n\033[38;5;4m[INFO]\033[0mRun Time:",
                    totime(int(list_time[-1])), " Total",
                    totime(int(sum(list_time))), " ETA",
                    totime(
                        int((loop - len(list_time)) *
                            (sum(list_time) / len(list_time)))),
                    "\n" + "━" * 50)

            if error == 0:
                exittime = datetime.now().strftime("%Y%m%d_%H%M%S")
                subprocess.check_call("mkdir ./html_logs/" + exittime,
                                      shell=True)
                subprocess.check_call("cp ./html/index.html ./html_logs/" +
                                      exittime + "/",
                                      shell=True)
                print("\033[38;5;10m\033[1m[OK]\033[0mDone! time:" +
                      totime(int(sum(list_time))) + "\n" + "━" * 50 +
                      "\nresult")
                bs = StringIO(result)
                data = pd.DataFrame(list(csv.reader(bs))[1:],
                                    columns=('date', 'team1', 'team2',
                                             'team1_score', 'team2_score',
                                             'team1 goal difference',
                                             "team2 goal difference"))
                data = data.set_index('date')
                # print(data)
                csvd = result.splitlines()[1:]
                csvtd = []
                for i in csvd:
                    csvtd.append(i.split(","))
                csvd = ""
                for i in csvtd:
                    for j in range(len(i)):
                        if j != 0:
                            if j != len(i) - 1:
                                csvd += i[j] + ","
                            else:
                                csvd += i[j] + "\n"
                with open("./html_logs/" + exittime + "/" + "html.csv",
                          "w") as f:
                    f.write("プレイヤー1,プレイヤー2," + data["team1"][0] + "の得点," +
                            data["team2"][0] + "の得点," + data["team1"][0] +
                            "の得失点差," + data["team2"][0] + "の得失点差\n" + csvd)
                data["team1_score"] = data["team1_score"].astype(int)
                data["team2_score"] = data["team2_score"].astype(int)
                print(data)
                print("━" * 50)
                heikin = data.mean()
                x = np.array(
                    range(
                        max(max(data["team1_score"]), max(data["team2_score"]))
                        + 1))
                y = np.array(
                    [0] *
                    (max(max(data["team1_score"]), max(data["team2_score"])) +
                     1))

                for i in data["team1_score"]:
                    y[i] += 1
                plt.bar(x - 0.15,
                        y,
                        color="y",
                        width=0.3,
                        label=data["team1"].values[0] + "\nAverage:" +
                        str(np.round(heikin["team1_score"], decimals=2)))

                x = np.array(
                    range(
                        max(max(data["team1_score"]), max(data["team2_score"]))
                        + 1))
                y = np.array(
                    [0] *
                    (max(max(data["team1_score"]), max(data["team2_score"])) +
                     1))
                for i in data["team2_score"]:
                    y[i] += 1
                plt.bar(x + 0.15,
                        y,
                        color="r",
                        width=0.3,
                        label=data["team2"].values[0] + "\nAverage:" +
                        str(np.round(heikin["team2_score"], decimals=2)))
                plt.ylabel("number of times")
                plt.xlabel("point")
                plt.legend(loc='best')
                plt.grid(True)
                plt.savefig("./html_logs/" + exittime + "/" + "file1.png",
                            dpi=300)
                plt.clf()

        finally:
            try:
                self.httpd.shutdown()
            except AttributeError:
                pass
            if exit:
                if Input is None:
                    input(lang.lang("Enterキーを押して続行..."))
                else:
                    Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
예제 #9
0
def setting(lang, module, Input):
    subp.reset()
    inp = ""
    while not lang.searchcmd("setting", inp):
        subprocess.check_call("clear", shell=True)
        print("\033[0m\033[38;5;172m")
        v = open("./version")
        figlet("cszp " + v.read())
        v.close()
        print("\n\n\033[1m\033[38;5;10m" + lang.lang("cszp 簡単サッカー実行プログラム"))
        print("\n\033[38;5;39m" + lang.lang("簡単サッカー実行リスト"))
        # noinspection PyBroadException
        data = module.Open("./config/setting.conf")
        draw_table(data)

        print("\033[38;5;39m" + lang.lang("設定"))
        # noinspection PyBroadException
        data = module.Open("./config/config.conf")
        draw_table(data)

        q = lang.question("setting", "※  注 [文字列] は引数を表します。 文字列は引数名です。")
        inp = Input.Input(q[0], dot=False, normal=False, word=q[1])
        if not lang.searchcmd("setting", inp):
            print("\033[38;5;9m" + lang.lang("ERR:そのようなコマンドはありません。"))
            Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)

    try:
        if inp == "back":
            pass

        elif inp.split(' ')[0] == "add":
            data = open("./config/setting.conf", "a")
            data.write("," + inp.split(' ')[1] + "," + inp.split(' ')[2])
            data.close()
            setting(lang, module, Input)

        elif inp.split(' ')[0] == "remove":
            data = module.Open("./config/setting.conf")
            datas = data.read()
            datas = datas.split(",")
            data.close()
            i = 0
            try:
                try:
                    while datas[i] != inp.split(" ")[1]:
                        i += 2
                except IndexError:
                    raise TypeError("data_ERROR")
                if datas[i + 1] in module.hogo:
                    raise AttributeError("protected")
                del datas[i:i + 2]
                datat = datas
                datas = ""
                for i in datat:
                    datas += i + ","
                datas = datas[:len(datas) - 1]
                data = open("./config/setting.conf", "w")
                data.write(datas)
                data.close()
            except TypeError:
                print("\033[38;5;9m" + lang.lang("ERR:名前"),
                      inp.split(" ")[1],
                      lang.lang("は簡単サッカー実行リストに登録されていません。\nタイプミスを確認してください"))
                Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
            except AttributeError:
                print("\033[38;5;9m" +
                      lang.lang("ERR:削除しようとしているリストの項目は保護されています。"))
                Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
            setting(lang, module, Input)

        elif inp.split(' ')[0] == "soccerwindow2":
            data = module.Open("./config/config.conf")
            datas = data.read()
            datas = datas.split(",")
            data.close()
            if inp.split(' ')[1].lower() == "on":
                datas[1] = "on"
            elif inp.split(' ')[1].lower() == "off":
                datas[1] = "off"
            else:
                print("\033[38;5;9m" +
                      lang.lang("ERR:使える引数はONまたはOFFです。\nタイプミスを確認してください"))
                Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
            write_conf(datas)
            setting(lang, module, Input)

        elif inp.split(' ')[0] == "rcg":
            data = module.Open("./config/config.conf")
            datas = data.read()
            datas = datas.split(",")
            data.close()
            if inp.split(' ')[1].lower() == "on":
                datas[3] = "on"
            elif inp.split(' ')[1].lower() == "off":
                datas[3] = "off"
            else:
                print("\033[38;5;9mERR:使える引数はONまたはOFFです。\nタイプミスを確認してください")
                Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
            write_conf(datas)
            setting(lang, module, Input)

        elif inp.split(' ')[0] == "rcl":
            data = module.Open("./config/config.conf")
            datas = data.read()
            datas = datas.split(",")
            data.close()
            if inp.split(' ')[1].lower() == "on":
                datas[5] = "on"
            elif inp.split(' ')[1].lower() == "off":
                datas[5] = "off"
            else:
                print("\033[38;5;9mERR:使える引数はONまたはOFFです。\nタイプミスを確認してください")
                Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
            write_conf(datas)
            setting(lang, module, Input)

        elif inp.split(' ')[0] == "fileout":
            data = module.Open("./config/config.conf")
            datas = data.read()
            datas = datas.split(",")
            data.close()
            datas[7] = inp.split(" ")[1]
            write_conf(datas)
            setting(lang, module, Input)
        else:
            sys.path.append(lang.functo("setting", inp)[0][0])
            plugin = import_module(lang.functo("setting", inp)[1][0])
            reload(plugin)
            try:
                plugin.plugin(lang, inp)
            except Exception:
                error_dump(lang, "PLUGIN ERROR")
            setting(lang, module, Input)
    except IndexError:
        print("\033[38;5;9m" + lang.lang("ERR:引数がありません。タイプミスを確認してください"))
        Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
        setting(lang, module, Input)
예제 #10
0
def menu(lang, module, Input):
    logger = logging.getLogger("menu")
    cszp_module.killsoccer()
    inp = ""
    subp.reset()
    while not lang.searchcmd("menu", inp):
        subprocess.check_call("clear", shell=True)
        print("\033[0m\033[38;5;172m")
        v = open("./version")
        cszp_module.figlet("cszp " + v.read())
        v.close()
        print("\n")
        q = lang.question("menu")
        inp = Input.Input(q[0], dot=False, normal=False, word=q[1])
        if not lang.searchcmd("menu", inp):
            logger.warning(lang.lang("ERR:そのようなコマンドはありません。"))
            print("\033[38;5;9m" + lang.lang("ERR:そのようなコマンドはありません。"))
            Input.Input(lang.lang("Enterキーを押して続行..."), dot=False)
    if inp == "exit":
        pass
    elif inp == "colortest":
        logger.info("select colortest")
        colortest.colortest()
        logger.info("printed colortest")
        Input.Input(lang.lang("Enterキーを押して続行..."))
        menu(lang, module, Input)
    elif inp == "setting":
        logger.info("select setting")
        cszp_setting.setting(lang, module, Input)
        logger.info("exited setting")
        menu(lang, module, Input)
    elif inp == "reset":
        logger.info("select reset")
        os.remove("./config/*")
        shutil.rmtree("plugins")
        shutil.rmtree("teams")
        logger.info("reseted")
        Input.Input(lang.lang("\n\nリセットが完了しました。\nEnterキーを押して続行..."),
                    dot=False,
                    textcolor="#fdb100")
        logger.info("exited reset")
        menu(lang, module, Input)
    elif inp == "test":
        logger.info("select test")
        cszp_soccer.setting(lang, testmode=True, module=module, Input_=Input)
        logger.info("exited test")
        menu(lang, module, Input)
    elif inp == "start":
        logger.info("select start")
        cszp_soccer.setting(lang, module=module, Input_=Input)
        logger.info("exited start")
        menu(lang, module, Input)
    elif inp == "rrt":
        logger.info("select rrt")
        cszp_soccer.rrt(lang, module=module, Input_=Input)
        logger.info("exited rrt")
        menu(lang, module, Input)
    elif inp == "lang":
        terminal_size = shutil.get_terminal_size()
        printtext = ["Select Language"]
        select = 0
        logger.info("select lang")
        logger.info("list " + str(lang.lang_list))
        logger.info("length " + str(len(lang.lang_list)))
        logger.info("enable lang name " + lang.enable_lang_name)
        for i in range(len(lang.lang_list)):
            if lang.lang_list[str(i)] == lang.enable_lang:
                select = i
                printtext.append(">> " + os.path.splitext(
                    os.path.basename(lang.lang_list[str(i)]))[0])
            else:
                printtext.append("   " + os.path.splitext(
                    os.path.basename(lang.lang_list[str(i)]))[0])
        printtext.append("")
        k = ""
        while k != "\n":
            lentext = max(map(len, printtext))
            for i in range(len(printtext)):
                if i == 0:
                    print("\033[" + str(int(terminal_size[1] / 2 + i)) + ";" +
                          str(int(terminal_size[0] / 2 - lentext / 2)) + "H┏" +
                          printtext[i].center(lentext, '━') + "┓")
                elif i == len(printtext) - 1:
                    print("\033[" + str(int(terminal_size[1] / 2 + i)) + ";" +
                          str(int(terminal_size[0] / 2 - lentext / 2)) + "H┗" +
                          printtext[i].center(lentext, '━') + "┛")
                else:
                    print("\033[" + str(int(terminal_size[1] / 2 + i)) + ";" +
                          str(int(terminal_size[0] / 2 - lentext / 2)) + "H┃" +
                          printtext[i].center(lentext, ' ') + "┃")
            k = subp.Key()
            if k == "\x1b":
                subp.Key()
                k = subp.Key()
                if k == "B":
                    if select < len(lang.lang_list) - 1:
                        select += 1
                elif k == "A":
                    if select > 0:
                        select -= 1

            printtext = ["Select Language"]
            for i in range(len(lang.lang_list)):
                if i == select:
                    printtext.append(">> " + os.path.splitext(
                        os.path.basename(lang.lang_list[str(i)]))[0])
                else:
                    printtext.append("   " + os.path.splitext(
                        os.path.basename(lang.lang_list[str(i)]))[0])
            printtext.append("")

        langf = open("lang", "w")
        langf.write(str(select))
        langf.close()
        lang = cszp_module.terminal(noenter=True)
        logger.info("reloaded")
        logger.info("select lang name " + lang.enable_lang_name)
        lang.autostart(lang)
        logger.info("autostart executed")
        logger.info("exited lang")
        menu(lang, module, Input)
    elif inp == "loop":
        logger.info("select loop")
        cszp_soccer.setting(lang, loopmode=True, module=module, Input_=Input)
        logger.info("exited loop")
        menu(lang, module, Input)
    elif inp == "server":
        logger.info("select server")
        print(lang.lang("Ctrl+Cで閲覧を終了します。"))
        try:
            logger.info("call",
                        "cd html_logs/ && python3 -m http.server 20000")
            subprocess.check_call(
                "cd html_logs/ && python3 -m http.server 20000", shell=True)
        except KeyboardInterrupt:
            pass
        except subprocess.CalledProcessError as e:
            logger.warning(e)
            Input(lang.lang("Enterキーを押して続行..."))
        logger.info("exited server")
        menu(lang, module, Input)
    elif inp == "plugin":
        logger.info("select plugin")
        tmp = cszp_plugin.plugin(module, lang)
        logger.info("exited plugin")
        if tmp is not None:
            menu(tmp, module, Input)
        else:
            menu(lang, module, Input)
    elif inp == "about":
        logger.info("select about")
        print("\033[0m")
        v = open("./version")
        vd = v.read().splitlines()[0]
        v.close()
        printtext = [
            "CSZP VER " + vd, "VERSION:" + vd, "",
            sys.version.splitlines()[0],
            sys.version.splitlines()[1], "Install Location:" + os.getcwd(), "",
            "SYSTEM:" + platform.system() + " " + platform.machine(),
            "PLATFORM:" + platform.platform(), "PC-NAME:" + platform.node(),
            "PYTHON-IMPLEMENTATION:" + platform.python_implementation()
        ]
        subp.printlist("about cszp", printtext)
        logger.info("exited about")
        menu(lang, module, Input)
    elif inp == "window":
        logger.info("select window")
        try:
            logger.info("call soccerwindow2")
            subprocess.check_call("soccerwindow2")
        except KeyboardInterrupt:
            pass
        except subprocess.CalledProcessError as e:
            logger.warning(e)
            Input(lang.lang("Enterキーを押して続行..."))
        logger.info("exited window")
        menu(lang, module, Input)
    else:
        logger.info("select other")
        sys.path.append(lang.functo("menu", inp)[0][0])
        plugin = import_module(lang.functo("menu", inp)[1][0])
        reload(plugin)
        logger.info("reload plugin module")
        try:
            logger.info("start plugin mode")
            plugin.plugin(lang, inp)
            logger.info("exited plugin mode")
        except Exception:
            error_dump(lang, "PLUGIN ERROR")
        logger.info("exited other")
        menu(lang, module, Input)
예제 #11
0
def main():
    logger = logging.getLogger("main")
    print("\033[38;5;2mloading Now...")
    logger.info("loading Now...")
    print("1/7")
    logger.debug("set python path:" + os.getcwd())
    import json
    logger.debug("imported json module")
    print("\033[1A2/7")
    import locale
    logger.debug("imported locale module")
    print("\033[1A3/7")
    import platform
    logger.debug("imported platform module")
    print("\033[1A4/7")
    from cszp.cszp_module import Open, terminal, figlet, error_dump, Input
    logger.debug(
        "imported Open, terminal, figlet, error_dump, Input at cszp.cszp_module"
    )
    print("\033[1A5/7")
    from cszp import cszp_menu
    logger.debug("imported cszp_menu at cszp")
    print("\033[1A6/7")
    import cuitools as subp
    logger.debug("imported cuitools module")
    print("\033[1A7/7")
    subp.reset()
    logger.debug("imported subp module")
    print("\033[1;1H\033[0m\033[38;5;172m")
    logger.info("cszp version " + open("./version").read())
    ver = open("./version")
    figlet("cszp " + ver.read())
    # noinspection PyBroadException
    print("")
    logger.info("python ver:" + platform.python_version())
    logger.info("PYTHON-IMPLEMENTATION:" + platform.python_implementation())
    logger.info("PLATFORM:" + platform.platform())
    logger.info("SYSTEM:" + platform.system() + " " + platform.machine())
    if int(sys.version_info[0]) == 3 and int(sys.version_info[1]) >= 6 and int(
            sys.version_info[2]) >= 1:
        sys.stdout.write("\033[38;5;10m\033[1m[OK] ")
        print("\033[0m\033[38;5;2mpythonVersion\033[38;5;7m:\033[38;5;6m" +
              platform.python_version())
    else:
        print("\033[0m\033[38;5;2mpythonVersion\033[38;5;7m:\033[38;5;6m" +
              platform.python_version())
        print(
            "\033[38;5;9m\033[1m[ERR] \033[0mThis program requires python3.6.1 or higher version."
        )
        logger.error("This program requires python3.6.1 or higher version.")
        logger.critical("cszp exited.")
        sys.exit()

    if not os.path.isdir("config"):
        print("\033[38;5;4m[INFO]\033[0mCreate directory: config")
        logger.info("Create directory: config")
        os.mkdir("config")
    if not os.path.isfile("config/hogo.json"):
        print("\033[38;5;4m[INFO]\033[0mCreate file: config/hogo.json")
        logger.info("Create file: config/hogo.json")
        tmp = open("config/hogo.json", "w")
        tmp.write("[]")
        tmp.close()
    if not os.path.isfile("config/plus.txt"):
        print("\033[38;5;4m[INFO]\033[0mCreate file: config/plus.txt")
        logger.info("Create file: config/plus.txt")
        open("config/plus.txt", "w").close()
    module = Open()
    if not os.path.isdir("html_logs"):
        print("\033[38;5;4m[INFO]\033[0mCreate directory: html_logs")
        logger.info("Create directory: html_logs")
        os.mkdir("html_logs")
    data = module.Open("./config/config.conf")
    path = data.read().splitlines()[0].split(",")[7]
    data.close()
    if not os.path.isdir(path):
        print("\033[38;5;4m[INFO]\033[0mCreate directory: csvdata")
        logger.info("Create directory: csvdata")
        os.mkdir(path)
    if not os.path.isdir("plugins"):
        print("\033[38;5;4m[INFO]\033[0mCreate directory: plugins")
        logger.info("Create directory: plugins")
        os.mkdir("plugins")
    if not os.path.isdir("teams"):
        print("\033[38;5;4m[INFO]\033[0mCreate directory: teams")
        logger.info("Create directory: teams")
        os.mkdir("teams")

    # main

    if not os.path.isfile("lang"):
        file = open("language/lang.json")
        lang_list = json.load(file)
        file.close()
        langf = open("lang", "w")
        langn = [
            k for k, n in lang_list.items()
            if n == locale.getlocale()[0].lower() + ".lang"
        ]
        if len(langn) == 1:
            logger.info("setlang:", langn[0])
            langf.write(langn[0])
        else:
            logger.info("setlang:1")
            langf.write("1")
        langf.close()
    lang = terminal()
    logger.info("inited")
    lang.autostart(lang)
    logger.info("autostart executed")
    Input = Input()
    try:
        logger.info("start menu")
        cszp_menu.menu(lang, module, Input)
    except KeyboardInterrupt:
        pass
    except EOFError:
        pass
    except Exception:
        error_dump(lang, "CSZP PROGRAM ERROR", True)

    #  stop
    subp.reset()
    logger.info("cszp exited.")
    print("\033[38;5;10mgood bye!")