示例#1
0
文件: timer.py 项目: andie23/_Puzzled
class Timer(Clock):
    def __init__(self, instanceId, sceneId=None):
        super(Clock, self).__init__()
        self.id = instanceId
        self.sceneId = sceneId
        self.instanceObj = None
        self.callback = None
        self.timerLimit = None
        self.scene = Scene(sceneId).getscene()

        if 'timer_instances' not in logic.globalDict:
            logic.globalDict['timer_instances'] = {}

    def load(self):
        instance = logic.globalDict['timer_instances'][self.id]
        self.sceneId = instance['scene_id']
        self.callback = instance['callback']
        self.scene = Scene(self.sceneId).getscene()
        self.timerLimit = instance['time_limit']
        self.instanceObj = ObjProperties().getObjByPropVal(
            'instance_id', self.id, self.scene.objects)
        Clock.__init__(self, self.instanceObj)

    def _addInstance(self):
        log.debug("Creating timer instance %s", self.id)
        obj = ObjProperties()
        idleInstanceList = obj.getPropObjGroup('timer_instance', self.scene, 0)
        idleInstanceObj = idleInstanceList[0]
        idleInstanceObj['instance_id'] = self.id
        self.scene.addObject(idleInstanceObj)
        timerObj = obj.getObjByPropVal('instance_id', self.id,
                                       self.scene.objects)
        return timerObj

    def _setGlobals(self):
        logic.globalDict['timer_instances'][self.id] = {
            'callback': self.callback,
            'scene_id': self.sceneId,
            'time_limit': self.timerLimit
        }

    def isAlive(self):
        return self.id in logic.globalDict['timer_instances']

    def destroy(self):
        log.debug("destroying timer instance %s", self.id)
        if not self.instanceObj:
            return
        self.instanceObj.endObject()
        del logic.globalDict['timer_instances'][self.id]

    def setTimer(self, time, func, *args, **kwargs):
        instanceObj = self._addInstance()
        self.timerLimit = time
        self.callback = lambda: func(*args, **kwargs)
        self.instanceObj = instanceObj
        self._setGlobals()
        Clock.__init__(self, instanceObj)
示例#2
0
文件: timer.py 项目: andie23/_Puzzled
 def load(self):
     instance = logic.globalDict['timer_instances'][self.id]
     self.sceneId = instance['scene_id']
     self.callback = instance['callback']
     self.scene = Scene(self.sceneId).getscene()
     self.timerLimit = instance['time_limit']
     self.instanceObj = ObjProperties().getObjByPropVal(
         'instance_id', self.id, self.scene.objects)
     Clock.__init__(self, self.instanceObj)
示例#3
0
文件: timer.py 项目: andie23/_Puzzled
 def _addInstance(self):
     log.debug("Creating timer instance %s", self.id)
     obj = ObjProperties()
     idleInstanceList = obj.getPropObjGroup('timer_instance', self.scene, 0)
     idleInstanceObj = idleInstanceList[0]
     idleInstanceObj['instance_id'] = self.id
     self.scene.addObject(idleInstanceObj)
     timerObj = obj.getObjByPropVal('instance_id', self.id,
                                    self.scene.objects)
     return timerObj
示例#4
0
    def refreshVsBlocks(self):
        vsBlocks = self.getVisualBlocks()
        lgBlocks = self.getLogicalBlocks()
        obj = ObjProperties()

        for vsBlock in vsBlocks:
            vsBlock.removeParent()
            lgBlock = obj.getObjByPropVal('block_number',
                                          vsBlock['visual_block'], lgBlocks)
            vsBlock.position = lgBlock.position
            vsBlock.setParent(lgBlock, 0, 0)
            lgBlock['_visual_block'] = str(vsBlock)
示例#5
0
def clearPositionNodes(scene):
    canvasList = ObjProperties().getPropObjGroup('canvas_id', scene)

    for canvasObj in canvasList:
        if 'main_canvas' in canvasObj:
            continue
        canvasObj.endObject()
