Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.78 KB | None | 0 0
  1. import akka.actor._
  2.  
  3. case class Ball(count: Int)
  4.  
  5. object Main {
  6.   def main(args: Array[String]): Unit = {
  7.     val actorSystem = ActorSystem("MySystem")
  8.     val player1 = actorSystem.actorOf(Props(new Player))
  9.     val player2 = actorSystem.actorOf(Props(new Player))
  10.  
  11.     player1.tell(Ball(5), player2)
  12.   }
  13. }
  14.  
  15. import akka.actor.Actor
  16.  
  17. class Player extends Actor {
  18.   def receive = {
  19.     case Ball(0) => context.system.terminate()
  20.     case Ball(count) =>
  21.       require(count > 0)
  22.       if (count % 2 == 0) print("ping\n") else print("pong\n")
  23.       sender ! Ball(count - 1)
  24.   }
  25. }
  26.  
  27.  
  28.  
  29. ================================
  30.  
  31.  
  32. import akka.actor._
  33.  
  34. import scala.collection.mutable.ArrayBuffer
  35.  
  36. case class Ball(count: Int)
  37.  
  38. object Main {
  39.   def main(args: Array[String]): Unit = {
  40.     val actorSystem = ActorSystem()
  41.     val players = ArrayBuffer[ActorRef]()
  42.     val player0 = actorSystem.actorOf(Props(classOf[Player], 0, players))
  43.     val player1 = actorSystem.actorOf(Props(classOf[Player], 1, players))
  44.     val player2 = actorSystem.actorOf(Props(classOf[Player], 2, players))
  45.  
  46.     players += player0 += player1 += player2
  47.  
  48.     player0 ! Ball(0)
  49.   }
  50. }
  51.  
  52. import akka.actor.{Actor, ActorRef}
  53.  
  54. import scala.collection.mutable.ArrayBuffer
  55. import scala.util.Random
  56.  
  57. class Player(val num: Int, val players: ArrayBuffer[ActorRef]) extends Actor {
  58.   val random = new Random()
  59.  
  60.   def receive = {
  61.     case Ball(count) =>
  62.       var nextPlayerIdx = random.nextInt(players.length)
  63.       while (nextPlayerIdx == num) nextPlayerIdx = random.nextInt(players.length)
  64.       println("Player " + num + " recieved throw number: " + count + ". Throwing to " + nextPlayerIdx + ". Throw number " + (count + 1))
  65.       Thread.sleep(1000)
  66.       players(nextPlayerIdx) ! Ball(count + 1)
  67.   }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement