main.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Argument Parser open source project
  4. //
  5. // Copyright (c) 2020 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. import ArgumentParser
  12. struct RollOptions: ParsableArguments {
  13. @Option(help: ArgumentHelp("Rolls the dice <n> times.", valueName: "n"))
  14. var times = 1
  15. @Option(
  16. help: ArgumentHelp(
  17. "Rolls an <m>-sided dice.",
  18. discussion:
  19. "Use this option to override the default value of a six-sided die.",
  20. valueName: "m"))
  21. var sides = 6
  22. @Option(help: "A seed to use for repeatable random generation.")
  23. var seed: Int? = nil
  24. @Flag(name: .shortAndLong, help: "Show all roll results.")
  25. var verbose = false
  26. }
  27. // If you prefer writing in a "script" style, you can call `parseOrExit()` to
  28. // parse a single `ParsableArguments` type from command-line arguments.
  29. let options = RollOptions.parseOrExit()
  30. let seed = options.seed ?? .random(in: .min ... .max)
  31. var rng = SplitMix64(seed: UInt64(truncatingIfNeeded: seed))
  32. let rolls = (1...options.times).map { _ in
  33. Int.random(in: 1...options.sides, using: &rng)
  34. }
  35. if options.verbose {
  36. for (number, roll) in zip(1..., rolls) {
  37. print("Roll \(number): \(roll)")
  38. }
  39. }
  40. print(rolls.reduce(0, +))