def Hit(): print('Dealer deals new card') suit = GameLogic.GetSuit() rank = GameLogic.GetRank() lblStr = rank + ' of ' + suit print(lblStr) label.config(text=lblStr) #Change text
def on_mouse_press(self, x, y, button, modifiers): # Called when the user presses a mouse button. columunIndex = int((x - MARGIN) / (SQUARE_SIZE + MARGIN)) print(columunIndex) if logic.getBoardStatus() != logic.YELLOW_WON and logic.getBoardStatus() != logic.RED_WON: if logic.canPlay(columunIndex): logic.play(columunIndex)
def is_valid(self): if self.start_vec is None or self.end_vec is None: # check if one hasnt been set yet return False start_piece = GL.get_piece(self.board, self.start_vec) end_piece = GL.get_piece(self.board, self.end_vec) if GL.get_team( start_piece ) != self.player: # make sure you're moving your own pieces return False if end_piece != GL.EMPTY: # you must move to an empty square return False move_tup = (self.start_vec, self.end_vec) temp = GL.get_potential_moves(self.board, self.start_vec) for potential_move in temp: if potential_move == move_tup: self.captured = potential_move.captured if GL.can_capture(self.board, self.player) and not self.captured: return False return True return False
def set_active_camera(self, camera): """Set the active camera""" if type(camera) == str: scene = gl.getCurrentScene() camera = scene.cameras[camera] scene.active_camera = camera else: gl.getCurrentScene().active_camera = camera.camera
def startGame(self): if not self.gameIsRunning: for i, btn in enumerate(self.buttons): btn.clicked.connect( getattr(self, "button" + str(i) + "pressed")) self.gameIsRunning = True self.playerOne = -1 self.playerTwo = -2 self.game = GameLogic(self.playerOne, self.playerTwo)
def findSceneByName(sceneName): if sceneName == "": return GameLogic.getCurrentScene() for scene in GameLogic.getSceneList(): if scene.name == sceneName: return scene raise LookupError(("No active scene with name '%s' found" % (sceneName)))
def mouse_click(screen, board): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.MOUSEBUTTONDOWN: #left, mid, right = pygame.mouse.get_pressed() board.update = True pos = pygame.mouse.get_pos() if (board.player != board.opp and not board.game_over) or board.game_over: gl.update_board(screen, board, pos)
def main(cont): own = cont.getOwner() sens = cont.getSensor('type_hit') if sens.isPositive(): for ob in sens.getHitObjectList(): if ob.type == 'ram': actu = cont.getActuator('ramDetect') GameLogic.addActiveActuator(actu, True)
def parse_input(user_address, client_socket, pre_parsed_message): # input: # ssid # operation # operation context try: string_list = pre_parsed_message.split('\n') session_id, operation, operation_context = int( string_list[0]), string_list[1], string_list[2] except Exception: client_socket.send( f"O {user_address} enviou uma mensagem invalida!\n".encode( "utf-8")) client_socket.close() return False if session_id == 0: Value, newid = Db.create_member_user(operation_context) if Value: client_socket.send( f"OK New member added with id: {newid}".encode("utf-8")) else: client_socket.send(f"Error Adding New Row".encode("utf-8")) elif session_id != -1 and not Db.check(session_id): client_socket.send("INVALID SESSION ID".encode("utf-8")) else: # operações na DB if operation == "DB": error, output = Db.run_query(session_id, operation_context) if error: print("ERROR + DB: " + error) client_socket.send(str(error).encode("utf-8")) else: print("OK + DB") client_socket.send(output.encode("utf-8")) # operações no jogo elif operation == "GAME": Game.find_enemy(session_id, operation_context) print("OK + GAME") # operações na shop elif operation == "SHOP": error, output = Shop.parse(session_id, operation_context) if error: client_socket.send(str(error).encode("utf-8")) print("ERROR + SHOP: " + error) else: client_socket.send(str(output).encode("utf-8")) print("OK + SHOP") else: client_socket.send("NO VALID OPERATION".encode("utf-8"))
def main(cont): own = cont.getOwner() for ob in own.getChildren(): if hasattr(ob, 'carried'): pos = ob.getPosition() ob.carried= 0 ob.removeParent() play_cart_act= cont.getActuators()[0] GameLogic.addActiveActuator(play_cart_act, True)
def avoidanceVector(self,fear): '''find an vector that will avoid a named object in the current scene ''' if not fear in GameLogic.getCurrentScene().objects: return Vector((0,0)) # object was not found fearObj = GameLogic.getCurrentScene().objects[fear] fearPos = fearObj.worldPosition.copy() theta = atan2(self.worldPosition[1] - fearPos.y,self.worldPosition[0] - fearPos.x) return(Vector((cos(theta),sin(theta))))
def on_draw(self): # Rendering arcade.start_render() # Print board printBoard() if logic.getBoardStatus() == logic.RED_WON: arcade.draw_text("Red Win", 50, 10, arcade.color.BLACK, 14) elif logic.getBoardStatus() == logic.YELLOW_WON: arcade.draw_text("Yellow Win", 50, 10, arcade.color.BLACK, 14) else: arcade.draw_text(logic.currentPlayer, 50, 10, arcade.color.BLACK, 14)
def main(): game_exit = False while not game_exit: display_title() for event in pygame.event.get(): if event.type == pygame.QUIT: game_exit = True if event.type == pygame.MOUSEBUTTONDOWN: if UIHandler.check_title_buttons_clicked() == "Play": GameLogic.on_start() player.on_start() elif UIHandler.check_title_buttons_clicked() == "How to play": GameLogic.state = "how to play" elif UIHandler.check_title_buttons_clicked() == "Quit": GameLogic.game_running = False game_exit = True while GameLogic.game_running: for event in pygame.event.get(): if event.type == pygame.QUIT: GameLogic.game_running = False game_exit = True KeyboardHandler.on_event(event, player) on_tick() draw() pygame.display.update() clock.tick(Config.FPS) while GameLogic.state == "high score": display_high_score_screen() for event in pygame.event.get(): if event.type == pygame.QUIT: GameLogic.state = "quit" game_exit = True if event.type == pygame.MOUSEBUTTONDOWN: if UIHandler.check_high_score_buttons_clicked( ) == "Finish": GameLogic.state = "title" while GameLogic.state == "how to play": display_how_to_play_screen() for event in pygame.event.get(): if event.type == pygame.QUIT: GameLogic.state = "quit" game_exit = True if event.type == pygame.MOUSEBUTTONDOWN: if UIHandler.check_how_to_play_buttons_clicked() == "Back": GameLogic.state = "title"
def avoid(self): p1 = self.worldPosition.copy() p1.z = 0 result = self.blank.copy() for sheep in self.flock: p2 = sheep.worldPosition.copy() p2.z = 0 dist = (p1 - p2).magnitude angle = atan2(p1.y - p2.y,p1.x - p2.x) if 0 < dist < self.r1: size = 1/dist**2 result.x = result.x + size*cos(angle) result.y = result.y + size*sin(angle) try: #Will fail if there is no ram. ram = GameLogic.getCurrentScene().objects['ram'] p2 = ram.worldPosition.copy() p2.z = 0 dist = (p1 - p2).magnitude angle = atan2(p1.y - p2.y,p1.x - p2.x) if 0 < dist < 1.5*self.r1: size = 1.5/dist**2 result.x = result.x + size*cos(angle) result.y = result.y + size*sin(angle) except: pass result = result + self.avoidStatic() tractor = GameLogic.getCurrentScene().objects['tractor'] p2 = tractor.worldPosition.copy() p2.z = 0 dist = (p1 - p2).magnitude angle = atan2(p1.y - p2.y,p1.x - p2.x) if 0 < dist < 3*self.r1: size = 5/dist**2 result.x = result.x + size*cos(angle) result.y = result.y + size*sin(angle) if result.magnitude > 0.05: self.run() result.normalize() return result if result.magnitude > 0.04: self.flounder() else: self.walk() result.normalize() return result
def Hit(): if GameLogic.cardTotal > 21 or GameLogic.funds <= 0: GameLogic.box.showinfo('Lost', 'You have lost the game.\nPlease choose New from File menu') else: print('Dealer deals new card') suit = GameLogic.GetSuit() rank = GameLogic.GetRank() lblStr = rank + ' of ' + suit print(GameLogic.cardTotal) isMatch = GameLogic.CheckHand(lblStr, self.cardManager.GetCards()) while isMatch == 'match': suit = GameLogic.GetSuit() rank = GameLogic.GetRank() lblStr = rank + ' of ' + suit isMatch = GameLogic.CheckHand(lblStr, self.cardManager.GetCards()) if rank == 'Ace': if 11 + GameLogic.cardTotal > 21: GameLogic.cardTotal += 1 else: GameLogic.cardTotal += 11 else: GameLogic.cardTotal += GameLogic.GetRankNum(rank) self.cardManager.SetNextCard(lblStr) if GameLogic.isOver(GameLogic.cardTotal) == 'true': GameLogic.box.showinfo('Lost', 'You have lost the game.\nPress NEW ROUND to play again') GameLogic.funds -= 50 self.SetLabel() elif GameLogic.cardTotal == 21: GameLogic.box.showinfo('WIN!!!!!', 'You have WON the game!!!!') GameLogic.funds += 100 self.SetLabel()
def main(): if GameLogic.Object['closed']: return # get controller controller = GameLogic.getCurrentController() gu.keep_conn([conn1, conn2]) obj = controller.owner pos = obj.localPosition ori = obj.localOrientation try: arduino = serial.Serial('/dev/arduino_ethernet', 9600) if x1_in <= pos[0] <= x_out and y_in <= pos[1] <= y_out: arduino.write(b'A') elif -x1_in >= pos[0] >= -x_out and -y_in >= pos[1] >= -y_out: arduino.write(b'B') else: arduino.write(b'L') except: print("No reward") if conn1 is not None: # get mouse movement t1, dt1, x1, y1 = gu.read32(conn1) t2, dt2, x2, y2 = gu.read32(conn2) else: t1, dt1, x1, y1 = np.array([0,]), np.array([0,]), np.array([0,]), np.array([0,]) t2, dt2, x2, y2 = np.array([0,]), np.array([0,]), np.array([0,]), np.array([0,]) # move according to ball readout: movement(controller, (x1, y1, x2, y2, t1, t2, dt1, dt2))
def onMouse(): Rasterizer.showMouse(True) cont = GameLogic.getCurrentController() mouse = cont.sensors["Mouse"] over = cont.sensors["Over"] if mouse.positive: hit = over.hitObject if hit is None: return print(hit.name) print(hit.children) if hit.name in buildings: deselectAll() hit.children["Base01.Selected"].setVisible(True) infoPanelShow(hit) addUnit() else: if hit.name in units: deselectAll() hit.children["Unit0.Selected"].setVisible(True) cont.owner["selected"] = hit["id"] infoPanelShow(hit) else: for target in scene.objects: if "Target" in target.name and target["id"] == cont.owner["selected"]: target.localPosition = over.hitPosition
def main(): imgDetectorX = 64 * 5 imgDetectorY = 36 * 5 imgPickupX = 256 imgPickupY = 144 if hasattr(GameLogic, 'detector') and hasattr(GameLogic, 'pickup'): GameLogic.detector.refresh(True) GameLogic.pickup.refresh(True) GameLogic.detector_png = list(GameLogic.detector.source.image) GameLogic.pickup_png = list(GameLogic.pickup.source.image) thread = Worker(None) thread.run(imgDetectorX, imgDetectorY, imgPickupX, imgPickupY) else: scene = GameLogic.getCurrentScene() screen1 = scene.objects['Screen1'] screen2 = scene.objects['Screen2'] detectorcamera = scene.objects['DetectionCamera'] pickupcamera = scene.objects['PickupCamera'] GameLogic.detector = bge.texture.Texture(screen1, 0, 0) GameLogic.pickup = bge.texture.Texture(screen2, 0, 0) GameLogic.detector.source = VideoTexture.ImageRender( scene, detectorcamera) GameLogic.detector.source.capsize = (imgDetectorX, imgDetectorY) GameLogic.detector_png = GameLogic.detector.source.image[:] GameLogic.pickup.source = VideoTexture.ImageRender(scene, pickupcamera) GameLogic.pickup.source.capsize = (imgPickupX, imgPickupY) GameLogic.pickup_png = GameLogic.pickup.source.image[:]
def main(): # Get owner controller = GameLogic.getCurrentController() owner = controller.owner Host = 'localhost' ServerPort = 10000 # Set socket server only one time at the first frame if not owner['OneTime']: # Set UDP socket GameLogic.sServer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to host GameLogic.sServer.bind((Host, ServerPort)) # If no data are found, pass GameLogic.sServer.setblocking(0) # Set prop to pass test owner['OneTime'] = True # Get Position and Orientation PosCar = owner.worldPosition OriCar = owner.worldOrientation # New in python 3 stupid = (PosCar[0], PosCar[1], PosCar[2], OriCar[0][0], OriCar[0][1], OriCar[0][2], OriCar[1][0], OriCar[1][1], OriCar[1][2], OriCar[2][0], OriCar[2][1], OriCar[2][2]) print(stupid) # Serialize data Data = pickle.dumps(stupid) # Send Data to client GameLogic.sServer.sendto(Data, (Host, 10001))
def __init__(self, obName, left, right, axis, medianValue): ''' Create a new LODBranch node. Parameters: obName: The name of the object that represents this node. It should be the sum of all the descendants. It must be on a hidden layer. left: The left LODNode. right: The right LODNode. axis: The axis to search on. medianValue: The location of the median element (of all the leaves) on the given axis. ''' LODNode.__init__(self) self.Object = GameLogic.getCurrentScene().objectsInactive['OB' + obName] # # Parents just cause problems with visibility. # self.Object.removeParent() self.ObjectInstance = None self.Name = obName # # The number of dimensions do not need to be known, because each node # explicitely stores its axis. # self.MedianValue = medianValue self.Axis = axis self.Left = left self.Right = right
def toggle_manipulation(self): """ change from and to manipulation mode. a request to use by a socket. Done for wiimote remote control. """ human = self.blender_obj scene = GameLogic.getCurrentScene() hand_target = scene.objects['IK_Target_Empty.R'] head_target = scene.objects['Target_Empty'] if human['Manipulate']: #Rasterizer.showMouse(False) human['Manipulate'] = False # Place the hand beside the body hand_target.localPosition = [0.0, -0.3, 0.8] head_target.setParent(human) head_target.localPosition = [1.3, 0.0, 1.7] else: #Rasterizer.showMouse(True) human['Manipulate'] = True head_target.setParent(hand_target) # Place the hand in a nice position hand_target.localPosition = [0.6, 0.0, 1.4] # Place the head in the same place head_target.localPosition = [0.0, 0.0, 0.0]
def update_robots(self): """ Update robots' poses in the HLA federation for multinode synchronization. """ self.morse_ambassador.tag = False scene = GameLogic.getCurrentScene() t = self.morse_ambassador.current_time + self.morse_ambassador.lookahead for obj in self.morse_ambassador.objects: obj_name = self.rtia.getObjectInstanceName(obj) obj_pos = scene.objects[obj_name].worldPosition.to_tuple() obj_ori = scene.objects[obj_name].worldOrientation.to_euler() hla_att = { self.morse_ambassador.out_position: MorseVector.pack([obj_pos[0], obj_pos[1], obj_pos[2]]), self.morse_ambassador.out_orientation: MorseVector.pack([obj_ori.x, obj_ori.y, obj_ori.z])} try: self.rtia.updateAttributeValues(obj, hla_att, "update", t) except rti.InvalidFederationTime: logger.debug("Invalid time for UAV: %s; Federation time is %s", t, self.rtia.queryFederateTime()) if self.certi_env["TimeRegulation"]: self.rtia.timeAdvanceRequest(t) while (not self.morse_ambassador.tag): self.rtia.tick(0, 1) scene.objects["HLA_Empty"]["Time"] = self.morse_ambassador.current_time else: self.rtia.tick()
def configureHLA(self): """ Configure the HLA network environment. Uses the Game Properties of the HLA_Empty object if defined, default values otherwise. """ logger.info("Initializing configuration") if os.getenv("CERTI_HTTP_PROXY") == None: os.environ["CERTI_HTTP_PROXY"] = "" logger.debug("CERTI_HTTP_PROXY= %s", os.environ["CERTI_HTTP_PROXY"]) try: hla = GameLogic.getCurrentScene().objects["HLA_Empty"] for k in self.certi_env.keys(): try: v = hla[k] self.certi_env[k] = v logger.debug("%s= %s", k, v) except KeyError: logger.debug("No property for %s; using %s", k, self.certi_env[k]) except KeyError: log.error("The HLA_Empty object has not been found on current scene!") os.environ["CERTI_HOST"] = self.certi_env["CERTI_HOST"] logger.debug("CERTI_HOST= %s", os.environ["CERTI_HOST"])
def initialize(server_addrPort): """Initialize connections and configures facial subsystem""" import sys # for init, imports are done on demand print "LIGHTHEAD Facial Animation System, python version:", sys.version print "loaded module from", __path__[0] import comm from lightHead_server import lightHeadServer, lightHeadHandler G.server = comm.create_server(lightHeadServer, lightHeadHandler, server_addrPort, THREAD_INFO) G.server.create_protocol_handlers() # get driven objects objs = G.getCurrentScene().objects for obj_name in ('eye_L', 'eye_R', 'jaw', 'tongue'): try: setattr(G, obj_name, objs[OBJ_PREFIX+obj_name]) except KeyError: try: # WARNING: at least in python 2.6 capitalize and title docstrings are confused! setattr(G, obj_name, objs[OBJ_PREFIX+obj_name.title()]) except KeyError, e: raise Exception('no object "%s" in blender file' % e[0][16:-18])
def printAll(cont): if not cont.sensors[0].positive: return for obj in GameLogic.getCurrentScene().objects: if PBase in obj: printBaseForObj(obj)
def default_action(self): """ Look for nearby victims, and heal when instructed to """ # Look for victims in the cone of the sensor contr = GameLogic.getCurrentController() radar = contr.sensors['Radar'] if radar.triggered and radar.positive: for victim_obj in radar.hitObjectList: victim_position = victim_obj.worldPosition self.local_data['victim_dict'][victim_obj.name] = [victim_position[0], victim_position[1], victim_position[2]] # Find the closest victim and its distance new_distance = self.blender_obj.getDistanceTo(victim_obj) if new_distance < self._nearest_distance: self._nearest_victim = victim_obj self._nearest_distance = new_distance # When instructed to do so, help a victim if self._healing: self._heal_victim() if radar.triggered and not radar.positive: # Clear the variables for the victims self.local_data['victim_dict'] = {} self._nearest_victim = None self._nearest_distance = 999999
def grasp_(self, seq): """ Grasp object. """ human = self.blender_obj if human['Manipulate']: scene = GameLogic.getCurrentScene() hand_empty = scene.objects['Hand_Grab.R'] selected_object = hand_empty['Near_Object'] if seq == "t": # Check that no other object is being carried if (human['DraggedObject'] == None or human['DraggedObject'] == '') : # If the object is draggable if selected_object != None and selected_object != '': # Clear the previously selected object, if any human['DraggedObject'] = selected_object # Remove Physic simulation selected_object.suspendDynamics() # Parent the selected object to the hand target selected_object.setParent (hand_empty) if seq == "f": if (human['DraggedObject'] != None and human['DraggedObject'] != '') : previous_object = human["DraggedObject"] # Restore Physics simulation previous_object.restoreDynamics() previous_object.setLinearVelocity([0, 0, 0]) previous_object.setAngularVelocity([0, 0, 0]) # Remove the parent previous_object.removeParent() # Clear the object from dragged status human['DraggedObject'] = None
def __init__(self, obj, parent=None): logger.info('%s initialization' % obj.name) # Call the constructor of the parent class super(self.__class__,self).__init__(obj, parent) # Direction of the global vectors self.world_X_vector = mathutils.Vector([1,0,0]) self.world_Y_vector = mathutils.Vector([0,1,0]) self._destination = self.blender_obj.position self._wp_object = None self._collisions = False # Convert the direction tolerance to radians self._angle_tolerance = math.radians(10) # Choose the type of function to move the object #self._type = 'Velocity' self._type = 'Position' self.local_data['x'] = self._destination[0] self.local_data['y'] = self._destination[1] self.local_data['z'] = self._destination[2] # Waypoint tolerance (in meters) self.local_data['tolerance'] = 0.5 # Read the speed from the Blender object properties try: self.local_data['speed'] = self.blender_obj['Speed'] logger.info("Using specified speed of %d" % self.local_data['speed']) # Otherwise use a default value except KeyError as detail: self.local_data['speed'] = 1.0 logger.info("Using default speed of %d" % self.local_data['speed']) # Identify an object as the target of the motion try: wp_name = self.blender_obj['Target'] if wp_name != '': scene = GameLogic.getCurrentScene() self._wp_object = scene.objects[wp_name] logger.info("Using object '%s' to indicate motion target" % wp_name) except KeyError as detail: self._wp_object = None # Identify the collision detectors for the sides for child in self.blender_obj.children: if "Radar.R" in child.name: self._radar_r = child if "Radar.L" in child.name: self._radar_l = child try: logger.info("Radar Right is '%s'" % self._radar_r.name) logger.info("Radar Left is '%s'" % self._radar_l.name) self._collisions = True except AttributeError as detail: logger.warning("No radars found attached to the waypoint actuator.\n\tThere will be no obstacle avoidance") logger.info('Component initialized')
def main(): if GameLogic.Object['closed']: return # get controller controller = GameLogic.getCurrentController() nmouse = 1 mkey = 'm%dconn' % (nmouse) if mkey in GameLogic.Object.keys(): t1, dt1, x1, y1 = gu.read32(GameLogic.Object[mkey]) gu.keep_conn([GameLogic.Object[mkey]]) else: t1, dt1, x1, y1 = 0, 0, np.array([ 0, ]), np.array([ 0, ]) nmouse = 2 mkey = 'm%dconn' % (nmouse) if mkey in GameLogic.Object.keys(): t2, dt2, x2, y2 = gu.read32(GameLogic.Object[mkey]) gu.keep_conn([GameLogic.Object[mkey]]) else: t2, dt2, x2, y2 = 0, 0, np.array([ 0, ]), np.array([ 0, ]) # move according to ball readout: movement(controller, (x1, y1, x2, y2, t1, t2, dt1, dt2))
def default_action(self): """ Look for nearby victims, and heal when instructed to """ # Look for victims in the cone of the sensor contr = GameLogic.getCurrentController() radar = contr.sensors['Radar'] if radar.triggered and radar.positive: for victim_obj in radar.hitObjectList: victim_position = victim_obj.worldPosition # Fill the data structure for the victim victim_coordinate = OrderedDict([ ('x', victim_position[0]), ('y', victim_position[1]), ('z', victim_position[2]) ]) victim_data = OrderedDict([ ('coordinate', victim_coordinate), ('requirements', victim_obj['Requirements']), ('severity', victim_obj['Severity']) ]) self.local_data['victim_dict'][victim_obj.name] = victim_data # Find the closest victim and its distance new_distance = self.blender_obj.getDistanceTo(victim_obj) if new_distance < self._nearest_distance: self._nearest_victim = victim_obj self._nearest_distance = new_distance # When instructed to do so, help a victim if self._healing: self._heal_victim() if radar.triggered and not radar.positive: # Clear the variables for the victims self.local_data['victim_dict'] = {} self._nearest_victim = None self._nearest_distance = 999999
def main(cont): own = cont.getOwner() carry_sens = cont.getSensor('carry_touch') carry_done = False if carry_sens.isPositive(): for ob in carry_sens.getHitObjectList(): if hasattr(ob, 'carried') and ob.carried == 0: ob.carried = 1 ob.setParent(own) carry_done = True if carry_done: play_carry_act = cont.getActuators()[0] GameLogic.addActiveActuator(play_carry_act, True)
def __init__(self, obNames): ''' Create a new LODLeaf node. Parameters: obNames: A list of objects that this node represents. These must be on a hidden layer. ''' LODNode.__init__(self) # # ObjectPairs is a list of tuples: (positionObject, meshObject). When # this node is activated, meshObject will be instantiated in the same # position as positionObject. This allows the same meshObject (e.g. a # group) to be re-used for several elements in the tree. # self.ObjectPairs = [] self.Name = str(obNames) sceneObs = GameLogic.getCurrentScene().objectsInactive for name in obNames: oPos = sceneObs['OB' + name] oMesh = oPos if oPos.has_key('LODObject'): oMesh = sceneObs['OB' + oPos['LODObject']] # # Parents just cause problems with visibility. # oPos.removeParent() self.ObjectPairs.append((oPos, oMesh)) self.ObjectInstances = [] self.NumFramesActive = -1
def reset_view(contr): """ Make the human model look forward """ human = contr.owner scene = GameLogic.getCurrentScene() target = scene.objects['Target_Empty'] # Reset the Empty object to its original position target.localPosition = [1.3, 0.0, 1.7]
def identifyPivot(base): """ Looks for a pivot that meets following criteria relative to base: same position same orientation has NO property "base" has property "baseName" with the name of the base is NOT base Input: base "baseName" property containing the name of the base object (without "OB") """ #============================================================================= # nearlyEqual #============================================================================= def nearlyEqual(objectA, objectB): return ( roundString(objectA)==roundString(objectB) ) # I would prefer to read the group name directly but it is not available. # Therefore the group name should be in property baseType #============================================================================== baseType = base[PBaseType] for obj in GameLogic.getCurrentScene().objects: if (baseType in obj and obj is not base and PBase not in obj and nearlyEqual(obj.worldPosition, base.worldPosition) and nearlyEqual(obj.worldOrientation, base.worldOrientation) ): return obj print ("%s- no pivot found with %s" %(base.name, baseType)) return None
def keyHandler(): cont = G.getCurrentController() keys = cont.sensors["key"].events for key in keys: ## up arrow if key[0] == K.UPARROWKEY: G.car["force"] = -15.0 ## down arrow elif key[0] == K.DOWNARROWKEY: G.car["force"] = 10.0 ## right arrow elif key[0] == K.RIGHTARROWKEY: G.car["steer"] -= 0.05 ## left arrow elif key[0] == K.LEFTARROWKEY: G.car["steer"] += 0.05 ## R elif key[0] == K.RKEY: if key[1] == 1: # re-orient car if G.car["jump"] > 2.0: G.car.position = (G.car.worldPosition[0], G.car.worldPosition[1], G.car.worldPosition[2] + 3.0) G.car.alignAxisToVect([0.0, 0.0, 1.0], 2, 1.0) G.car.setLinearVelocity([0.0, 0.0, 0.0], 1) G.car.setAngularVelocity([0.0, 0.0, 0.0], 1) G.car["jump"] = 0 ## Spacebar elif key[0] == K.SPACEKEY: # hackish Brake if G.car["speed"] > 2.0: G.car["force"] = 15.0 if G.car["speed"] < -2.0: G.car["force"] = -15.0
def quit(): """ Cleanly quit the simulation """ contr = GameLogic.getCurrentController() main_close(contr) main_terminate(contr)
def main(): if GameLogic.Object['closed']: return # get controller controller = GameLogic.getCurrentController() nmouse = 1 mkey = 'm%dconn' % (nmouse) if mkey in GameLogic.Object.keys(): t1, dt1, x1, y1 = gu.read32(GameLogic.Object[mkey]) gu.keep_conn([GameLogic.Object[mkey]]) else: t1, dt1, x1, y1 = 0, 0, np.array([0,]), np.array([0,]) nmouse = 2 mkey = 'm%dconn' % (nmouse) if mkey in GameLogic.Object.keys(): t2, dt2, x2, y2 = gu.read32(GameLogic.Object[mkey]) gu.keep_conn([GameLogic.Object[mkey]]) else: t2, dt2, x2, y2 = 0, 0, np.array([0,]), np.array([0,]) # move according to ball readout: movement(controller, (x1, y1, x2, y2, t1, t2, dt1, dt2))
def shadow(): cont = G.getCurrentController() ownpos = [-5.0, 0.0, 8.0] pos = G.car.worldPosition cont.owner.worldPosition = [ pos[0] + ownpos[0], pos[1] + ownpos[1], pos[2] + ownpos[2] ]
def default_action(self): """ Compute the local temperature Temperature is measured dependent on the closest fire source. """ min_distance = 100000.0 fires = False scene = GameLogic.getCurrentScene() # Look for the fire sources marked so for obj in scene.objects: try: obj['Fire'] fire_radius = obj['Fire_Radius'] # If the direction of the fire is also important, # we can use getVectTo instead of getDistanceTo distance = self.blender_obj.getDistanceTo(obj) if distance < min_distance: min_distance = distance fires = True except KeyError as detail: logger.debug("Exception: " + str(detail)) pass temperature = self._global_temp # Trial and error formula to get a temperature dependant on # distance to the nearest fire source. if fires: temperature += self._fire_temp * math.e ** (-0.2 * min_distance) # Store the data acquired by this sensor that could be sent # via a middleware. self.local_data['temperature'] = float(temperature)
def main(controller): print("SpawnTest Begin") owner = controller.owner owner['scene'] = GameLogic.getCurrentScene() print ('Scenes:', bge.logic.getSceneList()) objects = owner['scene'].objects hidObjects = owner['scene'].objectsInactive owner['cubePositioner'] = hidObjects["DataCubeRoot"] owner['cuboidObject'] = hidObjects['Cuboid'] owner['cuboidText'] = hidObjects["DynamicText"] #printSceneObjects(scene) tmpPath = "C:\\Users\\Glen\\Dropbox\\GradProject\\randomCube.xml" #TODO: Change this to relative path tableXMLPath = "C:\\Users\\Glen\\Dropbox\\GradProject\\DataTable.xml" #dataCubeFromFile(tmpPath, hidObjects['Cuboid'], cuboidText, testDataCubePositioner, scene) owner['dataTable'] = dataTableFromFile(tableXMLPath) owner['tableIndex'] = indexDataTable(owner['dataTable']) owner['dataCube'] = dataCubeFromDataTable(owner['dataTable'], owner['tableIndex'], 'All', owner['cuboidObject'], owner['cuboidText'], owner['cubePositioner'], owner['scene']) #spawnDataCube(2, 2, 2, scene, hidObjects["Cuboid"], testDataCubePositioner) #printSceneObjects(scene) print("SpawnTest End")
def default_action(self): """ Apply (x, y, w) to the parent robot. """ # Reset movement variables vx, vy, vz = 0.0, 0.0, 0.0 rx, ry, rz = 0.0, 0.0, 0.0 # Tick rate is the real measure of time in Blender. # By default it is set to 60, regardles of the FPS # If logic tick rate is 60, then: 1 second = 60 ticks ticks = GameLogic.getLogicTicRate() # Scale the speeds to the time used by Blender try: vx = self.local_data['x'] / ticks vy = self.local_data['y'] / ticks rz = self.local_data['w'] / ticks # For the moment ignoring the division by zero # It happens apparently when the simulation starts except ZeroDivisionError: pass # Get the Blender object of the parent robot parent = self.robot_parent.blender_obj # Give the movement instructions directly to the parent # The second parameter specifies a "local" movement parent.applyMovement([vx, vy, vz], True) parent.applyRotation([rx, ry, rz], True)
def default_action(self): """ Change the 'Severity' property of a nearby victim When the victim is fully healed, set its status as not Injured """ contr = GameLogic.getCurrentController() radar = contr.sensors["Radar"] if self.local_data["heal"]: if radar.triggered and radar.positive: victim = radar.hitObject # Restore the health to the victim if victim["Severity"] > 0: victim["Severity"] = victim["Severity"] - 1 # Set the colors depending on the severity of the injuries red = 1 - victim["Severity"] * 0.05 green = 0.5 + red victim.color = [red, green, 0.5, 1.0] # Change the status if victim["Severity"] == 0: victim["Injured"] = False # Reset the healing flag self.local_data["heal"] = 0
def use_ability(self, num): if num == 1: GameLogic.use_shout(self.x, self.y) if num == 2: GameLogic.use_extend_deadline(self.x, self.y) if num == 3: GameLogic.use_score_up() if num == 4: GameLogic.use_sparkle()
def rotate(co): """ Set the human orientation in reference to the camera orientation. """ ow = co.owner keyboard = co.sensors['Keyboard'] pos = logic.getCurrentScene().objects['POS_EMPTY'] keylist = keyboard.events k = [] #initiate a list with all currently pressed keys for key in keylist: if key[1] == logic.KX_INPUT_ACTIVE: k.append(key[0]) # add all pressed keys to a list - as ASCII CODES ow.worldPosition = pos.worldPosition # Get active camera scene = GameLogic.getCurrentScene() active_camera = scene.active_camera if pos['Manipulate']: ow.worldOrientation = pos.worldOrientation # lock camera to head in Manipulation Mode else: if FORWARDS in k and not(LEFT in k or RIGHT in k): applyrotate(pos.worldOrientation, ow) elif LEFT in k and not(FORWARDS in k or BACKWARDS in k): applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi / 2, 3, 'Z'), ow) # turn around 90 deg elif RIGHT in k and not(FORWARDS in k or BACKWARDS in k): applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi * 3/2, 3, 'Z'), ow) # turn around 270 deg elif LEFT in k and FORWARDS in k: applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi / 4, 3, 'Z'), ow) # turn around 45 deg elif RIGHT in k and FORWARDS in k: applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi * 7 / 4, 3, 'Z'), ow) # turn around 315 deg elif BACKWARDS in k and not(LEFT in k or RIGHT in k): if active_camera.name == "Human_Camera": applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi, 3, 'Z'), ow) # turn around 180 deg if in game-mode elif LEFT in k and BACKWARDS in k: if active_camera.name == "Human_Camera": applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi * 3/4, 3, 'Z'), ow) else: applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi / 4, 3, 'Z'), ow) # turn around 135 deg if in game-mode, else turn 45 deg elif RIGHT in k and BACKWARDS in k: if active_camera.name == "Human_Camera": applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi * 5/4, 3, 'Z'), ow) else: applyrotate(pos.worldOrientation * Matrix.Rotation(math.pi * 7 / 4, 3, 'Z'), ow)
def findObjects(matcher, params, scene=None, attribute=None): if scene is None: objects = [] for scene in GameLogic.getSceneList(): objects.extend(findObjects(matcher, params, scene, attribute)) return objects objectsToMatch = retrieveSceneObjects(scene, attribute) return [obj for obj in objectsToMatch if matcher(obj, *params)]
def main(): top = tkinter.Tk() top.title("Woody") top.resizable(True, True) game = gl.Game(top) top.mainloop()
def isSafeToGraze(self): p1 = self.worldPosition.copy() p1.z = 0 tractor = GameLogic.getCurrentScene().objects['tractor'] p2 = tractor.worldPosition.copy() p2.z = 0 dist = (p1 - p2).magnitude return dist > 3*self.r1
def setPortal(): # This may run when entering a new scene, we may be entering from a portal # 2nd players are placed higher, make sure portal enteries have enough room above sce = GameLogic.getCurrentScene() try: scene_name = globalDict['PORTAL_SCENENAME'] except: scene_name = '' if scene_name and scene_name != sce.name: # we have come from another blend file that needs to switch to a scene. # first switch the scene, this script will run again and set_scene_actu = cont.actuators['portal_scene'] set_scene_actu.scene = scene_name cont.activate(set_scene_actu) return try: target_name = globalDict['PORTAL_OBNAME'] except: return try: target_ob = sce.objects[target_name] # alredy has 'OB' prefix except: print('Oops: portal switch error,', target_name, 'object is not in the scene') return pos = target_ob.worldPosition pos[2] += 1.0 * ID # move other players higher so they dont overlap own_player.localPosition = pos own_player.localOrientation = target_ob.worldOrientation # Keep GameLogic.PORTAL_OBNAME incase there are more players # Annoying, the 'Loading Text', needs to be turned off if we're only for sce in GameLogic.getSceneList(): if sce.name == 'hud': ob = sce.objects.get('OBloading') if ob: ob.visible = False
def minimax(gamestate, depth, alpha, beta, is_max_player): # maximizing player is AI (red) if depth == 0 or is_terminal(gamestate, is_max_player): return (None, heuristic(gamestate)) best_move = None if is_max_player: value = float('-inf') for potential_move in GL.get_all_potential_moves(gamestate, GL.RED): next_gamestate = create_next_gamestate(gamestate, potential_move) test_value = minimax(next_gamestate, depth - 1, alpha, beta, False)[1] if value < test_value: value = test_value best_move = potential_move alpha = max(alpha, value) if alpha >= beta: break return (best_move, value) else: value = float('inf') for potential_move in GL.get_all_potential_moves(gamestate, GL.BLACK): next_gamestate = create_next_gamestate(gamestate, potential_move) test_value = minimax(next_gamestate, depth - 1, alpha, beta, True)[1] if value > test_value: value = test_value best_move = potential_move beta = min(beta, value) if alpha >= beta: break return (best_move, value)
def link_services(): """ Read the configuration script (inside the .blend file) and assign the correct service handlers and options to each component. """ try: component_list = component_config.component_service except (AttributeError, NameError) as detail: # Exit gracefully if there are no services specified logger.info("No service section found in configuration file.") return True for component_name, request_manager_data in component_list.items(): # Get the instance of the object if component_name == "simulation": # Special case for the pseudo-component 'simulation' continue try: instance = GameLogic.componentDict[component_name] except KeyError as detail: try: scene = GameLogic.getCurrentScene() robot_obj = scene.objects[component_name] instance = GameLogic.robotDict[robot_obj] except KeyError as detail: logger.error("Component listed in component_config.py not found in scene: {0}".format(detail)) logger.error( """ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ERROR: the component_services section of your configuration file is not valid. Please check the name of your components and restart the simulation. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! """ ) return False for request_manager in request_manager_data: try: modulename, classname = request_manager.rsplit(".", 1) except ValueError: logger.error( "You must specify the fully qualified name " + "of the request manager (eg: " + "morse.middleware.socket_request_manager.SocketRequestManager)" ) return False # Load required request managers if not GameLogic.morse_services.add_request_manager(request_manager): return False GameLogic.morse_services.register_request_manager_mapping(component_name, classname) instance.register_services() logger.info("Component: '%s' using middleware '%s' for services" % (component_name, classname)) return True
def rotation_around_object(point,obj_name,axis,degree): cont=bge.logic.getCurrentController() #取得目前的控制 obj=cont.owner #模組 obj2=GameLogic.getCurrentScene().objects[obj_name] #取得中心點物件 vec=point-obj2.position #兩物件座標的向量 tra=mathutils.Matrix.Translation(-1*vec) tra*=mathutils.Matrix.Rotation(math.radians(degree), 4, axis) #旋轉矩陣 tra*=mathutils.Matrix.Translation(vec) obj.localTransform*=tra
def first_person(name): cont = bge.logic.getCurrentController() #取得目前的控制camera obj = cont.owner #模組 player = GameLogic.getCurrentScene().objects[name] rotation = player.worldOrientation.to_euler() degree = math.radians(90) #朝向物件 obj.worldOrientation = [degree, 0, rotation.z] obj.position = player.position vec.rotate(rotation) obj.position += vec
def switchScene(): G.loc = "1" if G.menuState == "car": G.UIScene.active_camera = G.UIScene.objects["OBCameraCar"] elif G.menuState == "loc": G.UIScene.active_camera = G.UIScene.objects["OBCameraLoc"] else: cont = G.getCurrentController() cont.actuators["load"].fileName = G.loc + ".blend" cont.activate("load")
def addCredit(): ## setup aliases cont = G.getCurrentController() add = cont.actuators["add"] own = cont.owner ## add a sequence of objects, then repeat add.object = str(own["counter"]) cont.activate(add) own["counter"] += 1 if own["counter"] > 10: own["counter"] = 0
def draw_overlays(display): for x in overlays: display.blit(x.get_surface(), (x.x, x.y)) x.on_tick() if GameLogic.abilities_ready_to_use(): display.blit(ability_ready_overlay_img, shout_pos) display.blit(ability_ready_overlay_img, extend_deadline_pos) display.blit(ability_ready_overlay_img, score_up_pos) display.blit(ability_ready_overlay_img, sparkle_pos) if GameLogic.score_up_active: display.blit(ability_active_overlay_img, score_up_pos) if GameLogic.sparkle_active: display.blit(ability_active_overlay_img, sparkle_pos)
def mainLoop(): pygame.init() init() initHUD() clock = pygame.time.Clock() Indicator.HUDs["computer"].changeText(0) Indicator.HUDs["player"].changeText(0) bg = pygame.Surface(conf.resolution) bg.fill(pygame.Color(conf.backGroundColor)) gameField = pygame.Surface((conf.resolution[0] - conf.gameFieldOffset[0], conf.resolution[1] - conf.gameFieldOffset[1])) gameField.fill(pygame.Color(Level.enumColor.fieldBackgroundColor)) lvl = Level.Level(gameField, conf.N) logic = GameLogic.gameLogic(lvl) machine = Player.MachinePlayer("base", lvl) while True: # event block for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit(0) if e.type == pygame.MOUSEBUTTONDOWN: if logic.activePlayer[0] == GameLogic.enumControlType.human: pos = pygame.mouse.get_pos() relativePos = (pos[0] - conf.gameFieldOffset[0], pos[1] - conf.gameFieldOffset[1]) move = lvl.transformMousePosToCells(relativePos) logic.makeMove(move) # update block Indicator.HUDs["move"].changeText(*logic.getInfo()) for key in logic.state["score"]: Indicator.HUDs[key].changeText(logic.state["score"][key]) if logic.activePlayer[0] == GameLogic.enumControlType.machine: move = machine.makeMove(logic.state["moves"]) logic.makeMove(move) if logic.exitState[0]: if logic.exitState[1] == GameLogic.enumPlayers.player2[1]: machine.flushHistory() machine.close() return logic.exitState[1] # show block conf.screen.blit(bg, (0, 0)) conf.screen.blit(gameField, conf.gameFieldOffset) lvl.drawLevel() for hud in Indicator.HUDs.values(): hud.show() pygame.display.update() clock.tick(100)
def run_battleship(cls, speed): """ :param speed(optional): This is the run method for the battleship program. It creates an instance for the logic class ArrangemenBoardAndBoats, board class, gamelogic, and the scorestat class. The method is constructed to run as long as boats exist in the board. When a boat is removed, it is added to a scorestad dictionary. The program is created to stop when 9 boats are added to the scorestat. The speed parameter is optional and can be added to the logic to slow down the game simulation. :return: """ log = Log() arrangelogic = ArrangeBoardAndBoats() boards = arrangelogic.place_boats() gamelogic = GameLogic() scorestat = Scorestat() while True: players = ["Stian", "Bot"] for i, b in enumerate(boards): if i == 0: player = players[0] else: player = players[1] gamelogic.play(b, players, i, speed, player=player) log.print_log(scorestat.get_scoredict())
def render(): board_screen.blit(board_bg, (0,0)) for y in range(8): for x in range(8): tile = GL.get_piece(board, Vector2(x,y)) if tile == GL.EMPTY: continue elif tile == GL.RED: board_screen.blit(red_checker, (checker_locs[x], checker_locs[y])) elif tile == GL.BLACK: board_screen.blit(black_checker, (checker_locs[x], checker_locs[y])) elif tile == GL.RED * GL.KING: board_screen.blit(red_checker_king, (checker_locs[x], checker_locs[y])) elif tile == GL.BLACK * GL.KING: board_screen.blit(black_checker_king, (checker_locs[x], checker_locs[y])) pygame.display.flip()