Ejemplo n.º 1
0
 def get_platform(self, platform_id):
     """Get a platform
     :param platform_id: The uuid of a platform
     :returns: an object of type platform containing the requested platform
     """
     mongo_result = self.__db.platforms.find_one({"_id": ObjectId(platform_id)})
     return Platform.from_mongo_result(mongo_result)
Ejemplo n.º 2
0
    def __init__(self, player):

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with the width, height, x, and y of platform

        platforms = 4
        width = []
        width.append(random.randrange(Global_vars.SCREEN_WIDTH - 200, Global_vars.SCREEN_WIDTH + 400))
        height = Global_vars.SCREEN_HEIGHT - 200
        platform_level = [[width[0], height, 0, 450]]
        i = 0

        while platforms > 0:
            if platforms > 0:
                width.append(random.randrange(Global_vars.SCREEN_WIDTH - 200, Global_vars.SCREEN_WIDTH + 400))
                gap = random.randrange(120, Global_vars.player_jump_length)
                if len(width) > 2:
                    x += width[i] + gap
                else:
                    x = width[i] + gap
                y = random.randrange(height, height + 50)
                if x <= width[i]:
                    x += Global_vars.player_jump_length
                platform_level.append([width[-1], height, x, y])
                platforms -= 1
                i += 1

        # Go through the array above and add playforms
        for platform in platform_level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)
Ejemplo n.º 3
0
 def test_from_mongo_result_performs_mapping(self):
     """Initialise the mapper
     :param mongo_result: A MongoDB result. The following fields
     can currently be mapped:
       * _id
       * _Platform__name
       * _Platform__description
     """
     d = {"_id": "id",
          "_Platform__name": "name",
          "_Platform__description": "description"}
     p = Platform.from_mongo_result(d)
     self.assertEqual(d["_id"], p.id)
     self.assertEqual(d["_Platform__name"], p.name)
     self.assertEqual(d["_Platform__description"], p.description)
Ejemplo n.º 4
0
 def __init__(self):
     Map.__init__(self, 2400, 1200)
     
     ''' Locations and sizes of platforms (width, height, x y) ''' 
     map = [[200, 30, 270, 220],
            [200, 30, 300, 420],
            [200, 30, 600, 110],
            [200, 30, 1000, 800],
            [200, 30, 1400, 900],
            [200, 30, 1850, 1000],
            [200, 30, 10, 1150],
            [200, 30, 600, 1100],
            [200, 30, 2100, 1100]]
     
     for platform in map:
         block = Platform(platform[0], platform[1], platform[2], platform[3])
         self.platform_list.add(block)
Ejemplo n.º 5
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)
        self.setupUi(self)

        backgroundPixmap = QtGui.QPixmap("Resource/BG4.jpeg")
        self.platformImage = Platform(168, 321)
        backgroundCanvas = QtGui.QPixmap(self.screenWidth, self.screenHeight)
        painter = QtGui.QPainter(backgroundCanvas)
        painter.drawPixmap(0, 0, self.screenWidth, self.screenHeight,
                           backgroundPixmap)
        painter.drawImage(self.platformImage.xPos, self.platformImage.yPos,
                          self.platformImage.platformPic)
        painter.end()
        self.backgroundImage = backgroundCanvas.toImage()

        self.StormEagle = SpriteObject.StormEagle
        self.StormEagleSprites = SpriteObject.StormEagleFly
        self.StormEagle.currentState = State.decendingIntro
        self.StormEagle.posX = 450
        self.StormEagle.posY = 0

        self.Megaman = SpriteObject.Megaman
        self.Megaman.currentState = State.stand
        self.MegamanSprite = SpriteObject.MegamanStand
        self.Megaman.posX = round(self.screenWidth / 2)
        self.Megaman.posY = self.platformImage.yPos - self.MegamanSprite.array[
            self.Megaman.frameIndex].bottom + self.MegamanSprite.array[
                self.Megaman.frameIndex].centerY
        self.megamanCollisionIsOn = True

        self.StormProjectile = []
        self.StormProjectileSprite = SpriteObject.StormCannonProjectile

        self.GustProjectile = []
        self.GustProjectileSprite = SpriteObject.GustProjectile

        self.EggBombProjectile = []
        self.EggBombProjectileSprite = []

        self.gravitation = 50

        self.counterForRespawn = 0

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateScreen)
        self.timer.start(100)
 def generate_platform(self, index, score):
     if (score < MAX_JUMP * MAX_JUMP):
         change = int(math.sqrt(score))
     else:
         change = MAX_JUMP - 1
     width = 200 - randrange(change, change + 60)
     height = 20
     y = 600 - index * 100
     while True:
         side = bool(getrandbits(1))
         if side:
             x = randrange(self.last_x - MAX_JUMP, self.last_x - change)
         else:
             x = randrange(self.last_x + width + change,
                           self.last_x + MAX_JUMP + width)
         if x >= 0 and x <= SCREEN_WIDTH - width:
             break
     self.last_x = x
     return Platform(x, y, width, height)
Ejemplo n.º 7
0
	def generate_platform(self, index, score):
		"""Generuje platformy"""
		if(score < MAX_JUMP*MAX_JUMP):
			change = int(math.sqrt(score))
		else:
			change = MAX_JUMP-1
		width = 200 - randrange(change, change+60) #długość platformy
		height = 20 #wysokość
		y = 600 - index * 100
		while True:
			side = bool(getrandbits(1))  # losowe 0, 1, współgra z randrange()
			if side:
				x = randrange(self.last_x-MAX_JUMP , self.last_x-change)
			else:
				x = randrange(self.last_x+width+change , self.last_x+MAX_JUMP+width)
			if x >= 0 and x <= SCREEN_WIDTH - width:
				break
		self.last_x = x
		return Platform(x, y, width, height) #tworzenie platformy
Ejemplo n.º 8
0
Archivo: Main.py Proyecto: croulan/Myx
def main():
    platform = Platform()
    recipe = Recipe() 
    
    # Step 0: Preform hard reset to calibrate platform position during startup
    #platform.hard_Reset()   

    # Step 1: get recipe from user either from onboard gui or android app
    #sampleRecipe = sys.argv[1]
    sampleRecipe = "1,19.3,2,19.3,3,19.3,4,19.3,5,19.3,6,19.3,7,19.3,8,19.3,true" 

    # Step 2: split recipe string to a stack of seperate ingredients
    recipe.initilize_Stack(sampleRecipe)

    # Step 3: specify the order of the recipe
    if recipe.isOrdered == True:
        recipeOrder = recipe.recipeStack 
    else: 
        recipeOrder = platform.get_Shortest_Path(recipe)
    
    hbridge.turnOff()
    time.sleep(.3)
    # Step 4: interate over each ingredient then move platform
    for ingred in recipeOrder: 
        print "Getting %rmL of segment %r" %(ingred.mL, ingred.segNum)

        #segNum is NOT 0 indexed
        platform.move_To_Segment(platform.segList[ingred.segNum-1].name) 
        time.sleep(WAIT) 

        # Step 5: once platform reached its mark, pour amount
        
        hbridge.turnOn()
        time.sleep(.2)
        Actuator.actuate(Actuator.actDict[ingred.segNum-1], float(ingred.mL))
        hbridge.turnOff()
        time.sleep(WAIT) 



    # Step 6: repeat step 4 till stack is empty

    # Step 7: Move platform back to the middle
    print "Final offset: %r " % Platform.offset
    platform.reset()
Ejemplo n.º 9
0
def main(argv):
    help_string = "Compiler.py -f <win32 | elf32 | elf64> -O <0 | 1 | 2> -o <output file> input_file"

    platform = Platform.elf32
    input_file = ''
    output_file = ''
    optimization = 0

    asm_file = ''
    obj_file = ''

    try:
        opts, args = getopt.getopt(argv, "hf:o:O:")
        for opt, arg in opts:
            if opt == '-h':
                print(help_string)
                sys.exit()
            elif opt == "-f":
                platform = Platform.by_name(arg)
            elif opt == "-o":
                output_file = arg
            elif opt == "-O":
                optimization = int(arg)

        input_file = args[0]
        asm_file = os.path.splitext(input_file)[0] + ".asm"
        obj_file = os.path.splitext(input_file)[0] + (".obj" if platform == Platform.win32 else ".o")
        if output_file == '':
            output_file = os.path.splitext(input_file)[0] + "." + platform.output_file_extension()
    except getopt.GetoptError:
        print(help_string)
        sys.exit(2)

    try:
        run_compile(platform, input_file, asm_file, optimization)
        link_executable_file(platform, asm_file, obj_file, output_file)
    except SyntaxError as e:
        print("Syntax error:", e.msg, file=sys.stderr)
    except ValueError as e:
        print("Value error:", e, file=sys.stderr)
    except NameError as e:
        print("Name error:", e, file=sys.stderr)
Ejemplo n.º 10
0
    def __init__(self, main_instance):
        AbstractRole.__init__(self, main_instance)
        self.dialog = Dialog(self)
        Logger._instance.close()
        self.sessions = {}
        self.locked_sessions = []
        self.sessions_spooler = MPQueue.Queue()
        self.sessions_spooler2 = MPQueue.Queue()
        self.sessions_sync = MPQueue.Queue()
        self.logging_queue = MPQueue.Queue()

        self.manager = Manager(self.main_instance.smRequestManager)
        self.threads = []

        self.applications = {}
        self.applications_id_SM = {}
        self.applications_mutex = threading.Lock()

        self.has_run = False

        self.static_apps = RolePlatform.ApplicationsStatic(
            self.main_instance.smRequestManager)
        self.static_apps_must_synced = False
        self.static_apps_lock = threading.Lock()
Ejemplo n.º 11
0
	def req_icon(self, app_id):
		if self.role_instance.applications is None:
			return self.req_unauthorized()
		
		self.role_instance.applications_mutex.acquire()
		
		if not self.role_instance.applications_id_SM.has_key(app_id):
			self.role_instance.applications_mutex.release()
			return self.req_unauthorized()
		
		app =  self.role_instance.applications_id_SM[app_id]
		
		self.role_instance.applications_mutex.release()

		appsdetect = Platform.ApplicationsDetection()
		data = appsdetect.getIcon(app["filename"])
		if data is None:
			return self.req_not_found()
		
		response = {}
		response["code"] = httplib.OK
		response["Content-Type"] = "image/png"
		response["data"] = data
		return response
Ejemplo n.º 12
0
def draw_ground(difficulty):

    platform_y = [490, 520, 550]
    prev_generated = False

    if difficulty == "easy":
        spawn_rate = 0.2
    elif difficulty == "medium":
        spawn_rate = 0.3
    elif difficulty == "hard":
        spawn_rate = 0.5

    for i in range(0, 65000, 128):
        if (rand.random() > spawn_rate or i <= 512):
            ground = Platform(i, screen_height - 128)
            platforms.add(ground)
            game_objects.add(ground)
            sprites.add(ground)
            prev_generated = True
        else:
            if not(prev_generated):
                draw_platform(rand.choice([i, i - 128]), rand.randrange(1, 2), rand.choice(platform_y))
            prev_generated = False
    return spawn_rate
Ejemplo n.º 13
0
def gameloop():
    platform = Platform(colorrandom, 330, 550, 150, 30, 800)
    ball = Ball(WHITE, random_start_pos, 500, 15, 15)
    blocks = BlockHandler()
    score = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit(0)

        platform.update()
        ball.update()

        window.fill((0x00, ) * 3)

        window.blit(score_caption, (0, 0))
        ball.show(window)
        platform.show(window)
        for i in range(len(blocks.blocks)):
            blocks.blocks[i].show(window)

        collisionIndex = ball.rect.collidelist(blocks.blocks)
        if collisionIndex != -1:
            ball.reverseY()
            blocks.blocks.pop(collisionIndex)
            score += 1
        if ball.lives <= 0:
            return True
        if len(blocks.blocks) == 0:
            return False

        score_render = font.render(str(score), True, WHITE)
        window.blit(score_render, (100, 0))
        pygame.display.update()
        clock.tick(60)
Ejemplo n.º 14
0
	def __init__(self, screen_wdith, screen_height) :		
		# Call the parent constructor.
		super().__init__()

		# The borders of the level.
		self.left_edge = 0
		self.right_edge = 4590
		self.top_edge = -500
		self.bottom_edge = 1000
		# Where the camera stops moving on this level.
		self.shift_left_bound = self.left_edge + (screen_wdith/2)
		self.shift_right_bound = self.right_edge - (screen_wdith/2)
		self.shift_up_bound = self.top_edge + (screen_height/2)
		self.shift_down_bound = self.bottom_edge - (screen_height/2)

		# Where the player starts on this level.
		self.starting_x = 20
		self.starting_y = 212
		self.starting_right = True

		# The portal to the next level.
		self.portal = Portal(4480, -60)
		self.portal_list.add(self.portal)

		# Music for this level.
		self.music = "Assets/Music/Level_1.mp3"		
		
		# 2D array, containing the x and y coordinates and type for each platform.
		platforms = [
			[0, 288, 0],
			[70, 288, 1],
			[140, 288, 1],
			[210, 288, 1],
			[280, 288, 1],
			[350, 288, 1],
			[420, 288, 1],
			[490, 288, 1],
			[560, 288, 1],
			[630, 288, 1],
			[700, 288, 1],
			[770, 288, 2],

			[980, 168, 0],
			[1050, 168, 2],

			[1340, 168, 0],
			[1410, 168, 2],

			[1650, 168, 0],
			[1720, 168, 1],
			[1790, 168, 1],
			[1860, 168, 1],
			[1930, 168, 1],
			[2000, 168, 1],
			[2070, 168, 1],
			[2140, 168, 2],

			[2470, 330, 0],
			[2540, 330, 2],

			[2770, 350, 0],
			[2840, 350, 1],
			[2910, 350, 1],
			[2980, 350, 1],
			[3050, 350, 1],
			[3120, 350, 1],
			[3190, 350, 2],

			[3400, 230, 0],
			[3470, 230, 2],

			[3680, 110, 0],
			[3750, 110, 1],
			[3820, 110, 1],
			[3890, 110, 1],
			[3960, 110, 1],
			[4030, 110, 1],
			[4100, 110, 1],
			[4170, 110, 1],
			[4240, 110, 1],
			[4310, 110, 1],
			[4380, 110, 1],
			[4450, 110, 1],
			[4520, 110, 2]
			]

		# Go through the array above and create the platforms.
		for temp in platforms:
			platform = Platform(temp[0], temp[1], temp[2])
			self.platform_list.add(platform)

		# A 2D array containing the min-x, max-x, and y coordinates and color of each enemy.
		enemies = [
			[1650, 2210, 138, True],
			[2770, 3260, 320, False],
			[3680, 4310, 80, True],
			]

		# Go through the array above and create the enemies.
		for temp in enemies :
			enemy = Enemy(temp[0], temp[1], temp[2], temp[3])
			self.enemy_list.add(enemy)
