def spend_resource(database):
    faction_name = iq.select(
        message="Faction name:",
        choices=factionCrud.get_faction_names(database)).execute()
    resource = iq.select(message="Resource type:",
                         choices=resource_types).execute()
    amount = int(iq.text("Amount spent:").execute())

    factionCrud.spend_resource(database, faction_name, resource, amount)
def update_resource(database):
    faction_name = iq.select(
        message="Faction name:",
        choices=factionCrud.get_faction_names(database)).execute()
    resource = iq.select(message="Resource type:",
                         choices=resource_types).execute()
    new_total = int(iq.text("New total:").execute())

    factionCrud.set_resource(database, faction_name, resource, new_total)
Exemple #3
0
    def config_set(name, option):
        if type(option) is str:
            choice = inquirer.text(
                message=
                f"{Localizer.get_localized_text('prints','config_modification','set_prompt')} {name} (expecting str)",
                default=str(option),
                validate=lambda result: not result.isdigit(),
                filter=lambda result: str(result))
            choice = choice.execute()
            return choice

        if type(option) is int:
            choice = inquirer.text(
                message=
                f"{Localizer.get_localized_text('prints','config_modification','set_prompt')} {name} (expecting int)",
                default=str(option),
                validate=lambda result: result.isdigit(),
                filter=lambda result: int(result))
            choice = choice.execute()
            return choice

        if type(option) is bool:
            choice = inquirer.select(
                message=
                f"{Localizer.get_localized_text('prints','config_modification','set_prompt')} {name}",
                default=option,
                choices=[{
                    "name": "true",
                    "value": True
                }, {
                    "name": "false",
                    "value": False
                }],
                pointer=">")
            choice = choice.execute()
            return choice

        if type(option) is list:
            current = option[0]
            options = option[1]
            choice = inquirer.select(
                message=
                f"{Localizer.get_localized_text('prints','config_modification','set_prompt')} {name}",
                default=current,
                choices={option: option
                         for option in options},
                pointer=">")
            choice = choice.execute()
            option[0] = choice
            return option
def update_research(database):
    faction_name = iq.select(
        message="Faction name:",
        choices=factionCrud.get_faction_names(database)).execute()
    module_name = iq.select(message="Module name:",
                            choices=module_types).execute()
    tech_level = int(
        iq.text(
            message="Tech level:",
            validate=lambda level: 0 < int(level) < 10,
            invalid_message="Research has a maximum of 10.",
        ).execute())

    factionCrud.set_research(database, faction_name, module_name, tech_level)
Exemple #5
0
def choose_managed_user(account: MyPlexAccount):
    users = [u.title for u in account.users()]
    if not users:
        return None

    click.echo(success("Managed user(s) found:"))
    users = sorted(users)
    users.insert(0, account.username)
    user = inquirer.select(
        message="Select the user you would like to use:",
        choices=users,
        default=None,
        style=style,
        qmark="",
        pointer=">",
    ).execute()

    if user == account.username:
        return None

    # Sanity check, even the user can't input invalid user
    user_account = account.user(user)
    if user_account:
        return user

    return None
Exemple #6
0
def prompt_server(servers: List[MyPlexResource]):
    old_age = datetime.now() - timedelta(weeks=1)

    def fmt_server(s):
        if s.lastSeenAt < old_age:
            decorator = disabled
        else:
            decorator = comment

        product = decorator(f"{s.product}/{s.productVersion}")
        platform = decorator(f"{s.device}: {s.platform}/{s.platformVersion}")
        click.echo(f"- {highlight(s.name)}: [Last seen: {decorator(str(s.lastSeenAt))}, Server: {product} on {platform}]")
        c: ResourceConnection
        for c in s.connections:
            click.echo(f"    {c.uri}")

    owned_servers = [s for s in servers if s.owned]
    unowned_servers = [s for s in servers if not s.owned]
    sorter = partial(sorted, key=lambda s: s.lastSeenAt)

    server_names = []
    if owned_servers:
        click.echo(success(f"{len(owned_servers)} owned servers found:"))
        for s in sorter(owned_servers):
            fmt_server(s)
            server_names.append(s.name)
    if unowned_servers:
        click.echo(success(f"{len(unowned_servers)} unowned servers found:"))
        for s in sorter(unowned_servers):
            fmt_server(s)
            server_names.append(s.name)

    return inquirer.select(message="Select default server:", choices=sorted(server_names), default=None, style=style, qmark="", pointer=">",).execute()
    def run(self, context: typings.Context, args: list):
        player_model = context["models"]["Player"]
        player_view = context["views"]["player"]

        player_count = self.pop_arg(args)
        if player_count and player_count.isdigit():
            total_created = self.create_multiples(player_count, player_model)
            return player_view.render_multiples(total_created,
                                                title="Created Players")

        questions = {
            "first_name":
            text(
                message="Enter the first name of the player:",
                validate=validators.TextValidator(),
                default=f'{self._generate_fake("first_name")}',
            ),
            "last_name":
            text(
                message="Enter the last name of the player:",
                validate=validators.TextValidator(),
                default=f'{self._generate_fake("last_name")}',
            ),
            "birthday":
            text(
                message="Enter the birthday of the player:",
                validate=validators.DateValidator(),
                default=f'{self._generate_fake("birthday")}',
            ),
            "sexe":
            select(
                message="Enter the sexe of the player:",
                choices=["Male", "Female"],
                default=f'{self._generate_fake("sexe")}',
            ),
            "rank":
            text(
                message="Enter the rank of the player:",
                validate=validators.DigitValidator(),
                default=f'{self._generate_fake("rank")}',
            ),
        }

        result = {}

        for key, value in questions.items():
            sanitize_value = type(getattr(player_model(), key))
            try:
                result[key] = sanitize_value(value.execute())
            except KeyboardInterrupt:
                raise errors.GenericError("Canceld the creation of the player",
                                          title="Note")

        new_player = player_model(**result)
        new_player = new_player.save()

        player_view.render_single(new_player, title="Created Player")
Exemple #8
0
    def config_menu(self, section, choices, callback=None, callback_args=None):
        # recursion makes me want to die but its for a good cause

        prompt_choices = [{
            "name":
            f"{setting}" +
            (f" ({value[0]})" if isinstance(value, list) else
             f" ({value})" if not isinstance(value, dict) else " (>>)"),
            "value":
            setting
        } for setting, value in choices.items()]
        prompt_choices.insert(0, {
            "name": "back" if section != "main" else "done",
            "value": "back"
        })

        choice = inquirer.select(
            message=
            f"[{section}] {Localizer.get_localized_text('prints','config_modification','select_option')}",
            choices=prompt_choices,
            pointer=">")
        choice = choice.execute()

        if choice == "back":
            if section != "main":
                callback(*callback_args)
            elif callback is None:
                Config.modify_config(self.config)
                color_print([
                    ("LimeGreen",
                     Localizer.get_localized_text("prints",
                                                  "config_modification",
                                                  "config_saved"))
                ])
                return
        else:
            if isinstance(choices[choice], dict):
                self.config_menu(choice,
                                 choices[choice],
                                 callback=self.config_menu,
                                 callback_args=(section, choices, callback,
                                                callback_args))
            else:
                if choice == Localizer.get_config_key("locale"):
                    #translate config
                    old_locale = choices[choice]
                    new_locale = self.config_set(choice, choices[choice])[0]
                    self.config = Config.localize_config(self.config, True)
                    self.config["locale"][0] = new_locale
                    Localizer.locale = new_locale
                    self.config = Config.localize_config(self.config, False)
                    Localizer.config = self.config
                else:
                    choices[choice] = self.config_set(choice, choices[choice])

                self.config_menu(section, choices, callback, callback_args)
