游戏客户端互动

时间:2014-12-18 22:34:22

标签: python server

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

但这不是我想要的。我想要的是让游戏和客户在不同的班级。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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()

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