Ejemplo n.º 15
0
class Simulator:
    OFFSET = 10
    DEBUGSCREENSIZE = (350, 200)
    MASS = 1
    MOMENT = 500

    def __init__(self, ai_type, fullscreen):

        self.ai_type = ai_type
        # Screen
        self.running = True
        self.screen = Screen(fullscreen)

        self.width, self.height = pygame.display.Info(
        ).current_w, pygame.display.Info().current_h
        self.startPoistion = (self.width / 2, self.height / 2)
        # FpsController
        self.fpsController = FpsController()
        self.fpsCounter = 0
        self.setFps(60)
        # Physics
        self.physics = Physics()
        # Drone
        self.drone = self.createDrone()
        self.camera = Camera(self.drone.body.position)
        # Platform
        self.platform = Platform()
        # Add element to space
        self.physics.addToSpace(self.platform.getShapes())
        self.physics.addToSpace(self.drone.getShapes())

        # Create Debug Screen
        DebugScreen.getInstance().setSize(self.DEBUGSCREENSIZE)
        DebugScreen.getInstance().setPosition(
            (self.width - self.DEBUGSCREENSIZE[0] - 10, 10))

    def createDrone(self) -> Drone:

        if self.ai_type == AIType.fuzzyLogic:
            return Drone(self.MASS, self.MOMENT, self.physics.getGravity(),
                         self.startPoistion, FuzzyLogicAI())
        elif self.ai_type == AIType.neuronNetwork:
            return Drone(self.MASS, self.MOMENT, self.physics.getGravity(),
                         self.startPoistion, NeuralNetworkAI())
        elif self.ai_type == AIType.simpleAI:
            return Drone(self.MASS, self.MOMENT, self.physics.getGravity(),
                         self.startPoistion, SimpleAI())
        elif self.ai_type == AIType.manualAI:
            return Drone(self.MASS, self.MOMENT, self.physics.getGravity(),
                         self.startPoistion, ManualAI())
        raise RuntimeError("Invalid ai type")

    def setFps(self, numberOfFps):
        # Example of changes fps, default 60
        self.fpsController.setFps(numberOfFps)

    def checkEvents(self):

        for event in pygame.event.get():

            if event.type == QUIT or event.type == KEYDOWN and (
                    event.key in [K_ESCAPE, K_q]):
                self.running = False

            elif event.type == KEYDOWN and event.key == K_r:

                # Remove all Drone elements from the screen
                self.physics.removeObject(self.drone.getShapes())
                # Create new Drone and add to space
                self.drone = self.createDrone()
                self.physics.addToSpace(self.drone.getShapes())

        keys = pygame.key.get_pressed()

        # Engines take values ​​of <0, 1>
        # For physics testing they were introduced permanently

        leftPower = 0.0
        rightPower = 0.0

        if keys[K_UP]:
            leftPower += 0.2
            rightPower += 0.2

        self.drone.leftEngine.setForce(leftPower)
        self.drone.rightEngine.setForce(rightPower)

    def startSimulation(self):

        # Each iteration of this loop will last (at least) 1/(number of FPS | default 60) of a second.
        while self.running:
            self.checkEvents()

            self.drone.update()
            self.camera.update(self.drone.body.position)
            self.draw()
            self.physics.updatePhysics()
            self.fpsController.waitForReady()
            self.fpsController.nextFrame()

    def draw(self):
        self.screen.clear()

        DebugScreen.getInstance().addInfo(
            "x", "{:.2f}".format(self.drone.body.position.x))
        DebugScreen.getInstance().addInfo(
            "y", "{:.2f}".format(self.drone.body.position.y))

        # Set screen offset based on camera position
        self.screen.setOffset(self.camera.getPosition())

        # self.screen.drawPhysics(self.physics.space)
        self.platform.draw(self.screen)
        self.drone.draw(self.screen)

        DebugScreen.getInstance().draw(self.screen)

        self.screen.show()
  def my_constructor(
      self
    , NET_TRANS_NODE
    , SCENEGRAPH
    , PLATFORM_SIZE
    , SCALE
    , STARTING_MATRIX
    , NAVIGATION_LIST
    , INPUT_SENSOR_TYPE
    , INPUT_SENSOR_NAME
    , NO_TRACKING_MAT
    , GF_SETTINGS
    , ANIMATE_COUPLING
    , MOVEMENT_TRACES
    , INVERT
    , SLOT_MANAGER
    , TRANSMITTER_OFFSET
    , DISPLAYS
    , AVATAR_TYPE
    , CONFIG_FILE
    , TRACKING_TARGET_NAME = None
    ):
    
    ## @var SCENEGRAPH
    # Reference to the scenegraph.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var NET_TRANS_NODE
    # Reference to the net matrix node in the scenegraph for distribution.
    self.NET_TRANS_NODE = NET_TRANS_NODE

    ## @var coupled_navigations
    # List of coupled Navigation instances to which this Navigation's changes are forwarded to.
    self.coupled_navigations = []

    ## @var input_sensor_type
    # String indicating the type of input device to be created, e.g. "XBoxController" or "OldSpheron"
    self.input_sensor_type = INPUT_SENSOR_TYPE

    ## @var input_sensor_name
    # Name of the input device sensor as chosen in daemon.
    self.input_sensor_name = INPUT_SENSOR_NAME

    if self.input_sensor_name == None:
      self.input_sensor_name = "keyboard"

    ## @var start_matrix
    # Initial position matrix of the platform.
    self.start_matrix = STARTING_MATRIX
    
    # create device
    ## @var device
    # Device instance handling relative inputs of physical device.
    if self.input_sensor_type == "OldSpheron":
      self.device = OldSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "NewSpheron":
      self.device = NewSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "XBoxController":
      self.device = XBoxDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "KeyboardMouse":
      self.device = KeyboardMouseDevice()
      self.device.my_constructor(NO_TRACKING_MAT)
    elif self.input_sensor_type == "Spacemouse":
      self.device = SpacemouseDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "Globefish":
      self.device = GlobefishDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, NO_TRACKING_MAT)


    # init field connections
    self.sf_reset_trigger.connect_from(self.device.sf_reset_trigger)
    self.sf_coupling_trigger.connect_from(self.device.sf_coupling_trigger)
    self.sf_dof_trigger.connect_from(self.device.sf_dof_trigger)
    
    # create ground following
    ## @var groundfollowing
    # GroundFollowing instance to correct the absolute matrices with respect to gravity.
    self.groundfollowing = GroundFollowing()
    self.groundfollowing.my_constructor(self.SCENEGRAPH, self.device.sf_station_mat, float(GF_SETTINGS[1]))

    # create input mapping
    ## @var inputmapping
    # InputMapping instance to process and map relative device inputs to an absolute matrix.
    self.inputmapping = InputMapping()
    self.inputmapping.my_constructor(self, self.device, self.groundfollowing, STARTING_MATRIX, INVERT)
    self.inputmapping.set_input_factors(self.device.translation_factor, self.device.rotation_factor)
    self.inputmapping.sf_scale.value = SCALE

    # activate correct input mapping mode according to configuration file
    if GF_SETTINGS[0]:
      self.inputmapping.activate_realistic_mode()
    else:
      self.inputmapping.deactivate_realistic_mode()

    # create platform
    ## @var platform
    # Platform instance that is controlled by the Device.
    self.platform = Platform()
    self.platform.my_constructor(
        NET_TRANS_NODE = self.NET_TRANS_NODE
      , SCENEGRAPH = self.SCENEGRAPH
      , PLATFORM_SIZE = PLATFORM_SIZE
      , INPUT_MAPPING_INSTANCE = self.inputmapping
      , PLATFORM_ID = len(NAVIGATION_LIST)
      , TRANSMITTER_OFFSET = TRANSMITTER_OFFSET
      , NO_TRACKING_MAT = NO_TRACKING_MAT
      , DISPLAYS = DISPLAYS
      , AVATAR_TYPE = AVATAR_TYPE
      , SLOT_MANAGER = SLOT_MANAGER
      , CONFIG_FILE = CONFIG_FILE
      , AVATAR_MATERIAL = self.trace_material
      )

    # create device avatar
    if AVATAR_TYPE != "None":
      self.device.create_device_avatar(self.platform.platform_scale_transform_node
                                     , self.platform.platform_id)

    ## @var NAVIGATION_LIST
    # Reference to a list containing all Navigation instances in the setup.
    self.NAVIGATION_LIST = NAVIGATION_LIST

    # attributes
    ## @var in_dofchange_animation
    # Boolean variable to indicate if a movement animation for a DOF change (realistic/unrealistic) is in progress.
    self.in_dofchange_animation = False

    ## @var in_coupling_animation
    # Boolean variable to indicate if a movement animation for coupling is in progress.
    self.in_coupling_animation = False

    ## @var timer
    # Instance of TimeSensor to handle the duration of animations.
    self.timer = avango.nodes.TimeSensor()

    ## @var ANIMATE_COUPLING
    # Boolean indicating if an animation should be done when a coupling of navigations is initiated.
    self.ANIMATE_COUPLING = ANIMATE_COUPLING

    ## @var movement_traces
    # Boolean indicating if the movement traces are currently visualized by line segments.
    self.movement_traces = MOVEMENT_TRACES

    ## @var movement_traces_activated
    # Boolean indicating if the movement traces are generally activated.
    self.movement_traces_activated = self.movement_traces

    ## @var trace
    # The trace class that handles the line segment updating.
    self.trace = None

    if self.movement_traces:
      # create trace and add 'Shadeless' to material string to have a nicer line apperance
      ## @var trace
      # Instance of Trace class to handle trace drawing of this navigation's movements.
      self.trace = TraceLines.Trace(self.NET_TRANS_NODE, self.platform.platform_id, 500, 20.0, STARTING_MATRIX, self.trace_material + 'Shadeless')    

    # evaluate every frame
    self.always_evaluate(True)
Ejemplo n.º 17
0
  def my_constructor(self, SCENEGRAPH, PLATFORM_SIZE, STARTING_MATRIX, NAVIGATION_LIST, INPUT_SENSOR_TYPE, INPUT_SENSOR_NAME, NO_TRACKING_MAT, GF_SETTINGS, ANIMATE_COUPLING, MOVEMENT_TRACES, TRACKING_TARGET_NAME = None):
    
    ## @var SCENEGRAPH
    # Reference to the scenegraph.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var coupled_navigations
    # List of coupled Navigation instances to which this Navigation's changes are forwarded to.
    self.coupled_navigations = []

    ## @var input_sensor_type
    # String indicating the type of input device to be created, e.g. "XBoxController" or "Spheron"
    self.input_sensor_type = INPUT_SENSOR_TYPE

    ## @var start_matrix
    # Initial position matrix of the platform.
    self.start_matrix = STARTING_MATRIX
    
    # create device
    ## @var device
    # Device instance handling relative inputs of physical device.
    if self.input_sensor_type == "Spheron":
      self.device = OldSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "XBoxController":
      self.device = XBoxDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "KeyboardMouse":
      self.device = KeyboardMouseDevice()
      self.device.my_constructor()
    elif self.input_sensor_type == "Spacemouse":
      self.device = SpacemouseDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME)
    
    # create ground following
    ## @var groundfollowing
    # GroundFollowing instance to correct the absolute matrices with respect to gravity.
    self.groundfollowing = GroundFollowing()
    self.groundfollowing.my_constructor(self.SCENEGRAPH, self.device.sf_station_mat, GF_SETTINGS)

    # create input mapping
    ## @var inputmapping
    # InputMapping instance to process and map relative device inputs to an absolute matrix.
    self.inputmapping = InputMapping()
    self.inputmapping.my_constructor(self, self.device, self.groundfollowing, STARTING_MATRIX)
    self.inputmapping.set_input_factors(self.device.translation_factor, self.device.rotation_factor)
    
    # create platform
    ## @var platform
    # Platform instance that is controlled by the Device.
    self.platform = Platform()
    self.platform.my_constructor(self.SCENEGRAPH, PLATFORM_SIZE, self.inputmapping, len(NAVIGATION_LIST))

    ## @var NAVIGATION_LIST
    # Reference to a list containing all Navigation instances in the setup.
    self.NAVIGATION_LIST = NAVIGATION_LIST

    # attributes
    ## @var in_dofchange_animation
    # Boolean variable to indicate if a movement animation for a DOF change (realistic/unrealistic) is in progress.
    self.in_dofchange_animation = False

    ## @var frames_since_last_dofchange
    # Framecount to make realistic/unrealistic switch on one button. Switching again is possible after x frames.
    self.frames_since_last_dofchange = 0

    ## @var frames_since_last_coupling
    # Framecount since the last coupling / decoupling operation was done. Used to make functionality on one button.
    self.frames_since_last_coupling = 0

    ## @var in_coupling_animation
    # Boolean variable to indicate if a movement animation for coupling is in progress.
    self.in_coupling_animation = False

    ## @var timer
    # Instance of TimeSensor to handle the duration of animations.
    self.timer = avango.nodes.TimeSensor()

    ## @var ANIMATE_COUPLING
    # Boolean indicating if an animation should be done when a coupling of navigations is initiated.
    self.ANIMATE_COUPLING = ANIMATE_COUPLING

    ## @var movement_traces
    # Boolean indicating if the movement traces should be visualized by line segments.
    self.movement_traces = MOVEMENT_TRACES

    ## @var trace
    # The trace class that handles the line segment updating.
    self.trace = None
      

    # evaluate every frame
    self.always_evaluate(True)
