Beispiel #1
0
    def new(self):
        self.result = 0
        self.objects = pg.sprite.Group()
        self.platforms = pg.sprite.Group()
        self.players = pg.sprite.Group()
        self.player = Player(self)
        self.player.set_image("p1_front.png")
        self.players.add(self.player)
        self.objects.add(self.player)

        p1 = Platform(0, 560, WIDTH, 40)
        p2 = Platform(200, 464, 100, 20)
        p3 = Platform(125, 348, 80, 20)
        p4 = Platform(350, 232, 90, 20)
        p5 = Platform(175, 116, 110, 20)
        self.objects.add(p1)
        self.objects.add(p2)
        self.objects.add(p3)
        self.objects.add(p4)
        self.objects.add(p5)
        self.platforms.add(p1)
        self.platforms.add(p2)
        self.platforms.add(p3)
        self.platforms.add(p4)
        self.platforms.add(p5)
        self.run()
 def addPlatforms(self, platforms):
     for platform in platforms:
         block = Platform(platform[0])
         block.rect.x = platform[1]
         block.rect.y = platform[2]
         block.player = self.player
         self.platform_list.add(block)
Beispiel #3
0
    def isRunnable(self, entry_point=None): # fold>>
        """
        @description checks runnability conditions.
        @description A package is runnable for a given entry point when the following conditions are met:
        @description  - there is an executable group with that entry point
        @description  - the executable exists for the current platform and is executable
        @description  - if an interpreter is declared, the interpreter can be found and is executable
        """

        if self.__is_zipped:
            self._unpack()

        # if we have no executables, it is quickly said
        if len(self.__manifest.executableGroupList()) == 0: 
            return False
        
        # try with the default entry point if not provided
        if entry_point is None:
            entry_point = self.defaultExecutableGroupEntryPoint()
            # no default? then we know the answer
            if entry_point is None:
                return False
        executable_group = self.__manifest.executableGroup(entry_point)
        if executable_group is None:
            return False
            
        # try with the executable for the current platform. If not found, try with something that is supported
        executable = executable_group.executable(Platform.currentPlatform())

        if executable is None:
            # try to see if there's an executable that can run on this platform
            for exe in executable_group.executableList():
                if Platform.isCompatibleWith(exe.platform()):
                    executable = exe
                    break

        # still none? we rest our case
        if executable is None:
            return False
       
        # check for the existence of the file as specified in the path
        executable_absolute_path = _computeExecutableAbsolutePath(self.rootDir(), executable.path(), executable.pathType(), executable.platform())
        if not os.path.exists(executable_absolute_path):
            return False

        # check if the executable is interpreted, and in this case, if the interpreter can be found and executed
        interpreter = executable.interpreter()
        if interpreter is not None:
            interpreter_path=_which(interpreter)
            if interpreter_path is None:
                return False
            if not _isExecutable(interpreter_path):
                return False
        else:
           # not interpreted, check the executability of the file itself 
            if not _isExecutable(executable_absolute_path):
                return False

        # looks like there are chances it can be executable, after all
        return True 
Beispiel #4
0
def initJson():
	global jsonInstall
	load_json(DEFAULT_JSON)
	if Platform.getPackage("apt"):
		jsonInstall = get_json("apt")
	elif Platform.getPackage("yum"):
		jsonInstall = get_json("yum")
Beispiel #5
0
def hs():
    # Hide some objects
    names = ["Wall"]
    Platform.ShowObjectList("spyroom", names, False)
    # Disable physics for some objects
    names = ["Collid"]
    Platform.PhysObjectList("spyroom", names, False)
Beispiel #6
0
    def add_rotating_platform(self,
                              position,
                              radius=2,
                              platform_width=1,
                              T=600,
                              color=(50, 50, 50)):

        height = 10 * S
        R = radius * box_size * 2
        width = platform_width * box_size * 2
        # top will be at same level as floor for position[1] = 0
        pos = np.array(position, dtype='float') * (box_size * 2.0) + [
            0, floor + height
        ]
        path = [
            np.array([
                pos[0] + R * math.cos(2 * math.pi * x / T),
                pos[1] + R * math.sin(2 * math.pi * x / T)
            ]) for x in range(T)
        ]
        self.master_platform_list.append(
            Platform.Moving_Platform([width, height],
                                     copy.copy(path),
                                     color=color))
        self.master_platform_list.append(
            Platform.Moving_Platform([width, height],
                                     path[int(T / 2):] + path[:int(T / 2)],
                                     color=color))

        self.background_list.append(Platform.Platform(pos, [height, height]))
Beispiel #7
0
    def __init__(self, player):
        """ Create level 1. """

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

        self.background = pygame.image.load("background_01.png").convert()
        self.background.set_colorkey(constants.WHITE)
        self.level_limit = -2500

        # Array with type of platform, and x, y location of the platform.
        level = [[500, 500, Platform.GRASS_LEFT]]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform.Platform(platform[0], platform[1], platform[2],
                                      "tiles_spritesheet.png")
            block.player = self.player
            self.platform_list.add(block)

        # Add a custom moving platform
        block = Platform.Moving_Platform(1350, 280,
                                         Platform.STONE_PLATFORM_MIDDLE,
                                         "tiles_spritesheet.png")
        block.boundary_left = 1350
        block.boundary_right = 1600
        block.change_x = 1
        block.player = self.player
        block.level = self
        self.platform_list.add(block)
Beispiel #8
0
    def generateplatforms(self, initial):
        y = 900  # Generate from bottom of the screen
        start = -100
        if (initial == True):
            self.startY = -100
            # Fill starting screen with platforms

            while (y > -70):
                p = Platform.Platform()
                p.getKind(self.score)
                p.y = y
                p.startY = start
                self.platforms.append(p)
                y -= 30  # Generate every 30 pixels
                start += 30
                self.startY = start

        else:
            # Creates a platform based on current score
            p = Platform.Platform()

            if (self.score <= 2500):
                difficulty = 50
            elif (self.score < 4000):
                difficulty = 60
            else:
                difficulty = 70

            p.y = self.platforms[-1].y - difficulty
            self.startY += difficulty
            p.startY = self.startY
            p.getKind(self.score)
            self.platforms.append(p)
Beispiel #9
0
    def __init__(self, player):
        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -1000

        # Array with width, height, x, and y of platform
        level = [[210, 70, 500, 530],
                 [210, 30, 1000, 500],
                 [210, 30, 1000, 300],
                 [210, 30, 710, 400],
                 [210, 30, 1300, 150]
                 ]

        # Go through the array above and add platforms
        for platform in 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)

        # Add one enemies to the level
        # Set the height and width of the screen
        size = [SCREEN_WIDTH, SCREEN_HEIGHT]
        screen = pygame.display.set_mode(size)
        self.enemy_list.add(Enemy())
Beispiel #10
0
 def setup(self, target_point, target_ent=None):
     self.nextPointIndex = 1
     self.targetPoint = vec3(target_point)
     self.targetEnt = target_ent
     start_time = Platform.time_in_seconds()
     self.path = self.entity.pathToLocation(self.targetPoint)
     end_time = Platform.time_in_seconds()
     self.pathGraphic = None
Beispiel #11
0
 def initPlatforms(self):
     """Create and add platforms to platformList"""
     myPlatform = Platform.Platform((255, 0, 0), 10)
     self.platformList.append(myPlatform)
     myPlatform = Platform.Platform((255, 255, 0), 115)
     self.platformList.append(myPlatform)
     myPlatform = Platform.Platform((0, 0, 255), 220)
     self.platformList.append(myPlatform)
Beispiel #12
0
	def setup(self, target_point, target_ent=None):
		self.nextPointIndex = 1
		self.targetPoint = vec3(target_point)
		self.targetEnt = target_ent
		start_time = Platform.time_in_seconds()
		self.path = self.entity.pathToLocation( self.targetPoint )
		end_time = Platform.time_in_seconds()
		self.pathGraphic = None
Beispiel #13
0
def hide(bOn=False):
    #Platform.HideJalak()
    # Hide some objects
    names = [
        "Bamboo", "Dome", "Garden", "Pillar", "TreeTrunk", "Rain", "Water"
    ]
    Platform.ShowObjectList("garden", names, bOn)
    # Disable physics for some objects
    names = ["TreeTrunk"]
    Platform.PhysObjectList("garden", names, bOn)
Beispiel #14
0
def loadLayers( modname, mapname):
    path = '../%s/maps/%s/' % (modname, mapname )
    filename = path + 'layers.xml'
    layers = []
    tree = ET.parse( filename )
    root = tree.getroot()
    for l in  root.getchildren( ):
        new_layer = Layer()
        for attrs in l.getchildren():
            setattr( new_layer, attrs.tag.strip( string.whitespace) , attrs.text )
        layers.append(
                    TerrainLayer( Platform.asOSPath(new_layer.TextureName),
                                  Platform.asOSPath(path + 'layer_' + new_layer.Name + '.png'),
                                  Platform.asOSPath(path+'shadows.png') ) )
    return layers
Beispiel #15
0
def loadLayers(modname, mapname):
    path = '../%s/maps/%s/' % (modname, mapname)
    filename = path + 'layers.xml'
    layers = []
    tree = ET.parse(filename)
    root = tree.getroot()
    for l in root.getchildren():
        new_layer = Layer()
        for attrs in l.getchildren():
            setattr(new_layer, attrs.tag.strip(string.whitespace), attrs.text)
        layers.append(
            TerrainLayer(
                Platform.asOSPath(new_layer.TextureName),
                Platform.asOSPath(path + 'layer_' + new_layer.Name + '.png'),
                Platform.asOSPath(path + 'shadows.png')))
    return layers
Beispiel #16
0
    def set_fm(self):
        pi_version = Platform.pi_version()
        srate = str(int(self.sample_rate /
                        (1 if self.num_channels > 1 else 2)))
        if os.path.exists(cm.fm.fmfifo):
            os.remove(cm.fm.fmfifo)
        os.mkfifo(cm.fm.fmfifo, 0777)

        fm_command = [
            "sudo", cm.home_dir + "/bin/pifm", "-", cm.fm.frequency, srate,
            "stereo" if self.num_channels > 1 else "mono"
        ]

        if pi_version >= 2:
            fm_command = [
                "sudo", cm.home_dir + "/bin/pi_fm_rds", "-audio", "-", "-freq",
                cm.fm.frequency, "-srate", srate, "-ps",
                cm.fm.program_service_name, "-rt", cm.fm.radio_text, "-ctl",
                cm.fm.fmfifo, "-nochan", "2" if self.num_channels > 1 else "1"
            ]

        log.info("Sending output as fm transmission")

        with open(os.devnull, "w") as dev_null:
            self.fm_process = subprocess.Popen(fm_command,
                                               stdin=subprocess.PIPE,
                                               stdout=dev_null)
        self.output = lambda raw_data: self.fm_process.stdin.write(raw_data)

        fmoutthr = Thread(target=self.update_fmout,
                          args=(cm, cm.fm.program_service_name))
        fmoutthr.daemon = True
        fmoutthr.start()
Beispiel #17
0
def hide():
    Platform.HideJalak()
    # Hide some objects
    names = ["column_23", "column_22",
        "column_21", "column_20", "column_19",
        "column_18", "column_17", "column_16", 
        "column_15", "Light"]
    Platform.ShowObjectList("jalak", names, False)
    names = ["Dak2FAKE", "Dak1Plane", "dkta",
        "DAK2grndEntrnc"]
    Platform.ShowObjectList("city", names, False)
    names = ["Wall"]
    Platform.ShowObjectList("spyroom", names, False)
    # Disable physics for some objects
    names = ["Collid"]
    Platform.PhysObjectList("spyroom", names, False)
Beispiel #18
0
def hc():
    # Hide some objects
    names = ["column_23", "column_22",
        "column_21", "column_20", "column_19",
        "column_18", "column_17", "column_16", 
        "column_15", "Light"]
    Platform.ShowObjectList("jalak", names, False)
Beispiel #19
0
def platform2(where=None):
    matPos = None
    if where is None or where not in range(1, 5):
        matPos = PtGetLocalAvatar().getLocalToWorld()
    else:
        #Ahnonay
        if where == 1:
            tupPos = ((0.98276501894, 0.184859260917, 0.0, 23.3415126801),
                      (-0.184859260917, 0.98276501894, 0.0, 54.0308570862),
                      (0.0, 0.0, 1.0, -0.0328424945474), (0.0, 0.0, 0.0, 1.0))
        elif where == 2:
            tupPos = ((-0.897078573704, -0.44187015295, 0.0, 649.721862793),
                      (0.44187015295, -0.897078573704, 0.0, -877.984619141),
                      (0.0, 0.0, 1.0, 9445.71386719), (0.0, 0.0, 0.0, 1.0))
        elif where == 3:
            tupPos = ((0.00954949762672, -0.999954581261, 0.0, -102.545890808),
                      (0.999954581261, 0.00954949762672, 0.0, 54.9582672119),
                      (0.0, 0.0, 1.0, 10563.0976562), (0.0, 0.0, 0.0, 1.0))
        elif where == 4:
            tupPos = ((-0.748968303204, 0.662607133389, 0.0, 1560.00488281),
                      (-0.662607133389, -0.748968303204, 0.0, -51.4498291016),
                      (0.0, 0.0, 1.0, 10171.9091797), (0.0, 0.0, 0.0, 1.0))
        elif where == 5:
            tupPos = ((-0.937420606613, -0.3482016325, 0.0, 993.751708984),
                      (0.3482016325, -0.937420606613, 0.0, -455.378509521),
                      (0.0, 0.0, 1.0, 9424.86523438), (0.0, 0.0, 0.0, 1.0))
        matPos = ptMatrix44()
        matPos.setData(tupPos)

    Platform.CreatePlatform2(bShow=False, matAv=matPos)
Beispiel #20
0
    def update(self):
        # game loop - update
        self.all_sprites.update()
        # check collision only when falling downwards
        if self.player.velocity.y > 0:
            collision = pg.sprite.spritecollide(self.player, self.platforms, False)
            if collision:
                self.player.position.y = collision[0].rect.top + 1
                self.player.velocity.y = 0
                self.player.jump()
        # if player reaches top of the screen
        if self.player.rect.top <= HEIGHT / 4:
            self.player.position.y += abs(self.player.velocity.y)
            for platform in self.platforms:
                platform.rect.y += abs(self.player.velocity.y) 

                # delete platform if goes off the screen
                if platform.rect.top >= HEIGHT:
                    platform.kill()
        # spawn new platforms
        while len(self.platforms) < 6:
            plat_width = random.randrange(50, 100)
            platform = Platform(random.randrange(0, WIDTH - plat_width),
                                random.randrange(-30, -20),
                                plat_width, 15)
            self.platforms.add(platform)
            self.all_sprites.add(platform)
Beispiel #21
0
    def set_fm(self):
        pi_version = Platform.pi_version()
        srate = str(int(self.sample_rate / (1 if self.num_channels > 1 else 2)))

        fm_command = ["sudo",
                      cm.home_dir + "/bin/pifm",
                      "-",
                      cm.fm.frequency,
                      srate,
                      "stereo" if self.num_channels > 1 else "mono"]

        if pi_version >= 2:
            fm_command = ["sudo",
                          cm.home_dir + "/bin/pi_fm_rds",
                          "-audio", "-", "-freq",
                          cm.fm.frequency,
                          "-srate",
                          srate,
                          "-nochan",
                          "2" if self.num_channels > 1 else "1"]

        log.info("Sending output as fm transmission")

        with open(os.devnull, "w") as dev_null:
            self.fm_process = subprocess.Popen(fm_command,
                                               stdin=subprocess.PIPE,
                                               stdout=dev_null)
        self.output = lambda raw_data: self.fm_process.stdin.write(raw_data)
Beispiel #22
0
def create(background, ar):
    entities = pygame.sprite.Group()
    x = y = 0
    for row in ar:
        for col in row:
            if col == "g":
                block = Platform("ground.bmp", x, y)
                # background.blit(block, (x, y))
            if col == "t":
                block = Platform("gr1.bmp", x, y)
                # background.blit(block, (x, y))
            entities.add(block)
            x += block.get_width()
        y += block.get_height()
        x = 0
    return entities
Beispiel #23
0
    def __init__(self, name, time_stamp, header=None):
        self._platform = Platform.Platform()
        self._os = OS.OS()
        self._name = name
        self._ERR_FILE_EXIST = "ERROR: Log file '%s' already exists" % name
        self._ERR_FILE_OPEN = "ERROR: Unable to open log file '%s'" % name
        
        if self._os.is_file(name):
            raise Error.Error(msg=self._ERR_FILE_EXIST)
        else:
            try:
                f = open(name, 'w')
            except IOError:
                raise Error.Error(msg=self._ERR_FILE_OPEN)
            
            if header != None:
                f.write("%s\n" % header)

            line = "Generated %s" % time_stamp.as_string()
            f.write(line+"\n\n")
            line = "System: %s" % self._platform.system()
            f.write(line+"\n")
            line = "Python version: %s" % self._platform.python_version()
            f.write(line+"\n")
            line = ("Python implementation: %s" 
                    % self._platform.python_implementation())
            f.write(line+"\n\n")
            f.close()
Beispiel #24
0
def InstanceDataFromPacket(packet):
    """Grab instance data from the packet"""
    typepath = Platform.asOSPath(packet.typepath)
    typestr = GetEntTypeInfoForTypePath(typepath).typeClass
    yaw, pitch, roll = MathUtil.quaternionToEulerYawPitchRoll(
        quat(packet.qw, packet.qx, packet.qy, packet.qz))
    return EntInstanceData(None, typestr, typepath, packet.scriptname,
                           packet.x, packet.y, packet.z, yaw, pitch, roll)
Beispiel #25
0
    def __init__(self, player):
        """ Create level 1. """

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

        # Array with width, height, x, and y of platform
        level = [[210, 70, 500, 500], [210, 70, 200, 400], [210, 70, 600, 300],
                 [250, 70, 500, 300], [100, 100, 250, 250], [50, 50, 100, 100]]

        # Go through the array above and add platforms
        for platform in 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)
Beispiel #26
0
 def new(self):
     # start a new game
     self.all_sprites = pg.sprite.Group()
     self.platforms = pg.sprite.Group()
     self.player = Player(self)
     for plat in PLATFORM_LIST:
         Platform(plat[0], plat[1], plat[2], plat[3], self)
     self.run()
Beispiel #27
0
    def map_level_5(self):# 5번 맵 로딩 함수
        self.coin = 5
        #몬스터
        self.monster.append(Monster.Monster("mouse",1900,300, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 300, 2400))
        self.monster.append(Monster.Monster("wormGreen",2400,300, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 300, 2400))
        self.monster.append(Monster.Monster("bee",1100,450, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 300, 1200))
        self.monster.append(Monster.Monster("bee",600,450, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 1200, 2400))
        self.monster.append(Monster.Monster("bee",500,1000, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 600, 1200))
        self.monster.append(Monster.Monster("bee",800,1000, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*3, 1200, 2400))
        #플랫폼

        self.platform.append(Platform.Platform("thunder",1080,900, CHARACTER_SCALING * 0.5,fall = True, die = True))   #2층에서 내리는 번개
        self.platform.append(Platform.Platform("doorClosed_mid",2400,290, CHARACTER_SCALING * 0.5, teleport = True))   #아래 텔레포트
        self.platform.append(Platform.Platform("doorClosed_mid",50,610, CHARACTER_SCALING * 0.5, teleport = False))   #윗 텔레포트
        #3층 번개
        for i in range(1):
            self.platform.append(Platform.Platform("thunder",288+ (i*128),800, CHARACTER_SCALING * 0.5, fall = True,  die = True))
        for i in range(1):
            self.platform.append(Platform.Platform("thunder",358+ ( (14 + i)*64),800, CHARACTER_SCALING * 0.5, fall = True,  die = True))
        self.platform.append(Platform.Platform("thunder",1900,820, CHARACTER_SCALING, fall = True,  die = True))

        self.platform.append(Platform.Platform("bridgeA",400,930, CHARACTER_SCALING * 0.5,PLATFORM_MOVEMENT_SPEED*4, 400, 2200, hard_platform = True))
        #몬스터
        for i in range(len(self.monster)):
            self.monster_sprite.append(self.monster[i].newMonster())
            self.monster_list.append(self.monster_sprite[i])
        #플랫폼
        for i in range(len(self.platform)):
            self.platform_sprite.append(self.platform[i].newPlatform())
            self.platform_list.append(self.platform_sprite[i])
Beispiel #28
0
def platform(name="spy"):
    matPos = None
    if name == "spy":
        tupPos = ((0.841503858566, -0.540251135826, 0.0, -141.0), (0.540251135826, 0.841503858566, 0.0, -131.0), (0.0, 0.0, 1.0, 255.0), (0.0, 0.0, 0.0, 1.0)) 
        matPos = ptMatrix44()
        matPos.setData(tupPos)
    else:
        pass
    Platform.CreatePlatformSpy(bShow=False, matAv=matPos)
Beispiel #29
0
def get_default_bus():
    """Return the default bus number based on the device platform.  For a
    Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
    For a Beaglebone Black the first user accessible bus, 1, will be returned.
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        if Platform.pi_revision() == 1:
            # Revision 1 Pi uses I2C bus 0.
            return 0
        else:
            # Revision 2 Pi uses I2C bus 1.
            return 1
    elif plat == Platform.BEAGLEBONE_BLACK:
        # Beaglebone Black has multiple I2C buses, default to 1 (P9_19 and P9_20).
        return 1
    else:
        raise RuntimeError('Could not determine default I2C bus for platform.')
Beispiel #30
0
def get_default_bus():
    """Return the default bus number based on the device platform.  For a
    Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
    For a Beaglebone Black the first user accessible bus, 1, will be returned.
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        if Platform.pi_revision() == 1:
            # Revision 1 Pi uses I2C bus 0.
            return 0
        else:
            # Revision 2 Pi uses I2C bus 1.
            return 1
    elif plat == Platform.BEAGLEBONE_BLACK:
        # Beaglebone Black has multiple I2C buses, default to 1 (P9_19 and P9_20).
        return 1
    else:
        raise RuntimeError('Could not determine default I2C bus for platform.')
Beispiel #31
0
    def runEntryPoint(self, entry_point, arguments=None, environment=None): # fold>>
        """
        @description runs the platform specific executable with a given entry poin, or a compatible 
        @description platform specific/aspecific code under the same entry point.
        @description The function never returns. The executable runs with an execve call which
        @description replaces the current executable with the new executable. If you want to fork, you
        @description have to do it before calling run()
        """ 
        if self.__is_zipped:
            self._unpack()

        if not self.isRunnable(entry_point):
            raise NotRunnableException("Entry point "+entry_point+" is not runnable.")
      
        if arguments is None:
            arguments=[]
        if environment is None:
            environment = os.environ

        # add the environment variable containing the package base directory.
        # we use this and not os.setenv because os.setenv does not export to child processes.
        environment["PACKAGE_ROOT_DIR"]=self.rootDir()
        environment["CN_ROOT_DIR"]=self.rootDir()
        environment["CN_ENTRY_POINT"] = entry_point

        # FIXME: this code is heavily repeated. refactor it out!
        executable_group = self.__manifest.executableGroup(entry_point)
        executable = executable_group.executable(Platform.currentPlatform())
        if executable is None:
            # try to see if there's an executable that can run on this platform
            for exe in executable_group.executableList():
                if Platform.isCompatibleWith(exe.platform()):
                    executable = exe
                    break

        environment["CN_RUN_ARCH"]=executable.platform() 
        executable_absolute_path = _computeExecutableAbsolutePath(self.rootDir(), executable.path(), executable.pathType(), executable.platform())

        interpreter = executable.interpreter()
        if interpreter is not None:
            interpreter_path=_which(interpreter)
            os.execve(interpreter_path, [interpreter_path, executable_absolute_path]+list(arguments), environment)
        else:
            os.execve(executable_absolute_path,[executable_absolute_path]+list(arguments), environment)
Beispiel #32
0
 def map_level_3(self):# 3번 맵 로딩 함수
     self.coin = 4
     self.monster.append(Monster.Monster("bee",400,150, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED*2, 300, 1000))
     self.platform.append(Platform.Platform("bridgeA",400,50, CHARACTER_SCALING * 0.5,PLATFORM_MOVEMENT_SPEED, 300, 1200, hard_platform = True))
     for i in range(len(self.platform)):
         self.platform_sprite.append(self.platform[i].newPlatform())
         self.platform_list.append(self.platform_sprite[i])
     for i in range(len(self.monster)):
         self.monster_sprite.append(self.monster[i].newMonster())
         self.monster_list.append(self.monster_sprite[i])
Beispiel #33
0
def say(sentence):
    global __popen__

    if __popen__ is not None:
        __popen__.wait()

    print("Saying '{0}'".format(sentence))      
    cmd = ['mpg123', '-q', "http://translate.google.com/translate_tts?tl=en&q={0}".format(sentence)]
    if Platform.is_raspberrypi():
        __popen__ = subprocess.Popen(cmd)
Beispiel #34
0
 def add_floor(self,
               start,
               stop,
               color=platform_color,
               line_color=(0, 0, 0),
               line_width=2):
     self.master_platform_list.append(
         Platform.Platform([(start + stop) * box_size, floor + 50 * S],
                           [(stop - start + 1) * box_size, 50 * S], color,
                           line_color, line_width))
Beispiel #35
0
def play(file):
    global __popen__

    if __popen__ is not None:
        __popen__.wait()

    print("Playing '{0}'".format(file))      
    cmd = ['mpg123', '-q', file]
    if Platform.is_raspberrypi():
        __popen__ = subprocess.Popen(cmd)
Beispiel #36
0
 def map_level_2(self):# 2번 맵 로딩 함수
     self.coin = 4
     self.monster.append(Monster.Monster("bee",800,420, CHARACTER_SCALING * 0.5, MONSTER_MOVEMENT_SPEED, 800, 930))
     for i in range(len(self.monster)):
         self.monster_sprite.append(self.monster[i].newMonster())
         self.monster_list.append(self.monster_sprite[i])
     self.platform.append(Platform.Platform("rock",690,700, CHARACTER_SCALING * 0.5, fall = True, die = True))
     for i in range(len(self.platform)):
         self.platform_sprite.append(self.platform[i].newPlatform())
         self.platform_list.append(self.platform_sprite[i])
Beispiel #37
0
def main( argv=None ):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt( argv[1:], "dC:c:h", [ "debug", "config", "crontab", "help" ] )
        except getopt.error, msg:
            raise Utils.Usage( msg )
            
        debugMode = configFile = crontabFile = None
        
        for cliOpts, cliArgs in opts:
            if cliOpts in ( "-c", "--crontab" ):
                crontabFile = cliArgs

            if cliOpts in ( "-d", "--debug" ):
                debugMode = True

            if cliOpts in ( "-C", "--config" ):
                configFile = cliArgs

            if cliOpts in ( "-h", "--help" ):
                DisplayUsage()
                return 2
                
        if not Platform.isRunning():
            Utils.initLogging( logLevelNo=3 )
            logFacility = logging.getLogger( Utils.returnScriptName( ) )
            
            if configFile is None:
                print "A Config File Is Required."
                return 2
                
            configSettings = Utils.loadConfig( configFile )
            
            if not debugMode:
                if not Utils.makeDaemon():
                    logFacility.error( "Failed To Daemonize.  Running In The Foreground. " )
                    print "Failed To Daemonize.  Going To Run In The Foreground."
                
            if crontabFile is None:
                if not configSettings is None:
                    cronDaemon = CronLib.CronSQL( configSettings )
                else:
                    print "There Was A Problem Loading The Config File.  Check The Log File."
                    return 2
            else:
                try:
                    cronDaemon = CronLib.CronFile( crontabFile )
                except CronLib.CronError, errorMsg:
                    logFacility.error( "Failed To Start crond.  Reason: %s \n" % errorMsg )
                    print "Failed To Start crond.  Reason: %s \n" % errorMsg
                    return 1
                
            cronDaemon.run()
