-
-
Save darwin/bfeb7d25c11692e3f6fd431a7650deab to your computer and use it in GitHub Desktop.
Non-blocking version of core.async ping-pong game
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 ping-pong-go | |
(:require [clojure.core.async :as async :refer [<! >!]])) | |
(defn ping [ch] | |
(println "Ping") | |
(go | |
(>! ch :ping) | |
(<! (async/timeout 500)))) | |
(defn pong [ch] | |
(println "Pong") | |
(go | |
(>! ch :pong) | |
(<! (async/timeout 500)))) | |
(defn return [ch] | |
(go | |
(let [ball (<! ch)] | |
(if (= ball :ping) | |
(<! (pong ch)) | |
(<! (ping ch)))))) | |
(defn play [] | |
(let [ch (async/chan 1)] | |
(async/go-loop [cnt 0] | |
(if (= cnt 0) | |
(<! (ping ch)) | |
(<! (return ch))) | |
(if (< cnt 10) | |
(recur (inc cnt)) | |
(println "Game over!"))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment