游戏客户端交互

2024-09-30 04:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但这不是我想要的。我想要的是把游戏和客户端分为不同的类

谢谢你的帮助


Tags: 模块thefromselfclient游戏客户端data
1条回答
网友
1楼 · 发布于 2024-09-30 04:36:12

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

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

相关问题 更多 >

    热门问题