Skip to content

Instantly share code, notes, and snippets.

@tOverney
Last active September 24, 2015 19:54
Show Gist options
  • Save tOverney/0f65999579b202554b34 to your computer and use it in GitHub Desktop.
Save tOverney/0f65999579b202554b34 to your computer and use it in GitHub Desktop.
you start Ping and then, he plays with Pong (which is a better player that can smash).Ping can "survive" one smash and then he "becomes" vulnerable => next smash he looses.
case object Ball
case object SmashedBall
case object PleaseServe
case object YouWin
class Ping(pong: ActorRef) extends Actor {
override def receive = {
case PleaseServe =>
println("Serving")
pong ! Ball
context.become(fresh)
}
def fresh : Receive = {
case Ball =>
returnBall()
case SmashedBall =>
returnBall("Ha! Caught one!")
context.become(vulnerable)
}
def vulnerable : Receive = {
case Ball =>
returnBall()
case SmashedBall =>
println("Not again! ... You win Pong!")
pong ! YouWin
context.stop(self)
}
def returnBall(message : String = "ping") = {
println(message)
pong ! Ball
}
}
class Pong extends Actor {
val reload = 5
override def receive = preparingForSmash(reload)
def preparingForSmash(leftBeforeSmash : Int) : Receive = {
case Ball if leftBeforeSmash == 0 =>
println("Try catch this one!")
sender ! SmashedBall
context.become(preparingForSmash(reload))
case Ball =>
println("pong")
sender ! Ball
context.become(preparingForSmash(leftBeforeSmash - 1))
case YouWin =>
println("I'm so good!")
context.stop(self)
context.system.shutdown()
}
}
object TennisMatchTest extends App {
val system = ActorSystem("TennisMatch")
val pong = system.actorOf(Props[Pong], name = "PlayerTwo")
val ping = system.actorOf(Props(new Ping(pong)), name = "PlayerOne")
ping ! PleaseServe
system.awaitTermination
println("match is over let's go home!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment