Skip to content

Instantly share code, notes, and snippets.

@darwin
Forked from jmglov/ping_pong_go.clj
Last active August 15, 2022 11:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darwin/bfeb7d25c11692e3f6fd431a7650deab to your computer and use it in GitHub Desktop.
Save darwin/bfeb7d25c11692e3f6fd431a7650deab to your computer and use it in GitHub Desktop.
Non-blocking version of core.async ping-pong game
(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