Exemple #9
0
def getDeviceName() -> str:
	return inquirer.select(
		message='Select your device',
		choices=[
			Choice('respeaker2', name='Respeaker 2'),
			Choice('respeaker4', name='Respeaker 4-mic array'),
			Choice('respeaker4MicLinearArray', name='Respeaker 4 mic linear array'),
			Choice('respeaker6MicArray', name='Respeaker 6 mic array')
		]
	).execute()
Exemple #10
0
def move_ship(database):
    origin_location = promptUtils.planet_prompt(database, "From:")

    ships_on_origin = shipCrud.get_ships_on_planet(database, origin_location)
    ship_ids_on_origin = list(map(lambda ship: f"{ship.id}, modules: {ship.modules}, owner: {ship.owner}", ships_on_origin))

    ship_selection = iq.select(
        message="Ship:",
        choices=ship_ids_on_origin
    ).execute()

    ship_id = ship_selection.split(',')[0]

    origin_connections = planetCrud.get_connection_names(database, origin_location)

    destination = iq.select(
        message="Destination:",
        choices=origin_connections
    ).execute()

    shipCrud.move_ship(database, ship_id, destination)
Exemple #11
0
 def prompt_locale(config):
     locale = config["locale"]
     current = locale[0]
     options = locale[1]
     choice = inquirer.select(
         message=f"select your locale (language)",
         default=current,
         choices={option: option
                  for option in options},
         pointer=">")
     choice = choice.execute()
     locale[0] = choice
     return config
def create_facility(database):

    planet_name = promptUtils.planet_prompt(database)
    facility_type = iq.select(message="Facility type:",
                              choices=all_facility_types).execute()
    is_blockaded = iq.confirm("Blockaded?").execute()

    facility = {'planet': planet_name, 'facility_type': facility_type}

    facilityCrud.create_facility_from_dict(database, facility)

    if not is_blockaded:
        planetCrud.restore_garrison_points(database, planet_name)
        facilityCrud.restore_planet_facilities(database, planet_name)
def discover(ctx: click.Context, network: str, all_devices: bool, return_to_main_menu: bool = True):  # NOSONAR
	click.clear()
	click.secho('Discovering devices on your network, please wait', fg='yellow')

	ip = IP_REGEX.search(socket.gethostbyname(socket.gethostname()))
	if not ip and not network:
		printError("Couldn't retrieve local ip address")
	else:
		if not network:
			network = f"{'.'.join(ip[0].split('.')[0:3])}.0/24"

		click.secho(f'Scanning network: {network}', fg='yellow')
		waitAnimation()
		scan = networkscan.Networkscan(network)
		scan.run()

		if all_devices:
			click.secho('Discovered devices:', fg='yellow')
		else:
			click.secho('Discovered potential devices:', fg='yellow')

		devices = list()
		for device in scan.list_of_hosts_found:
			try:
				name = socket.gethostbyaddr(device)
				if not name:
					continue

				if all_devices or (not all_devices and ('projectalice' in name[0].lower() or 'raspberrypi' in name[0].lower())):
					click.secho(f'{device}: {name[0].replace(".home", "")}', fg='yellow')
					devices.append(device)
			except:
				continue  # If no name, we don't need the device anyway

		stopAnimation()

		devices.append('Return to main menu')  # NOSONAR
		device = inquirer.select(
			message='Select the device you want to connect to',
			choices=devices
		).execute()

		if device == 'Return to main menu':
			returnToMainMenu(ctx)
		else:
			ctx.invoke(connect, ip_address=device, return_to_main_menu=return_to_main_menu)

	if return_to_main_menu:
		returnToMainMenu(ctx)
Exemple #14
0
def main():
    action = inquirer.select(
        message="Select an action:",
        choices=[
            "Upload",
            "Download",
            Choice(value=None, name="Exit"),
        ],
        default=None,
    ).execute()
    if action:
        region = inquirer.select(
            message="Select regions:",
            choices=[
                Choice("ap-southeast-2", name="Sydney"),
                Choice("ap-southeast-1", name="Singapore"),
                Separator(),
                "us-east-1",
                "us-east-2",
            ],
            multiselect=True,
            transformer=lambda result:
            f"{len(result)} region{'s' if len(result) > 1 else ''} selected",
        ).execute()
Exemple #15
0
def choose_modules(database, ship_size, faction_name):
    faction_research = factionCrud.get_research(database, faction_name)
    modules_array = []

    for i in range(ship_size):
        module_type = iq.select(
            message="Module type:",
            choices=module_options
        ).execute()

        module_abbreviation = module_abbreviations.get(module_type)
        module_level = str(faction_research.get(module_type))
        modules_array.append(module_abbreviation + module_level)

    return ''.join(modules_array)
def load_save_or_new_game():
    _dungeon = None
    inner_command = inquirer.select(
        message="Do you want to continue from the last save?:",
        choices=["Yes", "No", "Quit"],
        default=None,
    ).execute()
    if inner_command == "Quit":
        quit()
    elif inner_command == "Yes":
        _dungeon = create_dungeon_from_json(abilities=abilities,
                                            json_data=fetch_dungeon(player))
    elif inner_command == "No":
        _dungeon = create_new_dungeon()
    return _dungeon
Exemple #17
0
        def _play_local_action():

            create_or_join_actions = {
                'Create a New Game': self._create_game,
                'Join a Game': self._join_game
            }

            while (True):

                create_or_join = inquirer.select(
                    'Create or Join a Game?',
                    create_or_join_actions).execute()

                response = create_or_join_actions[create_or_join]()

                if (create_or_join == 'Create a New Game'):
                    break
                else:
                    if (response == 'declined'):
                        continue
                    elif (response == 'accepted'):
                        break
Exemple #18
0
    def __init__(self):

        self._user_requesting: list[UserSettings] = []

        self._opponent = None

        def _play_local_action():

            create_or_join_actions = {
                'Create a New Game': self._create_game,
                'Join a Game': self._join_game
            }

            while (True):

                create_or_join = inquirer.select(
                    'Create or Join a Game?',
                    create_or_join_actions).execute()

                response = create_or_join_actions[create_or_join]()

                if (create_or_join == 'Create a New Game'):
                    break
                else:
                    if (response == 'declined'):
                        continue
                    elif (response == 'accepted'):
                        break

        game_actions = {
            'Play Against a Friend Locally': _play_local_action,
            # 'Play Against a Friend Online': self._play_online,
            'Play Against a Bot': self._play_bot
        }

        action = inquirer.select('Choose how to play:', game_actions).execute()

        # Run the function
        game_actions[action]()
Exemple #19
0
def create_ship(database):
    planet_name = promptUtils.planet_prompt(database)
    faction_name = faction_prompt(database)

    ship_size = iq.select(
        message="Class:",
        choices=[
            {"name": "Colony ship", "value": "COLONY"},
            {"name": "Class 1", "value": 1},
            {"name": "Class 2", "value": 2},
            {"name": "Class 3", "value": 3},
            {"name": "Class 4", "value": 4},
            {"name": "Class 5", "value": 5},
            {"name": "Class 6", "value": 6},
            {"name": "Class 7", "value": 7},
            {"name": "Class 8", "value": 8},
            {"name": "Class 9", "value": 9},
            {"name": "Class 10", "value": 10}
        ]
    ).execute()

    if ship_size == "COLONY":
        return shipCrud.create_ship_from_dict(database, {
            'owner': faction_name,
            'modules': ship_size,
            'location': planet_name
        })

    modules = choose_modules(database, ship_size, faction_name)

    ship = {
        'owner': faction_name,
        'modules': modules,
        'location': planet_name
    }

    shipCrud.create_ship_from_dict(database, ship)
Exemple #20
0
    def print_main_menu(self):
        print()
        print(f'{"Main Menu":^}')
        print()

        availableActions = [
            'Start a New Game', 'Watch a Game', 'Setting Options', 'Quit'
        ]

        user_action = inquirer.select('Choose an action:',
                                      availableActions).execute()

        if (user_action == availableActions[3]):
            print('Exiting ...')
            exit()

        if (user_action == availableActions[0]):
            game = Game()

        if (user_action == availableActions[1]):
            warn('h')

        if (user_action == availableActions[2]):
            warn('Settings')
Exemple #21
0
def faction_prompt(database, message="Faction:"):
    return iq.select(
        message=message,
        choices=factionCrud.get_faction_names(database)).execute()
Exemple #22
0
console.rule('[bold red]UNIVERSAL TESTING MACHINE')

result = 0

while result is not None:
    result = inquirer.select(message='Select a menu voice:',
                             choices=[{
                                 'name': 'Load Cell Calibration',
                                 'value': 'loadcell_calibration'
                             }, {
                                 'name': 'Manual Control',
                                 'value': 'manual'
                             }, {
                                 'name': 'Monotonic Test',
                                 'value': 'monotonic'
                             }, {
                                 'name': 'Cyclic Test',
                                 'value': 'cyclic'
                             }, {
                                 'name': 'Static Test',
                                 'value': 'static'
                             }, {
                                 'name': 'Exit',
                                 'value': None
                             }],
                             default='monotonic').execute()

    if result == 'loadcell_calibration':
        calibration_dir = helpers.create_calibration_dir()
        helpers.check_existing_calibration(calibration_dir, my_loadcell)
        if my_loadcell.is_calibrated is not True:
Exemple #23
0
def init(dirname: str = typer.Argument(".")):
    dirname = Path(dirname)

    basemap_zoom = 18  # TODO: Fix

    if Path(dirname.joinpath(FILENAME)).exists():
        typer.Abort()

    if not dirname.is_dir():
        typer.Abort()

    shortdirname = dirname.resolve().name

    uid = inquirer.text(message="Twin ID:", default=shortdirname).execute()

    location_keywords = None
    location = None
    bbox = []
    default_name = ""

    while True:
        location_keywords = inquirer.text(
            message="Location keywords (leave blank to skip):",
        ).execute()

        if not location_keywords:
            break

        geolocator = Nominatim(user_agent="owntwin-cli")
        location_candidates = geolocator.geocode(
            location_keywords, exactly_one=False, limit=5
        )

        if not location_candidates:
            typer.echo("Not found. Please Try again.")
            continue

        location = inquirer.select(
            message="Select nearby location:",
            choices=list(
                map(lambda x: {"name": x.address, "value": x}, location_candidates)
            )
            + [Separator(), {"name": "(Back)", "value": False}],
        ).execute()

        if location:
            break

    if not location_keywords:

        def validate(text):
            try:
                return len(tuple(map(lambda x: float(x.strip()), text.split(",")))) == 2
            except:
                return False

        location_coordinate = inquirer.text(
            message="Location coordinate [latitude, longitude] (leave blank to skip):",
            validate=validate,
            filter=lambda text: tuple(map(lambda x: float(x.strip()), text.split(","))),
        ).execute()
        location = namedtuple("location", ["latitude", "longitude", "address"])
        location.latitude, location.longitude = location_coordinate
        location.address = ""

    if location:
        lat, lng = location.latitude, location.longitude
        # print(location, lat, lng)
        size = inquirer.text(
            message="Side length (meter):",
            filter=lambda x: float(x),
            validate=NumberValidator(float_allowed=True),
        ).execute()

        # bbox = [
        #     lng + utils.meter_to_lng(size, lat, lng),  # east
        #     lat - utils.meter_to_lat(size, lat, lng),  # south
        #     lng - utils.meter_to_lng(size, lat, lng),  # west
        #     lat + utils.meter_to_lat(size, lat, lng),  # north
        # ]
        bbox = [
            lng - utils.meter_to_lng(size, lat, lng),  # west
            lat - utils.meter_to_lat(size, lat, lng),  # south
            lng + utils.meter_to_lng(size, lat, lng),  # east
            lat + utils.meter_to_lat(size, lat, lng),  # north
        ]
        tiles = mercantile.tiles(*bbox, basemap_zoom)
        tiles = list(tiles)
        basemap_bbox = utils.tiles_bounds(tiles)
        bbox = basemap_bbox

        typer.echo(
            "  Left (lng): {}\n  Bottom (lat): {}\n  Right (lng): {}\n  Top (lat): {}".format(
                *bbox
            )
        )
        typer.confirm("Is this OK?", default=True, abort=True)
        default_name = location.address

    name = inquirer.text(message="Twin name:", default=default_name).execute()
    type = inquirer.text(message="Twin type:", default="").execute()
    iri = inquirer.text(
        message="IRI or URL:", default=f"https://beta.owntwin.com/twin/{uid}"
    ).execute()
    description = inquirer.text(message="Description:", default="").execute()

    twin = {
        "id": uid,
        "name": name,
        "type": type,
        "type_label": type,
        "iri": iri,
        "description": description,
        "bbox": bbox,
        "canvas": {
            "width": 1024,
            "height": 1024,
        },
        "terrain": {
            "path": "assets/levelmap.json",
        },
        "building": {
            "path": "assets/buildings.json",
        },
        "modules": {},
    }

    # twin = {
    #     "name": name,
    #     ...
    #     "terrain": "levelmap.json",
    #     "objects": {
    #       "building": "building.json",
    #     },
    #     "modules": {},
    # }

    typer.echo(f"About to create {FILENAME}:\n")
    typer.echo(json.dumps(twin, ensure_ascii=False, indent=2))
    typer.confirm("Is this OK?", default=True, abort=True)

    if not dirname.exists():
        dirname.mkdir()

    save_config(twin, dirname.joinpath(FILENAME))