Beispiel #38
0
    def int(self, amount, screen, character):
        self.amount = amount
        self.platforms = [None] * amount
        self.visiblePlatforms = []
        for i in range(0, amount):
            if i > 0:
                randomX = random.randint((self.platforms[i-1].X)-(500), self.platforms[i-1].X + 500)
                while randomX < 0 or randomX > screen.get_width() - 80:
                    randomX = random.randint((self.platforms[i-1].X)-(500), self.platforms[i-1].X + 500)
                randomY = random.randint((self.platforms[i-1].Y)-(500), self.platforms[i-1].Y - 300)

                platform = Platform.Plateform()
                platform.int(randomX, randomY, screen, character, self)
            else:
                platform = Platform.Plateform()
                platform.int(screen.get_width()/2, 500, screen, character, self)
            
            self.platforms[i] = platform
            if platform.bottom > 0:
                self.visiblePlatforms.append(platform)
Beispiel #39
0
 def new(self):
     # start new game
     self.all_sprites = pg.sprite.Group()
     self.platforms = pg.sprite.Group()
     self.player = Player(self)
     self.all_sprites.add(self.player)
     for platform in PLATFORM_LIST:
         platform_to_add = Platform(*platform)
         self.all_sprites.add(platform_to_add)
         self.platforms.add(platform_to_add)
     self.run()
Beispiel #40
0
def platform(where=None, bAttachOn=False):
    matPos = None
    #if where is None or where not in range(1, 5):
    if where is None or where not in range(1, 6):
        matPos = PtGetLocalAvatar().getLocalToWorld()
    else:
        """
        #Ahnonay
        if where == 1:
            tupPos = ((0.98276501894, 0.184859260917, 0.0, 23.3415126801), (-0.184859260917, 0.98276501894, 0.0, 54.0308570862), (0.0, 0.0, 1.0, -0.0328424945474), (0.0, 0.0, 0.0, 1.0))
        elif where == 2:
            tupPos = ((-0.897078573704, -0.44187015295, 0.0, 649.721862793), (0.44187015295, -0.897078573704, 0.0, -877.984619141), (0.0, 0.0, 1.0, 9445.71386719), (0.0, 0.0, 0.0, 1.0))
        elif where == 3:
            tupPos = ((0.00954949762672, -0.999954581261, 0.0, -102.545890808), (0.999954581261, 0.00954949762672, 0.0, 54.9582672119), (0.0, 0.0, 1.0, 10563.0976562), (0.0, 0.0, 0.0, 1.0))
        elif where == 4:
            tupPos = ((-0.748968303204, 0.662607133389, 0.0, 1560.00488281), (-0.662607133389, -0.748968303204, 0.0, -51.4498291016), (0.0, 0.0, 1.0, 10171.9091797), (0.0, 0.0, 0.0, 1.0))
        elif where == 5:
            tupPos = ((-0.937420606613, -0.3482016325, 0.0, 993.751708984), (0.3482016325, -0.937420606613, 0.0, -455.378509521), (0.0, 0.0, 1.0, 9424.86523438), (0.0, 0.0, 0.0, 1.0))
        """
        """
        # Descent V1
        if where == 1:
            tupPos = ((-0.0784590244293, 0.996917307377, 0.0, 789.132202148), (-0.996917307377, -0.0784590244293, 0.0, -583.487670898), (0.0, 0.0, 1.0, 1151.59057617), (0.0, 0.0, 0.0, 1.0))
        elif where == 2:
            tupPos = ((0.859911203384, 0.510443627834, 0.0, 785.749572754), (-0.510443627834, 0.859911203384, 0.0, -574.134643555), (0.0, 0.0, 1.0, 1151.59057617), (0.0, 0.0, 0.0, 1.0))
        elif where == 3:
            tupPos = ((-0.398735255003, 0.91706776619, 0.0, 766.0), (-0.91706776619, -0.398735255003, 0.0, -699.0), (0.0, 0.0, 1.0, 715.0), (0.0, 0.0, 0.0, 1.0))
        elif where == 4:
        """
        # Descent V2
        if where == 1:
            tupPos = ((0.722353339195, -0.691524147987, 0.0, 766.198181152),
                      (0.691524147987, 0.722353339195, 0.0, -698.65826416),
                      (0.0, 0.0, 1.0, 608.855895996), (0.0, 0.0, 0.0, 1.0))
        elif where == 2:
            tupPos = ((1.0, -0.0, 0.0, 769.0), (0.0, 1.0, 0.0, -610.0),
                      (0.0, 0.0, 1.0, 1152.0), (0.0, 0.0, 0.0, 1.0))
        elif where == 3:
            tupPos = ((0.0, -1.0, 0.0, 766.0), (1.0, 0.0, 0.0, -699.0),
                      (0.0, 0.0, 1.0, 1146.0), (0.0, 0.0, 0.0, 1.0))
        elif where == 4:
            tupPos = ((0.0, -1.0, 0.0, 766.0), (1.0, 0.0, 0.0, -680.0),
                      (0.0, 0.0, 1.0, 1140.0), (0.0, 0.0, 0.0, 1.0))
        elif where == 5:
            tupPos = ((0.0, -1.0, 0.0, 766.0), (1.0, 0.0, 0.0, -680.0),
                      (0.0, 0.0, 1.0, 715.0), (0.0, 0.0, 0.0, 1.0))
        elif where == 6:
            tupPos = ((0.0, -1.0, 0.0, 766.0), (1.0, 0.0, 0.0, -680.0),
                      (0.0, 0.0, 1.0, 610.0), (0.0, 0.0, 0.0, 1.0))

        matPos = ptMatrix44()
        matPos.setData(tupPos)

    Platform.CreatePlatform2(bShow=False, matAv=matPos, bAttach=bAttachOn)
Beispiel #41
0
def InstanceDataFromPacket( packet ):
    """Grab instance data from the packet"""
    typepath = Platform.asOSPath(packet.typepath)
    typestr = GetEntTypeInfoForTypePath(typepath).typeClass
    yaw, pitch, roll = MathUtil.quaternionToEulerYawPitchRoll( quat( packet.qw, packet.qx, packet.qy, packet.qz) )
    return EntInstanceData(None,
                           typestr,
                           typepath,
                           packet.scriptname,
                           packet.x, packet.y, packet.z,
                           yaw, pitch, roll)
