Created
June 10, 2017 15:51
-
-
Save msszczep/31584e300aeda33bd47838d76f0efddc to your computer and use it in GitHub Desktop.
Faceoff: America's favorite new card game -- in Clojure
This file contains 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 faceoff.core) | |
;; Make deck of cards, shuffle | |
;; loop: | |
;; does a player have zero cards? | |
;; if yes: game over | |
;; if no: faceoff | |
;; determine winner, winner gets cards added | |
;; if tie: | |
;; does 1 player have < 5 cards | |
;; if yes: game over | |
;; if no: reserve three cards -- return to top of loop | |
(defn play-face-off [] | |
(let [ranks [:2 :3 :4 :5 :6 :7 :8 :9 :10 :J :Q :K :A] | |
cards (->> (for [rank ranks | |
suit [:clubs :diamonds :hearts :spades]] | |
{:rank rank :suit suit}) | |
(into []) | |
shuffle | |
(map-indexed vector) ; deal cards | |
(group-by (comp odd? first)) | |
vals | |
(map (partial map last)))] | |
(letfn [(get-rank [card] | |
(->> card | |
:rank | |
(.indexOf ranks))) | |
(who-wins? [card1 card2] | |
(cond (> (get-rank card1) (get-rank card2)) :card1 | |
(> (get-rank card2) (get-rank card1)) :card2 | |
:else :tie)) | |
(endgame [p1] | |
(if (> 5 (count p1)) | |
(println "Player 2 wins the game!") | |
(println "Player 1 wins the game!")))] | |
(loop [player1 (first cards) | |
player2 (last cards) | |
pot [] | |
hand 1] | |
(if (or (zero? (count player1)) | |
(zero? (count player2))) | |
(endgame player1) | |
(let [card1 (first player1) | |
card2 (first player2) | |
face-off-result (who-wins? card1 card2)] | |
(do | |
(Thread/sleep 200) ; time in milliseconds | |
(println (format "\nHand %s - P1: %s | P2 %s" | |
(str hand) | |
(count player1) | |
(count player2))) | |
(println (format "C1: %s | C2: %s" | |
(str card1) | |
(str card2))) | |
(cond (= face-off-result :card1) | |
(do | |
(println "P1 wins the hand\n") | |
(recur (concat (rest player1) | |
(shuffle [card1 card2]) | |
(shuffle pot)) | |
(rest player2) | |
[] | |
(inc hand))) | |
(= face-off-result :card2) | |
(do | |
(println "P2 wins the hand\n") | |
(recur (rest player1) | |
(concat (rest player2) | |
(shuffle [card2 card1]) | |
(shuffle pot)) | |
[] | |
(inc hand))) | |
(= face-off-result :tie) | |
(do | |
(println "We have a tie. FACEOFF!\n") | |
(if (or (> 5 (count player1)) | |
(> 5 (count player2))) | |
(endgame player1) | |
(recur (nthrest player1 4) | |
(nthrest player2 4) | |
(concat (take 4 player1) | |
(take 4 player2) | |
pot) | |
(inc hand)))))))))))) | |
(play-face-off) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment