### Install NumberLink and Gymnasium Source: https://github.com/misaghsoltani/numberlink/blob/main/notebooks/numberlink_interactive.ipynb Installs the necessary libraries, `uv` and `numberlink` along with `gymnasium`, using pip. The `-q` flag suppresses verbose output during installation. ```python %pip install -q uv !uv pip install -q numberlink gymnasium>=1.0 ``` -------------------------------- ### Install NumberLink with notebook integration using uv Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md Installs the NumberLink package with optional notebook dependencies using the uv package installer. ```bash uv pip install "numberlink[notebook]" ``` -------------------------------- ### Create and Run Interactive NumberLink Game Source: https://github.com/misaghsoltani/numberlink/blob/main/notebooks/numberlink_interactive.ipynb Creates a NumberLink environment with specified configurations and starts the interactive game loop. The `render_mode='human'` enables interactive play, and `NumberLinkViewer` handles user input and rendering. ```python env = gym.make( id="NumberLinkRGB-v0", render_mode="human", generator=generator_cfg, variant=variant_cfg, render_config=render_cfg, ) env.reset(seed=42) viewer = NumberLinkViewer(env, cell_size=64) viewer.loop() ``` -------------------------------- ### Install NumberLink from Source with UV Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Installs the NumberLink project from its source code using `uv`, a fast Python package manager. This method automatically creates a virtual environment and installs dependencies. ```bash git clone https://github.com/misaghsoltani/NumberLink.git cd NumberLink uv sync source .venv/bin/activate # Linux/macOS # Or on Windows: .venv\Scripts\activate uv run numberlink-cli --help ``` -------------------------------- ### Install NumberLink from PyPI Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Installs the NumberLink project from the Python Package Index (PyPI) into a virtual environment. This is a standard method for installing Python packages. ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install --upgrade pip pip install numberlink numberlink-cli --help ``` -------------------------------- ### Setup and Run NumberLink Gymnasium Environment Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/index.rst Demonstrates how to set up and run the NumberLinkRGB-v0 Gymnasium environment. It includes resetting the environment, sampling actions based on the action mask, and stepping through the environment until termination or truncation. ```python import gymnasium as gym import numpy as np import numberlink # Importing the package automatically registers NumberLinkRGB-v0 env = gym.make("NumberLinkRGB-v0", render_mode="rgb_array") observation, info = env.reset(seed=42) action_mask = info["action_mask"].astype(np.int8) terminated = False truncated = False while not (terminated or truncated): action = env.action_space.sample(mask=action_mask) observation, reward, terminated, truncated, info = env.step(action) action_mask = info["action_mask"] env.close() ``` -------------------------------- ### Configure NumberLink Environment Parameters Source: https://github.com/misaghsoltani/numberlink/blob/main/notebooks/numberlink_interactive.ipynb Sets up configuration objects for the NumberLink puzzle generator, variant rules, and rendering. This includes defining grid size, number of colors, path length, and visual properties. ```python generator_cfg = GeneratorConfig( mode="hamiltonian", colors=7, width=8, height=8, min_path_length=3, ) variant_cfg = VariantConfig( must_fill=True, allow_diagonal=False, cell_switching_mode=False, bridges_enabled=False, ) render_cfg = RenderConfig( gridline_color=(60, 60, 60), gridline_thickness=1, show_endpoint_numbers=True, render_height=550, render_width=550, ) ``` -------------------------------- ### Launch NumberLink Viewer with Pygame Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst This Python code demonstrates how to create and launch the NumberLink interactive viewer using Pygame. It sets up the environment with specific generator and variant configurations, then initializes the viewer and starts its main loop. Ensure Pygame is installed for this to function correctly. ```python env = gym.make( "NumberLinkRGB-v0", render_mode="human", generator=GeneratorConfig( mode="hamiltonian", colors=7, width=8, height=8, min_path_length=3, ), variant=VariantConfig( must_fill=True, allow_diagonal=False, cell_switching_mode=False, bridges_enabled=False ), render_config=RenderConfig( gridline_color=(60, 60, 60), gridline_thickness=1, show_endpoint_numbers=True, render_height=400, render_width=400, ), ) env.reset(seed=2) viewer = NumberLinkViewer(env, cell_size=64) viewer.loop() ``` -------------------------------- ### Quick Run NumberLink Viewer Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Launches the NumberLink viewer application directly from the command line. This is a quick way to test the installed application. ```bash numberlink-cli viewer ``` -------------------------------- ### Install NumberLink using pip Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/index.rst Installs the NumberLink package from PyPI using pip. This is the standard method for installing Python packages. ```console pip install numberlink ``` -------------------------------- ### Install NumberLink with notebook integration Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md Installs the NumberLink package with optional dependencies for notebook integration, enabling inline controls in Jupyter and Google Colab. ```bash pip install "numberlink[notebook]" ``` -------------------------------- ### Verify NumberLink Installation Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Commands to verify that the NumberLink package and its command-line interface are correctly installed. Checks package information and displays CLI help. ```bash python -m pip show numberlink || python -c "import numberlink\nprint(numberlink.__version__)" numberlink-cli --help ``` -------------------------------- ### Import NumberLink and Gymnasium Components Source: https://github.com/misaghsoltani/numberlink/blob/main/notebooks/numberlink_interactive.ipynb Imports essential classes and modules from the `gymnasium` and `numberlink` libraries. These are required for creating and configuring the NumberLink environment and its viewer. ```python import gymnasium as gym from numberlink import GeneratorConfig, NumberLinkViewer, RenderConfig, VariantConfig ``` -------------------------------- ### Install NumberLink using uv Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/index.rst Installs the NumberLink package using uv, a fast Python package installer and virtual environment manager. This ensures a reproducible workflow. ```console uv pip install numberlink ``` -------------------------------- ### Editable Source Install with UV or Pip Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Installs the NumberLink project in editable mode from source within a Conda environment, using either `uv` or `pip`. This is useful for development as changes to the source code are immediately reflected. ```bash # Using uv uv pip install -e . # or # Using pip pip install -e . ``` -------------------------------- ### Interact with Single NumberLink RGB Environment (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst Demonstrates basic interaction with the NumberLink RGB environment using Gymnasium. It shows how to reset the environment, sample actions based on a mask, and step through the environment until termination or truncation. This requires the 'gymnasium' and 'numpy' libraries. ```python import gymnasium as gym import numpy as np import numberlink # Importing the package automatically registers the environment env = gym.make("NumberLinkRGB-v0", render_mode="rgb_array") observation, info = env.reset(seed=123) action_mask = info["action_mask"].astype(np.int8) terminated = False truncated = False while not (terminated or truncated): action = env.action_space.sample(mask=action_mask) observation, reward, terminated, truncated, info = env.step(action) action_mask = info["action_mask"] env.close() ``` -------------------------------- ### Interact with Vectorized NumberLink Environments (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst Demonstrates the use of vectorized NumberLink environments for running multiple puzzles in parallel. It shows how to create a vectorized environment, reset multiple environments simultaneously, sample actions for each environment, and step them forward. This requires 'gymnasium' and 'numpy'. ```python import gymnasium as gym import numpy as np from numberlink import GeneratorConfig vec_env = gym.make_vec( "NumberLinkRGB-v0", num_envs=8, render_mode="rgb_array", generator=GeneratorConfig(width=6, height=6, colors=4), ) observations, infos = vec_env.reset(seed=7) actions = [vec_env.single_action_space.sample(mask=mask.astype(np.int8)) for mask in infos["action_mask"]] observations, rewards, terminated, truncated, infos = vec_env.step(actions) vec_env.close() ``` -------------------------------- ### Use Pygame Viewer for NumberLink Human Mode (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst Illustrates how to use the Pygame viewer for human interaction with the NumberLink environment. It shows how to create an environment in 'human' render mode and initialize the NumberLinkViewer. This requires 'gymnasium', 'numberlink', and 'pygame'. ```python import gymnasium as gym import numberlink # Auto-registration on import from numberlink.viewer import NumberLinkViewer env = gym.make("NumberLinkRGB-v0", render_mode="human") viewer = NumberLinkViewer(env, cell_size=64) viewer.loop() ``` -------------------------------- ### Customize NumberLink RGB Environment with Configuration (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst Shows how to customize the NumberLink RGB environment by passing configuration objects for generation, variant rules, and rendering. This allows for fine-grained control over puzzle generation and visual appearance. It requires 'gymnasium' and specific configuration classes from the 'numberlink' package. ```python import gymnasium as gym from numberlink import GeneratorConfig, RenderConfig, VariantConfig env = gym.make( "NumberLinkRGB-v0", render_mode="rgb_array", generator=GeneratorConfig(width=8, height=8, colors=5), variant=VariantConfig(must_fill=True, allow_diagonal=False, bridges_enabled=False), render_config=RenderConfig(cell_size=48), ) observation, info = env.reset(seed=7) env.close() ``` -------------------------------- ### Activate Conda Environment Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Activates a Conda environment named 'numberlink' or 'numberlink_dev'. This makes the project's installed packages and executables available in the current shell session. ```bash conda activate numberlink # or: conda activate numberlink_dev ``` -------------------------------- ### Vectorized Environment for Parallel Execution in Python Source: https://context7.com/misaghsoltani/numberlink/llms.txt Utilize vectorized environments for parallel execution of multiple NumberLink instances, ideal for training RL agents. This example shows how to create a vectorized environment and perform batched reset and step operations. ```python import gymnasium as gym import numpy as np from numberlink import GeneratorConfig # Create vectorized environment with 4 parallel instances vec_env = gym.make_vec( "NumberLinkRGB-v0", num_envs=4, render_mode="rgb_array", generator=GeneratorConfig(width=6, height=6, colors=4) ) # Reset all environments observations, infos = vec_env.reset(seed=0) print(f"Observations shape: {observations.shape}") # Output: Observations shape: (4, 6, 6, 3) or scaled if render_config specifies dimensions # Step with batched actions action_masks = infos["action_mask"] actions = [ vec_env.single_action_space.sample(mask=mask.astype(np.int8)) for mask in action_masks ] observations, rewards, terminated, truncated, infos = vec_env.step(actions) print(f"Rewards: {rewards}") print(f"Terminated: {terminated}") # Output examples: # Rewards: [-0.01, -0.01, -0.01, -0.01] # Terminated: [False, False, False, False] vec_env.close() ``` -------------------------------- ### Launch NumberLink Viewer via CLI Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst This bash command launches the NumberLink interactive pygame window using the command-line interface. It specifies a built-in level ID, sets the cell size, and applies the solution to the displayed board. This is a convenient way to interact with the project without writing Python code. ```bash python -m numberlink viewer --level-id 6x6_rgb_2 --cell-size 72 --apply-solution ``` -------------------------------- ### Inspect NumberLink Board via CLI Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/usage.rst This bash command uses the NumberLink command-line interface to print a text rendering of a specified puzzle board. The `--apply-solution` flag ensures that the stored solution is also applied and displayed in the text output. This is useful for quick inspection of puzzle states. ```bash python -m numberlink board --level-id builtin_7x7_ham_6c --apply-solution ``` -------------------------------- ### NumberLink Cell Switching Mode Environment Source: https://context7.com/misaghsoltani/numberlink/llms.txt Configures and uses the NumberLink environment with cell-switching mode enabled. In this mode, actions represent painting cells directly (row, column, color) instead of defining path moves. The action space size is printed, and an example of encoding and applying a cell-switching action is shown. Requires 'gymnasium' and 'numberlink'. ```python import gymnasium as gym from numberlink import GeneratorConfig, VariantConfig # Cell switching mode: actions encode (row, col, color) instead of path moves try: env = gym.make( "NumberLinkRGB-v0", generator=GeneratorConfig(width=5, height=5, colors=3), variant=VariantConfig(cell_switching_mode=True, must_fill=True) ) observation, info = env.reset() unwrapped = env.unwrapped # Action space is H * W * (num_colors + 1) for cell switching # +1 for "clear cell" action (color value 0) print(f"Action space: {env.action_space.n}") # Encode a cell switching action manually row, col = 2, 2 color_value = 1 # 0=clear, 1-N=colors action = unwrapped.encode_cell_switching_action(row, col, color_value) print(f"Action to paint ({row},{col}) with color {color_value}: {action}") # Apply the action observation, reward, terminated, truncated, info = env.step(action) env.close() except gym.error.Error as e: print(f"Error creating environment: {e}") ``` -------------------------------- ### Build Documentation with Pixi Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Commands to build project documentation using `pixi run` within the 'doc' environment. Includes options for standard builds, nitpicky warnings, and serving docs locally. ```bash pixi run -e doc docs pixi run -e doc docs-nitpick pixi run -e doc docs-run ``` -------------------------------- ### Initialize and Run Notebook Viewer in NumberLink (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md This snippet shows how to set up the NumberLink environment for use in a notebook, with custom configurations for the generator, variant, and rendering. It utilizes the NumberLinkViewer for an inline display within the notebook. Dependencies include gymnasium and optional notebook extras. ```python env = gym.make( "NumberLinkRGB-v0", render_mode="human", generator=GeneratorConfig(mode="hamiltonian", colors=7, width=8, height=8, min_path_length=3), variant=VariantConfig(must_fill=True, allow_diagonal=False, cell_switching_mode=False, bridges_enabled=False), render_config=RenderConfig(gridline_color=(60, 60, 60),gridline_thickness=1,show_endpoint_numbers=True,render_height=400,render_width=400), ) env.reset() viewer = NumberLinkViewer(env, cell_size=64) viewer.loop() ``` -------------------------------- ### Create and run a single NumberLink Gymnasium environment Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md Demonstrates how to create a single NumberLink environment using Gymnasium, reset it, and interact with it by sampling actions until the episode terminates or truncates. It utilizes RGB rendering and action masking. ```python import gymnasium as gym import numpy as np import numberlink # Importing the package automatically registers the environments env = gym.make("NumberLinkRGB-v0", render_mode="rgb_array") observation, info = env.reset(seed=42) action_mask = info["action_mask"] terminated = False truncated = False while not (terminated or truncated): action = env.action_space.sample(mask=action_mask) observation, reward, terminated, truncated, info = env.step(action) action_mask = info["action_mask"].astype(np.int8) env.close() ``` -------------------------------- ### Build Project Distributions with Hatch Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Directly uses the `hatch` build tool to create wheel and sdist packages. This is an alternative to using `pixi` for building distributions. ```bash hatch build -t wheel -t sdist ``` -------------------------------- ### Build Project Distributions with Pixi Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Builds distribution packages (wheel and sdist) for the project using the 'build' environment in `pixi`. This prepares the project for distribution. ```bash pixi shell -e build pixi run build pixi run -e build build ``` -------------------------------- ### Create and run vectorized NumberLink Gymnasium environments Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md Shows how to create multiple NumberLink environments in parallel using Gymnasium's vectorized environment API. It demonstrates resetting multiple environments, sampling actions based on individual masks, and stepping through the environments. Custom generator configurations can be applied. ```python import gymnasium as gym from numberlink import GeneratorConfig # Importing from numberlink automatically registers import numpy as np vec_env = gym.make_vec( "NumberLinkRGB-v0", num_envs=4, render_mode="rgb_array", generator=GeneratorConfig(width=6, height=6, colors=4), ) observations, infos = vec_env.reset(seed=0) actions = [vec_env.single_action_space.sample(mask=mask.astype(np.int8)) for mask in infos["action_mask"]] observations, rewards, terminated, truncated, infos = vec_env.step(actions) vec_env.close() ``` -------------------------------- ### Initialize and Run Human Render Mode in NumberLink (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md This snippet demonstrates how to initialize the NumberLink environment with human render mode and run the Pygame viewer. It requires the gymnasium and numberlink libraries. The output is a visual representation of the game in a separate window. ```python import gymnasium as gym import numberlink # Auto-registration on import from numberlink.viewer import NumberLinkViewer env = gym.make("NumberLinkRGB-v0", render_mode="human") viewer = NumberLinkViewer(env) viewer.loop() ``` -------------------------------- ### List and Create NumberLink Environments Source: https://context7.com/misaghsoltani/numberlink/llms.txt Demonstrates how to list available built-in levels and create a NumberLink environment with a specific level. It also shows how to access the level solution if available. Requires the 'numberlink' library and 'gymnasium'. ```python import gymnasium as gym from numberlink.levels import Level # Assuming LEVELS is accessible, e.g., from numberlink.levels # For demonstration, let's mock it if not directly importable class MockLevels: def keys(self): return ['builtin_5x5_rw_4c', 'builtin_6x6_rw_5c', 'builtin_7x7_ham_6c', 'another_level'] LEVELS = MockLevels() # List available built-in levels print("Available levels:", list(LEVELS.keys())[:5]) # Create environment with a specific built-in level try: env = gym.make("NumberLinkRGB-v0", level_id="builtin_7x7_ham_6c") observation, info = env.reset() print(f"Level: {info['level_id']}, Grid: {env.unwrapped.H}x{env.unwrapped.W}") # Access level solution if available solution = env.unwrapped.get_solution() if solution: print(f"Solution has {len(solution)} actions") env.close() except gym.error.Error as e: print(f"Error creating environment: {e}") # Define a custom level programmatically custom_level = Level( grid=[ "A..B", "....", "....", "B..A" ], bridges=None, # Optional: set of (row, col) for bridge cells solution=[ [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (3, 3)], [(0, 3), (0, 2), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3), (1, 3)] ] ) # To use custom_level, you would typically pass it to gym.make: # env = gym.make("NumberLinkRGB-v0", level=custom_level) # Load level from file (commented out as it requires a file path) # level = load_level_from_file("/path/to/puzzle.txt") # Optional adjacent solution file: /path/to/puzzle.txt.sol.json ``` -------------------------------- ### Create Conda Environments Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Creates Conda environments for the NumberLink project using provided environment files. Supports a default environment and a development environment with extra tools. ```bash conda env create -f environment.yml -n numberlink conda env create -f environment_dev.yml -n numberlink_dev ``` -------------------------------- ### Create and Interact with NumberLink Environment (Python) Source: https://context7.com/misaghsoltani/numberlink/llms.txt Demonstrates how to create a NumberLink environment using Gymnasium, reset it, sample actions based on a mask, and step through the environment until termination or truncation. It also shows the structure of the returned info dictionary. ```python import gymnasium as gym import numpy as np import numberlink # Auto-registers NumberLinkRGB-v0 # Create environment with RGB array rendering env = gym.make("NumberLinkRGB-v0", render_mode="rgb_array") # Reset to get initial observation and info observation, info = env.reset(seed=42) # observation: np.ndarray with shape (H, W, 3), dtype=uint8 # info contains: action_mask, steps, connected, level_id, solved, deadlocked action_mask = info["action_mask"] terminated = False truncated = False while not (terminated or truncated): # Sample valid action using the mask action = env.action_space.sample(mask=action_mask.astype(np.int8)) observation, reward, terminated, truncated, info = env.step(action) action_mask = info["action_mask"] env.close() # Example output info after completion: # { # "action_mask": array([...], dtype=uint8), # "steps": 47, # "connected": array([True, True, True, True]), # "level_id": None, # "solved": True, # "deadlocked": False # } ``` -------------------------------- ### Run Development Tasks with Pixi Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Execute predefined development tasks for code quality and type checking using `pixi run` within a specified environment (e.g., 'dev'). These tasks include linting, formatting, type checking, and more. ```bash pixi run -e dev lint pixi run -e dev ulint pixi run -e dev format pixi run -e dev fix pixi run -e dev mypy pixi run -e dev pyright pixi run -e dev format-check pixi run -e dev typecheck pixi run -e dev yamllint pixi run -e dev shellcheck pixi run -e dev check pixi run -e dev update-citation ``` -------------------------------- ### Auto-register NumberLink Environment with Gymnasium (Python) Source: https://github.com/misaghsoltani/numberlink/blob/main/README.md This code snippet demonstrates the automatic registration of the NumberLink environment with Gymnasium upon importing the numberlink package. This ensures the 'NumberLinkRGB-v0' environment is available for use without explicit registration calls. ```python import numberlink ``` -------------------------------- ### Configure Rewards with RewardConfig in Python Source: https://context7.com/misaghsoltani/numberlink/llms.txt Shape the rewards for reinforcement learning agents using RewardConfig. This allows defining penalties for steps and invalid actions, and bonuses for connecting color pairs and solving the puzzle. It's applied during environment creation. ```python import gymnasium as gym from numberlink import GeneratorConfig, RewardConfig reward_config = RewardConfig( step_penalty=-0.01, # Per-step penalty invalid_penalty=-0.05, # Penalty for invalid actions connect_bonus=0.5, # Bonus when a color pair is connected win_bonus=5.0 # Bonus for solving the puzzle ) env = gym.make( "NumberLinkRGB-v0", generator=GeneratorConfig(width=5, height=5, colors=3), reward_config=reward_config ) observation, info = env.reset() # Execute a random episode and track rewards total_reward = 0 for _ in range(100): action = env.action_space.sample(mask=info["action_mask"].astype(int)) observation, reward, terminated, truncated, info = env.step(action) total_reward += reward if terminated or truncated: break print(f"Episode reward: {total_reward:.2f}") print(f"Solved: {info['solved']}, Steps: {info['steps']}") env.close() ``` -------------------------------- ### Vectorized Execution of NumberLink Environment Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/index.rst Shows how to create and run a vectorized version of the NumberLinkRGB-v0 environment. This allows for running multiple environments in parallel, improving efficiency. ```python import gymnasium as gym import numpy as np import numberlink # Auto-registration on import vec_env = gym.make_vec("NumberLinkRGB-v0", num_envs=4, render_mode="rgb_array") observations, infos = vec_env.reset(seed=7) actions = [vec_env.single_action_space.sample(mask=mask.astype(np.int8)) for mask in infos["action_mask"]] observations, rewards, terminated, truncated, infos = vec_env.step(actions) vec_env.close() ``` -------------------------------- ### Utility Functions Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/_includes/types.rst This section covers utility functions available in the module. ```APIDOC ## Utility Functions ### select_signed_dtype **Description**: Selects a signed data type. ### select_unsigned_dtype **Description**: Selects an unsigned data type. ``` -------------------------------- ### Configure NumberLink Level Generation (Python) Source: https://context7.com/misaghsoltani/numberlink/llms.txt Shows how to customize the procedural generation of NumberLink levels using `GeneratorConfig` and `VariantConfig`. This includes setting grid dimensions, colors, path lengths, generation algorithms, and ensuring all cells are filled. ```python import gymnasium as gym from numberlink import GeneratorConfig, VariantConfig # Create generator configuration generator = GeneratorConfig( mode="hamiltonian", # "hamiltonian" or "random_walk" width=8, height=8, colors=6, min_path_length=3, # Minimum path distance between endpoints seed=123, # Optional seed for reproducibility max_retries=20, # Retry attempts for generation bridges_probability=0.0 # Probability of bridge cells (random_walk only) ) # Create environment with generator env = gym.make( "NumberLinkRGB-v0", render_mode="rgb_array", generator=generator, variant=VariantConfig(must_fill=True) # All cells must be filled ) observation, info = env.reset(seed=42) print(f"Grid: {env.unwrapped.H}x{env.unwrapped.W}, Colors: {env.unwrapped.num_colors}") # Output: Grid: 8x8, Colors: 6 # Regenerate a new level with the same configuration observation, info = env.unwrapped.regenerate_level(seed=100) env.close() ``` -------------------------------- ### Configure NumberLink Game Variants (Python) Source: https://context7.com/misaghsoltani/numberlink/llms.txt Illustrates how to configure specific game rules for the NumberLink environment using `VariantConfig`. This includes enabling or disabling diagonal movement, bridges, and cell-switching mode, and observing the impact on the action space size. ```python import gymnasium as gym from numberlink import GeneratorConfig, VariantConfig variant = VariantConfig( must_fill=True, # All cells must be occupied for solution allow_diagonal=False, # Allow 8-directional movement bridges_enabled=False, # Enable bridge cells (crossing paths) cell_switching_mode=False # Alternative action mode for cell painting ) # Generator for random walk with bridges generator = GeneratorConfig( mode="random_walk", width=6, height=6, colors=4, bridges_probability=0.1 # 10% chance of bridge cells ) env = gym.make( "NumberLinkRGB-v0", generator=generator, variant=VariantConfig(bridges_enabled=True) ) observation, info = env.reset() # Check environment configuration unwrapped = env.unwrapped print(f"Must fill: {unwrapped.variant.must_fill}") print(f"Diagonal allowed: {unwrapped.variant.allow_diagonal}") print(f"Action space size: {env.action_space.n}") # Output examples: # Must fill: True # Diagonal allowed: False # Action space size: 32 (colors * 2 heads * 4 directions) env.close() ``` -------------------------------- ### Customize Rendering with RenderConfig in Python Source: https://context7.com/misaghsoltani/numberlink/llms.txt Control the visual appearance of the NumberLink game using RenderConfig. This includes setting dimensions, colors for the grid and lines, endpoint styling, and displaying endpoint numbers. It's used when creating the Gymnasium environment. ```python import gymnasium as gym from numberlink import GeneratorConfig, RenderConfig render_config = RenderConfig( render_height=400, # Output image height in pixels render_width=400, # Output image width in pixels grid_background_color=(30, 30, 30), # RGB background color gridline_color=(60, 60, 60), # RGB gridline color (None to disable) gridline_thickness=1, # Gridline width in pixels endpoint_border_thickness=2, # Border around endpoints endpoint_border_color=(255, 255, 255),# White border show_endpoint_numbers=True, # Display color indices on endpoints number_font_color=(255, 255, 255), # White text number_font_border_color=(0, 0, 0), # Black outline number_font_border_thickness=1 ) env = gym.make( "NumberLinkRGB-v0", render_mode="rgb_array", generator=GeneratorConfig(width=6, height=6, colors=4), render_config=render_config ) observation, _ = env.reset() print(f"Observation shape: {observation.shape}") # Output: Observation shape: (400, 400, 3) # Get rendered frame frame = env.render() # frame is np.ndarray with shape (400, 400, 3) env.close() ``` -------------------------------- ### Procedural NumberLink Level Generation Source: https://context7.com/misaghsoltani/numberlink/llms.txt Shows how to use the `numberlink.generator` module to programmatically create NumberLink levels. It demonstrates generating levels using both the 'hamiltonian' and 'random_walk' modes with configurable parameters like dimensions, colors, and path lengths. Accessing the generated solution paths and bridge cells is also included. Requires 'numberlink'. ```python from numberlink.generator import generate_level from numberlink.config import GeneratorConfig, VariantConfig from numberlink.levels import Level # Generate using Hamiltonian partition (guarantees must_fill solvability) cfg = GeneratorConfig( mode="hamiltonian", width=8, height=8, colors=7, min_path_length=3, seed=42 ) variant = VariantConfig(must_fill=True, allow_diagonal=False) level: Level = generate_level(cfg, variant=variant) print("Generated grid:") for row in level.grid: print(row) # Access solution paths (list of coordinate lists) if level.solution: for i, path in enumerate(level.solution): print(f"Color {i}: {len(path)} cells, {path[0]} -> {path[-1]}") # Generate with random walk algorithm (supports bridges) cfg_rw = GeneratorConfig( mode="random_walk", width=6, height=6, colors=4, bridges_probability=0.15, seed=123 ) level_rw = generate_level(cfg_rw, variant=VariantConfig(bridges_enabled=True)) if level_rw.bridges: print(f"Bridge cells: {list(level_rw.bridges)}") ``` -------------------------------- ### Loading Built-in and Custom Levels in Python Source: https://context7.com/misaghsoltani/numberlink/llms.txt Access predefined levels from the LEVELS dictionary or load custom levels from files. This snippet shows the necessary imports for level management. ```python import gymnasium as gym from numberlink import LEVELS from numberlink.levels import Level, load_level_from_file ``` -------------------------------- ### Run NumberLink CLI Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/installation.rst Command to execute the NumberLink command-line interface, typically used for running the application or accessing its help information. ```bash pixi run numberlink-cli -h ``` -------------------------------- ### Human Mode Viewer for NumberLink Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/index.rst Demonstrates how to use the NumberLinkViewer to interact with the environment in human mode. This allows for visual inspection and manual control. ```python import gymnasium as gym import numberlink # Auto-registration on import from numberlink.viewer import NumberLinkViewer env = gym.make("NumberLinkRGB-v0", render_mode="human") viever = NumberLinkViewer(env) viever.loop() ``` -------------------------------- ### Interactive Viewer for NumberLink in Python Source: https://context7.com/misaghsoltani/numberlink/llms.txt Engage with the NumberLink game interactively using the NumberLinkViewer. This viewer supports keyboard and mouse controls for gameplay and offers features like solution replay and level generation. It requires Pygame. ```python import gymnasium as gym import numberlink from numberlink.viewer import NumberLinkViewer from numberlink import GeneratorConfig, VariantConfig, RenderConfig env = gym.make( "NumberLinkRGB-v0", render_mode="human", generator=GeneratorConfig( mode="hamiltonian", colors=5, width=7, height=7, min_path_length=3 ), variant=VariantConfig( must_fill=True, allow_diagonal=False ), render_config=RenderConfig( gridline_color=(60, 60, 60), gridline_thickness=1, show_endpoint_numbers=True, render_height=400, render_width=400 ) ) env.reset() # Create viewer with custom cell size viewer = NumberLinkViewer(env, cell_size=64) # Start interactive loop (opens pygame window) # Controls: # Arrow keys: move head / cursor # Tab/Shift+Tab: cycle colors # [ / ]: select left/right head (path mode) # Space: backtrack (path mode) or paint cell (cell mode) # R: reset level # N: generate new level # T: play/pause solution replay # S: stop replay # H: toggle help overlay # ESC: exit viewer.loop() ``` -------------------------------- ### Type Aliases Source: https://github.com/misaghsoltani/numberlink/blob/main/docs/_includes/types.rst This section details the various type aliases used for defining data structures and parameters within the NumberLink project. ```APIDOC ## Type Aliases ### RenderMode **Description**: Canonical type: ``Literal["rgb_array", "ansi", "human"]``. Represents the rendering mode for the environment. ### Coord **Description**: Canonical type: ``tuple[int, int]``. Represents a coordinate pair ``(row, column)`` on the grid. ### Lane **Description**: Canonical type: ``Literal["n", "v", "h"]``. Lane indicator for bridge cells. ``"n"`` for normal, ``"v"`` for vertical, ``"h"`` for horizontal. ### CellLane **Description**: Canonical type: ``tuple[int, int, Lane]``. Encodes a cell coordinate and its active lane as ``(row, column, lane)``. ### RGBInt **Description**: Canonical type: ``tuple[int, int, int]``. Represents an RGB color as ``(red, green, blue)`` integer values. ### ActType **Description**: Canonical type: ``numpy.integer | int``. Action type, accepting numpy integer scalars or built-in ``int``. ### ObsType **Description**: Canonical type: ``numpy.typing.NDArray[numpy.uint8]``. Observation type, an RGB image array. ### Snapshot **Description**: Runtime snapshot captured by ``numberlink.viewer.NumberLinkViewer._snapshot_state``. Contains internal environment arrays and viewer selection state for restoring configurations via ``numberlink.viewer.NumberLinkViewer._restore_state``. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.