Exemple #24
0
from InquirerPy import inquirer
from InquirerPy.validator import NumberValidator

age = inquirer.text(
    message="Enter your age:",
    validate=NumberValidator(),
    default="18",
    filter=lambda result: int(result),
    transformer=lambda result: "Adult" if int(result) >= 18 else "Youth",
).execute()

drinks = ["Soda", "Cidr", "Water", "Milk"] if age < 18 else ["Wine", "Beer"]

drink = inquirer.rawlist(message="What drinks would you like to buy:",
                         default=2,
                         choices=drinks).execute()

if drink in {"Wine", "Beer"}:
    bag = inquirer.select(message="Would you like a bag:",
                          choices=["Yes", "No"]).execute()

confirm = inquirer.confirm(message="Confirm?", default=True).execute()
Exemple #25
0
def prepareSdCard(ctx: click.Context):  # NOSONAR
	if not commons.isAdmin():
		commons.returnToMainMenu(ctx=ctx, pause=True, message='You need admin rights for this, please restart Alice CLI with admin elevated rights.')
		return

	operatingSystem = platform.system().lower()

	balenaExecutablePath = getBalenaPath()
	flasherAvailable = balenaExecutablePath != None

	downloadsPath = Path.home() / 'Downloads'

	doFlash = inquirer.confirm(
		message='Do you want to flash your SD card with Raspberry PI OS?',
		default=False
	).execute()

	installBalena = False
	if not flasherAvailable:
		installBalena = inquirer.confirm(
			message='balena-cli was not found on your system. It is required for working with SD cards, do you want to install it?',
			default=True
		)

	if not flasherAvailable and not installBalena:
		commons.returnToMainMenu(ctx, pause=True, message='Well then, I cannot work with your SD card without the appropriate tool to do it')
		return
	elif not flasherAvailable and installBalena:
		commons.printInfo('Installing Balena-cli, please wait...')
		balenaVersion = 'v13.1.1'
		if operatingSystem == 'windows':
			url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-windows-x64-installer.exe'
		elif operatingSystem == 'linux':
			url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-linux-x64-standalone.zip'
		else:
			url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-macOS-x64-installer.pkg'

		destination = downloadsPath / url.split('/')[-1]

		if destination.exists():
			commons.printInfo(f'Skipping download, using existing: {destination}')
		else:
			commons.printInfo('Downloading...')
			doDownload(url=url, destination=destination)

		if operatingSystem == 'windows':
			commons.printInfo("Starting the installation, please follow the instructions and come back when it's done!")
			subprocess.Popen(str(destination).split(), shell=True)
			click.pause('Press a key when the installation process is done! Please close your terminal and restart it to continue the flashing process')
			exit(0)
		elif operatingSystem == 'linux':
			executablePath = Path(balenaExecutablePath)
			commons.printInfo(f"Install dir: {executablePath.parent}")
			commons.printInfo(f'Extracting {destination} to {executablePath.name}...')
			archive = zipfile.ZipFile(destination)
			archive.extractall()  # extract to ./balena-cli/ i.e. sub dir of working directory.
			commons.printInfo('Setting ./balena-cli/balena as executable...')
			# set executable permission
			# from https://stackoverflow.com/questions/12791997/how-do-you-do-a-simple-chmod-x-from-within-python
			executablePath.chmod(509)  # now shell `./balena-cli/balena version` works
			commons.printInfo('Adding ./balena-cli to PATH...')
			os.environ['PATH'] += os.pathsep + str(executablePath.parent)
			sysPath = os.environ['PATH']
			commons.printInfo(f'New PATH: {sysPath}')
			click.pause('Installation Done. Press a key')
		else:
			click.pause('I have no idea how to install stuff on Mac, so I have downloaded the tool for you, please install it. Oh, and contact Psycho to let him know how to install a pkg file on Mac ;-)')
			exit(0)

	if doFlash:
		images = list()
		commons.printInfo('Checking for Raspberry PI OS images, please wait....')
		# Potential local files
		downloadsPath = Path.home() / 'Downloads'
		for file in downloadsPath.glob('*raspi*.zip'):
			images.append(str(file))

		images.append('https://downloads.raspberrypi.org/raspios_lite_armhf/images/raspios_lite_armhf-2021-05-28/2021-05-07-raspios-buster-armhf-lite.zip')

		# Deactivated for now, we enforce Buster only!
		# directories = list()
		# Get a list of available images online
		# url = 'https://downloads.raspberrypi.org/raspios_lite_armhf/images/'
		# page = requests.get(url)
		# if page.status_code == 200:
		# 	soup = BeautifulSoup(page.text, features='html.parser')
		# 	directories = [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith('/')]
		# 	if directories:
		# 		directories.pop(0)  # This is the return link, remove it...
		#
		# for directory in directories:
		# 	page = requests.get(directory)
		# 	if page.status_code == 200:
		# 		soup = BeautifulSoup(page.text, features='html.parser')
		# 		images.extend([directory + node.get('href') for node in soup.find_all('a') if node.get('href').endswith('.zip')])

		commons.printInfo('Checking for available SD card drives, please wait....')
		drives = list()

		sdCards = getSdCards()
		for sdCard in sdCards:
			drives.append(Choice(sdCard, name=sdCard))

		if not drives:
			commons.returnToMainMenu(ctx, pause=True, message='Please insert your SD card first')
			return

		image = inquirer.select(
			message='Select the image you want to flash. Keep in mind we only officially support the "Buster" Raspberry pi OS distro!',
			choices=images
		).execute()

		drive = inquirer.select(
			message='Select your SD card drive',
			choices=drives
		).execute()

		commons.printInfo("Flashing SD card, please wait")

		if image.startswith('https'):
			file = downloadsPath / image.split('/')[-1]
			doDownload(url=image, destination=file)
		else:
			file = image

		if operatingSystem == 'windows' or operatingSystem == 'linux':
			if operatingSystem == 'linux':
				# this only works on distros with "sudo" support.
				balenaCommand = f'sudo {balenaExecutablePath} local flash {str(file)} --drive {drive} --yes'
			else:
				balenaCommand = f'balena local flash {str(file)} --drive {drive} --yes'.split()
			subprocess.run(balenaCommand, shell=True)
			time.sleep(5)
		else:
			commons.returnToMainMenu(ctx, pause=True, message='Flashing only supported on Windows and Linux systems for now. If you have the knowledge to implement it on other systems, feel free to pull request!')
			return

		click.pause('Flashing complete. Please eject, unplug and replug your SD back, then press any key to continue...')

	ssid = inquirer.text(
		message='Enter the name of your Wifi network',
		validate=EmptyInputValidator(commons.NO_EMPTY)
	).execute()

	password = inquirer.secret(
		message='Enter your Wifi network\'s key',
		transformer=lambda _: commons.HIDDEN
	).execute()

	country = inquirer.select(
		message='Select your country. This is used for your Wi-Fi settings!',
		default='EN',
		choices=commons.COUNTRY_CODES
	).execute()

	drives = list()
	drive = ''
	if operatingSystem == 'linux':
		# typically, boot partition is the first increment of SD device
		# e.g. on /dev/sda drive /dev/sda1 is "boot" and /dev/sda2 is "rootfs"
		# Lookup up the boot mount point path via lsblk

		sdCards = getSdCards()
		command = f'sudo lsblk -o PATH,FSTYPE,LABEL,MOUNTPOINT --json'
		output = subprocess.run(command, capture_output=True, shell=True).stdout.decode()
		blkDevices = json.loads(output)
		for device in blkDevices['blockdevices']:
			if device["path"].startswith(tuple(sdCards)) and device['fstype'] == 'vfat' and device['label'] == 'boot':
				drives.append(Choice(value=device, name=device['path']))

		if len(drives) == 0:
			commons.printError(f'For some reason I cannot find the SD boot partition mount point {drive}.')
			commons.returnToMainMenu(ctx, pause=True, message="I'm really sorry, but I just can't continue without this info, sorry for wasting your time...")

		if len(drives) == 1:
			device = drives[0].value
			commons.printInfo(f'Auto-selected {device["path"]}.')
			drive = device
	else:
		j = 0
		while len(drives) <= 0:
			j += 1
			for dp in psutil.disk_partitions():
				if 'rw,removable' not in dp.opts.lower():
					continue

				drives.append(dp.device)

			if not drives:
				if j < 3:
					drives = list()
					commons.printError('For some reason I cannot find any writable SD partition. Please eject then unplug, replug your SD back and press any key to continue')
					click.pause()
				else:
					break

	if not drive:
		drive = inquirer.select(
			message='Please select the correct SD `boot` partition',
			choices=drives
		).execute()

	needToUnmount = False
	mountDir = ''
	if operatingSystem == 'linux':
		# if device has not been mounted yet, mount in temp directory
		if drive['mountpoint'] is None:
			needToUnmount = True
			mountDir = tempfile.mkdtemp(prefix='alice-cli-mount-')
			command = f"sudo mount {drive['path']} {mountDir}"
			result = subprocess.run(command, capture_output=True, shell=True)
			if not result.returncode == 0:
				commons.printError(f"Could not mount {drive['path']} to {mountDir}.")
				commons.returnToMainMenu(ctx, pause=True)
			drive['mountpoint'] = mountDir
			commons.printInfo(f"Mounted {drive['path']} to {mountDir} temporarily.")
		else:
			commons.printInfo(f"{drive['path']} is already mounted to {drive['mountpoint']}.")
		drive = drive['mountpoint']

	# Now let's enable SSH and Wi-Fi on boot.
	commons.printInfo('Adding ssh & wifi to SD boot....')
	sshFile = Path(drive, 'ssh')
	sshFile.unlink(missing_ok=True)
	sshFile.touch()

	content = f'country={country}\n'
	content += 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'
	content += 'update_config=1\n'
	content += 'network={\n'
	content += f'\tssid="{ssid}"\n'
	content += '\tscan_ssid=1\n'
	content += f'\tpsk="{password}"\n'
	content += '\tkey_mgmt=WPA-PSK\n'
	content += '}'
	Path(drive, 'wpa_supplicant.conf').write_text(content)

	if operatingSystem == 'linux' and needToUnmount and mountDir:
		command = f'sudo umount {drive}'
		result = subprocess.run(command, capture_output=True, shell=True)
		if not result.returncode == 0:
			commons.printError(f'Could not unmount {drive}.')
			commons.returnToMainMenu(ctx, pause=True)
		commons.printInfo(f'Unmounted {drive}')
		# only deletes empty dirs, so if unmounting failed for whatever reasons, we don't destroy anything
		os.rmdir(mountDir)

	commons.returnToMainMenu(ctx, pause=True, message='SD card is ready. Please plug it in your device and boot it!')
