Beispiel #1
0
    def __init__(self):
        self.current_animations = []
        self.enterRunDuration = 1.5
        self.enterWalkDuration = 0.5

        self.skipPlayRateChanges = [self.IDLE]

        self.ease_in_idle = LerpFunc(self.easeAnimation,
                                     fromData=0,
                                     toData=1,
                                     blendType="easeIn",
                                     extraArgs=[self.IDLE])
        self.ease_out_idle = LerpFunc(self.easeAnimation,
                                      fromData=1,
                                      toData=0,
                                      blendType="easeOut",
                                      extraArgs=[self.IDLE])

        self.ease_in_walk = LerpFunc(self.easeAnimation,
                                     fromData=0,
                                     toData=1,
                                     duration=self.enterWalkDuration,
                                     blendType="noBlend",
                                     extraArgs=[self.WALK])
        self.ease_out_walk = LerpFunc(self.easeAnimation,
                                      fromData=1,
                                      toData=0,
                                      blendType="noBlend",
                                      extraArgs=[self.WALK])
Beispiel #2
0
 def camera_lookat(self,
                   position,
                   rel=False,
                   duration=2.0,
                   proportional=True):
     new_rot, angle = self.camera.calc_look_at(position, rel)
     if settings.debug_jump: duration = 0
     if duration == 0:
         self.camera.set_camera_rot(new_rot)
     else:
         if proportional:
             duration = duration * angle / pi
         if self.current_interval != None:
             self.current_interval.pause()
         self.current_interval = LerpFunc(
             self.do_camera_rot,
             fromData=0,
             toData=1,
             duration=duration,
             blendType='easeInOut',
             extraArgs=[
                 self.camera.get_camera_rot(),
                 new_rot - self.camera.get_camera_rot()
             ],
             name=None)
         self.current_interval.start()
    def fadeOutLevel(self, fadeTime=1):
        """
        the level-falls-apart animation.
        """
        tiles = self.levelNode.findAllMatches("=Pos")
        for tile in tiles:
            x, y, z = self.getPosFromTile(tile)
            self.stopAnimatedTile(x, y, True)
            tile.setPos(x, y, 0)
            #tile.setHpr(random()*360,random()*360,random()*360)
            # seq = LerpPosHprInterval(tile,fadeTime+(0.3*fadeTime*random()),(x,y,-15),(random()*360 -180,random()*360-180,random()*360-180), blendType='easeIn')
            # seq.start()

            final_hpr = Vec3(random(), random(), random()) * 360.0
            force = (Vec3(random(), random(), random()) - 0.5) * 5.0
            force.z = 0
            seq = LerpFunc(self.tileGravityAnimation,
                           fromData=0,
                           toData=1,
                           duration=1.0,
                           blendType='noBlend',
                           extraArgs=[
                               tile.get_pos(render),
                               Vec3(0), final_hpr, tile, force
                           ])
            tile.setPythonTag("Seq", seq)
            seq.start()
Beispiel #4
0
    def loseGame(self, entry):
        # The triggers are set up so that the center of the ball should move to the
        # collision point to be in the hole
        global action
        action = "start"
        toPos = entry.getInteriorPoint(render)
        taskMgr.remove('rollTask')  # Stop the maze task
        self.pathFollowed = np.zeros(self.pm.shape)
        self.maze.setP(0)
        self.maze.setR(0)

        # Move the ball into the hole over a short sequence of time. Then wait a
        # second and call start to reset the game
        Sequence(
            Parallel(
                LerpFunc(self.ballRoot.setX,
                         fromData=self.ballRoot.getX(),
                         toData=toPos.getX(),
                         duration=.1),
                LerpFunc(self.ballRoot.setY,
                         fromData=self.ballRoot.getY(),
                         toData=toPos.getY(),
                         duration=.1),
                LerpFunc(self.ballRoot.setZ,
                         fromData=self.ballRoot.getZ(),
                         toData=self.ballRoot.getZ() - .9,
                         duration=.2)), Wait(1), Func(self.start)).start()
 def poofBean(self, bean, beanAnim):
     if bean == None:
         self.notify.warning(
             'poofBean, returning immediately as bean is None')
         return
     if bean.isEmpty():
         self.notify.warning(
             'poofBean, returning immediately as bean is empty')
         return
     currentAlpha = bean.getColorScale()[3]
     currentScale = bean.getScale()
     poofAnim = Sequence(
         Parallel(
             LerpFunc(bean.setAlphaScale,
                      fromData=currentAlpha,
                      toData=0.0,
                      duration=0.25),
             LerpFunc(bean.setScale,
                      fromData=currentScale,
                      toData=currentScale * 5.0,
                      duration=0.25)), Func(bean.stash),
         Func(beanAnim.finish), Func(bean.setAlphaScale, currentAlpha),
         Func(bean.setScale, currentScale))
     poofAnim.start()
     return
    def __shrinkLoadingBar(self):
        if self.__isValidDownloadBar():
            ivalDuration = 0.5
            barPosIval = LerpPosInterval(self.bar, ivalDuration,
                                         (-0.81, 0, -0.96))
            barScaleIval = LerpScaleInterval(self.bar, ivalDuration,
                                             (0.25, 0.25, 0.25))

            def posText(pos):
                self.bar['text_pos'] = (0, pos)

            def scaleText(scale):
                self.bar['text_scale'] = (scale, scale)

            textScaleIval = LerpFunc(scaleText,
                                     fromData=0.08,
                                     toData=0.16,
                                     duration=ivalDuration)
            textPosIval = LerpFunc(posText,
                                   fromData=-0.035,
                                   toData=-0.05,
                                   duration=ivalDuration)
            shrinkIval = Parallel(barPosIval, barScaleIval, textPosIval,
                                  textScaleIval, Func(self.loadingText.hide))
            self.hideBlockerIval = Sequence(shrinkIval, Wait(0.5),
                                            Func(self.__hideBlocker),
                                            Func(self.__resetLoadingBar),
                                            Func(self.destroy))
            self.hideBlockerIval.start()
Beispiel #7
0
    def hide(self):
        if self.__hidden:
            return
        self.__hidden = True

        if not (self.__fading and self.__fadingDuration):
            NodePath.hide(self)
            self.removeFocus()
            if self.__mask:
                self.__mask.hide()
            if self.__bgPath:
                self.__bgPath.hide()
            if self.__hiddenFunc:
                self.__hiddenFunc(*self.__eventExtraArgs)
        else:
            #self.removeFocus()
            if self.__currentInterval:
                self.__currentInterval.pause()
            endpos = tuple(
                map(operator.add, self.__originPos,
                    self.__fadingPositionOffset))
            parallel = Parallel(
                LerpFunc(_modifyAlphaScale,
                         self.__fadingDuration,
                         1,
                         0,
                         blendType='easeIn',
                         extraArgs=[self]),
                LerpPosInterval(self,
                                self.__fadingDuration,
                                endpos,
                                self.__originPos,
                                blendType='easeIn'),
            )
            if self.__bgPath:
                parallel.append(
                    LerpFunc(_modifyAlphaScale,
                             self.__fadingDuration,
                             1,
                             0,
                             blendType='easeIn',
                             extraArgs=[self.__bgPath]))

            self.__currentInterval = Sequence(
                parallel,
                Func(NodePath.hide, self),
                Func(self.removeFocus),
            )
            if self.__mask:
                self.__currentInterval.append(Func(self.__mask.hide))
            if self.__bgPath:
                self.__currentInterval.append(Func(self.__bgPath.hide))
            if self.__hiddenFunc:
                self.__currentInterval.append(
                    Func(self.__hiddenFunc, *self.__eventExtraArgs))

            self.__currentInterval.start()
Beispiel #8
0
 def damage(self, amt):
     self.hp -= amt
     if self.hp < 0:
         self.world.garbage.add(self)
         return
     def update_color(scaleval):
          if self.node: 
             self.node.set_color_scale(scaleval, scaleval, scaleval, 1.0)
     ramp_up = LerpFunc(update_color, fromData=3, toData=1, duration=.2, name=None)
     ramp_up.start()
Beispiel #9
0
    def playMusic(self, music):
        curMusic = None
        nextMusic = None
        # get the current running music
        if self.musicAmbient.status() == self.musicAmbient.PLAYING:
            curMusic = self.musicAmbient
        if self.musicFight.status() == self.musicFight.PLAYING:
            curMusic = self.musicFight
        if self.musicGameOver.status() == self.musicGameOver.PLAYING:
            curMusic = self.musicGameOver

        # check which music we want to play next
        if music == "Fight":
            nextMusic = self.musicFight
        elif music == "Ambient":
            nextMusic = self.musicAmbient
        elif music == "GameOver":
            nextMusic = self.musicGameOver
        else:
            # stop all music
            self.musicFight.stop()
            self.musicAmbient.stop()
            self.musicGameOver.stop()

        fade = None
        if curMusic != None and nextMusic != None:
            # fade from cur to next
            # fade in the new music
            lerpAudioFadeOut = LerpFunc(self.audioFade,
                                        fromData=1,
                                        toData=0,
                                        duration=1.0,
                                        extraArgs=[curMusic])
            lerpAudioFadeIn = LerpFunc(self.audioFade,
                                       fromData=0,
                                       toData=1,
                                       duration=1.0,
                                       extraArgs=[nextMusic])
            fade = Sequence(lerpAudioFadeOut,
                            Func(curMusic.stop),
                            Func(nextMusic.play),
                            lerpAudioFadeIn,
                            name="FadeMusic")

        elif nextMusic != None:
            lerpAudioFadeIn = LerpFunc(self.audioFade,
                                       fromData=0,
                                       toData=1,
                                       duration=1.0,
                                       extraArgs=[nextMusic])
            fade = Sequence(Func(nextMusic.play),
                            lerpAudioFadeIn,
                            name="FadeMusic")
        if fade != None:
            fade.start()
Beispiel #10
0
    def show(self):
        if not self.__hidden:
            return
        self.__hidden = False

        if self.__mask or self.__bgPath:
            if self.__mask:
                self.__mask.reparentTo(aspect2d, sort=self.getSort())
                self.__mask.show()
            if self.__bgPath:
                self.__bgPath.reparentTo(aspect2d, sort=self.getSort())
                self.__bgPath.show()
        self.reparentTo(self.getParent(), sort=self.getSort())
        if not (self.__fading and self.__fadingDuration):
            NodePath.show(self)
            self.requestFocus()
            if self.__shownFunc:
                self.__shownFunc(*self.__eventExtraArgs)
        else:
            NodePath.show(self)
            self.requestFocus()
            if self.__currentInterval:
                self.__currentInterval.pause()
            pos = tuple(
                map(operator.add, self.__originPos,
                    self.__fadingPositionOffset))

            parallel = Parallel(
                LerpFunc(_modifyAlphaScale,
                         self.__fadingDuration,
                         0,
                         1,
                         blendType='easeOut',
                         extraArgs=[self]),
                LerpPosInterval(self,
                                self.__fadingDuration,
                                self.__originPos,
                                pos,
                                blendType='easeOut'))
            if self.__bgPath:
                parallel.append(
                    LerpFunc(_modifyAlphaScale,
                             self.__fadingDuration,
                             0,
                             1,
                             blendType='easeOut',
                             extraArgs=[self.__bgPath]))

            self.__currentInterval = Sequence(parallel)
            if self.__shownFunc:
                self.__currentInterval.append(
                    Func(self.__shownFunc, *self.__eventExtraArgs))
            self.__currentInterval.start()
Beispiel #11
0
    def create_gun(self):
        """
        Creates the gun timer
        """

        # load image
        self.img = OnscreenImage(image=self.egg.find('**/gun-0'), pos=(1.05, 0, 0.75), scale=0.25)

        # interval
        self.interval = LerpFunc(self.run_interval, fromData=1, toData=0, duration=TIME)
        self.interval.start()

        return
 def _initVisuals(self):
     RepairMincroGame._initVisuals(self)
     self.model = loader.loadModel('models/gui/pir_m_gui_srp_pumping_main')
     self.visual = self.attachNewNode('visual')
     self.visual.setPos(-0.25, 0.0, 0.074999999999999997)
     goalTopLoc = self.model.find('**/locator_top')
     goalTopLoc.reparentTo(self.visual)
     goalBottomLoc = self.model.find('**/locator_bottom')
     goalBottomLoc.reparentTo(self.visual)
     self.goalPositions = (goalBottomLoc.getPos(self), goalTopLoc.getPos(self))
     self.greatLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Great, text_fg = (0.20000000000000001, 0.80000000000000004, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ACenter, text_font = PiratesGlobals.getPirateFont(), relief = None, text_shadow = (0.0, 0.0, 0.0, 1.0), scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.46500000000000002, 0.0, 0.0), parent = self)
     self.failLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Fail, text_fg = (0.80000000000000004, 0.20000000000000001, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ARight, text_font = PiratesGlobals.getPirateFont(), text_shadow = (0.0, 0.0, 0.0, 1.0), relief = None, scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.625, 0.0, 0.0), parent = self)
     self.shipBackground = self.model.find('**/static_ship_background')
     self.shipBackground.reparentTo(self.visual)
     self.waterMeter = self.model.find('**/sprite_waterBottom')
     self.waterMeter.reparentTo(self.visual)
     self.waterTop = self.model.find('**/sprite_waterTop')
     self.waterTop.reparentTo(self.visual)
     self.waterMeterTopLoc = self.waterMeter.find('**/locator_topOfShipWater')
     self.pumpBackground = self.model.find('**/pumpBackground')
     self.pumpBackground.reparentTo(self.visual)
     self.pumpWaterTop = self.model.find('**/sprite_pumpWaterTop')
     self.pumpWaterTop.reparentTo(self.visual)
     self.pumpWaterBottom = self.model.find('**/sprite_pumpWaterBottom')
     self.pumpWaterBottom.reparentTo(self.visual)
     self.pumpWaterTopLoc = self.pumpWaterBottom.find('**/locator_topOfPumpWater')
     self.pumpHandle = self.model.find('**/sprite_handle')
     self.pumpHandle.reparentTo(self.visual)
     self.pumpBar = self.model.find('**/static_pump')
     self.pumpBar.reparentTo(self.visual)
     self.goalBox = self.model.find('**/sprite_clickField')
     self.goalBox.reparentTo(self.visual)
     self.goalBox.setTransparency(1)
     self.enableGoalBox()
     self.pumpLine = self.model.find('**/sprite_bar')
     self.pumpLine.reparentTo(self.visual)
     self.ghostLine = self.visual.attachNewNode('ghostLine')
     self.pumpLine.getChild(0).copyTo(self.ghostLine)
     self.ghostLine.setScale(self.pumpLine.getScale())
     self.ghostLine.setColor(1.0, 0.20000000000000001, 0.20000000000000001, 1.0)
     self.shipForground = self.model.find('**/static_ship_foreground')
     self.shipForground.reparentTo(self.visual)
     cm = CardMaker('cardMaker')
     cm.setFrame(-0.33000000000000002, 0.33000000000000002, 0.0, 1.0)
     self.goalBox.setZ(self.goalPositions[TOP].getZ())
     self.goalBoxStartScale = self.goalBox.getSz()
     self.enableGoalBox()
     self.pumpWaterUpLerp = LerpFunc(self.setPumpWater, fromData = -0.10000000000000001, toData = 1.0, duration = 0.5)
     self.pumpWaterDownLerp = LerpFunc(self.setPumpWater, fromData = 1.0, toData = -0.10000000000000001, duration = 0.5)
     self.model.removeNode()
     del self.model
