def main(): # Calibrate camera to servo. This is a function get_angle = MU.calibrate_with_camera( 13, 303, 50, 40) #MU.calibrate_with_camera(13, 303, 50, 34) # Servo handler servo = ServoHandler(18, 100, 2.5, 20) # Pump Handler pump = PumpHandler(16) # Camera handler cam = CameraHandler(0, 8) # Keep track of the threads threads.append(cam) # This goes into a thread cam.start() # Create a background frame for comparisson background_frame = MU.get_background(cam) while True: smoothed_frame = cam.get_frame() component = MU.detect_main_change(background_frame, smoothed_frame) if len(component) != 0: component = component[0] # if the contour is too small, ignore it -> Not significant movement if MU.detect_contour(component): # Get the countour as a circle around the main change (x, y), radius = MU.get_enclosure(component) angle = int(get_angle(int(x))) print angle # Change the position only when it was changed (significantly) servo.set_angle(angle) # The pump shoots!!! pump.shot(1) # Reduce the speed of the readings dummy_event = threading.Event() dummy_event.wait(1)
def main(): # Calibrate camera to servo. This is a function get_angle = MU.calibrate_with_camera(13, 303, 50, 40)#MU.calibrate_with_camera(13, 303, 50, 34) # Servo handler servo = ServoHandler(18, 100, 2.5, 20) # Pump Handler pump = PumpHandler(16) # Camera handler cam = CameraHandler(0, 8) # Keep track of the threads threads.append(cam) # This goes into a thread cam.start() # Create a background frame for comparisson background_frame = MU.get_background(cam) while True: smoothed_frame = cam.get_frame() component = MU.detect_main_change(background_frame, smoothed_frame) if len(component) != 0: component = component[0] # if the contour is too small, ignore it -> Not significant movement if MU.detect_contour(component): # Get the countour as a circle around the main change (x,y), radius = MU.get_enclosure(component) angle = int( get_angle(int(x)) ) print angle # Change the position only when it was changed (significantly) servo.set_angle(angle) # The pump shoots!!! pump.shot(1) # Reduce the speed of the readings dummy_event = threading.Event() dummy_event.wait(1)
def __archive_cameras(self, cams, result_path): """ Archives images from array of cameras. Places directory of all results at the given path. """ camera_handlers = [] for camera in cams: # Create a new thread to handle the camera. camera_handler = CameraHandler(camera, result_path) # Run the thread. camera_handler.start() # Add the thread to the array of threads. camera_handlers.append(camera_handler) # Sleep to shift the starting time of all the threads. # time.sleep(interval / len(cams)) # Old time.sleep(0.5) # Wait for all the threads to finish execution. for camera_handler in camera_handlers: camera_handler.join()
def __init__(self,showbase): # Initialise Window self.showbase=showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming=deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text = "HP: "+str(100.0), pos = (0.95,-0.95), scale = 0.07,fg=(1,1,1,1),align=TextNode.ACenter,mayChange=1) # Keys array (down if 1, up if 0) self.keys={"left":0,"right":0,"up":0,"down":0,"c":0,"x":0} self.skybox=Skybox(self.showbase) self.ch=CameraHandler() # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man=SpellManager(self.showbase.num_warlocks) # until the Game() class is created in here which i think it should for i in self.showbase.spells: self.showbase.spell_man.add_spell(i) self.game=Game(self.showbase,game_tick) self.warlock=self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick=0 self.temp_tick=0 # Set event handlers for keys self.showbase.accept("escape",sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c",set_value,[self.keys,"c",1]) self.showbase.accept("c-up",set_value,[self.keys,"c",0]) # variable to track which spell has been requested self.current_spell=-1 # keys to change spell self.showbase.accept("q",self.set_spell,[0]) self.showbase.accept("w",self.set_spell,[1]) self.showbase.accept("e",self.set_spell,[2]) self.showbase.accept("r",self.set_spell,[3]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1",self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3",self.update_destination) # sets the camera up behind clients warlock looking down on it from angle follow=self.warlock.model self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(),0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop,"Game Loop")
class Round(): # Initialisation Function def __init__(self,showbase): # Initialise Window self.showbase=showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming=deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text = "HP: "+str(100.0), pos = (0.95,-0.95), scale = 0.07,fg=(1,1,1,1),align=TextNode.ACenter,mayChange=1) # Keys array (down if 1, up if 0) self.keys={"left":0,"right":0,"up":0,"down":0,"c":0,"x":0} self.skybox=Skybox(self.showbase) self.ch=CameraHandler() # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man=SpellManager(self.showbase.num_warlocks) # until the Game() class is created in here which i think it should for i in self.showbase.spells: self.showbase.spell_man.add_spell(i) self.game=Game(self.showbase,game_tick) self.warlock=self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick=0 self.temp_tick=0 # Set event handlers for keys self.showbase.accept("escape",sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c",set_value,[self.keys,"c",1]) self.showbase.accept("c-up",set_value,[self.keys,"c",0]) # variable to track which spell has been requested self.current_spell=-1 # keys to change spell self.showbase.accept("q",self.set_spell,[0]) self.showbase.accept("w",self.set_spell,[1]) self.showbase.accept("e",self.set_spell,[2]) self.showbase.accept("r",self.set_spell,[3]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1",self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3",self.update_destination) # sets the camera up behind clients warlock looking down on it from angle follow=self.warlock.model self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(),0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop,"Game Loop") def set_spell(self,spell): self.current_spell=spell # sends spell request to server if one is selected def cast_spell(self): if not self.current_spell==-1: target=self.ch.get_mouse_3d() if not target.getZ()==-1: data = {} data[0] = "spell" data[1] = {} data[1][0] = self.current_spell data[1][1] = {} data[1][1][0] = target.getX() data[1][1][1] = target.getY() self.showbase.client.sendData(data) self.current_spell=-1 # sends destination request to server, or cancels spell if selected def update_destination(self): if self.current_spell==-1: destination=self.ch.get_mouse_3d() if not destination.getZ()==-1: data = {} data[0] = "destination" data[1] = {} data[1][0] = destination.getX() data[1][1] = destination.getY() self.showbase.client.sendData(data) else: self.current_spell=-1 def update_camera(self,dt): # sets the camMoveTask to be run every frame self.ch.camMoveTask(dt) # if c is down update camera to always be following on the warlock if self.keys["c"]: follow=self.warlock.model self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(0,0) # Game Loop Procedure def game_loop(self,task): # update total time self.total_time+=globalClock.getDt() # process any incoming network packets temp=self.showbase.client.getData() if temp!=[]: for i in range(len(temp)): # this part puts the next packets onto the end of the queue self.incoming.append(temp[i]) # while there is packets to process while list(self.incoming): valid_packet=False package=self.incoming.popleft() # if username is sent, assign to client if package[0]=='tick': # not sure if this is the best way to do this but yea something to look into for syncing them all preround i guess if package[1]==0: self.total_time=0 # check what tick it should be self.temp_tick=package[1] # if this tick needs to be run (if frames are up to the server tick) if self.temp_tick*game_tick<=self.total_time: # run tick if not self.game.run_tick(): print 'Game Over' self.update_camera(game_tick) # maybe this should be put outside of this loop and just updated from the globalClock.getDt() self.hp.setText("HP: "+str(self.warlock.hp)) # i think there should be a HUD class which will show all the info needed for the player (like hps,spells cds, etc) valid_packet=True else: # otherwise put packet back on front of list and end frame processing self.incoming.appendleft(package) break # i think it should check for 'tick' and if not tick then pass the rest of the packets to a packet handler (kind of makes it more modable i guess for changing the game to another like pudgewars or centipede or w/e) # so i guess these will be put into a packet manager (i think this idea you had before anyway :P) silly me! :D # well, just leave here for now i guess :P elif package[0]=='update_dest': # if its an update packet then update destination of required warlock print "Update Destination: "+str(package[1])+" "+str(package[2]) self.game.warlock[package[1]].set_destination(Vec3(package[2][0],package[2][1],0)) valid_packet=True elif package[0]=='update_spell': # if its an update packet then update destination of required warlock print "Update Spell: "+str(package[1])+" "+str(package[2])+" "+str(package[3]) self.game.warlock[package[1]].set_spell(package[2],package[3]) valid_packet=True # Return cont to run task again next frame return task.cont
def setupCamera(self): self.camHandler = CameraHandler() self.camHandler.setTarget(self.environ.getX(), self.environ.getY(), self.environ.getZ())
class RTSEngine(DirectObject): def __init__(self): from pandac.PandaModules import loadPrcFileData loadPrcFileData("", "want-directtools #t") loadPrcFileData("", "want-tk #t") self.camHandler = None self.environ = None self.isMoving = False self.trav = CollisionTraverser() self.cHandler = CollisionHandlerQueue() self.picked = None self.selected = None self.setupEnvironment() self.setupCamera() self.setupActors() self.setupLighting() self.gui = mouseSelectTool() self.gui.selectable = [self.box, self.box2] def setupAI(self): self.AIWorld = AIWorld(render) self.AIChar = AICharacter("ralph", self.ralph, 60, 0.5, 15) self.AIWorld.addAiChar(self.AIChar) self.AIBehaviors = self.AIChar.getAiBehaviors() taskMgr.add(self.AIUpdate, "AIUpdate") return def run(self): run() def setupMouseCollision(self): 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.trav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) def setupCamera(self): self.camHandler = CameraHandler() self.camHandler.setTarget(self.environ.getX(), self.environ.getY(), self.environ.getZ()) def setupActors(self): # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor.Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph = loader.loadModel("models/ralph") self.ralph.setPos(ralphStartPos) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.box = loader.loadModel("models/box") self.box.setPos(5, 5, 1) self.box.setColor(1, 0, 0) self.box.setScale(.5) self.box.reparentTo(render) self.box2 = loader.loadModel("models/box") self.box2.setPos(-10, -10, 1) self.box2.setColor(1, 1, 0) self.box2.setScale(.5) self.box2.reparentTo(render) def setupLighting(self): #Setup the lighting and the shader to make it look cartoony plightnode = PointLight("point light") plightnode.setAttenuation(Vec3(1, 0, 0)) plight = render.attachNewNode(plightnode) plight.setPos(30, -50, 0) alightnode = AmbientLight("ambient light") alightnode.setColor(Vec4(0.8, 0.8, 0.8, 1)) alight = render.attachNewNode(alightnode) render.setLight(alight) render.setLight(plight) self.lastMousePos = None alight = AmbientLight("alight") alight.setColor(VBase4(0.5, 0.5, 0.5, 0.5)) self.alnp = self.ralph.attachNewNode(alight) def setupEnvironment(self): #self.environ = loader.loadModel("models/world") #self.terrain = GeoMipTerrain("MyTerrain") #self.terrain.setHeightfield(Filename("models/testHeightMap.png")) #self.terrain.setBruteforce(True) #self.terrain.setBlockSize(64) #self.terrain.setNear(40) #self.terrain.setFar(100) #self.terrain.setFocalPoint(base.camera) #self.environ = self.terrain.getRoot() #self.environ.setShader(Shader.make(SHADER)) #self.environ.setSz(50) #self.terrain_tex = loader.loadTexture('world/shortGrass.png') #self.ts = TextureStage('ts') #self.environ.setTexScale(self.ts.getDefault(),10,10) #self.environ.setTexture(self.terrain_tex,1) #self.terrain.generate() #self.environ.reparentTo(render) #base.toggleWireframe() #self.environ = self.terrain.getRoot() #self.environ.setPos(1,1,0) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(0, 0, 0) def update(self, task): self.terrain.setFocalPoint(base.camera.getX(), base.camera.getY()) self.terrain.update() return task.cont def setMove(self): try: print "none" except: print "Failed" self.ralph.loop("run") return def AIUpdate(self, task): self.AIWorld.update() if (self.AIBehaviors.behaviorStatus("pathfollow") == "done"): self.ralph.stop("run") self.ralph.pose("walk", 0) return task.cont def handleRalphCollision(self, task): 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(0, 0, 0) return task.cont
def __init__(self, showbase): # Initialise Window self.showbase = showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming = deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text="HP: " + str(100.0), pos=(0.95, -0.95), scale=0.07, fg=(1, 1, 1, 1), align=TextNode.ACenter, mayChange=1) # Keys array (down if 1, up if 0) self.keys = {"left": 0, "right": 0, "up": 0, "down": 0, "c": 0, "x": 0} self.skybox = Skybox(self.showbase) self.ch = CameraHandler() # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man = SpellManager( self.showbase.num_warlocks ) # until the Game() class is created in here which i think it should for i in self.showbase.spells: self.showbase.spell_man.add_spell(i) self.game = Game(self.showbase, game_tick) self.warlock = self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick = 0 self.temp_tick = 0 # Set event handlers for keys self.showbase.accept("escape", sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c", set_value, [self.keys, "c", 1]) self.showbase.accept("c-up", set_value, [self.keys, "c", 0]) # variable to track which spell has been requested self.current_spell = -1 # keys to change spell self.showbase.accept("q", self.set_spell, [0]) self.showbase.accept("w", self.set_spell, [1]) self.showbase.accept("e", self.set_spell, [2]) self.showbase.accept("r", self.set_spell, [3]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1", self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3", self.update_destination) # sets the camera up behind clients warlock looking down on it from angle follow = self.warlock.model self.ch.setTarget(follow.getPos().getX(), follow.getPos().getY(), follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(), 0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop, "Game Loop")
class Round(): # Initialisation Function def __init__(self, showbase): # Initialise Window self.showbase = showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming = deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text="HP: " + str(100.0), pos=(0.95, -0.95), scale=0.07, fg=(1, 1, 1, 1), align=TextNode.ACenter, mayChange=1) # Keys array (down if 1, up if 0) self.keys = {"left": 0, "right": 0, "up": 0, "down": 0, "c": 0, "x": 0} self.skybox = Skybox(self.showbase) self.ch = CameraHandler() # maybe this shit too, or this can stay here and just pass in an array of spells self.showbase.spell_man = SpellManager( self.showbase.num_warlocks ) # until the Game() class is created in here which i think it should for i in self.showbase.spells: self.showbase.spell_man.add_spell(i) self.game = Game(self.showbase, game_tick) self.warlock = self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick = 0 self.temp_tick = 0 # Set event handlers for keys self.showbase.accept("escape", sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c", set_value, [self.keys, "c", 1]) self.showbase.accept("c-up", set_value, [self.keys, "c", 0]) # variable to track which spell has been requested self.current_spell = -1 # keys to change spell self.showbase.accept("q", self.set_spell, [0]) self.showbase.accept("w", self.set_spell, [1]) self.showbase.accept("e", self.set_spell, [2]) self.showbase.accept("r", self.set_spell, [3]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1", self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3", self.update_destination) # sets the camera up behind clients warlock looking down on it from angle follow = self.warlock.model self.ch.setTarget(follow.getPos().getX(), follow.getPos().getY(), follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(), 0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop, "Game Loop") def set_spell(self, spell): self.current_spell = spell # sends spell request to server if one is selected def cast_spell(self): if not self.current_spell == -1: target = self.ch.get_mouse_3d() if not target.getZ() == -1: data = {} data[0] = "spell" data[1] = {} data[1][0] = self.current_spell data[1][1] = {} data[1][1][0] = target.getX() data[1][1][1] = target.getY() self.showbase.client.sendData(data) self.current_spell = -1 # sends destination request to server, or cancels spell if selected def update_destination(self): if self.current_spell == -1: destination = self.ch.get_mouse_3d() if not destination.getZ() == -1: data = {} data[0] = "destination" data[1] = {} data[1][0] = destination.getX() data[1][1] = destination.getY() self.showbase.client.sendData(data) else: self.current_spell = -1 def update_camera(self, dt): # sets the camMoveTask to be run every frame self.ch.camMoveTask(dt) # if c is down update camera to always be following on the warlock if self.keys["c"]: follow = self.warlock.model self.ch.setTarget(follow.getPos().getX(), follow.getPos().getY(), follow.getPos().getZ()) self.ch.turnCameraAroundPoint(0, 0) # Game Loop Procedure def game_loop(self, task): # update total time self.total_time += globalClock.getDt() # process any incoming network packets temp = self.showbase.client.getData() if temp != []: for i in range(len(temp)): # this part puts the next packets onto the end of the queue self.incoming.append(temp[i]) # while there is packets to process while list(self.incoming): valid_packet = False package = self.incoming.popleft() # if username is sent, assign to client if package[0] == 'tick': # not sure if this is the best way to do this but yea something to look into for syncing them all preround i guess if package[1] == 0: self.total_time = 0 # check what tick it should be self.temp_tick = package[1] # if this tick needs to be run (if frames are up to the server tick) if self.temp_tick * game_tick <= self.total_time: # run tick if not self.game.run_tick(): print 'Game Over' self.update_camera( game_tick ) # maybe this should be put outside of this loop and just updated from the globalClock.getDt() self.hp.setText( "HP: " + str(self.warlock.hp) ) # i think there should be a HUD class which will show all the info needed for the player (like hps,spells cds, etc) valid_packet = True else: # otherwise put packet back on front of list and end frame processing self.incoming.appendleft(package) break # i think it should check for 'tick' and if not tick then pass the rest of the packets to a packet handler (kind of makes it more modable i guess for changing the game to another like pudgewars or centipede or w/e) # so i guess these will be put into a packet manager (i think this idea you had before anyway :P) silly me! :D # well, just leave here for now i guess :P elif package[0] == 'update_dest': # if its an update packet then update destination of required warlock print "Update Destination: " + str(package[1]) + " " + str( package[2]) self.game.warlock[package[1]].set_destination( Vec3(package[2][0], package[2][1], 0)) valid_packet = True elif package[0] == 'update_spell': # if its an update packet then update destination of required warlock print "Update Spell: " + str(package[1]) + " " + str( package[2]) + " " + str(package[3]) self.game.warlock[package[1]].set_spell(package[2], package[3]) valid_packet = True # Return cont to run task again next frame return task.cont
logging.info("arduino start") arduino = ArduinoManager( "/dev/ttyACM0", 115200, 0, queueJob, "A", sendCamera, fpReceived, fpNow, ) ph.registerHandler(arduino) jobList.append(arduino) logging.info("camera start") c = CameraHandler(queueJob, "R", sendCamera, currentRunNumber, algoVer) ph.registerHandler(c) jobList.append(c) if algoVer == 1: resultsFolder = "/home/pi/checklist-results" imageFolder = "/home/pi/checklist-images" statusFolder = "/home/pi/checklist-status" remvoveFilesInFolder(resultsFolder) remvoveFilesInFolder(imageFolder) remvoveFilesInFolder(statusFolder) while True: if queueJob.qsize() != 0:
def __init__(self,showbase): # Initialise Window self.showbase=showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming=deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text = "HP: "+str(100.0), pos = (0.95,-0.95), scale = 0.07,fg=(1,1,1,1),align=TextNode.ACenter,mayChange=1) # Keys array (down if 1, up if 0) self.keys={"left":0,"right":0,"up":0,"down":0,"c":0,"x":0} self.skybox=Skybox(self.showbase) self.ch=CameraHandler() self.game=Game(self.showbase.num_warlocks,game_tick,self.showbase) self.warlock=self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick=0 self.temp_tick=0 # Set event handlers for keys self.showbase.accept("escape",sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c",set_value,[self.keys,"c",1]) self.showbase.accept("c-up",set_value,[self.keys,"c",0]) # variable to track which spell has been requested self.current_spell=0 # keys to change spell self.showbase.accept("q",self.set_spell,[1]) self.showbase.accept("w",self.set_spell,[2]) self.showbase.accept("e",self.set_spell,[3]) self.showbase.accept("r",self.set_spell,[4]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1",self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3",self.update_destination) # Create a method to read key-status and then do. on server side. # Should add a key here for the spell.. . # x is for spell test. self.showbase.accept("x",set_value,[self.keys,"spell1", 1]) self.showbase.accept("x-up",set_value,[self.keys,"spell1", 0]) #self.showbase.accept("a",self.warlock.add_spell_vel,[Vec3(20,0,0)]) #self.showbase.accept("d",self.warlock.add_spell_vel,[Vec3(-20,0,0)]) #self.showbase.accept("w",self.warlock.add_spell_vel,[Vec3(0,-20,0)]) #self.showbase.accept("s",self.warlock.add_spell_vel,[Vec3(0,20,0)]) #self.showbase.accept("+",self.warlock.add_damage,[1]) #self.showbase.accept("-",self.warlock.add_damage,[-1]) # sets the camera up behind clients warlock looking down on it from angle follow=self.warlock self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(),0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop,"Game Loop")
class Playstate(): # Initialisation Function def __init__(self,showbase): # Initialise Window self.showbase=showbase # total time since start of game, to keep ticks updating on time (rather, not before) self.total_time = 0 # packets queue self.incoming=deque() # this is unnecessary lol but meh ill comment it anyway self.hp = OnscreenText(text = "HP: "+str(100.0), pos = (0.95,-0.95), scale = 0.07,fg=(1,1,1,1),align=TextNode.ACenter,mayChange=1) # Keys array (down if 1, up if 0) self.keys={"left":0,"right":0,"up":0,"down":0,"c":0,"x":0} self.skybox=Skybox(self.showbase) self.ch=CameraHandler() self.game=Game(self.showbase.num_warlocks,game_tick,self.showbase) self.warlock=self.game.warlock[self.showbase.which] self.warlock.attach_ring(self.showbase) self.tick=0 self.temp_tick=0 # Set event handlers for keys self.showbase.accept("escape",sys.exit) # holding c will focus the camera on clients warlock self.showbase.accept("c",set_value,[self.keys,"c",1]) self.showbase.accept("c-up",set_value,[self.keys,"c",0]) # variable to track which spell has been requested self.current_spell=0 # keys to change spell self.showbase.accept("q",self.set_spell,[1]) self.showbase.accept("w",self.set_spell,[2]) self.showbase.accept("e",self.set_spell,[3]) self.showbase.accept("r",self.set_spell,[4]) # mouse 1 is for casting the spell set by the keys self.showbase.accept("mouse1",self.cast_spell) # mouse 3 is for movement, or canceling keys for casting spell self.showbase.accept("mouse3",self.update_destination) # Create a method to read key-status and then do. on server side. # Should add a key here for the spell.. . # x is for spell test. self.showbase.accept("x",set_value,[self.keys,"spell1", 1]) self.showbase.accept("x-up",set_value,[self.keys,"spell1", 0]) #self.showbase.accept("a",self.warlock.add_spell_vel,[Vec3(20,0,0)]) #self.showbase.accept("d",self.warlock.add_spell_vel,[Vec3(-20,0,0)]) #self.showbase.accept("w",self.warlock.add_spell_vel,[Vec3(0,-20,0)]) #self.showbase.accept("s",self.warlock.add_spell_vel,[Vec3(0,20,0)]) #self.showbase.accept("+",self.warlock.add_damage,[1]) #self.showbase.accept("-",self.warlock.add_damage,[-1]) # sets the camera up behind clients warlock looking down on it from angle follow=self.warlock self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(follow.getH(),0) # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.game_loop,"Game Loop") def set_spell(self,spell): self.current_spell=spell # sends spell request to server if one is selected def cast_spell(self): if not self.current_spell==0: target=self.ch.get_mouse_3d() if not target.getZ()==-1: data = {} data[0] = "spell" data[1] = {} data[1][0] = self.current_spell data[1][1] = {} data[1][1][0] = target.getX() data[1][1][1] = target.getY() self.showbase.client.sendData(data) self.current_spell=0 # sends destination request to server, or cancels spell if selected def update_destination(self): print "update_destination "+str(self.current_spell) if self.current_spell==0: destination=self.ch.get_mouse_3d() if not destination.getZ()==-1: data = {} data[0] = "destination" data[1] = {} data[1][0] = destination.getX() data[1][1] = destination.getY() self.showbase.client.sendData(data) else: self.current_spell=0 def update_camera(self,dt): # sets the camMoveTask to be run every frame self.ch.camMoveTask(dt) # if c is down update camera to always be following on the warlock if self.keys["c"]: follow=self.warlock self.ch.setTarget(follow.getPos().getX(),follow.getPos().getY(),follow.getPos().getZ()) self.ch.turnCameraAroundPoint(0,0) # Game Loop Procedure def game_loop(self,task): # update total time self.total_time+=globalClock.getDt() # process any incoming network packets temp=self.showbase.client.getData() if temp!=[]: for i in range(len(temp)): # this part puts the next packets onto the end of the queue self.incoming.append(temp[i]) # while there is packets to process while list(self.incoming): valid_packet=False package=self.incoming.popleft() # if username is sent, assign to client if package[0]=='tick': if package[1]==0: self.total_time=0 # check what tick it should be self.temp_tick=package[1] # if this tick needs to be run (if frames are up to the server tick) if self.temp_tick*game_tick<=self.total_time: # run tick self.game.run_tick() self.update_camera(game_tick) self.hp.setText("HP: "+str(self.warlock.hp)) #self.tick+=1 valid_packet=True else: #print "temp: "+str(self.temp_tick*game_tick) #print "total:"+str(self.total_time) # otherwise put packet back on front of list and end frame processing self.incoming.appendleft(package) break elif package[0]=='update_dest': # if its an update packet then update destination of required warlock print "Update Destination: "+str(package[1])+" "+str(package[2]) self.game.warlock[package[1]].set_destination(Vec3(package[2][0],package[2][1],0)) valid_packet=True elif package[0]=='update_spell': # if its an update packet then update destination of required warlock print "Update Spell: "+str(package[1])+" "+str(package[2])+" "+str(package[3]) self.game.warlock[package[1]].set_spell(package[2],package[3]) valid_packet=True if not valid_packet: data = {} data[0] = "error" data[1] = "Fail Server" self.game.client.sendData(data) print "Bad packet from server" print "Received: " + str(package) # Return cont to run task again next frame return task.cont
def setupCamera(self): self.camHandler = CameraHandler() self.camHandler.setTarget(self.environ.getX(),self.environ.getY(),self.environ.getZ())
class RTSEngine(DirectObject): def __init__(self): from pandac.PandaModules import loadPrcFileData loadPrcFileData("", "want-directtools #t") loadPrcFileData("", "want-tk #t") self.camHandler = None self.environ = None self.isMoving = False self.trav = CollisionTraverser() self.cHandler = CollisionHandlerQueue() self.picked = None self.selected = None self.setupEnvironment() self.setupCamera() self.setupActors() self.setupLighting() self.gui = mouseSelectTool() self.gui.selectable = [self.box,self.box2] def setupAI(self): self.AIWorld = AIWorld(render) self.AIChar = AICharacter("ralph",self.ralph,60,0.5,15) self.AIWorld.addAiChar(self.AIChar) self.AIBehaviors = self.AIChar.getAiBehaviors() taskMgr.add(self.AIUpdate,"AIUpdate") return def run(self): run() def setupMouseCollision(self): 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.trav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) def setupCamera(self): self.camHandler = CameraHandler() self.camHandler.setTarget(self.environ.getX(),self.environ.getY(),self.environ.getZ()) def setupActors(self): # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor.Actor("models/ralph",{"run":"models/ralph-run","walk":"models/ralph-walk"}) self.ralph = loader.loadModel("models/ralph") self.ralph.setPos(ralphStartPos) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.box = loader.loadModel("models/box") self.box.setPos(5,5,1) self.box.setColor(1,0,0) self.box.setScale(.5) self.box.reparentTo(render) self.box2 = loader.loadModel("models/box") self.box2.setPos(-10,-10,1) self.box2.setColor(1,1,0) self.box2.setScale(.5) self.box2.reparentTo(render) def setupLighting(self): #Setup the lighting and the shader to make it look cartoony plightnode = PointLight("point light") plightnode.setAttenuation(Vec3(1,0,0)) plight = render.attachNewNode(plightnode) plight.setPos(30,-50,0) alightnode = AmbientLight("ambient light") alightnode.setColor(Vec4(0.8,0.8,0.8,1)) alight = render.attachNewNode(alightnode) render.setLight(alight) render.setLight(plight) self.lastMousePos = None alight = AmbientLight("alight") alight.setColor(VBase4(0.5,0.5,0.5,0.5)) self.alnp = self.ralph.attachNewNode(alight) def setupEnvironment(self): #self.environ = loader.loadModel("models/world") #self.terrain = GeoMipTerrain("MyTerrain") #self.terrain.setHeightfield(Filename("models/testHeightMap.png")) #self.terrain.setBruteforce(True) #self.terrain.setBlockSize(64) #self.terrain.setNear(40) #self.terrain.setFar(100) #self.terrain.setFocalPoint(base.camera) #self.environ = self.terrain.getRoot() #self.environ.setShader(Shader.make(SHADER)) #self.environ.setSz(50) #self.terrain_tex = loader.loadTexture('world/shortGrass.png') #self.ts = TextureStage('ts') #self.environ.setTexScale(self.ts.getDefault(),10,10) #self.environ.setTexture(self.terrain_tex,1) #self.terrain.generate() #self.environ.reparentTo(render) #base.toggleWireframe() #self.environ = self.terrain.getRoot() #self.environ.setPos(1,1,0) self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setScale(0.25,0.25,0.25) self.environ.setPos(0,0,0) def update(self, task): self.terrain.setFocalPoint(base.camera.getX(),base.camera.getY()) self.terrain.update() return task.cont def setMove(self): try: print "none" except: print "Failed" self.ralph.loop("run") return def AIUpdate(self,task): self.AIWorld.update() if(self.AIBehaviors.behaviorStatus("pathfollow") == "done"): self.ralph.stop("run") self.ralph.pose("walk",0) return task.cont def handleRalphCollision(self,task): 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(0,0,0) return task.cont
from Config import * import direct.directbase.DirectStart from direct.gui.OnscreenText import OnscreenText from pandac.PandaModules import PandaNode, NodePath, Camera, TextNode, GeomTristrips, Geom, GeomVertexFormat, GeomVertexData, GeomVertexWriter, GeomNode, TransformState, OrthographicLens, TextureStage, TexGenAttrib, PNMImage, Texture, ColorBlendAttrib from panda3d.core import * from direct.gui.DirectGui import * from direct.interval.IntervalGlobal import * from direct.task import Task import Effect import Sprite from CameraHandler import CameraHandler camhandler = CameraHandler() terrain = render.attachNewNode('terrain') tile1 = loader.loadModel(GAME + "/models/slopes/flat") tile1.setScale(3.0) tile1.reparentTo(terrain) tile1.setColor(0, 0, 1, 1) tile1.setPos(9, 0, 0) sprite1 = Sprite.Sprite(GAME + '/textures/sprites/4C_F_1.png', 3) sprite1.node.reparentTo(terrain) sprite1.node.setPos(9, 0, 0) tile2 = loader.loadModel(GAME + "/models/slopes/flat") tile2.setScale(3.0) tile2.reparentTo(terrain) tile2.setColor(0, 0, 1, 1) tile2.setPos(-9, 0, 0) sprite2 = Sprite.Sprite(GAME + '/textures/sprites/4C_F_1.png', 1)
def get_photo4(self): CameraHandler.get_instance().capture('test.jpg') self.pixmap4 = QPixmap("test.jpg") self.ui.pushButtonPhoto4.setIcon(QIcon(self.pixmap4))