def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.username = "******" type = 0 factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.username, type, factionId]) # Create control points self.cpList[1] = BasicControlPoint(1, 210.984, 115.005, 0, 10, RED) self.cpList[2] = BasicControlPoint(2, 141.016, 0.440607, 0, 10, RED) self.cpList[3] = BasicControlPoint(3, -0.766843, 9.40588, 0, 10, RED) self.cpList[4] = BasicControlPoint(4, -210.771, 113.753, 0, 10, BLUE) self.cpList[5] = BasicControlPoint(5, -149.953, 0.674369, 0, 10, BLUE) taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler')
def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.cManager.startConnection() # self.login = login(self) taskMgr.add(self.menu, "Menu")
def submitRRegister(self): print "username: "******"password: "******"re-password: "******"" and self.registerUsername.strip() != "": print "Success (", self.registerUsername, ", ", self.registerPassword, ", ", self.registerCPassword, ")" self.cManager.sendRequest( Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.cancel() else: taskMgr.add(self.errorMessage, "destroyIncorrectUsername") self.message() print "Failed (", self.registerUsername, ", ", self.registerPassword, ", ", self.registerCPassword, ")" else: print "Cannot Connect to the Server"
def submitLogin(self): print "Login" print "username: "******"password: "******"" and self.passwordInput is not ""): #c = characterSelection() print "You pressed Submit", self.usernameInput, " ; ", self.passwordInput self.cManager.sendRequest( Constants.CMSG_AUTH, (self.usernameInput, self.passwordInput)) """ THiS IS WHERE IT STARTS TO GET WEIRD """ #self.registerFrame.hide() #c = selectcharandteamtype(self.registerFrame) else: print "Please enter in a username and password" else: print "Cannot connect to server."
def __init__(self): print 'Loading character selection...' self.cManager = ConnectionManager() self.startConnection() frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A) frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top) pos=(-0.5, 0, 0.5)) self.createCreateCharWindow()
def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0, 0, 0, 1)) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.name = "CPHandler" factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler') # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): base.win.setClearColor(Vec4(0,0,0,1)) # Network Setup print "before" self.cManager = ConnectionManager(self) self.startConnection() print "after" taskMgr.add(self.menu, "Menu")
def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() print "Ran Main2" #taskMgr.add(self.menu, "Menu") self.login = login() self.login.createLogo() self.login.createLoginWindow() print "Finished"
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() #taskMgr.add(self.menu, "Menu") base.win.setClearColor(Vec4(0,0,0,1)) self.imageObject = OnscreenImage(parent = render2d, image = 'images/mainPage.png', pos = (0,0,0), scale = (1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.button = DirectButton(image ='images/button.png',pos = (-.1,0,-.25), relief = None, scale = .40, command = self.startWorld) self.button.setTransparency(TransparencyAttrib.MAlpha) #self.cAudio = def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def menu(self, task): # Accept raw_input choice choice = input("1 - Rand int\n2 - Rand string\n3 - Rand short\n4 - Rand float\n6 - Exit\n") msg = 0 if choice is 1: msg = random.randint(-(2**16), 2**16 - 1) elif choice is 2: msg = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for x in range(7)) elif choice is 3: msg = random.randint(0, 2**16 - 1) elif choice is 4: msg = 100 * random.random() elif choice is 6: sys.exit() else: print "Invalid input" self.cManager.sendRequest(choice, msg); def startWorld(self): #send login request print "elll"
def __init__(self): self.emitter = EventEmitter() self.cManager = ConnectionManager(self) self.tester = Tester(self) if self.startConnection(): loadPrcFileData("", "window-type none") # disable graphics loadPrcFileData("", "audio-library-name null") # disable audio ShowBase.__init__(self) self.cManager.initTasks() self.emitter.emit('connection') self.run()
def __init__(self, lobby): self.playerList = {} self.userList = [] self.otherPlayersDataAvailable = False self.lobby = lobby self.gameWorld = World(self) self.loadinScreen = LoadingScreen(self.gameWorld) self.lobby.World.ServerConnection.activeStatus = False self.cManager = ConnectionManager(self, self.lobby.World.ServerConnection) self.cManager.startConnection() self.gameWorld.cManager = self.cManager self.cManager.sendRequest(Constants.CMSG_REQ_TEST) self.addVehicleProps(self.lobby.World.username, 0, 0, 0, 0, 0, 0, 0, 0, 0) # self.cManager.sendRequest(Constants.CMSG_SET_POSITION) # while not self.otherPlayersDataAvailable: # print "Wait for respponse" # sleep(1) # Fake player creation for the time being # x = 10 # y = 10 # z = 0 # print "LOBBY LIST: ", self.lobby.playerList # if len(self.lobby.playerList) > 0: # for idx, player in enumerate(self.lobby.playerList): # if player != None: # print "Creating -", player # self.addPlayer(player, 1, 0, 0, x, y, z, 0, 0, 0) # x += 10 # y += 10 taskMgr.add(self.startGameTask, "startGameTask")
def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.startConnection() self.login = login(self) self.name = "" self.w = None
def __init__(self): self.frame = None self.buttonFrame = None self.dl = None self.dl2 = None self.dl3 = None self.regSel = None self.loginSel = None self.uid = None self.pwd = None self.reg = None self.submit = None self.lbl = None self.errorLbl = None self.directRadioButtonHandler = None print "UserGUIHandler Init" self.playerId = "" self.loginState = -1 self.registerState = -1 self.worldManager = finalhw1.WorldManager() self.world = self.worldManager.w self.connectionManager = ConnectionManager(self) self.world.setConnectionManager(self.connectionManager) self.connectionManager.startConnection()
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() print "Ran Main" #taskMgr.add(self.menu, "Menu") self.login = login() print "Finished" def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def menu(self, task): # Accept raw_input choice self.login = login() if self.login.getStatus() == "Authorized": print "going to character Select Menu" return task.done return task.again
def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.cManager.startConnection() taskMgr.add(self.menu, "Menu")
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() print "Ran Main2" #taskMgr.add(self.menu, "Menu") self.login = login() self.login.createLogo() self.login.createLoginWindow() print "Finished" def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def menu(self, task): # Accept raw_input choice self.login = login() if self.login.getStatus() == "Authorized": print "going to character Select Menu" return task.done return task.again
def submitRRegister(self): print "username: "******"password: "******"re-password: "******"") self.rePasswordEntry.enterText("") try: self.cManager = ConnectionManager() self.startConnection() print "" except Exception: self.error = True if self.error is False: if self.registerPassword == self.registerCPassword and self.registerPassword.strip() != "" and self.registerUsername.strip() != "": print "Success (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" self.cManager.sendRequest(Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.cancel() else: taskMgr.add(self.errorMessage, "destroyIncorrectUsername") self.message() print "Failed (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" else: print "Cannot Connect to the Server"
def __init__(self): print 'Loading Login...' self.cManager = ConnectionManager() self.startConnection() frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A) frameSize=(-1, 1, -1, 1),#(Left,Right,Bottom,Top) pos=(-0.5, 0, 0.5)) self.createLoginWindow()
def __init__(self): base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup print "before" self.cManager = ConnectionManager(self) self.startConnection() print "after" # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # add spheres earth = Earth(self) sun = Sun(self) venus = Venus(self) controls = Control() chat = Chat(self) player = Ralph(self) # player = Panda(self) # player = Car(self) taskMgr.add(player.move, "moveTask") taskMgr.add(sun.rotatePlanets, "rotateSun", extraArgs=[self.player], appendTask=True) taskMgr.add(earth.rotatePlanets, "rotateEarth", extraArgs=[self.player], appendTask=True) taskMgr.add(venus.rotatePlanets, "rotateVenus", extraArgs=[self.player], appendTask=True) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self, usernameInput): self.currentUser = usernameInput print 'Loading character selection...' self.cManager = ConnectionManager(self) self.startConnection() frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A) frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top) pos=(-0.5, 0, 0.5)) self.createSelectionWindow()
def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0,0,0,1)) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.name = "CPHandler" factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler') # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() print "Ran Main" #taskMgr.add(self.menu, "Menu") self.login = login() print "Finished"
def __init__(self): __builtin__.main=self #self.loginEntry = [] self.createLogin(); self.dict = {} try: self.cManager = ConnectionManager() self.startConnection() except Exception: self.error = True
def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() #taskMgr.add(self.menu, "Menu") base.win.setClearColor(Vec4(0, 0, 0, 1)) self.imageObject = OnscreenImage(parent=render2d, image='images/mainPage.png', pos=(0, 0, 0), scale=(1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.button = DirectButton(image='images/button.png', pos=(-.1, 0, -.25), relief=None, scale=.40, command=self.startWorld) self.button.setTransparency(TransparencyAttrib.MAlpha)
def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() #taskMgr.add(self.menu, "Menu") base.win.setClearColor(Vec4(0,0,0,1)) self.imageObject = OnscreenImage(parent = render2d, image = 'images/mainPage.png', pos = (0,0,0), scale = (1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.button = DirectButton(image ='images/button.png',pos = (-.1,0,-.25), relief = None, scale = .40, command = self.startWorld) self.button.setTransparency(TransparencyAttrib.MAlpha)
class Main(ShowBase): def __init__(self): self.state = Constants.GAMESTATE_NOT_LOGGED_IN self.cManager = ConnectionManager(self) if self.startConnection(): ShowBase.__init__(self) self.cManager.initTasks() self.login = Login(self) self.characterSelection = CharacterSelection(self) self.game = Game(self) self.login.createLoginWindow() #self.characterSelection.createSelectionWindow() #self.game.init() self.run() def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: print 'Connecting...' if not self.cManager.startConnection(): print 'Connection failed!' answer = raw_input('Reconnect? (Y/N): ').lower() if answer == 'y': return self.startConnection() else: return False return True
def clickedSubmit(self): print "you pressed play button and the game will start with cid: ", self.finalcid, "; character type : ",self.finalchar,"; character name :",self.finalname,"; and Faction :",self.finaltype #game starts from its base faction you have selected self.tempType = 0 self.tempFact = 0 if self.finalname == "sword": self.tempType = 1 if self.finaltype == "blue": self.tempFact = 1 if self.startConnection(): self.cManager.sendRequest(Constants.CMSG_SELECT_CHARACTER, (self.mainUsername, self.finalname, self.finalcid, self.tempType, self.tempFact)); else: self.cManager = ConnectionManager() self.startConnection() self.cManager.sendRequest(Constants.CMSG_SELECT_CHARACTER, (self.mainUsername, self.finalname, self.finalcid, self.tempType, self.tempFact));
class Main(ShowBase): def __init__(self): self.emitter = EventEmitter() self.cManager = ConnectionManager(self) self.tester = Tester(self) if self.startConnection(): loadPrcFileData("", "window-type none") # disable graphics loadPrcFileData("", "audio-library-name null") # disable audio ShowBase.__init__(self) self.cManager.initTasks() self.emitter.emit('connection') self.run() def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: print 'Connecting...' if not self.cManager.startConnection(): print 'Connection failed!' answer = raw_input('Reconnect? (Y/N): ').lower() if answer == 'y': return self.startConnection() else: return False return True def emit(event, data = {}): # terrible alias but I already wrote protocol code self.emitter.emit(event, data)
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.startConnection() self.login = login(self) self.name = "" self.w = None #taskMgr.add(self.menu, "Menu") def sendHeartbeat(self, task): self.cManager.sendRequest(Constants.REQ_HEARTBEAT); return task.again def loadWorld(self, x, y, type, name): character = Character(self.cManager, x, y, type, name) self.w = World(self, character) self.characters = {name: character} #taskMgr.doMethodLater(1, self.sendHeartbeat, 'heartbeat-routine') taskMgr.doMethodLater(1, self.sendHeartbeat, 'heartbeat-routine') def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True
def __init__(self): self.state = Constants.GAMESTATE_NOT_LOGGED_IN self.cManager = ConnectionManager(self) if self.startConnection(): ShowBase.__init__(self) self.cManager.initTasks() self.login = Login(self) self.characterSelection = CharacterSelection(self) self.game = Game(self) self.login.createLoginWindow() #self.characterSelection.createSelectionWindow() #self.game.init() self.run()
def clickedSubmit(self): self.usernameInput = self.userTextbox.get().strip() self.passwordInput = self.passTextbox.get().strip() self.error = False try: self.cManager = ConnectionManager() self.startConnection() except Exception: self.error = True if self.error is False: if(self.usernameInput is not "" and self.passwordInput is not ""): #c = characterSelection() print "You pressed Submit", self.usernameInput, " ; ",self.passwordInput self.cManager.sendRequest(Constants.CMSG_AUTH, (self.usernameInput, self.passwordInput)); else: print "Please enter in a username and password" else: print "Cannot connect to server."
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.cManager.startConnection() taskMgr.add(self.menu, "Menu") def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def menu(self, task): # Accept raw_input choice choice = input("1 - Rand int\n2 - Rand string\n3 - Rand short\n4 - Rand float\n101 - login\n6 - Exit\n") msg = 0 username = 0 password = 0 if choice is 1: msg = random.randint(-(2**16), 2**16 - 1) elif choice is 2: msg = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for x in range(7)) elif choice is 3: msg = random.randint(0, 2**16 - 1) elif choice is 4: msg = 100 * random.random() elif choice is 101: username = "******" password = "******" elif choice is 6: sys.exit() else: print "Invalid input" if choice is 101: self.cManager.sendRequest(choice, username+" "+password) else: self.cManager.sendRequest(choice, msg); return task.again
def clickedSubmit(self): print "you pressed play button and the game will start with cid: ", self.finalcid, "; character type : ",self.finalchar,"; character name :",self.finalname,"; and Faction :",self.finaltype #game starts from its base faction you have selected main.username = self.finalname #needs to be added. keyword self.tempType = 0 self.tempFact = 0 if self.finalname == "sword": self.tempType = 1 if self.finaltype == "blue": self.tempFact = 1 if self.startConnection(): self.cManager.sendRequest(Constants.CMSG_SELECT_CHARACTER, (self.mainUsername, self.finalname, int(self.finalcid), self.tempType, self.tempFact)); else: self.cManager = ConnectionManager() self.startConnection() self.cManager.sendRequest(Constants.CMSG_SELECT_CHARACTER, (self.mainUsername, self.finalname, int(self.finalcid), self.tempType, self.tempFact)); self.imageObject.hide(); self.destroyCreateCharWindow() self.destroySelectionWindow()
def clickedRegRegister(self): self.registerUsername = self.regInputUser.get() self.registerPassword = self.regInputPass.get() self.registerCPassword = self.regInputCPass.get() self.error = False try: self.cManager = ConnectionManager() self.startConnection() except Exception: self.error = True if self.error is False: if self.registerPassword == self.registerCPassword and self.registerPassword.strip() != "" and self.registerUsername.strip() != "": print "Success (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" self.cManager.sendRequest(Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.clickedRegCancel() else: self.failed = OnscreenText(text="Your password does not match Confirm Password.", pos=(0, -.7), scale=0.06,fg=Constants.TEXT_ERROR_COLOR, align=TextNode.ACenter,mayChange=0) self.failed.reparentTo(self.frame) print "Failed (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" else: print "Cannot Connect to the Server"
def submitLogin(self): print "Login" print "username: "******"password: "******"" and self.passwordInput is not ""): #c = characterSelection() print "You pressed Submit", self.usernameInput, " ; ",self.passwordInput self.cManager.sendRequest(Constants.CMSG_AUTH, (self.usernameInput, self.passwordInput)); """ THiS IS WHERE IT STARTS TO GET WEIRD """ #self.registerFrame.hide() #c = selectcharandteamtype(self.registerFrame) else: print "Please enter in a username and password" else: print "Cannot connect to server."
class RRWorldManager(): def __init__(self, lobby): self.playerList = {} self.userList = [] self.otherPlayersDataAvailable = False self.lobby = lobby self.gameWorld = World(self) self.loadinScreen = LoadingScreen(self.gameWorld) self.lobby.World.ServerConnection.activeStatus = False self.cManager = ConnectionManager(self, self.lobby.World.ServerConnection) self.cManager.startConnection() self.gameWorld.cManager = self.cManager self.cManager.sendRequest(Constants.CMSG_REQ_TEST) self.addVehicleProps(self.lobby.World.username, 0, 0, 0, 0, 0, 0, 0, 0, 0) # self.cManager.sendRequest(Constants.CMSG_SET_POSITION) # while not self.otherPlayersDataAvailable: # print "Wait for respponse" # sleep(1) # Fake player creation for the time being # x = 10 # y = 10 # z = 0 # print "LOBBY LIST: ", self.lobby.playerList # if len(self.lobby.playerList) > 0: # for idx, player in enumerate(self.lobby.playerList): # if player != None: # print "Creating -", player # self.addPlayer(player, 1, 0, 0, x, y, z, 0, 0, 0) # x += 10 # y += 10 taskMgr.add(self.startGameTask, "startGameTask") def startGameTask(self, task): if self.otherPlayersDataAvailable: self.startGameSequence() return task.done else: return task.cont def addVehicleProps(self, username, carId, carPaint, carTires, x, y, z, h, p, r): if username in self.playerList.keys(): vehicle = self.playerList[username] vehicle.carId = carId vehicle.carPaint = carPaint vehicle.carTires = carTires vehicle.x = x vehicle.y = y vehicle.z = z vehicle.h = h vehicle.p = p vehicle.r = r self.playerList[username] = vehicle else: vehicle = VehicleAttributes(username, carId, carPaint, carTires, x, y, z, h, p, r) print "Adding to list player: ", username self.playerList[username] = vehicle def modifyPlayerPos(self, username, x, y, z, h, p, r): if username in self.playerList.keys(): vehicle = self.playerList[username] vehicle.x = x vehicle.y = y vehicle.z = z vehicle.h = h vehicle.p = p vehicle.r = r self.playerList[username] = vehicle else: VehicleAttributes(username, 0, 0, 0, x, y, z, h, p, r) def startGameSequence(self): self.loadinScreen.finish() self.gameWorld.initializeGameWorld()
class World(DirectObject): def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.username = "******" type = 0 factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.username, type, factionId]) # Create control points self.cpList[1] = BasicControlPoint(1, 210.984, 115.005, 0, 10, RED) self.cpList[2] = BasicControlPoint(2, 141.016, 0.440607, 0, 10, RED) self.cpList[3] = BasicControlPoint(3, -0.766843, 9.40588, 0, 10, RED) self.cpList[4] = BasicControlPoint(4, -210.771, 113.753, 0, 10, BLUE) self.cpList[5] = BasicControlPoint(5, -149.953, 0.674369, 0, 10, BLUE) taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler') def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def refresh(self, task): self.cManager.sendRequest(Constants.REQ_HEARTBEAT) return task.again def CPHandler(self, task): for cp in self.cpList.values(): if cp.factionId == RED: if cp.checkContested(self.characters): print("CP [", cp.id, "] is contested") elif cp.checkBluePresence(self.characters): cp.timer -= 1 print(cp.id, cp.timer) if cp.timer == 0: print("CP [", cp.id, "] taken by Blue") cp.factionId = BLUE #main.controlNpc.switchControl(cp.id) self.cManager.sendRequest(Constants.CMSG_NPCDEATH, [cp.id]) print "Sending Message : ", print cp.id else: cp.timer = 30 elif cp.factionId == BLUE: if cp.checkContested(self.characters): print("CP [", cp.id, "] contested") elif cp.checkRedPresence(self.characters): cp.timer += 1 print(cp.id, cp.timer) if cp.timer == 30: print("CP [", cp.id, "] taken by Red") cp.factionId = RED #main.controlNpc.switchControl(cp.id) self.cManager.sendRequest(Constants.CMSG_NPCDEATH, [cp.id]) else: cp.timer = 0 # Send 'timer' to server, which send to all clients self.cManager.sendRequest(Constants.CMSG_CONTROL_POINT_STATE, [cp.id, cp.timer, cp.factionId]) return task.again
class login: def __init__(self): #self.loginEntry = [] self.createLogin(); def createLogin(self): base.win.setClearColor(Vec4(0,0,0,1)) self.imageObject = OnscreenImage(parent = render2d, image = 'images/mainPage.png', pos = (0,0,0), scale = (1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.createMainFrame() self.createText() self.createTextEntry() self.createButtons() def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def createMainFrame(self): """Create the main base frame.""" self.registerFrame = DirectFrame( frameSize = (-0.512, 0.512, -0.362, 0.362), frameColor = (0.53, 0.42, 0.18, 0.70), pos = (0, 0, -0.28) ) self.mainBox = DirectFrame( frameSize = (-0.5, 0.5, -0.35, 0.35), frameColor = (0, 0, 0, 0.25), pos = (0, 0, 0) ) self.mainBox.reparentTo(self.registerFrame) self.blackFrame = DirectFrame( frameSize = (-2, 2, -2, 2), frameColor = (0, 0, 0, 0.3), pos = (0, 0, 0), state = DGG.NORMAL ) self.blackFrame.reparentTo(self.registerFrame, 1) self.blackFrame.hide() def createText(self): """Create some label for login text entry field""" self.headerLabel = DirectLabel(text='LOG IN', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1,1,1,1), text_scale=0.07, frameColor=(0, 0, 0, 0), pos=(0, 0, 0.23)) self.headerLabel.reparentTo(self.registerFrame) self.usernameLabel = DirectLabel(text='Username', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, 0.067)) self.usernameLabel.reparentTo(self.registerFrame) self.passwordLabel = DirectLabel(text='Password', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.070)) self.passwordLabel.reparentTo(self.registerFrame) def createTextEntry(self): """Create entry boxes for credentials.""" self.usernameEntry = DirectEntry(self.registerFrame,scale=0.055, pos=(-0.14, 0, 0.055), command=self.submitLogin, focus=1, focusInCommand=self.focus("username"), #focusInExtraArgs=[0], rolloverSound = None) self.usernameEntry.reparentTo(self.registerFrame) #self.loginEntry.append(self.usernameEntry) self.passwordEntry = DirectEntry(self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.08), command=self.submitLogin, obscured=1, focusInCommand=self.focus("password"), #focusInExtraArgs=[1], rolloverSound = None) self.passwordEntry.reparentTo(self.registerFrame) #self.loginEntry.append(self.passwordEntry) def createButtons(self): """Create some buttons.""" self.validateLoginFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (0.33, 0.42, 0.18, 0.95), # color of the login button pos = (-0.2, 0, -0.22) ) self.validateLoginFrame.reparentTo(self.mainBox) self.validateLogin = DirectButton (text='Log In', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.submitLogin, clickSound = None, rolloverSound = None) self.validateLogin.reparentTo(self.validateLoginFrame) self.registerButtonFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (1, 0, 1, 1), # color of the register button pos = (0.2, 0, -0.22) ) self.registerButtonFrame.reparentTo(self.mainBox) self.registerButton = DirectButton(text='Register', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.register, clickSound = None, rolloverSound = None) self.registerButton.reparentTo(self.registerButtonFrame) def focus(self, text): print text def clickedCancel(self): print "You pressed Cancel" exit() def submitLogin(self): print "Login" print "username: "******"password: "******"" and self.passwordInput is not ""): #c = characterSelection() print "You pressed Submit", self.usernameInput, " ; ",self.passwordInput self.cManager.sendRequest(Constants.CMSG_AUTH, (self.usernameInput, self.passwordInput)); """ THiS IS WHERE IT STARTS TO GET WEIRD """ #self.registerFrame.hide() #c = selectcharandteamtype(self.registerFrame) else: print "Please enter in a username and password" else: print "Cannot connect to server." #def resume(self): #self.registerFrame.show() def register(self): """Switch to the registration screen.""" self.registerFrame.hide() #R = Register(self.registerFrame) base.win.setClearColor(Vec4(0,0,0,1)) self.imageObject = OnscreenImage(parent = render2d, image = 'images/mainPage.png', pos = (0,0,0), scale = (1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.createRMainFrame() self.createRText() self.createRTextEntry() self.createRButtons() self.error = False print "Register" def createRMainFrame(self): """Create the main base frame.""" # frameColor is defined as (R,G,B,A) self.registerFrame = DirectFrame( frameSize = (-0.612, 0.612, -0.462, 0.462), frameColor = (0.53, 0.42, 0.18, 0.70), pos = (0, 0, -0.37) ) self.mainBox = DirectFrame( frameSize = (-0.6, 0.6, -0.45, 0.45), frameColor = (0, 0, 0, 0.25), pos = (0, 0, 0) ) self.mainBox.reparentTo(self.registerFrame) self.blackFrame = DirectFrame( frameSize = (-2, 2, -2, 2), frameColor = (0, 0, 0, 0.3), pos = (0, 0, 0), state = DGG.NORMAL ) self.blackFrame.reparentTo(self.registerFrame, 1) self.blackFrame.hide() def createRText(self): """Create some label for login text entry field""" self.headerLabel = DirectLabel(text='REGISTER', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1,1,1,1), text_scale=0.07, frameColor=(0, 0, 0, 0), pos=(0, 0, 0.28)) self.headerLabel.reparentTo(self.registerFrame) self.usernameLabel = DirectLabel(text='Username', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, 0.12)) self.usernameLabel.reparentTo(self.registerFrame) self.passwordLabel = DirectLabel(text='Password', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.023)) self.passwordLabel.reparentTo(self.registerFrame) self.rePasswordLabel = DirectLabel(text='Re-Password', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.16)) self.rePasswordLabel.reparentTo(self.registerFrame) def createRTextEntry(self): """Create entry boxes for credentials.""" self.usernameEntry = DirectEntry(self.registerFrame,scale=0.055, pos=(-0.14, 0, 0.12), command=self.submitRRegister, focus=1, #focusInCommand=self.setFocus, focusInExtraArgs=[0], rolloverSound = None) self.usernameEntry.reparentTo(self.registerFrame) self.passwordEntry = DirectEntry(self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.025), command=self.submitRRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[1], rolloverSound = None) self.passwordEntry.reparentTo(self.registerFrame) self.rePasswordEntry = DirectEntry(self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.165), command=self.submitRRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[2], rolloverSound = None) self.rePasswordEntry.reparentTo(self.registerFrame) def createRButtons(self): """Create some buttons.""" self.validateRegFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (0.33, 0.42, 0.18, 0.95), pos = (-0.2, 0, -0.30) ) self.validateRegFrame.reparentTo(self.mainBox) self.validateReg = DirectButton (text='Register', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.submitRRegister, clickSound = None, rolloverSound = None) self.validateReg.reparentTo(self.validateRegFrame) self.registerButtonFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (0.33, 0.42, 0.18, 0.95), pos = (0.2, 0, -0.30) ) self.registerButtonFrame.reparentTo(self.mainBox) self.registerButton = DirectButton(text='Cancel', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.cancel, clickSound = None, rolloverSound = None) self.registerButton.reparentTo(self.registerButtonFrame) def submitRRegister(self): print "username: "******"password: "******"re-password: "******"" and self.registerUsername.strip() != "": print "Success (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" self.cManager.sendRequest(Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.cancel() else: taskMgr.add(self.errorMessage, "destroyIncorrectUsername") self.message() print "Failed (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" else: print "Cannot Connect to the Server" def errorMessage(self, task): if task.time < 5.0: return task.cont else: self.failed.destroy() return task.done def message(self): self.failed = DirectLabel(text='Password needs to match', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1,1,1,1), text_scale=0.07, frameColor=(255, 0, 0, 1), pos=(0, 0, 0.20)) self.failed.reparentTo(self.registerFrame) def cancel(self): print "cancel" self.registerFrame.hide() self.createLogin()
class World(DirectObject): def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # Placeholder Login self.name = str(raw_input("Name: ")) factionId = int(input("Faction ID: ")) self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 # Create the control point Bar UI self.cp_bar = ControlPointBar() self.resource_bar = ResourceBar() taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, "CPHandler") taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def refresh(self, task): self.cManager.sendRequest(Constants.REQ_HEARTBEAT) return task.again #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Set the control point circle's height to Ralph's #for cp in self.cpList: # cp.model.setZ(self.character.actor.getZ() + 0.1) # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.character.actor) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.character.actor.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"] != 0): self.character.actor.setH(self.character.actor.getH() + 300 * globalClock.getDt()) if (self.keyMap["right"] != 0): self.character.actor.setH(self.character.actor.getH() - 300 * globalClock.getDt()) if (self.keyMap["forward"] != 0): self.character.actor.setY(self.character.actor, -25 * globalClock.getDt()) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["forward"] != 0) or (self.keyMap["left"] != 0) or (self.keyMap["right"] != 0): if self.isMoving is False: self.character.actor.loop("run") self.isMoving = True else: if self.isMoving: self.character.actor.stop() self.character.actor.pose("walk", 5) self.isMoving = False self.cManager.sendRequest(Constants.CMSG_MOVE, [ self.character.actor.getX(), self.character.actor.getY(), self.character.actor.getZ(), self.character.actor.getH() ]) # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.character.actor.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.character.actor.getPos()) self.floater.setZ(self.character.actor.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont # Used for checking whether to show the control point capture bar def inWhichControlPoint(self): for cp in self.cpList.values(): if cp.withinCircle(self.character.actor): return cp return None def CPBarHandler(self, task): # This is where you check to see if you are in a control point # to render the bar or not currentCP = self.inWhichControlPoint() if currentCP is not None: self.cp_bar.show() self.cp_bar.setValue(currentCP.timer) else: self.cp_bar.hide() return task.again def CPHandler(self, task): # Change colors of control points to match their faction for cp in self.cpList.values(): if cp.timer == 0: cp.model.setColor(0, 0, 255) if cp.timer == 30: cp.model.setColor(255, 0, 0) return task.again
class selectcharandteamtype(DirectObject): TEXT_COLOR = (1,1,1,1) FONT_TYPE_01 = 0 TEXT_SHADOW_COLOR = (0,0,0,0.5) characterSelectionInput = "" output = "" frame = DirectFrame() #character creation varaiables v=[0] v1=[0] nameOfChar = OnscreenText() nameOfCharTextbox = DirectEntry() factionSelection = OnscreenText() nameOfCharInput ='' charactertype = OnscreenText() def __init__(self): print 'Loading character selection...' self.cManager = ConnectionManager() self.startConnection() frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A) frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top) pos=(-0.5, 0, 0.5)) self.createCreateCharWindow() def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True #character Creation def createCreateCharWindow(self): self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A) frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top) pos=(-0.5, 0, 0.9)) self.charactertype = OnscreenText(text = "Character type :", pos = (-0.60, 0.32), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0) self.factionSelection.reparentTo(self.frame) self.buttons = [ DirectRadioButton(text = ' Axe ', variable=self.v, value=[0], scale=0.07, pos=(-0.05,0,0.32), command=self.setText), DirectRadioButton(text = ' Sword ', variable=self.v, value=[1], scale=0.07, pos=(0.3,0,0.32), command=self.setText) ] for button in self.buttons: button.setOthers(self.buttons) self.factionSelection = OnscreenText(text = "Faction Selection :", pos = (-0.15, -0.95), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0) self.factionSelection.reparentTo(self.frame) self.factionBtns = [ DirectRadioButton(text = ' Blue ', variable=self.v1, value=[0], scale=0.07, pos=(-0.05,0,-0.05), command=self.setfaction), DirectRadioButton(text = ' Red ', variable=self.v1, value=[1], scale=0.07, pos=(0.3,0,-0.05), command=self.setfaction) ] for button1 in self.factionBtns: button1.setOthers(self.factionBtns) self.okForCreateBtn = DirectButton(text = ("Start", "Start", "Start", "disabled"), scale=.08, command=self.clickedOkForCreateBtn, pos=(-0.05, 0.0, -1.25)) self.cancelForCreateBtn = DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancelForCreateBtn, pos=(0.4, 0.0, -1.25)) self.okForCreateBtn.reparentTo(self.frame) self.cancelForCreateBtn.reparentTo(self.frame) def destroyCreateCharWindow(self): self.frame.destroy() self.nameOfChar.destroy() self.nameOfCharTextbox.destroy() self.factionSelection.destroy() self.okForCreateBtn.destroy() self.cancelForCreateBtn.destroy() def clearnameOfChar(self): self.nameOfCharTextbox.enterText('') def getnameOfChar(self): self.nameOfCharInput = self.nameOfCharTextbox.get() def setnameOfChar(self, textEntered): print "name Of Char: ",textEntered self.nameOfChar = textEntered def clickedOkForCreateBtn(self): self.nameOfCharInput = self.nameOfCharTextbox.get().strip() print "you have pressed the ok button for creating a character" print "you have Created a char of type",self.chartitle,";Faction : ",self.factiontitle self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, (self.chartitle, self.factiontitle)); def clickedCancelForCreateBtn(self): print "you have press the cancel button from the create character frame" self.destroyCreateCharWindow() def setText(self): self.chartitle = "" if self.v[0]: self.chartitle="sword" else: self.chartitle="axe" def setfaction(self): self.factiontitle = "" if self.v1[0]: self.factiontitle="red" else: self.factiontitle="blue"
class Register: def __init__(self, oldFrame): self.oldFrame = oldFrame; base.win.setClearColor(Vec4(0,0,0,1)) self.imageObject = OnscreenImage(parent = render2d, image = 'images/mainPage.png', pos = (0,0,0), scale = (1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.createMainFrame() self.createText() self.createTextEntry() self.createButtons() self.error = False def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def createMainFrame(self): """Create the main base frame.""" # frameColor is defined as (R,G,B,A) self.registerFrame = DirectFrame( frameSize = (-0.612, 0.612, -0.462, 0.462), frameColor = (0.53, 0.42, 0.18, 0.70), pos = (0, 0, -0.37) ) self.mainBox = DirectFrame( frameSize = (-0.6, 0.6, -0.45, 0.45), frameColor = (0, 0, 0, 0.25), pos = (0, 0, 0) ) self.mainBox.reparentTo(self.registerFrame) self.blackFrame = DirectFrame( frameSize = (-2, 2, -2, 2), frameColor = (0, 0, 0, 0.3), pos = (0, 0, 0), state = DGG.NORMAL ) self.blackFrame.reparentTo(self.registerFrame, 1) self.blackFrame.hide() def createText(self): """Create some label for login text entry field""" self.headerLabel = DirectLabel(text='REGISTER', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1,1,1,1), text_scale=0.07, frameColor=(0, 0, 0, 0), pos=(0, 0, 0.28)) self.headerLabel.reparentTo(self.registerFrame) self.usernameLabel = DirectLabel(text='Username', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, 0.12)) self.usernameLabel.reparentTo(self.registerFrame) self.passwordLabel = DirectLabel(text='Password', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.023)) self.passwordLabel.reparentTo(self.registerFrame) self.rePasswordLabel = DirectLabel(text='Re-Password', text_align = TextNode.ARight, text_fg=(1,1,1,1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.16)) self.rePasswordLabel.reparentTo(self.registerFrame) def createTextEntry(self): """Create entry boxes for credentials.""" self.usernameEntry = DirectEntry(self.registerFrame,scale=0.055, pos=(-0.14, 0, 0.12), command=self.submitRegister, focus=1, #focusInCommand=self.setFocus, focusInExtraArgs=[0], rolloverSound = None) self.usernameEntry.reparentTo(self.registerFrame) self.passwordEntry = DirectEntry(self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.025), command=self.submitRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[1], rolloverSound = None) self.passwordEntry.reparentTo(self.registerFrame) self.rePasswordEntry = DirectEntry(self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.165), command=self.submitRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[2], rolloverSound = None) self.rePasswordEntry.reparentTo(self.registerFrame) def createButtons(self): """Create some buttons.""" self.validateRegFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (0.33, 0.42, 0.18, 0.95), pos = (-0.2, 0, -0.30) ) self.validateRegFrame.reparentTo(self.mainBox) self.validateReg = DirectButton (text='Register', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.submitRegister, clickSound = None, rolloverSound = None) self.validateReg.reparentTo(self.validateRegFrame) self.registerButtonFrame = DirectFrame( frameSize = (-0.131, 0.131, -0.056, 0.056), frameColor = (0.33, 0.42, 0.18, 0.95), pos = (0.2, 0, -0.30) ) self.registerButtonFrame.reparentTo(self.mainBox) self.registerButton = DirectButton(text='Cancel', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.cancel, clickSound = None, rolloverSound = None) self.registerButton.reparentTo(self.registerButtonFrame) def submitRegister(self): print "username: "******"password: "******"re-password: "******"" and self.registerUsername.strip() != "": print "Success (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" self.cManager.sendRequest(Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.clickedRegCancel() else: taskMgr.add(self.errorMessage, "destroyIncorrectUsername") self.message() print "Failed (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")" else: print "Cannot Connect to the Server" def errorMessage(self, task): if task.time < 5.0: return task.cont else: self.failed.destroy() return task.done def message(self): self.failed = DirectLabel(text='Password needs to match', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1,1,1,1), text_scale=0.07, frameColor=(255, 0, 0, 1), pos=(0, 0, 0.20)) self.failed.reparentTo(self.registerFrame) def cancel(self): print "cancel" self.registerFrame.hide() self.oldFrame.show()
class characterSelection(DirectObject): TEXT_COLOR = (1, 1, 1, 1) FONT_TYPE_01 = 0 TEXT_SHADOW_COLOR = (0, 0, 0, 0.5) characterSelectionInput = "" output = "" frame = DirectFrame() # character selection varaiables createCharacter = DirectButton() deleteCharacter = DirectButton() selectCharacter = OnscreenText() selectCharacterTextbox = DirectEntry() selectCharacterInput = "" referenceForSelection = OnscreenText() myScrolledList = DirectScrolledList() submitBtn = DirectButton() cancelBtn = DirectButton() # character deletion varaiables selectCharactertodelete = OnscreenText() deleteBtn = DirectButton() delCancelBtn = DirectButton() CharacterToDeleteTextbox = DirectEntry() referenceForDeletion = OnscreenText() CharacterToDeleteInput = " " # character creation varaiables v = [0] v1 = [0] nameOfChar = OnscreenText() nameOfCharTextbox = DirectEntry() factionSelection = OnscreenText() nameOfCharInput = "" def __init__(self): print "Loading character selection..." self.cManager = ConnectionManager() self.startConnection() frame = DirectFrame( frameColor=(0, 0, 0, 1), # (R,G,B,A) frameSize=(-3, 3, -3, 3), # (Left,Right,Bottom,Top) pos=(-0.5, 0, 0.5), ) self.createSelectionWindow() def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True # character Creation def createCreateCharWindow(self): self.frame = DirectFrame( frameColor=(0, 0, 0, 1), # (R,G,B,A) frameSize=(-3, 3, -3, 3), # (Left,Right,Bottom,Top) pos=(-0.5, 0, 0.9), ) self.buttons = [ DirectRadioButton( text=" Sword ", variable=self.v, value=[0], scale=0.07, pos=(-0.4, 0, 0.32), command=self.setText ), DirectRadioButton( text=" Axe ", variable=self.v, value=[1], scale=0.07, pos=(0.2, 0, 0.32), command=self.setText ), ] for button in self.buttons: button.setOthers(self.buttons) self.nameOfChar = OnscreenText( text="Name The Character :", pos=(-0.2, -0.75), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.nameOfChar.reparentTo(self.frame) self.nameOfCharTextbox = DirectEntry( text="", scale=0.07, pos=(0.25, 0, -0.75), command=self.setnameOfChar, initialText="name of character", numLines=1, focus=0, focusInCommand=self.clearnameOfChar, focusOutCommand=self.getnameOfChar, ) self.nameOfCharTextbox.reparentTo(self.frame) self.factionSelection = OnscreenText( text="Faction Selection :", pos=(-0.15, -0.95), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.factionSelection.reparentTo(self.frame) self.factionBtns = [ DirectRadioButton( text=" Blue ", variable=self.v1, value=[0], scale=0.07, pos=(-0.05, 0, -0.05), command=self.setfaction ), DirectRadioButton( text=" Red ", variable=self.v1, value=[1], scale=0.07, pos=(0.3, 0, -0.05), command=self.setfaction ), ] for button1 in self.factionBtns: button1.setOthers(self.factionBtns) self.okForCreateBtn = DirectButton( text=("Ok", "Ok", "Ok", "disabled"), scale=0.08, command=self.clickedOkForCreateBtn, pos=(-0.05, 0.0, -1.25) ) self.cancelForCreateBtn = DirectButton( text=("Cancel", "Cancel", "Cancel", "disabled"), scale=0.08, command=self.clickedCancelForCreateBtn, pos=(0.4, 0.0, -1.25), ) self.okForCreateBtn.reparentTo(self.frame) self.cancelForCreateBtn.reparentTo(self.frame) def destroyCreateCharWindow(self): self.frame.destroy() self.nameOfChar.destroy() self.nameOfCharTextbox.destroy() self.factionSelection.destroy() self.okForCreateBtn.destroy() self.cancelForCreateBtn.destroy() def clearnameOfChar(self): self.nameOfCharTextbox.enterText("") def getnameOfChar(self): self.nameOfCharInput = self.nameOfCharTextbox.get() def setnameOfChar(self, textEntered): print "name Of Char: ", textEntered self.nameOfChar = textEntered def clickedOkForCreateBtn(self): print "you have pressed the ok button for creating a character" def clickedCancelForCreateBtn(self): print "you have press the cancel button from the create character frame" self.destroyCreateCharWindow() self.createSelectionWindow() def setText(status=None): bk_text = "CurrentValue " def setfaction(status=None): bk_text = "CurrentValue " # character deletion def createDeleteCharWindow(self): self.frame = DirectFrame( frameColor=(0, 0, 0, 1), # (R,G,B,A) frameSize=(-3, 3, -3, 3), # (Left,Right,Bottom,Top) pos=(-0.5, 0, 0.9), ) self.selectCharactertodelete = OnscreenText( text="Select Character :", pos=(-0.02, -0.35), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.selectCharactertodelete.reparentTo(self.frame) self.selectCharacterToDeleteTextbox = DirectEntry( text="", scale=0.07, pos=(0.45, 0, -0.35), command=self.setselectCharacterToDelete, initialText="name of character", numLines=1, focus=0, focusInCommand=self.clearselectCharacterToDelete, focusOutCommand=self.getselectCharacterToDelete, ) self.selectCharacterToDeleteTextbox.reparentTo(self.frame) self.referenceForDeletion = OnscreenText( text="Reference to Character List:", pos=(-0.15, -0.75), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.referenceForDeletion.reparentTo(self.frame) self.deleteScrolledList = DirectScrolledList( decButton_pos=(0.35, 0, 0.53), decButton_text="Dec", decButton_text_scale=0.04, decButton_borderWidth=(0.005, 0.005), incButton_pos=(0.35, 0, -0.02), incButton_text="Inc", incButton_text_scale=0.04, incButton_borderWidth=(0.005, 0.005), pos=(0.7, 0, -0.99), numItemsVisible=4, forceHeight=0.11, itemFrame_frameSize=(-0.6, 0.6, -0.37, 0.11), itemFrame_pos=(0.35, 0, 0.4), ) for playerchar in ["xxxbluesword", "xxxblueaxe", "xxxredsword", "xxxredsword01", "xxx_red_sword04"]: l = DirectLabel(text=playerchar, text_scale=0.1) self.deleteScrolledList.addItem(l) self.deleteScrolledList.reparentTo(self.frame) self.deleteBtn = DirectButton( text=("Delete", "Delete", "Delete", "disabled"), scale=0.08, command=self.clickedDelete, pos=(-0.2, 0.0, -1.25), ) self.delCancelBtn = DirectButton( text=("Cancel", "Cancel", "Cancel", "disabled"), scale=0.08, command=self.clickedDelCancel, pos=(0.3, 0.0, -1.25), ) self.deleteBtn.reparentTo(self.frame) self.delCancelBtn.reparentTo(self.frame) def destroyDeleteCharWindow(self): self.frame.destroy() self.selectCharactertodelete.destroy() self.deleteBtn.destroy() self.delCancelBtn.destroy() self.selectCharacterToDeleteTextbox.destroy() self.referenceForDeletion.destroy() def clearselectCharacterToDelete(self): self.selectCharacterToDeleteTextbox.enterText("") def getselectCharacterToDelete(self): self.selectCharacterToDeleteInput = self.nameOfCharTextbox.get() def setselectCharacterToDelete(self, textEntered): print "name Of Char: ", textEntered self.selectCharacterToDelete = textEntered def clickedDelete(self): print "You pressed delete a character" def clickedDelCancel(self): print "to go back to slection menu" self.destroyDeleteCharWindow() self.createSelectionWindow() # character Selection def createSelectionWindow(self): self.frame = DirectFrame( frameColor=(0, 0, 0, 1), # (R,G,B,A) frameSize=(-3, 3, -3, 3), # (Left,Right,Bottom,Top) pos=(-0.5, 0, 0.9), ) self.createCharacter = DirectButton( text=("Create Character", "Create Character", "Create Character", "disabled"), scale=0.08, command=self.clickedCreateChar, pos=(-0.14, 0.0, -0.25), ) self.deleteCharacter = DirectButton( text=("Delete Character", "Delete Character", "Delete Character", "disabled"), scale=0.08, command=self.clickedDeleteChar, pos=(-0.14, 0.0, -0.40), ) self.createCharacter.reparentTo(self.frame) self.deleteCharacter.reparentTo(self.frame) self.selectCharacter = OnscreenText( text="Select Character :", pos=(-0.12, -0.55), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.selectCharacter.reparentTo(self.frame) self.myScrolledList = DirectScrolledList( decButton_pos=(0.35, 0, 0.53), decButton_text="Dec", decButton_text_scale=0.04, decButton_borderWidth=(0.005, 0.005), incButton_pos=(0.35, 0, -0.02), incButton_text="Inc", incButton_text_scale=0.04, incButton_borderWidth=(0.005, 0.005), pos=(0.05, 0, -0.3), numItemsVisible=4, forceHeight=0.11, itemFrame_frameSize=(-0.6, 0.6, -0.37, 0.11), itemFrame_pos=(0.35, 0, 0.4), ) self.selectCharacterTextbox = DirectEntry( text="", scale=0.07, pos=(0.28, 0, -0.55), command=self.setselectCharacterTextbox, initialText="name of character", numLines=1, focus=0, focusInCommand=self.clearselectCharacterTextbox, focusOutCommand=self.getselectCharacterTextbox, ) self.selectCharacterTextbox.reparentTo(self.frame) self.referenceForSeletion = OnscreenText( text="Reference to Character List:\n that already exists", pos=(-0.30, -0.75), scale=0.08, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=0, ) self.referenceForSeletion.reparentTo(self.frame) for playerchar in ["xxxbluesword", "xxxblueaxe", "xxxredsword", "xxxredsword01", "xxx_red_sword04"]: l = DirectLabel(text=playerchar, text_scale=0.1) self.myScrolledList.addItem(l) self.submitBtn = DirectButton( text=("Start", "Start", "Start", "disabled"), scale=0.08, command=self.clickedSubmit, pos=(-0.2, 0.0, -1.45) ) self.cancelBtn = DirectButton( text=("Cancel", "Cancel", "Cancel", "disabled"), scale=0.08, command=self.clickedCancel, pos=(0.3, 0.0, -1.45), ) self.submitBtn.reparentTo(self.frame) self.cancelBtn.reparentTo(self.frame) def destroySelectionWindow(self): self.frame.destroy() self.selectCharacter.destroy() self.createCharacter.destroy() self.deleteCharacter.destroy() self.submitBtn.destroy() self.cancelBtn.destroy() def clearselectCharacterTextbox(self): self.selectCharacterTextbox.enterText("") def getselectCharacterTextbox(self): self.selectCharacterTextbox = self.selectCharacterTextbox.get() def setselectCharacterTextbox(self, textEntered): print "name Of Char: ", textEntered self.selectCharacterTextbox = textEntered def clickedCreateChar(self): print "You pressed create a new character" self.destroySelectionWindow() self.createCreateCharWindow() def clickedDeleteChar(self): print "You pressed delete a character" self.destroySelectionWindow() self.createDeleteCharWindow() def clickedSubmit(self): print "you pressed start button" def clickedCancel(self): print "You pressed Cancel"
class World(DirectObject): def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0, 0, 0, 1)) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) # Login as 'CPHandler' # Temporary workaround, can add a seperate request/response for client/NPC client logins later self.name = "CPHandler" factionId = 0 self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler') # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def refresh(self, task): self.cManager.sendRequest(Constants.REQ_HEARTBEAT) return task.again def move(self, task): return None def CPHandler(self, task): for cp in self.cpList.values(): if cp.factionId == RED: if cp.checkContested(self.characters): print("CP [", cp.id, "] is contested") elif cp.checkBluePresence(self.characters): cp.timer -= 1 print(cp.id, cp.timer) if cp.timer == 0: print("CP [", cp.id, "] taken by Blue") cp.factionId = BLUE cp.model.setColor(0, 0, 255) else: cp.timer = 30 elif cp.factionId == BLUE: if cp.checkContested(self.characters): print("CP [", cp.id, "] contested") elif cp.checkRedPresence(self.characters): cp.timer += 1 print(cp.id, cp.timer) if cp.timer == 30: print("CP [", cp.id, "] taken by Red") cp.factionId = RED cp.model.setColor(255, 0, 0) else: cp.timer = 0 # Send 'timer' to server, which send to all clients self.cManager.sendRequest(Constants.CMSG_CONTROL_POINT_STATE, [cp.id, cp.timer, cp.factionId]) return task.again
class World(DirectObject): gameStateDict = { "Login": 0, "CreateLobby": 4, "EnterGame": 1, "BeginGame": 2, "InitializeGame": 3 } gameState = -1 # Login , EnterGame , BeginGame responseValue = -1 currentTime = 0 idleTime = 0 mySequence = None pandaPace = None jumpState = False isWalk = False previousPos = None # used to store the mainChar pos from one frame to another host = "" port = 0 vehiclelist = {} # Stores the list of all the others players characters characters = [] def __init__(self): self.login = "******" base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = { "hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey, ["powerup", 1]) self.accept("1-up", self.setKey, ["powerup", 0]) self.accept("2", self.setKey, ["powerup", 2]) self.accept("2-up", self.setKey, ["powerup", 0]) self.accept("3", self.setKey, ["powerup", 3]) self.accept("3-up", self.setKey, ["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN, [self.login, "1234"]) taskMgr.add(self.enterGame, "EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp") def createOtherVehicles(self, username, carType, carPaint, carTires): if username in self.vehiclelist.keys(): print "Player Already rendered" else: print "Creating copie other player @ 60" char = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0), username) self.characters.append(char) self.vehiclelist[username] = char def usePowerup(self, task): if self.keyMap["powerup"] == 1: self.mainCharRef.usePowerup(0) elif self.keyMap["powerup"] == 2: self.mainCharRef.usePowerup(1) elif self.keyMap["powerup"] == 3: self.mainCharRef.usePowerup(2) return task.cont def createPowerups(self): self.powerups = PowerupManager(self.cManager, self.characters) def use_powerup3(self): self.use_powerup(3) def setTime(self): self.cManager.sendRequest(Constants.CMSG_TIME) def use_powerup(self, num): if self.mainCharRef.power_ups[num - 1] == 0: print "power-up slot empty" else: print "power-up", num, "used" def doExit(self): self.cleanup() sys.exit(1) def cleanup(self): self.cManager.sendRequest(Constants.CMSG_DISCONNECT) self.cManager.closeConnection() self.world = None self.outsideWorldRender.removeNode() def doReset(self): self.mainCharRef.reset() def enterGame(self, task): self.startGameNow() return task.done if self.gameState == self.gameStateDict["Login"]: #responseValue = 1 indicates that this state has been finished if self.responseValue == 1: # Authentication succeeded #self.cManager.sendRequest(Constants.CMSG_CREATE_LOBBY, ["raceroyal","0","1"]) self.gameState = self.gameStateDict["CreateLobby"] #self.responseValue = -1 elif self.gameState == self.gameStateDict["CreateLobby"]: if self.responseValue == 1: print "Lobby Created and we are already in" # Lobby Created and we are already in self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 elif self.responseValue == 0: print "Game already created, let's join it" #Game already created, let's join it self.cManager.sendRequest(Constants.CMSG_ENTER_GAME_NAME, "raceroyal") self.gameState = self.gameStateDict["EnterGame"] self.responseValue = -1 self.startGameNow() #self.gameState = self.gameStateDict["InitializeGame"] # Everyone is in the game, we send ReqReady, and the server will send positions when every client did #self.cManager.sendRequest(Constants.CMSG_READY) elif self.gameState == self.gameStateDict["EnterGame"]: if self.responseValue == 1: # When the positions are sent, an acknowledgment is sent and we begin the InitializeGame self.responseValue = -1 self.gameState = self.gameStateDict["InitializeGame"] # Everyone is in the game, we send ReqReady, and the server will send positions when every client did self.cManager.sendRequest(Constants.CMSG_READY) elif self.gameState == self.gameStateDict["InitializeGame"]: if self.responseValue == 1: # Set up the camera self.camera = Camera(self.mainChar) self.gameState = self.gameStateDict["BeginGame"] self.cManager.sendRequest(Constants.CMSG_READY) self.responseValue = -1 elif self.gameState == self.gameStateDict["BeginGame"]: if self.responseValue == 1: taskMgr.add(self.move, "moveTask") return task.done return task.cont #return task.done def startGameNow(self): self.camera = Camera(self.mainChar) taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') taskMgr.add(self.move, "moveTask") def createEnvironment(self): self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) #self.environ.setPos(0, 0, 10) self.environ.setScale(500, 500, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = render.attachNewNode(node) #np.setPos(0, 0, 0) self.bulletWorld.attachRigidBody(node) self.visNP = loader.loadModel('models/track.egg') self.tex = loader.loadTexture("models/tex/Main.png") self.visNP.setTexture(self.tex) geom = self.visNP.findAllMatches('**/+GeomNode').getPath( 0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) trackShape = BulletTriangleMeshShape(mesh, dynamic=False) body = BulletRigidBodyNode('Bowl') self.visNP.node().getChild(0).addChild(body) bodyNP = render.anyPath(body) bodyNP.node().addShape(trackShape) bodyNP.node().setMass(0.0) bodyNP.setTexture(self.tex) self.bulletWorld.attachRigidBody(bodyNP.node()) self.visNP.reparentTo(render) self.bowlNP = bodyNP self.visNP.setScale(70) def initializeBulletWorld(self, debug=False): self.outsideWorldRender = render.attachNewNode('world') self.bulletWorld = BulletWorld() self.bulletWorld.setGravity(Vec3(0, 0, -9.81)) if debug: self.debugNP = self.outsideWorldRender.attachNewNode( BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(True) self.debugNP.node().showNormals(False) self.bulletWorld.setDebugNode(self.debugNP.node()) def makeCollisionNodePath(self, nodepath, solid): ''' Creates a collision node and attaches the collision solid to the supplied NodePath. Returns the nodepath of the collision node. ''' # Creates a collision node named after the name of the NodePath. collNode = CollisionNode("%s c_node" % nodepath.getName()) collNode.addSolid(solid) collisionNodepath = nodepath.attachNewNode(collNode) return collisionNodepath # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def getDist(self): mainCharX = self.mainChar.getPos().x mainCharY = self.mainChar.getPos().y pandaX = self.pandaActor2.getPos().x pandaY = self.pandaActor2.getPos().y dist = math.sqrt( abs(mainCharX - pandaX)**2 + abs(mainCharY - pandaY)**2) return dist def move(self, task): self.camera.update(self.mainChar) dt = globalClock.getDt() forces = self.mainCharRef.processInput(inputState, dt) moving = self.mainCharRef.chassisNP.getPos() print "Forces received& sending: ", moving[0], moving[1], moving[2] self.cManager.sendRequest(Constants.CMSG_MOVE, [ forces[0], forces[1], forces[2], moving.getX(), moving.getY(), moving.getZ(), self.mainCharRef.chassisNP.getH(), self.mainCharRef.chassisNP.getP(), self.mainCharRef.chassisNP.getR() ]) self.bulletWorld.doPhysics(dt, 10, 0.02) self.bulletWorld.doPhysics(dt) return task.cont def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def listFromInputState(self, inputState): # index 0 == forward # index 1 == brake # index 2 == right # index 3 == left result = [0, 0, 0, 0] if inputState.isSet('forward'): result[0] = 1 if inputState.isSet('brake'): result[1] = 1 if inputState.isSet('right'): result[2] = 1 if inputState.isSet('left'): result[3] = 1 return result def updateMove(self, task): if self.isMoving == True: moving = self.mainChar.getPos() - self.previousPos self.cManager.sendRequest(Constants.CMSG_MOVE, [ moving.getX(), moving.getY(), moving.getZ(), self.mainCharRef.actor.getH(), self.mainCharRef.actor.getP(), self.mainCharRef.actor.getR(), self.listFromInputState(inputState) ]) # self.cManager.sendRequest(Constants.RAND_FLOAT, 1.0) self.previousPos = self.mainChar.getPos() return task.again
def __init__(self): __builtin__.main = self self.cManager = ConnectionManager() self.startConnection() self.taskMgr = taskMgr self.base = base self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0, 0, 0, 1)) #self.environ = loader.loadModel("models/world") self.environ = loader.loadModel("models/land") """ self.swordLeft = loader.loadModel("models/Sword_Left") self.swordRight = loader.loadModel("models/Sword_Right") self.shieldLeft = loader.loadModel("models/Shield_Left") self.shieldRight = loader.loadModel("models/Shield_Right") self.money = loader.loadModel("models/Money") """ self.left_atk_tower = loader.loadModel("models/attack_tower") self.left_def_tower = loader.loadModel("models/defense_tower") self.right_atk_tower = loader.loadModel("models/attack_tower") self.right_def_tower = loader.loadModel("models/defense_tower") self.money_cp = loader.loadModel("models/money_point") self.left_atk_tower.setPos(141.016, 0.440607, 0) self.left_def_tower.setPos(210.984, 115.005, 0) self.right_atk_tower.setPos(-149.953, 0.674369, 0) self.right_def_tower.setPos(-210.771, 113.753, 0) self.money_cp.setPos(-0.903916, 11.3765, 0) self.left_atk_tower.setScale(2.0) self.right_atk_tower.setScale(2.0) self.left_def_tower.setScale(2.0) self.right_def_tower.setScale(2.0) self.money_cp.setScale(2.0) self.left_atk_tower.reparentTo(render) self.right_atk_tower.reparentTo(render) self.left_def_tower.reparentTo(render) self.right_def_tower.reparentTo(render) self.money_cp.reparentTo(render) self.environ.reparentTo(render) """ self.swordLeft.reparentTo(render) self.swordRight.reparentTo(render) self.shieldLeft.reparentTo(render) self.shieldRight.reparentTo(render) self.money.reparentTo(render) """ self.environ.setPos(0, 0, 0) self.environ.setH(90) """ self.swordLeft.setH(90) self.swordRight.setH(90) self.shieldLeft.setH(90) self.shieldRight.setH(90) self.money.setH(90) """ mySound = loader.loadSfx("sound/Retribution.mp3") mySound.setLoop(True) mySound.play() fp = FilterProperties() #fp.addReverb(0.6, 0.5, 0.1, 0.1, 0.1) base.sfxManagerList[0].configureFilters(fp) ## swordsmanStartPos = self.environ.find("**/start_point").getPos() ## self.player = Swordsman("Swordsman", 0) ## self.player._character.reparentTo(render) ## self.player._character.setScale(.1) ## self.player._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.player._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY(),swordsmanStartPos.getZ()) ## self.initx = swordsmanStartPos.getX() self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) ## self.characters["Axeman"] = Axeman("Axeman", 1) ## self.characters["Axeman"]._character.reparentTo(render) ## self.characters["Axeman"]._character.setScale(.1) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY() - 10,swordsmanStartPos.getZ()) ## self.characters["Axeman"]._character.loop("idle") self.accept("a", self.setKey, ["left", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("mouse1", self.attack, [3]) self.accept("mouse3", self.attack, [4]) self.username = str(raw_input("Username: "******"Type: ") faction = input("Faction: ") self.cManager.sendRequest(Constants.CMSG_AUTH, [self.username, type, faction]) #taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(.10, self.refresh, "heartbeat") base.disableMouse() #base.camera.setPos(self.player._character.getX(),self.player._character.getY()+10,2) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, 5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) Chat(self.cManager) # Create control points self.cpList[1] = ControlPoint(1, 210.984, 115.005, -5, 10, RED) self.cpList[2] = ControlPoint(2, 141.016, 0.440607, -5, 10, RED) self.cpList[3] = ControlPoint(3, -0.903916, 11.3765, -2, 10, RED) self.cpList[4] = ControlPoint(4, -210.771, 113.753, -2, 10, BLUE) self.cpList[5] = ControlPoint(5, -149.953, 0.674369, -2, 10, BLUE) # Create the control point Bar UI self.cp_bar = ControlPointBar() # self.resource_bar = ResourceBar() taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, "CPHandler") taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler') '''NPC Code Additions''' #self.isChased =[False,False] #self.npcList = [0,0] self.isChased = False self.npcList = 0 self.controlNpc = NPCController(render) taskMgr.add(self.taskAIUpdate, "AIUpdate") taskMgr.add(self.moveNpc, "Move")
class World(DirectObject): def __init__(self): #create Queue to hold the incoming chat #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0, "charge": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.cManager = ConnectionManager() self.cManager.startConnection() #------------------------------ #Chat Chat(self.cManager) #send dummy login info of the particular client #send first chat info #--------------------------------------- self.userName = username dummy_login = { 'user_id': self.userName, 'factionId': faction, 'password': '******' } self.cManager.sendRequest(Constants.RAND_STRING, dummy_login) chat = { 'userName': self.userName, #username 'message': '-------Login------' } self.cManager.sendRequest(Constants.CMSG_CHAT, chat) #-------------------------------------- #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8)) #frame = DirectFrame(text="Resource Bar", scale=0.001) resource_bar = DirectWaitBar(text="", value=35, range=100, pos=(0, 0, 0.9), barColor=(255, 255, 0, 1), frameSize=(-0.3, 0.3, 0, 0.03)) cp_bar = DirectWaitBar(text="", value=70, range=100, pos=(1.0, 0, 0.9), barColor=(0, 0, 255, 1), frameSize=(-0.3, 0.3, 0, 0.03), frameColor=(255, 0, 0, 1)) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) nameplate = TextNode('textNode username_' + str(self.userName)) nameplate.setText(self.userName) npNodePath = self.ralph.attachNewNode(nameplate) npNodePath.setScale(0.8) npNodePath.setBillboardPointEye() #npNodePath.setPos(1.0,0,6.0) npNodePath.setZ(6.5) bar = DirectWaitBar(value=100, scale=1.0) bar.setColor(255, 0, 0) #bar.setBarRelief() bar.setZ(6.0) bar.setBillboardPointEye() bar.reparentTo(self.ralph) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("c", self.setKey, ["charge", 1]) self.accept("c-up", self.setKey, ["charge", 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.ralph) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"] != 0): self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt()) if (self.keyMap["right"] != 0): self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) if (self.keyMap["forward"] != 0): self.ralph.setY(self.ralph, -25 * globalClock.getDt()) if (self.keyMap["charge"] != 0): self.ralph.setY(self.ralph, -250 * globalClock.getDt()) #ribbon = Ribbon(self.ralph, Vec4(1,1,1,1), 3, 10, 0.3) #ribbon.getRoot().setZ(2.0) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["forward"] != 0) or (self.keyMap["charge"] != 0) or ( self.keyMap["left"] != 0) or (self.keyMap["right"] != 0): if self.isMoving is False: self.ralph.loop("run") self.isMoving = True else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # Now check for collisions. self.cTrav.traverse(render) # Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.ralph.setPos(startpos) # Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater. entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): base.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.0) if (base.camera.getZ() < self.ralph.getZ() + 2.0): base.camera.setZ(self.ralph.getZ() + 2.0) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.ralph.getPos()) self.floater.setZ(self.ralph.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager(self) self.cManager.startConnection() # self.login = login(self) taskMgr.add(self.menu, "Menu") def menu(self, task): self.option = 0 choice = input("1-Register\n2-Login\n3-Exit\n") msg = 0 self.username = "" self.password = "" self.cpassword = "" if choice is 1: self.username = str(raw_input("Enter the username\n")) self.password = str(raw_input("Enter the password\n")) self.cpassword = str(raw_input("Confirm password\n")) if self.password == self.cpassword: self.cManager.sendRequest(Constants.CMSG_REGISTER, self.username + " " + self.password) elif choice is 2: self.username = str(raw_input("Enter the username\n")) self.password = str(raw_input("Enter the password\n")) self.cManager.sendRequest(Constants.CMSG_AUTH, self.username + " " + self.password) elif choice is 3: sys.exit() else: print "Invalid input" def processingLoginResponse(self, data): self.msg1 = data.getInt32() if self.msg1: self.pl_list = [] self.user = data.getString().split(" ") self.pl_count = data.getInt32() print "welcome ", self.user[1] print "No of players logged in- ", self.pl_count for num in range(0, self.pl_count): self.pl_list.append([num + 1, data.getString()]) # print self.pl_list #h(self,self.welcome,self.pl_list) charlist = ["Car", "Ralph", "Panda1", "Panda2"] usedlist = [] for l in self.pl_list: pl = l[1].split(",") usedlist.append(pl[1]) charlist.remove(pl[1]) print "Pick a Available Charactor", charlist role = raw_input("") print self.user[1] print role self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, self.user[1] + " " + role) # self.world.CharSelect(self.welcome,self.pl_list) else: print "Username Or Password invalid" def processingCreateResponse(self, data): self.msg1 = data.getInt32() if self.msg1: self.pl_list = [] self.name = data.getString() self.char = data.getString() self.pl_count = data.getInt32() for num in range(0, self.pl_count): self.pl_list.append([num + 1, data.getString()]) # print self.pl_list self.StartGame = self.Start(self) # def CharSelect(self, welcome, userList): # self.welcome = welcome # self.userList = userList # self.charSelect = characterSelection(self) # def Logout(self): # print "Logout" # def Game(self,user,char,count,playerlist): # self.user = user # self.char = char # self.count = count # self.playerlist = playerlist # print self.user # print self.char # print self.count # print self.playerlist # self.StartGame = Game(self) # print "game started" def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True
def __init__(self): self.login = "******" base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = { "hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey, ["powerup", 1]) self.accept("1-up", self.setKey, ["powerup", 0]) self.accept("2", self.setKey, ["powerup", 2]) self.accept("2-up", self.setKey, ["powerup", 0]) self.accept("3", self.setKey, ["powerup", 3]) self.accept("3-up", self.setKey, ["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN, [self.login, "1234"]) taskMgr.add(self.enterGame, "EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp")
class Main(DirectObject): def __init__(self): # Network Setup self.cManager = ConnectionManager() self.startConnection() #taskMgr.add(self.menu, "Menu") base.win.setClearColor(Vec4(0, 0, 0, 1)) self.imageObject = OnscreenImage(parent=render2d, image='images/mainPage.png', pos=(0, 0, 0), scale=(1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.button = DirectButton(image='images/button.png', pos=(-.1, 0, -.25), relief=None, scale=.40, command=self.startWorld) self.button.setTransparency(TransparencyAttrib.MAlpha) #self.cAudio = def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def menu(self, task): # Accept raw_input choice choice = input( "1 - Rand int\n2 - Rand string\n3 - Rand short\n4 - Rand float\n6 - Exit\n" ) msg = 0 if choice is 1: msg = random.randint(-(2**16), 2**16 - 1) elif choice is 2: msg = ''.join( random.choice('abcdefghijklmnopqrstuvwxyz') for x in range(7)) elif choice is 3: msg = random.randint(0, 2**16 - 1) elif choice is 4: msg = 100 * random.random() elif choice is 6: sys.exit() else: print "Invalid input" self.cManager.sendRequest(choice, msg) def startWorld(self): #send login request print "elll"
class login: def __init__(self): #self.loginEntry = [] self.createLogin() def createLogin(self): base.win.setClearColor(Vec4(0, 0, 0, 1)) self.imageObject = OnscreenImage(parent=render2d, image='images/mainPage.png', pos=(0, 0, 0), scale=(1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.createMainFrame() self.createText() self.createTextEntry() self.createButtons() def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def createMainFrame(self): """Create the main base frame.""" self.registerFrame = DirectFrame(frameSize=(-0.512, 0.512, -0.362, 0.362), frameColor=(0.53, 0.42, 0.18, 0.70), pos=(0, 0, -0.28)) self.mainBox = DirectFrame(frameSize=(-0.5, 0.5, -0.35, 0.35), frameColor=(0, 0, 0, 0.25), pos=(0, 0, 0)) self.mainBox.reparentTo(self.registerFrame) self.blackFrame = DirectFrame(frameSize=(-2, 2, -2, 2), frameColor=(0, 0, 0, 0.3), pos=(0, 0, 0), state=DGG.NORMAL) self.blackFrame.reparentTo(self.registerFrame, 1) self.blackFrame.hide() def createText(self): """Create some label for login text entry field""" self.headerLabel = DirectLabel(text='LOG IN', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1, 1, 1, 1), text_scale=0.07, frameColor=(0, 0, 0, 0), pos=(0, 0, 0.23)) self.headerLabel.reparentTo(self.registerFrame) self.usernameLabel = DirectLabel(text='Username', text_align=TextNode.ARight, text_fg=(1, 1, 1, 1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, 0.067)) self.usernameLabel.reparentTo(self.registerFrame) self.passwordLabel = DirectLabel(text='Password', text_align=TextNode.ARight, text_fg=(1, 1, 1, 1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.070)) self.passwordLabel.reparentTo(self.registerFrame) def createTextEntry(self): """Create entry boxes for credentials.""" self.usernameEntry = DirectEntry( self.registerFrame, scale=0.055, pos=(-0.14, 0, 0.055), command=self.submitLogin, focus=1, focusInCommand=self.focus("username"), #focusInExtraArgs=[0], rolloverSound=None) self.usernameEntry.reparentTo(self.registerFrame) #self.loginEntry.append(self.usernameEntry) self.passwordEntry = DirectEntry( self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.08), command=self.submitLogin, obscured=1, focusInCommand=self.focus("password"), #focusInExtraArgs=[1], rolloverSound=None) self.passwordEntry.reparentTo(self.registerFrame) #self.loginEntry.append(self.passwordEntry) def createButtons(self): """Create some buttons.""" self.validateLoginFrame = DirectFrame( frameSize=(-0.131, 0.131, -0.056, 0.056), frameColor=(0.33, 0.42, 0.18, 0.95), # color of the login button pos=(-0.2, 0, -0.22)) self.validateLoginFrame.reparentTo(self.mainBox) self.validateLogin = DirectButton(text='Log In', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.submitLogin, clickSound=None, rolloverSound=None) self.validateLogin.reparentTo(self.validateLoginFrame) self.registerButtonFrame = DirectFrame( frameSize=(-0.131, 0.131, -0.056, 0.056), frameColor=(1, 0, 1, 1), # color of the register button pos=(0.2, 0, -0.22)) self.registerButtonFrame.reparentTo(self.mainBox) self.registerButton = DirectButton(text='Register', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.register, clickSound=None, rolloverSound=None) self.registerButton.reparentTo(self.registerButtonFrame) def focus(self, text): print text def clickedCancel(self): print "You pressed Cancel" exit() def submitLogin(self): print "Login" print "username: "******"password: "******"" and self.passwordInput is not ""): #c = characterSelection() print "You pressed Submit", self.usernameInput, " ; ", self.passwordInput self.cManager.sendRequest( Constants.CMSG_AUTH, (self.usernameInput, self.passwordInput)) """ THiS IS WHERE IT STARTS TO GET WEIRD """ #self.registerFrame.hide() #c = selectcharandteamtype(self.registerFrame) else: print "Please enter in a username and password" else: print "Cannot connect to server." #def resume(self): #self.registerFrame.show() def register(self): """Switch to the registration screen.""" self.registerFrame.hide() #R = Register(self.registerFrame) base.win.setClearColor(Vec4(0, 0, 0, 1)) self.imageObject = OnscreenImage(parent=render2d, image='images/mainPage.png', pos=(0, 0, 0), scale=(1.444, 1, 1.444)) self.imageObject.setTransparency(TransparencyAttrib.MAlpha) self.createRMainFrame() self.createRText() self.createRTextEntry() self.createRButtons() self.error = False print "Register" def createRMainFrame(self): """Create the main base frame.""" # frameColor is defined as (R,G,B,A) self.registerFrame = DirectFrame(frameSize=(-0.612, 0.612, -0.462, 0.462), frameColor=(0.53, 0.42, 0.18, 0.70), pos=(0, 0, -0.37)) self.mainBox = DirectFrame(frameSize=(-0.6, 0.6, -0.45, 0.45), frameColor=(0, 0, 0, 0.25), pos=(0, 0, 0)) self.mainBox.reparentTo(self.registerFrame) self.blackFrame = DirectFrame(frameSize=(-2, 2, -2, 2), frameColor=(0, 0, 0, 0.3), pos=(0, 0, 0), state=DGG.NORMAL) self.blackFrame.reparentTo(self.registerFrame, 1) self.blackFrame.hide() def createRText(self): """Create some label for login text entry field""" self.headerLabel = DirectLabel(text='REGISTER', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1, 1, 1, 1), text_scale=0.07, frameColor=(0, 0, 0, 0), pos=(0, 0, 0.28)) self.headerLabel.reparentTo(self.registerFrame) self.usernameLabel = DirectLabel(text='Username', text_align=TextNode.ARight, text_fg=(1, 1, 1, 1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, 0.12)) self.usernameLabel.reparentTo(self.registerFrame) self.passwordLabel = DirectLabel(text='Password', text_align=TextNode.ARight, text_fg=(1, 1, 1, 1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.023)) self.passwordLabel.reparentTo(self.registerFrame) self.rePasswordLabel = DirectLabel(text='Re-Password', text_align=TextNode.ARight, text_fg=(1, 1, 1, 1), text_scale=0.06, frameColor=(0, 0, 0, 0), pos=(-0.19, 0, -0.16)) self.rePasswordLabel.reparentTo(self.registerFrame) def createRTextEntry(self): """Create entry boxes for credentials.""" self.usernameEntry = DirectEntry( self.registerFrame, scale=0.055, pos=(-0.14, 0, 0.12), command=self.submitRRegister, focus=1, #focusInCommand=self.setFocus, focusInExtraArgs=[0], rolloverSound=None) self.usernameEntry.reparentTo(self.registerFrame) self.passwordEntry = DirectEntry( self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.025), command=self.submitRRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[1], rolloverSound=None) self.passwordEntry.reparentTo(self.registerFrame) self.rePasswordEntry = DirectEntry( self.registerFrame, scale=0.055, pos=(-0.14, 0, -0.165), command=self.submitRRegister, obscured=1, #focusInCommand=self.setFocus, focusInExtraArgs=[2], rolloverSound=None) self.rePasswordEntry.reparentTo(self.registerFrame) def createRButtons(self): """Create some buttons.""" self.validateRegFrame = DirectFrame(frameSize=(-0.131, 0.131, -0.056, 0.056), frameColor=(0.33, 0.42, 0.18, 0.95), pos=(-0.2, 0, -0.30)) self.validateRegFrame.reparentTo(self.mainBox) self.validateReg = DirectButton(text='Register', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.submitRRegister, clickSound=None, rolloverSound=None) self.validateReg.reparentTo(self.validateRegFrame) self.registerButtonFrame = DirectFrame(frameSize=(-0.131, 0.131, -0.056, 0.056), frameColor=(0.33, 0.42, 0.18, 0.95), pos=(0.2, 0, -0.30)) self.registerButtonFrame.reparentTo(self.mainBox) self.registerButton = DirectButton(text='Cancel', text_fg=(1, 1, 1, 1), text_pos=(0, -0.015), text_scale=0.05, frameSize=(-0.125, 0.125, -0.05, 0.05), frameColor=(0, 0, 0, 0.2), relief=DGG.FLAT, pos=(0, 0, 0), command=self.cancel, clickSound=None, rolloverSound=None) self.registerButton.reparentTo(self.registerButtonFrame) def submitRRegister(self): print "username: "******"password: "******"re-password: "******"" and self.registerUsername.strip() != "": print "Success (", self.registerUsername, ", ", self.registerPassword, ", ", self.registerCPassword, ")" self.cManager.sendRequest( Constants.CMSG_REGISTER, (self.registerUsername, self.registerPassword)) self.cancel() else: taskMgr.add(self.errorMessage, "destroyIncorrectUsername") self.message() print "Failed (", self.registerUsername, ", ", self.registerPassword, ", ", self.registerCPassword, ")" else: print "Cannot Connect to the Server" def errorMessage(self, task): if task.time < 5.0: return task.cont else: self.failed.destroy() return task.done def message(self): self.failed = DirectLabel(text='Password needs to match', text_align=TextNode.ACenter, frameSize=(-0.2, 0.2, 0.2, 0.2), text_fg=(1, 1, 1, 1), text_scale=0.07, frameColor=(255, 0, 0, 1), pos=(0, 0, 0.20)) self.failed.reparentTo(self.registerFrame) def cancel(self): print "cancel" self.registerFrame.hide() self.createLogin()
def __init__(self): #create Queue to hold the incoming chat #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0, "charge": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.cManager = ConnectionManager() self.cManager.startConnection() #------------------------------ #Chat Chat(self.cManager) #send dummy login info of the particular client #send first chat info #--------------------------------------- self.userName = username dummy_login = { 'user_id': self.userName, 'factionId': faction, 'password': '******' } self.cManager.sendRequest(Constants.RAND_STRING, dummy_login) chat = { 'userName': self.userName, #username 'message': '-------Login------' } self.cManager.sendRequest(Constants.CMSG_CHAT, chat) #-------------------------------------- #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8)) #frame = DirectFrame(text="Resource Bar", scale=0.001) resource_bar = DirectWaitBar(text="", value=35, range=100, pos=(0, 0, 0.9), barColor=(255, 255, 0, 1), frameSize=(-0.3, 0.3, 0, 0.03)) cp_bar = DirectWaitBar(text="", value=70, range=100, pos=(1.0, 0, 0.9), barColor=(0, 0, 255, 1), frameSize=(-0.3, 0.3, 0, 0.03), frameColor=(255, 0, 0, 1)) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) nameplate = TextNode('textNode username_' + str(self.userName)) nameplate.setText(self.userName) npNodePath = self.ralph.attachNewNode(nameplate) npNodePath.setScale(0.8) npNodePath.setBillboardPointEye() #npNodePath.setPos(1.0,0,6.0) npNodePath.setZ(6.5) bar = DirectWaitBar(value=100, scale=1.0) bar.setColor(255, 0, 0) #bar.setBarRelief() bar.setZ(6.0) bar.setBillboardPointEye() bar.reparentTo(self.ralph) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("c", self.setKey, ["charge", 1]) self.accept("c-up", self.setKey, ["charge", 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): __builtin__.main = self self.taskMgr = taskMgr self.base = base # Connect to the server self.cManager = ConnectionManager() self.startConnection() self.characters = dict() self.cpList = dict() self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.ralphStartPos = self.environ.find("**/start_point").getPos() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # Placeholder Login self.name = str(raw_input("Name: ")) factionId = int(input("Faction ID: ")) self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId]) # Create two control points cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED) cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE) self.cpList[1] = cp1 self.cpList[2] = cp2 # Create the control point Bar UI self.cp_bar = ControlPointBar() self.resource_bar = ResourceBar() taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, "CPHandler") taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
class World(DirectObject): def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def __init__(self): base.win.setClearColor(Vec4(0,0,0,1)) # Network Setup print "before" self.cManager = ConnectionManager(self) self.startConnection() print "after" taskMgr.add(self.menu, "Menu") def Start(self,pl_name,pl_char,pl_count,pl_list): # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.environ.setScale(100,100,1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # # add spheres earth = Earth(self) sun = Sun(self) venus = Venus(self) controls = Control() chat = Chat(self) if pl_char == "Panda1" or pl_char == "Panda2": print "hi" player = Panda(self) elif pl_char == "Car": player = Car(self) else : player = Ralph(self) #player = Car(self) # player = Panda(self) # player = Car(self) taskMgr.add(player.move,"moveTask" ) taskMgr.add(sun.rotatePlanets,"rotateSun", extraArgs = [self.sun,self.player], appendTask = True) taskMgr.add(earth.rotatePlanets,"rotateEarth", extraArgs = [self.earth, self.player], appendTask = True) taskMgr.add(venus.rotatePlanets,"rotateVenus", extraArgs = [self.venus, self.player], appendTask = True) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) def menu(self, task): self.option = 0 choice = input("1-Register\n2-Login\n3-Exit\n") msg = 0 self.username = "" self.password = "" self.cpassword = "" if choice is 1: self.username = str(raw_input("Enter the username\n")) self.password = str(raw_input("Enter the password\n")) self.cpassword = str(raw_input("Confirm password\n")) if self.password == self.cpassword: self.cManager.sendRequest(Constants.CMSG_REGISTER, self.username+" "+self.password) elif choice is 2: self.username = str(raw_input("Enter the username\n")) self.password = str(raw_input("Enter the password\n")) self.cManager.sendRequest(Constants.CMSG_AUTH, self.username+" "+self.password); elif choice is 3: sys.exit() else: print "Invalid input" def processingLoginResponse(self, data): self.msg1 = data.getInt32() if self.msg1: self.pl_list = [] self.playersList = [] self.user = data.getString().split(" ") self.pl_count = data.getInt32() print "welcome ",self.user[1] print "No of players logged in- ", self.pl_count for num in range (0,self.pl_count): self.pl_list.append([num+1,data.getString()]) for num in range (0,self.pl_count): playerTemp = data.getString().split(",") self.playersList.append([User(playerTemp[0], float(playerTemp[2]), float(playerTemp[3]) float(playerTemp[4]), float(playerTemp[5]), int(playerTemp[6]), playerTemp[1])]) # print self.pl_list #h(self,self.welcome,self.pl_list) charlist =["Car","Ralph","Panda1","Panda2"] usedlist =[] for l in self.pl_list : pl = l[1].split(",") usedlist.append(pl[1]) charlist.remove(pl[1]) print "Pick a Available Charactor", charlist role = raw_input("") print self.user[1] print role self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, self.user[1]+" "+role) # self.world.CharSelect(self.welcome,self.pl_list) else : print "Username Or Password invalid" def processingCreateResponse(self, data): self.msg1 = data.getInt32() if self.msg1: self.pl_list = [] self.name = data.getString() self.char = data.getString() self.pl_count = data.getInt32() for num in range (0,self.pl_count): self.pl_list.append([num+1,data.getString()]) # print self.pl_list self.Start(self.name,self.char,self.pl_count,self.pl_list)
class World(DirectObject): def __init__(self): __builtin__.main = self self.cManager = ConnectionManager() self.startConnection() self.taskMgr = taskMgr self.base = base self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0, 0, 0, 1)) #self.environ = loader.loadModel("models/world") self.environ = loader.loadModel("models/land") """ self.swordLeft = loader.loadModel("models/Sword_Left") self.swordRight = loader.loadModel("models/Sword_Right") self.shieldLeft = loader.loadModel("models/Shield_Left") self.shieldRight = loader.loadModel("models/Shield_Right") self.money = loader.loadModel("models/Money") """ self.left_atk_tower = loader.loadModel("models/attack_tower") self.left_def_tower = loader.loadModel("models/defense_tower") self.right_atk_tower = loader.loadModel("models/attack_tower") self.right_def_tower = loader.loadModel("models/defense_tower") self.money_cp = loader.loadModel("models/money_point") self.left_atk_tower.setPos(141.016, 0.440607, 0) self.left_def_tower.setPos(210.984, 115.005, 0) self.right_atk_tower.setPos(-149.953, 0.674369, 0) self.right_def_tower.setPos(-210.771, 113.753, 0) self.money_cp.setPos(-0.903916, 11.3765, 0) self.left_atk_tower.setScale(2.0) self.right_atk_tower.setScale(2.0) self.left_def_tower.setScale(2.0) self.right_def_tower.setScale(2.0) self.money_cp.setScale(2.0) self.left_atk_tower.reparentTo(render) self.right_atk_tower.reparentTo(render) self.left_def_tower.reparentTo(render) self.right_def_tower.reparentTo(render) self.money_cp.reparentTo(render) self.environ.reparentTo(render) """ self.swordLeft.reparentTo(render) self.swordRight.reparentTo(render) self.shieldLeft.reparentTo(render) self.shieldRight.reparentTo(render) self.money.reparentTo(render) """ self.environ.setPos(0, 0, 0) self.environ.setH(90) """ self.swordLeft.setH(90) self.swordRight.setH(90) self.shieldLeft.setH(90) self.shieldRight.setH(90) self.money.setH(90) """ mySound = loader.loadSfx("sound/Retribution.mp3") mySound.setLoop(True) mySound.play() fp = FilterProperties() #fp.addReverb(0.6, 0.5, 0.1, 0.1, 0.1) base.sfxManagerList[0].configureFilters(fp) ## swordsmanStartPos = self.environ.find("**/start_point").getPos() ## self.player = Swordsman("Swordsman", 0) ## self.player._character.reparentTo(render) ## self.player._character.setScale(.1) ## self.player._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.player._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY(),swordsmanStartPos.getZ()) ## self.initx = swordsmanStartPos.getX() self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) ## self.characters["Axeman"] = Axeman("Axeman", 1) ## self.characters["Axeman"]._character.reparentTo(render) ## self.characters["Axeman"]._character.setScale(.1) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY() - 10,swordsmanStartPos.getZ()) ## self.characters["Axeman"]._character.loop("idle") self.accept("a", self.setKey, ["left", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("mouse1", self.attack, [3]) self.accept("mouse3", self.attack, [4]) self.username = str(raw_input("Username: "******"Type: ") faction = input("Faction: ") self.cManager.sendRequest(Constants.CMSG_AUTH, [self.username, type, faction]) #taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(.10, self.refresh, "heartbeat") base.disableMouse() #base.camera.setPos(self.player._character.getX(),self.player._character.getY()+10,2) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, 5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) Chat(self.cManager) # Create control points self.cpList[1] = ControlPoint(1, 210.984, 115.005, -5, 10, RED) self.cpList[2] = ControlPoint(2, 141.016, 0.440607, -5, 10, RED) self.cpList[3] = ControlPoint(3, -0.903916, 11.3765, -2, 10, RED) self.cpList[4] = ControlPoint(4, -210.771, 113.753, -2, 10, BLUE) self.cpList[5] = ControlPoint(5, -149.953, 0.674369, -2, 10, BLUE) # Create the control point Bar UI self.cp_bar = ControlPointBar() # self.resource_bar = ResourceBar() taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, "CPHandler") taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler') '''NPC Code Additions''' #self.isChased =[False,False] #self.npcList = [0,0] self.isChased = False self.npcList = 0 self.controlNpc = NPCController(render) taskMgr.add(self.taskAIUpdate, "AIUpdate") taskMgr.add(self.moveNpc, "Move") def taskAIUpdate(self, task): self.npcList = self.controlNpc.AIUpdate(self, globalClock.getDt(), self.cManager) return task.cont def moveNpc(self, task): self.cManager.sendRequest(Constants.CMSG_NPCMOVE, [self.username, self.npcList]) return task.cont def freeDeadNpc(self, cpId): if cpId == self.npcList: self.npcList = 0 self.isChased = False def startConnection(self): if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def refresh(self, task): self.cManager.sendRequest(Constants.REQ_HEARTBEAT) return task.again def setKey(self, key, value): self.keyMap[key] = value def move(self, task): #print self.player._character.getPos() main.miniMap.updateHeroPos(self.player._character.getX(), self.player._character.getY()) main.miniMap.updateHeroHpr(self.player._character.getH()) main.miniMap.resizeScreen(base.win.getXSize(), base.win.getYSize()) base.camera.lookAt(self.player._character) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) if self.player._is_moving == 2: if self.player.get_team() == 0: # position when killed dead_pos = self.player._character.getPos() """ self.cManager.sendRequest(Constants.CMSG_MOVE, [254.271, 6.72015, 0, self.player._character.getH(), 2]) self.player._character.setPos(254.271, 6.72015, 0) """ # add respawn logic to CPs cp_distances = {} for cp in self.cpList.values(): if cp.factionId == self.player.get_team(): d = self.distance(cp.x, cp.y, dead_pos.x, dead_pos.y) cp_distances[cp.id] = d print cp_distances if cp_distances: min_cp_id = min(cp_distances, key=cp_distances.get) self.cManager.sendRequest(Constants.CMSG_MOVE, [ self.cpList[min_cp_id].x, self.cpList[min_cp_id].y, self.cpList[min_cp_id].z, self.player._character.getH(), 2 ]) self.player._character.setPos(self.cpList[min_cp_id].x, self.cpList[min_cp_id].y, self.cpList[min_cp_id].z) else: self.cManager.sendRequest(Constants.CMSG_MOVE, [ 254.271, 6.72015, 0, self.player._character.getH(), 2 ]) self.player._character.setPos(254.271, 6.72015, 0) if isinstance(self.player, Swordsman): self.cManager.sendRequest(Constants.CMSG_HEALTH, [ self.player.get_name(), (-1) * int(Swordsman.MAX_HEALTH) ]) elif isinstance(self.player, Axeman): self.cManager.sendRequest(Constants.CMSG_HEALTH, [ self.player.get_name(), (-1) * int(Axeman.MAX_HEALTH) ]) elif self.player.get_team() == 1: """ self.cManager.sendRequest(Constants.CMSG_MOVE, [-268.27, 8.0602, 0, self.player._character.getH(), 2]) self.player._character.setPos(-268.27, 8.0602, 0) """ dead_pos = self.player._character.getPos() cp_distances = {} for cp in self.cpList.values(): if cp.factionId == self.player.get_team(): d = self.distance(cp.x, cp.y, dead_pos.x, dead_pos.y) cp_distances[cp.id] = d print cp_distances if cp_distances: min_cp_id = min(cp_distances, key=cp_distances.get) self.cManager.sendRequest(Constants.CMSG_MOVE, [ self.cpList[min_cp_id].x, self.cpList[min_cp_id].y, self.cpList[min_cp_id].z, self.player._character.getH(), 2 ]) self.player._character.setPos(self.cpList[min_cp_id].x, self.cpList[min_cp_id].y, self.cpList[min_cp_id].z) else: self.cManager.sendRequest( Constants.CMSG_MOVE, [-268.27, 8.0602, 0, self.player._character.getH(), 2]) self.player._character.setPos(-268.27, 8.0602, 0) if isinstance(self.player, Swordsman): self.cManager.sendRequest(Constants.CMSG_HEALTH, [ self.player.get_name(), (-1) * int(Swordsman.MAX_HEALTH) ]) elif isinstance(self.player, Axeman): self.cManager.sendRequest(Constants.CMSG_HEALTH, [ self.player.get_name(), (-1) * int(Axeman.MAX_HEALTH) ]) else: self.player.move(self.keyMap["forward"], self.keyMap["backward"], self.keyMap["left"], self.keyMap["right"], globalClock.getDt()) if (self.keyMap["forward"] != 0) or (self.keyMap["left"] != 0) or ( self.keyMap["right"] != 0) or (self.keyMap["backward"] != 0): if self.player._is_moving is False: self.player._character.loop("run") self.player._is_moving = True self.cManager.sendRequest(Constants.CMSG_MOVE, [ self.player._character.getX(), self.player._character.getY(), self.player._character.getZ(), self.player._character.getH(), 1 ]) #self.characters["Axeman"].moveActor(self.player._character.getX(), self.player._character.getY() - 10, self.player._character.getZ(), self.player._character.getH(), True, globalClock.getDt()) else: if self.player._is_moving: #self.player.character.stop() self.player._character.loop("idle") self.player._is_moving = False self.cManager.sendRequest(Constants.CMSG_MOVE, [ self.player._character.getX(), self.player._character.getY(), self.player._character.getZ(), self.player._character.getH(), 0 ]) #self.characters["Axeman"].moveActor(self.player._character.getX(), self.player._character.getY() - 10, self.player._character.getZ(), self.player._character.getH(), False, globalClock.getDt()) ## camvec = self.player.character.getPos() - base.camera.getPos() ## camvec.setZ(0) ## camdist = camvec.length() ## camvec.normalize() ## if (camdist > 10.0): ## base.camera.setPos(base.camera.getPos() + camvec*(camdist-10)) ## camdist = 10.0 ## if (camdist < 5.0): ## base.camera.setPos(base.camera.getPos() - camvec*(5-camdist)) ## camdist = 5.0 base.camera.setPos(self.player._character.getX(), self.player._character.getY() + 70, 40) self.floater.setPos(self.player._character.getPos()) self.floater.setZ(self.player._character.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont def attack(self, attack_id): self.player._is_attacking = True self.cManager.sendRequest(Constants.CMSG_ATTACK, attack_id) targets = self.find_target() #print targets damage = 0 AOE = False if attack_id == 3: damage = self.player.basic_attack() elif attack_id == 4: damage = self.player.special_attack() if isinstance(self.player, Axeman): AOE = True #if targets != None: if targets and not AOE: self.cManager.sendRequest(Constants.CMSG_HEALTH, [targets[0], damage]) #print "non-aoe" elif targets and isinstance(self.player, Axeman) and AOE: #print "aoe" for i in range(len(targets)): self.cManager.sendRequest(Constants.CMSG_HEALTH, [targets[i], damage]) def find_target(self): """ if h==Constants.NORTH: pass """ #current player pos and fixed fov fov = self.player.FOV px = self.player._character.getX() py = self.player._character.getY() h = self.player._character.getH() p_team = self.player.get_team() num_of_targets = 0 if isinstance(self.player, Swordsman): num_of_targets = 1 elif isinstance(self.player, Axeman): num_of_targets = 3 rx = 3 ry = 0 if h == 90: rx = 3 ry = 0 elif h == 135: theta = math.pi / 4 rx = (rx * math.cos(theta)) - (ry * math.sin(theta)) ry = (rx * math.sin(theta)) + (ry * math.cos(theta)) elif h == 180: rx = 0 ry = 3 elif h == 225: theta = (3 * math.pi) / 4 rx = (rx * math.cos(theta)) - (ry * math.sin(theta)) ry = (rx * math.sin(theta)) + (ry * math.cos(theta)) elif h == 270: rx = -3 ry = 0 elif h == 315: theta = (5 * math.pi) / 4 rx = (rx * math.cos(theta)) - (ry * math.sin(theta)) ry = (rx * math.sin(theta)) + (ry * math.cos(theta)) elif h == 0: rx = 0 ry = -3 elif h == 405: theta = (7 * math.pi) / 4 rx = (rx * math.cos(theta)) - (ry * math.sin(theta)) ry = (rx * math.sin(theta)) + (ry * math.cos(theta)) #player view direction based on heading cx = rx cy = ry #find length cl = math.sqrt(math.pow(cx, 2) + math.pow(cy, 2)) #normalized facing vector ncx = cx / cl ncy = cy / cl targets = [] candidates = {} '''selecting an npc target''' if not self.npcList == 0: currentNpc = self.controlNpc.getNpc(self.npcList) tx = currentNpc.getX() ty = currentNpc.getY() vx = tx - px vy = ty - py vl = math.sqrt(math.pow(vx, 2) + math.pow(vy, 2)) if vl == 0: return None #normalize nvx = vx / vl nvy = vy / vl #dot product dp = self.dot(ncx, ncy, nvx, nvy) angle = math.degrees(math.acos(dp)) d = self.distance(tx, ty, px, py) if angle < (fov / 2) and d < self.player.ATK_RANGE: #check if the npc is dead npcId = str(self.npcList) candidates["NPC," + npcId] = d '''end of selecting an npc target part''' for name, other in self.characters.iteritems(): tx = other._character.getX() ty = other._character.getY() #direction from player to other player vx = tx - px vy = ty - py vl = math.sqrt(math.pow(vx, 2) + math.pow(vy, 2)) if vl == 0: return None #normalize nvx = vx / vl nvy = vy / vl #dot product dp = self.dot(ncx, ncy, nvx, nvy) angle = math.degrees(math.acos(dp)) d = self.distance(tx, ty, px, py) if angle < (fov / 2) and d < self.player.ATK_RANGE: if (p_team != other.get_team()) and (not other._is_dead): candidates[name] = d if candidates: if num_of_targets == 1: targets.append(min(candidates, key=candidates.get)) elif num_of_targets == 3: #sorted_candidates=sorted(candidates.items(), key=operator.itemgetter(1)) for i in range(0, 3): if candidates: min_target = min(candidates, key=candidates.get) del candidates[min_target] targets.append(min_target) return targets def distance(self, ux, uy, vx, vy): dx = math.fabs(ux - vx) dy = math.fabs(uy - vy) d = math.sqrt(math.pow(dx, 2) + math.pow(dy, 2)) return d def dot(self, ux, uy, vx, vy): return (ux * vx) + (uy * vy) #--------------------------------------------------------------------- # This is the start of the control point code. #--------------------------------------------------------------------- def inWhichControlPoint(self): for cp in self.cpList.values(): if cp.withinCircle(self.player._character): return cp return None def CPBarHandler(self, task): # This is where you check to see if you are in a control point # to render the bar or not currentCP = self.inWhichControlPoint() if currentCP is not None: self.cp_bar.show() self.cp_bar.setValue(currentCP.timer) else: self.cp_bar.hide() return task.again def CPHandler(self, task): # Change colors of control points to match their faction for cp in self.cpList.values(): if cp.timer == 0: cp.model.setColor(0, 0, 255) if cp.timer == 30: cp.model.setColor(255, 0, 0) return task.again