Beispiel #13
0
 def _initVisuals(self):
     RepairMincroGame._initVisuals(self)
     self.model = loader.loadModel('models/gui/pir_m_gui_srp_pumping_main')
     self.visual = self.attachNewNode('visual')
     self.visual.setPos(-0.25, 0.0, 0.074999999999999997)
     goalTopLoc = self.model.find('**/locator_top')
     goalTopLoc.reparentTo(self.visual)
     goalBottomLoc = self.model.find('**/locator_bottom')
     goalBottomLoc.reparentTo(self.visual)
     self.goalPositions = (goalBottomLoc.getPos(self), goalTopLoc.getPos(self))
     self.greatLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Great, text_fg = (0.20000000000000001, 0.80000000000000004, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ACenter, text_font = PiratesGlobals.getPirateFont(), relief = None, text_shadow = (0.0, 0.0, 0.0, 1.0), scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.46500000000000002, 0.0, 0.0), parent = self)
     self.failLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Fail, text_fg = (0.80000000000000004, 0.20000000000000001, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ARight, text_font = PiratesGlobals.getPirateFont(), text_shadow = (0.0, 0.0, 0.0, 1.0), relief = None, scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.625, 0.0, 0.0), parent = self)
     self.shipBackground = self.model.find('**/static_ship_background')
     self.shipBackground.reparentTo(self.visual)
     self.waterMeter = self.model.find('**/sprite_waterBottom')
     self.waterMeter.reparentTo(self.visual)
     self.waterTop = self.model.find('**/sprite_waterTop')
     self.waterTop.reparentTo(self.visual)
     self.waterMeterTopLoc = self.waterMeter.find('**/locator_topOfShipWater')
     self.pumpBackground = self.model.find('**/pumpBackground')
     self.pumpBackground.reparentTo(self.visual)
     self.pumpWaterTop = self.model.find('**/sprite_pumpWaterTop')
     self.pumpWaterTop.reparentTo(self.visual)
     self.pumpWaterBottom = self.model.find('**/sprite_pumpWaterBottom')
     self.pumpWaterBottom.reparentTo(self.visual)
     self.pumpWaterTopLoc = self.pumpWaterBottom.find('**/locator_topOfPumpWater')
     self.pumpHandle = self.model.find('**/sprite_handle')
     self.pumpHandle.reparentTo(self.visual)
     self.pumpBar = self.model.find('**/static_pump')
     self.pumpBar.reparentTo(self.visual)
     self.goalBox = self.model.find('**/sprite_clickField')
     self.goalBox.reparentTo(self.visual)
     self.goalBox.setTransparency(1)
     self.enableGoalBox()
     self.pumpLine = self.model.find('**/sprite_bar')
     self.pumpLine.reparentTo(self.visual)
     self.ghostLine = self.visual.attachNewNode('ghostLine')
     self.pumpLine.getChild(0).copyTo(self.ghostLine)
     self.ghostLine.setScale(self.pumpLine.getScale())
     self.ghostLine.setColor(1.0, 0.20000000000000001, 0.20000000000000001, 1.0)
     self.shipForground = self.model.find('**/static_ship_foreground')
     self.shipForground.reparentTo(self.visual)
     cm = CardMaker('cardMaker')
     cm.setFrame(-0.33000000000000002, 0.33000000000000002, 0.0, 1.0)
     self.goalBox.setZ(self.goalPositions[TOP].getZ())
     self.goalBoxStartScale = self.goalBox.getSz()
     self.enableGoalBox()
     self.pumpWaterUpLerp = LerpFunc(self.setPumpWater, fromData = -0.10000000000000001, toData = 1.0, duration = 0.5)
     self.pumpWaterDownLerp = LerpFunc(self.setPumpWater, fromData = 1.0, toData = -0.10000000000000001, duration = 0.5)
     self.model.removeNode()
     del self.model
Beispiel #14
0
  def looseGame(self, holeNP):
    toPos = holeNP.node().getShapePos(0)
    self.stopGame()

    Sequence(
      Parallel(
      LerpFunc(self.ballNP.setX, fromData = self.ballNP.getX(),
               toData = toPos.getX(), duration = .1),
      LerpFunc(self.ballNP.setY, fromData = self.ballNP.getY(),
               toData = toPos.getY(), duration = .1),
      LerpFunc(self.ballNP.setZ, fromData = self.ballNP.getZ(),
               toData = self.ballNP.getZ() - .9, duration = .2)),
      Wait(1),
      Func(self.startGame)).start()
    def lose_game(self, holeNP):
        toPos = holeNP.node().get_shape_pos(0)
        self.stop_game()

        Sequence(
            Parallel(
                LerpFunc(self.ballNP.set_x, fromData = self.ballNP.get_x(),
                         toData = toPos.get_x(), duration = .1),
                LerpFunc(self.ballNP.set_y, fromData = self.ballNP.get_y(),
                         toData = toPos.get_y(), duration = .1),
                LerpFunc(self.ballNP.set_z, fromData = self.ballNP.get_z(),
                         toData = self.ballNP.get_z() - .9, duration = .2)),
                Wait(1),
                Func(self.start_game)).start()
Beispiel #16
0
    def create_moon(self):
        """
        Creates the moon timer
        """

        # load image
        self.img = OnscreenImage(image=self.egg.find('**/moon-quarter'), pos=(0, 0, 0),
                                 color=(1, 1, 1, 1), scale=0.25)

        # interval
        self.interval = LerpFunc(self.run_interval, fromData=1, toData=0, duration=TIME)
        self.interval.start()

        return
Beispiel #17
0
 def update_func(self, func, duration=0, extra=()):
     if settings.debug_jump: duration = 0
     if duration == 0:
         func(duration, *extra)
     else:
         if self.current_interval != None:
             self.current_interval.pause()
         self.last_interval_time = globalClock.getRealTime()
         self.current_interval = LerpFunc(self.do_update_func,
             fromData=0,
             toData=1,
             duration=duration,
             extraArgs=[func, extra],
             name=None)
         self.current_interval.start()
Beispiel #18
0
    def damage(self, amt):
        self.hp -= amt
        if self.hp < 0:
            self.world.garbage.add(self)
            return

        def update_color(scaleval):
            if self.node:
                self.node.set_color_scale(scaleval, scaleval, scaleval, 1.0)

        ramp_up = LerpFunc(update_color,
                           fromData=3,
                           toData=1,
                           duration=.2,
                           name=None)
        ramp_up.start()
Beispiel #19
0
 def move_and_rotate_camera_to(self, new_pos, new_rot, absolute=True, duration=0):
     if settings.debug_jump: duration = 0
     if duration == 0:
         if absolute:
             self.camera.set_camera_pos(new_pos)
             self.camera.set_camera_rot(new_rot)
         else:
             self.camera.set_rel_camera_pos(new_pos)
             self.camera.set_rel_camera_rot(new_rot)
     else:
         if self.current_interval != None:
             self.current_interval.pause()
         self.fake = NodePath('fake')
         if absolute:
             self.start_pos = self.camera.get_rel_camera_pos()
             self.end_pos = self.camera.get_rel_position_of(new_pos)
             #TODO
             #new_rot = self.camera.get_rel_rotation_of(new_pos)
         nodepath_lerp = LerpQuatInterval(self.fake,
                                          duration=duration,
                                          blendType='easeInOut',
                                          quat = LQuaternion(*new_rot),
                                          startQuat = LQuaternion(*self.camera.get_camera_rot())
                                          )
         func_lerp = LerpFunc(self.do_camera_move_and_rot,
                              fromData=0,
                              toData=1,
                              duration=duration,
                              blendType='easeInOut',
                              name=None)
         parallel = Parallel(nodepath_lerp, func_lerp)
         self.current_interval = parallel
         self.current_interval.start()
Beispiel #20
0
    def loadIntervals(self):

        def prepareHeightText():
            self.heightText.node().setText(TTLocalizer.PartyTrampolineGetHeight % int(self.toon.getZ()))
            self.heightText.setZ(self.indicatorFactor * self.toon.getZ() + self.heightTextOffset)

        self.heightTextInterval = Sequence(Func(prepareHeightText), LerpFunc(self.heightText.setAlphaScale, fromData=1.0, toData=0.0, duration=1.0))
Beispiel #21
0
 def enterDown(self):
     if self.oldState == 'Off':
         downAnimControl = self.actor.getAnimControl('down')
         self.actor.pose('down', downAnimControl.getNumFrames() - 1)
         return
     self.clearHitInterval()
     startScale = self.hole.getScale()
     endScale = Point3(5, 5, 5)
     self.hitInterval = Sequence(
         LerpFunc(self.setAlongSpline,
                  duration=1.0,
                  fromData=self.currentT,
                  toData=0.0),
         LerpScaleInterval(self.hole,
                           duration=0.175,
                           scale=endScale,
                           startScale=startScale,
                           blendType='easeIn'),
         Parallel(
             SoundInterval(self.upSound,
                           volume=0.6,
                           node=self.actor,
                           cutOff=PartyGlobals.PARTY_COG_CUTOFF),
             ActorInterval(self.actor, 'down', loop=0)),
         LerpScaleInterval(self.hole,
                           duration=0.175,
                           scale=Point3(3, 3, 3),
                           startScale=endScale,
                           blendType='easeOut'))
     self.hitInterval.start()
Beispiel #22
0
 def __init__(self, wheel_pos, radius, heading):
     self.radius = radius
     v_f = GeomVertexFormat.getV3()
     self.vdata = GeomVertexData('skid', v_f, Geom.UHDynamic)
     self.vdata.setNumRows(1)
     self.vertex = GeomVertexWriter(self.vdata, 'vertex')
     self.prim = GeomTriangles(Geom.UHStatic)
     self.cnt = 1
     self.last_pos = wheel_pos
     geom = Geom(self.vdata)
     geom.addPrimitive(self.prim)
     node = GeomNode('gnode')
     node.addGeom(geom)
     nodePath = render.attachNewNode(node)
     nodePath.setTransparency(True)
     nodePath.setDepthOffset(1)
     self.__set_material(nodePath)
     nodePath.node().setBounds(OmniBoundingVolume())
     self.add_vertices(radius, heading)
     self.add_vertices(radius, heading)
     self.remove_seq = Sequence(
         Wait(8),
         LerpFunc(nodePath.setAlphaScale, 8, 1, 0, 'easeInOut'),
         Func(nodePath.remove_node))
     self.remove_seq.start()