Beispiel #42
0
def test():
    model, header = Platform.get_model()

    print "We are going to do some basic tests to make sure"
    print "your hardware is working as expected."
    print "Raspberry Pi %s" % model
    print "You have %s channels defined" % str(cm.hardware.gpio_len)
    print "They are using gpio pins %s" % ", ".join(
        map(str, cm.hardware.gpio_pins))
    print "You have configured your relays as active %s" % (
        "low" if cm.hardware.active_low_mode else "high")
    print "pin_modes are %s " % ", ".join(cm.hardware.pin_modes)
    print "custom_channel_mapping %s being used" % ("is" if ccm else "is not")

    if ccm:
        print "[%s]" % ", ".join(
            map(str, cm.audio_processing.custom_channel_mapping))

    print "\nFirst we are going to flash each light in order to see if they are all working"

    raw_input("Press Enter to continue....")

    flash(True)

    print "If everything went correctly you should have seen each of your channels"
    print "flash one at a time in order of assignment."

    while True:
        answer = raw_input(
            "Did you see all channels flash in order? (yes/no) ").lower()
        yes = ['yes', 'y', 'yep', 'ja', 'si', 'oui']
        no = ['no', 'n', 'nope', 'nein', 'non']

        if answer in yes or answer in no:
            if answer in yes:
                print "Great, your basic config is ready for you to start with\n\n"

                sys.exit(1)

            if answer in no:
                print "Lets make sure you're using the correct gpio pins"
                print "Here is what the %s header looks like\n" % model
                print header
                print
                print "Make sure you are using the correct pins as listed above"

                if ccm:
                    print "Disable custom channel mapping to help with debugging your config"

                print "After you have made these corrections please rerun this test\n\n"

                sys.exit(1)

        print "Please answer yes or no"
Beispiel #43
0
    def resourceAbsolutePath(self, entry_point): # fold>>
        if self.__is_zipped:
            self._unpack()
        platform = Platform.currentPlatform()

        group = self.__manifest.resourceGroup(entry_point)

        if group is None:
            return None

        resource = group.resource(platform)

        if resource is not None:
            return _computeResourceAbsolutePath(self.rootDir(), resource.path(), resource.pathType(), platform)

        # look for something compatible
        for resource in group.resourceList():
            if Platform.isCompatibleWith(resource.platform()):
                return _computeResourceAbsolutePath(self.rootDir(), resource.path(), resource.pathType(), resource.platform())

        return None
Beispiel #44
0
    def executableAbsolutePath(self, entry_point): # fold>>
        if self.__is_zipped:
            self._unpack()
        platform = Platform.currentPlatform()
        
        group = self.__manifest.executableGroup(entry_point)

        if group is None:
            return None

        executable = group.executable(platform)

        if executable is not None:
            return _computeExecutableAbsolutePath(self.rootDir(), executable.path(), executable.pathType(), platform)

        # look for something compatible
        for executable in group.executableList():
            if Platform.isCompatibleWith(executable.platform()):
                return _computeExecutableAbsolutePath(self.rootDir(), executable.path(), executable.pathType(), executable.platform())

        return None
Beispiel #45
0
 def __init__(self, north, south, east, west, up, down):
     self.north = Platform.asOSPath(north)
     self.south = Platform.asOSPath(south)
     self.east  = Platform.asOSPath(east)
     self.west  = Platform.asOSPath(west)
     self.up    = Platform.asOSPath(up)
     self.down  = Platform.asOSPath(down)
def test():
    model, header = Platform.get_model()

    print "We are going to do some basic tests to make sure"
    print "your hardware is working as expected."
    print "Raspberry Pi %s" % model
    print "You have %s channels defined" % str(cm.hardware.gpio_len)
    print "They are using gpio pins %s" % ", ".join(map(str, cm.hardware.gpio_pins))
    print "You have configured your relays as active %s" % (
        "low" if cm.hardware.active_low_mode else "high")
    print "pin_modes are %s " % ", ".join(cm.hardware.pin_modes)
    print "custom_channel_mapping %s being used" % ("is" if ccm else "is not")

    if ccm:
        print "[%s]" % ", ".join(map(str, cm.audio_processing.custom_channel_mapping))

    print "\nFirst we are going to flash each light in order to see if they are all working"

    raw_input("Press Enter to continue....")

    flash(True)

    print "If everything went correctly you should have seen each of your channels"
    print "flash one at a time in order of assignment."

    while True:
        answer = raw_input("Did you see all channels flash in order? (yes/no) ").lower()
        yes = ['yes', 'y', 'yep', 'ja', 'si', 'oui']
        no = ['no', 'n', 'nope', 'nein', 'non']

        if answer in yes or answer in no:
            if answer in yes:
                print "Great, your basic config is ready for you to start with\n\n"

                return

            if answer in no:
                print "Lets make sure you're using the correct gpio pins"
                print "Here is what the %s header looks like\n" % model
                print header
                print
                print "Make sure you are using the correct pins as listed above"

                if ccm:
                    print "Disable custom channel mapping to help with debugging your config"

                print "After you have made these corrections please rerun this test\n\n"

                return

        print "Please answer yes or no"
Beispiel #47
0
    def __init__(self, player):
        """ Create level 1. """

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

        self.level_limit = -1000

        # Array with type of platform, and x, y location of the platform.
        level = [[210, 30, 450, 570],
                 [210, 30, 850, 420],
                 [210, 30, 850, 520],
                 [210, 30, 1120, 280],
                 [210, 50, 1120, 400],
                 [210, 50, 1120, 520]]

        # Go through the array above and add platforms
        for platform in 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)
Beispiel #48
0
def require_repeated_start():
    """Enable repeated start conditions for I2C register reads.  This is the
    normal behavior for I2C, however on some platforms like the Raspberry Pi
    there are bugs which disable repeated starts unless explicitly enabled with
    this function.  See this thread for more details:
      http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=15840
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        # On the Raspberry Pi there is a bug where register reads don't send a
        # repeated start condition like the kernel smbus I2C driver functions
        # define.  As a workaround this bit in the BCM2708 driver sysfs tree can
        # be changed to enable I2C repeated starts.
        subprocess.check_call('chmod 666 /sys/module/i2c_bcm2708/parameters/combined', shell=True)
        subprocess.check_call('echo -n 1 > /sys/module/i2c_bcm2708/parameters/combined', shell=True)
Beispiel #49
0
	def draw(self):

		TextureManager.GetTexture( Platform.asOSPath(self.textureName)).bind()
		glDisable(GL_CULL_FACE)
		glEnable(GL_BLEND)
		glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
		glDisable(GL_ALPHA_TEST)
		glDisable(GL_LIGHTING)
		glDepthMask( GL_FALSE )
		glColor4(1, 1, 1, 0.25)
		self._drawQuad(self.flowOffset)
		glColor4(1, 1, 1, 0.25)
		self._drawQuad(-self.flowOffset)
		glDepthMask( GL_TRUE )
		glEnable(GL_CULL_FACE)
Beispiel #50
0
def get_platform_gpio(**keywords):
    """Attempt to return a GPIO instance for the platform which the code is being
    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO
    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an
    exception if a GPIO instance can't be created for the current platform.  The
    returned GPIO object is an instance of BaseGPIO.
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        import RPi.GPIO
        return RPiGPIOAdapter(RPi.GPIO, **keywords)
    elif plat == Platform.BEAGLEBONE_BLACK:
        import Adafruit_BBIO.GPIO
        return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)
    elif plat == Platform.UNKNOWN:
        raise RuntimeError('Could not determine platform.')
