def update_winner(self,task): closest=0 closestDist = 999999 for i in range(1,len(self.Server.players)): x=self.Server.players[i].getX() y=self.Server.players[i].getY() z=self.Server.players[i].getZ() mx=self.Server.players[0].getX() my=self.Server.players[0].getY() mz=self.Server.players[0].getZ() dist=math.sqrt((x-mx)**2+(y-my)**2+(z-mz)**2) #print i, dist if dist <closestDist: closest = i closestDist=dist #print closest, " is the closest" self.poloScores[closest]+=100.0/24.0/10000.0 update = PyDatagram() update.addUint8(101) for score in self.poloScores: update.addFloat32(score) self.broadcast(update) return task.cont
def syncSmiley(self, task): print "SYNCING SMILEYS!" sync = PyDatagram() sync.addFloat32(self.smiley.vel) sync.addFloat32(self.smiley.pos.getZ()) self.broadcast(sync) return task.again
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()
def moveRalph(self): pkg = PyDatagram() pkg.addUint16(114) pkg.addFloat32(self.ralph.getX()) pkg.addFloat32(self.ralph.getY()) pkg.addFloat32(self.ralph.getZ()) pkg.addFloat32(self.ralph.getH()) self.cWriter.send(pkg,self.connection)
def moveRequest(self, x, y, z, h, isMoving): pkg = PyDatagram() pkg.addUint16(106) pkg.addFloat32(x) pkg.addFloat32(y) pkg.addFloat32(z) pkg.addFloat32(h) pkg.addUint16(isMoving) return pkg
def makeTimeDataDatagram(self, frameCount, frameTime, dt): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_TIME_DATA) datagram.addUint32(frameCount) datagram.addFloat32(frameTime) datagram.addFloat32(dt) return datagram
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
def update_players(self, task): for ip, player in self.players.items(): if player.do_move(): datagram = PyDatagram() datagram.addInt8(player.pid) datagram.addFloat32(player.node.getX()) datagram.addFloat32(player.node.getY()) for conn in self.connections: self.writer.send(datagram, conn) return task.cont
def sendStatusUpdates(self, updates): pkg = PyDatagram() pkg.addUint16(SV_MSG_UPDATE_STATES) pkg.addUint16(len(updates)) for update in updates: pkg.addString(update["player"]) pkg.addUint8(update["status"]) pkg.addFloat32(update["health"]) pkg.addUint8(update["charge"]) pkg.addUint8(update["jump"]) for client in CLIENTS: self.cWriter.send(pkg, client)
def send(self, args = None): try: pkg = PyDatagram() pkg.addUint16(Constants.RAND_FLOAT) pkg.addFloat32(args) self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_FLOAT) + '] Float Request') except: self.log('Bad [' + str(Constants.RAND_FLOAT) + '] Float Request') print_exc()
def send(self, args=None): try: pkg = PyDatagram() pkg.addUint16(Constants.RAND_FLOAT) pkg.addFloat32(args) self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_FLOAT) + '] Float Request') except: self.log('Bad [' + str(Constants.RAND_FLOAT) + '] Float Request') print_exc()
def makeSelectedMovementDatagram(self,xyz,hpr,scale): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_SELECTED_MOVEMENT) 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]) return datagram
def makeSelectedMovementDatagram(self, xyz, hpr, scale): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_SELECTED_MOVEMENT) 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]) return datagram
def send(self, args = []): try: #print "In Req", args[0], args[1] pkg = PyDatagram() pkg.addUint16(Constants.CMSG_KEY) pkg.addString(args[0]) pkg.addFloat32(args[1]) self.cWriter.send(pkg, self.connection) #print("sent move: ", args[0], " ",args[1], " ", args[2]) #self.log('Sent [' + str(Constants.RAND_FLOAT) + '] Float Request') except: self.log('Bad [' + str(Constants.CMSG_KEY) + '] Key Request')
def handleCompleteSetup(self, msgID, data, senderClient): self.screenText.appendText("A new game will start... ") self.screenText.appendText(str(len(CLIENTS))) self.screenText.appendText(" pushies will fight to death.") setups = self.gameLogic.start() numberOfPlayers = len(setups) pkg = PyDatagram() pkg.addUint16(SV_MSG_START_GAME) pkg.addUint16(numberOfPlayers) for setup in setups: pkg.addString(setup["player"]) pkg.addFloat32(setup["position"][0]) pkg.addFloat32(setup["position"][1]) pkg.addFloat32(setup["position"][2]) for receiverClient in CLIENTS: self.cWriter.send(pkg, receiverClient)
def send(self, args=None): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) pkg.addFloat32(args[0]) #x pkg.addFloat32(args[1]) #y pkg.addFloat32(args[2]) #z pkg.addFloat32(args[3]) #h self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_FLOAT) + '] Float Request') except: self.log('Bad [' + str(Constants.CMSG_MOVE) + '] Move Request') print_exc()
def send(self, args = None): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) pkg.addFloat32(args[0])#x pkg.addFloat32(args[1])#y pkg.addFloat32(args[2])#z pkg.addFloat32(args[3])#h self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_FLOAT) + '] Float Request') except: self.log('Bad [' + str(Constants.CMSG_MOVE) + '] Move Request') print_exc()
def send(self, args=None): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_CREATE_CHARACTER) pkg.addUint16(args[0]) #TYPE pkg.addFloat32(args[1]) #x pos pkg.addFloat32(args[2]) #y pos pkg.addFloat32(args[3]) #z pos # print "RequestCreateCharacter - ", args[0], " x:", args[1], " y:", args[2]," z:", args[3] self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_STRING) + '] Int Request') except: self.log('Bad [' + str(Constants.RAND_STRING) + '] Int Request') print_exc()
def send(self, pos): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) posNew = pos.split(",") pkg.addFloat32(float(posNew[0])) pkg.addFloat32(float(posNew[1])) pkg.addFloat32(float(posNew[2])) pkg.addFloat32(float(posNew[3])) pkg.addInt32(int(posNew[4])) self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_STRING) + '] Int Request') except: self.log('Bad [' + str(Constants.CMSG_MOVE) + '] Int Request') print_exc()
def send(self, args = None): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_CREATE_CHARACTER) pkg.addUint16(args[0]) #TYPE pkg.addFloat32(args[1]) #x pos pkg.addFloat32(args[2]) #y pos pkg.addFloat32(args[3]) #z pos # print "RequestCreateCharacter - ", args[0], " x:", args[1], " y:", args[2]," z:", args[3] self.cWriter.send(pkg, self.connection) #self.log('Sent [' + str(Constants.RAND_STRING) + '] Int Request') except: self.log('Bad [' + str(Constants.RAND_STRING) + '] Int Request') print_exc()
def send(self, pos): try: pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) posNew = pos.split(",") pkg.addFloat32(float(posNew[0])) pkg.addFloat32(float(posNew[1])) pkg.addFloat32(float(posNew[2])) pkg.addFloat32(float(posNew[3])) pkg.addInt32(int(posNew[4])) self.cWriter.send(pkg, self.connection) # self.log('Sent [' + str(Constants.RAND_STRING) + '] Int Request') except: self.log("Bad [" + str(Constants.CMSG_MOVE) + "] Int Request") print_exc()
def send(self, forces): try: #print "Req Move: ", forces[3], forces[4], forces[5], forces[6], forces[7], forces[8] pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) pkg.addFloat32(forces[0]) pkg.addFloat32(forces[1]) pkg.addFloat32(forces[2]) pkg.addFloat32(forces[3]) pkg.addFloat32(forces[4]) pkg.addFloat32(forces[5]) pkg.addFloat32(forces[6]) pkg.addFloat32(forces[7]) pkg.addFloat32(forces[8]) self.cWriter.send(pkg, self.connection) except: self.log('Bad [' + str(Constants.CMSG_MOVE) + '] Move Request')
def send(self, username = None): try: user_data = username.split() x = float(user_data[0]) y = float(user_data[1]) z = float(user_data[2]) h = float(user_data[3]) print x print y print z print h pkg = PyDatagram() pkg.addUint16(Constants.CMSG_MOVE) pkg.addFloat32(x) pkg.addFloat32(y) pkg.addFloat32(z) pkg.addFloat32(h) self.cWriter.send(pkg, self.connection) except: self.log('Bad [' + str(Constants.CMSG_MOVE) + '] Request') print_exc()
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 move(self): self.player.x += 1 pkg = PyDatagram() pkg.addUint16(114) pkg.addFloat32(self.player.x) pkg.addFloat32(self.player.y) pkg.addFloat32(self.player.z) pkg.addFloat32(self.player.rotation) self.cWriter.send(pkg,self.connection)
def move(self): self.player.x += 1 pkg = PyDatagram() pkg.addUint16(114) pkg.addFloat32(self.player.x) pkg.addFloat32(self.player.y) pkg.addFloat32(self.player.z) pkg.addFloat32(self.player.rotation) self.cWriter.send(pkg, self.connection)
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)
def makeCamFrustumDatagram(self, focalLength, filmSize, filmOffset): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_CAM_FRUSTUM) datagram.addFloat32(focalLength) datagram.addFloat32(filmSize[0]) datagram.addFloat32(filmSize[1]) datagram.addFloat32(filmOffset[0]) datagram.addFloat32(filmOffset[1]) return datagram
def makeCamOffsetDatagram(self, xyz, hpr): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_CAM_OFFSET) datagram.addFloat32(xyz[0]) datagram.addFloat32(xyz[1]) datagram.addFloat32(xyz[2]) datagram.addFloat32(hpr[0]) datagram.addFloat32(hpr[1]) datagram.addFloat32(hpr[2]) return datagram
def makeCamMovementDatagram(self, xyz, hpr): datagram = PyDatagram() datagram.addUint32(self.packetNumber) self.packetNumber = self.packetNumber + 1 datagram.addUint8(CLUSTER_CAM_MOVEMENT) datagram.addFloat32(xyz[0]) datagram.addFloat32(xyz[1]) datagram.addFloat32(xyz[2]) datagram.addFloat32(hpr[0]) datagram.addFloat32(hpr[1]) datagram.addFloat32(hpr[2]) return datagram
def syncSmiley(self, task): for tempID in range(0,5): sync = PyDatagram() sync.addUint8(13) sync.addInt8(tempID) sync.addFloat32(self.Server.players[tempID].getX()) sync.addFloat32(self.Server.players[tempID].getY()) sync.addFloat32(self.Server.players[tempID].getZ()) sync.addFloat32(self.Server.players[tempID].getH()) sync.addFloat32(self.Server.players[tempID].getP()) sync.addFloat32(self.Server.players[tempID].getR()) #print "The velocity is ", self.Server.players[tempID].getTag("velocity") sync.addFloat32(1.0) #sync.addFloat32(float(self.Server.players[tempID].getTag("velocity"))) self.broadcast(sync) return task.again '''
def sendPositionUpdates(self, updates): pkg = PyDatagram() pkg.addUint16(SV_MSG_UPDATE_POSITIONS) pkg.addUint16(len(updates)) for update in updates: pkg.addString(update[0]) pkg.addFloat32(update[1][0]) pkg.addFloat32(update[1][1]) pkg.addFloat32(update[1][2]) pkg.addFloat32(update[2][0]) pkg.addFloat32(update[2][1]) pkg.addFloat32(update[2][2]) for client in CLIENTS: self.cWriter.send(pkg, client)
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
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
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
def send(self, kwargs): try: pkg = PyDatagram() pkg.addUint16(Constants.C_MOVE) pkg.addFloat32(kwargs['x']) pkg.addFloat32(kwargs['y']) pkg.addFloat32(kwargs['z']) pkg.addFloat32(kwargs['h']) pkg.addFloat32(kwargs['p']) pkg.addFloat32(kwargs['r']) self.cWriter.send(pkg, self.connection) self.log('Sent [' + str(Constants.C_MOVE) + '] RequestMove') except: self.log('Bad [' + str(Constants.C_MOVE) + '] RequestMove') print_exc()
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
def server_messager(self,msg,args=[]): if msg == "map_set": order = PyDatagram() order.addUint16(MAP_SET) order.addInt32(args[0]) self.send_package(order) elif msg == "client_update": order = PyDatagram() order.addUint16(CLIENT_INIT_UPDATE) order.addString(args[0]) order.addString(args[1]) order.addInt32(args[2]) order.addInt32(args[3]) self.send_package(order) elif msg == "chat_send": r = args[0][0] g = args[0][1] b = args[0][2] order = PyDatagram() order.addUint16(SERVER_CHAT) order.addInt32(r) order.addInt32(g) order.addInt32(b) order.addString(args[1]) self.send_package(order) base.menu_manager.menus["mp-game"].chat_add((r,g,b,1),args[1]) elif msg == "ready_button": order = PyDatagram() order.addUint16(SERVER_READY) order.addInt32(args[0]) order.addInt32(args[1]) self.send_package(order) base.menu_manager.menus["mp-game"].obj_list[args[0]]["indicatorValue"]=args[1] base.menu_manager.menus["mp-game"].start_game_check() elif msg == "server_loaded": order = PyDatagram() order.addUint16(SERVER_LOADED) self.send_package(order) elif msg == "all_loaded": order = PyDatagram() order.addUint16(ALL_LOADED) self.send_package(order) elif msg == "game_start": order = PyDatagram() order.addUint16(GAME_START) self.send_package(order) elif msg == "army_kill": order = PyDatagram() order.addUint16(ARMY_KILL) order.addInt32(args[0]) self.send_package(order) elif msg == "build_start": order = PyDatagram() order.addUint16(BUILD_START) order.addInt32(args[0]) order.addInt8(args[1]) order.addString(args[2]) self.send_package(order) elif msg == "tower_capture": order = PyDatagram() order.addUint16(TOWER_CAPTURE) order.addInt32(args[0]) order.addInt8(args[1]) self.send_package(order) elif msg == "build_complete": order = PyDatagram() order.addUint16(BUILD_COMPLETE) order.addInt32(args[0]) order.addInt8(args[1]) order.addString(args[2]) self.send_package(order) elif msg == "build_cancel": order = PyDatagram() order.addUint16(BUILD_CANCEL) order.addInt32(args[0]) self.send_package(order) elif msg == "battle_start": order = PyDatagram() order.addUint16(BATTLE_START) order.addInt32(args[0]) order.addFloat32(args[1]) order.addFloat32(args[2]) order.addInt32(args[3]) order.addFloat32(args[4]) order.addFloat32(args[5]) order.addInt32(args[6]) self.send_package(order) elif msg == "battle_clash": order = PyDatagram() order.addUint16(BATTLE_CLASH) order.addInt32(args[0]) order.addInt32(args[1]) order.addInt32(args[2]) order.addString(args[3]) order.addInt8(args[4]) self.send_package(order) elif msg == "battle_turn": order = PyDatagram() order.addUint16(BATTLE_TURN) order.addInt32(args[0]) order.addInt32(args[1]) self.send_package(order) elif msg == "battle_end": order = PyDatagram() order.addUint16(BATTLE_END) order.addInt32(args[0]) self.send_package(order) elif msg == "battle_armyadd": order = PyDatagram() order.addUint16(BATTLE_ARMYADD) order.addInt32(args[0]) order.addInt32(args[1]) order.addFloat32(args[2]) order.addFloat32(args[3]) self.send_package(order)
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)]))
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)
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
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)
def floatRequest(self, msg): pkg = PyDatagram() pkg.addUint16(4) pkg.addFloat32(msg) return pkg