引用两个演员 [英] Keeping references to two actors

查看:121
本文介绍了引用两个演员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个2人小游戏,可以与演员通过网络进行互动。每个客户端都会向服务器发送一条消息,要求加入该服务器,此时我想保留对发件人的引用,但是当第二个玩家加入时,它将覆盖我对第一个发件人的引用:

I am making a little 2 player game that will work over the network with actors. Each client sends a message to the server to join and I want to keep references to the senders at that point, but when the second player joins it overwrites my reference to the first one:

case class JoinMsg

class Server(port: Int) extends Actor {
  var client1: OutputChannel[Any] = null
  var client2: OutputChannel[Any] = null
  def act() {
    alive(port)
    register('Server, self)
    while (true) {
      receive {
        case JoinMsg =>
          if (client1 == null) {
            Console.println("got player 1")
            client1 = sender
            client1 ! new Msg("Waiting for player 2")
          } else if (client2 == null) {
            Console.println("got player 2")
            client2 = sender
            Console.println("blatted client1?: "+(client1 == client2))//true
            client1 ! new Msg("hi")
            client2 ! new Msg("hi")
          }
      }
    }
  }
}

解决这个问题的正确方法是什么?

What's the right way to go about this? Thx.

推荐答案

使用Akka看起来像这样:

With Akka it would look like this:

import akka.actor._

case object JoinMsg
case class Msg(s: String)

class Server extends Actor {

  def receive = {
    case JoinMsg =>
      println("got player 1")
      sender ! Msg("Waiting for player 2")
      context.become(waitingForPlayer2(sender))
  }

  def waitingForPlayer2(client1: ActorRef): Actor.Receive = {
    case JoinMsg =>
      println("got player 2")
      sender ! Msg("hi")
      client1 ! Msg("hi")
      context.become(ready(client1, sender))
  }

  def ready(client1: ActorRef, client2: ActorRef): Actor.Receive = {
    case m: Msg if sender == client1 => client2 ! m
    case m: Msg if sender == client2 => client1 ! m
  }
}

object Demo extends App {
  val system = ActorSystem("Game")
  val server = system.actorOf(Props[Server], "server")

  system.actorOf(Props(new Actor {
    server ! JoinMsg
    def receive = {
      case Msg(s) => println(s)
    }
  }))

  system.actorOf(Props(new Actor {
    server ! JoinMsg
    def receive = {
      case Msg(s) => println(s)
    }
  }))
}

完全相同的参与者代码可以与远程参与者一起使用。您只需要进行几行配置,就可以使用 actorFor 从客户端进行服务器查找。阅读 Akka远程演员

Exact same actor code can be used with remote actors. You only need a few lines of configuration and the lookup of the server from the clients is performed with actorFor. Read about Akka remote actors.

这篇关于引用两个演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