Beispiel #23
0
    def turnLeft(self):
        #turns left

        initial = self.camAngle
        final = self.camAngle - math.pi/2

        #turn animation
        turnTime = 0.2
        turnRightSeq = Sequence()
        turnRightSeq.append(LerpFunc(self.changeCamAngle, turnTime, initial,
                                                         final, 'easeInOut'))
        turnRightSeq.start()


        self.setKey("left", 1) #notes that left key is pressed

        #changes the direction left, based on current direction
        if self.direction == "N":
            self.direction = "W"
        elif self.direction == "W":
            self.direction = "S"
        elif self.direction == "S":
            self.direction = "E"
        else:
            self.direction = "N"

        #when you turn, all the collision disablements should be True
        #just checking
        #self.enableAllWalls()

        #update the label
        self.updateDirectionText()
Beispiel #24
0
    def __showSplat(self, position, direction, hot=False):
        if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():
            self.kaboomTrack.finish()
        self.clearHitInterval()
        splatName = 'splat-creampie'
        self.splat = globalPropPool.getProp(splatName)
        self.splat.setBillboardPointEye()
        self.splat.reparentTo(render)
        self.splat.setPos(self.root, position)
        self.splat.setAlphaScale(1.0)
        if not direction == 1.0:
            self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[0])
            if self.currentFacing > 0.0:
                facing = 'HitFront'
            else:
                facing = 'HitBack'
        else:
            self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[1])
            if self.currentFacing > 0.0:
                facing = 'HitBack'
            else:
                facing = 'HitFront'
        if hot:
            targetscale = 0.75
            part = 'head'
        else:
            targetscale = 0.5
            part = 'body'

        def setSplatAlpha(amount):
            self.splat.setAlphaScale(amount)

        self.hitInterval = Sequence(
            ActorInterval(self.actor, part + facing, loop=0),
            Func(self.actor.loop, 'idle'))
        self.hitInterval.start()
        self.kaboomTrack = Parallel(
            SoundInterval(self.pieHitSound,
                          volume=1.0,
                          node=self.actor,
                          cutOff=PartyGlobals.PARTY_COG_CUTOFF),
            Sequence(
                Func(self.splat.showThrough),
                Parallel(
                    Sequence(
                        LerpScaleInterval(self.splat,
                                          duration=0.175,
                                          scale=targetscale,
                                          startScale=Point3(0.1, 0.1, 0.1),
                                          blendType='easeOut'), Wait(0.175)),
                    Sequence(
                        Wait(0.1),
                        LerpFunc(setSplatAlpha,
                                 duration=1.0,
                                 fromData=1.0,
                                 toData=0.0,
                                 blendType='easeOut'))),
                Func(self.splat.cleanup), Func(self.splat.removeNode)))
        self.kaboomTrack.start()
        return
Beispiel #25
0
    def fadeOut(self, element, time):
        """ Example updating RCSS attributes from code
        by modifying the 'color' RCSS attribute to slowly
        change from solid to transparent.

        element: the Rocket element whose style to modify
        time: time in seconds for fadeout
        """

        # get the current color from RCSS effective style
        color = element.style.color
        # convert to RGBA form
        prefix = color[:color.rindex(',')+1].replace('rgb(', 'rgba(')

        def updateAlpha(t):
            # another way of setting style on a specific element
            attr = 'color: ' + prefix + str(int(t)) +');'
            element.SetAttribute('style', attr)

        alphaInterval = LerpFunc(updateAlpha,
                             duration=time,
                             fromData=255,
                             toData=0,
                             blendType='easeIn')

        return alphaInterval
Beispiel #26
0
    def __init__(self, whl_pos, whl_radius, car_h):
        GameObject.__init__(self)
        self.radius = whl_radius
        v_f = GeomVertexFormat.getV3()
        vdata = GeomVertexData('skid', v_f, Geom.UHDynamic)
        prim = GeomTriangles(Geom.UHStatic)
        self.vtx_cnt = 1
        self.last_pos = whl_pos
        geom = Geom(vdata)
        geom.add_primitive(prim)
        self.node = GeomNode('gnode')
        self.node.add_geom(geom)
        nodepath = self.eng.gfx.root.attach_node(self.node)
        nodepath.set_transparency(True)
        nodepath.set_depth_offset(1)
        nodepath.node.set_two_sided(True)  # for self-shadowing issues
        self.__set_material(nodepath)
        nodepath.p3dnode.set_bounds(OmniBoundingVolume())
        self.add_vertices(whl_radius, car_h)
        self.add_vertices(whl_radius, car_h)

        def alpha(time, n_p):
            if not n_p.is_empty:
                n_p.node.set_shader_input('alpha', time)
            # this if seems necessary since, if there are skidmarks and you
            # exit from the race (e.g. back to the menu), then alpha is being
            # called from the interval manager even if the interval manager
            # correctly says that there are 0 intervals.

        self.remove_seq = Sequence(
            Wait(8), LerpFunc(alpha, 8, .5, 0, 'easeInOut', [nodepath]),
            Func(nodepath.remove_node))
        self.remove_seq.start()
Beispiel #27
0
    def contTunnel(self):
        # This line uses slices to take the front of the list and put it on the
        # back. For more information on slices check the Python manual
        self.tunnel = self.tunnel[1:] + self.tunnel[0:1]
        # Set the front segment (which was at TUNNEL_SEGMENT_LENGTH) to 0, which
        # is where the previous segment started
        self.tunnel[0].setZ(0)
        # Reparent the front to render to preserve the hierarchy outlined above
        self.tunnel[0].reparentTo(render)
        # Set the scale to be apropriate (since attributes like scale are
        # inherited, the rest of the segments have a scale of 1)
        self.tunnel[0].setScale(.155, .155, .305)
        # Set the new back to the values that the rest of teh segments have
        self.tunnel[3].reparentTo(self.tunnel[2])
        self.tunnel[3].setZ(-TUNNEL_SEGMENT_LENGTH)
        self.tunnel[3].setScale(1)

        # Set up the tunnel to move one segment and then call contTunnel again
        # to make the tunnel move infinitely
        self.tunnelMove = Sequence(
            LerpFunc(self.tunnel[0].setZ,
                     duration=TUNNEL_TIME,
                     fromData=0,
                     toData=TUNNEL_SEGMENT_LENGTH * .305),
            Func(self.contTunnel)
        )
        self.tunnelMove.start()
Beispiel #28
0
 def toggleScale(self) :
     '''a realistic scaling toggle :
     '''
     if not self.realist_scale :
         init = 0
         end = 1
     else:
         init = 1
         end = 0
     scale = LerpFunc(self.scaleSystem,
         fromData=init,
         toData=end,
         duration=SCALELEN,
         blendType='easeIn',
         name='scaling')
     
     scale.start()
Beispiel #29
0
    def _hideFlashMessage( self, duration=0.0 ):
        if self.isDisabled():
            assert self.notify.debug("_hideFlashMessage we're disabled, but still hiding self.flashText")
            # return

        self.flashTextInterval = Sequence(Wait( duration ),
                                          LerpFunc( self.flashText.setAlphaScale, fromData=1.0, toData=0.0, duration=1.0 ),
                                          Func( self.flashText.stash ),)
        self.flashTextInterval.start()
Beispiel #30
0
 def stopMusic(self, time):
     if (self.isPlaying):
         i = LerpFunc(self.stopMusicLerp,
                      fromData=1,
                      toData=0,
                      duration=time,
                      blendType='noBlend',
                      extraArgs=[],
                      name=None).start()
Beispiel #31
0
    def loseGame(self, entry):
        toPos = entry.getInteriorPoint(render)
        taskMgr.remove("rollTask")

        Sequence(
            Parallel(
                LerpFunc(self.ballRoot.setX,
                         fromData=self.ballRoot.getX(),
                         toData=toPos.getX(),
                         duration=0.1),
                LerpFunc(self.ballRoot.setY,
                         fromData=self.ballRoot.getY(),
                         toData=toPos.getY(),
                         duration=0.1),
                LerpFunc(self.ballRoot.setZ,
                         fromData=self.ballRoot.getZ(),
                         toData=self.ballRoot.getZ() - .9,
                         duration=0.2)), Wait(1), Func(self.start)).start()
