Source

fogbow / src / main / scala / fogbow / example / actor / PingPong.scala

Full commit
package fogbow.example.actor

import akka.actor.{Actor, ActorRef, PoisonPill}
import Actor._

import scala.util.Random

object PingPong {
  
  val randomGen = new Random

  case class Ball(partner: ActorRef, volley: Int)

  case object EndGame

  case class Player (name: String) extends Actor {

    def receive = {

      case Ball(partner, volley) =>
	Thread.sleep(500)
	
	if (randomGen.nextInt(100) < 10) {

	  println(name + ": ending game!")
	  partner ! EndGame
	  self.stop

	} else {

	  println (name + ": " + volley)
	  partner ! Ball(self, volley+1)

	}

      case EndGame =>
	self.stop
    }
  }

  def main (args: Array[String]) {
    val ping = actorOf(Player("ping"))
    ping.start

    val pong = actorOf(Player("pong"))
    pong.start

    pong ! Ball(ping, 1)
  }

}