root.zig (1141B)
1 const std = @import("std"); 2 const testing = std.testing; 3 4 pub fn dicer(args: anytype, wtr: anytype) !void { 5 doDicer(args, wtr) catch |e| switch (e) { 6 error.MissingArg, error.InvalidCharacter => { 7 try printUsage(wtr); 8 return; 9 }, 10 else => return e, 11 }; 12 } 13 14 fn doDicer(args: anytype, wtr: anytype) !void { 15 const dice_str = args.next() orelse return error.MissingArg; 16 var spl = std.mem.splitScalar(u8, dice_str, 'd'); 17 const count = try std.fmt.parseInt(u64, spl.first(), 10); 18 const sides = try std.fmt.parseInt(u64, spl.next() orelse "6", 10); 19 20 try wtr.writeAll("Dice roll: "); 21 var total: u64 = 0; 22 for (0..count) |_| { 23 const res = roll(sides); 24 try std.fmt.format(wtr, "{} ", .{res}); 25 total += res; 26 } 27 try std.fmt.format(wtr, " total: {}", .{total}); 28 try wtr.writeByte('\n'); 29 } 30 31 fn roll(dsize: u64) u64 { 32 return (std.crypto.random.int(u64) % dsize) + 1; 33 } 34 35 fn printUsage(wtr: anytype) !void { 36 try std.fmt.format(wtr, 37 \\Usage: 38 \\ dicer XdY 39 \\ 40 \\Rolls X dice with Y 41 \\ 42 , .{}); 43 }