Beispiel #32
0
 def _hideFlashMessage(self, duration=0.0):
     if self.isDisabled():
         pass
     self.flashTextInterval = Sequence(
         Wait(duration),
         LerpFunc(self.flashText.setAlphaScale,
                  fromData=1.0,
                  toData=0.0,
                  duration=1.0), Func(self.flashText.stash))
     self.flashTextInterval.start()
Beispiel #33
0
def play_audio(audio,fadein = 0, volume = 1, loop = False, manager = None):
    '''plays an AudioSound'''
    if manager is _voiceMgr:
        _currentVoices.append(audio)
    
    if loop:
        audio.setLoop(True)
    if not fadein:
        audio.setVolume(volume)
        audio.play()
    else:
        interval = LerpFunc(_lerpAdjust, duration = fadein,
                            fromData = 0, toData = volume,
                            extraArgs = [audio], blendType = 'easeOut')
        _fadeinIntervalTable[audio] = interval   
        _intervals.append(interval)    
            #save the interval in the table so if the audio stops during the interval it can stop the interval first
        audio.play()
        interval.start()
    def fadeOutLevel(self,fadeTime=1):
        """
        the level-falls-apart animation.
        """
        tiles = self.levelNode.findAllMatches("=Pos")
        for tile in tiles:
            x,y,z = self.getPosFromTile(tile)
            self.stopAnimatedTile(x,y,True)
            tile.setPos(x,y,0)
            #tile.setHpr(random()*360,random()*360,random()*360)
            # seq = LerpPosHprInterval(tile,fadeTime+(0.3*fadeTime*random()),(x,y,-15),(random()*360 -180,random()*360-180,random()*360-180), blendType='easeIn')
            # seq.start()

            final_hpr = Vec3(random(), random(), random()) * 360.0
            force = (Vec3(random(), random(), random())-0.5) * 5.0
            force.z = 0
            seq = LerpFunc(self.tileGravityAnimation, fromData=0, toData=1, duration=1.0, blendType='noBlend', extraArgs=[tile.get_pos(render), Vec3(0), final_hpr, tile, force])
            tile.setPythonTag("Seq", seq)
            seq.start()
Beispiel #35
0
    def appendStoredText(self,textprops, speed = 0, fadein = 0, fadeinType = 0):
        #append a text stored with appendText() or by loading self.recordedText
        text = textprops['text']
        newLine = textprops['newLine']
        custom = textprops['custom']
        if custom:
            textMaker = TextNode('temptextmaker', self.textMaker)
            font = textprops['font']
            if font:
                textMaker.setFont(font)
            textScale = textprops['textScale']
            if textScale:
                textMaker.setTextScale(textScale)
            fg = textprops['fg']
            if fg:
                self.setFg(fg, textMaker)
            shadow = textprops['shadow']
            shadowOffset = textprops['shadowOffset']
            if shadow:
                self.setShadow(shadow, shadowOffset, textMaker)
            
            #prepared to add more props here
            
        else: textMaker = self.textMaker
        
        
        if newLine or not self.lines:
            self.startLine()

        if not speed:
            for word in text:
                self.appendWord(word, tm = textMaker, fadein = fadein, fadeinType = fadeinType)
        #TYPER EFFECT
        else:
            self.__TextLerpInit()
            self.__currentLerpInterval = LerpFunc(self._appendTextLerpFunc,extraArgs = [text,textMaker,fadein,fadeinType],
                                                  duration = len(text)/float(speed))
            self.__currentLerpInterval.start()
 def zoomOut(self):
     i = LerpFunc(self.setZoom, fromData = self.ZOOMLEVEL, toData = self.ZOOMLEVEL*1.3, duration = 1.0,blendType = "easeInOut")
     i.start()