示例#6
0
class Clock():
    '''
    An API for controlling Timer property built 
    into the game engine found in game properties. 
    It provides control for starting, stopping and
    resuming a timer. 

    Note: Game object passed in the constructor must
          have the following properties:
            1) 'timer' type 'Timer'
            2) 'is_timer_active' type 'Boolean'
            3) 'timer_snapshot' type 'Float'
    '''

    def __init__(self, timerObj):
        self.timerObj = ObjProperties(timerObj)

    def start(self):
        self.reset()
        self._setIsActive(True)

    def stop(self):
        self.setTimeSnapshot(self.curtime())
        self._setIsActive(False)

    def reset(self):
        self.settimer(0.0)

    def resume(self):
        self._setIsActive(True)
        self.settimer(self.getTimeSnapshot())

    def curtime(self):
        if not self.isActive:
            return self.getTimeSnapshot()
        return self.timerObj.getProp('timer')

    def setTimeSnapshot(self, time):
        self.timerObj.setProp('timer_snapshot', time)

    def settimer(self, val):
        self.timerObj.setProp('timer', val)

    def _setIsActive(self, bool):
        self.timerObj.setProp('is_timer_active', bool)
    
    def getTimeSnapshot(self):
        return self.timerObj.getProp('timer_snapshot')
 
    @property
    def isActive(self):
        return self.timerObj.getProp('is_timer_active')        
示例#7
0
def _addObjResource(name):
    from objproperties import ObjProperties
    
    scene = getHudScene().getscene()
    obj = ObjProperties().getPropObjGroup(name, scene, 0)

    if str(obj) not in scene.objects:
        scene.addObject(str(obj[0]))
示例#8
0
def showChallengeList(scene, challenges, positionNodes):
    clearPositionNodes(scene)
    for index, challenge in enumerate(challenges):
        # get a position node object by it's index assigned to it
        positionNode = ObjProperties().getObjByPropVal('position_node', index,
                                                       positionNodes)
        canvas = ChallengeCanvas(challenge['id'])
        canvas.add(positionNode, False)
        setChallengeMenu(canvas, challenge)
示例#9
0
def _attachBg(targetObj, col, sceneName, visible=True):
    from objproperties import ObjProperties
    from scene_helper import Scene

    scene = Scene(sceneName).getscene()
    bg = ObjProperties().getPropObjGroup('background_view', scene, 0)[0]
    bg['target_obj'] = str(targetObj)
    bg.visible = visible
    bg.color = col
    scene.addObject(bg)
    bg = ObjProperties().getObjByPropVal('target_obj', str(targetObj),
                                         scene.objects)
    bg.position = targetObj.position
    # push it back alittle
    bg.position[2] -= 0.4
    bg.setParent(targetObj)
示例#10
0
    def setLogicalBlockNumbers(self):
        '''
        Assigns random block_numbers to logical_blocks in the active scene.
        
        Note: By default, a logical block does not have a block_number
        '''

        logicalBlocks = self.getLogicalBlocks()
        lbCount = len(logicalBlocks)
        generatedNums = []

        for logicalBlock in logicalBlocks:
            lbProp = ObjProperties(logicalBlock)
            randomNum = 0

            # Skip random number 0 because blocks are counted from 1 to 15
            # for example..
            while (randomNum in generatedNums or randomNum == 0):
                randomNum = randint(0, lbCount)

            generatedNums.append(randomNum)
            lbProp.setProp('block_number', randomNum)
            self.log.debug('%s assigned to logic_block', randomNum)
