this repo has no description
at main 2.4 kB view raw
1const std = @import("std"); 2const hex = @import("hex.zig"); 3const tst = std.testing; 4 5// Generate hexagon-shaped map with given radius (N rings around center) 6// Uses axial coords: |q|<=N, |r|<=N, |q+r|<=N 7pub fn generateHexWorld(comptime N: i32, outer_radius: f32, allocator: std.mem.Allocator) !std.ArrayListUnmanaged(hex.Cell) { 8 var cells = std.ArrayListUnmanaged(hex.Cell){}; 9 10 var q: i32 = -N; 11 while (q <= N) : (q += 1) { 12 const r1 = @max(-N, -q - N); 13 const r2 = @min(N, -q + N); 14 var r: i32 = r1; 15 while (r <= r2) : (r += 1) { 16 try cells.append(allocator, hex.new_hex(outer_radius, hex.Axial.init(q, r))); 17 } 18 } 19 20 return cells; 21} 22 23// Template-based generation using axial coords 24// Template indexed by [r][q] where r,q range from -N to +N 25// Template size is (2*N+1) x (2*N+1), center is at [N][N] 26pub fn generateFromTemplate(comptime N: i32, template: *const [2 * N + 1][2 * N + 1]u1, outer_radius: f32, allocator: std.mem.Allocator) !std.ArrayListUnmanaged(hex.Cell) { 27 var cells = std.ArrayListUnmanaged(hex.Cell){}; 28 29 var q: i32 = -N; 30 while (q <= N) : (q += 1) { 31 var r: i32 = -N; 32 while (r <= N) : (r += 1) { 33 const ti_r: usize = @intCast(r + N); 34 const ti_q: usize = @intCast(q + N); 35 if (template[ti_r][ti_q] == 1) { 36 try cells.append(allocator, hex.new_hex(outer_radius, hex.Axial.init(q, r))); 37 } 38 } 39 } 40 41 return cells; 42} 43 44// Old template-based generation (offset coords) 45pub fn generateWorld(comptime H: usize, comptime W: usize, template: *const [H][W]u1, outer_radius: f32) [H][W]?hex.Cell { 46 var grid: [H][W]?hex.Cell = undefined; 47 48 for (0..H) |row| { 49 for (0..W) |col| { 50 if (template[row][col] == 1) { 51 const offset = hex.Offset{ .col = @intCast(col), .row = @intCast(row) }; 52 grid[row][col] = hex.new_hex(outer_radius, offset.toAxial()); 53 } else { 54 grid[row][col] = null; 55 } 56 } 57 } 58 59 return grid; 60} 61 62test "generateWorld creates grid from template" { 63 const template = [3][3]u1{ 64 .{ 1, 1, 0 }, 65 .{ 1, 0, 1 }, 66 .{ 0, 1, 1 }, 67 }; 68 const grid = generateWorld(3, 3, &template, 50.0); 69 try tst.expect(grid[0][0] != null); 70 try tst.expect(grid[0][2] == null); 71 try tst.expect(grid[1][1] == null); 72}