Ejemplo n.º 18
0
    def loadLevel(self):
        levelFile = open(self.fileName, "r")
        jsonString = levelFile.read()
        parsedJson = json.loads(jsonString)

        player = None
        for instance in parsedJson["Level"]:
            for item in instance:
                if item == "Name" and instance[item] == "Player":
                    y = instance["Y"]
                    x = instance["X"]
                    angle = instance["Angle"]
                    player = Player(self.world, x, y, cursor=self.cursor)
                    player.rotation = angle
                    player.stableRotation = angle
                    self.world.addEntity(player)
        for instance in parsedJson["Level"]:
            for item in instance:
                if item == "Room":
                    self.world.roomHeight = instance[item]["Height"]
                    self.world.roomWidth = instance[item]["Width"]
                    
                if item == "Name":
                    y = instance["Y"]
                    x = instance["X"]
                    angle = instance["Angle"]
                    if instance[item] == "Satellite Platform":
                        imageIndex = instance["Image Index"]
                        
                        platform = Platform(self.world, x, y, player=player)
                        platform.frame = imageIndex
                        self.levelObjects.append(platform)
                        
                    elif instance[item] == "Spikes":
                        imageIndex = instance["Image Index"]
                        
                        sprite = None
                        if imageIndex == 0:
                            sprite = self.world.assetLoader.smallSpikes
                        elif imageIndex == 2:
                            sprite = self.world.assetLoader.bigSpikes
                        spike = Spike(self.world, x, y, sprite=sprite, player=player)
                        self.levelObjects.append(spike)
                        
                    elif instance[item] == "Checkpoint":
                        
                        checkpoint = Checkpoint(self.world, x, y, player=player)
                        self.levelObjects.append(checkpoint)
                        
                    elif instance[item] == "Pull Orb":
                        
                        pass
                        pullOrb = PullOrb(self.world, x, y, player=player, cursor=self.cursor)
                        self.levelObjects.append(pullOrb)
                              
                    elif instance[item] == "Attract Tether":
                        
                        pass
                        pullOrbTether = PullOrbTether(self.world, x, y, player=player)
                        self.levelObjects.append(pullOrbTether)
                              
                    elif instance[item] == "End Rocket":
                        
                        rocket = Rocket(self.world, x, y, player=player)
                        self.levelObjects.append(rocket)
                              
                    elif instance[item] == "Earth":
                        pass
                              
                    elif instance[item] == "Bouncy":
                        
                        bouncy = Bouncy(self.world, x, y, player=player)
                        self.levelObjects.append(bouncy)
                    
                    elif instance[item] == "Repel Orb":
                        
                        repelOrb = RepelOrb(self.world, x, y, player=player, cursor=self.cursor)
                        self.levelObjects.append(repelOrb)
                        
        return self.levelObjects
Ejemplo n.º 19
0
 def setUp(self):
     self.slug = 'na'
     self.platform = Platform(self.slug)
 def __get_stored_platforms(self):
     return [Platform.from_dict({"name": "1"})]
Ejemplo n.º 21
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "huajiao"
     self.cache_key = cache_key()
     self.live_type = ""
     pass
Ejemplo n.º 22
0
    if args.debug:
        l = logging.DEBUG
    if args.quiet:
        l = logging.CRITICAL

    if args.output:
        logging.basicConfig(filename=args.output, level=l)
    else:
        logging.basicConfig(stream=stderr, level=l)

    time_period = None
    minutes = 1  # DEFAULT - USE MINUTE BARS
    if args.timeframe:
        try:
            minutes = int(args.timeframe)
        except:
            logging.critical(
                "Please enter an integer for minutes. Exiting....")
            exit()
        if minutes < 1 or minutes > 1440:
            logging.critical(
                "Please enter a number of minutes between 1 and 1440. Exiting...."
            )
            exit()

    core = Core()
    brain = Brain(core)

    platform = Platform(core, brain, minutes)
    platform.run()
Ejemplo n.º 23
0
blue = (0,0, 255)
white = (255,255,255)

def reinit():
	global player
	global platform_controller
	global floor
	global camera
	player = Player()
	platform_controller = PlatformController()
	floor = Platform(0, SCREEN_HEIGHT-36, SCREEN_WIDTH, 36)
	camera = Camera(player)

player = Player()
platform_controller = PlatformController()
floor = Platform(0, SCREEN_HEIGHT-36, SCREEN_WIDTH, 36)

arrow_image = load_image("arrow.png")
selected_option = 0.30

background = load_image('background.jpg')

camera = Camera(player)

game_state = 'Menu'

game_loop = True
clock = pygame.time.Clock()
fps = 60

while game_loop:
Ejemplo n.º 24
0
    global floor
    global camera
    global prev_pos
    players = []
    for i in range(num_players):
        players.append(Player())
    platform_controller = PlatformController()
    floor = Platform(0, SCREEN_HEIGHT - 36, SCREEN_WIDTH, 36, 0)
    camera = Camera(players[0])


players = []
for i in range(num_players):
    players.append(Player())
platform_controller = PlatformController()
floor = Platform(0, SCREEN_HEIGHT - 36, SCREEN_WIDTH, 36, 0)

arrow_image = load_image(resource_path("arrow.png"))
selected_option = 0.30

background = load_image(resource_path('background.jpg'))

camera = Camera(players[0])

game_state = 'Menu'

game_loop = True
clock = pygame.time.Clock()
fps = 600
# play_mode = "Single"
play_mode = "Bot"
Ejemplo n.º 25
0
def main():
    import pygame
    from TitleScreen import TitleScreen
    from Platform import Platform
    from Player import Player
    import time
    import sys

    pygame.init()
    size = (1050, 650)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Epic Smash Siblings Omega")
    clock = pygame.time.Clock()

    # Colours
    black = (0, 0, 0)
    white = (255, 255, 255)
    green = (0, 255, 0)
    red = (255, 0, 0)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    purple = (255, 0, 255)

    # Vars
    done = False

    def character_select(ID):
        p1_choose = TitleScreen(74, screen, 250, 100,
                                "Player 1 Choose Colour.")
        p2_choose = TitleScreen(74, screen, 250, 100, "Player 2 Choose Colour")

        r = 255
        g = 0
        b = 0
        RGB = (r, g, b)
        colour_rects = [
            pygame.Rect(400, 200, 20, 20),
            pygame.Rect(450, 200, 20, 20),
            pygame.Rect(500, 200, 20, 20),
            pygame.Rect(550, 200, 20, 20),
            pygame.Rect(600, 200, 20, 20),
            pygame.Rect(500, 240, 20, 20)
        ]
        colour_list = [red, blue, green, yellow, purple, RGB]
        done = False
        while not done:
            if r > 0 and b == 0:
                r -= 5
                g += 5
                colour_list[5] = (r, g, b)
            elif g > 0 and r == 0:
                g -= 5
                b += 5
                colour_list[5] = (r, g, b)
            elif b > 0 and g == 0:
                r += 5
                b -= 5
                colour_list[5] = (r, g, b)
            if ID == 0:
                p1_choose.drawText()
            else:
                screen.blit(title_image, (0, 0))
                p2_choose.drawText()
            pygame.draw.rect(screen, black, (390, 190, 240, 40))
            pygame.draw.rect(screen, black, (490, 230, 40, 40))
            for i in range(len(colour_rects)):
                if colour_rects[i].width == 40:
                    pygame.draw.rect(screen, colour_list[i],
                                     colour_rects[i].move(-10, -10))
                else:
                    pygame.draw.rect(screen, colour_list[i], colour_rects[i])

            pygame.display.update()
            m_pos = pygame.mouse.get_pos()
            for colour in colour_rects:
                if pygame.Rect(colour).collidepoint(m_pos[0], m_pos[1]):
                    colour.width = 40
                    colour.height = 40
                else:
                    colour.width = 20
                    colour.height = 20

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if ID == 0:
                        if pygame.Rect(colour_rects[0]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].colour = red
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[1]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].colour = blue
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[2]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].colour = green
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[3]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].colour = yellow
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[4]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].colour = purple
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[5]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[0].is_RGB = True
                            click_sound.play()
                            return
                    elif ID == 1:
                        if pygame.Rect(colour_rects[0]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].colour = red
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[1]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].colour = blue
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[2]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].colour = green
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[3]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].colour = yellow
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[4]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].colour = purple
                            click_sound.play()
                            return
                        elif pygame.Rect(colour_rects[5]).collidepoint(
                                m_pos[0], m_pos[1]):
                            players[1].is_RGB = True
                            click_sound.play()
                            return

    def restart():
        player_1_wins = TitleScreen(74, screen, 350, 250, "Player 1 Wins!")
        player_2_wins = TitleScreen(74, screen, 350, 250, "Player 2 Wins!")
        player_1_wins.colour = (255, 0, 0)
        player_2_wins.colour = (255, 0, 0)
        screen.blit(git_gud, (0, 0))

        if players[1].stock_remaining == 0:
            player_1_wins.drawText()
        elif players[0].stock_remaining == 0:
            player_2_wins.drawText()
        pygame.display.update()
        time.sleep(2)
        while True:
            pygame.init()
            screen.blit(git_gud, (0, 0))
            restart_text = TitleScreen(74, screen, 350, 250, "Play again? Y/N")
            restart_text.drawText()
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_y:
                        main()
                    elif event.key == pygame.K_n:
                        sys.exit()

    # Platforms
    platforms = [
        Platform(screen, black, 275, 450, 500, 40),
        Platform(screen, black, 325, 350, 125, 10),
        Platform(screen, black, 465, 250, 125, 10),
        Platform(screen, black, 600, 350, 125, 10)
    ]

    # Main background image
    background_image = pygame.image.load('main_background.jpeg').convert()

    # Players
    players = [
        Player(screen, red, 300, 400, 20, 40, platforms, 0),
        Player(screen, green, 725, 400, 20, 40, platforms, 1)
    ]
    player_1_text = TitleScreen(24, screen, 160, 600, "Player 1's stock:")
    player_2_text = TitleScreen(24, screen, 460, 600, "Player 2's stock:")
    player_1_health = TitleScreen(24, screen, 160, 550, "Player 1's Health:")
    player_2_health = TitleScreen(24, screen, 460, 550, "Player 2's Health:")
    player_info = [
        player_1_text, player_1_health, player_2_text, player_2_health
    ]

    # Title screen
    click_sound = pygame.mixer.Sound("select_noise.wav")
    pygame.mixer.music.load('title_screen_theme.wav')
    pygame.mixer.music.play(-1, 0.0)
    title_image = pygame.image.load('smash_cover.jpg').convert()
    title_image.set_colorkey(white)
    play_button = TitleScreen(48, screen, 350, 575, "Press any key to play!")
    play_button.colour = black
    git_gud = pygame.image.load('git gud.png').convert()

    screen.fill(white)
    screen.blit(title_image, (0, 0))
    pygame.display.update()
    character_select(0)
    character_select(1)
    play_button.drawText()
    pygame.display.update()
    play_button.waitForPlayerToPressKey()
    click_sound.play()

    pygame.mixer.music.stop()
    pygame.mixer.music.load('playing_theme.wav')
    pygame.mixer.music.play(-1, 0.0)

    # -------- Main Program Loop -----------
    while not done:
        # --- Main event loop
        # --- All events are detected here
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    players[0].x_speed = -3
                    players[0].direction = "LEFT"
                if event.key == pygame.K_d:
                    players[0].x_speed = 3
                    players[0].direction = "RIGHT"
                if event.key == pygame.K_w:
                    if players[0].jumps_available > 0:
                        players[0].jumping = True
                if event.key == pygame.K_SPACE:
                    players[0].attacking = True
                if event.key == pygame.K_LEFT:
                    players[1].x_speed = -3
                    players[1].direction = "LEFT"
                if event.key == pygame.K_RIGHT:
                    players[1].x_speed = 3
                    players[1].direction = "RIGHT"
                if event.key == pygame.K_UP:
                    if players[1].jumps_available > 0:
                        players[1].jumping = True
                if event.key == pygame.K_KP_ENTER:
                    players[1].attacking = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    players[0].x_speed = 0
                if event.key == pygame.K_d:
                    players[0].x_speed = 0
                if event.key == pygame.K_SPACE:
                    players[0].attacking = False
                if event.key == pygame.K_LEFT:
                    players[1].x_speed = 0
                if event.key == pygame.K_RIGHT:
                    players[1].x_speed = 0
                if event.key == pygame.K_KP_ENTER:
                    players[1].attacking = False

        # --- Game logic should go here

        for player in players:
            player.Move()

            if player == players[0]:
                player.die(300)
            else:
                player.die(725)

            if player.stock_remaining == 0:
                done = True

        # --- Screen-clearing code goes here
        screen.fill(white)

        # --- Drawing code should go here
        # Background
        screen.blit(background_image, (0, 0))
        # Platforms
        for platform in platforms:
            platform.draw_platform()

        # Players
        for player in players:
            player.draw()
            player.attack(players)
        # Stocks
        for text in player_info:
            text.drawText()
        players[0].draw_health_bar(300)
        players[1].draw_health_bar(600)
        for player in players:
            for i in range(player.stock_remaining):
                if player == players[0]:
                    pygame.draw.rect(screen, player.colour,
                                     (300 + (30 * i), 600, 20, 20))
                else:
                    pygame.draw.rect(screen, player.colour,
                                     (600 + (30 * i), 600, 20, 20))

        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

        # --- Limit to 60 frames per second
        clock.tick(60)

    # Game over
    restart()
    return
Ejemplo n.º 26
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "douyu"
Ejemplo n.º 27
0
 def test_from_dict_performs_mappings(self):
     d  = {"name": "name",
           "description": "description"}
     result = Platform.from_dict(d)
     self.assertEqual(d["name"], result.name)
     self.assertEqual(d["description"], result.description)
Ejemplo n.º 28
0
 def get_platforms(self):
     """Get a list of platforms
     :returns: A list of type Platform of all stored platforms
     """
     result = self.__db.platforms.find().sort("_Platform__name")
     return list(map(lambda p: Platform.from_mongo_result(p), result))
Ejemplo n.º 29
0
 def test_from_dict_returns_platform(self):
     result = Platform.from_dict({"":""})
     self.assertIsInstance(result, Platform)
Ejemplo n.º 30
0
class TestPlatform(unittest.TestCase):
    def setUp(self):
        self.slug = 'na'
        self.platform = Platform(self.slug)

    def test_count_and_has_url(self):
        self.assertEqual(self.platform.count, 0)
        self.assertFalse(self.platform.has_url())

        self.platform.add_data({'url': match_url_template.format(matchid=1)})
        self.assertEqual(self.platform.count, 1)
        self.assertTrue(self.platform.has_url())

        self.platform.add_data(
            {'url': summoner_url_template.format(name=fake_name)})
        self.assertEqual(self.platform.count, 2)
        self.assertTrue(self.platform.has_url())

        self.platform.add_data({'url': static_champions_url})
        self.assertEqual(self.platform.count, 3)
        self.assertTrue(self.platform.has_url())

        self.platform.get()
        self.assertEqual(self.platform.count, 2)
        self.assertTrue(self.platform.has_url())

        self.platform.get()
        self.assertEqual(self.platform.count, 1)
        self.assertTrue(self.platform.has_url())

        self.platform.get()
        self.assertEqual(self.platform.count, 0)
        self.assertFalse(self.platform.has_url())

    def test_rate_limit_ok(self):
        url = match_url_template.format(matchid=1)
        self.assertTrue(self.platform.rate_limit_ok())
        self.platform.add_data({'url': match_url_template.format(matchid=1)})
        self.platform.handle_response_headers(url, headers)
        self.assertTrue(self.platform.rate_limit_ok())
        new_headers = copy.copy(headers)
        new_headers['X-App-Rate-Limit'] = "1:0.01"
        new_headers['X-App-Rate-Limit-Count'] = "1:0.01"
        new_headers['X-Method-Rate-Limit'] = "5:1"
        new_headers['X-Method-Rate-Limit-Count'] = "1:1"
        self.platform.handle_response_headers(url, new_headers)
        self.assertFalse(self.platform.rate_limit_ok())
        time.sleep(0.01)
        self.assertTrue(self.platform.rate_limit_ok())
        self.platform.get()
        self.assertFalse(self.platform.rate_limit_ok())

    def test_handle_response_headers(self):
        url = match_url_template.format(matchid=1)
        endpoint_str = Endpoint.identify_endpoint(url)
        self.assertRaises(Exception, self.platform.handle_response_headers,
                          (url, headers))
        self.platform.add_data({'url': url})
        self.assertEqual(self.platform.platform_limits, {})
        self.platform.handle_response_headers(url, headers)
        self.assertEqual(len(self.platform.platform_limits), 2)
        self.assertEqual(self.platform.platform_limits["1"].cap, 20)
        self.assertEqual(self.platform.platform_limits["1"].seconds, 1)
        self.assertEqual(self.platform.platform_limits["1"].used, 1)
        self.assertEqual(self.platform.platform_limits["120"].cap, 100)
        self.assertEqual(self.platform.platform_limits["120"].seconds, 120)
        self.assertEqual(self.platform.platform_limits["120"].used, 1)
        self.assertEqual(len(self.platform.limited_endpoints), 1)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["60"].cap,
            270)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["60"].seconds,
            60)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["60"].used, 1)
        new_headers = copy.copy(headers)
        new_headers['X-App-Rate-Limit'] = "1:1"
        new_headers['X-App-Rate-Limit-Count'] = "1:1"
        new_headers['X-Method-Rate-Limit'] = "5:1"
        new_headers['X-Method-Rate-Limit-Count'] = "1:1"
        self.platform.handle_response_headers(url, new_headers)
        self.assertEqual(len(self.platform.platform_limits), 1)
        self.assertEqual(self.platform.platform_limits["1"].cap, 1)
        self.assertEqual(self.platform.platform_limits["1"].seconds, 1)
        self.assertEqual(self.platform.platform_limits["1"].used, 1)
        self.assertEqual(len(self.platform.limited_endpoints), 1)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["1"].cap, 5)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["1"].seconds,
            1)
        self.assertEqual(
            self.platform.limited_endpoints[endpoint_str].limits["1"].used, 1)

    def test_add_data_static_random(self):
        s1 = {'url': static_champions_url}
        s2 = {'url': static_summoner_spells_url}
        s3 = {'url': static_items_url}
        s = [s1, s2, s3]
        self.platform.add_data(s1)
        self.platform.add_data(s2)
        self.platform.add_data(s3)
        self.assertEqual(self.platform.static_count, 3)
        self.assertTrue(self.platform.get() in s)
        self.assertTrue(self.platform.get() in s)
        self.assertTrue(self.platform.get() in s)
        self.assertRaises(Exception, self.platform.get)

    def test_add_data_static_sorted(self):
        c1 = {'url': static_champion_url.format(id=1)}
        c2 = {'url': static_champion_url.format(id=2)}
        c3 = {'url': static_champion_url.format(id=3)}
        self.platform.add_data(c1)
        self.platform.add_data(c2)
        self.platform.add_data(c3)
        self.assertEqual(self.platform.static_count, 3)
        self.assertEqual(self.platform.get(), c1)
        self.assertEqual(self.platform.get(), c2)
        self.assertEqual(self.platform.get(), c3)
        self.assertRaises(Exception, self.platform.get)

    def test_add_data_static_sorted_atFront(self):
        c1 = {'url': static_champion_url.format(id=1)}
        c2 = {'url': static_champion_url.format(id=2)}
        c3 = {'url': static_champion_url.format(id=3)}
        self.platform.add_data(c1, front=True)
        self.platform.add_data(c2, front=True)
        self.platform.add_data(c3, front=True)
        self.assertEqual(self.platform.static_count, 3)
        self.assertEqual(self.platform.get(), c3)
        self.assertEqual(self.platform.get(), c2)
        self.assertEqual(self.platform.get(), c1)
        self.assertRaises(Exception, self.platform.get)

    def test_add_data_limited_alternate(self):
        m1 = {'url': match_url_template.format(matchid=1)}
        m2 = {'url': match_url_template.format(matchid=2)}
        m3 = {'url': match_url_template.format(matchid=3)}
        s1 = {'url': summoner_url_template.format(name=1)}
        s2 = {'url': summoner_url_template.format(name=2)}
        s3 = {'url': summoner_url_template.format(name=3)}
        self.platform.add_data(m1)
        self.platform.add_data(m2)
        self.platform.add_data(m3)
        self.platform.add_data(s1)
        self.platform.add_data(s2)
        self.platform.add_data(s3)
        self.assertEqual(self.platform.limited_count, 6)
        self.assertEqual(self.platform.get(), m1)
        self.assertEqual(self.platform.get(), s1)
        self.assertEqual(self.platform.get(), m2)
        self.assertEqual(self.platform.get(), s2)
        self.assertEqual(self.platform.get(), m3)
        self.assertEqual(self.platform.get(), s3)
        self.assertRaises(Exception, self.platform.get)

    def test_add_data_limited_sorted(self):
        m1 = {'url': match_url_template.format(matchid=1)}
        m2 = {'url': match_url_template.format(matchid=2)}
        m3 = {'url': match_url_template.format(matchid=3)}
        self.platform.add_data(m1)
        self.platform.add_data(m2)
        self.platform.add_data(m3)
        self.assertEqual(self.platform.limited_count, 3)
        self.assertEqual(self.platform.get(), m1)
        self.assertEqual(self.platform.get(), m2)
        self.assertEqual(self.platform.get(), m3)
        self.assertRaises(Exception, self.platform.get)

    def test_add_data_limited_sorted_atFront(self):
        m1 = {'url': match_url_template.format(matchid=1)}
        m2 = {'url': match_url_template.format(matchid=2)}
        m3 = {'url': match_url_template.format(matchid=3)}
        self.platform.add_data(m1, front=True)
        self.platform.add_data(m2, front=True)
        self.platform.add_data(m3, front=True)
        self.assertEqual(self.platform.limited_count, 3)
        self.assertEqual(self.platform.get(), m3)
        self.assertEqual(self.platform.get(), m2)
        self.assertEqual(self.platform.get(), m1)
        self.assertRaises(Exception, self.platform.get)

    def test_available(self):
        self.assertFalse(self.platform.available())
        static_data_1 = {'url': static_items_url}
        limited_data_1 = {'url': match_url_template.format(matchid=100)}
        limited_data_2 = {'url': match_url_template.format(matchid=200)}
        self.platform.add_data(static_data_1)
        self.assertTrue(self.platform.available())
        self.platform.get()
        self.assertFalse(self.platform.available())
        self.platform.add_data(limited_data_1)
        self.assertTrue(self.platform.available())
        self.platform.add_data(limited_data_2)
        self.platform.get()
        self.assertTrue(self.platform.available())  # No response headers yet

        new_headers = copy.copy(headers)
        new_headers['X-Method-Rate-Limit'] = '1:0.1'
        new_headers['X-Method-Rate-Limit-Count'] = '1:0.1'
        self.platform.handle_response_headers(
            match_url_template.format(matchid=100), new_headers, 200)
        self.assertFalse(self.platform.available())
        time.sleep(0.1)
        self.assertTrue(self.platform.available())

    def test_handle_delay(self):
        limited_data_1 = {'url': match_url_template.format(matchid=100)}
        limited_data_2 = {'url': match_url_template.format(matchid=200)}
        self.platform.add_data(limited_data_1)
        self.platform.add_data(limited_data_2)
        self.assertTrue(self.platform.available())
        self.platform.get()
        new_headers = get_date_header()
        new_headers['X-Method-Rate-Limit'] = '2:0.1'
        new_headers['X-Method-Rate-Limit-Count'] = '1:0.1'
        self.platform.handle_response_headers(
            match_url_template.format(matchid=100), new_headers, 429)
        self.assertFalse(
            self.platform.available())  # Should have a default delay
        time.sleep(1)
        self.assertTrue(self.platform.available())

    def test_get_usage(self):
        used = {'static': {}, 'limited': {}}
        self.assertEqual(self.platform.get_usage(), used)
        url = match_url_template.format(matchid=100)
        match_endpoint = Endpoint.identify_endpoint(url)
        used['limited'][match_endpoint] = 'No limits defined'
        self.platform.add_data({'url': url})
        self.assertEqual(self.platform.get_usage(), used)
        self.platform.handle_response_headers(url, headers)
        used['limited'][match_endpoint] = '1:270'
        self.assertEqual(self.platform.get_usage(), used)
        self.platform.get()
        used['limited'][match_endpoint] = '2:270'
        self.assertEqual(self.platform.get_usage(), used)

        # Static tests
        static_endpoint = Endpoint.identify_endpoint(static_champions_url)
        self.platform.add_data({'url': static_champions_url})
        used['static'][static_endpoint] = 'No limits defined'
        self.assertEqual(self.platform.get_usage(), used)
        self.platform.get()
        new_headers = copy.copy(headers)
        new_headers['X-Method-Rate-Limit-Count'] = '1:60,2:120'
        new_headers['X-Method-Rate-Limit'] = '7:60,10:120'
        used['static'][static_endpoint] = '1:7,2:10'
        self.platform.handle_response_headers(static_champions_url,
                                              new_headers)
Ejemplo n.º 31
0
import simpy
import World as w
from Perception import Event as e
from Platform import Platform as plat, PlatformTask as platTask
from matplotlib import pyplot as plt
"""create simulation objects"""
env = simpy.Environment()
simpleWorld = w.World(3, 3, env)
simpleTask = platTask.PlatformTask('A3')
platform1 = plat.Platform('platform 1', env, simpleWorld)
"""1.create world model(s)"""
platform1.WM.createArea(3, 3, 0, 'A')
platform1.WM.createArea(1.5, 1.5, 1, 'A1')
platform1.WM.createArea(1.5, 1.5, 1, 'A2')
platform1.WM.createArea(1.5, 1.5, 1, 'A3')

platform1.WM.containArea('A', 'A1', [-0.75, -0.75])
platform1.WM.containArea('A', 'A2', [-0.75, 0.75])
platform1.WM.containArea('A', 'A3', [0.75, 0.75])