示例#11
0
    def addVisualBlocks(self):
        '''
        This methods loads a visual_block, which is a puzzle block a player will
        see as they interact with the game. The visual blocks are added and parented to
        logical blocks that share the same block_number.
        '''

        logicalBlockObjs = self.getLogicalBlocks()
        inactvObjs = self.scene.objectsInactive

        for logicalBlockObj in logicalBlockObjs:
            obj = ObjProperties()
            logicalBlock = LogicalBlock(logicalBlockObj)
            inactVsBlock = obj.getObjByPropVal('visual_block',
                                               logicalBlock.blockID,
                                               inactvObjs)

            self.scene.addObject(inactVsBlock, logicalBlockObj, 0)
            actVsBlock = obj.getObjByPropVal('visual_block',
                                             logicalBlock.blockID,
                                             self.scene.objects)
            actVsBlock.position = logicalBlockObj.position
            actVsBlock.setParent(logicalBlockObj, 0, 0)
            logicalBlock.setVsBlock(str(actVsBlock))
示例#12
0
    def addInstance(self, action):
        '''
        Add object in the scene with an always 
        sensor(with PosPulse mode == True) set in logic bricks
        '''

        if self.getInstance():
            return

        instance = ObjProperties().getPropObjGroup(
            'always_instance', self.scene, 0
        )[0]
        instance['instance_id'] = self.id
        self.scene.addObject(instance)
        self.setAction(action)
示例#13
0
 def _loadVsBlocks(self, staticBlocks):
     for staticBlock in staticBlocks:
         vsBlock = ObjProperties().getObjByPropVal(
             'visual_block', staticBlock['block_number'],
             self.scene.objectsInactive)
         self.scene.addObject(vsBlock)
         vsBlock = self.scene.objects[str(vsBlock)]
         vsBlock.visible = False
         vsBlock.position = staticBlock.position
         vsBlock.setParent(staticBlock, False, False)
示例#14
0
    def _addCanvasObj(self, isVisible):
        log.debug('setting inactive canvas object')
        scene = self.__getScene()
        canvas = scene.objectsInactive[self._canvasName]

        log.debug('assigning identity %s to canvas %s', self.getId(),
                  self._canvasName)
        canvas['canvas_id'] = self.getId()
        self._tagWidgets(canvas)
        self._setvisibility(isVisible, canvas)

        log.debug('adding canvas %s into the scene on node %s',
                  self._canvasName, self.getNode())
        scene.addObject(canvas, self.getNode(), 0)
        self.setObj(ObjProperties().getObjByPropVal('canvas_id', self.getId(),
                                                    scene.objects))
示例#15
0
 def markVisualBlocks():
     data = logic.globalDict[id]
     data['index'] += 1
     if data['index'] <= data['total']:
         vsBlock = ObjProperties().getObjByPropVal('visual_block',
                                                   data['index'],
                                                   scene.objects)
         if vsBlock:
             timer = Timer(id, 'HUD')
             timer.setTimer(
                 timerDelay, lambda: clickAnimation(
                     vsBlock, lambda: animate_match_color(
                         vsBlock, onfinishAction=markVisualBlocks)))
             timer.start()
     else:
         logic.globalDict[id]['index'] = 0
示例#16
0
def init():
    scene = logic.getCurrentScene()
    # Detect if program is in scene preload mode
    # and jump back to PRELOAD scene
    if '_preload_scene' in logic.globalDict:
        scene.replace('PRELOAD')
        return

    sceneInitObj = ObjProperties().getPropObjGroup(
        '_SCENE_CONTROLLER_', scene, 0
    )

    if not sceneInitObj:
        return

    if sceneInitObj not in scene.objects:
        scene.addObject(str(sceneInitObj[0]))
示例#17
0
def loadCursorObjs():
    '''
    Loads all cursor objects from hidden layer into active layer.
    Cursors are parented to an empty cursor object and 
    visibility set to False.
    '''

    from objproperties import ObjProperties

    scene = Scene('HUD').getscene()
    parentCursor = getCursorObj()
    cursorList = ObjProperties().getPropObjGroup('mouse_pointer', scene, 0)

    for cursor in cursorList:
        cursor.visible = False
        scene.addObject(cursor, parentCursor)
        scene.objects[str(cursor)].setParent(parentCursor)
示例#18
0
    def setStaticBlockNumbers(self, numberStructure, staticBlocks=[]):
        '''
        Assign static block numbers that will be used when matching logical_blocks 
        to static_blocks. The numbers assigned to static_blocks is
        based on the order and pattern in the numberStructure. 

        The method expects a number structure such as :
            {
                1 : [1, 2, 3, 4],
                2 : [5, 6, 7, 8],
                3 : [9, 10, 11, 12],
                4 : [13, 14, 15],
            }
        The dictionary key / index numbers represent static block rows. The list values of these
        index numbers represents the order in which numbers must be assigned to static blocks.. 

        Required static_block properties:
            @property row <int>
            @property index <int>
    
        In summary, the numberStructure represents the pattern in which the puzzle needs to be solved..
        '''

        self.log.debug(
            'Using numberStructure %s to assign block_numbers to static blocks',
            numberStructure)

        if not staticBlocks:
            staticBlocks = self.getStaticBlocks()

        for staticBlock in staticBlocks:
            staticBlocProp = ObjProperties(staticBlock)
            staticBlocIndex = staticBlocProp.getProp('index')
            staticBlocRow = staticBlocProp.getProp('row')

            if staticBlocRow in numberStructure:
                numStructRow = numberStructure[staticBlocRow]
                numStructIndexVal = numStructRow[staticBlocIndex]
                staticBlocProp.setProp('block_number', numStructIndexVal)
                self.log.debug(
                    '''
                    Static block %s has been assigned block_number %s 
                ''', staticBlock, numStructIndexVal)
            else:
                error = '''
                        Static obj %s's row %s not found in number structure!
                        ''', staticBlock, staticBlockRow
                self.log.error(error)
                raise PuzzleBlockLoaderError(error)
示例#19
0
def animateVisualBlocks(challengeName, timerDelay=0.3):
    from button_effects import clickAnimation
    from block_effects import animate_match_color
    from objproperties import ObjProperties
    from timer import Timer

    id = 'pattern_visualiser_data'
    scene = Scene('HUD').getscene()

    if id not in logic.globalDict:
        logic.globalDict[id] = {
            'total':
            len(ObjProperties().getPropObjGroup('visual_block', scene)),
            'index': 0
        }
    else:
        logic.globalDict[id]['index'] = 0

    def markVisualBlocks():
        data = logic.globalDict[id]
        data['index'] += 1
        if data['index'] <= data['total']:
            vsBlock = ObjProperties().getObjByPropVal('visual_block',
                                                      data['index'],
                                                      scene.objects)
            if vsBlock:
                timer = Timer(id, 'HUD')
                timer.setTimer(
                    timerDelay, lambda: clickAnimation(
                        vsBlock, lambda: animate_match_color(
                            vsBlock, onfinishAction=markVisualBlocks)))
                timer.start()
        else:
            logic.globalDict[id]['index'] = 0

    markVisualBlocks()
示例#20
0
 def getInstance(self):
     instance = ObjProperties().getObjByPropVal(
         'instance_id', self.getId(), self.scene.objects
     )
     return instance
示例#21
0
def getPositionNodes(scene):
    return ObjProperties().getPropObjGroup('position_node', scene)
示例#22
0
 def getBlocks(self, title, layer=1):
     blocks = ObjProperties().getPropObjGroup(title, self.scene, layer)
     return blocks
示例#23
0
 def load(self):
     staticBlocks = ObjProperties().getPropObjGroup('static_block',
                                                    self.scene)
     puzzleLoader = PuzzleLoader(self.scene)
     puzzleLoader.setStaticBlockNumbers(self.pattern, staticBlocks)
     self._loadVsBlocks(staticBlocks)
示例#24
0
 def __init__(self, timerObj):
     self.timerObj = ObjProperties(timerObj)
示例#25
0
 def isset(self):
     return ObjProperties().getObjByPropVal(
         'canvas_id', self.getId(),
         self.__getScene().objects) is not None