### Basic RLTK Hello World in Rust Source: https://github.com/amethyst/bracket-lib/blob/master/rltk/README.md This snippet demonstrates the minimal setup for a 'Hello World' application using RLTK. It initializes a simple 8x8 console, defines a game state, and starts the main game loop. Requires the 'rltk' crate as a dependency. ```rust extern crate rltk; use rltk::{Rltk, GameState, Console}; struct State {} impl GameState for State { fn tick(&mut self, ctx : &mut Rltk) { ctx.cls(); ctx.print(1, 1, "Hello RLTK World"); } } fn main() { let context = Rltk::init_simple8x8(80, 50, "Hello RLTK World", "resources"); let gs = State{ }; rltk::main_loop(context, gs); } ``` -------------------------------- ### Automate WASM Example Builds (Windows Batch) Source: https://github.com/amethyst/bracket-lib/blob/master/rltk/README.md A Windows batch script to automate the building, binding, and staging of multiple RLTK Rust examples for WebAssembly. It uses a subroutine `:StageExample` to handle individual examples, renaming output files to match typical web conventions (`myblob_bg.wasm`, `myblob.js`). ```bat @ECHO OFF mkdir ./wasm_help/staging REM Build the actual WASM files and helpers CALL :StageExample ex01-helloworld, ex01 CALL :StageExample ex02-sparse, ex02 CALL :StageExample ex03-walking, ex03 CALL :StageExample ex04-fov, ex04 CALL :StageExample ex05-dijkstra, ex05 CALL :StageExample ex06-astar-mouse, ex06 CALL :StageExample ex07-tiles, ex07 CALL :StageExample ex08-rex, ex08 CALL :StageExample ex09-offsets, ex09 CALL :StageExample ex10-postprocess, ex10 CALL :StageExample ex11-random, ex11 CALL :StageExample ex12-simplex, ex12 CALL :StageExample ex13-textblock, ex13 CALL :StageExample ex14-dwarfmap, ex14 CALL :StageExample ex15-specs, ex15 REM Duplicate example 1 into the root for compatibility with links I've already shared copy .\wasm_help\staging\ex01\ .\wasm_help\staging REM Submit to server cd wasm_help\staging REM INSERT your copy command to copy to your web server here cd ..\.. REM Finish EXIT /B 0 REM Usage: StageExample EXAMPLE :StageExample echo Building example %~1 cargo build --example %~1 --target wasm32-unknown-unknown --release echo wasm-gc .\target\wasm32-unknown-unknown\release\examples\%~1.wasm mkdir .\wasm_help\staging\%~2 wasm-bindgen .\target\wasm32-unknown-unknown\release\examples\%~1.wasm --out-dir .\wasm_help\staging\%~2 --no-modules --no-typescript copy .\wasm_help\index.html .\wasm_help\staging\%~2 move .\wasm_help\staging\%~2\%~1_bg.wasm .\wasm_help\staging\%~2\myblob_bg.wasm move .\wasm_help\staging\%~2\%~1.js .\wasm_help\staging\%~2\myblob.js EXIT /B 0 ``` -------------------------------- ### Minimal Bracket-Terminal Game Setup and Display Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/README.md This Rust code snippet demonstrates the minimal setup required to run a bracket-terminal application. It initializes a simple 80x50 terminal with a title, defines a game state structure, and uses the `tick` function to print text to the screen. The `main_loop` function then drives the game. ```rust use bracket_terminal::prelude::*; struct State {} impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { ctx.print(1, 1, "Hello Bracket World"); } } fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Minimal Bracket World") .build()?; let gs: State = State {}; main_loop(context, gs) } ``` -------------------------------- ### Add Individual bracket-lib Crates to Cargo.toml Source: https://context7.com/amethyst/bracket-lib/llms.txt This example demonstrates how to add specific crates from the bracket-lib ecosystem to your Cargo.toml. This allows for a more modular approach, including only the necessary components like bracket-color, bracket-geometry, etc. ```toml [dependencies] bracket-color = "~0.8" bracket-geometry = "~0.8" bracket-pathfinding = "~0.8" bracket-random = "~0.8" bracket-noise = "~0.8" bracket-terminal = "~0.8" ``` -------------------------------- ### Calculate Distances Between Points Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/ex_geometry.md Shows how to calculate the distance between two points using various algorithms: Pythagoras, Pythagoras Squared, Manhattan, and Chebyshev. This is useful for pathfinding and spatial analysis in games. ```rust use bracket_geometry::prelude::Point; use bracket_geometry::algorithms::distance; fn main() { let p1 = Point::new(0, 0); let p2 = Point::new(10, 20); let pythagoras = distance::pythagoras(p1, p2); let pythagoras_squared = distance::pythagoras_squared(p1, p2); let manhattan = distance::manhattan(p1, p2); let chebyshev = distance::chebyshev(p1, p2); println!("Point {{ x: {}, y: {} }}", p1.x, p1.y); println!("Point {{ x: {}, y: {} }}", p2.x, p2.y); println!("Pythagoras Distance: {}", pythagoras); println!("Pythagoras Squared Distance: {}", pythagoras_squared); println!("Manhattan Distance: {}", manhattan); println!("Chebyshev Distance: {}", chebyshev); } ``` -------------------------------- ### Add bracket-lib with Alternative Rendering Backend in Cargo.toml Source: https://context7.com/amethyst/bracket-lib/llms.txt This example shows how to configure bracket-lib to use an alternative rendering backend, like 'webgpu'. It requires disabling default features and explicitly specifying the desired feature. ```toml [dependencies] bracket-lib = { version = "~0.8", default-features = false, features = ["webgpu"] } ``` -------------------------------- ### Plot Lines Using Vector Math Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/ex_geometry.md This example utilizes vector math for plotting lines, offering an alternative to Bresenham's algorithm. It can be faster on certain CPUs for extensive line plotting due to floating-point calculations, though the line quality might differ. ```rust use bracket_geometry::prelude::Point; use bracket_geometry::algorithms::vector_line; fn main() { let mut display = vec![vec![' '; 80]; 50]; let start = Point::new(5, 5); let end = Point::new(40, 45); for p in vector_line::vector_line(start, end) { if p.x >= 0 && p.x < 80 && p.y >= 0 && p.y < 50 { display[p.y as usize][p.x as usize] = '*'; } } for row in display.iter() { for cell in row.iter() { print!("{}", cell); } println!(""); } } ``` -------------------------------- ### Build WASM Example with Cargo Source: https://github.com/amethyst/bracket-lib/blob/master/rltk/README.md Compiles a Rust example project to the `wasm32-unknown-unknown` target in release mode, preparing it for WebAssembly. ```bash cargo build --example ex01-helloworld --target wasm32-unknown-unknown --release ``` -------------------------------- ### 2D Circle Plotting with Bresenham's Algorithm Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/README.md Illustrates how to implement Bresenham's circle algorithm from the bracket-geometry crate. This example shows iterating through the points that form a circle centered at a given point with a specified radius. ```rust use bracket_geometry::prelude::*; for point in BresenhamCircle::new(Point::new(10,10), 5) { println!("{:?}", point); } ``` -------------------------------- ### Build Terminal Context with Title and Specific Font Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/consoles.md This example shows how to build a terminal context using `RltkBuilder` (aliased as `BTermBuilder`), setting a window title, specifying a font with its dimensions, and configuring a sparse console. It also demonstrates disabling vertical synchronization. ```rust let mut context = RltkBuilder::simple(80, 60) .unwrap() .with_title("Roguelike Tutorial") .with_font("vga8x16.png", 8, 16) .with_sparse_console(80, 30, "vga8x16.png") .with_vsync(false) .build()?; ``` -------------------------------- ### Draw Lines with Bresenham's Line Algorithm Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/ex_geometry.md Illustrates Bresenham's Line algorithm for drawing a line on a console grid. This algorithm is efficient for raster graphics as it uses only integer arithmetic. ```rust use bracket_geometry::prelude::{Point, BresenhamLine}; fn main() { let mut display = vec![vec![' '; 80]; 50]; let start = Point::new(10, 10); let end = Point::new(30, 20); for p in BresenhamLine::new(start, end) { if p.x >= 0 && p.x < 80 && p.y >= 0 && p.y < 50 { display[p.y as usize][p.x as usize] = '*'; } } for row in display.iter() { for cell in row.iter() { print!("{}", cell); } println!(""); } } ``` -------------------------------- ### Plot Gridded Circles with BresenhamCircle Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/ex_geometry.md Demonstrates the usage of `BresenhamCircle` for efficiently plotting gridded circles with compensation for grid locations. This method is optimized for rendering on discrete grids. ```rust use bracket_geometry::prelude::BresenhamCircle; fn main() { let mut display = vec![vec![' '; 80]; 50]; for p in BresenhamCircle::new(10, 10, 5) { display[p.y as usize][p.x as usize] = '*'; } for row in display.iter() { for cell in row.iter() { print!("{}", cell); } println!(""); } } ``` -------------------------------- ### Perform A* Pathfinding Search Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-pathfinding/README.md This code snippet demonstrates how to perform an A* pathfinding search using the bracket-lib. It requires the start and end points (as indices) and a reference to the map implementing the necessary traits. The result indicates success and contains the path steps. ```rust let path = a_star_search( map.point2d_to_index(START_POINT), map.point2d_to_index(END_POINT), &map ); if path.success { // Do something with it! path.steps has the whole path. } ``` -------------------------------- ### 2D Line Plotting with Bresenham and Vector Algorithms Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/README.md Demonstrates how to use the bracket-geometry crate for 2D line plotting. It shows examples of generating a line as a vector of points using Bresenham's algorithm and iterating through points with Bresenham's algorithm. The Vector algorithm is also mentioned as an alternative. ```rust use bracket_geometry::prelude::*; let bresenham_line = line2d(LineAlg::Bresenham, Point::new(1,1), Point::new(5,5)); println!("{:?}", bresenham_line); ``` ```rust use bracket_geometry::prelude::*; for point in Bresenham::new(Point::new(1,1), Point::new(5,5)) { println!("{:?}", point); } ``` -------------------------------- ### Initialize Game State and Run Main Loop Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/consoles.md Demonstrates how to initialize the Bracket Terminal context, create a game state structure that implements `GameState`, and start the main game loop. The `tick` function within the game state is called every frame for game logic and rendering. ```rust use bracket_lib::prelude::*; struct State {} impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { ctx.print(1, 1, "Hello Bracket World"); } } fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Minimal Bracket World") .build()?; let gs: State = State {}; main_loop(context, gs) } ``` -------------------------------- ### Initialize Simple 80x50 Console with Title Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/consoles.md Initializes the Bracket Terminal with a default 80x50 simple console and sets the window title. This is a common starting point for new projects using the library. It requires the 'bevy_render' and 'bevy_window' features. ```rust fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Minimal Bracket World") .build()?; // ... rest of your application logic Ok(()) } ``` -------------------------------- ### Implement BaseMap get_available_exits for Pathfinding Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-pathfinding/README.md This snippet shows the implementation of `get_available_exits` for the `BaseMap` trait, required by A* and Dijkstra algorithms. It returns a list of valid neighboring tiles and the cost to move to them. The example checks cardinal directions. ```rust impl BaseMap for Map { fn is_opaque(&self, idx: usize) -> bool { self.tiles[idx as usize] == '#' } fn get_available_exits(&self, idx: usize) -> SmallVec<[(usize, f32); 10]> { let mut exits = SmallVec::new(); let location = self.index_to_point2d(idx); if let Some(idx) = self.valid_exit(location, Point::new(-1, 0)) { exits.push((idx, 1.0)) } if let Some(idx) = self.valid_exit(location, Point::new(1, 0)) { exits.push((idx, 1.0)) } if let Some(idx) = self.valid_exit(location, Point::new(0, -1)) { exits.push((idx, 1.0)) } if let Some(idx) = self.valid_exit(location, Point::new(0, 1)) { exits.push((idx, 1.0)) } exits } } ``` -------------------------------- ### Sweep Angles and Project Points with Bresenham Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/ex_geometry.md Demonstrates sweeping angles from 0 to 360 degrees using `bracket-geometry`'s angle functions. It then projects a point along each angle and draws a line to the projected point using Bresenham's algorithm. ```rust use bracket_geometry::prelude::{Point, BresenhamLine}; use bracket_geometry::algorithms::angle; fn main() { let mut display = vec![vec![' '; 80]; 50]; let center = Point::new(40, 25); let radius = 15; for deg in (0..360).step_by(5) { let rad = angle::degrees_to_radians(deg as f32); let end_point = Point::new( center.x + (rad.cos() * radius as f32) as i32, center.y + (rad.sin() * radius as f32) as i32, ); for p in BresenhamLine::new(center, end_point) { if p.x >= 0 && p.x < 80 && p.y >= 0 && p.y < 50 { display[p.y as usize][p.x as usize] = '*'; } } } for row in display.iter() { for cell in row.iter() { print!("{}", cell); } println!(""); } } ``` -------------------------------- ### Using the WebGPU Rendering Backend Source: https://github.com/amethyst/bracket-lib/blob/master/README.md To use the WebGPU rendering backend, disable default features and explicitly enable the 'webgpu' feature. This backend supports Vulkan, Metal, and WebGPU, offering modern graphics capabilities. ```toml [dependencies.bracket-lib] version = "~0.8" default-features = false features = ["webgpu"] ``` -------------------------------- ### Minimal Hello World Terminal App Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/hello_terminal.md Creates a basic terminal application that displays 'Hello Bracket World'. It demonstrates the essential structure for a bracket-lib application, including setting up the game state and the main loop. ```rust use bracket_lib::prelude::*; struct State {} impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { ctx.print(1, 1, "Hello Bracket World"); } } fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Minimal Bracket World") .build()?; let gs: State = State {}; main_loop(context, gs) } ``` -------------------------------- ### Color Management with RGB and HSV in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Illustrates color manipulation using the bracket-color crate, covering creation of colors via named constants, RGB floats, RGB bytes, and hex codes. It demonstrates color interpolation, conversion between RGB and HSV, grayscale conversion, and basic arithmetic operations on colors. A ColorPair is also shown for foreground/background settings. Dependencies include `bracket_color::prelude::*`. ```rust use bracket_color::prelude::*; // Create colors using various methods let red = RGB::named(RED); let green = RGB::from_f32(0.0, 1.0, 0.0); let blue = RGB::from_u8(0, 0, 255); let magenta = RGB::from_hex("#FF00FF").expect("Invalid hex"); // Color interpolation (lerp) let col1 = RGB::named(CYAN); let col2 = RGB::named(YELLOW); let percent = 0.5; let interpolated = col1.lerp(col2, percent); // Convert to HSV for hue manipulation let hsv = red.to_hsv(); let hsv_modified = HSV::from_f32(hsv.h + 30.0, hsv.s, hsv.v); let modified_rgb = hsv_modified.to_rgb(); // Grayscale conversions let grey = blue.to_greyscale(); let desaturated = green.desaturate(); // Arithmetic operations let darker = red * 0.5; let lighter = blue + RGB::from_f32(0.2, 0.2, 0.2); let mixed = red + green; // ColorPair for foreground/background let pair = ColorPair::new(RGB::named(WHITE), RGB::named(BLACK)); ``` -------------------------------- ### Using the Curses Rendering Backend Source: https://github.com/amethyst/bracket-lib/blob/master/README.md To use the Curses rendering backend (ncurses/pdcurses), disable default features and enable the 'curses' feature. This is suitable for cross-platform terminal applications. ```toml [dependencies.bracket-lib] version = "~0.8" default-features = false features = ["curses"] ``` -------------------------------- ### Terminal Rendering and Game Loop in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Demonstrates setting up a game loop and rendering a virtual console with text, boxes, and colored elements using bracket-terminal. It includes input handling for terminal size and title, and utilizes a custom state struct to manage game logic within the `tick` function. Dependencies include `bracket-lib::prelude::*` for core functionalities. ```rust use bracket_lib::prelude::*; struct State { y: i32, going_down: bool, } impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { // Clear the console ctx.cls(); // Print colored text let fg = RGB::named(CYAN); let bg = RGB::named(BLACK); ctx.print_color(1, self.y, fg, bg, "♫ Hello World ☺"); // Draw UI elements ctx.draw_box(39, 0, 20, 3, RGB::named(WHITE), RGB::named(BLACK)); // Pretty printing with inline color tags ctx.printer( 40, 49, "#[blue]Hello #[pink]Bracket#[] world.", TextAlign::Center, Some(RGBA::from_u8(200, 200, 200, 255)) ); // Display FPS ctx.printer( 58, 1, &format!("#[pink]FPS: #[]{{}}", ctx.fps), TextAlign::Right, None ); // Update state if self.going_down { self.y += 1; if self.y > 48 { self.going_down = false; } } else { self.y -= 1; if self.y < 2 { self.going_down = true; } } } } fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Bracket World") .build()?; let gs = State { y: 1, going_down: true }; // Register color palette for pretty printing register_palette_color("blue", RGB::named(BLUE)); register_palette_color("pink", RGB::named(MAGENTA)); main_loop(context, gs) } ``` -------------------------------- ### WGPU Resolver Configuration Source: https://github.com/amethyst/bracket-lib/blob/master/README.md When using the 'webgpu' backend, you might need to add 'resolver = 2' to your Cargo.toml. This is a requirement for WGPU to correctly handle platform selection. ```toml resolver = "2" ``` -------------------------------- ### Calculate Field of View Set Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-pathfinding/README.md This code snippet shows how to compute the Field of View (FOV) set using bracket-lib. It requires a starting point, the desired range, and a reference to the map. The `is_opaque` method on the map is essential for this function. ```rust let fov = field_of_view_set(START_POINT, 6, &map); ``` -------------------------------- ### Dijkstra Maps for Multiple Targets in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Demonstrates how to create and utilize Dijkstra maps for finding paths to multiple goals simultaneously using the bracket-pathfinding library. It covers setting up the map, defining search targets, generating the flow map, and accessing distance information. ```rust use bracket_pathfinding::prelude::*; use bracket_geometry::prelude::*; let map = Map { tiles: vec!['.'; 100], width: 10, height: 10, }; // Define multiple search targets let mut search_targets: Vec = Vec::new(); search_targets.push(map.point2d_to_index(Point::new(2, 2))); search_targets.push(map.point2d_to_index(Point::new(7, 7))); search_targets.push(map.point2d_to_index(Point::new(9, 2))); // Create Dijkstra map with max distance 1024.0 let flow_map = DijkstraMap::new( map.width as usize, map.height as usize, &search_targets, &map, 1024.0 ); // Access distances directly let current_pos = map.point2d_to_index(Point::new(5, 5)); let distance = flow_map.map[current_pos]; println!("Distance to nearest target: {}", distance); // Find best exit toward targets if let Some(exit) = flow_map.find_lowest_exit(current_pos, &map) { let next_point = map.index_to_point2d(exit); println!("Move to: {:?}", next_point); } ``` -------------------------------- ### Geometric Primitives and Line Drawing in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Demonstrates the creation and manipulation of points and rectangles, along with line and circle drawing algorithms using Bresenham and vector methods. It also includes distance calculations. ```rust use bracket_geometry::prelude::*; // Create and manipulate points let p1 = Point::new(1, 1); let p2 = Point::new(5, 5); let p3 = Point::zero(); let p4 = Point::from_tuple((10, 20)); // Rectangle operations let rect = Rect::with_size(0, 0, 10, 10); let center = rect.center(); let is_inside = rect.point_in_rect(Point::new(5, 5)); let intersects = rect.intersect(&Rect::with_size(8, 8, 10, 10)); // Iterate through rectangle points rect.for_each(|point| { println!("Point in rect: {:?}", point); }); // Bresenham line drawing let line: Vec = Bresenham::new(Point::new(0, 6), Point::new(6, 0)) .collect(); for (i, point) in line.iter().enumerate() { println!("Line point {}: {:?}", i, point); } // Vector-based line (faster, no corner smoothing) let vector_line = line2d(LineAlg::Vector, Point::new(1, 1), Point::new(10, 10)); // Bresenham circle let circle: Vec = BresenhamCircle::new(Point::new(10, 10), 5) .collect(); // Distance calculations let pythagoras = DistanceAlg::Pythagoras.distance2d(p1, p2); let manhattan = DistanceAlg::Manhattan.distance2d(p1, p2); let chebyshev = DistanceAlg::Chebyshev.distance2d(p1, p2); let squared = DistanceAlg::PythagorasSquared.distance2d(p1, p2); ``` -------------------------------- ### Enabling Serde Serialization Support Source: https://github.com/amethyst/bracket-lib/blob/master/README.md This feature flag allows various bracket-lib sub-systems to support serialization and de-serialization using the Serde library. This is crucial for saving and loading game state. ```toml [dependencies.bracket-lib] version = "~0.8" features = ["serde"] ``` -------------------------------- ### Bouncy Hello World Terminal App Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/hello_terminal.md An interactive terminal application showcasing bracket-lib's features like state management, color manipulation, text alignment, and drawing. The 'Hello Bracket World' text bounces vertically on the screen. ```rust use bracket_lib::prelude::*; struct State { y: i32, going_down: bool, } impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { let col1 = RGB::named(CYAN); let col2 = RGB::named(YELLOW); let percent: f32 = self.y as f32 / 50.0; let fg = col1.lerp(col2, percent); ctx.cls(); ctx.printer( 40, 49, "#[blue]Hello #[pink]Bracket#[] world.", TextAlign::Center, Some(RGBA::from_u8(200, 200, 200, 255)), ); ctx.print_color( 1, self.y, fg, RGB::named(BLACK), "♫ ♪ Hello Bracket World ☺", ); if self.going_down { self.y += 1; if self.y > 48 { self.going_down = false; } } else { self.y -= 1; if self.y < 2 { self.going_down = true; } } ctx.draw_box(39, 0, 20, 3, RGB::named(WHITE), RGB::named(BLACK)); ctx.printer( 58, 1, &format!("#[pink]FPS: #[]{{}}", ctx.fps), TextAlign::Right, None, ); ctx.printer( 58, 2, &format!("#[pink]Frame Time: #[]{{}} ms", ctx.frame_time_ms), TextAlign::Right, None, ); } } fn main() -> BError { let context = BTermBuilder::simple80x50() .with_title("Hello Bracket World") .build()?; let gs: State = State { y: 1, going_down: true, }; register_palette_color("blue", RGB::named(BLUE)); register_palette_color("pink", RGB::named(MAGENTA)); main_loop(context, gs) } ``` -------------------------------- ### Procedural Noise Generation in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Illustrates the use of FastNoise algorithms from the bracket-noise library for generating procedural content like terrain heightmaps. It covers configuring various noise types (Simplex Fractal, Perlin Fractal, White Noise, Value, Cellular) and generating noise values. ```rust use bracket_noise::prelude::*; use bracket_random::prelude::*; // Create and configure noise generator let mut rng = RandomNumberGenerator::new(); let mut noise = FastNoise::seeded(rng.next_u64()); // Configure Simplex Fractal noise noise.set_noise_type(NoiseType::SimplexFractal); noise.set_fractal_type(FractalType::FBM); noise.set_fractal_octaves(5); noise.set_fractal_gain(0.6); noise.set_fractal_lacunarity(2.0); noise.set_frequency(2.0); // Generate heightmap let width = 80; let height = 50; let mut heightmap = vec![vec![0.0; width]; height]; for y in 0..height { for x in 0..width { let noise_value = noise.get_noise( (x as f32) / 160.0, (y as f32) / 100.0 ); heightmap[y][x] = noise_value; // Noise values range from -1.0 to 1.0 if noise_value < -0.5 { println!("Water"); } else if noise_value < 0.0 { println!("Beach"); } else if noise_value < 0.5 { println!("Grass"); } else { println!("Mountain"); } } } // Perlin Fractal noise let mut perlin = FastNoise::new(); perlin.set_noise_type(NoiseType::PerlinFractal); perlin.set_fractal_octaves(4); let value = perlin.get_noise(10.5, 20.3); // White noise let mut white = FastNoise::new(); white.set_noise_type(NoiseType::WhiteNoise); let random_value = white.get_noise(x as f32, y as f32); // Value noise (smoother than white noise) let mut value_noise = FastNoise::new(); value_noise.set_noise_type(NoiseType::Value); let smooth_value = value_noise.get_noise(5.0, 5.0); // Cellular noise let mut cellular = FastNoise::new(); cellular.set_noise_type(NoiseType::Cellular); cellular.set_cellular_distance_function(CellularDistanceFunction::Euclidean); cellular.set_cellular_return_type(CellularReturnType::Distance); let cell_value = cellular.get_noise(8.0, 8.0); ``` -------------------------------- ### Create Dijkstra Map Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-pathfinding/README.md This snippet illustrates the creation of a Dijkstra map using bracket-lib. It requires specifying the map dimensions, a vector of target tile indices, and a reference to the map. A cost parameter is also provided. ```rust let mut search_targets : Vec = Vec::new(); search_targets.push(map.point2d_to_index(START_POINT)); search_targets.push(map.point2d_to_index(END_POINT)); let flow_map = DijkstraMap::new(MAP_WIDTH, MAP_HEIGHT, &search_targets, &map, 1024.0); ``` -------------------------------- ### Using the Crossterm Rendering Backend Source: https://github.com/amethyst/bracket-lib/blob/master/README.md To use the Crossterm rendering backend for terminal-based applications, disable default features and enable the 'crossterm' feature. This provides a robust terminal interface. ```toml [dependencies.bracket-lib] version = "~0.8" default-features = false features = ["crossterm"] ``` -------------------------------- ### Project Dependency Update Command Source: https://github.com/amethyst/bracket-lib/blob/master/README.md If you encounter issues with dependencies, running 'cargo update' may resolve them by fetching the latest compatible versions of your project's dependencies. ```bash cargo update ``` -------------------------------- ### A-Star Pathfinding with Custom Map in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Implements A* pathfinding on a custom map structure by defining traits required by the pathfinding algorithm. This includes defining map dimensions, checking for opaque tiles, and providing available exits. ```rust use bracket_pathfinding::prelude::*; use bracket_geometry::prelude::*; use smallvec::SmallVec; struct Map { tiles: Vec, width: i32, height: i32, } impl Algorithm2D for Map { fn dimensions(&self) -> Point { Point::new(self.width, self.height) } } impl BaseMap for Map { fn is_opaque(&self, idx: usize) -> bool { self.tiles[idx] == '#' } fn get_available_exits(&self, idx: usize) -> SmallVec<[(usize, f32); 10]> { let mut exits = SmallVec::new(); let location = self.index_to_point2d(idx); // Check cardinal directions if let Some(idx) = self.valid_exit(location, Point::new(-1, 0)) { exits.push((idx, 1.0)); } if let Some(idx) = self.valid_exit(location, Point::new(1, 0)) { exits.push((idx, 1.0)); } if let Some(idx) = self.valid_exit(location, Point::new(0, -1)) { exits.push((idx, 1.0)); } if let Some(idx) = self.valid_exit(location, Point::new(0, 1)) { exits.push((idx, 1.0)); } exits } fn get_pathing_distance(&self, idx1: usize, idx2: usize) -> f32 { DistanceAlg::Pythagoras.distance2d( self.index_to_point2d(idx1), self.index_to_point2d(idx2) ) } } // Perform A* pathfinding let map = Map { tiles: vec!['.'; 100], width: 10, height: 10 }; let start = map.point2d_to_index(Point::new(0, 0)); let end = map.point2d_to_index(Point::new(9, 9)); let path = a_star_search(start, end, &map); if path.success { println!("Path found with {} steps", path.steps.len()); for step in &path.steps { let point = map.index_to_point2d(*step); println!("Step: {:?}", point); } } else { println!("No path found"); } ``` -------------------------------- ### Initialize a Fancy Console Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/fancy.md Initializes a simple 80x50 fancy console with a specified font and title. This is part of the BTermBuilder chain for creating game contexts. V-sync is disabled. ```rust let mut context = BTermBuilder::simple80x50() .with_fancy_console(80, 50, "terminal8x8.png") .with_title("Bracket Terminal - Fancy Consoles") .with_vsync(false) .build()?; ``` -------------------------------- ### Add Complete bracket-lib to Cargo.toml Source: https://context7.com/amethyst/bracket-lib/llms.txt This snippet shows how to add the entire bracket-lib toolkit as a dependency in your project's Cargo.toml file. It specifies a version constraint for bracket-lib. ```toml [dependencies] bracket-lib = "~0.8" ``` -------------------------------- ### Implement Algorithm2D Dimensions for Map Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-pathfinding/README.md This snippet shows how to implement the `dimensions` method for the `Algorithm2D` trait, which is necessary for the library to understand the map's size. It requires defining the map's width and height. ```rust impl Algorithm2D for Map { fn dimensions(&self) -> Point { Point::new(MAP_WIDTH, MAP_HEIGHT) } } ``` -------------------------------- ### Distance Calculations Between Points Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/README.md Shows how to calculate distances between two points using various algorithms provided by the bracket-geometry crate. It demonstrates Pythagoras, PythagorasSquared, Manhattan, and Chebyshev distance calculations for 2D points. ```rust use bracket_geometry::prelude::*; println!("{:?}", DistanceAlg::Pythagoras.distance2d(Point::new(0,0), Point::new(5,5))); println!("{:?}", DistanceAlg::PythagorasSquared.distance2d(Point::new(0,0), Point::new(5,5))); println!("{:?}", DistanceAlg::Manhattan.distance2d(Point::new(0,0), Point::new(5,5))); println!("{:?}", DistanceAlg::Chebyshev.distance2d(Point::new(0,0), Point::new(5,5))); ``` -------------------------------- ### Saving Console State to File Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/consoles_print.md Allows saving the current state of a console to different file formats. `to_xp_layer` saves the console as a REX Paint file, preserving colors and characters. `ctx.screenshot(filename)` captures the console's content as a PNG image. ```rust to_xp_layer("output.xp"); ctx.screenshot("screenshot.png"); ``` -------------------------------- ### Adding bracket-lib to Cargo.toml Source: https://github.com/amethyst/bracket-lib/blob/master/README.md This snippet shows how to include the bracket-lib dependency in your project's Cargo.toml file. Ensure you are using a compatible version, such as '~0.8'. ```toml [dependencies] bracket-lib = "~0.8" ``` -------------------------------- ### Configuring RLTK with Different Backends Source: https://github.com/amethyst/bracket-lib/blob/master/rltk/README.md This shows how to configure RLTK to use different rendering backends by leveraging Cargo feature flags. By default, it uses OpenGL. To use other backends like 'curses', 'crossterm', or 'webgpu', you need to disable default features and explicitly enable the desired feature. This affects rendering capabilities and dependencies. ```bash # Using ncurses backend: cargo run --example curses14-dwarfmap --features curses --no-default-features # Using crossterm backend: cargo run --example crossterm18-textsprites --no-default-features --features="crossterm" # Using WebGPU backend: cargo run --example av13-textblock --no-default-features --features wgpu ``` -------------------------------- ### Add bracket-lib with Feature Flags in Cargo.toml Source: https://context7.com/amethyst/bracket-lib/llms.txt This snippet illustrates how to add bracket-lib with specific feature flags enabled. This allows customization of functionality, such as including 'serde' for serialization, 'specs' for ECS integration, or 'threaded' for multi-threading. ```toml [dependencies] bracket-lib = { version = "~0.8", features = ["serde", "specs", "threaded"] } ``` -------------------------------- ### Embed and Link Resources with bracket-embedding in Rust Source: https://github.com/amethyst/bracket-lib/blob/master/bracket-embedding/README.md This Rust code demonstrates how to use the `embedded_resource!` macro to declare an embedded resource and the `link_resource!` macro to link it, making it accessible within the program. This is particularly useful for embedding assets like configuration files or scripts in WASM builds. ```rust use bracket_embedding::prelude::*; embedded_resource!(SOURCE_FILE, "embedding.rs"); fn main() { // This helper macro links the above embedding, allowing it to be accessed as a resource from various parts of the program. link_resource!(SOURCE_FILE, "embedding.rs"); } ``` -------------------------------- ### Add Stable Bracket-lib Version (TOML) Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/linking.md Include the latest stable release of the bracket-lib by adding the specified dependency to your project's Cargo.toml file. This is the recommended approach for most projects. ```toml [dependencies] bracket-lib = "0.8" ``` -------------------------------- ### Link to Bracket-lib GitHub Version (TOML) Source: https://github.com/amethyst/bracket-lib/blob/master/manual/src/linking.md Incorporate the development version of bracket-lib directly from its GitHub repository by adding this configuration to your Cargo.toml. This allows access to the latest features but may be less stable. ```toml [dependencies] bracket-lib = { git = "https://github.com/amethyst/bracket-lib.git" } ``` -------------------------------- ### RPG-Style Dice Rolling in Rust Source: https://context7.com/amethyst/bracket-lib/llms.txt Explains how to use the bracket-random library for rolling dice in RPG-style notation. It covers basic dice rolls, parsing complex dice strings, generating random numbers, and making random selections from slices. ```rust use bracket_random::prelude::*; // Create random number generator let mut rng = RandomNumberGenerator::new(); // Seeded RNG for reproducible results let mut seeded_rng = RandomNumberGenerator::seeded(12345); // Roll dice let d6 = rng.roll_dice(1, 6); // 1d6 let three_d6 = rng.roll_dice(3, 6); // 3d6 let d20_plus_5 = rng.roll_dice(1, 20) + 5; // Parse and roll dice strings let result = rng.roll_str("3d6+12").expect("Invalid dice string"); let damage = rng.roll_str("2d8-1").expect("Invalid dice string"); // Parse dice string to get components let dice_type = parse_dice_string("3d6-4").expect("Invalid format"); println!("Number of dice: {}", dice_type.n_dice); println!("Die type: {}", dice_type.die_type); println!("Bonus: {}", dice_type.bonus); // Random number generation let random_u64 = rng.next_u64(); let random_f64: f64 = rng.rand(); let in_range = rng.range(1, 100); // Random selection from slices let treasure = vec!["Gold", "Silver", "Bronze", "Copper"]; if let Some(item) = rng.slice(&treasure) { println!("Found: {}", item); } // Random index selection if let Some(idx) = rng.slice_index(&treasure) { println!("Index: {}, Item: {}", idx, treasure[idx]); } // Distribution testing let mut results = vec![0; 18]; for _ in 0..10000 { let roll = rng.roll_dice(3, 6); results[roll as usize - 3] += 1; } ``` -------------------------------- ### Enabling Multi-threading Source: https://github.com/amethyst/bracket-lib/blob/master/README.md The 'threaded' feature flag enables multi-threading on certain bracket-lib sub-systems. This can improve performance by utilizing multiple CPU cores for computationally intensive tasks. ```toml [dependencies.bracket-lib] version = "~0.8" features = ["threaded"] ```