Skip to content

Instantly share code, notes, and snippets.

@vehas
Created April 11, 2019 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vehas/c2206dcd3993fbcd6e3647d2dd396d70 to your computer and use it in GitHub Desktop.
Save vehas/c2206dcd3993fbcd6e3647d2dd396d70 to your computer and use it in GitHub Desktop.
kata from http://codingdojo.org/kata/Tennis/ take winner and game state, return updated game state
(ns tennis.tennis)
(def next-score
{0 15
15 30
30 40})
(defn tennis [winner {:keys [score advantage] :as game-state}]
"kata from http://codingdojo.org/kata/Tennis/
take winner and game state, return updated game state"
;;The scoring system is rather simple:
(cond
;; 3. If both have 40 the players are deuce.
;; a. If the game is in deuce
(= (vals score) [40 40])
(cond
;;, the winner of a ball will have advantage and game ball.
(nil? advantage)
(assoc game-state :advantage winner)
;; b. If the player with advantage wins the ball he wins the game
(= advantage winner)
(assoc game-state :winner winner)
;; c. If the player without advantage wins they are back at deuce.
:else
(dissoc game-state :advantage))
;;2. If you have 40 and you win the ball you win the game, however there are special rules.
(= (get score winner) 40)
(assoc game-state :status :win :winner winner)
;; 1. Each player can have either of these points in one game 0 15 30 40
:else
(update-in game-state [:score winner] next-score)))
[
(tennis :p1 {:score {:p1 0 :p2 0}}) ;; => {:score {:p1 15, :p2 0}}
(tennis :p1 {:score {:p1 0 :p2 15}}) ;; => {:score {:p1 15, :p2 15}}
(tennis :p2 {:score {:p1 15 :p2 30}}) ;; => {:score {:p1 15, :p2 40}}
(tennis :p2 {:score {:p1 40 :p2 40}}) ;; => {:score {:p1 40, :p2 40}, :advantage :p2}
(tennis :p1 {:score {:p1 40 :p2 40} ;; => {:score {:p1 40, :p2 40}, :advantage :p1, :winner :p1}
:advantage :p1})
(tennis :p1 {:score {:p1 40 :p2 40} ;; => {:score {:p1 40, :p2 40}}]
:advantage :p2})]
(def score-described
{0 "love"
15 "fifteen"
30 "thirty"
40 "forty"})
(defn running-score [winner {:keys [score]}]
(->> winner
(get score)
(get score-described)))
[ (running-score :p1 {:score {:p1 0 :p2 0}})
(running-score :p1 {:score {:p1 0 :p2 15}})
(running-score :p2 {:score {:p1 15 :p2 30}})
(running-score :p2 {:score {:p1 40 :p2 40}})
(running-score :p1 {:score {:p1 40 :p2 40}
:advantage :p1})
(running-score :p1 {:score {:p1 40 :p2 40}
:advantage :p2})]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment