Ejemplo n.º 1
0
def dg_set_kill(pid, kill):
    if pid is not None:
        dg = PyDatagram()
        dg.addUint8(SET_KILL)
        dg.addUint16(pid)
        dg.addBool(kill)
        return dg
    else:
        print("!! TRIED TO SEND DATAGRAM WITH NO PID !!")
Ejemplo n.º 2
0
 def send_server_info(self):
     pkg = PyDatagram()
     pkg.addUint16(SMSG_INFO)
     for id in self.CLIENTS_ID:
         pkg.addUint8(id)
         pkg.addString(self.CLIENTS_USER_NAMES[id])
         pkg.addString(self.CLIENTS_IP[id])
         pkg.addBool(self.CLIENTS_READY[id])
     self.broadcast_pkg(pkg)
Ejemplo n.º 3
0
 def getCarPosDatagram(self, num, data):
     newDatagram = PyDatagram()
     newDatagram.addUint8(CAR_MESSAGE)
     newDatagram.addUint8(num)
     for j in range(5):
         newDatagram.addFloat32(float(data[j]))
     for j in range(5):
         newDatagram.addBool(data[5][j])
     newDatagram.addInt32(data[6])
     return newDatagram
Ejemplo n.º 4
0
 def getNewCarPosDatagram(self, num):
     newDatagram = PyDatagram()
     newDatagram.addUint8(PLAYER_ASSIGNMENT_MESSAGE)
     newDatagram.addUint8(num)
     newDatagram.addFloat32(self.carData.carlist[num].model.getX())
     newDatagram.addFloat32(self.carData.carlist[num].model.getY())
     vel = self.carData.carlist[num].vel.getXY()
     newDatagram.addFloat32(vel[0])
     newDatagram.addFloat32(vel[1])
     newDatagram.addFloat32(self.carData.carlist[num].model.getH())
     for j in range(5):
         newDatagram.addBool(self.carData.carlist[num].input[j])
     newDatagram.addInt32(self.carData.carlist[num].hp)
     return newDatagram
Ejemplo n.º 5
0
 def getCarPosDatagramFromCar(self, num):
     # creates a car_message datagram from the entry in carData (used to get new cars up to date)
     newDatagram = PyDatagram()
     newDatagram.addUint8(CAR_MESSAGE)
     newDatagram.addUint8(num)
     newDatagram.addFloat32(self.carData.carlist[num].model.getX())
     newDatagram.addFloat32(self.carData.carlist[num].model.getY())
     vel = self.carData.carlist[num].vel.getXY()
     newDatagram.addFloat32(vel[0])
     newDatagram.addFloat32(vel[1])
     newDatagram.addFloat32(self.carData.carlist[num].model.getH())
     for j in range(5):
         newDatagram.addBool(self.carData.carlist[num].input[j])
     newDatagram.addBool(self.carData.carlist[num].lightsOn)
     newDatagram.addInt32(self.carData.carlist[num].hp)
     return newDatagram
Ejemplo n.º 6
0
 def getNewCarPosDatagram(self, num):
     # same as getCarPosDatagramFromCar, but is a player_assignment_message
     newDatagram = PyDatagram()
     newDatagram.addUint8(PLAYER_ASSIGNMENT_MESSAGE)
     newDatagram.addUint8(num)
     newDatagram.addFloat32(self.carData.carlist[num].model.getX())
     newDatagram.addFloat32(self.carData.carlist[num].model.getY())
     vel = self.carData.carlist[num].vel.getXY()
     newDatagram.addFloat32(vel[0])
     newDatagram.addFloat32(vel[1])
     newDatagram.addFloat32(self.carData.carlist[num].model.getH())
     for j in range(5):
         newDatagram.addBool(self.carData.carlist[num].input[j])
     newDatagram.addBool(self.carData.carlist[num].lightsOn)
     newDatagram.addInt32(self.carData.carlist[num].hp)
     return newDatagram
Ejemplo n.º 7
0
    def sendLoginMsg(self):
        """
        Send a message to the server with our loginName
        """

        DISLID = ConfigVariableInt('fake-DISL-PlayerAccountId',0).getValue()
        if not DISLID:
            NameStringId = ("DISLID_%s" % (self.loginName))
            DISLID = ConfigVariableInt(NameStringId, 0).getValue()

        cr=self.cr
        # Time to send a login message
        datagram = PyDatagram()
        # Add message type
        datagram.addUint16(CLIENT_LOGIN)
        # Add login name
        datagram.addString(self.loginName)
        # Add our IP address

        if cr.connectMethod != cr.CM_HTTP:
            datagram.addUint32(cr.tcpConn.getAddress().getIp())
        else:
            # Actually, using the OpenSSL library we don't know our
            # own IP address.  But no one really cares anyway.
            datagram.addUint32(0)
        # Add the UDP port we will be listening on. (Bogus for now)
        datagram.addUint16(5150)
        # Add the Server Version ID
        datagram.addString(cr.serverVersion)
        # Add the dc file hash
        datagram.addUint32(cr.hashVal)
        # Add password
        datagram.addString(self.password)
        # Add create flag
        datagram.addBool(self.createFlag)
        # Add the download verification string.
        datagram.addString(cr.validateDownload)
        # And the magic word enable string.
        datagram.addString(cr.wantMagicWords)
        # And our dev fake DISL account ID
        datagram.addUint32(DISLID)
        # Whether or not to enable OTP_WHITELIST
        datagram.addString(ConfigVariableString('otp-whitelist',"YES").getValue())

        # Send the message
        cr.send(datagram)
Ejemplo n.º 8
0
 def getPosDatagram(self):
     # send player car data
     num = self.carData.index
     if num < 0:
         return None
     newDatagram = PyDatagram()
     newDatagram.addUint8(CAR_MESSAGE)
     newDatagram.addUint8(num)
     newDatagram.addFloat32(self.carData.carlist[num].model.getX())
     newDatagram.addFloat32(self.carData.carlist[num].model.getY())
     vel = self.carData.carlist[num].vel.getXY()
     newDatagram.addFloat32(vel[0])
     newDatagram.addFloat32(vel[1])
     newDatagram.addFloat32(self.carData.carlist[num].model.getH())
     for j in range(5):
         newDatagram.addBool(self.carData.carlist[num].input[j])
     newDatagram.addBool(self.carData.carlist[num].lightsOn)
     newDatagram.addInt32(self.carData.carlist[num].hp)
     return newDatagram
Ejemplo n.º 9
0
 def makeNamedObjectMovementDatagram(self, xyz, hpr, scale, color, hidden, name):
     datagram = PyDatagram()
     datagram.addUint32(self.packetNumber)
     self.packetNumber = self.packetNumber + 1
     datagram.addUint8(CLUSTER_NAMED_OBJECT_MOVEMENT)
     datagram.addString(name)
     datagram.addFloat32(xyz[0])
     datagram.addFloat32(xyz[1])
     datagram.addFloat32(xyz[2])
     datagram.addFloat32(hpr[0])
     datagram.addFloat32(hpr[1])
     datagram.addFloat32(hpr[2])
     datagram.addFloat32(scale[0])
     datagram.addFloat32(scale[1])
     datagram.addFloat32(scale[2])
     datagram.addFloat32(color[0])
     datagram.addFloat32(color[1])
     datagram.addFloat32(color[2])
     datagram.addFloat32(color[3])
     datagram.addBool(hidden)
     return datagram
Ejemplo n.º 10
0
 def makeNamedObjectMovementDatagram(self, xyz, hpr, scale, color, hidden, name):
     datagram = PyDatagram()
     datagram.addUint32(self.packetNumber)
     self.packetNumber = self.packetNumber + 1
     datagram.addUint8(CLUSTER_NAMED_OBJECT_MOVEMENT)
     datagram.addString(name)
     datagram.addFloat32(xyz[0])
     datagram.addFloat32(xyz[1])
     datagram.addFloat32(xyz[2])
     datagram.addFloat32(hpr[0])
     datagram.addFloat32(hpr[1])
     datagram.addFloat32(hpr[2])
     datagram.addFloat32(scale[0])
     datagram.addFloat32(scale[1])
     datagram.addFloat32(scale[2])
     datagram.addFloat32(color[0])
     datagram.addFloat32(color[1])
     datagram.addFloat32(color[2])
     datagram.addFloat32(color[3])        
     datagram.addBool(hidden)
     return datagram    
 def sendLoginMsg(self):
     DISLID = config.GetInt('fake-DISL-PlayerAccountId', 0)
     if not DISLID:
         NameStringId = 'DISLID_%s' % self.loginName
         DISLID = config.GetInt(NameStringId, 0)
     cr = self.cr
     datagram = PyDatagram()
     datagram.addUint16(CLIENT_LOGIN)
     datagram.addString(self.loginName)
     if cr.connectMethod != cr.CM_HTTP:
         datagram.addUint32(cr.tcpConn.getAddress().getIp())
     else:
         datagram.addUint32(0)
     datagram.addUint16(5150)
     datagram.addString(cr.serverVersion)
     datagram.addUint32(cr.hashVal)
     datagram.addString(self.password)
     datagram.addBool(self.createFlag)
     datagram.addString(cr.validateDownload)
     datagram.addString(cr.wantMagicWords)
     datagram.addUint32(DISLID)
     datagram.addString(config.GetString('otp-whitelist', 'YES'))
     cr.send(datagram)
 def sendLoginMsg(self):
     DISLID = config.GetInt('fake-DISL-PlayerAccountId', 0)
     if not DISLID:
         NameStringId = 'DISLID_%s' % self.loginName
         DISLID = config.GetInt(NameStringId, 0)
     cr = self.cr
     datagram = PyDatagram()
     datagram.addUint16(CLIENT_LOGIN)
     datagram.addString(self.loginName)
     if cr.connectMethod != cr.CM_HTTP:
         datagram.addUint32(cr.tcpConn.getAddress().getIp())
     else:
         datagram.addUint32(0)
     datagram.addUint16(5150)
     datagram.addString(cr.serverVersion)
     datagram.addUint32(cr.hashVal)
     datagram.addString(self.password)
     datagram.addBool(self.createFlag)
     datagram.addString(cr.validateDownload)
     datagram.addString(cr.wantMagicWords)
     datagram.addUint32(DISLID)
     datagram.addString(config.GetString('otp-whitelist', 'YES'))
     cr.send(datagram)
Ejemplo n.º 13
0
 def sendUserInput(self, inputArr = [], *args):
     pkg = PyDatagram()
     pkg.addUint16(CLIENT_INPUT)
     pkg.addUint64(self.myClock)
     pkg.addBool(inputArr[0])
     pkg.addBool(inputArr[1])
     pkg.addBool(inputArr[2])
     pkg.addBool(inputArr[3])
     pkg.addBool(inputArr[4])
     if inputArr[4]:
         pkg.addFloat32(inputArr[5])
         pkg.addFloat32(inputArr[6])
         pkg.addFloat32(inputArr[7])
         pkg.addString(str(inputArr[8]))
     pkg.addFloat32(self.gameEngine.players[self.id].playerNP.getH() % 360)
     pkg.addFloat32(self.gameEngine.players[self.id].playerSpine.getP() % 360)
     # Now lets send the whole thing...
     self.send(pkg)
Ejemplo n.º 14
0
class Packet():
    
    (
    PC_REQUEST_ENVIRONMENT,
    PC_START_ENVIRONMENT_STREAM,
    PC_CONT_ENVIRONMENT_STREAM,
    PC_END_ENVIRONMENT_STREAM,
    PC_ACK_END_ENVIRONMENT_STREAM,
    PC_WORLD_SEED,
    PC_ENGINE_LOADED,
    PC_TEAM_SELECT,
    PC_PLAYER_DEATH,
    PC_PLAYER_RESPAWN,
    PC_REQUEST_INFO,
    PC_REQUEST_RESPONSE,
    PC_SERVER_INFO,
    PC_REQUEST_JOIN,
    PC_REQUEST_JOIN_RESPONSE,
    PC_PLAYER_JOINED,
    PC_CONNECTED_PLAYERS,
    PC_CLIENT_PLAYER_STATE,
    PC_SERVER_PLAYER_STATE,
    PC_CLIENT_READY,
    PC_CLIENT_CHANGE_ITEM,
    PC_CLIENT_RELOAD,
    PC_GAME_STATE,
    PC_RELIABLE_STATE,
    PC_CLIENT_DISCONNECT,
    PC_GO_AWAY,
    PC_PLAYER_DISCONNECT,
    PC_CLIENT_CHAT_MESSAGE,
    PC_SERVER_CHAT_MESSAGE,
    PC_SERVER_ENVIRONMENT_CHANGE,
    PC_SCOREBOARD,
    PC_UNRELIABLE_PACKET,
    PC_RELIABLE_PACKET,
    PC_TCP_PACKET,
    PC_EMPTY
    ) = range(35)
    
    def __init__(self):
        self.dg = PyDatagram()
        
    def AddBool(self, value):
        if(value):
            self.dg.addBool(True)
        else:
            self.dg.addBool(False)
        
    def AddUint8(self, value):
        self.dg.addUint8(value)
        
    def AddUint16(self, value):
        self.dg.addUint16(value)
        
    def AddUint32(self, value):
        self.dg.addUint32(value)
        
    def AddFloat32(self, value):
        self.dg.addFloat32(value)
        
    def GetDatagram(self):
        return self.dg
    
    def GetDatagramSize(self):
        return self.dg.getLength()
    
    def AddFixedString(self, text):
        n = len(text)
        self.dg.addUint8(n)
        self.dg.addFixedString(text, n)
        
    def AddString(self, text):
        self.dg.addFixedString(text, len(text))
        
    def GetLength(self):
        return self.dg.getLength()
        
    @staticmethod
    def GetFixedString(data):
        length = data.getUint8()
        return data.getFixedString(length)
    
    @staticmethod
    def GetRemainingAsString(data):
        length = data.getRemainingSize()
        return data.getFixedString(length)
    
    @staticmethod
    def PeerAddrToIpPort(peerAddr):
        return '%s:%s' % (peerAddr.getIpString(), peerAddr.getPort())
    
    @staticmethod
    def BitsToInt16(bits):
        return int(''.join(bits), 2)
    
    @staticmethod
    def BitsToInt32(bits):
        return int(''.join(bits), 2)
    
    @staticmethod
    # http://www.daniweb.com/software-development/python/code/216539
    def Int16ToBits(int16):
        return list(''.join([str((int16 >> y) & 1) for y in range(16-1, -1, -1)]))
    
    @staticmethod
    def Int32ToBits(int32):
        return list(''.join([str((int32 >> y) & 1) for y in range(32-1, -1, -1)]))
Ejemplo n.º 15
0
 def send(self, cmd, onoff):
     print 'CLIENT SEND', cmd, onoff
     datagram = PyDatagram()
     datagram.addString(cmd)
     datagram.addBool(onoff)
     self.writer.send(datagram, self.connection)
Ejemplo n.º 16
0
 def send(self, cmd, onoff):
     datagram = PyDatagram()
     datagram.addString(cmd)
     datagram.addBool(onoff)
     self.writer.send(datagram, self.connection)
Ejemplo n.º 17
0
class ServerGame:
    def __init__(self, network):
        self.gameEngine = GameEngine()
        self.network = network

        self.lastConnection = None
        self.serverClock = 0
        self.count_down_time = 0

        self.client_received_list = []
        self.listPkg = PyDatagram()
        self.clientInputList = PyDatagram()
        self.clientInputList.addUint16(SERVER_INPUT)
        self.clientInputList.addUint64(self.serverClock)
        self.clientsAlive = []
        self.clientsDead = []
        self.display_text = GameUI.createDisplayUI("Loading...")
        self.count = 0

    def count_down_start(self):
        taskMgr.doMethodLater(1.0, self.count_down, 'Count Down')
        # taskMgr.doMethodLater(1.0, self.debug_count, 'Debug Count')

    def count_down(self, task):
        if self.count_down_time == -1:
            taskMgr.remove('Count Down')
            self.network.handlers[CLIENT_INPUT] = self.client_input_handler
            self.game_start()
        else:
            self.network.broadcastMsg("/count_down " +
                                      str(self.count_down_time))
            self.display_text.setText(str(self.count_down_time))
            self.count_down_time -= 1
        return task.again

    def debug_count(self, task):
        print(self.count)
        self.count = 0
        return task.again

    # to send game's initial stats
    def game_start(self):
        base.oobe()
        self.display_text.setText("Begin")
        pkg = PyDatagram()
        pkg.addUint16(GAME_INITIALIZE)
        pkg.addUint32(self.network.playerCount)
        for client_id in self.network.CLIENTS_ID:
            x = random.randint(1, 5)
            y = random.randint(1, 5)
            self.gameEngine.players.append(Player(x, y, 20, client_id))
            self.gameEngine.world.attachCharacter(
                self.gameEngine.players[client_id].playerNP.node())
            pkg.addUint32(client_id)
            pkg.addFloat32(x)
            pkg.addFloat32(y)
        for client_id in self.network.CLIENTS_ID:
            temp = pkg.__copy__()
            temp.addUint32(client_id)
            self.network.cWriter.send(temp,
                                      self.network.RELATION_OBJ_ID[client_id])
        # taskMgr.add(self.update, 'update')
        self.clientsAlive = self.network.CLIENTS_ID.copy()
        self.display_text.destroy()

    def client_input_handler(self, msgID, data, client):
        found = False
        client_clock = data.getUint64()
        # print('my time is', self.serverClock, 'client clock is', clientClock)
        if client_clock == self.serverClock:
            for c in self.client_received_list:
                if c == client:
                    found = True
                    break
            if not found:
                self.client_received_list.append(client)
                player = self.gameEngine.players[
                    self.network.RELATION_OBJ_ID[client]]

                x, y, z = 0, 0, 0
                w = data.getBool()
                a = data.getBool()
                s = data.getBool()
                d = data.getBool()
                shoot = data.getBool()
                if shoot:
                    x = data.getFloat32()
                    y = data.getFloat32()
                    z = data.getFloat32()
                    player_hit_id = data.getString()
                    if player_hit_id != "None":
                        player_hit_id = int(player_hit_id)
                        self.gameEngine.players[player_hit_id].health -= 30
                        if self.gameEngine.players[player_hit_id].health <= 0:
                            self.gameEngine.players[player_hit_id].health = 0
                            if player_hit_id in self.clientsAlive:
                                self.clientsAlive.pop(player_hit_id)
                                self.clientsDead.append(player_hit_id)
                    player.weapon.fire_with_pos(self.gameEngine.world, x, y, z)
                h = data.getFloat32()
                p = data.getFloat32()

                if w:
                    self.gameEngine.speed.setY(self.gameEngine.walk_speed)
                if a:
                    self.gameEngine.speed.setX(-self.gameEngine.walk_speed)
                if s:
                    self.gameEngine.speed.setY(-self.gameEngine.walk_speed)
                if d:
                    self.gameEngine.speed.setX(self.gameEngine.walk_speed)

                player.playerNP.setH(h)
                player.playerSpine.setP(p)
                player.playerNP.node().setLinearMovement(
                    self.gameEngine.speed, True)

                self.clientInputList.addUint32(
                    self.network.RELATION_OBJ_ID[client])
                self.clientInputList.addBool(True)
                self.clientInputList.addFloat32(player.playerNP.getX())
                self.clientInputList.addFloat32(player.playerNP.getY())
                self.clientInputList.addFloat32(player.playerNP.getZ())
                self.clientInputList.addFloat32(player.playerNP.getH())
                self.clientInputList.addFloat32(player.playerSpine.getP())
                self.clientInputList.addFloat32(self.gameEngine.speed.getX())
                self.clientInputList.addFloat32(self.gameEngine.speed.getY())
                self.clientInputList.addBool(shoot)
                if shoot:
                    self.clientInputList.addFloat32(x)
                    self.clientInputList.addFloat32(y)
                    self.clientInputList.addFloat32(z)
                self.clientInputList.addUint8(player.health)
                self.gameEngine.speed.setX(0)
                self.gameEngine.speed.setY(0)
                self.broadcast_task()

    def broadcast_task(self):
        if self.client_received_list.__len__() >= self.clientsAlive.__len__():
            # print("Broadcasting. Server Clock = " + str(self.serverClock))
            for c in self.network.CLIENTS_ID:
                self.network.cWriter.send(self.clientInputList,
                                          self.network.RELATION_OBJ_ID[c])
            self.serverClock += 1
            self.clientInputList = PyDatagram()
            self.clientInputList.addUint16(SERVER_INPUT)
            self.clientInputList.addUint64(self.serverClock)
            for client_id in self.clientsDead:
                self.clientInputList.addUint32(client_id)
                self.clientInputList.addBool(False)
            self.client_received_list.clear()
            self.update()
        else:
            pass
            # print("Waiting for all inputs. Server Clock = " +
            #       str(self.serverClock), "remaining users = " +
            #       str(self.clientsAlive.__len__() - self.client_received_list.__len__()))

    # Update
    def update(self):
        dt = globalClock.getDt()
        self.gameEngine.world.doPhysics(dt)
Ejemplo n.º 18
0
 def PARTY_UPDATED(self, yourturn, chars, player):
     myPyDatagram = PyDatagram()
     myPyDatagram.addString('PARTY_UPDATED')
     myPyDatagram.addBool(yourturn)
     myPyDatagram.addString32(json.dumps(chars))
     self.cWriter.send(myPyDatagram, player)
Ejemplo n.º 19
0
    def handleDatagram(self, dg):
        if not dg.getLength() > 0:
            return None
        dgi = PyDatagramIterator(dg)
        connection = dg.getConnection()
        msgType = dgi.getUint16()
        if msgType == CLIENT_HEARTBEAT:
            self.notify.debug('Recieved heartbeat.')
        elif msgType == CLIENT_DISCONNECT:
            if connection in self.connectionList:
                self.connectionList.remove(connection)
        elif msgType == CLIENT_SET_ZONE:
            self.handleSetZone(dgi, connection)
        elif msgType == CLIENT_REMOVE_ZONE:
            self.handleRemoveZone(dgi, connection)
        elif msgType == CLIENT_CREATE_OBJECT_REQUIRED:
            self.handleClientCreateObjectRequired(dg, dgi)
        elif msgType == CLIENT_OBJECT_UPDATE_FIELD:
            doId = dgi.getUint32()
            fieldId = dgi.getUint16()
            print "DEBUG: Got Toontown field update for Toontown doId = %d and Toontown fieldId = %d" % (doId, fieldId)
        elif msgType == CLIENT_OBJECT_DELETE:
            self.handleClientDeleteObject(dg, dgi.getUint32())
        elif msgType == CLIENT_OBJECT_DISABLE:
            self.handleClientDisable(dg, dgi.getUint32())
        elif msgType == CLIENT_ADD_INTEREST:
            #self.handleClientAddInterest(self, Client, dgi)
           
            handle = dgi.getUint16()
            contextId = dgi.getUint32()
            parentId = dgi.getUint32()
            zoneList = [dgi.getUint32()]  
            print 'DEBUG: Network :: Interest -> (%d, %d, %d)' % (handle, contextId, parentId)
            while True:
                remainingData = (dg.getLength() - dgi.getCurrentIndex())
                if remainingData == 0:
                    break
                zoneList.append(dgi.getUint32())
            if handle == 2: #Aww yeah we found the tewtow shard list interest!
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(4618) #parentId
                datagram.addUint32(3) #zoneId
                datagram.addUint16(58) #ToontownDistrict DClass Field
                datagram.addUint32(316000000) #Shard ID (doId)
                datagram.addString('Astron is for n00bs') #District name
                datagram.addUint8(1) # 1 - Enabled 0 - Disabled
                datagram.addBool(0)
                self.cw.send(datagram, connection)
            if handle == 4:
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(4618) #parentId
                datagram.addUint32(3) #zoneId
                datagram.addUint16(387) #ToontownDistrict DClass Field
                datagram.addUint32(900000000) #Shard ID (doId)
                datagram.addString("2013-08-22 23:49:46")
                self.cw.send(datagram, connection)
               
                datagran2 = PyDatagram()
                datagran2.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagran2.addUint32(0)
                datagran2.addUint32(0)
                datagran2.addUint16(172)
                datagran2.addUint32(637100008)
                arg = []
                datagran2.addUint16(len(arg) << 1)
                for i in arg:
                    datagran2.addInt16(int(i))
                datagran2.addUint16(len(arg) << 1)
                for i in arg:
                    datagran2.addInt16(int(i))
                datagran2.addUint16(len(arg) << 1)
                for i in arg:
                    datagran2.addInt16(int(i))
                datagran2.addUint16(len(arg) << 1)
                for i in arg:
                    datagran2.addInt16(int(i))
                #arg = [64, 65, 66, 10, 15]
                datagran2.addUint16(len(arg))
                for i in arg:
                    datagran2.addUint16(int(i))
                self.cw.send(datagran2, connection)
           
            if handle == 5:
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_OBJECT_UPDATE_FIELD)
                datagram.addUint32(1) #doId
                datagram.addUint16(112) #fieldId
                datagram.addUint32(316000000)
                self.cw.send(datagram, connection)
            datagram = PyDatagram()
            datagram.addUint16(CLIENT_DONE_INTEREST_RESP)
            datagram.addUint16(handle)
            datagram.addUint32(contextId)
            datagram.addUint32(parentId)
            for zoneId in zoneList:
                datagram.addUint32(zoneId)
            self.cw.send(datagram, connection)
            datagram = PyDatagram()
            datagram.addUint16(CLIENT_DONE_INTEREST_RESP)
            datagram.addUint16(handle)
            datagram.addUint32(contextId)
            datagram.addUint32(parentId)
            for zoneId in zoneList:
                datagram.addUint32(zoneId)
            self.cw.send(datagram, connection)
        elif msgType == CLIENT_REMOVE_INTEREST:
            return None
        #Lets start with the tewtow specific msgtypes.
        elif msgType == CLIENT_LOGIN_TOONTOWN:
            self.handleClientLoginToontown(dgi, connection)
        elif msgType == CLIENT_GET_AVATARS:
            self.handleGetAvatars(dgi, connection)			

        elif msgType == CLIENT_GET_AVATARS:
            self.handleGetAvatars(dgi, connection)

        elif msgType == CLIENT_CREATE_AVATAR:
            #return None
            datagram = PyDatagram()
            datagram.addUint16(CLIENT_CREATE_AVATAR_RESP)
            datagram.addUint16(0) #echoContext
            datagram.addUint8(0) #returnCode
            datagram.addUint32(1)
            self.cw.send(datagram, connection)
        elif msgType == CLIENT_SET_NAME_PATTERN:
            datagram = PyDatagram()
            datagram.addUint16(CLIENT_SET_NAME_PATTERN_ANSWER)
            datagram.addUint32(1)
            datagram.addUint8(0)
            self.cw.send(datagram, connection)
        elif msgType == CLIENT_SET_AVATAR:
                packer = DCPacker()
                dclass = self.dclassesByName['DistributedToon']
                datagram = PyDatagram()
                datagram.addUint16(15) #CLIENT_GET_AVATAR_DETAILS_RESP Msgtype
                datagram.addUint32(1)
                datagram.addUint8(0)
                datagram.addString('Infinity') #Toon name
                datagram.addString('Unknown')
                datagram.addUint32(0)
                datagram.addBool(1)
                datagram.addString('t\x05\x01\x00\x01\x39\x1b\x33\x1b\31\x1b\x14\x00\x14\x14') #DNA (blob)
                datagram.addUint8(1) #GM
                datagram.addUint16(2500) #Max Bank
                datagram.addUint16(0) #Current Bank
                datagram.addUint16(40) #Max Jellybeans
                datagram.addUint16(0) #Current Jellybeans
                datagram.addUint16(15) #Max Laff
                datagram.addUint16(15) #Current Laff
                datagram.addUint32(0) #Battle ID
                datagram.addString('Unknown') #Experience (blob)
                datagram.addUint8(10) #Max Gag Carry
 
                #setTrackAccess
 
                field = dclass.getField(13)
                print field
                arg = [0, 0, 0, 0, 1, 1, 0]
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addInt16(int(i))

                datagram.addInt8(3) #Track Progress 1
                datagram.addUint32(9) #Track Progress 2
 
               
 
                #setTrackBonusLevel
 
                field = dclass.getField(15)
                print field
 
                arg = [0, 0, 0, 0, 1, 1, 0]
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addInt8(int(i))

                datagram.addString('') #setInventory
 
                #setMaxNPCFriends (Uint16)
 
                datagram.addUint16(16)
               
 
                arg = []
                datagram.addUint16(len(arg) * 5)
                for i in arg:
                    datagram.addUint32(int(i))
 
                datagram.addUint32(316000000) #setDefaultShard
 
                datagram.addUint32(2000) #setDefaultZone
 
                datagram.addString('')
 
 
                field = dclass.getField(22)
                print field
 
                arg = [1000, 2000 , 3000, 4000, 5000, 6000, 8000, 9000, 10000, 11000, 12000, 13000]
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 

                field = dclass.getField(23)
                print field
 
                arg = [1000, 2000 , 3000, 4000, 5000, 6000, 8000, 9000, 10000, 11000, 12000, 13000]
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                datagram.addString('') #setInterface
 
                datagram.addUint32(2000) #setLastHood
 
                datagram.addUint8(1) #setTutorialAck
 
                datagram.addUint32(25) #setMaxClothes
 
                #setClothesTopsList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
 
                #setClothesBottomsList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint32(0) #setMaxAccessories
 
                #setHatList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setGlassessList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setBackpackList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setShoesList(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint8(0) #setHat 1
                datagram.addUint8(0) #setHat 2
                datagram.addUint8(0) #setHat 3
 
                datagram.addUint8(0) #setGlasses 1
                datagram.addUint8(0) #setGlasses 2
                datagram.addUint8(0) #setGlasses 3
 
                datagram.addUint8(0) #setBackpack 1
                datagram.addUint8(0) #setBackpack 2
                datagram.addUint8(0) #setBackpack 3
 
                datagram.addUint8(0) #setShoes 1
                datagram.addUint8(0) #setShoes 2
                datagram.addUint8(0) #setShoes 3
 
                datagram.addString('')
 
                #setEmoteAccess(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setCustomMeeages(uint16array)
 
                arg = []
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
                datagram.addString('') #setResistanceMessages
 
                #setPetTrickPhrases(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint16(0) #setCatalogSchedule 1
                datagram.addUint32(0) #setVatalogSchedule 2
 
                datagram.addString('') #setCatalog 1
                datagram.addString('') #setCatalog 2
                datagram.addString('') #setCatalog 3
 
                datagram.addString('') #setMailBoxContents
 
                datagram.addString('') #SetDeliverySchedule
 
                datagram.addString('') #setGiftSchedule
 
                datagram.addString('') #setAwardMailboxContents
 
                datagram.addString('') #setAwardSchedule
 
                datagram.addUint8(0) #setAwardNotify
 
                datagram.addUint8(0) #setCatalogNotify 1
 
                datagram.addUint8(0) #setCatalogNotify 2
 
                datagram.addUint8(0) #setSpeedChatStyleIndex
 
                #setTeleportAccess (uint32array)
 
                arg = [1000, 2000 , 3000, 4000, 5000, 6000, 8000, 9000, 10000, 11000, 12000, 13000]
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                #setCogStatus (uint32array)
                arg = []
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                #setCogCount (uint32array)
                arg = []
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                #setCogRadar(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setBuildingRadar(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setCogLevels(uint8array)
 
                arg = [0, 0, 0, 0]
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setCogTypes(uint8array)
 
                arg = [0, 0, 0, 0]
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setCogParts (uint32array)
                arg = [0, 0, 0, 0]
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                #setCogMerits(uint16array)
 
                arg = [0, 0, 0, 0]
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
                datagram.addUint32(0) #setHouseId
 
                #setQuests (uint32array)
                arg = []
                datagram.addUint16(len(arg) << 2)
                for i in arg:
                    datagram.addUint32(int(i))
 
                #setQuestHistory(uint16array)
 
                arg = []
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
                datagram.addUint8(0) #setRewardHistory 1
 
                #setRewardHistory 2(uint16array)
 
                arg = []
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
 
                datagram.addUint8(1) #setQuestCarryLimit
 
                datagram.addInt16(0) #setCheesyEffect 1
                datagram.addUint32(0) #setCheesyEffect 2
                datagram.addUint32(0) #setCheesyEffect 3
 
                datagram.addUint8(0) #setPosIndex
 
                #setFishCollection 1(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFishCollection 2(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFishCollection 3(uint16array)
 
                arg = []
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
                datagram.addUint8(20) #setMaxFishTank
 
                #setFishTank 1(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFishTank 2(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFishTank 3(uint16array)
 
                arg = []
                datagram.addUint16(len(arg) << 1)
                for i in arg:
                    datagram.addUint16(int(i))
 
                datagram.addUint8(1) #setFishingRod
 
                #setFishingTrophies(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFlowerCollection 1(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFlowerCollection 2(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFlowerBasket 1(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                #setFlowerBasket 2(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint8(25) #setMaxFlowerBasket
 
                #setGardenTrophies(uint8array)
 
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint8(1) #setShovel
 
                datagram.addUint32(0) #setShovelSkill
 
                datagram.addUint8(1) #setWateringCan
 
                datagram.addUint32(0) #setWateringCanSkill
 
                datagram.addUint32(0) #setPetID
 
                datagram.addUint8(0) #setPetTutorialDone
 
                datagram.addUint8(0) #setFishBingoTutorialDone
 
                datagram.addUint8(0) #setFishBingoMarkTutorialDone
 
                datagram.addInt8(0) #setKartBodyType
 
                datagram.addInt8(0) #setKartBodyColor
 
                datagram.addInt8(0) #setKartAccessoryColor
 
                datagram.addInt8(0) #setKartEngineBlockType
 
                datagram.addInt8(0) #setKartSpoilerType
 
                datagram.addInt8(0) #setKartFrontWheelWellType
 
                datagram.addInt8(0) #setKartBackWheelWellType
 
                datagram.addInt8(0) #setKartRimType
 
                datagram.addInt8(0) #setKartDecalType
 
                datagram.addUint32(100) #setTickets
 
                datagram.addUint8(0) #setKartingHistory 1
                datagram.addUint8(0) #setKartingHistory 2
                datagram.addUint8(0) #setKartingHistory 3
                datagram.addUint8(0) #setKartingHistory 4
                datagram.addUint8(0) #setKartingHistory 5
                datagram.addUint8(0) #setKartingHistory 6
                datagram.addUint8(0) #setKartingHistory 7
                datagram.addUint8(0) #setKartingHistory 8
                datagram.addUint8(0) #setKartingHistory 9
                datagram.addUint8(0) #setKartingHistory 10
                datagram.addUint8(0) #setKartingHistory 11
                datagram.addUint8(0) #setKartingHistory 12
                datagram.addUint8(0) #setKartingHistory 13
                datagram.addUint8(0) #setKartingHistory 14
                datagram.addUint8(0) #setKartingHistory 15
                datagram.addUint8(0) #setKartingHistory 16
 
               
                datagram.addUint8(0) #setKartingTrophies 1
                datagram.addUint8(0) #setKartingTrophies 2
                datagram.addUint8(0) #setKartingTrophies 3
                datagram.addUint8(0) #setKartingTrophies 4
                datagram.addUint8(0) #setKartingTrophies 5
                datagram.addUint8(0) #setKartingTrophies 6
                datagram.addUint8(0) #setKartingTrophies 7
                datagram.addUint8(0) #setKartingTrophies 8
                datagram.addUint8(0) #setKartingTrophies 9
                datagram.addUint8(0) #setKartingTrophies 11
                datagram.addUint8(0) #setKartingTrophies 11
                datagram.addUint8(0) #setKartingTrophies 12
                datagram.addUint8(0) #setKartingTrophies 13
                datagram.addUint8(0) #setKartingTrophies 14
                datagram.addUint8(0) #setKartingTrophies 15
                datagram.addUint8(0) #setKartingTrophies 16
                datagram.addUint8(0) #setKartingTrophies 17
                datagram.addUint8(0) #setKartingTrophies 18
                datagram.addUint8(0) #setKartingTrophies 19
                datagram.addUint8(0) #setKartingTrophies 20
                datagram.addUint8(0) #setKartingTrophies 21
                datagram.addUint8(0) #setKartingTrophies 22
                datagram.addUint8(0) #setKartingTrophies 23
                datagram.addUint8(0) #setKartingTrophies 24
                datagram.addUint8(0) #setKartingTrophies 25
                datagram.addUint8(0) #setKartingTrophies 26
                datagram.addUint8(0) #setKartingTrophies 27
                datagram.addUint8(0) #setKartingTrophies 28
                datagram.addUint8(0) #setKartingTrophies 29
                datagram.addUint8(0) #setKartingTrophies 30
                datagram.addUint8(0) #setKartingTrophies 31
                datagram.addUint8(0) #setKartingTrophies 32
                datagram.addUint8(0) #setKartingTrophies 33
 
                datagram.addUint32(0) #setKartingPersonalBest 1
                datagram.addUint32(0) #setKartingPersonalBest 2
                datagram.addUint32(0) #setKartingPersonalBest 3
                datagram.addUint32(0) #setKartingPersonalBest 4
                datagram.addUint32(0) #setKartingPersonalBest 5
                datagram.addUint32(0) #setKartingPersonalBest 6
 
                datagram.addUint32(0) #setKartingPersonalBest2 1
                datagram.addUint32(0) #setKartingPersonalBest2 2
                datagram.addUint32(0) #setKartingPersonalBest2 3
                datagram.addUint32(0) #setKartingPersonalBest2 4
                datagram.addUint32(0) #setKartingPersonalBest2 5
                datagram.addUint32(0) #setKartingPersonalBest2 6
                datagram.addUint32(0) #setKartingPersonalBest2 7
                datagram.addUint32(0) #setKartingPersonalBest2 8
                datagram.addUint32(0) #setKartingPersonalBest2 9
                datagram.addUint32(0) #setKartingPersonalBest2 10
                datagram.addUint32(0) #setKartingPersonalBest2 11
                datagram.addUint32(0) #setKartingPersonalBest2 12
 
                #setKartAccessoriesOwned [16]
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
                datagram.addInt8(0)
 
                #setCogSummonsEarned
                arg = []
                datagram.addUint16(len(arg))
                for i in arg:
                    datagram.addUint8(int(i))
 
                datagram.addUint8(0) #setGardenStart
 
                #setGolfHistory [18]
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
                datagram.addUint16(0)
 
                #setPackedGolfHoleBest [18]
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
 
                #setGolfCourseBest
                datagram.addUint8(0)
                datagram.addUint8(0)
                datagram.addUint8(0)
 
                datagram.addUint8(0) #setPinkSlips
 
                datagram.addUint8(0) #setNametagStyle

                self.cw.send(datagram, connection)

               
        elif msgType == CLIENT_SET_WISHNAME:
            #print dgi
            avId = dgi.getUint16()
            unknown = dgi.getString()
            pendingName = dgi.getString()
            print pendingName
            divide = pendingName.split(' ')
            lenStr = len(divide)
            s = 0
            while s != lenStr:
                nameCheck = divide[s]
                s += 1
            with open ("TewtowBlacklist.txt", "r") as badWordFile:
                data=badWordFile.readlines()
                for word in data:
                    chrList = list(word)
                    if chrList.count('\n') == 1:
                        chrList.remove('\n')
                    badWord = ''.join(chrList)
                    if nameCheck == badWord:
                        print 'Bad name detected, are you trying to get banned?'
                        datagram = PyDatagram()
                        datagram.addUint16(CLIENT_SET_WISHNAME_RESP)
                        datagram.addUint32(avId)
                        datagram.addUint16(0)
                        datagram.addString('NO')
                        datagram.addString('NO')
                        datagram.addString('')
                        message = PyDatagram()
                        message.addUint16(CLIENT_SYSTEM_MESSAGE)
                        message.addString('Sorry, That name is not allowed.')
                        self.cw.send(message, connection)
                    else:
                        datagram = PyDatagram()
                        datagram.addUint16(CLIENT_SET_WISHNAME_RESP)
                        datagram.addUint32(avId)
                        datagram.addUint16(0)
                        datagram.addString('NO')
                        datagram.addString('')
                        datagram.addString('NO')
                        self.cw.send(datagram, connection)
 
        elif msgType == CLIENT_OBJECT_LOCATION:
            doId = dgi.getUint32()
            parentId = dgi.getUint32()
            zoneId = dgi.getUint32()
            print 'Network :: Location -> (%d, %d, %d)' % (doId, parentId, zoneId)
            if zoneId == 2000:
               
                #DistributedMickey
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(316000000) #parentId
                datagram.addUint32(2) #zoneId
                #datagram.addUint16(83)
                datagram.addUint16(65)
                datagram.addUint32(433103088)
                datagram.addString("a")
                datagram.addString("a")
                datagram.addInt16(0)
                self.cw.send(datagram, connection)
           
            if zoneId == 1000:
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(316000000) #parentId
                datagram.addUint32(2) #zoneId
                #datagram.addUint16(83)
                datagram.addUint16(108)
                datagram.addUint32(433103088)
                datagram.addString("DockedEast")
                datagram.addInt16(100)
                self.cw.send(datagram, connection)
            if zoneId == 5000:
                '''
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(316000000) #parentId
                datagram.addUint32(2) #zoneId
                datagram.addUint16(68)
                datagram.addUint32(433103088)
                datagram.addString("a")
                datagram.addString("a")
                datagram.addInt16(0)
                self.cw.send(datagram, connection)
                '''
               
        #self.cw.send(datagram, connection)
            if zoneId == 2000:
                pass
                '''#message = PyDatagram()
                #message.addUint16(CLIENT_SYSTEM_MESSAGE)
                #message.addString('Surprised? I thought so. :P')
                #self.cw.send(message, connection)
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(316000000) #parentId
                datagram.addUint32(2) #zoneId
                #datagram.addUint16(83)
                datagram.addUint16(65)
                datagram.addUint32(433103088)
                datagram.addString("b")
                datagram.addString("a")
                datagram.addInt16(0)
                self.cw.send(datagram, connection)'''
               
            if zoneId == 3000:
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_CREATE_OBJECT_REQUIRED_OTHER_RESP)
                datagram.addUint32(316000000) #parentId
                datagram.addUint32(2) #zoneId
                #datagram.addUint16(83)
                datagram.addUint16(79)
                datagram.addUint32(433103089)
                datagram.addString("a")
                datagram.addString("a")
                datagram.addInt16(0)
                self.cw.send(datagram, connection)
               
                datagram = PyDatagram()
                datagram.addUint16(CLIENT_GET_STATE_RESP)
                self.cw.send(datagram, connection)

			
        else:
            self.notify.warning('Got a datagram %d; but could not handle it.' % msgType)
Ejemplo n.º 20
0
 def PARTY_UPDATED(self, yourturn, chars, player):
     myPyDatagram = PyDatagram()
     myPyDatagram.addString('PARTY_UPDATED')
     myPyDatagram.addBool(yourturn)
     myPyDatagram.addString32(json.dumps(chars))
     self.cWriter.send(myPyDatagram, player)
Ejemplo n.º 21
0
class Server(DirectObject):
    def __init__(self):
        DirectObject.__init__(self)
        self.gameEngine = GameEngine()

        # If you press Escape @ the server window, the server will quit.
        self.accept("escape", self.quit)
        self.lastConnection = None
        self.serverClock = 0
        self.lobbyWaitTime = 6
        self.randomValue = {}

        self.playerCount = 0
        self.listenStat = 1
        self.listPkg = PyDatagram()
        self.clientInputList = PyDatagram()
        self.clientInputList.addUint16(SERVER_INPUT)
        self.clientInputList.addUint64(self.serverClock)
        self.clientsAlive = {}

        self.displayText = GameUI.createDisplayUI("Loading...")
        # Create network layer objects

        # Deals with the basic network stuff
        self.cManager = QueuedConnectionManager()

        # Listens for new connections and queue's them
        self.cListener = QueuedConnectionListener(self.cManager, 0)

        # Reads data send to the server
        self.cReader = QueuedConnectionReader(self.cManager, 0)

        # Writes / sends data to the client
        self.cWriter = ConnectionWriter(self.cManager, 0)

        # open a server socket on the given port. Args: (port,timeout)
        self.tcpSocket = self.cManager.openTCPServerRendezvous(PORT, 1)

        # Tell the listener to listen for new connections on this socket
        self.cListener.addConnection(self.tcpSocket)

        # Start Listener task
        taskMgr.add(self.listenTask, "serverListenTask", -40)

        # Start Read task

        taskMgr.add(self.readTask, "serverReadTask", -39)

    def listenTask(self, task):
        if self.listenStat < 60 * self.lobbyWaitTime:
            x = int(self.listenStat / 60)
            if x == (self.listenStat / 60):
                self.timeToStart = self.lobbyWaitTime - x
                self.displayText.setText(str(self.timeToStart))
                self.broadcastMsg('/timeToStart ' + str(self.timeToStart))

            self.listenStat += 1
            if self.cListener.newConnectionAvailable():
                rendezvous = PointerToConnection()
                netAddress = NetAddress()
                newConnection = PointerToConnection()

                if self.cListener.getNewConnection(rendezvous, netAddress,
                                                   newConnection):
                    newConnection = newConnection.p()
                    # tell the Reader that there's a new connection to read from
                    self.cReader.addConnection(newConnection)
                    CLIENTS[newConnection] = netAddress.getIpString()
                    CLIENTS_ID[newConnection] = self.playerCount
                    self.clientsAlive[self.playerCount] = newConnection
                    self.lastConnection = newConnection
                    print("Got a connection!")
                    self.playerCount += 1
                else:
                    print("getNewConnection returned false")
            elif self.listenStat == 60 * self.lobbyWaitTime:
                self.gameStart()
                taskMgr.add(self.broadcastTask, "broadcastTask")
        return task.cont

    def readTask(self, task):
        """
        If there's any data received from the clients,
        get it and send it to the handlers.
        """
        while 1:
            (datagram, data, msgID) = self.nonBlockingRead(self.cReader)
            if msgID is MSG_NONE:
                # got nothing todo
                break
            else:
                # Got a datagram, handle it
                self.handleDatagram(data, msgID, datagram.getConnection())

        return task.cont

    def nonBlockingRead(self, qcr):
        """
        Return a datagram iterator and type if data is available on the
        queued connection reader
        """
        if self.cReader.dataAvailable():
            datagram = NetDatagram()
            if self.cReader.getData(datagram):
                data = PyDatagramIterator(datagram)
                msgID = data.getUint16()
            else:
                data = None
                msgID = MSG_NONE
        else:
            datagram = None
            data = None
            msgID = MSG_NONE
        # Note, return datagram to keep a handle on the data
        return (datagram, data, msgID)

    def handleDatagram(self, data, msgID, client):
        """
        Check if there's a handler assigned for this msgID.
        Since we dont have case statements in python,
        I'm using a dictionary to avoid endless elif statements.
        """

        ########################################################
        ##
        ## Of course you can use as an alternative smth like this:
        ## if msgID == CMSG_AUTH: self.msgAuth(msgID, data, client)
        ## elif...

        if msgID in Handlers.keys():
            Handlers[msgID](msgID, data, client)
        else:
            print("Unknown msgID: %d" % msgID)
            print(data)
        return

    def msgAuth(self, msgID, data, client):

        #########################################################
        ##
        ## Okay... The client sent us some Data. We need to extract
        ## the data the same way it was placed into the buffer.
        ## Its like "first in, first out"
        ##

        username = data.getString()
        password = data.getString()

        ## Now that we have the username and pwd, we need to
        ## determine if the client has the right user/pwd-combination.
        ## this variable will be sent later to the client, so lets
        ## create/define it here.
        flag = None

        if not username in USERS.keys():
            # unknown user
            ## That 0 is going to be sent later on. The client knows with
            ## that 0 that the username was not allowed.
            flag = 0
        elif USERS[username] == password:
            # authenticated, come on in
            flag = 1
            # CLIENTS[username] = 1
            # print("User: %s, logged in with pass: %s" % (username, password))
        else:
            # Wrong password, try again or bugger off
            flag = 2

        ## again... If you have read the client.py first, you know what
        ## I want to say. Do not use this type in a productive system.
        ## If you want to use it, just define 0 and 1.
        ## 1 -> Auth OK
        ## 0 -> Username/Password combination not correct.
        ## Otherwise its far too easy to get into the system...

        ## Creating a buffer to hold the data that is going to be sent.
        pkg = PyDatagram()

        ## The first Bytes we send to the client in that paket will be
        ## the ones that classify them as what they are. Here they mean
        ## "Hi Client! I am an Auth Response from the server."
        ## How does the client know that? Well, because both have a
        ## definition saying "SMSG_AUTH_RESPONSE  = 2"
        ## Due to shorter Network Pakets Yellow used Numbers instead
        ## of the whole Name. So you will see a 2 in the paket if you
        ## catch it somewhere...
        pkg.addUint16(SMSG_AUTH_RESPONSE)

        ## Now we are sending, if the auth was
        ## successfull ("1") or not ("0" or "2")
        pkg.addUint32(flag)

        ## Now lets send the whole story...
        self.cWriter.send(pkg, client)

    def msgChat(self, msgID, data, client):

        #########################################################
        ##
        ## This is again only an example showing you what you CAN
        ## do with the received code... Example: Sending it back.
        # print 'ChatMsg: ',chatMsg

        ## If you have trouble with the print command:
        ## print 'ChatMsg: ',data.GetString() does the same.
        ## Attention! The (partial) content of "data" is lost after the
        ## first getString()!!!
        ## If you want to test the above example, comment the
        ## next line out...

        print("ChatMsg: %s" % data.getString())

    def msgDisconnectReq(self, msgID, data, client):
        pkg = PyDatagram()
        pkg.addUint16(SMSG_DISCONNECT_ACK)
        self.cWriter.send(pkg, client)
        del CLIENTS[client]
        self.cReader.removeConnection(client)

    def quit(self):
        self.cManager.closeConnection(self.tcpSocket)
        sys.exit()

    def clientInputHandler(self, msgID, data, client):
        found = False
        clientClock = data.getUint64()
        # print('my time is', self.serverClock, 'client clock is', clientClock)
        if clientClock == self.serverClock:
            for c in CLIENT_INPUT_RECEIVED:
                if c == client:
                    found = True
                    break
            if not found:
                CLIENT_INPUT_RECEIVED.append(client)
                player = self.gameEngine.players[CLIENTS_ID[client]]

                x, y, z = 0, 0, 0
                w = data.getBool()
                a = data.getBool()
                s = data.getBool()
                d = data.getBool()
                shoot = data.getBool()
                if shoot:
                    x = data.getFloat32()
                    y = data.getFloat32()
                    z = data.getFloat32()
                    playerHitId = data.getString()
                    if playerHitId != "None":
                        playerHitId = int(playerHitId)
                        self.gameEngine.players[playerHitId].health -= 30
                        if self.gameEngine.players[playerHitId].health <= 0:
                            self.gameEngine.players[playerHitId].health = 0
                            if playerHitId in self.clientsAlive:
                                self.clientsAlive.pop(playerHitId)
                    player.weapon.fire_with_pos(self.gameEngine.world, x, y, z)
                h = data.getFloat32()
                p = data.getFloat32()

                if w:
                    self.gameEngine.speed.setY(self.gameEngine.walk_speed)
                if a:
                    self.gameEngine.speed.setX(-self.gameEngine.walk_speed)
                if s:
                    self.gameEngine.speed.setY(-self.gameEngine.walk_speed)
                if d:
                    self.gameEngine.speed.setX(self.gameEngine.walk_speed)

                player.playerNP.setH(h)
                player.playerSpine.setP(p)
                player.playerNP.node().setLinearMovement(
                    self.gameEngine.speed, True)

                self.clientInputList.addUint32(CLIENTS_ID[client])
                self.clientInputList.addFloat32(player.playerNP.getX())
                self.clientInputList.addFloat32(player.playerNP.getY())
                self.clientInputList.addFloat32(player.playerNP.getZ())
                self.clientInputList.addFloat32(player.playerNP.getH())
                self.clientInputList.addFloat32(player.playerSpine.getP())
                self.clientInputList.addFloat32(self.gameEngine.speed.getX())
                self.clientInputList.addFloat32(self.gameEngine.speed.getY())
                self.clientInputList.addBool(shoot)
                if shoot:
                    self.clientInputList.addFloat32(x)
                    self.clientInputList.addFloat32(y)
                    self.clientInputList.addFloat32(z)
                self.clientInputList.addUint8(player.health)
                self.gameEngine.speed.setX(0)
                self.gameEngine.speed.setY(0)

    def broadcastTask(self, task):
        if CLIENT_INPUT_RECEIVED.__len__() >= self.clientsAlive.__len__():
            # print("Broadcasting. Server Clock = " + str(self.serverClock))
            for c in CLIENTS:
                self.cWriter.send(self.clientInputList, c)

            self.serverClock += 1
            self.X = self.Y = 0
            self.clientInputList = PyDatagram()
            self.clientInputList.addUint16(SERVER_INPUT)
            self.clientInputList.addUint64(self.serverClock)
            CLIENT_INPUT_RECEIVED.clear()
            if self.clientsAlive.__len__() == 1:
                self.broadcastMsg("/game_end " +
                                  str(self.clientsAlive.popitem()[0]))
        else:
            pass
            # print("Waiting for all inputs. Server Clock = " + str(self.serverClock), "remaining users = " + str(self.clientsAlive.__len__() - CLIENT_INPUT_RECEIVED.__len__()))

        return task.cont

    #to send game's initial stats
    def gameStart(self):
        self.displayText.setText("Starting game...")
        if CLIENTS.__len__() > 1:
            ranValPkg = PyDatagram()
            ranValPkg.addUint16(GAME_INITIALIZE)
            ranValPkg.addUint32(self.playerCount)
            for client in CLIENTS:
                x = random.randint(1, 5)
                y = random.randint(1, 5)
                self.gameEngine.players.append(
                    Player(x, y, 20, CLIENTS_ID[client]))
                self.gameEngine.world.attachCharacter(self.gameEngine.players[
                    CLIENTS_ID[client]].playerNP.node())
                ranValPkg.addUint32(CLIENTS_ID[client])
                ranValPkg.addFloat32(x)
                ranValPkg.addFloat32(y)
            for client in CLIENTS:
                temp = ranValPkg.__copy__()
                temp.addUint32(CLIENTS_ID[client])
                self.cWriter.send(temp, client)
            taskMgr.add(self.update, 'update')
        else:
            self.broadcastMsg("/info no_clients")
            GameUI.createWhiteBgUI("Not enough clients connected.")
        self.displayText.destroy()

    # Update
    def update(self, task):
        dt = globalClock.getDt()
        self.gameEngine.world.doPhysics(dt)
        return task.cont

    def broadcastMsg(self, msg):
        pkg = PyDatagram()
        pkg.addUint16(SMSG_CHAT)
        pkg.addString(msg)
        for c in CLIENTS:
            self.cWriter.send(pkg, c)