0

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

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")
          }
      }
    }
  }
}

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

4

1 回答 1

1

使用 Akka,它看起来像这样:

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 远程演员的信息。

于 2013-03-20T21:18:26.843 回答