Exemple #26
0
    def run(self, context: typings.Context, args: list):
        tournament_model = context["models"]["Tournament"]
        tournament_view = context["views"]["tournament"]

        players = context["models"]["Player"].find_many()

        has_min_players = lambda players: len(players) >= 8

        if not has_min_players(players):
            raise errors.GenericError(
                "Cannot create a tournament without at least 8 players created !"
            )

        questions = {
            "name":
            text(
                message="Enter the name of the tournament:",
                validate=validators.TextValidator(),
                default=f'{self._generate_fake("name")}',
            ),
            "location":
            text(
                message="Enter the location of the tournament:",
                validate=lambda text: len(text) > 0,
                default=f'{self._generate_fake("location")}',
            ),
            "date":
            text(
                message="Enter date of the tournament:",
                validate=validators.DateValidator(),
                default=f'{self._generate_fake("date")}',
            ),
            "rounds":
            text(
                message="Enter the rounds of the tournament:",
                validate=validators.DigitValidator(),
                default="4",
            ),
            "players":
            select(
                message="Select the participants:",
                choices=[{
                    "name": f"{p.full_name}",
                    "value": p
                } for p in players],
                instruction=
                "> use Spacebar to select, and Enter to exit the selection",
                validate=lambda players: has_min_players(players) and len(
                    players) % 2 == 0 and len(players),
                invalid_message=
                "Cannot select less than 8 players OR odd players",
                multiselect=True,
                transformer=lambda result: "%s player%s selected" %
                (len(result), "s" if len(result) > 1 else ""),
            ),
            "time_control":
            select(
                message="Time control of the Tournament:",
                choices=["blitz", "bullet"],
                default="blitz",
            ),
            "desc":
            text(
                message="Description:",
                default="None",
            ),
        }

        result = {}

        for key, value in questions.items():
            sanitize_value = type(getattr(tournament_model(), key))
            try:
                result[key] = sanitize_value(value.execute())
            except KeyboardInterrupt:
                raise errors.GenericError(
                    "Canceld the creation of the tournament", title="Note")

        new_tournament = tournament_model(**result)
        new_tournament = new_tournament.save()

        tournament_view.render_single(new_tournament,
                                      title="Created Tournament",
                                      hint=True)