platform1.WM.linkAreas('A1', 'A2')
platform1.WM.linkAreas('A2', 'A3')

platform1.WM.setStartingArea('A1')
simpleWorld.setAreaList(platform1.WM.areaList)
"""2. give tasks"""
platform1.giveTask(simpleTask)
"""3. generate paths"""
"""4. generate plans"""
platform1.plan.addState('start', None, None)
platform1.plan.addState('PS1', 'waiting in', 'A1')
 def __get_suggested_platforms(self):
     return [Platform.from_dict({"name": "1"}), Platform.from_dict({"name": "2"})]
Ejemplo n.º 33
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "panda"
Ejemplo n.º 34
0
class Navigation(avango.script.Script):

  ## Default constructor.
  def __init__(self):
    self.super(Navigation).__init__()

  ## Custom constructor.
  # @param SCENEGRAPH Reference to the scenegraph in which the navigation should take place.
  # @param PLATFORM_SIZE Physical size of the platform in meters. Passed in an two-element list: [width, depth]
  # @param STARTING_MATRIX Initial position matrix of the platform to be created.
  # @param NAVIGATION_LIST List of all navigations in the setup.
  # @param INPUT_SENSOR_TYPE String indicating the type of input device to be created, e.g. "XBoxController" or "Spheron"
  # @param INPUT_SENSOR_NAME Name of the input device sensor as chosen in daemon.
  # @param NO_TRACKING_MAT Matrix which should be applied if no tracking is available.
  # @param GF_SETTINGS Setting list for the GroundFollowing instance: [activated, ray_start_height]
  # @param ANIMATE_COUPLING Boolean indicating if an animation should be done when a coupling of navigations is initiated.
  # @param MOVEMENT_TRACES Boolean indicating if the device should leave traces behind.
  # @param TRACKING_TARGET_NAME Name of the device's tracking target name as chosen in daemon.
  def my_constructor(self, SCENEGRAPH, PLATFORM_SIZE, STARTING_MATRIX, NAVIGATION_LIST, INPUT_SENSOR_TYPE, INPUT_SENSOR_NAME, NO_TRACKING_MAT, GF_SETTINGS, ANIMATE_COUPLING, MOVEMENT_TRACES, TRACKING_TARGET_NAME = None):
    
    ## @var SCENEGRAPH
    # Reference to the scenegraph.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var coupled_navigations
    # List of coupled Navigation instances to which this Navigation's changes are forwarded to.
    self.coupled_navigations = []

    ## @var input_sensor_type
    # String indicating the type of input device to be created, e.g. "XBoxController" or "Spheron"
    self.input_sensor_type = INPUT_SENSOR_TYPE

    ## @var start_matrix
    # Initial position matrix of the platform.
    self.start_matrix = STARTING_MATRIX
    
    # create device
    ## @var device
    # Device instance handling relative inputs of physical device.
    if self.input_sensor_type == "Spheron":
      self.device = OldSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "XBoxController":
      self.device = XBoxDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "KeyboardMouse":
      self.device = KeyboardMouseDevice()
      self.device.my_constructor()
    elif self.input_sensor_type == "Spacemouse":
      self.device = SpacemouseDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME)
    
    # create ground following
    ## @var groundfollowing
    # GroundFollowing instance to correct the absolute matrices with respect to gravity.
    self.groundfollowing = GroundFollowing()
    self.groundfollowing.my_constructor(self.SCENEGRAPH, self.device.sf_station_mat, GF_SETTINGS)

    # create input mapping
    ## @var inputmapping
    # InputMapping instance to process and map relative device inputs to an absolute matrix.
    self.inputmapping = InputMapping()
    self.inputmapping.my_constructor(self, self.device, self.groundfollowing, STARTING_MATRIX)
    self.inputmapping.set_input_factors(self.device.translation_factor, self.device.rotation_factor)
    
    # create platform
    ## @var platform
    # Platform instance that is controlled by the Device.
    self.platform = Platform()
    self.platform.my_constructor(self.SCENEGRAPH, PLATFORM_SIZE, self.inputmapping, len(NAVIGATION_LIST))

    ## @var NAVIGATION_LIST
    # Reference to a list containing all Navigation instances in the setup.
    self.NAVIGATION_LIST = NAVIGATION_LIST

    # attributes
    ## @var in_dofchange_animation
    # Boolean variable to indicate if a movement animation for a DOF change (realistic/unrealistic) is in progress.
    self.in_dofchange_animation = False

    ## @var frames_since_last_dofchange
    # Framecount to make realistic/unrealistic switch on one button. Switching again is possible after x frames.
    self.frames_since_last_dofchange = 0

    ## @var frames_since_last_coupling
    # Framecount since the last coupling / decoupling operation was done. Used to make functionality on one button.
    self.frames_since_last_coupling = 0

    ## @var in_coupling_animation
    # Boolean variable to indicate if a movement animation for coupling is in progress.
    self.in_coupling_animation = False

    ## @var timer
    # Instance of TimeSensor to handle the duration of animations.
    self.timer = avango.nodes.TimeSensor()

    ## @var ANIMATE_COUPLING
    # Boolean indicating if an animation should be done when a coupling of navigations is initiated.
    self.ANIMATE_COUPLING = ANIMATE_COUPLING

    ## @var movement_traces
    # Boolean indicating if the movement traces should be visualized by line segments.
    self.movement_traces = MOVEMENT_TRACES

    ## @var trace
    # The trace class that handles the line segment updating.
    self.trace = None
      

    # evaluate every frame
    self.always_evaluate(True)

  ## Resets the platform's matrix to the initial value.
  def reset(self):
    self.inputmapping.set_abs_mat(self.start_matrix)

  ## Sets platform to new start position
  def set_to_pos(self, NEWPOS):
    self.start_matrix = NEWPOS
    self.reset()

  ## Activates 3-DOF (realistic) navigation mode.
  def activate_realistic_mode(self):

    # remove pitch and roll from current orientation
    _current_mat = self.platform.sf_abs_mat.value
    _current_trans = _current_mat.get_translate()
    _current_yaw = Tools.get_yaw(_current_mat)

    ## @var start_rot
    # Quaternion representing the start rotation of the animation
    self.start_rot = self.platform.sf_abs_mat.value.get_rotate()

    ## @var target_rot
    # Quaternion representing the target rotation of the animation
    self.target_rot = avango.gua.make_rot_mat(math.degrees(_current_yaw), 0, 1, 0).get_rotate()

    ## @var animation_time
    # Time of the rotation animation in relation to the rotation distance.
    self.animation_time = 2 * math.sqrt(math.pow(self.start_rot.x - self.target_rot.x, 2) + math.pow(self.start_rot.y - self.target_rot.y, 2) + math.pow(self.start_rot.z - self.target_rot.z, 2) + math.pow(self.start_rot.w - self.target_rot.w, 2))
   
    # if no animation is needed, set animation time to a minimum value to avoid division by zero
    if self.animation_time == 0.0:
      self.animation_time = 0.01

    ## @var start_trans
    # Starting translation vector of the animation.
    self.start_trans = _current_trans

    ## @var animation_start_time
    # Point in time where the animation started.
    self.animation_start_time = self.timer.Time.value
 
    self.in_dofchange_animation = True                       
  
  ## Animates the removal of pitch and roll angles when switching from 6-DOF (unrealistic) to 3-DOF (realistic) navigation mode.
  def animate_dofchange(self):

    _current_time = self.timer.Time.value
    _slerp_ratio = (_current_time - self.animation_start_time) / self.animation_time

    if _slerp_ratio > 1:
      _slerp_ratio = 1
      self.in_dofchange_animation = False
      self.inputmapping.activate_realistic_mode()
      self.frames_since_last_dofchange = 0

    _transformed_quat = self.start_rot.slerp_to(self.target_rot, _slerp_ratio)

    _position_yaw_mat = avango.gua.make_trans_mat(self.start_trans.x, self.start_trans.y, self.start_trans.z) * \
                        avango.gua.make_rot_mat(_transformed_quat)

    self.inputmapping.set_abs_mat(_position_yaw_mat)

  ## Activates 6-DOF (unrealistic) navigation mode.
  def deactivate_realistic_mode(self):
    self.inputmapping.deactivate_realistic_mode()
    self.frames_since_last_dofchange = 0

  ## Bidirectional coupling of this and another navigation.
  # @param NAVIGATION The Navigation to be coupled.
  def couple_navigation(self, NAVIGATION):
    if not ((NAVIGATION in self.coupled_navigations) or (self in NAVIGATION.coupled_navigations)):
      for _nav in self.coupled_navigations:
        if not (NAVIGATION in _nav.coupled_navigations):
          _nav.coupled_navigations.append(NAVIGATION)
        if not (_nav in NAVIGATION.coupled_navigations):
          NAVIGATION.coupled_navigations.append(_nav)
      for _nav in NAVIGATION.coupled_navigations:
        if not (self in _nav.coupled_navigations):
          _nav.coupled_navigations.append(self)
        if not (_nav in self.coupled_navigations):
          self.coupled_navigations.append(_nav)
      self.coupled_navigations.append(NAVIGATION)
      NAVIGATION.coupled_navigations.append(self)

  ## Bidirectional decoupling of this and another navigation.
  # @param NAVIGATION The Navigation to be decoupled.
  def decouple_navigation(self, NAVIGATION):
    if NAVIGATION in self.coupled_navigations:
      self.coupled_navigations.remove(NAVIGATION)
      NAVIGATION.coupled_navigations.remove(self)

  ## Triggers the coupling mechanism.
  # When other platforms are close enough, they are coupled to each other.
  def trigger_coupling(self):

    self.frames_since_last_coupling = 0
    
    # list containing the navigataions close enough to couple
    _close_navs = []

    # threshold when two navigations should be considered for coupling (distance in meter)
    _threshold = 7.0
    
    # compute center position of own platform
    _position_self = (self.platform.sf_abs_mat.value * self.device.sf_station_mat.value).get_translate()

    # check for all navigations in the setup
    for _nav in self.NAVIGATION_LIST:
      
      # compute center position of currently iterated platform
      _position_nav = (_nav.platform.sf_abs_mat.value * _nav.device.sf_station_mat.value).get_translate()

      # append navigation to the list of close ones if distance is smaller than a threshold
      if _nav != self and Tools.euclidean_distance(_position_self, _position_nav) < _threshold:
        _close_navs.append(_nav)

    # sort list of close navs, highest distance first
    _close_navs.sort(key = lambda _nav: Tools.euclidean_distance(_position_self, (_nav.platform.sf_abs_mat.value * _nav.device.sf_station_mat.value).get_translate()), reverse = True)

    if len(_close_navs) > 0:
      # couple the close navigations
      for _nav in _close_navs:
        self.couple_navigation(_nav)

      if self.ANIMATE_COUPLING:
        # do an animation to closest navigation if this functionality is switched on
        _nav_animation_target = _close_navs[-1]
        
        self.set_coupling_animation_settings(_nav_animation_target)
   
        for i in range(len(_close_navs) - 1):
          _close_navs[i].set_coupling_animation_settings(_nav_animation_target)

      print "Coupling of platform " + str(self.platform.platform_id) + " successfully initiated."

    else:
      print "No platform in range for coupling."
      self.frames_since_last_coupling = 0
  
  ## Sets all the necessary attributes to perform a lerp and slerp animation to another navigation.
  # @param TARGET_NAVIGATION The Navigation instance to animate to.
  def set_coupling_animation_settings(self, TARGET_NAVIGATION):
    self.start_rot = self.platform.sf_abs_mat.value.get_rotate()
    self.start_trans = self.platform.sf_abs_mat.value.get_translate()

    _start_rot_center_mat = self.platform.sf_abs_mat.value * self.device.sf_station_mat.value
    _target_rot_center_mat = TARGET_NAVIGATION.platform.sf_abs_mat.value * TARGET_NAVIGATION.device.sf_station_mat.value

    _difference_vector = _target_rot_center_mat.get_translate() - _start_rot_center_mat.get_translate()
    _difference_vector.y = 0.0

    self.target_rot = self.start_rot
    #self.target_rot = avango.gua.make_rot_mat(math.degrees(Tools.get_yaw(_target_rot_center_mat)), 0, 1, 0).get_rotate()
    self.target_trans = self.start_trans + _difference_vector

    self.animation_time = 0.5 * math.sqrt(math.pow(self.start_trans.x - self.target_trans.x, 2) + math.pow(self.start_trans.y - self.target_trans.y, 2) + math.pow(self.start_trans.z - self.target_trans.z, 2)) + \
                          math.sqrt(math.pow(self.start_rot.x - self.target_rot.x, 2) + math.pow(self.start_rot.y - self.target_rot.y, 2) + math.pow(self.start_rot.z - self.target_rot.z, 2) + math.pow(self.start_rot.w - self.target_rot.w, 2))

    # if no animation is needed, set animation time to a minimum value to avoid division by zero
    if self.animation_time == 0.0:
      self.animation_time = 0.01

    self.animation_start_time = self.timer.Time.value
    self.in_coupling_animation = True

  ## Animates the movement to another platform during the coupling process.
  def animate_coupling(self):
    
    _current_time = self.timer.Time.value
    _animation_ratio = (_current_time - self.animation_start_time) / self.animation_time

    if _animation_ratio > 1:
      _animation_ratio = 1
      self.in_coupling_animation = False
      self.frames_since_last_coupling = 0

    _transformed_quat = self.start_rot.slerp_to(self.target_rot, _animation_ratio)
    _transformed_vec = self.start_trans.lerp_to(self.target_trans, _animation_ratio)

    _animation_mat = avango.gua.make_trans_mat(_transformed_vec.x, _transformed_vec.y, _transformed_vec.z) * \
                     avango.gua.make_rot_mat(_transformed_quat)

    self.inputmapping.set_abs_mat(_animation_mat)
  
  ## Decouples this Navigation from all coupled Navigations.
  def clear_couplings(self):

    if len(self.coupled_navigations) > 0:
      # create hard copy of coupled navigations
      _couplings = list(self.coupled_navigations)

      # iterate over all navigations and clear the coupling
      for _nav in _couplings:
        _nav.decouple_navigation(self)

      self.coupled_navigations = []
      self.frames_since_last_coupling = 0

      print "Cleared couplings of platform " + str(self.platform.platform_id)

  ## Switches from realistic to unrealistic or from unrealistic to realistic mode on this
  # and all other coupled instances.
  def trigger_dofchange(self):

    # if in realistic mode, switch to unrealistic mode
    if self.inputmapping.realistic == True:
      self.deactivate_realistic_mode()
      for _navigation in self.coupled_navigations:
        _navigation.deactivate_realistic_mode()
    
    # if in unrealistic mode, switch to realistic mode
    else:
      self.activate_realistic_mode()
      for _navigation in self.coupled_navigations:
        _navigation.activate_realistic_mode()

  
  ## Evaluated every frame.
  def evaluate(self):

    # increase frame counters
    self.frames_since_last_dofchange = self.frames_since_last_dofchange + 1
    self.frames_since_last_coupling = self.frames_since_last_coupling + 1

    # handle visibilities
    self.platform.platform_transform_node.GroupNames.value = []
    for _nav in self.coupled_navigations:
      self.platform.platform_transform_node.GroupNames.value.append("couple_group_" + str(_nav.platform.platform_id))


    # handle button inputs

    if self.input_sensor_type == "Spheron" or self.input_sensor_type == "KeyboardMouse":

      # left mouse button (Spheron) or R-key (KeyboardMouse) resets platform
      if self.device.mf_buttons.value[1] == True:
        self.reset()
        for _navigation in self.coupled_navigations:
            _navigation.reset()

      # right mouse button (Spheron) or H-key (KeyboardMouse) triggers switch between 
      # realistic (3 DOF) and unrealistic (6 DOF) mode
      if self.device.mf_buttons.value[0] == True:
        if self.frames_since_last_dofchange > 100:        # at least 100 frames must lie between two dofchanges
           self.trigger_dofchange()

      # middle mouse button (Spheron) or G-key (KeyboardMouse) triggers coupling
      if self.device.mf_buttons.value[2] == True:
        if self.frames_since_last_coupling > 100:        # at least 100 frames must lie between two coupling actions
          if len(self.coupled_navigations) == 0:
            self.trigger_coupling()
          else:
            self.clear_couplings()               
    

    elif self.input_sensor_type == "XBoxController":
      # X Button resets platform
      if self.device.mf_buttons.value[2] == True:
        self.reset()
        for _navigation in self.coupled_navigations:
            _navigation.reset()
      
      # A Button triggers switch between realistic (3 DOF) and unrealistic (6 DOF) mode
      if self.device.mf_buttons.value[0] == True:
        if self.frames_since_last_dofchange > 100:        # at least 100 frames must lie between two dofchanges
           self.trigger_dofchange()

      # B Button triggers coupling
      if self.device.mf_buttons.value[1] == True:
        if self.frames_since_last_coupling > 100:        # at least 100 frames must lie between two coupling actions
          if len(self.coupled_navigations) == 0:
            self.trigger_coupling()
          else:
            self.clear_couplings()


    elif self.input_sensor_type == "Spacemouse":
      
      # left button triggers switch between realistic (3 DOF) and unrealistic (6 DOF) mode
      if self.device.mf_buttons.value[0] == True:
        if self.frames_since_last_dofchange > 100:       # at least 100 frames must lie between two dofchanges
          self.trigger_dofchange()

      # right button triggers coupling
      if self.device.mf_buttons.value[1] == True:
        if self.frames_since_last_coupling > 100:        # at least 100 frames must lie between two coupling actions
          if len(self.coupled_navigations) == 0:
            self.trigger_coupling()
          else:
            self.clear_couplings()

          
    # handle dofchange animation
    if self.in_dofchange_animation:
      self.animate_dofchange()

    # handle coupling animation
    elif self.in_coupling_animation:
      self.animate_coupling()

    # draw the traces if enabled
    #if self.movement_traces:
    #  _station_trans = self.device.sf_station_mat.value.get_translate()
    #  _mat = self.platform.sf_abs_mat.value * avango.gua.make_trans_mat(_station_trans.x, 0, _station_trans.z)
    #  if self.trace == None:
    #    self.trace = TraceLines.Trace(self.SCENEGRAPH.Root.value, self.platform.platform_id, 20, _mat)  
      
    #  self.trace.update(_mat)
Ejemplo n.º 35
0
from subprocess import call
from button import Button
from player import Player
from Enemy import Enemy
from AeroEnemy import AeroEnemy
from Projectile import Projectile
from Platform import Platform
import pygame
index = 0
with open("currentLevel", "r") as f:
    try:
        index = int(f.readline())
        print(index)
    except Exception as e:
        print(e)
if index == 1:
    level = [[AeroEnemy(100, 240, 64, 64)], [Enemy(200, 580, 64, 64), Enemy(300, 580, 64, 64)], Player(680, 580, 64, 64),
             [Platform(480, 540, 200, 25, (0, 255, 0)), Platform(100, 500, 200, 25, (0, 255, 0)),
              Platform(550, 400, 200, 25, (0, 221, 0))], pygame.image.load('background/maxresdefault2.jpg')]
else:

    level = [[AeroEnemy(100, 240, 64, 64)], [Enemy(200, 620, 64, 64)], Player(680, 620, 64, 64),
             [Platform(500, 540, 200, 25, (0, 255, 0)), Platform(100, 500, 200, 25, (0, 255, 0)),
              Platform(550, 400, 200, 25, (0, 221, 0))], pygame.image.load('background/maxresdefault.jpg')]
Ejemplo n.º 36
0
    def loadWorld_11(self):
        tmxData = load_pygame("worlds/1-1/W11.tmx")
        self.mapSize = (tmxData.width, tmxData.height)

        self.sky = pg.Surface((WINDOW_W, WINDOW_H))
        self.sky.fill((pg.Color('#5c94fc')))

        # 2D List
        self.map = [[0] * tmxData.height for i in range(tmxData.width)]

        layer_num = 0
        for layer in tmxData.visible_layers:
            for y in range(tmxData.height):
                for x in range(tmxData.width):

                    # Getting pygame surface
                    image = tmxData.get_tile_image(x, y, layer_num)

                    # It's none if there are no tile in that place
                    if image is not None:
                        tileID = tmxData.get_tile_gid(x, y, layer_num)

                        if layer.name == 'Foreground':

                            # 22 ID is a question block, so in taht case we shoud load all it's images
                            if tileID == 22:
                                image = (
                                    image,  # 1
                                    tmxData.get_tile_image(0, 15,
                                                           layer_num),  # 2
                                    tmxData.get_tile_image(1, 15,
                                                           layer_num),  # 3
                                    tmxData.get_tile_image(
                                        2, 15, layer_num)  # activated
                                )

                            # Map class has 1)"map" list, which is used in collision system because we can
                            # easily get block by x and y coordinate 2)"obj", "obj_bg" and simular arrays -
                            # they are used in rendering because you don't need to cycle through every
                            # (x, y) pair. Here we are adding the same platform object in 2 different arrays.
                            self.map[x][y] = Platform(x * tmxData.tileheight,
                                                      y * tmxData.tilewidth,
                                                      image, tileID)
                            self.obj.append(self.map[x][y])

                        elif layer.name == 'Background':
                            self.map[x][y] = BGObject(x * tmxData.tileheight,
                                                      y * tmxData.tilewidth,
                                                      image)
                            self.obj_bg.append(self.map[x][y])
            layer_num += 1

        # Tubes
        self.spawn_tube(28, 10)
        self.spawn_tube(37, 9)
        self.spawn_tube(46, 8)
        self.spawn_tube(55, 8)
        self.spawn_tube(163, 10)
        self.spawn_tube(179, 10)

        # Mobs
        self.mobs.append(Goombas(736, 352, False))
        self.mobs.append(Goombas(1295, 352, True))
        self.mobs.append(Goombas(1632, 352, False))
        self.mobs.append(Goombas(1672, 352, False))
        self.mobs.append(Goombas(5570, 352, False))
        self.mobs.append(Goombas(5620, 352, False))

        self.map[21][8].bonus = 'mushroom'
        self.map[78][8].bonus = 'mushroom'
        self.map[109][4].bonus = 'mushroom'

        self.flag = Flag(6336, 48)
