【问题标题】:Game client interaction游戏客户端交互
【发布时间】:2014-12-18 22:34:21
【问题描述】:

我有一个小游戏,它有一个小客户端,游戏从服务器接收数据。客户端在一个模块中,而游戏在另一个模块中。问题是客户端从服务器接收数据,但是要在游戏中执行操作,客户端需要访问游戏的方法(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())

当然会发生错误,因为 MyClient 类中没有定义方法 dataOnScreen。 如果我执行以下操作,一切正常(将客户端写入游戏):

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()

但这不是我想要的。我想要的是将游戏和客户端放在不同的类中。

感谢您的帮助。

【问题讨论】:

  • 我假设您希望客户端和服务器通过网络进行通信。在这种情况下,您不能简单地从一个函数调用另一个函数,您需要使用某种网络协议从一个到另一个进行通信。
  • 我认为他们对服务器/客户端通信没问题,问题在于实际游戏和客户端类的链接/分离(我认为)。

标签: python server


【解决方案1】:

也许你可以做一些事情,比如将函数或 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()

有点像客户端的上下文或传入函数时的回调。

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多