Exemple #27
0
def installAlice(ctx: click.Context, force: bool):
	click.secho('\nInstalling Alice!', fg='yellow')

	result = sshCmdWithReturn('test -d ~/ProjectAlice/ && echo "1"')[0].readline()
	if result:
		if not force:
			commons.printError('Alice seems to already exist on that host')
			confirm = inquirer.confirm(
				message='Erase and reinstall?',
				default=False
			).execute()

			if confirm:
				commons.returnToMainMenu(ctx)
				return

		sshCmd('sudo systemctl stop ProjectAlice')
		sshCmd('sudo rm -rf ~/ProjectAlice')

	adminPinCode = inquirer.secret(
		message='Enter an admin pin code. It must be made of 4 characters, all digits only. (default: 1234)',
		default='1234',
		validate=lambda code: code.isdigit() and int(code) < 10000,
		invalid_message='Pin must be 4 numbers',
		transformer=lambda _: commons.HIDDEN
	).execute()

	mqttHost = inquirer.text(
		message='Mqtt hostname',
		default='localhost',
		validate=EmptyInputValidator(commons.NO_EMPTY)
	).execute()

	mqttPort = inquirer.number(
		message='Mqtt port',
		default=1883,
		validate=EmptyInputValidator(commons.NO_EMPTY)
	).execute()

	activeLanguage = inquirer.select(
		message='What language should Alice be using?',
		default='en',
		choices=[
			Choice('en', name='English'),
			Choice('de', name='German'),
			Choice('fr', name='French'),
			Choice('it', name='Italian'),
			Choice('pl', name='Polish'),
		]
	).execute()

	activeCountryCode = inquirer.select(
		message='Enter the country code to use.',
		default='EN',
		choices=commons.COUNTRY_CODES
	).execute()

	releaseType = inquirer.select(
		message='What releases do you want to receive? If you are unsure, leave this to Stable releases!',
		default='master',
		choices=[
			Choice('master', name='Stable releases'),
			Choice('rc', name='Release candidates'),
			Choice('beta', name='Beta releases'),
			Choice('alpha', name='Alpha releases')
		]
	).execute()

	audioDevice = inquirer.select(
		message='Select your audio hardware if listed',
		default='respeaker2',
		choices=[
			Choice('respeaker2', name='Respeaker 2 mics'),
			Choice('respeaker4', name='Respeaker 4 mic array'),
			Choice('respeaker4MicLinear', name='Respeaker 4 mic linear array'),
			Choice('respeaker6', name='Respeaker 6 mic array'),
			Choice('respeaker7', name='Respeaker 7'),
			Choice('respeakerCoreV2', name='Respeaker Core version 2'),
			Choice('googleAIY', name='Google AIY'),
			Choice('googleAIY2', name='Google AIY 2'),
			Choice('matrixCreator', name='Matrix Creator'),
			Choice('matrixVoice', name='Matrix Voice'),
			Choice('ps3eye', name='PS3 Eye'),
			Choice('jabra410', name='Jabra 410'),
			Choice(None)
		]
	).execute()

	soundInstalled = inquirer.confirm(
		message='Did you already install your sound hardware using Alice CLI or confirmed it to be working?',
		default=False
	).execute()

	installHLC = inquirer.confirm(
		message='Do you want to install HLC? HLC can pilot leds such as the ones on Respeakers to provide visual feedback.',
		default=False
	).execute()

	advancedConfigs = inquirer.confirm(
		message='Do you want to set more advanced configs? If you do, DO NOT ABORT IN THE MIDDLE!',
		default=False
	).execute()

	asr = 'coqui'
	tts = 'pico'
	awsAccessKey = ''
	awsSecretKey = ''
	googleServiceFile = ''
	shortReplies = False
	devMode = False
	githubUsername = ''
	githubToken = ''
	enableDataStoring = True
	skillAutoUpdate = True

	if advancedConfigs:
		asr = inquirer.select(
			message='Select the ASR engine you want to use',
			default='coqui',
			choices=[
				Choice('coqui', name='Coqui'),
				Choice('snips', name='Snips (English only!)'),
				Choice('google', name='Google (Online!)'),
				Choice('deepspeech', name='Deepspeech'),
				Choice('pocketsphinx', name='PocketSphinx')
			]
		).execute()

		tts = inquirer.select(
			message='Select the TTS engine you want to use',
			default='pico',
			choices=[
				Choice('pico', name='Coqui'),
				Choice('mycroft', name='Mycroft'),
				Choice('amazon', name='Amazon'),
				Choice('google', name='Google'),
				Choice('watson', name='Watson')
			]
		).execute()

		if tts == 'amazon':
			awsAccessKey = inquirer.secret(
				message='Enter your AWS access key',
				validate=EmptyInputValidator(commons.NO_EMPTY),
				transformer=lambda _: commons.HIDDEN
			).execute()

			awsSecretKey = inquirer.secret(
				message='Enter your AWS secret key',
				validate=EmptyInputValidator(commons.NO_EMPTY),
				transformer=lambda _: commons.HIDDEN
			).execute()

		if tts == 'google' or asr == 'google':
			googleServiceFile = inquirer.filepath(
				message='Enter your Google service file path',
				default='~/',
				validate=PathValidator(is_file=True, message='Input is not a file')
			).execute()

		shortReplies = inquirer.confirm(
			message='Do you want Alice to use short replies?',
			default=False
		).execute()

		devMode = inquirer.confirm(
			message='Do you want to activate the developer mode?',
			default=False
		).execute()

		if devMode:
			githubUsername = inquirer.text(
				message='Enter your Github username. This is required for Dev Mode.',
				validate=EmptyInputValidator(commons.NO_EMPTY)
			).execute()

			githubToken = inquirer.secret(
				message='Enter your Github access token. This is required for Dev Mode.',
				validate=EmptyInputValidator(commons.NO_EMPTY),
				transformer=lambda _: commons.HIDDEN
			).execute()

		enableDataStoring = inquirer.confirm(
			message='Enable telemetry data storing?',
			default=True
		).execute()

		skillAutoUpdate = inquirer.confirm(
			message='Enable skill auto update?',
			default=True
		).execute()

	commons.waitAnimation()
	confFile = Path(Path.home(), '.pacli/projectalice.yaml')
	confFile.parent.mkdir(parents=True, exist_ok=True)

	updateSource = commons.getUpdateSource(releaseType)

	try:
		with requests.get(url=f'https://raw.githubusercontent.com/project-alice-assistant/ProjectAlice/{updateSource}/ProjectAlice.yaml', stream=True) as r:
			r.raise_for_status()
			with confFile.open('wb') as fp:
				for chunk in r.iter_content(chunk_size=8192):
					if chunk:
						fp.write(chunk)
	except Exception as e:
		commons.printError(f'Failed downloading ProjectAlice.yaml {e}')
		commons.returnToMainMenu(ctx, pause=True)

	with confFile.open(mode='r') as f:
		try:
			confs = yaml.safe_load(f)
		except yaml.YAMLError as e:
			commons.printError(f'Failed reading projectalice.yaml {e}')
			commons.returnToMainMenu(ctx, pause=True)

	confs['adminPinCode'] = str(int(adminPinCode)).zfill(4)
	confs['mqttHost'] = mqttHost
	confs['mqttPort'] = int(mqttPort)
	confs['activeLanguage'] = activeLanguage
	confs['activeCountryCode'] = activeCountryCode
	confs['useHLC'] = installHLC
	confs['aliceUpdateChannel'] = releaseType
	confs['skillsUpdateChannel'] = releaseType
	confs['ttsLanguage'] = f'{activeLanguage}-{activeCountryCode}'

	if soundInstalled:
		confs['installSound'] = False
		if audioDevice:
			confs['audioHardware'][audioDevice] = True
	else:
		confs['installSound'] = True

	confs['asr'] = asr
	confs['awsAccessKey'] = awsAccessKey
	confs['awsSecretKey'] = awsSecretKey
	confs['tts'] = tts
	confs['shortReplies'] = shortReplies
	confs['devMode'] = devMode
	confs['githubUsername'] = githubUsername
	confs['githubToken'] = githubToken
	confs['enableDataStoring'] = enableDataStoring
	confs['skillAutoUpdate'] = skillAutoUpdate

	if googleServiceFile and Path(googleServiceFile).exists():
		confs['googleServiceFile'] = Path(googleServiceFile).read_text()

	if asr == 'google':
		confs['keepASROffline'] = False

	if tts in ['amazon', 'google', 'watson']:
		confs['keepTTSOffline'] = False

	with confFile.open(mode='w') as f:
		yaml.dump(confs, f)

	commons.printSuccess('Generated ProjectAlice.yaml')

	commons.printInfo('Updating system')
	sshCmd('sudo apt-get update')
	sshCmd('sudo apt-get install git -y')
	sshCmd('git config --global user.name "Han Oter"')
	sshCmd('git config --global user.email "*****@*****.**"')

	commons.printInfo('Cloning Alice')
	sshCmd('git clone https://github.com/project-alice-assistant/ProjectAlice.git ~/ProjectAlice')

	sftp = commons.SSH.open_sftp()
	sftp.put(str(confFile), '/home/pi/ProjectAlice/ProjectAlice.yaml')
	sftp.close()

	sshCmd('sudo rm /boot/ProjectAlice.yaml')
	sshCmd('sudo cp ~/ProjectAlice/ProjectAlice.yaml /boot/ProjectAlice.yaml')

	commons.printInfo('Start install process')
	sshCmd('cd ~/ProjectAlice/ && python3 main.py')

	commons.printSuccess('Alice has completed the basic installation! She\'s now working further to complete the installation, let\'s see what she does!')
	ctx.invoke(systemLogs)