Ejemplo n.º 37
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "bilibili"
class Navigation(avango.script.Script):

  # input fields
  ## @var sf_reset_trigger
  # Boolean field to indicate if the platform is to be reset.
  sf_reset_trigger = avango.SFBool()

  ## @var sf_coupling_trigger
  # Boolean field to indicate if the coupling mechanism is to be triggered.
  sf_coupling_trigger = avango.SFBool()

  ## @var sf_dof_trigger
  # Boolean field to indicate if the change of the dof mode is to be triggered.
  sf_dof_trigger = avango.SFBool()  

  # static class variables
  ## @var trace_materials
  # List of material pretexts to choose from when a trace is created. All avatars on this
  # platform will have this material.
  trace_materials = ['AvatarBlue', 'AvatarCyan', 'AvatarGreen', 'AvatarMagenta', 'AvatarDarkGreen',
                     'AvatarOrange', 'AvatarRed', 'AvatarWhite', 'AvatarYellow', 'AvatarGrey']

  ## @var material_used
  # List of booleans to indicate if a material in trace_materials was already used.
  material_used = [False, False, False, False, False,
                   False, False, False, False, False]

  ## Default constructor.
  def __init__(self):
    self.super(Navigation).__init__()

    # if every material has already been used, reset the pool
    _reset_pool = True

    for _boolean in Navigation.material_used:
      if _boolean == False:
        _reset_pool = False
        break

    if _reset_pool:
      Navigation.material_used = [False, False, False, False, False, False, False, False, False, False]

    # get a random material from the pool of materials
    _random_material_number = random.randint(0, len(Navigation.trace_materials) - 1)
 
    # if the material is already used, go further until the first unused one is found
    while Navigation.material_used[_random_material_number] == True:
      _random_material_number = (_random_material_number + 1) % len(Navigation.material_used)

    # get the selected material 
    ## @var trace_material
    # The material to be used for the movement traces.
    self.trace_material = Navigation.trace_materials[_random_material_number]
    Navigation.material_used[_random_material_number] = True

  ## Custom constructor.
  # @param NET_TRANS_NODE Reference to the net matrix node in the scenegraph for distribution.
  # @param SCENEGRAPH Reference to the scenegraph in which the navigation should take place.
  # @param PLATFORM_SIZE Physical size of the platform in meters. Passed in an two-element list: [width, depth]
  # @param SCALE Start scaling of the platform.
  # @param STARTING_MATRIX Initial position matrix of the platform to be created.
  # @param NAVIGATION_LIST List of all navigations in the setup.
  # @param INPUT_SENSOR_TYPE String indicating the type of input device to be created, e.g. "XBoxController" or "OldSpheron"
  # @param INPUT_SENSOR_NAME Name of the input device sensor as chosen in daemon.
  # @param NO_TRACKING_MAT Matrix which should be applied if no tracking is available.
  # @param GF_SETTINGS Setting list for the GroundFollowing instance: [activated, ray_start_height]
  # @param ANIMATE_COUPLING Boolean indicating if an animation should be done when a coupling of navigations is initiated.
  # @param MOVEMENT_TRACES Boolean indicating if the device should leave traces behind.
  # @param INVERT Boolean indicating if the input values should be inverted.
  # @param SLOT_MANAGER Reference to the one and only SlotManager instance in the setup.
  # @param TRANSMITTER_OFFSET The matrix offset that is applied to the values delivered by the tracking system.
  # @param DISPLAYS The names of the displays that belong to this navigation.
  # @param AVATAR_TYPE A string that determines what kind of avatar representation is to be used ["joseph", "joseph_table", "kinect"].
  # @param CONFIG_FILE The path to the config file that is used.
  # @param TRACKING_TARGET_NAME Name of the device's tracking target name as chosen in daemon.
  def my_constructor(
      self
    , NET_TRANS_NODE
    , SCENEGRAPH
    , PLATFORM_SIZE
    , SCALE
    , STARTING_MATRIX
    , NAVIGATION_LIST
    , INPUT_SENSOR_TYPE
    , INPUT_SENSOR_NAME
    , NO_TRACKING_MAT
    , GF_SETTINGS
    , ANIMATE_COUPLING
    , MOVEMENT_TRACES
    , INVERT
    , SLOT_MANAGER
    , TRANSMITTER_OFFSET
    , DISPLAYS
    , AVATAR_TYPE
    , CONFIG_FILE
    , TRACKING_TARGET_NAME = None
    ):
    
    ## @var SCENEGRAPH
    # Reference to the scenegraph.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var NET_TRANS_NODE
    # Reference to the net matrix node in the scenegraph for distribution.
    self.NET_TRANS_NODE = NET_TRANS_NODE

    ## @var coupled_navigations
    # List of coupled Navigation instances to which this Navigation's changes are forwarded to.
    self.coupled_navigations = []

    ## @var input_sensor_type
    # String indicating the type of input device to be created, e.g. "XBoxController" or "OldSpheron"
    self.input_sensor_type = INPUT_SENSOR_TYPE

    ## @var input_sensor_name
    # Name of the input device sensor as chosen in daemon.
    self.input_sensor_name = INPUT_SENSOR_NAME

    if self.input_sensor_name == None:
      self.input_sensor_name = "keyboard"

    ## @var start_matrix
    # Initial position matrix of the platform.
    self.start_matrix = STARTING_MATRIX
    
    # create device
    ## @var device
    # Device instance handling relative inputs of physical device.
    if self.input_sensor_type == "OldSpheron":
      self.device = OldSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "NewSpheron":
      self.device = NewSpheronDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "XBoxController":
      self.device = XBoxDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, TRACKING_TARGET_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "KeyboardMouse":
      self.device = KeyboardMouseDevice()
      self.device.my_constructor(NO_TRACKING_MAT)
    elif self.input_sensor_type == "Spacemouse":
      self.device = SpacemouseDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, NO_TRACKING_MAT)
    elif self.input_sensor_type == "Globefish":
      self.device = GlobefishDevice()
      self.device.my_constructor(INPUT_SENSOR_NAME, NO_TRACKING_MAT)


    # init field connections
    self.sf_reset_trigger.connect_from(self.device.sf_reset_trigger)
    self.sf_coupling_trigger.connect_from(self.device.sf_coupling_trigger)
    self.sf_dof_trigger.connect_from(self.device.sf_dof_trigger)
    
    # create ground following
    ## @var groundfollowing
    # GroundFollowing instance to correct the absolute matrices with respect to gravity.
    self.groundfollowing = GroundFollowing()
    self.groundfollowing.my_constructor(self.SCENEGRAPH, self.device.sf_station_mat, float(GF_SETTINGS[1]))

    # create input mapping
    ## @var inputmapping
    # InputMapping instance to process and map relative device inputs to an absolute matrix.
    self.inputmapping = InputMapping()
    self.inputmapping.my_constructor(self, self.device, self.groundfollowing, STARTING_MATRIX, INVERT)
    self.inputmapping.set_input_factors(self.device.translation_factor, self.device.rotation_factor)
    self.inputmapping.sf_scale.value = SCALE

    # activate correct input mapping mode according to configuration file
    if GF_SETTINGS[0]:
      self.inputmapping.activate_realistic_mode()
    else:
      self.inputmapping.deactivate_realistic_mode()

    # create platform
    ## @var platform
    # Platform instance that is controlled by the Device.
    self.platform = Platform()
    self.platform.my_constructor(
        NET_TRANS_NODE = self.NET_TRANS_NODE
      , SCENEGRAPH = self.SCENEGRAPH
      , PLATFORM_SIZE = PLATFORM_SIZE
      , INPUT_MAPPING_INSTANCE = self.inputmapping
      , PLATFORM_ID = len(NAVIGATION_LIST)
      , TRANSMITTER_OFFSET = TRANSMITTER_OFFSET
      , NO_TRACKING_MAT = NO_TRACKING_MAT
      , DISPLAYS = DISPLAYS
      , AVATAR_TYPE = AVATAR_TYPE
      , SLOT_MANAGER = SLOT_MANAGER
      , CONFIG_FILE = CONFIG_FILE
      , AVATAR_MATERIAL = self.trace_material
      )

    # create device avatar
    if AVATAR_TYPE != "None":
      self.device.create_device_avatar(self.platform.platform_scale_transform_node
                                     , self.platform.platform_id)

    ## @var NAVIGATION_LIST
    # Reference to a list containing all Navigation instances in the setup.
    self.NAVIGATION_LIST = NAVIGATION_LIST

    # attributes
    ## @var in_dofchange_animation
    # Boolean variable to indicate if a movement animation for a DOF change (realistic/unrealistic) is in progress.
    self.in_dofchange_animation = False

    ## @var in_coupling_animation
    # Boolean variable to indicate if a movement animation for coupling is in progress.
    self.in_coupling_animation = False

    ## @var timer
    # Instance of TimeSensor to handle the duration of animations.
    self.timer = avango.nodes.TimeSensor()

    ## @var ANIMATE_COUPLING
    # Boolean indicating if an animation should be done when a coupling of navigations is initiated.
    self.ANIMATE_COUPLING = ANIMATE_COUPLING

    ## @var movement_traces
    # Boolean indicating if the movement traces are currently visualized by line segments.
    self.movement_traces = MOVEMENT_TRACES

    ## @var movement_traces_activated
    # Boolean indicating if the movement traces are generally activated.
    self.movement_traces_activated = self.movement_traces

    ## @var trace
    # The trace class that handles the line segment updating.
    self.trace = None

    if self.movement_traces:
      # create trace and add 'Shadeless' to material string to have a nicer line apperance
      ## @var trace
      # Instance of Trace class to handle trace drawing of this navigation's movements.
      self.trace = TraceLines.Trace(self.NET_TRANS_NODE, self.platform.platform_id, 500, 20.0, STARTING_MATRIX, self.trace_material + 'Shadeless')    

    # evaluate every frame
    self.always_evaluate(True)

  ## Resets the platform's matrix to the initial value.
  def reset(self):
    self.inputmapping.set_abs_mat(self.start_matrix)
    self.inputmapping.set_scale(1.0)
    self.trace.clear(self.start_matrix)

  ## Activates 3-DOF (realistic) navigation mode.
  def activate_realistic_mode(self):

    # remove pitch and roll from current orientation
    _current_mat = self.platform.sf_abs_mat.value
    _current_trans = _current_mat.get_translate()
    _current_yaw = Tools.get_yaw(_current_mat)

    ## @var start_rot
    # Quaternion representing the start rotation of the animation
    self.start_rot = self.platform.sf_abs_mat.value.get_rotate()

    ## @var target_rot
    # Quaternion representing the target rotation of the animation
    self.target_rot = avango.gua.make_rot_mat(math.degrees(_current_yaw), 0, 1, 0).get_rotate()

    ## @var animation_time
    # Time of the rotation animation in relation to the rotation distance.
    self.animation_time = 2 * math.sqrt(math.pow(self.start_rot.x - self.target_rot.x, 2) \
      + math.pow(self.start_rot.y - self.target_rot.y, 2) \
      + math.pow(self.start_rot.z - self.target_rot.z, 2) \
      + math.pow(self.start_rot.w - self.target_rot.w, 2))
   
    # if no animation is needed, set animation time to a minimum value to avoid division by zero
    if self.animation_time == 0.0:
      self.animation_time = 0.01

    ## @var start_trans
    # Starting translation vector of the animation.
    self.start_trans = _current_trans

    ## @var animation_start_time
    # Point in time where the animation started.
    self.animation_start_time = self.timer.Time.value
 
    self.in_dofchange_animation = True                       
  
  ## Animates the removal of pitch and roll angles when switching from 6-DOF (unrealistic) to 3-DOF (realistic) navigation mode.
  def animate_dofchange(self):

    _current_time = self.timer.Time.value
    _slerp_ratio = (_current_time - self.animation_start_time) / self.animation_time

    # when end of animation is reached
    if _slerp_ratio > 1:
      _slerp_ratio = 1
      self.in_dofchange_animation = False
      self.inputmapping.activate_realistic_mode()

    # compute slerp position and set it on the player's inputmapping
    _transformed_quat = self.start_rot.slerp_to(self.target_rot, _slerp_ratio)

    _position_yaw_mat = avango.gua.make_trans_mat(self.start_trans.x, self.start_trans.y, self.start_trans.z) * \
                        avango.gua.make_rot_mat(_transformed_quat)

    self.inputmapping.set_abs_mat(_position_yaw_mat)

  ## Activates 6-DOF (unrealistic) navigation mode.
  def deactivate_realistic_mode(self):
    self.inputmapping.deactivate_realistic_mode()

  ## Bidirectional coupling of this and another navigation.
  # @param NAVIGATION The Navigation to be coupled.
  def couple_navigation(self, NAVIGATION):

    # write navigation to be coupled in the list of coupled navigations on all coupled navigations
    if not ((NAVIGATION in self.coupled_navigations) or (self in NAVIGATION.coupled_navigations)):
      for _nav in self.coupled_navigations:
        if not (NAVIGATION in _nav.coupled_navigations):
          _nav.coupled_navigations.append(NAVIGATION)
        if not (_nav in NAVIGATION.coupled_navigations):
          NAVIGATION.coupled_navigations.append(_nav)
      for _nav in NAVIGATION.coupled_navigations:
        if not (self in _nav.coupled_navigations):
          _nav.coupled_navigations.append(self)
        if not (_nav in self.coupled_navigations):
          self.coupled_navigations.append(_nav)
      self.coupled_navigations.append(NAVIGATION)
      NAVIGATION.coupled_navigations.append(self)

      # if one of the navigations is in unrealistic (6 dof) mode, switch the other one to unrealistic as well
      if self.inputmapping.realistic == False and NAVIGATION.inputmapping.realistic == True:
        NAVIGATION.deactivate_realistic_mode()
      elif self.inputmapping.realistic == True and NAVIGATION.inputmapping.realistic == False:
        self.deactivate_realistic_mode()


  ## Bidirectional decoupling of this and another navigation.
  # @param NAVIGATION The Navigation to be decoupled.
  def decouple_navigation(self, NAVIGATION):
    if NAVIGATION in self.coupled_navigations:
      self.coupled_navigations.remove(NAVIGATION)
      NAVIGATION.coupled_navigations.remove(self)

  ## Triggers the coupling mechanism.
  # When other platforms are close enough, they are coupled to each other.
  def trigger_coupling(self):
    
    # list containing the navigataions close enough to couple
    _close_navs = []

    # threshold when two navigations should be considered for coupling (distance in meter)
    _threshold = 7.0
    
    # compute center position of own platform
    _position_self = (self.platform.sf_abs_mat.value * self.device.sf_station_mat.value).get_translate()

    # check for all navigations in the setup
    for _nav in self.NAVIGATION_LIST:
      
      # compute center position of currently iterated platform
      _position_nav = (_nav.platform.sf_abs_mat.value * _nav.device.sf_station_mat.value).get_translate()

      # append navigation to the list of close ones if distance is smaller than a threshold
      if _nav != self and \
         Tools.euclidean_distance(_position_self, _position_nav) < _threshold and \
         _nav.platform.sf_scale.value == self.platform.sf_scale.value:
        _close_navs.append(_nav)

    # sort list of close navs, highest distance first
    _close_navs.sort(key = lambda _nav: Tools.euclidean_distance(_position_self,
      (_nav.platform.sf_abs_mat.value * _nav.device.sf_station_mat.value).get_translate()),
      reverse = True)

    if len(_close_navs) > 0:
      if self.movement_traces_activated:
        _mat = self.get_current_world_pos()
        self.trace.clear(_mat)

      # couple the close navigations
      for _nav in _close_navs:
        self.couple_navigation(_nav)
        
        # clear movement traces
        if _nav.movement_traces_activated:
          _mat = _nav.get_current_world_pos()
          _nav.trace.clear(_mat)
          _nav.movement_traces = False

      if self.ANIMATE_COUPLING:
        # do an animation to closest navigation if this functionality is switched on
        _nav_animation_target = _close_navs[-1]
        
        self.set_coupling_animation_settings(_nav_animation_target)
        self.inputmapping.blocked = True
        self.platform.show_coupling_plane()
   
        for i in range(len(_close_navs)):
          _close_navs[i].set_coupling_animation_settings(_nav_animation_target)
          _close_navs[i].inputmapping.blocked = True
          _close_navs[i].platform.show_coupling_plane()

      # notify users
      _all_coupled_navs = list(self.coupled_navigations)
      _all_coupled_navs.append(self)

      for _nav in _all_coupled_navs:
        _nav.platform.display_coupling(_all_coupled_navs)

    else:
      print "No platform in range for coupling."

  
  ## Sets all the necessary attributes to perform a lerp and slerp animation to another navigation.
  # @param TARGET_NAVIGATION The Navigation instance to animate to.
  def set_coupling_animation_settings(self, TARGET_NAVIGATION):

    # determine start and target rotation and translation
    self.start_rot = self.platform.sf_abs_mat.value.get_rotate()
    self.start_trans = self.platform.sf_abs_mat.value.get_translate()

    _start_rot_center_mat = self.platform.sf_abs_mat.value * self.device.sf_station_mat.value
    _target_rot_center_mat = TARGET_NAVIGATION.platform.sf_abs_mat.value * TARGET_NAVIGATION.device.sf_station_mat.value

    _difference_vector = _target_rot_center_mat.get_translate() - _start_rot_center_mat.get_translate()
    _difference_vector.y = 0.0

    # it turned out that slerping rotation does not look that nice
    # can be changed by switching comments in the two lines below
    self.target_rot = self.start_rot
    #self.target_rot = avango.gua.make_rot_mat(math.degrees(Tools.get_yaw(_target_rot_center_mat)), 0, 1, 0).get_rotate()

    ## @var target_trans
    # The current animation's target translation.
    self.target_trans = self.start_trans + _difference_vector

    ## @var target_navigation
    # Reference to the target Navigation instance used in coupling animations. Used for updating target_trans when the rotation center moves.
    self.target_navigation = TARGET_NAVIGATION

    ## @var start_rot_center_mat
    # Matrix representing the transformation of the start navigation's rotation center (used for coupling animation purposes).
    self.start_rot_center_mat = _start_rot_center_mat

    self.animation_time = 0.5 * math.sqrt(math.pow(self.start_trans.x - self.target_trans.x, 2) \
      + math.pow(self.start_trans.y - self.target_trans.y, 2) + math.pow(self.start_trans.z - self.target_trans.z, 2)) \
      + math.sqrt(math.pow(self.start_rot.x - self.target_rot.x, 2) + math.pow(self.start_rot.y - self.target_rot.y, 2) \
      + math.pow(self.start_rot.z - self.target_rot.z, 2) + math.pow(self.start_rot.w - self.target_rot.w, 2))

    # if no animation is needed, set animation time to a minimum value to avoid division by zero
    if self.animation_time == 0.0:
      self.animation_time = 0.01

    self.animation_start_time = self.timer.Time.value
    self.in_coupling_animation = True

  ## Animates the movement to another platform during the coupling process.
  def animate_coupling(self):
    
    _current_time = self.timer.Time.value
    _animation_ratio = (_current_time - self.animation_start_time) / self.animation_time

    # recompute target_trans in case the rotation center moves
    _target_rot_center_mat = self.target_navigation.platform.sf_abs_mat.value * self.target_navigation.device.sf_station_mat.value
    _difference_vector = _target_rot_center_mat.get_translate() - self.start_rot_center_mat.get_translate()
    _difference_vector.y = 0.0
    self.target_trans = self.start_trans + _difference_vector
    
    # when end of animation is reached
    if _animation_ratio > 1:
      _animation_ratio = 1
      self.in_coupling_animation = False

      # clear blockings when all coupling animations are done
      _clear_blockings = True
      for _nav in self.coupled_navigations:
        if _nav.in_coupling_animation == True:
          _clear_blockings = False
          break

      if _clear_blockings:
        self.inputmapping.blocked = False
        self.platform.hide_coupling_plane()
        for _nav in self.coupled_navigations:
          _nav.inputmapping.blocked = False
          _nav.platform.hide_coupling_plane()

    # compute slerp and lerp position and set it on the player's inputmapping
    _transformed_quat = self.start_rot.slerp_to(self.target_rot, _animation_ratio)
    _transformed_vec = self.start_trans.lerp_to(self.target_trans, _animation_ratio)

    _animation_mat = avango.gua.make_trans_mat(_transformed_vec.x, _transformed_vec.y, _transformed_vec.z) * \
                     avango.gua.make_rot_mat(_transformed_quat)

    self.inputmapping.set_abs_mat(_animation_mat)
  
  ## Decouples this Navigation from all coupled Navigations.
  def clear_couplings(self):

    if len(self.coupled_navigations) > 0:
      # create hard copy of coupled navigations
      _couplings = list(self.coupled_navigations)

      if self.movement_traces_activated:
        self.movement_traces = True
        _mat = self.get_current_world_pos()
        self.trace.clear(_mat)

        if len(_couplings) == 1:
          _couplings[0].movement_traces = True
          _mat = _couplings[0].get_current_world_pos()
          _couplings[0].trace.clear(_mat)

      # iterate over all navigations and clear the coupling
      for _nav in _couplings:
        _nav.decouple_navigation(self)
        _nav.platform.remove_from_coupling_display(self, True)
        self.platform.remove_from_coupling_display(_nav, False)

      self.coupled_navigations = []

  ## Switches from realistic to unrealistic or from unrealistic to realistic mode on this
  # and all other coupled instances.
  def trigger_dofchange(self):

    # if in realistic mode, switch to unrealistic mode
    if self.inputmapping.realistic == True:
      #print "GF off"
      self.deactivate_realistic_mode()
      for _navigation in self.coupled_navigations:
        _navigation.deactivate_realistic_mode()
    
    # if in unrealistic mode, switch to realistic mode
    else:
      #print "GF on"
      self.activate_realistic_mode()
      for _navigation in self.coupled_navigations:
        _navigation.activate_realistic_mode()

  ## Computes the current world position of the rotation center on the platform ground (y = 0).
  def get_current_world_pos(self):
    _station_trans = self.device.sf_station_mat.value.get_translate()
    _mat = self.platform.sf_abs_mat.value * avango.gua.make_trans_mat(avango.gua.Vec3(_station_trans.x, 0, _station_trans.z) * self.platform.sf_scale.value)
    return _mat
  
  ## Evaluated every frame.
  def evaluate(self):

    # handle visibilities
    if self.ANIMATE_COUPLING:
      self.platform.platform_transform_node.GroupNames.value = []
      for _nav in self.coupled_navigations:
        self.platform.platform_transform_node.GroupNames.value.append("couple_group_" + str(_nav.platform.platform_id))

    # handle dofchange animation
    if self.in_dofchange_animation:
      self.animate_dofchange()

    # handle coupling animation
    elif self.in_coupling_animation:
      self.animate_coupling()

    # draw the traces if enabled
    if self.movement_traces:
      _mat = self.get_current_world_pos()
      self.trace.update(_mat)


  ## Evaluated when value changes.
  @field_has_changed(sf_reset_trigger)
  def sf_reset_trigger_changed(self):
  
    if self.sf_reset_trigger.value == True: # button pressed
      #print "RESET"
      self.reset()
      for _navigation in self.coupled_navigations:
          _navigation.reset()


  ## Evaluated when value changes.
  @field_has_changed(sf_coupling_trigger)
  def sf_coupling_trigger_changed(self):
  
    if self.sf_coupling_trigger.value == True: # button pressed

      if self.in_coupling_animation == False: 
        if len(self.coupled_navigations) == 0:
          self.trigger_coupling()
        else:
          self.clear_couplings()           
          

  ## Evaluated when value changes.
  @field_has_changed(sf_dof_trigger)
  def sf_dof_trigger_changed(self):
  
    if self.sf_dof_trigger.value == True: # button pressed

      if self.in_dofchange_animation == False:
         self.trigger_dofchange()
Ejemplo n.º 39
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "momo"
     pass
Ejemplo n.º 40
0
    def __init__(self, screen_wdith, screen_height):
        # Call the parent constructor.
        super().__init__()

        # The borders of the level.
        self.left_edge = -1500
        self.right_edge = 2500
        self.top_edge = -1800
        self.bottom_edge = 1000
        # Where the camera stops moving on this level.
        self.shift_left_bound = self.left_edge + (screen_wdith / 2)
        self.shift_right_bound = self.right_edge - (screen_wdith / 2)
        self.shift_up_bound = self.top_edge + (screen_height / 2)
        self.shift_down_bound = self.bottom_edge - (screen_height / 2)

        # Where the player starts on this level.
        self.starting_x = 429
        self.starting_y = 212
        self.starting_right = False

        # The portal to the next level.
        self.portal = Portal(460, -1430)
        self.portal_list.add(self.portal)

        # Music for this level.
        self.music = "Assets/Music/Level_2.mp3"

        # 2D array, containing the x and y coordinates and type for each platform.
        platforms = [[210, 288, 0], [280, 288, 1], [350, 288,
                                                    1], [420, 288, 1],
                     [490, 288, 1], [560, 288, 2], [-700, 168, 0],
                     [-630, 168, 1], [-560, 168, 1], [-490, 168, 1],
                     [-420, 168, 1], [-350, 168, 1], [-280, 168, 1],
                     [-210, 168, 1], [-140, 168, 1], [-70, 168, 1],
                     [0, 168, 1], [70, 168, 2], [-910, 28, 0], [-840, 28, 2],
                     [-680, -108, 0], [-610, -108, 1], [-540, -108, 1],
                     [-470, -108, 1], [-400, -108, 1], [-330, -108, 1],
                     [-260, -108, 1], [-190, -108, 1], [-120, -108, 2],
                     [150, -108, 0], [220, -108, 2], [490, -108, 0],
                     [560, -108, 1], [630, -108, 2], [910, -108, 0],
                     [980, -108, 2], [1130, -230, 0], [1200, -230, 1],
                     [1270, -230, 1], [1340, -230, 1], [1410, -230, 1],
                     [1480, -230, 1], [1550, -230, 2], [1700, -360, 0],
                     [1770, -360, 2], [1410, -480, 0], [1480, -480, 2],
                     [1700, -600, 0], [1770, -600, 2], [1410, -730, 0],
                     [1480, -730, 2], [1700, -860, 0], [1770, -860, 2],
                     [-200, -1000, 0], [-130, -1000, 1], [-60, -1000, 1],
                     [10, -1000, 1], [80, -1000, 1], [150, -1000, 1],
                     [220, -1000, 1], [290, -1000, 1], [360, -1000, 1],
                     [430, -1000, 1], [500, -1000, 1], [570, -1000, 1],
                     [640, -1000, 1], [710, -1000, 1], [780, -1000, 1],
                     [850, -1000, 1], [920, -1000, 1], [990, -1000, 1],
                     [1060, -1000, 1], [1130, -1000, 1], [1200, -1000, 1],
                     [1270, -1000, 1], [1340, -1000, 1], [1410, -1000, 1],
                     [1480, -1000, 2], [-490, -1120, 0], [-420, -1120, 2],
                     [-200, -1260, 0], [-130, -1260, 1], [-60, -1260, 1],
                     [10, -1260, 1], [80, -1260, 1], [150, -1260, 1],
                     [220, -1260, 1], [290, -1260, 1], [360, -1260, 1],
                     [430, -1260, 1], [500, -1260, 2]]

        # Go through the array above and create the platforms.
        for temp in platforms:
            platform = Platform(temp[0], temp[1], temp[2])
            self.platform_list.add(platform)

        # A 2D array containing the min-x, max-x, and y coordinates and color of each enemy.
        enemies = [[-700, -350, 138, False], [-350, 140, 138, True],
                   [490, 700, -138, False], [-680, -50, -138, False],
                   [1130, 1620, -260, True], [-200, 220, -1030, True],
                   [220, 640, -1030, False], [640, 1060, -1030, True],
                   [1060, 1550, -1030, False], [-200, 290, -1290, True]]

        # Go through the array above and create the enemies.
        for temp in enemies:
            enemy = Enemy(temp[0], temp[1], temp[2], temp[3])
            self.enemy_list.add(enemy)
Ejemplo n.º 41
0
 def __init__(self):
     Platform.__init__(self)
     self.platform = "yizhibo"
     pass
Ejemplo n.º 42
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE.size)
    pygame.display.set_caption("Use arrows to move!")
    timer = pygame.time.Clock()

    level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                    PPPPPPPPPPP                          P",
        "P                    PPPPPPPPPPP                          P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                 PPPPPPPPPPPPPPPP                        P",
        "P                 PPPPPPPPPPPPPPPP                        P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                           PP            P",
        "P                                           PP            P",
        "P                                           PP            P",
        "P                                           PP            P",
        "P                 PPPPPPPPPPP               PP            P",
        "P                 PPPPPPPPPPP               PP            P",
        "P                 PPPPPPPPPPP                             P",
        "P                 PPPPPPPPPPP                             P",
        "P                 PPPPPPPPPPP                             P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "P                                                         P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
    ]

    platforms = pygame.sprite.Group()
    player = Player(platforms, (TILE_SIZE, TILE_SIZE), 100)
    level_width = len(level[0]) * TILE_SIZE
    level_height = len(level) * TILE_SIZE
    entities = CameraAwareLayeredUpdates(
        player, pygame.Rect(0, 0, level_width, level_height))

    # build the level
    x = y = 0
    for row in level:
        for col in row:
            if col == "P":
                Platform((x, y), platforms, entities)
            x += TILE_SIZE
        y += TILE_SIZE
        x = 0

    enemies = []

    lost = False
    lost_count = 0
    lost_font = pygame.font.SysFont("comicsans", 60)

    while 1:

        if player.health <= 0:
            lost = True
            lost_count += 1

        if lost:
            if lost_count > FPS * 3:
                return
            else:
                print("You lost !!!")
                continue

        if len(enemies) == 0:
            #spawn all enemies
            for i in range(5):
                enemyX = random.randrange(50, level_width - 150)
                enemyY = random.randrange(50, level_height - 200)
                enemy = Enemy(platforms, (enemyX, enemyY), 100, entities)
                enemies.append(enemy)

        # handle events
        for e in pygame.event.get():
            if e.type == QUIT:
                return

        mouse1, mouse2, mouse3 = pygame.mouse.get_pressed()
        if mouse1:
            mouseX, mouseY = pygame.mouse.get_pos()

            targetX = mouseX - SCREEN_CENTER_X + player.rect.left
            targetY = mouseY - SCREEN_CENTER_Y + player.rect.top

            player.shoot(targetX, targetY, entities)

        player.draw_healthbar(entities)
        player.move_fireballs(enemies)

        for enemy in enemies:
            if enemy.health <= 0:
                enemy.dispose()
                enemies.remove(enemy)
            else:
                enemy.move(player)
                enemy.draw_healthbar(entities)
                if random.randrange(0, 2 * FPS) == 1:
                    enemy.shoot(player.rect.left, player.rect.top, entities)
                enemy.move_fireballs([player])

        entities.update()
        screen.fill((0, 0, 0))
        entities.draw(screen)
        pygame.display.update()

        timer.tick(FPS)
Ejemplo n.º 43
0
 def test_from_dict(self):
     Platform.from_dict({"":""})
Ejemplo n.º 44
0

def reinit():
    global player
    global platform_controller
    global floor
    global camera
    player = Player()
    platform_controller = PlatformController()
    floor = Platform(0, SCREEN_HEIGHT - 36, SCREEN_WIDTH, 36)
    camera = Camera(player)


player = Player()
platform_controller = PlatformController()
floor = Platform(0, SCREEN_HEIGHT - 36, SCREEN_WIDTH, 36)

arrow_image = load_image("arrow.png")
selected_option = 0.30

background = load_image('background.jpg')
thief = load_image('7.png')
over = load_image('8.png')

camera = Camera(player)

game_state = 'Menu'

game_loop = True
clock = pygame.time.Clock()
fps = 60
Ejemplo n.º 45
0
 def get_platform(self, platform_id="", name=""):
     platform = Platform()
     platform.id = platform_id
     platform.name = name
     return platform