2014-12-18 135 views
-1

我有一个小游戏,有一个小客户端,游戏接收来自服务器的数据。客户端在一个模块中,游戏在另一个模块中。问题在于客户端从服务器接收数据,但要执行游戏中的操作,客户端需要访问游戏方法(类MyGame),并使用这样的代码,我得到一个错误:游戏客户端交互

模块客户端:

class MyClient: 
    #receives data from the server 
    #It is a task, always listening 
    def readerConnection: 
     #if a data arrives from the server... 
     if newData: 
      #call dataOnScreen of class MyGame 
      ...dataOnScreen() 

模块游戏:

from client import MyClient 

class MyGame: 
    def _init_(self, client): 
     #begin to receive data from the server 
     self.c = client 

    #print data received from the server on screen 
    def dataOnScreen(self): 
     ............ 
#the game begins   
MyGame(MyClient()) 
当然

,因为该方法dataOnScreen未在类定义MyClient发生错误。 如果我这样做,一切工作正常(写客户端进入游戏):

class MyGame: 
    def _init_(self): 
     ......... 
    #receives data from the server 
    #It is a task, always listening 
    def readerConnection: 
     #if a data arrives from the server... 
     if newData: 
      #call dataOnScreen 
      self.dataOnScreen() 

    #print data received from the server on screen 
    def dataOnScreen(self): 
     ............ 
#the game begins   
MyGame() 

但这不是我想要的。我想要的是让游戏和客户处于不同的阶级。

感谢您的帮助。

+0

我假设您希望客户端和服务器通过网络进行通信。在这种情况下,你不能简单地从一个方向调用一个函数,你需要使用某种网络协议从一个到另一个进行通信。 – 2014-12-18 22:43:23

+0

我认为他们可以用服务器/客户端通信,这是实际游戏和客户端类的联系/分离,这是问题(我认为)。 – 2014-12-18 22:46:42

回答

0

也许你可以做一些事情,比如将函数或MyGame对象传递给客户端,这样它就知道在接收数据时该怎么做。

喜欢的东西

class MyGame: 
    def _init_(self, client): 
     #begin to receive data from the server 
     self.c = client 
     client.game = self 


class MyClient: 
    #receives data from the server 
    #It is a task, always listening 
    def readerConnection: 
     #if a data arrives from the server... 
     if newData: 
      #call dataOnScreen of class MyGame 
      self.game.dataOnScreen() 

有点像客户端环境或回调,如果你在一个函数中传递。