def set_audio_device(sample_rate, num_channels):
    global fm_process
    pi_version = Platform.pi_version()

    if cm.audio_processing.fm:
        srate = str(int(sample_rate / (1 if num_channels > 1 else 2)))

        fm_command = ["sudo",
                      cm.home_dir + "/bin/pifm",
                      "-",
                      cm.audio_processing.frequency,
                      srate,
                      "stereo" if num_channels > 1 else "mono"]

        if pi_version == 2:
            fm_command = ["sudo",
                          cm.home_dir + "/bin/pi_fm_rds",
                          "-audio", "-", "-freq",
                          cm.audio_processing.frequency,
                          "-srate",
                          srate,
                          "-nochan",
                          "2" if num_channels > 1 else "1"]

        log.info("Sending output as fm transmission")
        
        
        with open(os.devnull, "w") as dev_null:
            fm_process = subprocess.Popen(fm_command, stdin=subprocess.PIPE, stdout=dev_null)

        return lambda raw_data: fm_process.stdin.write(raw_data)
    elif cm.lightshow.audio_out_card is not '':
        if cm.lightshow.mode == 'stream-in':
            num_channels = 2

        output_device = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL, cm.lightshow.audio_out_card)
        output_device.setchannels(num_channels)
        output_device.setrate(sample_rate)
        output_device.setformat(aa.PCM_FORMAT_S16_LE)
        output_device.setperiodsize(CHUNK_SIZE)

        return lambda raw_data: output_device.write(raw_data)

    else:
        return lambda raw_data: None
Beispiel #52
0
    def __init__(self, world, ent_xml_data, ent_config):
        """Initializes location data and mesh filename """
        self.initialData  = ent_xml_data
        self.typeInfo = ent_config
        self.world = world
        self.scriptname = ent_xml_data.scriptname
        self.meshOffset = vec3( 0, 0, 0)
        self.meshFile = Platform.asOSPath( ent_config.meshFile )
        self.behaviors = [x(self) for x in ent_config.behaviors]
        self.typeName = ent_config.typeName
        self.boundingSphere = None
        self.owner = None
        self.netVector = None

        if world.isServer and self.serverside:
            self.entID = world.generateEntID()
        else:
            self.entID = None
        self._createPhysicsBody()
        self._resetLocation()
Beispiel #53
0
def LoadEntsFromFile( filename, world, is_server ):
    #store instance variables
    ents = []

    #Load from the XML file holding the entities
    tree = ET.parse( filename )
    root = tree.getroot()

    for ent in root.getchildren( ):
        if ent.tag == 'count': continue  #Ignore the count element

        #read all the XML data associated with the ent into an object
        instance_data = EntInstanceData(ent.getchildren())

        #read the INI files description of the ent type
        type_info = GetEntTypeInfoForTypePath(Platform.asOSPath(instance_data.typepath))

        if not is_server and type_info.pythonClass.serverside:
            continue #if we're on the client side, and this is a serverside ent
                     #don't make it
        else:
            ents.append(MakeEnt(world, instance_data, type_info))
    return ents
Beispiel #54
0
def main():
    """The main game function that contains all the game attributes and the
        main game loop.
    """
    pygame.init()
    FPS = 30
    fps_clock = pygame.time.Clock()
    
    SCREENSIZE = (800, 600)
    
    screen = pygame.display.set_mode(SCREENSIZE)
    pygame.display.set_caption("Journey to the West")
    
    pygame.mouse.set_visible(False)
    
    background = Background.Background((800, 600))
    platform = Platform.platformGroup()
    player = Player.Player((-100, 0))
    
    moveL = False
    moveR = False
    
    gameIdle =True
    gameContinue = True
    gamePause = False
    
    endGameCounter = 100
    
    pygame.mixer.music.load('bg.ogg')
    pygame.mixer.music.set_endevent(USEREVENT)
    pygame.mixer.music.play()
    
    fullscreen = False
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == USEREVENT:
                    pygame.mixer.music.play()
            if (event.type == KEYDOWN and event.key == K_RETURN and 
                (pygame.key.get_mods() & KMOD_ALT)):
                if fullscreen:
                    fullscreen = False
                    screen = pygame.display.set_mode(SCREENSIZE)
                else:
                    fullscreen = True
                    screen = pygame.display.set_mode(SCREENSIZE, FULLSCREEN)
            if gameContinue:
                if gameIdle:
                    if event.type == KEYDOWN and event.key == K_RETURN:
                        gameIdle = False
                        player.unhideHeart()
                elif gamePause:
                    if event.type == KEYDOWN:
                        if event.key == K_p:
                            gamePause = False
                        if event.key == K_q:
                            pygame.quit()
                            sys.exit()
                else:
                    if event.type == KEYDOWN:
                        if event.key == K_EQUALS:
                            player.increaseHealth()
                        if event.key == K_RIGHT:
                            moveR = True
                        if event.key == K_LEFT:
                            moveL = True
                        if event.key == K_SPACE:
                            player.jump()
                        if event.key == K_p:
                            gamePause = True
                    if event.type == KEYUP:
                        if event.key == K_RIGHT:
                            moveR = False
                        if event.key == K_LEFT:
                            moveL = False
            else:
                if event.type == KEYDOWN:
                    if event.key == K_r:
                        background = Background.Background((800, 600))
                        platform = Platform.platformGroup()
                        player = Player.Player((150, 200))
                        gameContinue = True
                        moveL = False
                        moveR = False
                    if event.key == K_q:
                        pygame.quit()
                        sys.exit()
        
        if gameContinue:
            if gameIdle:
                player.hideHeart()
                player.land(platform.platList(), Platform.Platform(1, (13000, 3)))
                background.update(screen)
                player.update(screen)
                demo(screen)
                platform.update(screen)
                if not player.moveR():
                    background.moveR()
            elif gamePause:
                pause(screen)
            else:
                if moveL:
                    player.moveL()
                if moveR:
                    if not player.moveR():
                        background.moveR()
                        platform.moveR()
                        screen.fill((0, 0, 0))
                player.land(platform.platList(), platform.finalPlat())
                player.enemyCollision(platform.monList())
                player.fruitCollison(platform.fruList())
                player.fireballCollison(platform.fireList())
                if player.gameOver() or player.win():
                    gameContinue = False
                background.update(screen)
                platform.update(screen)
                player.update(screen)
        else:
            if endGameCounter == 0:
                gameIdle = True
                background = Background.Background((800, 600))
                platform = Platform.platformGroup()
                player = Player.Player((150, 200))
                gameContinue = True
                moveL = False
                moveR = False
                endGameCounter = 100
            else: endGameCounter -= 1
            if player.win():
                gameWon(screen)
            else:
                gameOver(screen)
 
        pygame.display.update()
        fps_clock.tick(FPS)
