Last active
December 20, 2015 06:09
-
-
Save zerokarmaleft/6084002 to your computer and use it in GitHub Desktop.
core.async example: Ping Pong
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
(defn player | |
[msg table] | |
(go (loop [] | |
(let [ball (<! table)] ;; the ball was hit to this player | |
(.log js/console msg) | |
(<! (timeout 100)) ;; wait 100msecs | |
(>! table (update-in ball [:hits] inc)) ;; hit the ball back | |
(recur))))) | |
(defn game | |
[table ball] | |
(go (do (.log js/console "Game started.") | |
(>! table ball) ;; put the ball into play | |
(<! (timeout 1000)) ;; game lasts for ten seconds | |
(<! table) ;; take the ball out of play (fun police) | |
(.log js/console "Game ended.")))) | |
(defn ping-pong! | |
[] | |
(let [table (chan) | |
ball {:hits 0}] | |
(player "ping" table) ;; start a player process that pings | |
(player "pong" table) ;; start a player process that pongs | |
(game table ball))) ;; start the game process |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment