diff --git a/project.clj b/project.clj index c0672f6..247efa9 100644 --- a/project.clj +++ b/project.clj @@ -4,7 +4,8 @@ :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.8.0"] - [clojail "1.0.6"]] + [clojail "1.0.6"] + [org.clojure/core.match "0.3.0-alpha5"]] :main ^:skip-aot clojurebot.core :target-path "target/%s" :profiles {:uberjar {:aot :all}}) diff --git a/src/clojurebot/core.clj b/src/clojurebot/core.clj index aa0be89..3cbe681 100644 --- a/src/clojurebot/core.clj +++ b/src/clojurebot/core.clj @@ -7,6 +7,7 @@ [clojail.testers :as testers] [clojure.edn :as edn] [clojure.java.io :as io] + [clojure.core.match :refer [match]] [clojurebot.irc :as irc] [clojure.string :as string])) @@ -103,16 +104,33 @@ (str "Error: No symbol for " sym-name)) "Error: No arguments provided"))) -(reg-commend +(defn- parse-number-of-dice + [n] + (if (nil? n) [:ok 1] + (try + (let [result (Integer/parseInt n)] + (cond + (< result 0) [:error "You can't roll a negative amount of dice, man"] + (= result 0) [:error "You want to roll zero dice? Okay, you rolled nothing..."] + :else [:ok result])) + (catch java.lang.NumberFormatException _ + [:error (str n " is not a number! Please give me a number of dice to roll.")]) + (catch java.lang.ClassCastException _ + [:error (str "I'm expecting a number-string as input, but you've given me " n ", with " (type n))])))) + +(reg-command "d20" (fn [n] - (if (< n 0) - "You can't roll a negative amount of dice, man" - (str "You rolled a " - (->> #(+ (rand-int 20) 1) - (repeatedly) - (take n) - (string/join " and a ")))))) + (match (parse-number-of-dice n) + [:error err] err + [:ok x] (let [nums (->> #(+ (rand-int 20) 1) + (repeatedly) + (take x))] + (str "You rolled " + (string/join " and " nums) + (if (> x 1) + (str ", totalling " (reduce + 0 nums))))))) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Entry point