Beispiel #55
0
def MakeEnt( world, init_data, type_info=None ):
    """Creates an entity from an EntInstanceData object"""
    if not type_info:
        type_info = GetEntTypeInfoForTypePath( Platform.asOSPath(init_data.typepath) )
    return type_info.pythonClass( world, init_data, type_info )
Beispiel #56
0
def flash_nrf51(jtag, softdevice, bootloader, board, firmware):
    """Flash Bluefruit module Softdevice + Bootloader + Firmware"""

    if (board is None) or (board not in supported_boards):
        click.echo( "Please specify the board either " + ', '.join(supported_boards) )
        sys.exit(1)

    if (board == "blefriend16"):
        board = "blefriend"
        bootloader = 0 # force legacy bootloader

    if firmware is None:
        click.echo("Please specify the firmware version e.g: 0.6.5")
        sys.exit(1)

    if jtag not in supported_programmers:
        click.echo("Unsupported programmer, please specify one of following: " + ', '.join(supported_programmers))
        sys.exit(1)

    click.echo('jtag       \t: %s' % jtag)
    click.echo('softdevice \t: %s' % softdevice)
    click.echo('bootloader \t: %s' % bootloader)
    click.echo('board      \t: %s' % board)
    click.echo('firmware   \t: %s' % firmware)

    softdevice_hex = glob.glob(firmware_dir + '/softdevice/*' + softdevice + '_softdevice.hex')[0].replace('\\', '/')
    bootloader_hex = glob.glob(firmware_dir + '/bootloader/*' + str(bootloader) + '.hex')[0].replace('\\', '/')
    signature_hex = glob.glob(firmware_dir + '/' + firmware + '/' + board + '/*_signature.hex')[0].replace('\\', '/')
    firmware_hex = signature_hex.replace('_signature.hex', '.hex')

    click.echo('Writing Softdevice + DFU bootloader + Application to flash memory')
    if (jtag == 'jlink') or (jtag == 'stlink'):
        # click.echo('adalink -v nrf51822 --programmer ' + jtag +
        #                                 ' --wipe --program-hex "' + softdevice_hex + '"' +
        #                                 ' --program-hex "' + bootloader_hex + '"' +
        #                                 ' --program-hex "' + firmware_hex + '"' +
        #                                 ' --program-hex "' + signature_hex + '"')
        flash_status = subprocess.call('adalink nrf51822 --programmer ' + jtag +
                                       ' --wipe --program-hex "' + softdevice_hex + '"' +
                                       ' --program-hex "' + bootloader_hex + '"' +
                                       ' --program-hex "' + firmware_hex + '"' +
                                       ' --program-hex "' + signature_hex + '"', shell=True)
    elif (jtag == 'rpigpio'): # or (jtag == 'stlink'):
        if (jtag == 'rpigpio'):
            if (Platform.platform_detect() != Platform.RASPBERRY_PI):
                sys.exit()
            else:
                openocd_bin = openocd_dict['RPi_gpio']
                subprocess.call('chmod 755 ' + openocd_bin, shell=True)
                interface_cfg = 'raspberrypi' + ('2' if Platform.pi_version() == 2 else '') + '-native.cfg'
                interface_cfg = interface_cfg + ' -c "transport select swd" -c "set WORKAREASIZE 0"'
        else:
            interface_cfg = 'stlink-v2.cfg'
            if platform.system() != 'Linux':
                openocd_bin = openocd_dict[platform.system()]
            else:
                if Platform.platform_detect() == Platform.RASPBERRY_PI:
                    openocd_bin = openocd_dict['RPi']
                else:
                    openocd_bin = openocd_dict['Ubuntu']
                subprocess.call('chmod 755 ' + openocd_bin, shell=True)
                interface_cfg = 'stlink-v2.cfg'
        openocd_cmd = openocd_bin + ' -s ' + openocd_dir + '/scripts -l log.txt ' + '-f interface/' + interface_cfg + ' -f target/nrf51.cfg'
        flash_status = subprocess.call(openocd_cmd + ' -c init -c "reset init" -c halt -c "nrf51 mass_erase"' +
                                       ' -c "program ' + softdevice_hex + ' verify"' +
                                       ' -c "program ' + bootloader_hex + ' verify"' +
                                       ' -c "program ' + firmware_hex + ' verify"' +
                                       ' -c "program ' + signature_hex + ' verify"' +
                                       ' -c reset -c exit', shell=True if platform.system() != 'Windows' else False)
    else:
        click.echo('unsupported debugger')
        sys.exit()

    if flash_status != 0:
        print "Flash FAILED"
    else:
        print "Flash OK"
def end_early():
    """atexit function"""
    if state == "random_pattern":
        exit_event.set()
        time.sleep(3)
        turn_off_lights()


atexit.register(end_early)

# Remove traceback on Ctrl-C
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))

cm = configuration_manager.Configuration()

is_a_raspberryPI = Platform.platform_detect() == 1

if is_a_raspberryPI:
    import wiringpi2 as wiringpi
else:
    # if this is not a RPi you can't run wiringpi so lets load
    # something in its place
    import wiring_pi as wiringpi

    logging.debug("Not running on a raspberryPI")

_PWM_MAX = cm.hardware.pwm_range
_ACTIVE_LOW_MODE = cm.hardware.active_low_mode

always_on_channels = cm.lightshow.always_on_channels
always_off_channels = cm.lightshow.always_off_channels
Beispiel #58
0
	def __init__(self, type, data):
		self.type = type
		self.data = data
		self.handled = False
		self.timestamp = Platform.time_in_seconds()
Beispiel #59
0
import time
import Platform

if Platform.is_raspberrypi():
    import RPi.GPIO as GPIO
    # we have to use BCM mode to stay compatible with the dot3k
    GPIO.setmode(GPIO.BCM)

lamps = [6, 13, 19, 26]
if Platform.is_raspberrypi():
    for lamp in lamps:
        GPIO.setup(lamp, GPIO.OUT)


def set_lamp(lamp_id, state):
    if Platform.is_raspberrypi() and lamp_id >= 0 and lamp_id < len(lamps):
        GPIO.output(lamps[lamp_id], state)
    
def all_off():
    for lamp in range(0, len(lamps)):
        set_lamp(lamp, 0)

def build_good():
    set_lamp(0, 1)
    set_lamp(1, 1)
    set_lamp(2, 0)
    set_lamp(3, 0)

def broken_test():
    set_lamp(0, 0)
    set_lamp(1, 1)
Beispiel #60
0
def set_lamp(lamp_id, state):
    if Platform.is_raspberrypi() and lamp_id >= 0 and lamp_id < len(lamps):
        GPIO.output(lamps[lamp_id], state)