def command_checker(uinput):
    if uinput == "Quit":
        save()
        quit()
    else:
        if uinput == "Description":
            log_room_desc(uinput)
        elif uinput == "Inventory":
            logger.add_log(player.inventory.show_inventory(), uinput)
            while True:
                inner_command = inquirer.select(
                    message="Select a category:",
                    choices=[
                        "Scrolls",
                        "Armors",
                        "Weapons",
                        "Potions",
                        "Miscs",
                        "Back",
                    ],
                    default=None,
                ).execute()
                if inner_command == "Back":
                    break
                else:
                    item = inquirer.select(
                        message="Select an item to inspect:",
                        choices=player.inventory.get_items_by_type(
                            inner_command) + [
                                "Back",
                            ],
                        default=None,
                    ).execute()
                    if item == "Back":
                        continue
                    else:
                        logger.add_log(item.inspect()["Log"],
                                       uinput + " inspect")
                        while True:
                            choice = inquirer.select(
                                message=f"Do you want to use {item.name}:",
                                choices=["Yes", "No"],
                                default=None,
                            ).execute()
                            if choice == "No":
                                break
                            else:
                                logger.add_log(
                                    item.use(player)["Log"],
                                    "Use " + item.name)
                                next_turn()
                                break
        elif uinput == "Merlin Shop":
            logger.add_log(merlin_Shop.show_shop()["Log"], uinput)
            while True:
                category = inquirer.select(
                    message="Select a category:",
                    choices=[
                        "Scrolls",
                        "Armors",
                        "Weapons",
                        "Potions",
                        "Miscs",
                        "Back",
                    ],
                    default=None,
                ).execute()
                if category == "Back":
                    break
                else:
                    while True:
                        trade_type = inquirer.select(
                            message=f"Select a trade type for {category}:",
                            choices=[
                                "Buy",
                                "Sell",
                                "Sell All",
                                "Back",
                            ],
                            default=None,
                        ).execute()
                        if trade_type == "Back":
                            break
                        elif trade_type == "Buy":
                            while True:
                                item_to_buy = inquirer.select(
                                    message="Select a item to inspect:",
                                    choices=merlin_Shop.inventory.
                                    get_items_by_type(category) + [
                                        "Back",
                                    ],
                                    default=None,
                                ).execute()
                                if item_to_buy == "Back":
                                    break
                                else:
                                    logger.add_log(
                                        item_to_buy.inspect()["Log"], category)
                                    confirmation = inquirer.select(
                                        message="Do want to buy it?:",
                                        choices=[
                                            "Yes",
                                            "No",
                                        ],
                                        default=None,
                                    ).execute()
                                    if confirmation == "No":
                                        break
                                    else:
                                        result = merlin_Shop.buy_from_shop(
                                            item_to_buy, player)
                                        logger.add_log(
                                            result["Log"],
                                            f"Buy {item_to_buy.name}")
                                        next_turn()
                                        continue
                        elif trade_type == "Sell":
                            while True:
                                item_to_sell = inquirer.select(
                                    message="Select a trade type:",
                                    choices=player.inventory.get_items_by_type(
                                        category) + [
                                            "Back",
                                        ],
                                    default=None,
                                ).execute()
                                if item_to_sell == "Back":
                                    break
                                else:
                                    logger.add_log(
                                        item_to_sell.inspect()["Log"],
                                        category)
                                    confirmation = inquirer.select(
                                        message="Do want to sell it?:",
                                        choices=[
                                            "Yes",
                                            "No",
                                        ],
                                        default=None,
                                    ).execute()
                                    if confirmation == "No":
                                        break
                                    else:
                                        result = merlin_Shop.sell_to_shop(
                                            item_to_sell, player)
                                        logger.add_log(
                                            result["Log"],
                                            f"Sell {item_to_sell.name}")
                                        next_turn()
                                        continue
                        elif trade_type == "Sell All":
                            confirmation = inquirer.select(
                                message=f"Do want to sell all {category}?:",
                                choices=[
                                    "Yes",
                                    "No",
                                ],
                                default=None,
                            ).execute()
                            if confirmation == "No":
                                break
                            else:
                                for item in player.inventory.get_items_by_type(
                                        category):
                                    result = merlin_Shop.sell_to_shop(
                                        item["value"], player)
                                    logger.add_log(result["Log"],
                                                   f"Sell All {category}")
                                next_turn()
                                continue
        elif uinput == "Inspect":
            characters_name = [{
                "name": ch.name,
                "value": ch
            } for ch in dungeon.rooms[tuple(player.position)].characters]
            while True:
                selected_character = inquirer.select(
                    message="Select a character to inspect:",
                    choices=["Your self"] + characters_name + [
                        "Back",
                    ],
                    default=None,
                ).execute()
                if selected_character == "Your self":
                    logger.add_log(player.inspect()["Log"],
                                   uinput + " " + selected_character)
                    next_turn()
                elif selected_character == "Back":
                    break
                else:
                    logger.add_log(selected_character.inspect()["Log"], uinput)
                    next_turn()
        elif uinput == "Wait":
            next_turn()
        elif uinput == "Go to":
            while True:
                inner_command = inquirer.select(
                    message="Select a direction to go to:",
                    choices=directions + [
                        "Back",
                    ],
                    default=None,
                ).execute()
                dir_name = ""
                if inner_command == "Back":
                    break
                else:
                    for item in directions:
                        if type(inner_command
                                ) != str and item["value"] == inner_command:
                            dir_name = item["name"]
                    if len(dungeon.rooms[tuple(
                            player.position)].characters) > 0:
                        logger.add_log([(
                            "#ff0000",
                            "for moving to another room you need to kill all enemies in this one"
                        )], uinput + " " + dir_name)
                        break
                    result = player.move(dungeon,
                                         direction=inner_command,
                                         max=dungeon.dungeon_size)
                    if result == "":
                        log_room_desc()
                        next_turn()
                    else:
                        logger.add_log(result["Log"])
        elif uinput == "Abilities":
            while True:
                inner_command = inquirer.select(
                    message="Select an ability to use:",
                    choices=list(player.abilities.keys()) + [
                        "Back",
                    ],
                    default=None,
                ).execute()
                if inner_command == "Back":
                    break
                elif inner_command == "lockpicking":
                    if len(dungeon.rooms[tuple(
                            player.position)].characters) > 0:
                        log_room_desc()
                        logger.add_log([
                            ("#ff0000", "you need to kill these persons first")
                        ], inner_command)
                        return
                    else:
                        while True:
                            direction = inquirer.select(
                                message=
                                "Select a door direction to go cracking it's lock:",
                                choices=directions + [
                                    "Back",
                                ],
                                default=None,
                            ).execute()
                            dir_name = ""
                            for item in directions:
                                if type(direction) != str and item[
                                        "value"] == direction:
                                    dir_name = item["name"]
                            if direction == "Back":
                                break
                            else:
                                key, _to = player.create_vector(
                                    direction, 1, dungeon.dungeon_size)
                                if key in dungeon.doors and dungeon.doors[
                                        key].locked:
                                    result = player.abilities[
                                        "lockpicking"].execute(
                                            player, dungeon.doors[key],
                                            dungeon,
                                            dungeon.doors[key].difficulty)
                                    dungeon.doors[key].locked = result[
                                        "IsLocked"]
                                    logger.add_log(result["Log"],
                                                   inner_command)
                                    if not dungeon.doors[key].locked:
                                        dungeon.rooms[key[
                                            0]].description = room_description_gen(
                                                dungeon.doors,
                                                dungeon.rooms[key[0]])
                                        dungeon.rooms[key[
                                            1]].description = room_description_gen(
                                                dungeon.doors,
                                                dungeon.rooms[key[1]])
                                elif key not in dungeon.doors:
                                    logger.add_log([
                                        ("#ff0000",
                                         "there is no door in this direction")
                                    ], inner_command)
                                else:
                                    logger.add_log([(
                                        "#ffff00",
                                        "This door is not locked. Why you try to pick-locking it? just pass-through it"
                                    )], inner_command)
                            next_turn()
                else:
                    characters = dungeon.rooms[tuple(
                        player.position)].characters
                    characters_list = [{
                        "name": ch.name,
                        "value": ch
                    } for ch in characters]
                    character = inquirer.select(
                        message=f"Select a character to use {inner_command}:",
                        choices=characters_list + ["Your Self"] + [
                            "Back",
                        ],
                        default=None,
                    ).execute()
                    if character == "Your Self":
                        result = player.abilities[inner_command].execute(
                            executor=player, target=player, dungeon=dungeon)
                        logger.add_log(result["Log"],
                                       inner_command + " on yourself")
                        is_game_over(dungeon)
                        next_turn()
                    elif character == "Back":
                        continue
                    else:
                        target = character
                        ability = player.abilities[inner_command]
                        result = ability.execute(executor=player,
                                                 target=target,
                                                 dungeon=dungeon)
                        logger.add_log(result["Log"],
                                       inner_command + " on " + character.name)
                        if target.health <= 0:
                            dungeon.rooms[tuple(
                                player.position
                            )].description = room_description_gen(
                                dungeon_doors=dungeon.doors,
                                room=dungeon.rooms[tuple(player.position)])
                            is_game_over(dungeon)
                        else:
                            ability = random.choice(
                                list(target.abilities.values()))
                            if ability.ability_type == 0:
                                result = ability.execute(executor=target,
                                                         target=player,
                                                         dungeon=dungeon)
                                logger.add_log(result["Log"],
                                               "Enemy attack you")
                                is_game_over(dungeon)
                            else:
                                result = ability.execute(executor=target,
                                                         target=target,
                                                         dungeon=dungeon)

                                logger.add_log(result["Log"],
                                               "Enemy Heal self")
                        next_turn()
            player_abilities["fast attack"] = abilities["fast attack"]
            player_abilities["flame"] = abilities["flame"]
            player_abilities["zen"] = abilities["zen"]
            player_abilities["lockpicking"] = abilities["lockpicking"]
            armor = armor_gen(base_power_ratio=3, rarity="common")
            insert_item(armor)
            weapon = weapon_gen(base_power_ratio=3, rarity="common")
            insert_item(weapon)
            player = character_gen(character_type="player",
                                   _name=name,
                                   abilities=player_abilities,
                                   _position=[0, 0],
                                   armor=armor,
                                   weapon=weapon)
            insert_player(player)
            break

logger.add_log(player.inspect()["Log"])
log_room_desc()
merlin_Shop = shop_gen(shop_type="Merlin", abilities=abilities)
while True:
    user_input = inquirer.select(
        message="Select an action:",
        choices=[
            "Go to", "Abilities", "Wait", "Description", "Inspect",
            "Inventory", "Merlin Shop", "Quit"
        ],
        default=None,
    ).execute()
    command_checker(user_input)
Exemple #30
0
           ------------------------
           Observed Planets
           ------------------------
           {get_planet_entries(database, planets_in_report['observed'], faction_name)}
           """)


def print_report(args):
    resources_section = generate_resources_section(args)
    module_research_section = generate_module_research_section(args)
    planets_section = generate_planets_section(args)

    print(resources_section)
    print(module_research_section)
    print(planets_section)


if __name__ == '__main__':
    db = db.get_db()

    kwargs = {
        'db': db,
        '--faction': iq.select(
            message="Faction name:",
            choices=factionCrud.get_faction_names(db)
        ).execute()
    }

    print_report(kwargs)