class RepairPumpingGame(RepairMincroGame):
    pumpDownSounds = None
    pumpUpSounds = None
    pumpGoodSounds = None
    pumpBadSounds = None
    
    def __init__(self, repairGame):
        self.config = RepairGlobals.Pumping
        RepairMincroGame.__init__(self, repairGame, 'pumping', PLocalizer.Minigame_Repair_Pumping_Start)

    
    def _initVars(self):
        RepairMincroGame._initVars(self)
        self.pumpRate = 0.0
        self.remainingWater = 1.0
        self.chainCount = 0
        self.barDirection = UP
        self.goalIndex = TOP
        self.currentBarRate = self.config.barStartRange[0]
        self.hitRange = self.config.hitRange[0]
        self.barPercent = 0.0
        self.failedPercentAndDirection = (-1.0, UP)

    
    def _initAudio(self):
        RepairMincroGame._initAudio(self)
        if not self.pumpDownSounds:
            RepairPumpingGame.pumpDownSounds = (loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_DOWN01), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_DOWN02), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_DOWN03))
            RepairPumpingGame.pumpUpSounds = (loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_UP01), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_UP02), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_UP03))
            RepairPumpingGame.pumpGoodSounds = (loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD01), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD02), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD03), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD04), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD05), loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_GOOD06))
            RepairPumpingGame.pumpBadSounds = (loadSfx(SoundGlobals.SFX_MINIGAME_REPAIR_PUMP_BAD),)
        

    
    def _initVisuals(self):
        RepairMincroGame._initVisuals(self)
        self.model = loader.loadModel('models/gui/pir_m_gui_srp_pumping_main')
        self.visual = self.attachNewNode('visual')
        self.visual.setPos(-0.25, 0.0, 0.074999999999999997)
        goalTopLoc = self.model.find('**/locator_top')
        goalTopLoc.reparentTo(self.visual)
        goalBottomLoc = self.model.find('**/locator_bottom')
        goalBottomLoc.reparentTo(self.visual)
        self.goalPositions = (goalBottomLoc.getPos(self), goalTopLoc.getPos(self))
        self.greatLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Great, text_fg = (0.20000000000000001, 0.80000000000000004, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ACenter, text_font = PiratesGlobals.getPirateFont(), relief = None, text_shadow = (0.0, 0.0, 0.0, 1.0), scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.46500000000000002, 0.0, 0.0), parent = self)
        self.failLabel = DirectLabel(text = PLocalizer.Minigame_Repair_Pumping_Fail, text_fg = (0.80000000000000004, 0.20000000000000001, 0.29999999999999999, 1.0), text_pos = (0.0, 0.59999999999999998), text_align = TextNode.ARight, text_font = PiratesGlobals.getPirateFont(), text_shadow = (0.0, 0.0, 0.0, 1.0), relief = None, scale = (0.080000000000000002, 0.080000000000000002, 0.080000000000000002), pos = (-0.625, 0.0, 0.0), parent = self)
        self.shipBackground = self.model.find('**/static_ship_background')
        self.shipBackground.reparentTo(self.visual)
        self.waterMeter = self.model.find('**/sprite_waterBottom')
        self.waterMeter.reparentTo(self.visual)
        self.waterTop = self.model.find('**/sprite_waterTop')
        self.waterTop.reparentTo(self.visual)
        self.waterMeterTopLoc = self.waterMeter.find('**/locator_topOfShipWater')
        self.pumpBackground = self.model.find('**/pumpBackground')
        self.pumpBackground.reparentTo(self.visual)
        self.pumpWaterTop = self.model.find('**/sprite_pumpWaterTop')
        self.pumpWaterTop.reparentTo(self.visual)
        self.pumpWaterBottom = self.model.find('**/sprite_pumpWaterBottom')
        self.pumpWaterBottom.reparentTo(self.visual)
        self.pumpWaterTopLoc = self.pumpWaterBottom.find('**/locator_topOfPumpWater')
        self.pumpHandle = self.model.find('**/sprite_handle')
        self.pumpHandle.reparentTo(self.visual)
        self.pumpBar = self.model.find('**/static_pump')
        self.pumpBar.reparentTo(self.visual)
        self.goalBox = self.model.find('**/sprite_clickField')
        self.goalBox.reparentTo(self.visual)
        self.goalBox.setTransparency(1)
        self.enableGoalBox()
        self.pumpLine = self.model.find('**/sprite_bar')
        self.pumpLine.reparentTo(self.visual)
        self.ghostLine = self.visual.attachNewNode('ghostLine')
        self.pumpLine.getChild(0).copyTo(self.ghostLine)
        self.ghostLine.setScale(self.pumpLine.getScale())
        self.ghostLine.setColor(1.0, 0.20000000000000001, 0.20000000000000001, 1.0)
        self.shipForground = self.model.find('**/static_ship_foreground')
        self.shipForground.reparentTo(self.visual)
        cm = CardMaker('cardMaker')
        cm.setFrame(-0.33000000000000002, 0.33000000000000002, 0.0, 1.0)
        self.goalBox.setZ(self.goalPositions[TOP].getZ())
        self.goalBoxStartScale = self.goalBox.getSz()
        self.enableGoalBox()
        self.pumpWaterUpLerp = LerpFunc(self.setPumpWater, fromData = -0.10000000000000001, toData = 1.0, duration = 0.5)
        self.pumpWaterDownLerp = LerpFunc(self.setPumpWater, fromData = 1.0, toData = -0.10000000000000001, duration = 0.5)
        self.model.removeNode()
        del self.model

    
    def destroy(self):
        del self.goalPositions
        self.pumpBar.removeNode()
        self.pumpLine.removeNode()
        self.goalBox.removeNode()
        self.pumpHandle.removeNode()
        self.waterMeter.removeNode()
        self.waterTop.removeNode()
        self.ghostLine.removeNode()
        self.shipBackground.removeNode()
        self.shipForground.removeNode()

    
    def reset(self):
        RepairMincroGame.reset(self)
        self.remainingWater = WATER_LEVEL_START
        self.chainCount = 0
        self.barDirection = UP
        self.goalIndex = TOP
        self.barPercent = 0.0
        self.failedPercentAndDirection = (-1.0, UP)
        actualZ = self.goalPositions[BOTTOM].getZ()
        actualZ -= self.visual.getZ()
        self.pumpLine.setZ(actualZ)
        self.setGoalIndex(TOP)
        self.pumpHandle.setR(ROTATION_MIN)
        self.waterMeter.setSz(WATER_LEVEL_START)
        self.waterTop.setZ(self.waterMeterTopLoc.getZ(self.visual))
        self.ghostLine.stash()
        self.setPumpWater(1.0)
        self.failLabel.stash()
        self.greatLabel.stash()
        self.repairGame.gui.setTutorial(self.name)
        self.repairGame.gui.setTitle(self.name)

    
    def setDifficulty(self, difficulty):
        RepairMincroGame.setDifficulty(self, difficulty)
        percent = difficulty / self.repairGame.difficultyMax
        dif = self.config.pumpPowerRange[0] - self.config.pumpPowerRange[1]
        self.pumpRate = self.config.pumpPowerRange[0] - dif * percent
        dif = self.config.barStartRange[0] - self.config.barStartRange[1]
        self.currentBarRate = self.config.barStartRange[0] - dif * percent
        dif = self.config.hitRange[0] - self.config.hitRange[1]
        self.hitRange = self.config.hitRange[0] - dif * percent
        self.goalBox.setSz((self.hitRange / 0.17999999999999999) * self.goalBoxStartScale)

    
    def setGoalIndex(self, goalIndex):
        self.goalIndex = goalIndex
        self.goalBox.setZ(self, self.goalPositions[goalIndex].getZ())
        self.goalBox.setR(180 * (goalIndex - 1))

    
    def resetFail(self):
        self.failedPercentAndDirection = (-1.0, UP)
        self.enableGoalBox()
        self.hideMarkers()

    
    def updateTask(self, task):
        dt = globalClock.getDt()
        percentTimeThisStep = dt / (self.currentBarRate + self.config.barSpeedMax)
        self.barPercent = self.barPercent + percentTimeThisStep * self.barDirection
        if self.failedPercentAndDirection[0] >= 0.0:
            if self.failedPercentAndDirection[1] != self.barDirection:
                if self.failedPercentAndDirection[0] * self.barDirection < self.barPercent * self.barDirection:
                    self.resetFail()
                
            
        
        if self.barPercent >= 1.0:
            self.barPercent = 1.0
            self.barDirection = DOWN
            if not self.isLineInBox():
                self.chainCount = 0
            
            if self.failedPercentAndDirection[0] < 0.5:
                self.resetFail()
            
        elif self.barPercent <= 0.0:
            self.barPercent = 0.0
            self.barDirection = UP
            if not self.isLineInBox():
                self.chainCount = 0
            
            if self.failedPercentAndDirection[0] > 0.5:
                self.resetFail()
            
        
        actualZ = self.goalPositions[0].getZ() + (self.goalPositions[1].getZ() - self.goalPositions[0].getZ()) * self.barPercent
        actualZ -= self.visual.getZ()
        self.pumpLine.setZ(actualZ)
        return Task.cont

    
    def enableGoalBox(self):
        self.goalBox.setColor(0.20000000000000001, 1.0, 0.20000000000000001, 0.59999999999999998)
        self.goalBoxEnabled = 1

    
    def disableGoalBox(self):
        self.goalBox.setColor(1.0, 0.20000000000000001, 0.20000000000000001, 0.29999999999999999)
        self.goalBoxEnabled = 0

    
    def isLineInBox(self):
        if self.goalIndex == TOP:
            return self.barPercent >= 1.0 - self.hitRange
        else:
            return self.barPercent <= self.hitRange

    
    def onMouseClick(self):
        if self.isLineInBox() and self.goalBoxEnabled == 1:
            actualPumpAmount = self.pumpRate + self.config.chainMultiplier * self.chainCount * self.pumpRate
            actualPumpAmount *= WATER_LEVEL_START - WATER_LEVEL_DONE
            self.remainingWater -= actualPumpAmount
            self.remainingWater = max(0.0, self.remainingWater)
            self.waterMeter.setSz(self.remainingWater)
            self.waterTop.setZ(self.waterMeterTopLoc.getZ(self.visual) - 0.001)
            if self.barPercent > 0.5:
                self.pumpWaterDownLerp.duration = self.currentBarRate
                self.pumpWaterDownLerp.start()
                self.barDirection = DOWN
                self.pumpHandle.setR(ROTATION_MAX)
                random.choice(self.pumpDownSounds).play()
            else:
                self.pumpWaterUpLerp.duration = self.currentBarRate
                self.pumpWaterUpLerp.start()
                self.barDirection = UP
                self.pumpHandle.setR(ROTATION_MIN)
                random.choice(self.pumpUpSounds).play()
            if self.barPercent > 0.5:
                self.setGoalIndex(BOTTOM)
            else:
                self.setGoalIndex(TOP)
            self.currentBarRate /= self.config.barSpeedIncrease
            self.chainCount += 1
            self.setSuccessMarker()
            if self.remainingWater <= WATER_LEVEL_DONE and self.barDirection == DOWN:
                self.remainingWater = 0.0
                self.request('Outro')
                return None
            
            totalRange = WATER_LEVEL_START - WATER_LEVEL_DONE
            current = WATER_LEVEL_START - self.remainingWater
            percent = min(100, int((current / totalRange) * 100))
            self.repairGame.d_reportMincroGameProgress(percent, max(0, min(5, self.chainCount) - 1))
        else:
            self.disableGoalBox()
            self.currentBarRate /= self.config.barSpeedDecrease
            self.currentBarRate += (1 - self.config.barSpeedDecrease) * self.config.barSpeedMin
            self.currentBarRate = min(self.currentBarRate, self.config.barSpeedMin)
            self.setFailMarker()
            self.chainCount = 0
            self.failedPercentAndDirection = (self.barPercent, self.barDirection)

    
    def setPumpWater(self, value):
        self.pumpWaterBottom.setSz(value)
        self.pumpWaterTop.setZ(self.pumpWaterTopLoc.getZ(self.visual))

    
    def setSuccessMarker(self):
        self.greatLabel.setZ(self.pumpLine.getZ())
        self.greatLabel.unstash()
        pumpSoundIndex = min(len(self.pumpGoodSounds) - 1, self.chainCount / 2)
        self.pumpGoodSounds[pumpSoundIndex].play()

    
    def setFailMarker(self):
        self.hideMarkers()
        self.ghostLine.setPos(self.pumpLine.getPos())
        self.ghostLine.unstash()
        self.failLabel.setZ(self.pumpLine.getZ())
        self.failLabel.unstash()
        random.choice(self.pumpBadSounds).play()

    
    def hideMarkers(self):
        self.ghostLine.stash()
        self.greatLabel.stash()
        self.failLabel.stash()

    
    def enterGame(self):
        RepairMincroGame.enterGame(self)
        taskMgr.add(self.updateTask, 'RepairPumpingGame.updateTask')
        self.accept('mouse1', self.onMouseClick)
        self.enableGoalBox()

    
    def exitGame(self):
        RepairMincroGame.exitGame(self)
        taskMgr.remove('RepairPumpingGame.updateTask')
        self.ignore('mouse1')

    
    def enterOutro(self):
        RepairMincroGame.enterOutro(self)
        self.repairGame.d_reportMincroGameScore(150)
