Created
September 27, 2013 01:06
-
-
Save llasram/6722857 to your computer and use it in GitHub Desktop.
Rock, Paper, Scissors, as expressed in `clara-rules`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns ropasc.core | |
(:refer-clojure :exclude [==]) | |
(:require [clara.rules :as cr :refer [defrule defquery ==]])) | |
(defrecord Action [player choice]) | |
(defrecord Victory [winner loser]) | |
(defrecord Tie [player1 player2]) | |
(defrule paper-beats-rock | |
[Action (== ?winner player) (= :paper choice)] | |
[Action (== ?loser player) (= :rock choice)] | |
=> | |
(cr/insert! (->Victory ?winner ?loser))) | |
(defrule rock-beats-scissors | |
[Action (== ?winner player) (= :rock choice)] | |
[Action (== ?loser player) (= :scissors choice)] | |
=> | |
(cr/insert! (->Victory ?winner ?loser))) | |
(defrule scissors-beat-paper | |
[Action (== ?winner player) (= :scissors choice)] | |
[Action (== ?loser player) (= :paper choice)] | |
=> | |
(cr/insert! (->Victory ?winner ?loser))) | |
(defrule same-action-ties | |
[Action (== ?player1 player) (== ?choice1 choice)] | |
[Action (== ?player2 player) (== ?choice2 choice)] | |
[:test (and (= ?choice1 ?choice2) (< ?player1 ?player2))] | |
=> | |
(cr/insert! (->Tie ?player1 ?player2))) | |
(defquery query-results | |
[] | |
[:or [?victory <- Victory] | |
[?tie <- Tie]]) | |
(defn run-game | |
[& choices] | |
(let [actions (map ->Action (range) choices) | |
session (cr/mk-session 'ropasc.core)] | |
(-> (apply cr/insert session actions) | |
(cr/fire-rules) | |
(cr/query query-results)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment