예제 #1
0
def main_online(host=''):
    try:
        if not host:
            if bool(persist_data.DATA["debug"]["RANDOMIZE_UUID"]):
                persist_data.DATA["online"]["uuid"] = str(uuid.uuid4())
            host = input(
                f"Please enter the IP of the server (leave empty for [{persist_data.DATA['online']['last_ip']}]) : "
            )
            if not host:
                host = persist_data.DATA['online']['last_ip']
            persist_data.update_key("last_ip", host, "online")
        socket_client.main(host)
        while socket_client.human_to_bool("Do you want to play again ?\n"):
            socket_client.main(host)
        exit()
    except KeyboardInterrupt:
        print("Exiting ...")
        exit(0)
    except Exception as e:
        print("Something went wrong :", e)
        exit(-1)
예제 #2
0
def _join_game(
        wb,
        ip="localhost"):  # Initiate the connexion between client and server
    player_id = _send_data("join%" + persist_data.DATA["online"]["name"], ip)
    if player_id == b"started":
        wb.clear()
        wb.update("The game you tried to join already started",
                  status=red("Connection failed"))
        wb.update("Press [ENTER] to try again")
        wait(1)  # Avoid spam
        input()
        return _join_game(wb, ip)
    elif player_id == b"wait%":
        wb.update("Waiting for admin to restart the game ...",
                  status=yellow("Waiting ..."))
        while player_id == b"wait%":
            wait(persist_data.DATA["online"]["update_speed"])
            player_id = _send_data(
                "join%" + persist_data.DATA["online"]["name"], ip)
        return int(player_id)
    elif player_id == b"":
        wb.update("Error while joining, try again later",
                  status=red("Unknown error"))
    elif player_id == b"outdated%":
        wb.update(
            "Your client is outdated, please download the latest version",
            status=red("Client outdated"))
        import webbrowser
        webbrowser.open(persist_data.DATA["update_url"])
        exit_server()
    elif player_id == b"outdated%update":
        wb.update(f"You are about to receive an update from {ip}.",
                  status=red("Client outdated"))
        if human_to_bool("Do you trust this server ?\n"):
            import lelonmo.updater as updater
            updater.auto_update(ip, wb)
        else:
            wb.update("Aborted update, you cannot play on this server. ")
        exit_server()

    else:
        try:
            int(player_id)
        except:
            wb.update("Error while joining, try again later",
                      status=red("Unknown error"))
            exit()
        if int(player_id) >= 0:
            return int(player_id)
        else:
            name = ""
            while not int(player_id) >= 0:
                wb.clear()
                wb.update({
                    -1: "Please enter a username",
                    -2: "Username cannot be a space",
                    -3: "Username contains forbiden words or characters",
                    -4: "This username is already taken"
                }[int(player_id)],
                          status=red("Invalid username"))
                name = input("Please enter your username : "******"join%" + name, ip))
                except ValueError:
                    wb.update("Error while joining, try again later",
                              status=red("Unknown error"))
                    exit()
            persist_data.update_key('name', name, "online")
            return int(player_id)
예제 #3
0
def main(host="localhost"):
    global server_ip
    server_ip = host
    menu_format = MenuFormatBuilder() \
        .set_border_style_type(MenuBorderStyleType.DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER) \
        .set_prompt("") \
        .set_title_align('center') \
        .set_subtitle_align('center') \
        .set_left_margin(4) \
        .set_right_margin(4) \
        .show_header_bottom_border(True) \
        .set_prologue_text_align('left')

    wb = WhiteBoard(menu_format)

    # Set the name if not set already (or if it has been reset)
    if not persist_data.DATA["online"]["name"]:
        name = ""
        while (not name) or ("%" in name):
            name = input("Please enter your username : "******"Username updated, go to Settings > Online Settings to change it")
    else:
        wb.add("You are logged in as", persist_data.DATA["online"]["name"])

    wb.add(f"Joining the game hosted at {host}")
    player_id = _join_game(wb, host)
    wb.add("Joined successfully")
    admin = False
    if player_id == 0:  # Player id =
        wb.add("You are the administrator, press [ENTER] to start the game")
        admin = True
    playerboard = PlayerUpdate(wb, host)
    playerboard.start()
    if admin:
        input()
        if _send_data("start%", host) == "ok%":
            wb.add("Game started successfully")
        else:
            wb.add("Unauthorized")
            if not persist_data.DATA["online"]["name"] in playerboard.players:
                playerboard.enable = False
                del admin
                del wb
                del player_id
                from lelonmo.main_online import main_online
                main_online(host)

    _wait_for_status("start", host)

    wb.clear()
    wb.add("Game started\n",
           "You have to compose your word with these letters\n",
           " ".join(_status(host)[5:]))

    playerboard.enable = False
    playerboard.invert = True
    playerboard.run(True)  # Show the players once after update then stop
    while not _send_data(input("Enter your word : "),
                         host).decode("utf-8").startswith("valid%"):
        print("Invalid, try again")
    wb.clear()
    wb.add("Waiting for other players to finish")
    playerboard = PlayerUpdate(wb, host)
    playerboard.start()
    _wait_for_status("results", host)
    playerboard.enable = False
    wb.updatable = ""

    result_data = json.loads(_status(host)[7:])
    wb.clear()
    wb.add("Results : \n Winner(s):\n * " +
           "\n  * ".join([i[0] + " : " + i[1] for i in result_data["best"]]) +
           "\n\n Scores :\n * " + "\n  * ".join(
               [i["name"] + " : " + i["word"]
                for i in result_data["players"]]))
예제 #4
0
                pass
        exit()
else:
    print("Starting the game, please wait ...")
    print("Checking dependancies ... ")
    try:
        import six
    except:
        print("six is not installed, trying to install it automatically ...")
        import subprocess
        import sys
        command = [sys.executable, "-m", "pip", "install", "six", "--user"]
        subprocess.run(command)
    import lelonmo.persist_data as persist
    if os_name == "Windows" and persist.DATA["game"]['FIRST_RUN']:
        persist.update_key("async_input", True, "online")
        if platform.version().startswith("10."):
            persist.update_key("FIRST_RUN", False, "game")
        elif persist.DATA["game"]['FIRST_RUN']:
            persist.update_key("FIRST_RUN", False, "game")
            input(
                "Colors are not supported on this version of windows, and are disabled by default. ")
            persist.update_key("USE_COLORS", False, "settings")
    elif os_name == "Darwin":
        try:
            import Quartz
            import objc
        except:
            print("Quartz and objc are not installed, trying to install it automatically ...")
            import subprocess
            import sys
예제 #5
0
파일: main.py 프로젝트: Roboffox/LeLonMo
        try:
            u = input()
        except:
            u = "exit"
        if u == "exit":
            try:
                main_thread.tcpsock.close()
            except OSError:
                pass
        exit()
else:
    print("Starting the game, please wait ...")
    if os_name == "Windows":
        import lelonmo.persist_data as persist
        if platform.version().startswith("10."):
            persist.update_key("FIRST_RUN", False, "game")
        elif persist.DATA["game"]['FIRST_RUN']:
            persist.update_key("FIRST_RUN", False, "game")
            input(
                "Colors are not supported on this version of windows, and are disabled by default. "
            )
            persist.update_key("USE_COLORS", False, "settings")
        import lelonmo.menu as menu
        menu.main()
    else:
        import lelonmo.menu as menu
        input(
            "This platform is not officially supported press [ENTER] to continue"
        )
        menu.main()