Beispiel #38
0
    def rotateCube(self,direction):
        """
        rotates the cube according to the direction passed as first argument. accepted values are "up" "down" "left" "right"
        """
        #first check if we are allowed to move the block at all..
        if self.isAnimated() : 
            print "canceling rotation of cube"
            return
            
        #cleaning up from last rotation (we cant clean those up at the end of this function cause the interval needs the dummynode for rotation)
        self.cube.wrtReparentTo(render)
        try:
            dummy.remove_node()
        except:
            pass

        self.setAnimated(True)
        duration = 0.2
        x1,y1,x2,y2 = self.getCubeTiles()
        
        self.level.animateTile(x1,y1)
        self.level.animateTile(x2,y2)
        
        dummy = render.attachNewNode("dummy")
        dummy.reparentTo(self.cube)
        dummy.setZ(render,0)
        dummy.wrtReparentTo(render)
        dummy.setHpr(0,0,0)
        dest_hpr = Vec3(0)
            
        if self.cube.getZ(render) > .7:
            #case1 : cube is standing upright
            #ok... since we rotate relative there are rounding errors... since there !might! be some uebernoob playing the game
            #needing one gazillion rotations to reach the goal it might happen those rounding errors actually get visible
            #so let him enjoy and reset the cube every-time it's standing straight-up.
            
            self.cube.setZ(render,1) #how comes this is one?.. well.. i know.. because of my learnings..
            self.cube.setX(render, round(self.cube.getX(render),0)  )
            self.cube.setY(render, round(self.cube.getY(render),0)  )
            self.cube.setH(render, round(self.cube.getH(render),0)  )
            self.cube.setP(render, round(self.cube.getP(render),0)  )
            self.cube.setR(render, round(self.cube.getR(render),0)  )


            if direction == "right":
                dummy.setY(dummy,.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, -90, 0)
                self.setCubeTiles( x1, y1+1 ,x1 , y1+2 )
                
            if direction == "left":
                dummy.setY(dummy,-.5)
                self.cube.wrtReparentTo(dummy)
                dest_hpr = Vec3(0, 90, 0)
                self.setCubeTiles( x1, y1-2 ,x1 , y1-1 )
               
            if direction == "up":
                dummy.setX(dummy,-.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, -90)
                self.setCubeTiles( x1-2, y1 ,x1-1 , y1 )
                            
            if direction == "down":
                dummy.setX(dummy,.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, 90)
                self.setCubeTiles( x1+1, y1 ,x1+2 , y1 )          
            
        elif x1 == x2 :  #if aligned to y-axis
            if direction == "right":
                dummy.setY(dummy,1)
                self.cube.wrtReparentTo(dummy)
                dest_hpr = Vec3(0, -90, 0)
                self.setCubeTiles( x1, y1+2  )

            if direction == "left":
                dummy.setY(dummy,-1)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 90, 0)
                self.setCubeTiles( x1, y1-1)

            if direction == "up":
                dummy.setX(dummy,-.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, -90)
                self.setCubeTiles( x1-1, y1, x2-1, y2 )
                
            if direction == "down":
                dummy.setX(dummy,.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, 90)
                self.setCubeTiles( x1+1, y1, x2+1, y2 )


        elif y1==y2 : #if it is alligned to x-axis..

            if direction == "right":
                dummy.setY(dummy,.5)
                self.cube.wrtReparentTo(dummy)
                dest_hpr = Vec3(0, -90, 0)
                self.setCubeTiles( x1, y1+1, x2, y2+1 )
                
            if direction == "left":
                dummy.setY(dummy,-.5)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 90, 0)
                self.setCubeTiles( x1, y1-1, x2, y2-1 )
            
            if direction == "up":
                dummy.setX(dummy,-1)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, -90)
                self.setCubeTiles( x1-1, y1  )
                
            if direction == "down":
                dummy.setX(dummy,1)
                self.cube.wrtReparentTo(dummy) 
                dest_hpr = Vec3(0, 0, 90)
                self.setCubeTiles( x1+2, y1  )

        else:
            print("Invalid move. Waiting ..")


        print("Rotating!")
        anim = self.animate( LerpHprInterval(dummy, duration, dest_hpr,(0,0,0) ) )

        
        #this sorta.. doesnt belong here.. but i dunno where to put it yet.
        x1,y1,x2,y2 = self.getCubeTiles()
        # self.level.tintTile(x1,y1) #this is fun to play with if your cube is invisible...
        # self.level.tintTile(x2,y2)
        self.level.stopAnimatedTile(x1,y1) #stops the tile-animation for the tiles below the block
        self.level.stopAnimatedTile(x2,y2)
        
        #cheking what consequences your move had... muhahaa... if you get a 1 .. i've got bad news for you
        checkresult = checkMove(self.level.levelNode,self.getCubeTiles(),self.sounds)
        if checkresult == 1:
            self.falls +=1
            self.moves +=1

            # Force to the corner when the cuboid falls down
            side_force = 1.7

            force = Vec3(0, 0, 0)
            if direction == "up":
                force = Vec3(-side_force, 0, 0)
            elif direction == "down":
                force = Vec3(side_force, 0, 0)
            elif direction == "left":
                force = Vec3(0, -side_force, 0)
            elif direction == "right":
                force = Vec3(0, side_force, 0)

            dummy.set_hpr(render, Vec3(0, 0, 0))

            del anim

            self.setAnimated(True)
            final_hpr = dest_hpr * 3.0 + Vec3(random(), random(), random()) * 360.0 * 0.0
            anim = LerpFunc(self.animateCube, fromData=0, toData=1, duration=1.3, blendType='noBlend', extraArgs=[dummy.get_pos(render), Vec3(0), final_hpr, dummy, force])
            taskMgr.doMethodLater( anim.getDuration(), self.resetCube , "resetTask")

        elif checkresult == 2:

            #ok.. once reached the goal, move the block down, fading it out. thenload the new level etc.
            anim.pop()
            anim.append( Func(lambda: self.level.fadeOutLevel() ) )

            Sequence(Wait(0.3), Func(lambda *args: self.cube.hide())).start()

            taskMgr.doMethodLater( anim.getDuration()+2 , self.levelUp , "lvlup")
            taskMgr.doMethodLater( anim.getDuration()+2 , lambda *args: self.cube.show(), "show cube")
            taskMgr.doMethodLater( anim.getDuration()+2 , lambda *args: self.shard_node.node().remove_all_children(), "clear shards")
            
            Sequence(Wait(0.2), Func(lambda *args: self.sounds.playSound("finish.wav"))).start()

            self.moves = 0
            self.falls = 0

            cube_min, cube_max = Vec3(-0.5, -0.5, -1), Vec3(0.5, 0.5, 1)
            self.shard_node.set_pos(dummy.get_pos(render) + Vec3(-0.5, 0, 0))
            shard_size = (cube_max - cube_min) / 5.0

            self.shard_node.hide()
            Sequence(Wait(0.22), Func(lambda *args: self.shard_node.show())).start()

            for i in range(5):
                for j in range(5):
                    for k in range(5):
                        shard = loader.loadModel("models/CubeShard.bam")
                        shard.reparent_to(self.shard_node)
                        shard.set_x(i * shard_size.x + 0.1)
                        shard.set_y(j * shard_size.y + 0.1)
                        shard.set_z(k * shard_size.z + 0.2)
                        shard.set_scale(0.8 + random())

                        force = Vec3(i-2 - 0.15, j-2 - 0.15, k-2 + 2.6)
                        force.normalize()
                        force *= 12.0 * (1 + random() * 0.5)

                        d_hpr = Vec3(random(), random(), random()) * 360.0 * (3.0 + random())

                        shard_anim = Sequence(
                            Wait(0.22),
                            LerpFunc(self.animateShard, fromData=0, toData=2, duration=2.0, blendType='noBlend', extraArgs=[shard.get_pos(), d_hpr, shard, force]),
                            LerpHprInterval(shard, 1.0 + random(), d_hpr * 1.6, d_hpr, blendType='noBlend'),
                        )
                        shard_anim.start()

        elif checkresult == 0:
            #how lame... just a ..move..
            print "playing sound"
            self.moves += 1
            self.sounds.playSound("stonerotate.wav")
        print "moves:",self.moves ,"  falls:",self.falls
        #last but not least.. we start the animation .. did you know that the pc knows you'r failing before you actually do? .. scary..
        anim.start()
Beispiel #39
0
class SogalText(NodePath):
    '''
    A text label, contains many TextLines
    '''
    def __init__(self,
                 parent = None,
                 pos = (0,0,0),
                 text = u'',
                 wordwrap = None, 
                 maxRows = None, 
                 spacing = 0,
                 lineSpacing = 0,
                 minLineHeight = 0.5,
                 font = None,
                 fg = (1,1,1,1),
                 scale = 0.07, 
                 shadow = None,
                 shadowOffset = (0.04, 0.04),
                 textScale = None,
                 ):
        '''
        Constructor
        :param parent: parent NodePath
        :param text: text
        :param font: font of the text
        :param wordwrap: set the width when wraping the word (note that )
        :param maxRows: max row of the text
        :param spacing: spacing of words
        :param lineSpacing: spacing of lines
        :param minLineHeight: height of a line when it is empty
        :param fg: foreground color
        :param scale: scale of the text
        :param shadow: shadow color of the text
        :param shadowOffset: shadow offset of the text
        '''
        self.destroyed = False
        self.__parent = parent or aspect2d
        self.__lerpLock = Lock()
        self.__font = font
        self.__currentLerpInterval = None
        self.wordwrap = wordwrap
        self.lines = []
        self.spacing = spacing
        self.lineSpacing = lineSpacing
        self.minLineHeight = minLineHeight
        
        self.maxRows = maxRows
        
        self.recordedText = [] #recorder text sections used in backup
        
        NodePath.__init__(self,'')
        self.setScale(scale)
        self.setPos(pos)
        
        self.currentHeight = 0
        
        
        self.reparentTo(self.__parent)  # @UndefinedVariable
        
        self.textMaker = TextNode('textMaker')
        if font:
            self.setFont(font, specNode = None)
        if fg:
            self.setFg(fg, specNode = None)
        if shadow:
            self.setShadow(shadow, shadowOffset, specNode = None)
        if textScale:
            self.setTexScale(textScale,specNode = None)
        
        self.textMaker.setAlign(TextNode.ALeft)
        
        if shadow:
            pass
        if text:
            self.appendText(text)
            
    def destroy(self):
        if self.__currentLerpInterval:
            self.__currentLerpInterval.pause()
        self.clear()
        if not self.destroyed:
            self.destroyed = True
        self.textMaker = None
        self.recordedText = None
        self.removeNode()
        
    def clear(self):
        if self.__currentLerpInterval:
            self.__currentLerpInterval.pause()
        self.currentHeight = 0
        for tl in self.lines:
            tl.removeNode()
        self.lines = []
        self.recordedText = []
    
    def setFg(self, fg, specNode = None):
        node = specNode or self.textMaker
        node.setTextColor(fg[0], fg[1], fg[2], fg[3])
        
    def setFont(self,font, specNode = None):
        node = specNode or self.textMaker
        node.setFont(font)
        
    def setShadow(self, shadow, offset = (0.04, 0.04), specNode = None):
        node = specNode or self.textMaker

        if shadow[3] != 0:
            node.setShadowColor(shadow[0], shadow[1], shadow[2], shadow[3])
            node.setShadow(offset)
        else:
            node.clearShadow()
            
    def setTextScale(self, scale , specNode = None):
        node = specNode or self.textMaker
        node.setTextScale(scale)
        
    def setMaxRows(self,maxrows):
        self.maxRows = maxrows
    
    def setWordwrap(self,wordwrap):
        self.wordwrap = wordwrap
        
    def setMinLineHeight(self,minLineHeight):
        self.minLineHeight = minLineHeight
        
    
    
    def appendText(self, text,speed = 0, fadein = 0, fadeinType = 0, newLine = False,
                   custom = False, font = None, textScale = 1, fg = (1,1,1,1), 
                   shadow = None, shadowOffset = (0.04, 0.04), **kwargs):
        textprops = dict(text = text,newLine = newLine, custom = custom, font = font, textScale = textScale, fg = fg, 
                 shadow = shadow, shadowOffset = shadowOffset, **kwargs)
        
        self.recordedText.append(textprops)
        
        self.appendStoredText(textprops, speed, fadein, fadeinType)
            

            
    def appendStoredText(self,textprops, speed = 0, fadein = 0, fadeinType = 0):
        #append a text stored with appendText() or by loading self.recordedText
        text = textprops['text']
        newLine = textprops['newLine']
        custom = textprops['custom']
        if custom:
            textMaker = TextNode('temptextmaker', self.textMaker)
            font = textprops['font']
            if font:
                textMaker.setFont(font)
            textScale = textprops['textScale']
            if textScale:
                textMaker.setTextScale(textScale)
            fg = textprops['fg']
            if fg:
                self.setFg(fg, textMaker)
            shadow = textprops['shadow']
            shadowOffset = textprops['shadowOffset']
            if shadow:
                self.setShadow(shadow, shadowOffset, textMaker)
            
            #prepared to add more props here
            
        else: textMaker = self.textMaker
        
        
        if newLine or not self.lines:
            self.startLine()

        if not speed:
            for word in text:
                self.appendWord(word, tm = textMaker, fadein = fadein, fadeinType = fadeinType)
        #TYPER EFFECT
        else:
            self.__TextLerpInit()
            self.__currentLerpInterval = LerpFunc(self._appendTextLerpFunc,extraArgs = [text,textMaker,fadein,fadeinType],
                                                  duration = len(text)/float(speed))
            self.__currentLerpInterval.start()
                
    def __TextLerpInit(self):
        if self.__currentLerpInterval:
            self.__currentLerpInterval.finish()
        self.__lerpLock.acquire()
        self.__lastTextLerpValue = 0
        self.__lerpLock.release()
                
    def _appendTextLerpFunc(self, lerp, text, tm, fadein, fadeinType):
        '''The function interval method for typer effect'''
        self.__lerpLock.acquire()
        tlen = len(text)
        start = int(math.floor(self.__lastTextLerpValue * tlen))
        end = int(math.floor(lerp * tlen))
        if end > start:
            appendingText = text[start:end]
            for word in appendingText:
                self.appendWord(word, tm, fadein = fadein, fadeinType = fadeinType)
        self.__lastTextLerpValue = lerp
        self.__lerpLock.release()
        
    def isWaiting(self):
        if self.__currentLerpInterval:
            return self.__currentLerpInterval.isPlaying()
        return False
    
    def quickFinish(self):
        if self.__currentLerpInterval:
            return self.__currentLerpInterval.finish()
        for l in self.lines:
            l.quickFinish()       

            
    def appendWord(self,word,tm = None, fadein = 0, fadeinType = 0):
        if word == '\n':
            self.startLine()
            return
        
        textMaker = tm or self.textMaker
        if not self.lines:
            self.startLine()
        
        active_line = self.lines[-1] 
        
        unicodeText = isinstance(word, types.UnicodeType)
        if unicodeText:
            textMaker.setWtext(word)
        else:
            textMaker.setText(word)
            
        width = textMaker.getWidth()
        height = textMaker.getHeight()
        node = textMaker.generate()
        textpath = NodePath('text_path')
        textpath.attachNewNode(node)
        if self.wordwrap:
            if active_line.getTotalWidth() + width > self.wordwrap:
                self.startLine()
                active_line = self.lines[-1]
        
        active_line.append(textpath, width, height,self.spacing, fadein = fadein, fadeinType = fadeinType)
        active_line.setPos(0,0,-(self.currentHeight + active_line.getLineHeight()) )
          
    def startLine(self):
        if self.lines:
            self.currentHeight += self.lines[-1].getLineHeight() + self.lineSpacing 
        line = TextLine(parent = self, height = self.minLineHeight)
        line.setPos(0,0,-self.currentHeight)
        self.lines.append(line)
    
    def removeNode(self, *args, **kwargs):
        return NodePath.removeNode(self, *args, **kwargs)
            
    def getCurrentText(self):
        return self.recordedText
    
    def getCopiedText(self):
        return copy.deepcopy(self.recordedText)
    
    def loadRecordedText(self,recorded):
        for section in recorded:
            self.appendStoredText(section)
        self.recordedText = copy.copy(recorded)
            
    def getNewText(self):
        if self.recordedText:
            return self.recordedText[0]['text']
        return ''
        
    def getEndPos(self):
        if self.lines:
            return (self.lines[-1].getEndPos()[0],0 , -(self.currentHeight + self.lines[-1].getLineHeight()))
        else: return (0,0,0)
        
    def hasContent(self):
        "get if this text label empty"
        return bool(self.lines)