Exemple #1
0
    def loadGUI(self):
        self.vidas_imgs = list()
        w = 0.24
        for i in range(self.VIDAS):
            image_warning = OnscreenImage(
                image='../data/Texture/signal_warning.png',
                pos=(-1 + i * w, 0, 0.85),
                parent=self._playing_node2d)
            image_warning.setScale(0.1)
            image_warning.setTransparency(TransparencyAttrib.MAlpha)
            image_warning.hide()

            image_ok = OnscreenImage(image='../data/Texture/signal_ok.png',
                                     pos=(-1 + i * w, 0, 0.85),
                                     parent=self._playing_node2d)
            image_ok.setScale(0.1)
            image_ok.setTransparency(TransparencyAttrib.MAlpha)
            image_ok.show()
            self.vidas_imgs.append((image_ok, image_warning))

        self._level_time_O = OnscreenText(text='',
                                          pos=(0, 0.85),
                                          scale=0.14,
                                          fg=(1.0, 1.0, 1.0, 1.0),
                                          bg=(0.0, 0.0, 0.0, 1.0),
                                          parent=self._playing_node2d)
Exemple #2
0
class HUD(DirectObject):
    def __init__(self):

        self.winXhalf = base.win.getXSize() / 2
        self.winYhalf = base.win.getYSize() / 2

        croshairsize = 0.05#17.0

        self.crosshair = OnscreenImage(
            image = os.path.join("..", "data", "crosshair.png"),
            scale = (croshairsize, 1, croshairsize),
            #pos = (self.winXhalf - croshairsize/2.0, 0, -self.winYhalf - croshairsize/2.0)
            pos = (0, 0, 0)
            )
        self.crosshair.setTransparency(1)

        self.ammo = DirectLabel(
            scale = 0.15,
            text = "100/100",
            pos = (base.a2dLeft + 0.025, 0.0, base.a2dBottom + 0.05),
            text_align = TextNode.ALeft,
            frameColor = (0, 0, 0, 0),
            text_fg = (1,1,1,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (0.05, 0.05)
            )
        self.ammo.setTransparency(1)

        self.nowPlaying = DirectLabel(
            scale = 0.05,
            text = "Now Playing: Echovolt - Nothing to Fear",
            pos = (base.a2dLeft + 0.025, 0.0, base.a2dTop - 0.05),
            text_align = TextNode.ALeft,
            frameColor = (0, 0, 0, 0),
            text_fg = (1,1,1,1)
            )
        self.nowPlaying.setTransparency(1)

        self.accept("window-event", self.recalcAspectRatio)
        self.hide()

    def show(self):
        self.crosshair.show()
        self.nowPlaying.show()
        self.ammo.show()

    def hide(self):
        self.crosshair.hide()
        self.nowPlaying.hide()
        self.ammo.hide()

    def updateAmmo(self, maxAmmo, ammo):
        self.ammo["text"] = "%02d/%02d" % (maxAmmo, ammo)

    def recalcAspectRatio(self, window):
        self.ammo.setPos(base.a2dLeft + 0.025, 0.0, base.a2dBottom + 0.05)
        self.ammo.setPos(base.a2dLeft + 0.025, 0.0, base.a2dTop - 0.05)
Exemple #3
0
class LifebarUI(UIBase):
    def __init__(self,world):
        UIBase.__init__(self,world)

        
        #self.mainChar = world.hero
        
        self.liferoundImage = DirectFrame(image='./LEGameAssets/Textures/health_tray.png',
                                            pos = (1.34,0,-1), scale = (1.34,1,1),
                                            frameColor = (1,1,1,0))
        self.lifebarImage = OnscreenImage(image='./LEGameAssets/Textures/lifebar.png', 
                                          pos = (0.285,0,-0.125),scale=(0.215, 1, 0.026))
        self.liferoundImage.setTransparency(1)
        
        self.liferoundImage.reparentTo(base.a2dTopLeft)
        self.lifebarImage.reparentTo(base.a2dTopLeft)
        self.entirelife = self.world.hero.getMaxHealth()
        #self.accept("a", self.update)
        #self.accept("s", self.reset)
        #self.update()
        
    def update(self):    
        self.life = self.world.hero.getHealth()
        self.lifebarupdate(self.entirelife, self.life)
        #self.accept("a", self.lifebarupdate)
        #self.accept("s", self.hide)
        #self.accept("d", self.show)
       # print "lifebar"
       #pass
        
    def lifebarupdate(self, entirelife, life):
        #entirelife = 100
        #self.life = self.life-10
        if life>0:
            self.lifebarImage['scale'] = (float(life)/entirelife*0.215,1,0.026)
            self.lifebarImage['pos'] = (0.285-(1-float(life)/entirelife)*0.215,0,-0.125)
        else:
            self.lifebarImage.hide()
    
    def reset(self):
        self.life = self.world.hero.getMaxHealth()
        self.lifebarImage['scale'] = (0.215, 1, 0.026)
        self.lifebarImage['pos'] = (0.285,0,-0.125)
        self.lifebarImage.show()
        
    def hide(self):
        self.liferoundImage.hide()
        self.lifebarImage.hide()
        
    def show(self):
        self.liferoundImage.show()
        self.lifebarImage.show()
        
#w = LifebarUI()
#run()
Exemple #4
0
class English(HUDElement):
    def __init__(self):
        HUDElement.__init__(self)
        self.dir = ani.model_dir / 'hud' / 'english'
        self.text_scale = 0.2
        self.text_color = (1, 1, 1, 1)

        self.circle = OnscreenImage(image=panda_path(self.dir / 'circle.png'),
                                    parent=self.dummy_right,
                                    scale=0.15)
        self.circle.setTransparency(TransparencyAttrib.MAlpha)
        autils.alignTo(self.circle, self.dummy_right, autils.CL, autils.C)
        self.circle.setZ(-0.65)

        self.crosshairs = OnscreenImage(image=panda_path(self.dir /
                                                         'crosshairs.png'),
                                        pos=(0, 0, 0),
                                        parent=self.circle,
                                        scale=0.14)
        self.crosshairs.setTransparency(TransparencyAttrib.MAlpha)

        self.text = OnscreenText(
            text="(0.00, 0.00)",
            pos=(0, -1.15),
            scale=self.text_scale,
            fg=self.text_color,
            align=TextNode.ACenter,
            mayChange=True,
            parent=self.circle,
        )

    def set(self, a, b):
        self.crosshairs.setPos(-a, 0, b)
        self.text.setText(f"({a:.2f},{b:.2f})")

    def init(self):
        self.show()

    def show(self):
        self.circle.show()

    def hide(self):
        self.circle.hide()

    def destroy(self):
        self.hide()
        del self.text
        del self.crosshairs
        del self.circle
Exemple #5
0
class Switches(ServiceScreenBase):
    def __init__(self, screen_manager):
        super(Switches, self).__init__(screen_manager, "Switch Test")

        self.current_switch = OnscreenText(
            "",
            1,
            fg=(1, 1, 1, 1),
            pos=(-1.3, 0.60),
            align=TextNode.ALeft,
            scale=.10,
            mayChange=True,
            # font = base.fontLoader.load('Arial Bold.ttf'),
            parent=self.node2d)
        self.switches = OnscreenImage(parent=self.node2d,
                                      image="assets/images/switch_matrix.jpg",
                                      scale=(1, 1, 0.8))
        # Size
        # (0.15, 0, 0.174)
        self.switch_active = OnscreenImage(
            parent=self.node2d,
            image="assets/images/switch_active.png",
            scale=(0.075, 0.1, 0.087),
            pos=(-0.456, 0, 0.52156))
        self.switch_active.setTransparency(TransparencyAttrib.MAlpha)

    def set_active(self, swnum):
        swnum = swnum - 11
        base_pos = (-0.456, 0, 0.52156)
        pos = (base_pos[0], 0, base_pos[2] - (swnum * 0.174) + 0.005)
        self.switch_active.setPos(pos)

    def img_size(self, model):
        min, max = model.getTightBounds()
        return max - min

    def set_switch(self, text):
        self.current_switch.setText(text)

    def show(self):
        super(Switches, self).show()
        self.switches.show()
        self.switch_active.show()

    def hide(self):
        super(Switches, self).hide()
        self.switches.hide()
        self.switch_active.hide()
 def loadGUI(self):
     self.vidas_imgs = list()
     w = 0.24
     for i in range(self.VIDAS):
         image_warning = OnscreenImage(image = '../data/Texture/signal_warning.png', pos=(-1 + i*w, 0, 0.85), parent=self._playing_node2d)
         image_warning.setScale(0.1)
         image_warning.setTransparency(TransparencyAttrib.MAlpha)
         image_warning.hide()
         
         image_ok = OnscreenImage(image = '../data/Texture/signal_ok.png', pos=(-1 + i*w, 0, 0.85), parent=self._playing_node2d)
         image_ok.setScale(0.1)
         image_ok.setTransparency(TransparencyAttrib.MAlpha)
         image_ok.show()
         self.vidas_imgs.append((image_ok, image_warning))
         
     self._level_time_O = OnscreenText(text = '', pos = (0, 0.85), scale = 0.14, fg=(1.0, 1.0, 1.0, 1.0), bg=(0.0, 0.0, 0.0, 1.0), parent=self._playing_node2d)
Exemple #7
0
class Menu:
    def __init__(self):
        self.loadStartMenu()

    def loadStartMenu(self):
        base.setBackgroundColor(0, 0.25, 0.4)

        self.title = OnscreenImage(image=str(MAINDIR) +
                                   '/assets/gui/title.png',
                                   pos=(0, 0, 0.20),
                                   scale=(0.5, 0.5, 0.125))
        self.title.setTransparency(1)

        mapsworld = loader.loadModel("assets/gui/world_maps")
        mapsranking = loader.loadModel("assets/gui/classement_maps")

        self.world_button = DirectButton(
            geom=(mapsworld.find("**/world_ready"),
                  mapsworld.find("**/world_over")),
            frameColor=(0, 0, 0, 0),
            pos=(0.0, 0, -0.40),
            command=base.messenger.send,
            scale=0.35,
            extraArgs=["Menu-Start-World"])
        self.ranking_button = DirectButton(
            geom=(mapsranking.find("**/classement_ready"),
                  mapsranking.find("**/classement_over")),
            frameColor=(0, 0, 0, 0),
            pos=(0, 0, -0.80),
            command=base.messenger.send,
            scale=0.25,
            extraArgs=["Menu-Start-Ranking"])

    def hideStartMenu(self):
        self.world_button.hide()
        self.ranking_button.hide()
        self.title.hide()

    def showStartMenu(self):
        self.world_button.show()
        self.ranking_button.show()
        self.title.show()
Exemple #8
0
    def transition_screen(self, image, time):
        """
        Creates a transition screen. An image is popup while listening to input is set to False
        @param image: the image name
        @param time: the lifetime of the popup.
        """
        new_image = OnscreenImage(
            self.main_screen.image_path + image + ".png",
            parent=self.main_screen.gui_render_node,
            pos=(0, 0, 0),
        )
        new_image.set_bin("fixed", 10)
        new_image.show()
        self._update()

        # hidding on_screen_texts
        for o in self.on_screen_texts:
            self.on_screen_texts[o].hide()

        relisten = False
        if self._listen_to_input:
            self._listen_to_input = False
            relisten = True
            self.lock_text.hide()

        def to_call(relisten):
            if relisten:
                self._listen_to_input = True
                self.lock_text.show()

            new_image.destroy()
            # showing on_screen_texts
            for o in self.on_screen_texts:
                self.on_screen_texts[o].show()

            self._update()

        self.main_screen.gameEngine.taskMgr.doMethodLater(time,
                                                          to_call,
                                                          name="update",
                                                          extraArgs=[relisten])
Exemple #9
0
class LoadIcon:
    """
    A spinning icon.
    """
    def __init__(self, mainScreen, x=0.0, y=0.0):
        self.main_screen = mainScreen
        self._image = OnscreenImage(
            image=self.main_screen.image_path + "load_icon.png",
            pos=(x, 0, y),
            parent=self.main_screen.gameEngine.render2d,
            scale=(0.07, 1, 0.07))
        self._image.setTransparency(TransparencyAttrib.MAlpha)
        self.spin_task = None
        self._image.hide()

    def set_pos(self, x, y):
        """
        Sets the position of the icon
        @param x: the relative x in the screen
        @param y: the relative y in the screen
        """
        self._image.set_r(0)
        self._image.set_pos(x, 0, y)

    def start(self):
        """
        Starts the spinning animation and shows it.
        """
        self._image.set_r(0)
        self._image.show()
        self.spin_task = self._image.hprInterval(duration=2, hpr=(0, 0, 360))
        self.spin_task.loop()

    def stop(self):
        """
        Stops the spinning animation and hides it.
        @return:
        """
        self.spin_task.finish()
        self._image.hide()
Exemple #10
0
class Cursor:
    def __init__(self, path, scale, hotspot):
        if not path:
            return
        self.__set_standard_curson(False)
        self.cursor_img = OnscreenImage(path)
        self.cursor_img.setTransparency(True)
        self.cursor_img.setScale(scale)
        self.cursor_img.setBin('gui-popup', 50)
        self.hotspot_dx = scale[0] * (1 - 2 * hotspot[0])
        self.hotspot_dy = scale[2] * (1 - 2 * hotspot[1])
        eng.event.attach(self.on_frame)

    def __set_standard_curson(self, show):
        props = WindowProperties()
        props.setCursorHidden(not show)
        base.win.requestProperties(props)

    def show(self):
        self.cursor_img.show()

    def show_standard(self):
        self.__set_standard_curson(True)

    def hide(self):
        self.cursor_img.hide()

    def hide_standard(self):
        self.__set_standard_curson(False)

    def cursor_top(self):
        self.cursor_img.reparent_to(self.cursor_img.get_parent())

    def on_frame(self):
        if base.mouseWatcherNode.hasMouse():
            x = base.mouseWatcherNode.getMouseX()
            y = base.mouseWatcherNode.getMouseY()
            h_x = x * base.getAspectRatio() + self.hotspot_dx
            self.cursor_img.setPos(h_x, 0, y - self.hotspot_dy)
Exemple #11
0
class Logo(HUDElement):
    def __init__(self):
        HUDElement.__init__(self)

        self.img = OnscreenImage(image=ani.logo_paths['pt_smaller'],
                                 pos=(0.94, 0, 0.89),
                                 parent=render2d,
                                 scale=(0.08 * 0.49, 1, 0.08))
        self.img.setTransparency(TransparencyAttrib.MAlpha)

    def init(self):
        self.show()

    def show(self):
        self.img.show()

    def hide(self):
        self.img.hide()

    def destroy(self):
        self.hide()
        del self.img
Exemple #12
0
class Gameover:
    def __init__(self,score):
        self.loadMenu(score)

    def loadMenu(self,score):

        mapsparkour = loader.loadModel("assets/gui/retour_maps")
        self.screen=OnscreenImage(image=str(MAINDIR)+'/assets/gui/gameover_screen.png',pos=(0,0,0),scale=(0.65,0.65,0.65))
        self.screen.setTransparency(1)

        self.font = loader.loadFont(str(MAINDIR)+'/assets/fonts/allerdisplay.ttf')
        self.score = OnscreenText(text="{}".format(score), pos=(0,-0.2),scale=0.15, fg=(1, 1, 1, 1), align=TextNode.ACenter,font= self.font)
    

    def hideMenu(self):
        self.gameover_button.hide()
        self.screen.hide()
        self.score.hide()

    def showMenu(self):
        self.screen.show()
        self.gameover_button.show()
        self.score.show()
Exemple #13
0
class TestApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.set_background_color(0.1137, 0.1450, 0.1725)
        self.disable_mouse()
        self.mire = OnscreenImage(image=os.path.join(MAINDIR, 'test.jpeg'))
        self.mire.setScale(1.6, 1, 1)
        self.mire.hide()
        self.is_shown = False

        command_dic = {"toggleImage": self.toggleImage}
        self.commandline = pconsole.Console()
        self.commandline.create(command_dic, app=self, event='f1')
        self.task_mgr.add(self.update, "updatingTask")

    def update(self, task):
        return task.cont

    def toggleImage(self):
        if self.is_shown:
            self.mire.hide()
        else:
            self.mire.show()
        self.is_shown = not self.is_shown
Exemple #14
0
class BSpecial (Bar):
    def __init__(self):
        Bar.__init__(self)
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Init the bar with alpha sprites
        self.cereal = False
        self.specialCereal = OnscreenImage(image="./tex/cereal_not_special.png", pos = (0.43, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1)
        self.specialCereal.setTransparency(TransparencyAttrib.MAlpha)
        
        self.banana = False
        self.specialBanana = OnscreenImage(image="./tex/banana_not_special.png", pos = (0.63, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1)
        self.specialBanana.setTransparency(TransparencyAttrib.MAlpha)
        
        self.cheese = False
        self.specialCheese = OnscreenImage(image="./tex/cheese_not_special.png", pos = (0.83, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1)
        self.specialCheese.setTransparency(TransparencyAttrib.MAlpha)
        
        self.tomato = False
        self.specialTomato = OnscreenImage(image="./tex/tomato_not_special.png", pos = (1.03, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1)
        self.specialTomato.setTransparency(TransparencyAttrib.MAlpha)
        
        self.egg = False
        self.specialEgg= OnscreenImage(image="./tex/egg_not_special.png", pos = (1.23, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1)
        self.specialEgg.setTransparency(TransparencyAttrib.MAlpha)
        
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It makes visible (change alpha sprite) the item corresponding to the type given
    def itemCollected(self,type):
        if type == "GRAIN":
            self.cereal = True
            self.specialCereal.setImage("./tex/cereal_special.png")
            self.specialCereal.setTransparency(TransparencyAttrib.MAlpha)
        if type == "FRUIT":
            self.banana = True
            self.specialBanana.setImage("./tex/banana_special.png")
            self.specialBanana.setTransparency(TransparencyAttrib.MAlpha)
        if type == "MILK":
            self.cheese = True
            self.specialCheese.setImage("./tex/cheese_special.png")
            self.specialCheese.setTransparency(TransparencyAttrib.MAlpha)
        if type == "VEGETABLE":
            self.tomato = True
            self.specialTomato.setImage("./tex/tomato_special.png")
            self.specialTomato.setTransparency(TransparencyAttrib.MAlpha)
        if type == "FISH":
            self.egg = True
            self.specialEgg.setImage("./tex/egg_special.png")
            self.specialEgg.setTransparency(TransparencyAttrib.MAlpha)
    #end itemCollected
    
    # It puts the bar at the same characteristics as its initialization
    def reInit(self):
        self.cereal = False
        self.specialCereal.setImage("./tex/cereal_not_special.png")
        self.specialCereal.setTransparency(TransparencyAttrib.MAlpha)
        
        self.banana = False
        self.specialBanana.setImage("./tex/banana_not_special.png")
        self.specialBanana.setTransparency(TransparencyAttrib.MAlpha)
        
        self.cheese = False
        self.specialCheese.setImage("./tex/cheese_not_special.png")
        self.specialCheese.setTransparency(TransparencyAttrib.MAlpha)
        
        self.tomato = False
        self.specialTomato.setImage("./tex/tomato_not_special.png")
        self.specialTomato.setTransparency(TransparencyAttrib.MAlpha)
        
        self.egg = False
        self.specialEgg.setImage("./tex/egg_not_special.png")
        self.specialEgg.setTransparency(TransparencyAttrib.MAlpha)
    #end reInit
    
    # It check if all the special items are collected.
    # Return true if it's correct.
    def hasAllSpecial(self):
        if( (self.cereal == True) and (self.banana == True) and (self.cheese == True) and (self.tomato == True) and (self.egg == True) ):
            return True
        else:
            return False
    #end hasAllSpecial
    
    # It makes disappear the bar
    def hide(self):
        self.specialCereal.hide()
        self.specialBanana.hide()
        self.specialCheese.hide()
        self.specialTomato.hide()
        self.specialEgg.hide()
    #end hide
    
    # It makes appear the bar
    def show(self):
        self.specialCereal.show()
        self.specialBanana.show()
        self.specialCheese.show()
        self.specialTomato.show()
        self.specialEgg.show()
    #end show
            
class Player(object, DirectObject.DirectObject):
    def __init__(self):
        self.node = 0  #the player main node
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 10
        self.speedMax = 100
        self.agility = 3
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        #self

        self.textSpeed = OnscreenText(text='Speed: ' + str(self.speed),
                                      pos=(-1.34, 0.95),
                                      scale=0.07,
                                      fg=(1, 1, 1, 1),
                                      bg=(0.2, 0.2, 0.2, 0.4),
                                      align=TextNode.ALeft)
        self.textHP = OnscreenText(text='Health:    ' + str(self.HP),
                                   pos=(-1.33, 0.85),
                                   scale=0.07,
                                   fg=(1, 1, 1, 1),
                                   bg=(0.2, 0.2, 0.2, 0.4),
                                   align=TextNode.ALeft)
        self.roll = 0
        self.camHeight = 0

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)

        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    '''
    loadModel
    This will load all the visible stuff
    '''

    def loadModel(self):
        """ make the nodepath for player """
        self.node = NodePath('player')
        self.node.setPos(1000, 1000, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('griffin')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #self.contrail.loadConfig('media/contrail.ptf')
        #self.contrail.start(self.node,render)

        #gravity (aceleration 9.82)
        self.gravityFN = ForceNode('world-forces')
        self.gravityFNP = render.attachNewNode(self.gravityFN)
        self.gravityForce = LinearVectorForce(0, 0, -9.82)
        self.gravityFN.addForce(self.gravityForce)

        #add gravity to engine
        #base.physicsMgr.addLinerForce(self.gravityForce)

        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)

        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)

        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)

        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)

    '''
    addCamera
    camera setup
    '''

    def addCamera(self):
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    '''
    addEvents
    This will set up the events the class will accept
    '''

    def addEvents(self):
        self.accept("wheel_up", self.evtSpeedUp)
        self.accept("wheel_down", self.evtSpeedDown)
        self.accept('hit', self.evtHit)
        self.accept('l', self.evtLand)
        self.accept('o', self.evtStart)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        self.accept('mouse3', self.evtBoostOn)
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    '''
    addCollisions
    This will add a collision sphere for the player
    and a segment to check weather the ground is close/flat enough for landing
    '''

    def addCollisions(self):
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNode.setFromCollideMask(BitMask32(0x1A))
        self.cNode.setIntoCollideMask(BitMask32(0x4))

        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        self.collisionHandler.addInPattern('hit')
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        # landing segment:
        self.landingCNodeSegment = CollisionNode('playerRay')
        self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20))
        self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8))

        self.landingCNodeSegmentPath = self.node.attachNewNode(
            self.landingCNodeSegment)
        #self.landingCNodeSegmentPath.show()
        base.cTrav.addCollider(self.landingCNodeSegmentPath,
                               self.collisionHandlerQueue)

    '''
    addSound
    adds the engine sound
    @TODO add more
    '''

    def addSound(self):
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

    '''
    deleteTask
    task which calls the destructor after a given time (after the explosion animation)
    '''

    def deleteTask(self, task):
        self.__del__()
        return task.done

    '''
    mouseUpdateTask
    This task will handle mouse movement and control the planes rotation.
    If free look is enabled, it will rotate the camera around the player.
    '''

    def mouseUpdateTask(self, task):
        """ this task updates the mouse """
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)
        #base.camera.setY(-30+self.speed/10)
        #base.camera.setX(self.roll*0.5)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    '''
    moveUpdateTask
    Will update players position depending on speed and direction
    '''

    def moveUpdateTask(self, task):
        """ this task makes the player move """
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))

        #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed)
        return task.cont

    def landTask(self, task):
        if self.collisionHandlerQueue.getNumEntries() == 0 and task.frame > 3:
            print 'to faar'
            self.landing = False
            self.evtFreeLookOFF()
            return task.done
        elif self.collisionHandlerQueue.getNumEntries() == 0:
            return task.cont

        self.collisionHandlerQueue.sortEntries()
        entry = self.collisionHandlerQueue.getEntry(0)
        if entry.getInto != self.cNode:
            n = entry.getSurfaceNormal(render)
            n.normalize()
            if n.getZ() < 0.8:
                print 'too steep'
                self.landing = False
                self.evtFreeLookOFF()
                return task.done

            self.cNode.setFromCollideMask(BitMask32(0x0))
            self.cNode.setIntoCollideMask(BitMask32(0x0))
            self.node.setZ(self.node.getZ() - 0.05)
            if entry.getSurfacePoint(self.node).getZ() > -0.5:
                #self.landing = tr
                #self.evtFreeLookOFF()
                return task.done

        return task.cont

    def startTask(self, task):
        self.collisionHandlerQueue.sortEntries()
        entry = self.collisionHandlerQueue.getEntry(0)

        self.node.setZ(self.node.getZ() + 0.05)
        if entry.getSurfacePoint(self.node).getZ() < -10:
            self.landing = False
            self.evtFreeLookOFF()
            self.cNode.setFromCollideMask(BitMask32(0x18))
            self.cNode.setIntoCollideMask(BitMask32(0x4))
            return task.done

        return task.cont

    '''
    explode
    this will cause the plane to explode with a nice particle effect.
    '''

    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()
        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    '''
    zoomTask
    will adjust camera position according to zoom factor specified in self.zoom
    in a smooth way.
    '''

    def zoomTask(self, task):
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    '''
    evtBoostOn
    Will set most inputs to ignore, add a speed boost and an additional
    particle effect     
    '''

    def evtBoostOn(self):
        taskMgr.remove(self.mouseTask)
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('mouse1')
        self.ignore('l')
        self.ignore('o')
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    '''
    evtBoostOff
    Will reactivate inputs, substract speed boost and stop the additional
    particle effect     
    '''

    def evtBoostOff(self):
        self.speed -= 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.ignore('mouse3-up')
        self.addEvents()
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        #self.contrail.loadConfig('../../media/contrail.ptf')
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    '''
    evtHit
    This event will be called if the player gets hit by an object.
    It will reduce the HP by 1 each time we hit a missile.
    If HP reaches 0, the player will explode.
    If we hit an other object like a rock, the player will explode imidiatly
    '''

    def evtHit(self, entry):
        if entry.getIntoNodePath().getParent().getTag(
                "orign") != self.node.getName():

            #if entry.getIntoNodePath().getName() == "projectile":
            #self.HP -= 1
            #self.textHP.setText('HP   : '+str(self.HP))
            if self.HP == 0:
                self.explode()
            else:
                self.explode()

    '''
    evtFreeLookON
    Event that activates free look mode and therefore changes cam position
    '''

    def evtFreeLookON(self):
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    '''
    evtFreeLookOFF
    Event that deactivates free look mode and therefore changes cam position
    back to original
    '''

    def evtFreeLookOFF(self):
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    '''
    __del__
    destructor will remove particle effect, tasks and the whole node
    '''

    def __del__(self):
        self.ignoreAll()
        self.contrail.cleanup()
        base.camera.reparentTo(render)
        base.camera.setPos(2000, 2000, 800)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        messenger.send('player-death')

    '''
    evtSpeedUp
    Will be called if player wants to increase speed.
    - engine sound will become louder
    - camera will zoom out
    - speed display will be updated
    '''

    def evtSpeedUp(self):
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1)
        self.zoom = -5 - (self.speed / 10)
        self.textSpeed.setText('Speed: ' + str(self.speed))

    '''
    evtSpeedDown
    Will be called if player wants to decrease speed.
    - engine sound will become more silent
    - camera will zoom in
    - speed display will be updated
    '''

    def evtSpeedDown(self):
        if self.landing:
            return 0
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            #self.engineSound.setVolume(0)
            self.engineSound.setPlayRate(0)
        self.zoom = -5 - (self.speed / 10)

    def evtLand(self):
        if self.speed != 0 or self.landing:
            return 0
        self.evtFreeLookON()  # landing will enable freelook mode
        self.landing = True
        self.node.setP(0)
        taskMgr.add(self.landTask, 'land-task')

    def evtStart(self):
        if not self.landing:
            return 0
        taskMgr.add(self.startTask, 'start-task')

    def evtMenuOpen(self):
        """event that will be called if main menu is opened (esc)"""
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)

    def evtMenuClose(self):
        """event that will be called if main menu is closed (esc)"""
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
Exemple #16
0
class BAbility(Bar):
    def __init__(self, power):
        Bar.__init__(self)

        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.amount = 0
        self.power = []

        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------------BAR INIT------------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        if power == "GRAIN":
            self.path = "./tex/ability_cereal_bar.png"
            self.path2 = "./tex/rice.png"
            self.path3 = "./tex/ability_cereal_amount.png"
            self.posX = -1.20
            self.posY = -0.85
        if power == "FRUIT":
            self.path = "./tex/ability_fruit_bar.png"
            self.path2 = "./tex/straw.png"
            self.path3 = "./tex/ability_fruit_amount.png"
            self.posX = -1.08
            self.posY = -0.85
        if power == "MILK":
            self.path = "./tex/ability_milk_bar.png"
            self.path2 = "./tex/milk.png"
            self.path3 = "./tex/ability_milk_amount.png"
            self.posX = -0.96
            self.posY = -0.85
        if power == "VEGETABLE":
            self.path = "./tex/ability_vegetable_bar.png"
            self.path2 = "./tex/letuce.png"
            self.path3 = "./tex/ability_vegetable_amount.png"
            self.posX = -0.84
            self.posY = -0.85
        if power == "FISH":
            self.path = "./tex/ability_fish_bar.png"
            self.path2 = "./tex/fish.png"
            self.path3 = "./tex/ability_fish_amount.png"
            self.posX = -0.72
            self.posY = -0.85

        # Initial sprite bar
        self.bar = OnscreenImage(image=self.path,
                                 pos=(self.posX, 0, self.posY),
                                 hpr=None,
                                 scale=(0.05, 1.0, 0.035),
                                 color=None,
                                 parent=None,
                                 sort=1)
        self.bar.setTransparency(TransparencyAttrib.MAlpha)

        # Shape ability bar
        self.item = OnscreenImage(image=self.path2,
                                  pos=(self.posX, 0, -0.90),
                                  hpr=None,
                                  scale=0.06,
                                  color=None,
                                  parent=None,
                                  sort=2)
        self.item.setTransparency(TransparencyAttrib.MAlpha)

        # It prepares sprites amount bar
        i = 0
        while i < 5:
            self.power.append(
                OnscreenImage(image=self.path3,
                              pos=(self.posX, 0,
                                   self.posY + ((i + 1) * 0.055)),
                              hpr=None,
                              scale=(0.05, 1.0, 0.025),
                              color=None,
                              parent=None,
                              sort=1))
            self.power[i].setTransparency(TransparencyAttrib.MAlpha)
            self.power[i].hide()
            i = i + 1

    #end __init__

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It increases the amount of the bar
    def itemCollected(self, amnt):
        if self.amount > 4: self.amount = 5
        else:
            self.power[self.amount].show()
            self.amount = self.amount + amnt

    #end itemCollected

    # It decreases the amount of the bar
    def powerUsed(self, amnt):
        self.amount = self.amount - 1
        self.power[self.amount].hide()

    #end powerUsed

    # It makes empty the bar
    def setEmpty(self):
        while self.amount > 0:
            self.amount = self.amount - 1
            self.power[self.amount].hide()

    #end setEmpty

    # It makes disappear the bar
    def hide(self):
        self.bar.hide()
        self.item.hide()

        i = 0
        while i < 5:
            self.power[i].hide()
            i = i + 1

    #end hide

    # It makes that sprite have an intermitent alpha effect for 2 seconds
    def taskGlowing(self, task):
        if task.time > 2:
            self.bar.show()
            self.item.show()
            i = 0
            while i < self.amount:
                self.power[i].show()
                i = i + 1

            self.isVisible = True
            self.lastTime = 0.0
            return task.done
        else:
            if (task.time - self.lastTime) > 0.15:
                self.lastTime = task.time
                if self.isVisible == True:
                    self.bar.hide()
                    self.item.hide()
                    i = 0
                    while i < self.amount:
                        self.power[i].hide()
                        i = i + 1

                    self.isVisible = False
                else:
                    self.bar.show()
                    self.item.show()
                    i = 0
                    while i < self.amount:
                        self.power[i].show()
                        i = i + 1

                    self.isVisible = True

            return task.cont
class LabTask03(DirectObject):
  
  #define the state of the game and level
  gameState = 'INIT'
  gameLevel = 1
  cameraState = 'STARTUP'
  count = 0
  attempts = 3
  posX = -200
  posY = 20
  posZ = 30
  score = 0
  contacts = 0
  pause = False
  fire = True
  desiredCamPos = Vec3(-200,30,20)

  def __init__(self):
    self.imageObject = OnscreenImage(image = 'models/splashscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    preloader = Preloader()
    self.musicLoop = loader.loadSfx("music/loop/EndlessBliss.mp3")
    self.snowmansHit = loader.loadSfx("music/effects/snowball_hit.wav")
    self.candleThrow = loader.loadSfx("music/effects/snowball_throw.wav")
    self.presentHit = loader.loadSfx("music/effects/present_hit.wav")
    self.loseSound = loader.loadSfx("music/effects/Failure-WahWah.mp3")
    self.winSound = loader.loadSfx("music/effects/Ta Da-SoundBible.com-1884170640.mp3")
    self.nextLevelSound = loader.loadSfx("music/effects/button-17.wav")
    self.loseScreen = OnscreenImage(image = 'models/losescreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.loseScreen.hide()
    self.winScreen = OnscreenImage(image = 'models/winscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.winScreen.hide()
    self.helpScreen = OnscreenImage(image = 'models/helpscreen.jpg', pos=(0,0,0.1), scale=(1,1,0.8))
    self.helpScreen.hide()
    self.backBtn = DirectButton(text=("Back"), scale = 0.1,  pos = (0,0,-0.8), command = self.doBack)
    self.retryBtn = DirectButton(text="Retry", scale = 0.1, pos = (0,0,0), command = self.doRetry)
    self.retryBtn.hide()
    self.menuBtn = DirectButton(text="Main Menu", scale = 0.1, pos = (0,0,0), command = self.doBack)
    self.menuBtn.hide()
    self.backBtn.hide()
    base.setBackgroundColor(0.1, 0.1, 0.8, 1)
    #base.setFrameRateMeter(True)
    
    # Position the camera
    base.cam.setPos(0, 30, 20)
    base.cam.lookAt(0, 30, 0)

    # Light
    alight = AmbientLight('ambientLight')
    alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
    alightNP = render.attachNewNode(alight)

    dlight = DirectionalLight('directionalLight')
    dlight.setDirection(Vec3(1, 1, -1))
    dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
    dlightNP = render.attachNewNode(dlight)

    render.clearLight()
    render.setLight(alightNP)
    render.setLight(dlightNP)

    # Input
    self.accept('escape', self.doExit)
    self.accept('r', self.doReset)
    self.accept('f1', self.toggleWireframe)
    self.accept('f2', self.toggleTexture)
    self.accept('f3', self.toggleDebug)
    self.accept('f5', self.doScreenshot)
    self.accept('f', self.doShoot, [True])
    self.accept('p', self.doPause)

    inputState.watchWithModifiers('forward', 'w')
    inputState.watchWithModifiers('left', 'a')
    inputState.watchWithModifiers('reverse', 's')
    inputState.watchWithModifiers('right', 'd')
    inputState.watchWithModifiers('turnLeft', 'q')
    inputState.watchWithModifiers('turnRight', 'e')
    
    inputState.watchWithModifiers('moveLineUp', 'i')
    inputState.watchWithModifiers('moveLineDown','k')
    inputState.watchWithModifiers('moveLineRight','l')
    inputState.watchWithModifiers('moveLineLeft','j')
    
    self.font = loader.loadFont('models/SHOWG.TTF')
    self.font.setPixelsPerUnit(60)
    self.attemptText = OnscreenText(text='', pos = (0.9,0.8), scale = 0.07, font = self.font)
    self.levelText = OnscreenText(text='', pos=(-0.9,0.9), scale = 0.07, font = self.font )
    self.scoreText = OnscreenText(text='', pos = (0.9,0.9), scale = 0.07, font = self.font)
    self.text = OnscreenText(text = '', 
                              pos = (0, 0), scale = 0.07, font = self.font)
    self.pauseText = OnscreenText(text='P: Pause', pos= (0.9,0.7), scale = 0.05, font = self.font)
    self.pauseText.hide()
    # Task
    taskMgr.add(self.update, 'updateWorld')

    # Physics
    self.setup()

  # _____HANDLER_____
  
  def doRetry(self):
    self.loseScreen.hide()
    self.levelText.clearText()
    self.scoreText.clearText()
    self.attemptText.clearText()
    self.playGame()
    self.retryBtn.hide()
    self.cleanup()
    self.setup()
    

  def doExit(self):
    self.cleanup()
    sys.exit(1)

  def doReset(self):
    self.attempts = 3
    self.cameraState = 'STARTUP'
    base.cam.setPos(0,30,20)
    self.arrow.removeNode()
    self.scoreText.clearText()
    self.levelText.clearText()
    self.attemptText.clearText()
    self.cleanup()
    self.setup()
    
  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')
    
    
  def doShoot(self, ccd):
    if(self.fire and self.attempts > 0 and self.gameState == 'PLAY'):
      self.cameraState = 'LOOK'
      self.fire = False
      self.candleThrow.play()
      self.attempts -= 1
      #get from/to points from mouse click
      ## pMouse = base.mouseWatcherNode.getMouse()
      ## pFrom = Point3()
      ## pTo = Point3()
      ## base.camLens.extrude(pMouse, pFrom, pTo)
      
      ## pFrom = render.getRelativePoint(base.cam, pFrom)
      ## pTo = render.getRelativePoint(base.cam, pTo)
      
      # calculate initial velocity
      v = self.pTo - self.pFrom
      ratio = v.length() / 40
      v.normalize()
      v *= 70.0 * ratio
      torqueOffset = random.random() * 10
      
      #create bullet
      shape = BulletSphereShape(0.5)
      shape01 = BulletSphereShape(0.5)
      shape02 = BulletSphereShape(0.5)
      shape03 = BulletSphereShape(0.5)
      body = BulletRigidBodyNode('Candle')
      bodyNP = self.worldNP.attachNewNode(body)
      bodyNP.node().addShape(shape, TransformState.makePos(Point3(0,0,0)))
      bodyNP.node().addShape(shape01, TransformState.makePos(Point3(0,0.5,-0.5)))
      bodyNP.node().addShape(shape02,TransformState.makePos(Point3(0,1,-1)))
      bodyNP.node().addShape(shape03,TransformState.makePos(Point3(0,1.5,-1.5)))
      bodyNP.node().setMass(100)
      bodyNP.node().setFriction(1.0)
      bodyNP.node().setLinearVelocity(v)
      bodyNP.node().applyTorque(v*torqueOffset)
      bodyNP.setPos(self.pFrom)
      bodyNP.setCollideMask(BitMask32.allOn())
      
      visNP = loader.loadModel('models/projectile.X')
      visNP.setScale(0.7)
      visNP.clearModelNodes()
      visNP.reparentTo(bodyNP)
      
      #self.bird = bodyNP.node()
      
      if ccd:
          bodyNP.node().setCcdMotionThreshold(1e-7)
          bodyNP.node().setCcdSweptSphereRadius(0.5)
          
      self.world.attachRigidBody(bodyNP.node())
      
      #remove the bullet again after 1 sec
      self.bullets = bodyNP
      taskMgr.doMethodLater(5, self.removeBullet, 'removeBullet', extraArgs=[bodyNP], 
                            appendTask = True)
      
    
  def removeBullet(self, bulletNP, task):
    self.cameraState = 'STAY'
    self.fire = True
    self.world.removeRigidBody(bulletNP.node())
    bulletNP.removeNode()
    if(self.attempts <= 0 and len(self.snowmans)>0):
      self.gameState = 'LOSE'
      self.doContinue()
      
    return task.done

  # ____TASK___

  def processInput(self, dt):
    force = Vec3(0, 0, 0)
    torque = Vec3(0, 0, 0)
    #print self.pTo.getY()
    if inputState.isSet('forward'):
      if(self.pTo.getZ() < 40):
        self.pTo.addZ(0.5)
    if inputState.isSet('reverse'):
      if(self.pTo.getZ() > 0 ):
        self.pTo.addZ(-0.5)
    if inputState.isSet('left'):
      if(self.pTo.getY() < 100):
        self.pTo.addY(0.5)
        self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()-0.006,self.arrow.getSz())
    if inputState.isSet('right'):
      if(self.pTo.getY() > 60):
        self.pTo.addY(-0.5)
        self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()+0.006,self.arrow.getSz())
        
    self.arrow.lookAt(self.pTo)
    
  def processContacts(self, dt):
      for box in self.boxes:
        for snowman in self.snowmans:
          result = self.world.contactTestPair(box, snowman.node())
      
          if (result.getNumContacts() > 0):
            self.snowmansHit.play()
            self.score += 100
            self.text.setPos(0,0.7)
            self.text.setText("HIT")
            self.snowmans.remove(snowman)
            self.world.removeRigidBody(snowman.node())
            snowman.removeNode()
            if(len(self.snowmans)  <= 0):
              self.gameState = "NEXT"
              self.text.setText('Nice! Press space to continue')

              
      for box in self.boxes:
        for present in self.presents:
          result01 = self.world.contactTestPair(box,present.node())
          if(result01.getNumContacts() > 0):
            self.presents.remove(present)
            self.world.removeRigidBody(present.node())
            present.removeNode()
            self.presentHit.play()
            self.score += 500
            
  def doContinue(self):
    if(self.gameState == 'INIT'):
      self.gameState = 'MENU'
      self.text.clearText()
      self.musicLoop.setLoop(True)
      self.musicLoop.setVolume(0.5)
      self.musicLoop.play()
      self.startBtn = DirectButton(text=("Play"), scale = 0.1, pos = (0,0,0),command=self.playGame)
      self.helpBtn = DirectButton(text=("Help"), scale = 0.1, pos = (0,0,-0.2),command=self.help)
      self.exitBtn = DirectButton(text=("Exit"), scale = 0.1,  pos = (0,0,-0.4), command = self.doExit)
      return
    
    if self.gameState == 'NEXT':
      self.nextLevelSound.play()
      self.fire = True
      self.gameLevel += 1
      self.score += (self.attempts * 100)
      self.doReset()
      self.gameState = 'PLAY'
      return
    
    if self.gameState == 'LOSE':
      self.loseSound.play()
      self.arrow.removeNode()
      self.loseScreen.show()
      self.levelText.hide()
      self.attemptText.hide()
      self.scoreText.hide()
      self.text.hide()
      self.pauseText.hide()
      self.retryBtn.show()
      return
    
    if self.gameState == 'WIN':
      self.levelText.hide()
      self.attemptText.hide()
      self.scoreText.clearText()
      self.scoreText.setPos(0,0.6)
      self.scoreText.setText("%s"%self.score)
      self.winScreen.show()
      self.winSound.play()
      self.menuBtn.show()
      self.pauseText.hide()
      return
      
    
  def playGame(self):
    print "Play Game"
    self.attempts = 3
    self.score = 0
    self.gameLevel = 1
    self.gameState = 'PLAY'
    self.musicLoop.setVolume(0.3)
    self.imageObject.hide()
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.cleanup()
    self.setup()
    
  def doBack(self):
    self.gameState = 'MENU'
    self.scoreText.setPos(0.9,0.9)
    self.scoreText.hide()
    self.imageObject.show()
    self.startBtn.show()
    self.exitBtn.show()
    self.helpBtn.show()
    self.helpScreen.hide()
    self.backBtn.hide()
    self.menuBtn.hide()
    self.winScreen.hide()
    
  def help(self):
    self.gameState = 'HELP'
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.backBtn.show()
    self.helpScreen.show()
    return
    
  def doPause(self):
    self.pause  = not self.pause
    if(self.pause):
      self.text.setText("Pause")
    else:
      self.text.clearText()
      

  def update(self, task):

    dt = globalClock.getDt()
    if(not self.pause):
      if self.gameState == 'INIT':
        self.text.setPos(0,0)
        self.text.setText('Press space to continue')
        self.accept('space',self.doContinue)
          
      if self.gameState == 'PLAY':
        #print self.posZ
        #if(self.posX < -120):
        #  self.posX += 0.03
        #  self.posZ -= 0.02
        #elif(self.posZ < 70):
        #  self.posZ += 0.02;
        #elif(self.posZ > 70 and self.posX > -120):
        #  self.posZ -= 0.02
        #  self.posX -= 0.03
        #base.cam.setPos(self.posX, self.posZ, self.posY)
        self.levelText.setText('Level: %s'%self.gameLevel)
        self.attemptText.setText('Tries Left: %s'%self.attempts)
        self.scoreText.setText('Score: %s'%self.score)
        self.pauseText.show()
        self.processContacts(dt)
        self.world.doPhysics(dt, 20, 1.0/180.0)
        #self.drawLines()
        self.processInput(dt)
        
        if self.cameraState == 'STARTUP':
          oldPos = base.cam.getPos()
          pos = (oldPos*0.9) + (self.desiredCamPos*0.1)
          base.cam.setPos(pos)
          base.cam.lookAt(0,30,0)
        elif self.cameraState == 'STAY':
          #oldPos = base.cam.getPos()
          #currPos = (oldPos*0.9) + (self.desiredCamPos*0.1)
          #base.cam.setPos(currPos)
          base.cam.lookAt(0,30,0)
        elif self.cameraState == 'LOOK':
          base.cam.lookAt(self.bullets)
          #base.cam.setPos(-200,self.bullets.getZ(),20)
        
      if self.gameState == 'NEXT':
        self.world.doPhysics(dt, 20, 1.0/180.0)
        

      ## self.raycast()
    
    return task.cont
      
  def raycast(self):
    # Raycast for closest hit
    tsFrom = TransformState.makePos(Point3(0,0,0))
    tsTo = TransformState.makePos(Point3(10,0,0))
    shape = BulletSphereShape(0.5)
    penetration = 1.0
    result = self.world.sweepTestClosest(shape, tsFrom, tsTo, penetration)
    if result.hasHit():
        torque = Vec3(10,0,0)
        force = Vec3(0,0,100)
        
        ## for hit in result.getHits():
            ## hit.getNode().applyTorque(torque)
            ## hit.getNode().applyCentralForce(force)
        result.getNode().applyTorque(torque)
        result.getNode().applyCentralForce(force)
        ## print result.getClosestHitFraction()
        ## print result.getHitFraction(), \
            ## result.getNode(), \
            ## result.getHitPos(), \
            ## result.getHitNormal()

  def cleanup(self):
    self.world = None
    self.worldNP.removeNode()
    self.arrow.removeNode()
    self.lines.reset()
    self.text.clearText()

  def setup(self):
    self.attemptText.show()
    self.levelText.show()
    self.scoreText.show()
    self.text.show()
    
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())
    
    #arrow
    self.scaleY = 10
    self.arrow = loader.loadModel('models/arrow.X')
    self.arrow.setScale(0.5,0.5,0.5)
    self.arrow.setAlphaScale(0.5)
    #self.arrow.setTransparency(TransparencyAttrib.MAlpha) 
    self.arrow.reparentTo(render)
    
    #SkyBox
    skybox = loader.loadModel('models/skybox.X')
    skybox.reparentTo(render)

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())
    
    visualNP = loader.loadModel('models/ground.X')
    visualNP.clearModelNodes()
    visualNP.reparentTo(np)
    
    #some boxes
    self.boxes = []
    self.snowmans = []
    self.platforms = []
    self.presents = []
    #TODO: Make a table
    #Table Top
    #self.createBox(Vec3(),Vec3())
    if(self.gameLevel == 1):
      self.createBox(Vec3(5,7,1),Vec3(0,5,10),1.0)
      #2 legs
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-1,5),1.0)
      
      # Pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(1.5, Vec3(0,-10,4.0),10.0)
      
    if(self.gameLevel == 2):
      #table01
      self.createBox(Vec3(5,14,1),Vec3(0,-2,12),2.0)
      self.createBox(Vec3(5,7,1),Vec3(0,5,10),2.0)
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-1,5),1.0)
      #table02
      self.createBox(Vec3(5,7,1),Vec3(0,-9,10),2.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-3,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-15,5),1.0)
      #table03
      self.createBox(Vec3(1,1,1), Vec3(0,-1,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,-3,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,3,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,-5,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,5,14), 2.0)
      #pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(2.0, Vec3(0,-9,2.0), 10.0)
      self.createSnowman(2.0,Vec3(0,-23,2.0),10.0)
      
    if(self.gameLevel == 3):
      #table01
      self.createBox(Vec3(4,2,2),Vec3(0,12,12),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,13,5),1.0)
      #table02
      self.createBox(Vec3(4,2,2),Vec3(0,-15,12),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-14,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-16,5),1.0)
      #table03
      self.createBox(Vec3(4,10,1),Vec3(0,-1,12),1.0)
      self.createBox(Vec3(4,10,1),Vec3(0,-1,14),1.0)
      self.createBox(Vec3(4,2,4),Vec3(0,-2,5),0.1)
      #table04
      self.createPlatform(Vec3(4,8,1),Vec3(0,7,16),1.0)
      self.createPlatform(Vec3(4,8,1),Vec3(0,-9,16),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,13,20),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-16,20),1.0)
      #table05
      self.createBox(Vec3(4,15,1),Vec3(0,-1,24),1.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,2,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,-2,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,4,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,8,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,6,20),5.0)
      
      #pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(2.0,Vec3(0,-8.5,2.0),10.0)
      self.createSnowman(1.5, Vec3(0,-9,19.5), 7.0)
      
      #presents
      self.createPresent(Vec3(2,2,2),Vec3(0,-20,5))
         
    if(self.gameLevel == 4):
      #wall
      self.createStoneBox(Vec3(4,1.5,10), Vec3(0,20,10),20)
      #table01
      self.createBox(Vec3(4,1,5), Vec3(0,7,7),1)
      self.createBox(Vec3(4,1,5), Vec3(0,0,7),1)
      self.createBox(Vec3(4,1,4), Vec3(0,3,7),1)
      self.createPlatform(Vec3(5,8,1), Vec3(0,4,13),1)
      self.createBox(Vec3(4,1,3), Vec3(0,11,18),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-3,18),1)
      self.createBox(Vec3(4,8,1), Vec3(0,4,25),1)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,4,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,7,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,2,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,2,29),2)
      #stairs
      self.createPlatform(Vec3(4,50,4), Vec3(0,-55,5),100)
      #table02
      self.createBox(Vec3(4,1,5), Vec3(0,-13,15),1)
      self.createBox(Vec3(4,1,5), Vec3(0,-20,15),1)
      self.createBox(Vec3(4,1,4), Vec3(0,-17,15),1)
      self.createPlatform(Vec3(4,8,1), Vec3(0,-16,22),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-9,28),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-23,28),1)
      self.createBox(Vec3(4,8,1), Vec3(0,-16,33),1)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-16,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-13,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-18,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-18,37),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-14,37),2)
      
      #snowman
      self.createSnowman(2.0,Vec3(0,30,5),1.0)
      self.createSnowman(1.5,Vec3(0,4,18),1.0)
      self.createSnowman(1.5,Vec3(0,-13,26),1.0)
      self.createSnowman(1.5,Vec3(0,-19,26),1.0)
      self.createSnowman(2.0,Vec3(0,12,5),1.0)
      self.createPresent(Vec3(2,2,2),Vec3(0,-25,13))
      self.createPresent(Vec3(3,3,3),Vec3(0,-30,13))
      self.createPresent(Vec3(4,4,4),Vec3(0,-36,13))
      #self.createSnowman(1.5,Vec3(0,4,20),1.0)

      
    if(self.gameLevel == 5):
      #table01
      self.createStoneBox(Vec3(4,7,3), Vec3(0,30,5),10.0)
      self.createStoneBox(Vec3(4,7,3), Vec3(0,-30,5),10.0)
      self.createBox(Vec3(4,1,3), Vec3(0,0,5), 1.0)
      self.createSnowman(1.5,Vec3(0,-6,5),1.0)
      self.createSnowman(1.5,Vec3(0,6,5),1.0)
      self.createBox(Vec3(4,1,3), Vec3(0,-12,5), 1.0)
      self.createBox(Vec3(4,1,3), Vec3(0,12,5), 1.0)
      self.createSnowman(1.5,Vec3(0,-18,5),1.0)
      self.createSnowman(1.5,Vec3(0,18,5),1.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-18,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-6,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,6,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,18,10), 0.1)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,23,14), 1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,-23,14), 1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,18,14),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-18,14),1.0)
      self.createStoneBox(Vec3(4,1,7),Vec3(0,13,20), 2.0)
      self.createStoneBox(Vec3(4,1,7),Vec3(0,-13,20), 2.0)
      self.createBox(Vec3(4,1,3),Vec3(0,8,14),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-8,14),1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,3,14), 1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,-3,14), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,-20 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,20 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,-5 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,5 ,20), 1.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,-18,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,18,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,-7.5,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,7.5,25), 2.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-12,30), 2.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,12,30), 2.0)
      self.createBox(Vec3(4,1,5),Vec3(0,-5,30), 2.0)
      self.createBox(Vec3(4,1,5),Vec3(0,5,30), 2.0)
      self.createBox(Vec3(4,5,1),Vec3(0,0,40), 2.0)
      self.createPlatform(Vec3(4,2,0.5),Vec3(0,0,42), 2.0)
      self.createStoneBox(Vec3(4,0.5,2),Vec3(0,-3.5,45), 2.0)
      self.createStoneBox(Vec3(4,0.5,2),Vec3(0,3.5,45), 2.0)
      self.createStoneBox(Vec3(4,4,0.5),Vec3(0,0,48), 2.0)
      
      self.createPresent(Vec3(1.5,1.5,1.5),Vec3(0,22,30))
      self.createPresent(Vec3(1.5,1.5,1.5),Vec3(0,-22,30))
      self.createPresent(Vec3(2,2,1),Vec3(0,0,44))
      self.createPresent(Vec3(3,3,4),Vec3(0,0,33))
      
      
    if(self.gameLevel > 5):
      self.gameState = 'WIN'
      self.doContinue()
      return
        
    # drawing lines between the points 
    ## self.lines = LineNodePath(parent = render, thickness = 3.0, colorVec = Vec4(1, 0, 0, 1))
    ## self.pFrom = Point3(-4, 0, 0.5)
    ## self.pTo = Point3(4, 0, 0.5)
    
    # Aiming line 
    self.lines = LineNodePath(parent = render, thickness = 3.0, 
                              colorVec = Vec4(1, 0, 0, 1))
    self.pFrom = Point3(0, 100, 0.5)
    self.pTo = Point3(0, 60, 10)
    
    self.arrow.setPos(self.pFrom)
      
    
  def drawLines(self):  
    # Draws lines for the ray.
    self.lines.reset()  
    self.lines.drawLines([(self.pFrom,self.pTo)])
    self.lines.create()
    
  def createBox(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Obstacle')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/crate.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.boxes.append(body)
    
  def createStoneBox(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Obstacle')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/stone.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.boxes.append(body)
    
  def createSnowman(self, size, pos, mass):
    shape = BulletBoxShape(Vec3(size,size,size))
    shape01 = BulletSphereShape(size/2)
    body = BulletRigidBodyNode('Snowman')
    np = self.worldNP.attachNewNode(body)
    np.node().setMass(mass)
    np.node().addShape(shape, TransformState.makePos(Point3(0,0,-1)))
    np.node().addShape(shape01, TransformState.makePos(Point3(0,0,1)))
    np.node().setFriction(10.0)
    np.node().setDeactivationEnabled(False)
    np.setPos(pos)
    np.setCollideMask(BitMask32.allOn())
      
    self.world.attachRigidBody(np.node())
  
    visualNP = loader.loadModel('models/snowman.X')
    visualNP.setScale(size)
    visualNP.clearModelNodes()
    visualNP.reparentTo(np)
    self.snowmans.append(np)
    
  def createPlatform(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Platform')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/crate.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.platforms.append(body)
    
  def createPresent(self,size,pos):
    shape = BulletBoxShape(size*0.7)
    body = BulletRigidBodyNode('Present')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())
    
    self.world.attachRigidBody(bodyNP.node())
    
    visNP = loader.loadModel('models/present.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.presents.append(bodyNP)
Exemple #18
0
class MainMenu(DirectObject):
    def __init__(self, skipIntro=False):
        render.show()
        engine.Mouse.showCursor()
        # In case we just got back from the tutorial, which hides everything
        # sometimes.
        engine.renderLit.show()
        self.backgroundSound = audio.FlatSound("menu/background.ogg",
                                               volume=0.3)
        self.backgroundSound.setVolume(0)
        self.backgroundSound.setLoop(True)
        self.clickSound = audio.FlatSound("menu/click.ogg", volume=0.3)
        self.active = True
        self.accept("escape", self.escape)
        self.accept("mouse1", self.click)
        self.cameraDistance = 20

        self.globe = engine.loadModel("menu/Globe")
        self.globe.reparentTo(render)
        self.globe.setTransparency(TransparencyAttrib.MAlpha)
        self.globe.setColor(Vec4(1, 1, 1, 0.6))
        self.globe.setTwoSided(True)
        self.globe.setRenderModeWireframe()

        self.overlay = camera.attachNewNode("overlay")
        self.overlay.setTransparency(TransparencyAttrib.MAlpha)
        self.overlay.setColor(Vec4(1, 1, 1, 0))
        self.overlay.setPos(0, 0, 0)
        self.overlay.setPos(0, self.cameraDistance, 0)

        self.overlay1 = engine.loadModel("menu/overlay1")
        self.overlay1.setScale(4)
        self.overlay1.setTwoSided(True)
        self.overlay1.setRenderModeWireframe()
        self.overlay1.reparentTo(self.overlay)

        self.overlay2 = engine.loadModel("menu/overlay2")
        self.overlay2.setScale(4)
        self.overlay2.setTwoSided(True)
        self.overlay2.setRenderModeWireframe()
        self.overlay2.reparentTo(self.overlay)

        self.overlay3 = engine.loadModel("menu/overlay3")
        self.overlay3.setScale(4)
        self.overlay3.setTwoSided(True)
        self.overlay3.setRenderModeWireframe()
        self.overlay3.setR(uniform(0, 360))
        self.overlay3.setP(uniform(0, 360))
        self.overlay3.setH(uniform(0, 360))
        self.overlay3.reparentTo(self.overlay)

        self.overlay4 = engine.loadModel("menu/overlay3")
        self.overlay4.setScale(4)
        self.overlay4.setTwoSided(True)
        self.overlay4.setRenderModeWireframe()
        self.overlay4.setH(uniform(0, 360))
        self.overlay4.setR(uniform(0, 360))
        self.overlay4.setP(uniform(0, 360))
        self.overlay4.reparentTo(self.overlay)

        self.text = engine.loadModel("menu/text")
        self.text.setScale(4)
        self.text.setTwoSided(True)
        self.text.reparentTo(self.overlay)

        self.selector = engine.loadModel("menu/selector")
        self.selector.setScale(4)
        self.selector.setTwoSided(True)
        self.selector.reparentTo(self.overlay)

        self.selectedItem = 0

        self.skyBox = engine.loadModel("menu/skybox")
        self.skyBox.setScale(self.cameraDistance * 5)
        self.skyBox.setRenderModeWireframe()
        self.skyBox.setTwoSided(True)
        self.skyBox.reparentTo(render)
        self.skyBox.setTransparency(TransparencyAttrib.MAlpha)
        self.skyBox.setColor(Vec4(1, 1, 1, 0))

        cmbg = CardMaker("background")
        size = 10
        cmbg.setFrame(-size * engine.aspectRatio, size * engine.aspectRatio,
                      -size, size)
        self.background = camera.attachNewNode(cmbg.generate())
        self.background.setTexture(loader.loadTexture("menu/background.jpg"),
                                   1)
        self.background.setPos(0, size * 1.25, 0)
        self.background.setDepthWrite(False)

        self.belt = JunkBelt(5)

        self.angle = uniform(0, 360)
        self.period = 60
        self.uiAngle = 0

        self.logo = OnscreenImage(image="menu/logo.png",
                                  pos=(0, 0, 0),
                                  scale=((512.0 / 175.0) * 0.075, 0, 0.075))
        self.logo.setTransparency(TransparencyAttrib.MAlpha)
        self.logo.setColor(1, 1, 1, 0)
        self.logo.setBin("transparent", 0)

        self.loadingScreen = OnscreenImage(image="menu/loading.jpg",
                                           pos=(0, 0, 0))
        self.loadingScreen.setScale(render2d, VBase3(1))
        self.loadingScreen.setSx(2)
        self.loadingScreen.hide()

        self.skipToEndOfTutorial = skipIntro

        global firstBoot
        firstBoot = False

        self.introTime = 2
        if firstBoot and not skipIntro:
            self.introTime = 4

        self.showLogin = firstBoot

        self.hostList = ui.HostList(self.startClient)
        self.mapList = ui.MapList(self.startServer)
        self.loginDialog = ui.LoginDialog(self.setUsername)
        self.loginDialogShown = False

        self.introSound = audio.FlatSound("menu/intro.ogg", volume=0.15)
        self.introSound.play()

        self.clientConnectAddress = None
        self.serverMapName = None
        self.serverMode = 0  # 0 for normal, 1 for tutorial
        self.serverGameType = 0  # 0 for deathmatch, 1 for survival

        self.username = "******"

        self.startTime = -1
        self.goTime = -1
        if base.appRunner is not None:
            token = base.appRunner.getToken("username")
            if token != "" and token != "Unnamed":
                self.setUsername(token)
                self.loginDialogShown = True

    def escape(self):
        if self.hostList.visible:
            self.hostList.hide()
        elif self.mapList.visible:
            self.mapList.hide()

    def startClient(self, host):
        self.clickSound.play()
        self.hostList.hide()
        self.loadingScreen.show()
        self.clientConnectAddress = host
        self.goTime = engine.clock.time

    def startServer(self, map, gametype):
        # Tutorial works on Point Control maps.
        if not (self.serverMode == 1 and gametype == 1):
            self.clickSound.play()
            self.mapList.hide()
            self.loadingScreen.show()
            self.serverMapName = map
            self.serverGameType = gametype
            self.goTime = engine.clock.time

    def setUsername(self, username):
        self.clickSound.play()
        self.username = username
        engine.savedUsername = self.username
        engine.saveConfigFile()
        self.loginDialog.hide()

    def update(self):
        if not self.active:
            return
        net.context.readTick()
        if self.startTime == -1:
            self.startTime = engine.clock.time
        elapsedTime = engine.clock.time - self.startTime
        if elapsedTime < self.introTime:
            blend = elapsedTime / self.introTime
            self.angle += engine.clock.timeStep * (1 - blend)
            self.cameraDistance = 20 + (1 - blend)**2 * 200
        elif elapsedTime < self.introTime + 2:
            self.cameraDistance = 20
            blend = (elapsedTime - self.introTime) / 2
            self.overlay.setColor(Vec4(1, 1, 1, blend))
            self.logo.setColor(1, 1, 1, blend)
            self.skyBox.setColor(Vec4(1, 1, 1, blend))
            if not self.backgroundSound.isPlaying():
                self.backgroundSound.play()
            self.backgroundSound.setVolume(blend * 0.5)
        else:
            self.cameraDistance = 20
            self.overlay.setColor(Vec4(1, 1, 1, 1))
            self.logo.setColor(1, 1, 1, 1)
            self.skyBox.setColor(Vec4(1, 1, 1, 1))
            self.backgroundSound.setVolume(0.5)

        if elapsedTime > self.introTime:
            if not self.loginDialogShown and self.showLogin:
                self.loginDialog.show()
                self.loginDialogShown = True

        self.uiAngle -= engine.clock.timeStep * 2
        self.text.setR(self.uiAngle)

        self.hostList.update()
        self.mapList.update()
        self.loginDialog.update()
        mouse = base.win.getPointer(0)
        props = base.win.getProperties()
        vector = Vec3((mouse.getX() / float(props.getXSize())) - 0.5,
                      (mouse.getY() / float(props.getYSize())) - 0.5, 0)
        vector.normalize()
        angle = math.degrees(math.atan2(-vector.getX(), vector.getY())) + 180
        angle -= self.uiAngle
        if not self.hostList.visible and not self.mapList.visible and not self.loginDialog.visible:
            self.selectedItem = int(round(angle / 90.0))
        while self.selectedItem > 3:
            self.selectedItem -= 4
        while self.selectedItem < 0:
            self.selectedItem += 4
        self.selector.setR(self.uiAngle + self.selectedItem * 90)

        self.overlay1.setR(self.overlay1.getR() - engine.clock.timeStep * 2)
        self.overlay2.setR(self.overlay2.getR() + engine.clock.timeStep * 2)
        self.overlay3.setH(self.overlay3.getH() + engine.clock.timeStep * 10)
        self.overlay4.setP(self.overlay4.getP() - engine.clock.timeStep * 10)
        self.belt.update()
        self.angle += engine.clock.timeStep * 0.025
        camera.setPos(
            math.cos(self.angle) * self.cameraDistance,
            math.sin(self.angle) * self.cameraDistance,
            math.cos(elapsedTime / 45 + 2) * 2)
        camera.lookAt(Point3(0, 0, 0))

        backend = None
        game = None

        if self.goTime != -1 and engine.clock.time - self.goTime > 0.25:
            if self.clientConnectAddress is not None:
                self.delete()
                online.connectTo(self.clientConnectAddress)
                backend = ClientBackend(self.clientConnectAddress,
                                        self.username)
                game = Game(backend)
            elif self.serverMapName is not None:
                if self.serverMode == 0:
                    # Normal server mode
                    self.delete()
                    if self.serverGameType == 0:
                        backend = PointControlBackend(
                            True, self.username)  # Deathmatch
                    else:
                        backend = SurvivalBackend(True,
                                                  self.username)  # Survival
                    game = Game(backend)
                    game.localStart(self.serverMapName)
                elif self.serverMode == 1:
                    # Tutorial mode
                    self.delete()
                    backend = PointControlBackend(False, self.username)
                    game = Tutorial(backend,
                                    2 if self.skipToEndOfTutorial else 0)
                    game.localStart(self.serverMapName)

        net.context.writeTick()
        return backend, game

    def click(self):
        if self.mapList.visible or self.hostList.visible or self.loginDialog.visible or engine.clock.time - \
                self.startTime < self.introTime + 0.5:
            return
        self.clickSound.play()
        if self.selectedItem == 0:  # Join
            self.hostList.show()
        elif self.selectedItem == 1:  # Tutorial
            self.mapList.show()
            self.serverMode = 1
        elif self.selectedItem == 2:  # Exit
            engine.exit()
        elif self.selectedItem == 3:  # Host
            self.mapList.show()
            self.serverMode = 0

    def delete(self):
        self.loadingScreen.destroy()
        self.hostList.delete()
        self.mapList.delete()
        self.loginDialog.delete()
        self.active = False
        self.overlay.removeNode()
        self.belt.delete()
        self.background.removeNode()
        self.globe.removeNode()
        self.skyBox.removeNode()
        self.ignoreAll()
        self.logo.destroy()
        self.introSound.stop()
        self.backgroundSound.stop()
Exemple #19
0
class Level:
    def __init__(self, background):
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Background
        self.back = background
        self.back[0].setX(34)
        self.back[1].setX(146)
        
        # Arrow
        self.arrow = OnscreenImage(image="./tex/fletxa.png", pos = (1.1, 0, 0.60),hpr=None, scale = (0.20,0,0.20), color=None, parent=None, sort=5)
        self.arrow.setTransparency(TransparencyAttrib.MAlpha)
        self.arrow.hide()
        self.arrowSound = base.loadSfx('./sound/fletxa.wav')
        self.arrowSound.setVolume(.5)
        
        # Items, enemies list
        self.items = []
        self.enemies = []
        
        # Others
        self.numMoveIt = 0
        self.movingBackground = False
        self.state = 0
        self.win = None
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------LEVEL CONFIGURATION-------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Start tasks
        taskMgr.add(self.taskLevel, 'taskLevel')
        
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It moves the background on screen.
    def moveBackground(self,x,y):
        if( math.fabs(self.numMoveIt-self.back[0].getX()) >= 30.0 ):
            self.movingBackground = False
            self.arrow.hide()
    #end moveBackground
    
    # It hides the level.
    def hideLevel(self):
        self.win.hide()
    #end hideLevel
    
    # It configures the level for a level transition.
    def moveOn(self):
        self.numMoveIt = 0
        self.movingBackground = True
        self.interval = self.back[0].posInterval(5.0, Point3(self.back[0].getX()-30,self.back[0].getY(),self.back[0].getZ()))
        self.interval.start()
        self.interval2 = self.back[1].posInterval(5.0, Point3(self.back[1].getX()-30,self.back[1].getY(),self.back[1].getZ()))
        self.interval2.start()
        self.numMoveIt = self.back[0].getX()
        self.arrow.show()
        self.arrowSound.play()
    #end moveOn
    
    # It removes all items from screen.
    def removeItems(self):
        while self.items != []:
            for x in self.items:
                x.model.setX(-100)
                self.items.remove(x)
    #end removeItems
    
    # It removes all the items and enemies from screen.
    def removeAll(self):
        while self.items != []:
            for x in self.items:
                x.model.setX(-100)
                self.items.remove(x)
                
        while self.enemies != []:
            for x in self.enemies:
                x.model.setX(-100)
                x.life = x.life - 1
                self.enemies.remove(x)
    #end removeAll
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------TASKS,THREADS------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It manages the level on every scene.
    def taskLevel(self, task):
        return task.cont
    #end taskLevel
    
#end class Level
Exemple #20
0
class LifebarUI(UIBase):
    def __init__(self, world):
        UIBase.__init__(self, world)

        #self.mainChar = world.hero

        self.liferoundImage = DirectFrame(
            image='./LEGameAssets/Textures/health_tray.png',
            pos=(1.34, 0, -1),
            scale=(1.34, 1, 1),
            frameColor=(1, 1, 1, 0))
        self.lifebarImage = OnscreenImage(
            image='./LEGameAssets/Textures/lifebar.png',
            pos=(0.285, 0, -0.125),
            scale=(0.215, 1, 0.026))
        self.liferoundImage.setTransparency(1)

        self.liferoundImage.reparentTo(base.a2dTopLeft)
        self.lifebarImage.reparentTo(base.a2dTopLeft)
        self.entirelife = self.world.hero.getMaxHealth()
        #self.accept("a", self.update)
        #self.accept("s", self.reset)
        #self.update()

    def update(self):
        self.life = self.world.hero.getHealth()
        self.lifebarupdate(self.entirelife, self.life)
        #self.accept("a", self.lifebarupdate)
        #self.accept("s", self.hide)
        #self.accept("d", self.show)

    # print "lifebar"
    #pass

    def lifebarupdate(self, entirelife, life):
        #entirelife = 100
        #self.life = self.life-10
        if life > 0:
            self.lifebarImage['scale'] = (float(life) / entirelife * 0.215, 1,
                                          0.026)
            self.lifebarImage['pos'] = (0.285 -
                                        (1 - float(life) / entirelife) * 0.215,
                                        0, -0.125)
        else:
            self.lifebarImage.hide()

    def reset(self):
        self.life = self.world.hero.getMaxHealth()
        self.lifebarImage['scale'] = (0.215, 1, 0.026)
        self.lifebarImage['pos'] = (0.285, 0, -0.125)
        self.lifebarImage.show()

    def hide(self):
        self.liferoundImage.hide()
        self.lifebarImage.hide()

    def show(self):
        self.liferoundImage.show()
        self.lifebarImage.show()


#w = LifebarUI()
#run()
Exemple #21
0
class Engine(ShowBase):

    def __init__(self, mouse):
        ShowBase.__init__(self)
        self.mouse = mouse
        self.joy_x = None
        self.joy_y = None
        props = WindowProperties()
        props.setMouseMode(WindowProperties.MRelative)  # keep mouse in screen
        self.disableMouse()
        self.win.requestProperties(props)
        self.setBackgroundColor(0, 0, 0)
        # Make missiles glow
        self.filters = CommonFilters(self.win, self.cam)
        self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="large")
        self.screen_width = self.win.getXSize()
        self.screen_height = self.win.getYSize()
        self.center_x = self.screen_width/2
        self.center_y = self.screen_height/2
        # self.win.movePointer(0, self.center_x, self.center_y)
        self.enableParticles()
        self.cTrav = CollisionTraverser()
        # self.cTrav.setRespectPrevTransform(True)
        self.pusher = PhysicsCollisionHandler()
        self.pusher.addInPattern('%fn-into-%in')
        self.target = None
        self.maxvel = 50
        self.roll_time = 0
        self.fuel = 1000
        self.ship()
        self.sounds()
        self.hud()
        self.part = Spacedust(self)
        self.events()
        self.camLens.setFov(70)
        self.camLens.setNear(1)
        self.camLens.setFar(500)
        self.get_key = {
            "ACCEL": False,
            "DECEL": False,
            "FORWARD_THRUST": False,
            "REVERSE_THRUST": False,
            "ROLL_LEFT": False,
            "ROLL_RIGHT": False,
            "ROLL_LEFT_BEG": False,
            "ROLL_RIGHT_BEG": False,
            "FIRE": False,
            "FIRING": False,
            "LOCK": False,
            "LOCKING": False,
        }
        self.AIworld = AIWorld(self.render)
        self.taskMgr.add(self.update, "task-update")
        self.taskMgr.doMethodLater(1, self.fuel_usage, "task-fuel-usage")
        self.taskMgr.add(self.AI_update, "AI-update")
        self.gen_enemy()

    def gen_enemy(self):
        x = randint(-1000, 1000)
        y = randint(-1000, 1000)
        z = randint(-1000, 1000)
        Enemy(self, 0, x, y, z)

    def AI_update(self, task):
        self.AIworld.update()
        return task.cont

    def hud(self):
        self.font = self.loader.loadFont("./fnt/subatomic.tsoonami.ttf")
        self.aim = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.02)
        self.aim.setTransparency(TransparencyAttrib.MAlpha)
        self.locker = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.12)
        self.locker.setTransparency(TransparencyAttrib.MAlpha)
        self.locker.hide()

        self.txtFuel = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.8), text='FUEL', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtSpeed = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.7), text='SPEED', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtDist = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.6), text='DIST', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtCoord = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.5), text='COORD', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.taskMgr.doMethodLater(1, self.instruments, "task-instruments")

    def instruments(self, task):
        self.txtSpeed.setText("SPEED: %s" % str(int(self.mvel)))
        self.txtFuel.setText("FUEL: %s" % str(self.fuel))
        if self.target is not None:
            self.txtDist.setText("DISTANCE: %s" % str(round(self.dist, 1)))
        else:
            self.txtDist.setText("DISTANCE: ---")
        self.txtCoord.setText("COORD: %s %s %s" % (str(round(self.fighter.getX(), 1)), str(round(self.fighter.getY(), 1)), str(round(self.fighter.getZ(), 1))))
        return task.again

    def set_key(self, key, value):
        self.get_key[key] = value

    def toggle_key(self, key):
        self.set_key(key, not self.get_key[key])

    def init_roll(self, a, task):
        if task.time <= 2:
            if self.roll_time <= task.time:
                self.roll_time = task.time
            else:
                self.roll_time += task.time
                if self.roll_time > 2:
                    self.roll_time = 2
            self.fighter.setR(self.fighter.getR() + a * self.roll_time)
        else:
            self.fighter.setR(self.fighter.getR() + a * 2)
        return task.cont

    def end_roll(self, a, b, task):
        if task.time < b:
            self.roll_time -= task.time
            if self.roll_time < 0:
                self.roll_time = 0
            self.fighter.setR(self.fighter.getR() + a * (b - task.time))
            return task.cont
        else:
            return task.done

    def roll(self, a):
        if a > 0:
            self.set_key("ROLL_RIGHT_BEG", True)
        else:
            self.set_key("ROLL_LEFT_BEG", True)
        self.taskMgr.add(self.init_roll, "task-init-roll", extraArgs=[a], appendTask=True)

    def unroll(self, a):
        if a > 0:
            self.set_key("ROLL_RIGHT_BEG", False)
        else:
            self.set_key("ROLL_LEFT_BEG", False)
        self.taskMgr.remove("task-init-roll")
        self.taskMgr.add(self.end_roll, "task-end-roll", extraArgs=[a, self.roll_time], appendTask=True)

    def to_roll(self):
        if self.get_key["ROLL_LEFT"]:
            if not self.get_key["ROLL_LEFT_BEG"]:
                if self.fuel > 5:
                    self.roll(-1)
                    self.snd_roller.play()
        else:
            if self.get_key["ROLL_LEFT_BEG"]:
                self.unroll(-1)
                self.snd_roller.stop()
        if self.get_key["ROLL_RIGHT"]:
            if not self.get_key["ROLL_RIGHT_BEG"]:
                if self.fuel > 5:
                    self.roll(+1)
                    self.snd_roller.play()
        else:
            if self.get_key["ROLL_RIGHT_BEG"]:
                self.unroll(+1)
                self.snd_roller.stop()

    def fuel_usage(self, task):
        if self.get_key["FORWARD_THRUST"] or self.get_key["REVERSE_THRUST"]:
            self.fuel -= 9
        if self.get_key["ROLL_LEFT_BEG"] or self.get_key["ROLL_RIGHT_BEG"]:
            self.fuel -= 4
        self.fuel -= 1
        if self.fuel < 0:
            self.fuel = 0
        return task.again

    def chk_speed(self, mvel):
        if mvel < 0.01:
            # stop fighter dead
            if self.prt.getActive():
                self.set_key("DECEL", False)
            mvel = 0
        if mvel > self.maxvel:
            # stop fighter accelerating
            if self.pft.getActive():
                self.set_key("ACCEL", False)
            mvel = self.maxvel
        self.part.p.renderer.setLineScaleFactor(mvel*2)
        self.part.pn.setPos(self.fighter, 0, 10, 0)
        return mvel

    def thrust_shake(self, task):
        x = uniform(-1000, 1000)
        y = uniform(-1000, 1000)
        self.repos(x, y, 0.001)
        return task.cont

    def thrust_end(self, task):
        if task.time < 5:
            f = (5. - task.time) / 5.
            s = 1000.*f
            x = uniform(-s, s)
            y = uniform(-s, s)
            self.repos(x, y, 0.001)
            self.snd_thrust.setVolume(f)
            return task.cont
        self.snd_thrust.stop()
        return task.done

    def thrust(self, a):
        if a > 0:
            self.set_key("FORWARD_THRUST", True)
        else:
            self.set_key("REVERSE_THRUST", True)
        self.taskMgr.remove("task-thrust-end")
        self.snd_thrust.setVolume(1)
        self.snd_thrust.play()
        self.taskMgr.add(self.thrust_shake, "task-thrust-shake")

    def unthrust(self, a):
        if a > 0:
            self.set_key("FORWARD_THRUST", False)
        else:
            self.set_key("REVERSE_THRUST", False)
        self.taskMgr.remove("task-thrust-shake")
        self.taskMgr.add(self.thrust_end, "task-thrust-end")

    def to_thrust(self):
        if self.get_key["ACCEL"]:
            if self.mvel < self.maxvel - 1:
                if not self.get_key["FORWARD_THRUST"]:
                    if self.fuel > 10:
                        self.pft.setActive(True)
                        self.thrust(+1)
        else:
            if self.get_key["FORWARD_THRUST"]:
                self.pft.setActive(False)
                self.unthrust(+1)
        if self.get_key["DECEL"]:
            if self.mvel > 0:
                if not self.get_key["REVERSE_THRUST"]:
                    if self.fuel > 10:
                        self.prt.setActive(True)
                        self.thrust(-1)
        else:
            if self.get_key["REVERSE_THRUST"]:
                self.prt.setActive(False)
                self.unthrust(-1)

    def events(self):
        self.accept("escape", self.quit)
        self.accept('mouse1', self.set_key, ["FIRE", True])
        self.accept('mouse1-up', self.set_key, ["FIRE", False])
        self.accept('mouse3', self.set_key, ["LOCK", True])
        self.accept('mouse3-up', self.set_key, ["LOCK", False])
        self.accept("w", self.set_key, ["ACCEL", True])
        self.accept("w-up", self.set_key, ["ACCEL", False])
        self.accept("s", self.set_key, ["DECEL", True])
        self.accept("s-up", self.set_key, ["DECEL", False])
        self.accept("a", self.set_key, ["ROLL_LEFT", True])
        self.accept("a-up", self.set_key, ["ROLL_LEFT", False])
        self.accept("d", self.set_key, ["ROLL_RIGHT", True])
        self.accept("d-up", self.set_key, ["ROLL_RIGHT", False])

    def update(self, task):
        self.pos()
        self.speed()
        if self.fuel > 0:
            self.to_roll()
            self.to_thrust()
            self.to_fire()
            self.to_lock()
        self.rehud()
        return task.cont

    def rehud(self):
        if self.target is not None:
            c = self.target.np.getPos(self.fighter)
            self.dist = c.length()
            c.normalize()
            self.d2 = c - Vec3(0, 1, 0)*c.dot(Vec3(0, 1, 0))
            self.target.radar.setPos(self.d2.getX(), 1, self.d2.getZ())

    def sounds(self):
        self.audio3d = Audio3DManager.Audio3DManager(self.sfxManagerList[0], self.camera)
        self.audio3d.setListenerVelocityAuto()
        self.snd_space = self.loader.loadSfx("./snd/space.flac")
        self.snd_space.setLoop(True)
        self.snd_thrust = self.loader.loadSfx("./snd/thrust.flac")
        self.snd_thrust.setLoop(True)
        self.snd_roller = self.loader.loadSfx("./snd/roller.flac")
        self.snd_roller.setLoop(True)
        self.snd_launch = self.loader.loadSfx("./snd/launch.flac")
        self.snd_lock = self.loader.loadSfx("./snd/lock.flac")
        self.snd_space.play()

    def quit(self):
        self.taskMgr.running = False

    def repos(self, x, y, d):
        player_q = self.fighter.getQuat()
        up = player_q.getUp()
        right = player_q.getRight()
        up.normalize()
        right.normalize()
        up_q = copy(player_q)
        right_q = copy(player_q)
        up_q.setFromAxisAngle(-(x * d), up)
        right_q.setFromAxisAngle(y * d, right)
        self.fighter.setQuat(player_q.multiply(up_q.multiply(right_q)))

    def move_end(self, x, y, task):
        if task.time <= 1:
            d = 0.002*(1 - task.time)
            self.repos(x, y, d)
            return task.cont
        return task.done

    def pos(self):
        if self.mouse:
            md = self.win.getPointer(0)
            x = md.getX()
            y = md.getY()
        else:
            x = self.joy_x
            y = self.joy_y
        if self.win.movePointer(0, self.center_x, self.center_y):
            x -= self.center_x
            y -= self.center_y
            if x != 0 or y != 0:
                self.taskMgr.add(self.move_end, 'task-move-end', extraArgs=[x, y], appendTask=True)

    def speed(self):
        fwd = self.fighter.getQuat().getForward()
        fwd.normalize()
        self.mvel = self.anpo.getVelocity().length()
        # speed control
        self.mvel = self.chk_speed(self.mvel)
        self.anpo.setVelocity(fwd * self.mvel)

    def ship(self):
        an = ActorNode()
        an.getPhysicsObject().setMass(100)
        self.fighter = self.render.attachNewNode(an)
        self.physicsMgr.attachPhysicalNode(an)
        self.anpo = an.getPhysicsObject()
        fn = ForceNode("force-node-fighter")
        self.fighter.attachNewNode(fn)
        self.pft = LinearVectorForce(Vec3(0, +1, 0) * 500)  # forward thrust
        self.prt = LinearVectorForce(Vec3(0, -1, 0) * 500)  # reverse thrust
        self.pft.setMassDependent(1)
        self.prt.setMassDependent(1)
        self.pft.setActive(False)
        self.prt.setActive(False)
        fn.addForce(self.pft)
        fn.addForce(self.prt)
        an.getPhysical(0).addLinearForce(self.pft)
        an.getPhysical(0).addLinearForce(self.prt)
        self.camera.reparentTo(self.fighter)
        from_obj = self.fighter.attachNewNode(CollisionNode('fighter'))
        from_obj.node().setFromCollideMask(BitMask32(0x1))
        from_obj.setCollideMask(BitMask32(0x1))
        from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1))
        # from_obj.show()
        self.pusher.addCollider(from_obj, self.fighter)
        self.cTrav.addCollider(from_obj, self.pusher)

    def launch_bullet(self):
        speed = 500.
        scale = Vec3(0.05)
        color = Vec4(0, 1, 0, 1)
        mask = BitMask32(0x2)
        lookat = Vec3(0, 100, 0)
        Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(-0.5, 0, 0), self.fighter, lookat, 0.5)
        Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(+0.5, 0, 0), self.fighter, lookat, 0.5)
        self.snd_launch.play()

    def to_fire(self):
        if self.get_key["FIRE"]:
            if not self.get_key["FIRING"]:
                self.set_key("FIRING", True)
                self.taskMgr.doMethodLater(0.16, self.fire_bullet, "task-fire-bullet")
        else:
            if self.get_key["FIRING"]:
                self.set_key("FIRING", False)
                self.taskMgr.remove("task-fire-bullet")

    def fire_bullet(self, task):
        if self.fuel >= 5:
            self.fuel -= 5
            self.launch_bullet()
        return task.again

    def launch_missile(self):
        speed = 100
        scale = Vec3(0.2)
        color = Vec4(1, 0, 0, 1)
        mask = BitMask32(0x2)
        lookat = Vec3(0, 0, 0)
        self.missile = Missile(self, "missile", speed, scale, color, mask, self.fighter, Vec3(0, 0, -2), self.target.np, lookat, 3)
        self.snd_launch.play()
        self.taskMgr.add(self.guide_missile, "task-guide-missile")

    def guide_missile(self, task):
        try:
            quat = Quat()
            lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up())
            self.missile.anp.setQuat(quat)
            fwd = quat.getForward()
            fwd.normalize()
            mvel = self.missile.anpo.getVelocity().length()
            self.missile.anpo.setVelocity(fwd*mvel)
        except:
            return task.done
        return task.cont

    def can_lock(self):
        if self.dist >= 30 and self.dist <= 300 and abs(self.d2.getX()) <= 0.1 and abs(self.d2.getZ()) <= 0.1:
            return True
        else:
            return False

    def remove_lock(self):
        if self.get_key["LOCKING"]:
            self.set_key("LOCKING", False)
            self.locker.hide()
            self.snd_lock.stop()
            self.taskMgr.remove("task-fire-missile")

    def to_lock(self):
        if self.get_key["LOCK"]:
            if self.can_lock():
                if self.fuel >= 100:
                    if not self.get_key["LOCKING"]:
                        self.set_key("LOCKING", True)
                        self.locker.setScale(0.12)
                        self.locker.setColor(1, 0, 0, 0.5)
                        self.locker.show()
                        self.snd_lock.play()
                        self.taskMgr.add(self.fire_missile, "task-fire-missile")
                else:
                    self.remove_lock()
            else:
                self.remove_lock()
        else:
            self.remove_lock()

    def fire_missile(self, task):
        if self.fuel >= 100:
            if task.time < 3.6:
                e = (3.6 - task.time)/3.6
                f = 0.02 + e*0.1
                self.locker.setScale(f)
                self.locker.setColor(e, 1-e, 0, 0.5)
                return task.cont
            else:
                self.fuel -= 100
                self.launch_missile()
                return task.done
Exemple #22
0
class PlayerHUD():
    def __init__(self):
        #
        # Player status section
        #
        heartscale = (0.1, 1, 0.1)
        self.heart1 = OnscreenImage(
            image = "HeartIcon.png",
            scale = heartscale,
            pos = (0.2, 0, -0.15))
        self.heart1.setTransparency(True)
        self.heart1.reparentTo(base.a2dTopLeft)
        self.heart2 = OnscreenImage(
            image = "HeartIcon.png",
            scale = heartscale,
            pos = (0.45, 0, -0.15))
        self.heart2.setTransparency(True)
        self.heart2.reparentTo(base.a2dTopLeft)
        self.heart3 = OnscreenImage(
            image = "HeartIcon.png",
            scale = heartscale,
            pos = (0.7, 0, -0.15))
        self.heart3.setTransparency(True)
        self.heart3.reparentTo(base.a2dTopLeft)

        self.keys = DirectLabel(
            text = "x0",
            frameColor = (0, 0, 0, 0),
            text_fg = (1, 1, 1, 1),
            text_scale = 1.8,
            text_pos = (1, -0.25, 0),
            text_align = TextNode.ALeft,
            image = "Keys.png",
            pos = (0.2, 0, -0.4))
        self.keys.setScale(0.085)
        self.keys.setTransparency(True)
        self.keys.reparentTo(base.a2dTopLeft)

        self.actionKey = DirectLabel(
            frameColor = (0, 0, 0, 0),
            text_fg = (1, 1, 1, 1),
            scale = 0.15,
            pos = (0, 0, 0.15),
            text = _("Action: E/Enter"))
        self.actionKey.setTransparency(True)
        self.actionKey.reparentTo(base.a2dBottomCenter)
        self.actionKey.hide()

    def show(self):
        self.keys.show()

    def hide(self):
        self.heart1.hide()
        self.heart2.hide()
        self.heart3.hide()
        self.keys.hide()
        self.hideActionKey()

    def setHealthStatus(self, value):
        """this function will set the health image in the top righthand corner
        according to the given value, where value is a integer between 0 and 100
        """
        if value >= 1: self.heart1.show()
        else: self.heart1.hide()
        if value >= 2: self.heart2.show()
        else: self.heart2.hide()
        if value >= 3: self.heart3.show()
        else: self.heart3.hide()

    def showActionKey(self):
        self.actionKey.show()

    def hideActionKey(self):
        self.actionKey.hide()

    def updateKeyCount(self, numKeys):
        self.keys["text"] = "x%d" % numKeys
Exemple #23
0
class RonnieRacer(DirectObject):
  
  gameState = 'INIT'
  gameLevel = 1
  distanceTravelled = 0
  speed = 0
  score = 0
  triesLeft = 3
  count = 0
  rot = 0
  time = 0
  pause = False
  
  def __init__(self):
    self.imageObject = OnscreenImage(image = 'media/images/splashscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.loseScreen = OnscreenImage(image = 'media/images/gameover.png', pos=(0,0,0), scale=(1,1,0.8))
    self.loseScreen.hide()
    self.retryScreen = OnscreenImage(image = 'media/images/retry.png', pos=(0,0,0), scale=(1,1,0.8))
    self.retryScreen.hide()
    self.congratScreen = OnscreenImage(image = 'media/images/congratulations.png', pos=(0,0,0), scale = (1,1,0.8))
    self.congratScreen.hide()
    self.winScreen = OnscreenImage(image = 'media/images/victory.png', pos=(0,0,0), scale = (1,1,0.8))
    self.winScreen.hide()
    self.pauseScreen = OnscreenImage(image = 'media/images/pause.png', pos=(0,0,0), scale = (1,1,0.8))
    self.pauseScreen.hide()
    self.instructionScreen = OnscreenImage(image = 'media/images/instructions.png', pos=(0,0,0), scale = (1,1,0.8))
    self.instructionScreen.hide()
    preloader = Preloader()
    base.setBackgroundColor(0, 0, 0, 1)
    base.setFrameRateMeter(True)
    
    # Audio
    self.loseSound = base.loader.loadSfx("media/audio/sfxboo.wav")
    self.winSound = base.loader.loadSfx("media/audio/cheer2.aif")
    self.menuMusic = base.loader.loadSfx("media/audio/Scattershot.mp3")
    self.gameMusic = base.loader.loadSfx("media/audio/Ghostpocalypse - 7 Master.mp3")
    
    self.menuMusic.setLoop(True)
    self.menuMusic.setLoopCount(0)
    
    self.gameMusic.setLoop(True)
    self.gameMusic.setLoopCount(0)

    #setup buttons
    self.retryBtn = DirectButton(text="Retry", scale = 0.1, pos = (0,0,0), command = self.doRetry)
    self.retryBtn.hide()
    self.menuBtn = DirectButton(text="Main Menu", scale = 0.1, pos = (0,0,0), command = self.doMenu)
    self.menuBtn.hide()
    self.nextBtn = DirectButton(text='Next', scale = 0.1, pos = (0,0,0), command = self.doNext)
    self.nextBtn.hide()
    self.backBtn = DirectButton(text='back', scale = 0.1, pos = (-0.7,0,-0.7), command = self.doBack)
    self.backBtn.hide()
    
    #setup font
    self.font = loader.loadFont('media/SHOWG.TTF')
    self.font.setPixelsPerUnit(60)
    
    #setup text
    self.text = OnscreenText(text = '', pos = (0, 0), scale = 0.07, font = self.font)
    
    self.rpmText = OnscreenText(text = '', 
                            pos = (-0.9, -0.9), scale = 0.07, font = self.font)
                            
    self.speedText = OnscreenText(text = '', 
                            pos = (0, -0.9), scale = 0.07, font = self.font)
                            
    self.distanceText = OnscreenText(text = '', 
                            pos = (0.9, -0.9), scale = 0.07, font = self.font)
    
    self.triesLeftText = OnscreenText(text = '', 
                            pos = (1.0, 0.9), scale = 0.07, font = self.font)
    
    self.gameLevelText = OnscreenText(text = '', 
                            pos = (-1.0, 0.9), scale = 0.07, font = self.font)
    
    self.timeText = OnscreenText(text = '', 
                            pos = (0, 0.9), scale = 0.07, font = self.font)
    
    self.scoreText = OnscreenText(text = '', 
                            pos = (1.0, 0.8), scale = 0.07, font = self.font)
    
    self.finalScoreText = OnscreenText(text = '', 
                            pos = (0, 0.2), scale = 0.07, font = self.font)
    # Light
    alight = AmbientLight('ambientLight')
    alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
    alightNP = render.attachNewNode(alight)

    dlight = DirectionalLight('directionalLight')
    dlight.setDirection(Vec3(1, 1, -1))
    dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
    dlightNP = render.attachNewNode(dlight)

    render.clearLight()
    render.setLight(alightNP)
    render.setLight(dlightNP)

    # Input
    self.accept('escape', self.doExit)
    self.accept('r', self.doReset)
    self.accept('f1', self.toggleWireframe)
    self.accept('f2', self.toggleTexture)
    self.accept('f3', self.toggleDebug)
    self.accept('f5', self.doScreenshot)

    inputState.watchWithModifiers('forward', 'w')
    inputState.watchWithModifiers('left', 'a')
    inputState.watchWithModifiers('reverse', 's')
    inputState.watchWithModifiers('right', 'd')
    inputState.watchWithModifiers('turnLeft', 'a')
    inputState.watchWithModifiers('turnRight', 'd')

    # Task
    taskMgr.add(self.update, 'updateWorld')

  # _____HANDLER_____
  def doExit(self):
    sys.exit(1)

  def doReset(self):
    self.cleanup()
    self.terrain.getRoot().removeNode()
    self.setup()

  def doBack(self):
    self.backBtn.hide()
    self.instructionScreen.hide()
    
    self.imageObject.show()
    self.helpBtn.show()
    self.startBtn.show()
    self.exitBtn.show()

  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')

  # ____TASK___

  def processInput(self, dt):
    # Process input
    engineForce = 0.0
    brakeForce = 0.0
    
    self.accept('p', self.doPause)
  
    if inputState.isSet('forward'):
       engineForce = 15.0
       brakeForce = 0.0
   
    if inputState.isSet('reverse'):
       engineForce = -25.0
       brakeForce = 25.0
   
    if inputState.isSet('turnLeft'):
       self.steering += dt * self.steeringIncrement
       self.steering = min(self.steering, self.steeringClamp)
   
    if inputState.isSet('turnRight'):
       self.steering -= dt * self.steeringIncrement
       self.steering = max(self.steering, -self.steeringClamp)
   
    # Apply steering to front wheels
    self.vehicle.setSteeringValue(self.steering, 0)
    self.vehicle.setSteeringValue(self.steering, 1)
   
    # Apply engine and brake to rear wheels
    self.vehicle.applyEngineForce(engineForce, 2)
    self.vehicle.applyEngineForce(engineForce, 3)
    self.vehicle.setBrake(brakeForce, 2)
    self.vehicle.setBrake(brakeForce, 3)
    
  def processContacts(self, dt):
    result = self.world.contactTestPair(self.vehicleNP.node(), self.flagNP.node())
    if(result.getNumContacts() > 0):
      self.gameState = 'WIN'
      self.doContinue()
      
  def doContinue(self):
    if(self.gameState == 'INIT'):
      self.gameState = 'MENU'
      self.menuMusic.play()
      self.text.hide()
      self.startBtn = DirectButton(text=("Play"), scale = 0.1, pos = (0.5,0,0),command=self.playGame)
      self.helpBtn = DirectButton(text=("Help"), scale = 0.1, pos = (0.5,0,-0.2),command=self.help)
      self.exitBtn = DirectButton(text=("Exit"), scale = 0.1,  pos = (0.5,0,-0.4), command = self.doExit)
      return
      
    if(self.gameState == 'RETRY'):
      self.retryScreen.show()
      self.retryBtn.show()
      
      self.loseSound.play()
      return
    
    if(self.gameState == 'LOSE'):
      self.loseScreen.show()
      self.menuBtn.show()
      return
    
    if(self.gameState == 'WIN'):
      if(self.gameLevel < 3):
        self.congratScreen.show()
        self.nextBtn.show()
      elif(self.gameLevel >= 3):
        self.winScreen.show()
        self.menuBtn.show()
      self.finalScoreText.setText('Your Score: '+str(int(self.score)))
      self.finalScoreText.show()
        
      self.winSound.play()
      
  def help(self):
    self.gameState = 'HELP'
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.imageObject.hide()
    self.instructionScreen.show()
    self.backBtn.show()
    
  def doNext(self):
    self.nextBtn.hide()
    self.finalScoreText.hide()
    self.congratScreen.hide()
    self.gameLevel += 1
    if(self.gameLevel == 2):
      self.score += 2000
    elif(self.gameLevel == 3):
      self.score += 3000
    self.doReset()
    self.triesLeft = 3
    self.gameState = 'PLAY'
    
  def doRetry(self):
    self.doReset()
    self.gameState = 'PLAY'
    self.retryScreen.hide()
    self.retryBtn.hide()
    self.triesLeft -= 1
  
  def doMenu(self):
    self.cleanup()
    self.terrain.getRoot().removeNode()
    self.gameState = 'MENU'
    
    self.score = 0
    
    self.imageObject.show()
    self.startBtn.show()
    self.exitBtn.show()
    self.helpBtn.show()
    
    self.loseScreen.hide()
    self.menuBtn.hide()
    self.winScreen.hide()
    self.finalScoreText.hide()
    
    self.speedText.hide()
    self.distanceText.hide()
    self.rpmText.hide()
    self.scoreText.hide()
    self.gameLevelText.hide()
    self.timeText.hide()
    self.triesLeftText.hide()
    
    self.gameMusic.stop()
    self.menuMusic.play()
      
  def doPause(self):
    self.pause  = not self.pause
    if(self.pause):
      self.pauseScreen.show()
    else:
      self.pauseScreen.hide()
      
  def playGame(self):
    self.gameState = 'PLAY'
    
    self.triesLeft = 3
    self.gameLevel = 1
    
    self.imageObject.hide()
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    
    self.menuMusic.stop()
    self.gameMusic.play()
    
    self.speedText.show()
    self.distanceText.show()
    self.rpmText.show()
    self.scoreText.show()
    self.gameLevelText.show()
    self.triesLeftText.show()
    self.timeText.show()
    
    # Physics
    self.setup()

  def update(self, task):
    dt = globalClock.getDt()
    if(not self.pause):
      if(self.gameState == 'RETRY'):
        return task.cont
      
      if (self.gameState == 'INIT'):
        self.accept('space', self.doContinue)
        self.text.setText('Press Space to Continue')
        
      if(self.gameState == 'PLAY'):
        if (self.steering > 0):
            self.steering -= dt * 50
        if (self.steering < 0):
            self.steering += dt * 50
            
        playerOldSpeed = self.vehicle.getCurrentSpeedKmHour()
        
        self.processInput(dt)
        self.processContacts(dt)
        self.world.doPhysics(dt, 10, 0.008)
  
        #calculate speed,rpm,distance and display text
        self.speed = self.vehicle.getCurrentSpeedKmHour()
        if(self.speed<0):
            self.speed = -self.speed
        self.speedText.setText('Speed: ' + str(int(self.speed)) + 'Km/h')
        self.distanceTravelled += self.speed*(dt/3600)
        self.distanceText.setText('Distance: '+str(float(int(self.distanceTravelled * 1000))/1000) + 'Km')
  
        playerNewSpeed = self.vehicle.getCurrentSpeedKmHour()
  
        playerAcceleration = (playerNewSpeed - playerOldSpeed) / (dt/60)
        #playerPosText = self.vehicleNP.getPos()
        #self.text.setText('Player position: %s'%playerPosText)
        self.rpmText.setText('Engine RPM: ' + str(int(((self.vehicle.getCurrentSpeedKmHour() / 60) * 1000) / (2 * 0.4 * 3.14159265))) + ' Rpm')
        
        self.triesLeftText.setText('Tries Left: ' + str(self.triesLeft))
  
        self.gameLevelText.setText('Level: '+ str(self.gameLevel))
        
        #update camera
        #position
        d = self.vehicleNP.getPos() - base.cam.getPos()
        if(d.length() > 8):
          base.cam.setX(base.cam.getX() + d.getX()*dt)
          base.cam.setY(base.cam.getY() + d.getY()*dt)
        base.cam.setZ(self.vehicleNP.getZ() + 4)
        #lookat
        base.cam.lookAt(self.vehicleNP.getPos()+Vec3(0,0,1))
        
        if(self.gameLevel == 1):
          if(self.vehicleNP.getZ() < -17):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
        elif(self.gameLevel == 2):
          if(self.vehicleNP.getZ() < -20):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
        elif(self.gameLevel == 3):
          if(self.vehicleNP.getZ() < -17):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
            
        if(self.speed < 5):
          self.steeringIncrement = 120
        elif(self.speed >= 5 and self.speed < 10):
          self.steeringIncrement = 100
        elif(self.speed >= 10 and self.speed < 15):
          self.steeringIncrement = 80
        elif(self.speed >=15 and self.speed < 30):
          self.steeringIncrement = 60
          
        #spin the flag
        self.rot += 1
        self.flagNP.setHpr(self.rot,0,0)
        
        #time
        self.time += dt
        self.timeText.setText('Time: ' + str(int(self.time)))
        if(self.score > 0):
          self.score -= dt
        self.scoreText.setText('Score: '+str(int(self.score)))

    return task.cont

  def cleanup(self):
    self.world = None
    self.worldNP.removeNode()

  def setup(self):
    # Steering info
    self.steering = 0.0            # degree
    self.steeringClamp = 30.0      # degree
    self.steeringIncrement = 80.0 # degree per second
    
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    #self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())
    
    if(self.gameLevel == 1):
      #set score
      print('GameLevel')
      self.score = 1000
      self.distanceTravelled = 0
      self.time = 0
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_1.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
    
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

    # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-93, -88, -7)#-93, -88, -7) #(-82,65.8,-8) #(55,8.38,-6)#(45, -19, -8)#(-93, -88, -7)
      self.vehicleNP.setHpr(-90,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)
      
      #Obstacles
      self.setupObstacleOne(Vec3(50, -5, -4), 1.8, Vec3(60, 0, 0))
      self.setupObstacleFour(Vec3(63.3, 59.2, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(41, 57, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(7.5, 53.8, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(-28, 81.4, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleSix(Vec3(-91, 81 , -6), 1, Vec3(60,0,0))
      
      #Goal
      self.setupGoal(Vec3(-101,90.6,-6.5))
      
      #self.vehicleNP.setPos(Vec3(6,52,-6))
      self.setupTerrain()
    elif(self.gameLevel == 2):
      self.distanceTravelled = 0
      self.time  = 0 
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_2.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
      
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

      # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-99.6,105,-11.8)#(88, 21, -11)#(34.3,8.4,-11.8)#(-99.6,105,-11.8)#(86.4,41.2,-12)
      self.vehicleNP.setHpr(-130,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)
      
      self.setupObstacleFive(Vec3(91, 3, -9),1,Vec3(90,0,0))
      self.setupObstacleFive(Vec3(94,-19, -10),0.9,Vec3(90,0,0))
      self.setupObstacleFive(Vec3(85,-40, -10),1,Vec3(90,0,0))
      self.setupObstacleFour(Vec3(-33.5, 23.4,-14.5),1,Vec3(0,0,0))
      self.setupObstacleFour(Vec3(-43.3, 24.2,-14.5),1,Vec3(0,0,0))
      self.setupObstacleTwo(Vec3(34.7,20.9,-8.5),1,Vec3(90,0,0))
      self.setupObstacleTwo(Vec3(26.8,20.3,-8.5),1,Vec3(90,0,0))
      self.setupObstacleTwo(Vec3(42.1,22.5,-8.5),1,Vec3(90,0,0))
      #self.setupObstacleFive(Vec3(91,0.2, -8),2.1,Vec3(90,0,0))
            
      #Goal
      self.setupGoal(Vec3(94,-89.7,-10))
      self.setupTerrain()
    elif(self.gameLevel == 3):
      self.distanceTravelled = 0
      self.time  = 0 
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_3.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
      
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

      # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-110, -110, 0)
      self.vehicleNP.setHpr(-40,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)

      self.setupTerrain()
      
      #Goal
      self.setupGoal(Vec3(114,100,-13))
      
      #Obstacles
      self.setupObstacleFour(Vec3(-60, -73, -9), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(-63, -77, -9), 1, Vec3(0, 0, 0))
      self.setupObstacleTwo(Vec3(-15, -40, -3), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(-60, 12, -11), 1, Vec3(0, 0, 0))
      self.setupObstacleSix(Vec3(-15, 90, -6), 1.5, Vec3(-30, 0, 0))
      self.setupObstacleFour(Vec3(28, 87, -11), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(32, 90, -11), 1, Vec3(0, 0, 0))



  def addWheel(self, pos, front, np):
    wheel = self.vehicle.createWheel()

    wheel.setNode(np.node())
    wheel.setChassisConnectionPointCs(pos)
    wheel.setFrontWheel(front)

    wheel.setWheelDirectionCs(Vec3(0, 0, -1))
    wheel.setWheelAxleCs(Vec3(1, 0, 0))
    wheel.setWheelRadius(0.4)
    wheel.setMaxSuspensionTravelCm(40.0)

    wheel.setSuspensionStiffness(40.0)
    wheel.setWheelsDampingRelaxation(2.3)
    wheel.setWheelsDampingCompression(4.4)
    wheel.setFrictionSlip(100.0);
    wheel.setRollInfluence(0.1)

  def setupTerrain(self):
    if(self.gameLevel == 1):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_1.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(1000)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/longGrass.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/greenrough.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/grayRock.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))
    elif(self.gameLevel == 2):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_2.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(100)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/sandripple.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/orangesand.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/grayRock.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))
    elif(self.gameLevel == 3):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_3.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(100)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/hardDirt.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/littlerocks.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/greenrough.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))

  def setupObstacleOne(self, pos, scale, turn):
    
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1) * scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2 * scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.9)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.9)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(0, 0, -0.1 * scale)
    pivotB = Point3(0, 0, 1 * scale)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    # Box B
    shape = BulletBoxShape(Vec3(3, 2, 0.1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn);
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 2, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(0, 0, 0)
    pivotB = Point3(0, 0, -1 * scale)
    
    hinge = BulletHingeConstraint(bodyB, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(0,360, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
  
  def setupObstacleTwo(self,pos,scale,turn):
    
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box B
    shape = BulletBoxShape(Vec3(0.1, 1, 1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(100.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(2, 0, 0)
    pivotB = Point3(0, 0, 2)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 1, 1)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(100.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(-2, 0, 0)
    pivotB = Point3(0, 0, 2)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    self.world.attachConstraint(hinge)
  
  def setupObstacleThree(self, pos, scale, turn):
    # Box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1))
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyA.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    #Box B
    shape = BulletBoxShape(Vec3(0.1,0.1,0.1))
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyB.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1,0.1,0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Slider
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    
    slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
    slider.setDebugDrawSize(2.0)
    slider.setLowerLinearLimit(0)
    slider.setUpperLinearLimit(12)
    slider.setLowerAngularLimit(-90)
    slider.setUpperAngularLimit(-85)
    self.world.attachConstraint(slider)
    
    # Box C
    shape = BulletBoxShape(Vec3(1, 3, 0.1))
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyC.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(0.1)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())  
    bodyNP.setPos(Vec3(pos.getX() + 3, pos.getY() - 4, pos.getZ()))
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(1, 3, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    bodyNP.node().setLinearVelocity(-100)
    
    # Slider
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    
    slider = BulletSliderConstraint(bodyA, bodyC, frameA, frameB, True)
    slider.setDebugDrawSize(2.0)
    slider.setLowerLinearLimit(2)
    slider.setUpperLinearLimit(6)
    slider.setLowerAngularLimit(-90)
    slider.setUpperAngularLimit(-85)
    self.world.attachConstraint(slider)
  
  def setupObstacleFour(self, pos, scale, turn):
    #Start Here
    # Box A
    shape = BulletBoxShape(Vec3(0.01, 0.01, 0.01) * scale)
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 4) #(0, 0, 4)

    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.01, 0.01, 0.01)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletSphereShape(0.5*scale)

    bodyB = BulletRigidBodyNode('Sphere B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(10.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 5) #(0, 0, 0.001)

    visNP = loader.loadModel('media/models/ball.egg')
    visNP.clearModelNodes()
    visNP.setScale(1.25*scale)
    visNP.reparentTo(bodyNP)
    
    bodyNP.node().setLinearVelocity(100)

    self.world.attachRigidBody(bodyB)

    # Cone
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90))
    frameB = TransformState.makePosHpr(Point3(2, 0, 0)*scale, Vec3(0, 0, 0))

    cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB)
    cone.setDebugDrawSize(2.0)
    cone.setLimit(30, 90, 270, softness=1.0, bias=0.3, relaxation=10.0)
    self.world.attachConstraint(cone)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 1)*scale)

    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 3)
    
    self.world.attachRigidBody(bodyC)

    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
  def setupObstacleSix(self, pos, scale, turn):
    #box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOff())
    bodyNP.setPos(pos.getX()-2,pos.getY(),pos.getZ()+2.5)#-2,0,2.5)
    bodyNP.setHpr(turn)
    
    # Box B
    shape = BulletBoxShape(Vec3(2, 0.1, 3)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX()-3,pos.getY(), pos.getZ())#, 0, 0)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(2, 0.1, 3)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    
    # Hinge
    pivotA = Point3(-2, 0, -3)
    pivotB = Point3(-2, 0, -3)
    axisA = Vec3(0, 0, 1)
    axisB = Vec3(0, 0, 1)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(0,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    #box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOff())
    bodyNP.setPos(pos.getX()+2,pos.getY(),pos.getZ()+2.5)#2,0,2.5)
    bodyNP.setHpr(turn)
    
    # Box B
    shape = BulletBoxShape(Vec3(2, 0.1, 3)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX()+4, pos.getY(), pos.getZ())# 0, 0)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(2, 0.1, 3)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    pivotA = Point3(2, 0, -3)
    pivotB = Point3(2, 0, -3)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(-90,0, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
  def setupObstacleFive(self, pos, scale, turn):
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box B
    shape = BulletBoxShape(Vec3(3, 2, 0.1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 2, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(0, 0, 0)
    pivotB = Point3(0, 0, 5)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-50,50, softness=0.5, bias=0.3, relaxation=0.6)
    self.world.attachConstraint(hinge)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.9)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.9)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(0, 0, -1.1)
    pivotB = Point3(0, 0, 1)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
  def setupGoal(self, pos):
      # Goal
      shape = BulletBoxShape(Vec3(1, 1, 1))

      body = BulletRigidBodyNode('Flag')

      self.flagNP = self.worldNP.attachNewNode(body)
      self.flagNP.node().addShape(shape)
      self.flagNP.setCollideMask(BitMask32.allOn())
      self.flagNP.setPos(pos)
      
      visNP = loader.loadModel('media/models/Flag.X')
      visNP.clearModelNodes()
      visNP.reparentTo(self.flagNP)
    
      self.world.attachRigidBody(body)
class OnScreenInterface():
	
	# Time users have for each level will be listed here
	LEVEL_1_TIME = (3,59)
	LEVEL_2_TIME = (6,59)
	
	'''
	    Constructor takes a reference of the current game, creates a direct frame that everything
	    will be parented to and also sets the sound effect that will be used for aything on the 
	    onscreen interface class.
	    @param game - pointer to current game
	'''
	def __init__(self,game):
		self.previous = -1
		self.min = 0
		self.sec = 0
		self.__game = game
		self.create_main_frame()
		self.set_sound()

	'''
	    Creates instance variables for all sounds effects that will be used for this
	    instance of the class. Volume and playrate is also set.
	'''
	def set_sound(self):
		self.intro = base.loader.loadMusic("sfx/not_seems.mp3")
		self.hover = base.loader.loadSfx("sfx/hover.mp3")
		self.click = base.loader.loadSfx("sfx/click.wav")
		self.pause = base.loader.loadSfx("sfx/pause.wav")
		self.blocked = base.loader.loadSfx("sfx/blocked.wav")
		self.blocked.setVolume(.05)
		self.hover.setPlayRate(5)
		self.hover.setVolume(.05)
		self.intro.setVolume(.5)
		self.intro.setLoop(True)

	'''
	    Creates instance variable that decides how much time user will have to complete the current level
	'''
	def set_timer(self,level):
		if level == 'L1':
			self.min = OnScreenInterface.LEVEL_1_TIME[0]
			self.sec = OnScreenInterface.LEVEL_1_TIME[1]
		elif level == 'L2':
			self.min = OnScreenInterface.LEVEL_2_TIME[0]
			self.sec = OnScreenInterface.LEVEL_2_TIME[1]
	
	'''
	   Creates the initial two frames that are needed in the game before the gameplay starts
	'''
	def load_initial_interface(self):
		self.create_player()
		self.create_start()
		self.create_stage_selector(button=False)
	
	'''
	   Creates the rest of the frames that are needed once gameplay has started
	'''
	def load_essentials(self):
		self.create_health_bar()
		self.create_token_counter()
		self.create_coordinate_view()	
		self.create_help_menu()
		self.create_control_guide()
		self.create_stage_selector()
		self.create_leaderboard_selector()
		self.create_leaderboard(self.__game.current_level)

	#------------------------------------------------------------------------- CREATE METHODS -----------------------------------------------------------------#

	'''
	    Creates frame that will be the parent of all the other frames created for this game.
	    This is done so that when all gui interfaces need to be destroyed they can be destroyed with 
	    on call to destroy.
	'''
	def create_main_frame(self):
		self.main_frame = DirectFrame(frameColor = (0,0,0,0),frameSize=(-2,2,-1,1), pos=(0,0,0))

	
	'''
	    Creates game start frame. This frame is not hidden because it is the first thing the user sees.	
	'''
	def create_start(self):
		# Direct frame to hold contents of start frame
		self.start_frame = DirectFrame(parent = self.main_frame,frameColor = (0,0,0,1),frameSize=(-2,2,-1,1), pos=(0,0,0))
		
		# Onscreen image of kyklops
		kyklops = OnscreenImage(parent=self.start_frame,image = 'img/kyklops.png', pos = (.9, 0, .3), scale = (.3,0,.3))
		kyklops.setTransparency(TransparencyAttrib.MAlpha)
		
		# Onscreen image of game title
		title = OnscreenImage(parent=self.start_frame,image = 'img/title.png', pos = (0, 0, 0), scale = (.8,0,.3))
		title.setTransparency(TransparencyAttrib.MAlpha)
		
		# Onscreen image of eve rolling
		rolling_eve = OnscreenImage(parent=self.start_frame,image = 'img/rolling-eve.png', pos = (-.95, 0, -.1), scale = (.5,0,.5))
		rolling_eve.setTransparency(TransparencyAttrib.MAlpha)

		# Create button to start game
		self.create_menu_button(self.start_frame,'START',LVecBase3f(0,0,-.5),self.show_input)

		# Play intro music		
		self.intro.play()

	'''
	    Creates a fields so the player can input his/her name at the beginning of the game. This is used
	    to store the name and user score at the end of each stage in the game.
	'''
	def create_player(self):
		# Direct frame to hold input field
		self.input_frame = DirectFrame(parent=self.main_frame,frameColor = (0,0,0,1),frameSize=(-2,2,-1,1), pos=(0,0,0))
		
		# Instructions for user
		instructions = OnscreenText(parent=self.input_frame, text = 'Enter your name: ', pos = (0,.2), scale = 0.1, fg=(0,.2,.2,1),shadow=(1,1,1,.7))
		
		# Name input field
		self.entry = DirectEntry(parent=self.input_frame,text = "",scale=(.1,1,.08),pos=(-.5,0,0),command=self.set_player,numLines=1,focus=1)

		# Hide frame
		self.input_frame.hide()

	'''
	    Creates help menu frame with buttons for each option in the menu. This frame is hidden.
	'''
	def create_help_menu(self):
		# Direct frame to hold buttons and text
		self.help_frame = DirectFrame(parent=self.main_frame,frameColor = (.6,.6,.6,.7),frameSize=(-2,2,-1,1), pos=(0,0,0))
		
		# Title for frame
		title = OnscreenText(parent=self.help_frame, text = 'MENU', pos = (0, .4), scale = 0.2, fg=(0,.2,.2,1),shadow=(.5,.5,.5,1) )
		
		# Buttons for menu frame
		self.create_menu_button(self.help_frame,'Controls',LVecBase3f(0,0,.1),self.show_controls)
		self.create_menu_button(self.help_frame,'Level Select',LVecBase3f(0,0,-.1),self.show_level_select)
		self.create_menu_button(self.help_frame,'Leaderboard',LVecBase3f(0,0,-.3),self.show_lb_selection)
		self.create_menu_button(self.help_frame,'Quit',LVecBase3f(0,0,-.5),sys.exit)
		
		# Hide frame 
		self.help_frame.hide()

	'''
	    Creates control instruction frame. This frame hidden. 
	'''
	def create_control_guide(self):
		# Direct frame to hold player control instructions
		self.control_frame = DirectFrame(frameColor = (.9,.9,.9,.9),frameSize=(-2,2,-1,1), pos=(0,0,0))

		# Title for frame
		frame_title = OnscreenText(parent=self.control_frame, text = 'CONTROL KEYS', pos = (0, .5), scale = 0.1, fg=(0,.2,.2,1),shadow=(.5,.5,.5,1))

		OnscreenText(parent=self.control_frame, text = 'PLAYER CONTROLS', pos = (-.5, .3), scale = 0.08, fg=(0,0,0,1),shadow=(.5,.5,.5,1))
		OnscreenText(parent=self.control_frame, text = 'OTHER CONTROLS', pos = (.5, .3), scale = 0.08, fg=(0,0,0,1),shadow=(.5,.5,.5,1))

		# Player control instructions
		OnscreenText(parent=self.control_frame, text = '[w] - Forward', pos = (-.5, .2), scale = 0.07, fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[a] - Left', pos = (-.5, .1), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[d] - Right', pos = (-.5, 0), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[s] - Back', pos = (-.5, -.1), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[space] - Jump', pos = (-.5, -.2), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[m] - Toggle Modes', pos = (-.5, -.3), scale = 0.07,fg=(0,0,0,1))

		OnscreenText(parent=self.control_frame, text = '[h] - Help Menu', pos = (.5, .2), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[c] - Toggle Camera Modes', pos = (.5, .1), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[q] - Toggle Music On/Off', pos = (.5, 0), scale = 0.07,fg=(0,0,0,1))
		OnscreenText(parent=self.control_frame, text = '[x] - Toggle SFX On/Off', pos = (.5, -.1), scale = 0.07,fg=(0,0,0,1))

		# Create button to go back to main menu
		self.create_menu_button(self.control_frame,'Back',LVecBase3f(0,0,-.7),self.show_menu)

		# Hide frame
		self.control_frame.hide()
	'''
	    Creates stage selection frame. This frame is hidden.
	'''
	def create_stage_selector(self,button=True):
		# Direct frame to hold stage selection buttons
		self.stage_select_frame = DirectFrame(parent=self.main_frame,frameColor = (.8,.8,.8,.9),frameSize=(-2,2,-1,1), pos=(0,0,0))
		
		title = OnscreenText(parent=self.stage_select_frame, text = 'Stage Selection', pos = (0, .7), scale = .15,fg=(0,.2,.2,1))

		# Stage select buttons with title for each button 
		t1 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 1', pos = (-.9, .5), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/stage1.png','',LVecBase3f(-.9,0,.2),self.__game.clean_and_set,'L1')
		# Stage 2 will be unlocked when stage 2 is made		
		t2 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 2', pos = (-.3, .5), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/stage2.png','',LVecBase3f(-.3,0,.2),self.__game.clean_and_set,'L2')
		
		t3 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 3', pos = (.3, .5), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(.3,0,.2),self.__game.clean_and_set,'L3')
		
		t4 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 4', pos = (.9, .5), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(.9,0,.2),self.__game.clean_and_set,'L4')
		
		t5 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 5', pos = (-.9, -.1), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(-.9,0,-.4),self.__game.clean_and_set,'L5')
		
		t6 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 6', pos = (-.3, -.1), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(-.3,0,-.4),self.__game.clean_and_set,'L6')
		
		t7 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 7', pos = (.3, -.1), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(.3,0,-.4),self.__game.clean_and_set,'L7')
			
		t8 = OnscreenText(parent=self.stage_select_frame, text = 'STAGE 8', pos = (.9, -.1), scale = 0.07,fg=(0,.2,.2,1))
		self.create_stage_button(self.stage_select_frame,'img/locked.jpg','',LVecBase3f(.9,0,-.4),self.__game.clean_and_set,'L8')
		
		if button is True:		
			# Create button to go back to main menu
			self.create_menu_button(self.stage_select_frame,'Back',LVecBase3f(0,0,-.8),self.show_menu)
		
		# Hide frame
		self.stage_select_frame.hide()

	
	'''
	    Creates leaderboard selection frame which will contain links to the leaderboard for the different game stages. This frame is hidden.
	'''
	def create_leaderboard_selector(self):
		# Direct frame to hold links to the leaderboards for different levels
		self.leaderboard_selection_frame = DirectFrame(parent=self.main_frame,frameColor = (.8,.8,.8,.9),frameSize=(-2,2,-1,1), pos=(0,0,0))

		# Frame title
		title = OnscreenText(parent=self.leaderboard_selection_frame, text = 'LEADERBOARD SELECTION', pos = (0, .6), scale = 0.15, fg=(0,.2,.2,1),shadow=(.5,.5,.5,1))
		
		# Links to leaderboards for the stages that are currently made
		self.link(self.leaderboard_selection_frame,'STAGE 1',LVecBase3f(0,0,.0),self.show_leaderboard,'L1')
		self.link(self.leaderboard_selection_frame,'STAGE 2',LVecBase3f(0,0,-.1),self.show_leaderboard,'L2')
		
		# Create button to go back to main menu
		self.create_menu_button(self.leaderboard_selection_frame,'Back',LVecBase3f(0,0,-.4),self.show_menu)

		# Hide frame 
		self.leaderboard_selection_frame.hide()

	'''
	    Leaderboard is created based on the level that was clicked on the leaderboard selector frame. This information is gathered from the stored information in
	    .leaderboard.txt. This method will look for the correct section in the file and output the information for the stage choosen onto a direct frame.
	'''
	def create_leaderboard(self,level):
		# Direct frame to hold all contents of the leaderboard
		self.leaderboard_frame = DirectFrame(parent=self.main_frame,frameColor = (.8,.8,.8,.9),frameSize=(-2,2,-1,1), pos=(0,0,0))

		# Create a scroll_frame to hold contents of leaderboard file
		scroll_frame = DirectScrolledFrame(parent = self.leaderboard_frame,
						   canvasSize=(-1,1,-4,4),
					           frameColor = (1,1,1,.9),
						   frameSize=(-1,1,-.5,.5), 
						   pos=(0,0,0),
						   manageScrollBars=True,
						   scrollBarWidth = .04, 
					           autoHideScrollBars = True)

		# Frame title
		title = OnscreenText(parent=self.leaderboard_frame, text = 'LEADERBOARD', pos = (0, .6), scale = 0.15, fg=(0,.2,.2,1),shadow=(.5,.5,.5,1))
		
		# Open .leaderboard.txt file as read only
		leaderboard_file = open('files/.leaderboard.txt','r')
		start_read = False					# Boolean that will used to notify loop when to start generating text on the scroll canvas
		start = leaderboard_file.read(1)			# Reads only the first byte of the file, equivalent to a character

		# Guide for leaderboard
		name = OnscreenText(parent=scroll_frame.getCanvas(), text = 'NAME', pos = (-.1, 3.9), scale = 0.075,fg=(0,.2,.2,1))
		score = OnscreenText(parent=scroll_frame.getCanvas(), text = 'SCORE', pos = (.5, 3.9), scale = 0.075,fg=(0,.2,.2,1))
		
		index = 1
		v_pos = 3.8

		# Loop will iterate through the contents of the file
		while len(start) != 0:
			if start == '#': leaderboard_file.readline()			# Comments in text file start with an octothorpe and are ignored
			elif start == '@'and start_read is False:			# Line with @ signify the beginning of a set of level info
				if leaderboard_file.readline().split()[0] == level:	# This checks if the info that follows is the information we need
					start_read = True
			elif start == '@'and start_read is True:			# If this condition is true then we read through all the information we need
				break
			elif start_read is True:
				coord = leaderboard_file.readline().split(',')
				if len(coord) == 1:
					name = 'Unknown'				
					score = coord[0]
				else:
					name = start + coord[0]					
					score = coord[1]					
				entry_text = str(index) + ".\t " + name + '\t\t' + score
				# Create onscreen text for each entry
				entry = OnscreenText(parent=scroll_frame.getCanvas(), text = entry_text, pos = (0,v_pos), scale = 0.07,fg=(0,0,0,1))
				# Increase index and decrease vertical position
				index += 1
				v_pos -= .1
			# Read the first byte of the next line
			start = leaderboard_file.read(1)

		leaderboard_file.close()

		# Create button to go back to the leaderboard selection frame
		self.create_menu_button(self.leaderboard_frame,'Back',LVecBase3f(0,0,-.7),self.show_lb_selection)

		# Hide frame
		self.leaderboard_frame.hide()
	
	'''
	    Creates a frame in the top of the window that shows player health and timer. Frame is hidden.
	'''
	def create_health_bar(self):
		# Direct frame that holds all contents such as timer and health bar
		self.health_frame = DirectFrame(parent=self.main_frame,frameColor=(0, 0, 0, .4),frameSize=(-2, 3, -.1, 1),pos=(-.6, 0, .9))
		
		# Create a direct wait bar that will be used as the health gauge.
		self.bar = DirectWaitBar(parent=self.health_frame,
					 text = "HEALTH",
					 text_fg=(1,1,1,1), 
					 value = 100, 
					 range=100, 
					 pos = (.15,0,-.02),
					 barColor=VBase4(0,.2,.2,1),
					 scale=.6)

		# Onscreen image for eve face icon on health gauge
		eve_icon = OnscreenImage(parent=self.bar,image = 'img/eve_face.png', pos = (-1.15, 0, -.075), scale = (.25,1,.25))
		eve_icon.setTransparency(TransparencyAttrib.MAlpha)
		
		# Create a node for timer
		timer_txt = str(self.min) + ' min ' + str(self.sec) + ' seconds'
		self.timer = OnscreenText(parent=self.health_frame, text = timer_txt, pos = (1.5, -.02), scale = 0.07, fg=(1,1,1,1))

		# Hide frame
		self.health_frame.hide()
	
	'''
	    Creates an a token counter in the right bottom corner of screen. This image is hidden.
	'''
	def create_token_counter(self):
		# Set onscreen image and set transparency
		self.shape = OnscreenImage(image = 'img/tire_score.png', pos = (1, 0, -.85), scale = (.3,1,.1))
		self.shape.setTransparency(TransparencyAttrib.MAlpha)
		
		# Set another onscreen image and set transparency
		tire = OnscreenImage(parent=self.shape,image = 'img/tire.png', pos = (-1, 0, 0), scale = (.4,1,1))
		tire.setTransparency(TransparencyAttrib.MAlpha)

		# Set text displaying the number of token collected
		self.score = OnscreenText(parent=self.shape, text = str(self.__game.eve.tiresCollected), pos = (0, -.1), scale = (.3,.8), fg=(255,255,255,1))

		# Hide token counter
		self.shape.hide()

	'''
	    Creates a frame that displays the name of the stage at the beginning of every stage in the game. Only level 1 and 2 are set.
	'''
	def create_stage_title(self,level):
		s_text = ""
		t_text = ""

		# The following if statement set the text that will be displayed
		if level == 'L1':
			s_text = "Stage 1:"
			t_text = "The Journey Begins"
		elif level == 'L2':
			s_text = "Stage 2:"
			t_text = "The Dark Place"
		
		# Direct frame to hold stage title
		self.stage_frame = DirectFrame(parent=self.main_frame,frameColor=(0, 0, 0, .6),frameSize=(-2, 3, -.1, .4),pos=(0, 0, 0))
		
		stage_name = OnscreenText(parent=self.stage_frame, text = s_text, pos = (0, .2), scale = 0.16, fg=(1,.84,0,1),shadow=(1,1,1,.2))
		stage_title = OnscreenText(parent=self.stage_frame, text = t_text, pos = (0, 0), scale = 0.12, fg=(1,.84,0,1),shadow=(1,1,1,.2))

	'''
	    Creates onscreen text showing current position of the character
	'''
	def create_coordinate_view(self):
		self.coord = OnscreenText(parent=self.main_frame,text='1', style = 1, fg= (1,1,1,1),  pos=(0,-0.95), align=TextNode.A_right, scale=0.08)
		self.coord.hide()

	#------------------------------------------------------------------------- SHOW METHODS -----------------------------------------------------------------#

	'''
	    Shows input frame so user can enter his/her name. 	
	'''	
	def show_input(self):
		self.__game.accept('h', self.do_nothing)
		self.start_frame.destroy()
		self.input_frame.show()	
	
	'''
	    Shows menu frame and hides anything else that may be showing	
	'''
	def show_menu(self):
		if self.control_frame.isHidden() is False:
			self.control_frame.hide()
		elif self.leaderboard_selection_frame.isHidden() is False:
			self.leaderboard_selection_frame.hide()
		elif self.stage_select_frame.isHidden() is False:
			self.stage_select_frame.hide()
		self.__game.accept('h', self.toggleHelp)
		self.help_frame.show()
	
	'''
	    Shows frame that contains the game instructions
	'''
	def show_controls(self):
		self.__game.accept('h', self.do_nothing)
		self.help_frame.hide()
		self.control_frame.show()

	'''
	    Shows stage select frame
	'''
	def show_level_select(self):
		self.__game.accept('h', self.do_nothing)
		self.help_frame.hide()
		self.stage_select_frame.show()

	'''
	    Shows leaderboard selector frame
	'''
	def show_lb_selection(self):
		if self.leaderboard_frame.isHidden() is False:
			self.leaderboard_frame.hide()
		elif self.help_frame.isHidden() is False:
			self.__game.accept('h', self.do_nothing)
			self.help_frame.hide()
		self.leaderboard_selection_frame.show()
	
	'''
	    Shows leaderboard frame for a specific level
	    @param level - stage whose leaderboard will be displayed
	'''
	def show_leaderboard(self,level):
		self.leaderboard_selection_frame.hide()
		self.create_leaderboard(level)
		self.leaderboard_frame.show()

	'''
	    Shows in game stats, which is health gauge, timer and token counter
	'''
	def show_game_interface(self):
		self.health_frame.show()
		self.shape.show()

	'''
	    Hides the game interface. This is used when the help menu us shown.
	'''
	def hide_game_interface(self):
		self.health_frame.hide()
		self.shape.hide()


	#------------------------------------------------------------------------- CREATE BTN METHODS -----------------------------------------------------------------#

	'''
	    Creates a button with an= simple button image as the background. This is the default btn.
	    @param parent - who the button will be parented to
	    @param btn_text - text that will be displayed on button
	    @param btn_pos - position of the button
	    @param cmd - command that will be executed when button is clicked
	    @param level - each link created is based on a stage, this is the stage this btn represents
	'''
	def create_menu_button(self,parent,btn_text,btn_pos,cmd):
		start_btn = DirectButton(parent=parent,
					 text=btn_text,
					 pos=btn_pos,
					 scale=(.2,1,.15),
					 command=cmd,
					 pressEffect=1,
					 text_scale=(.4,.4),
					 text_pos=(.1,.1),
					 text_fg=(.1,.1,.1,1),
					 text_shadow=(1,1,1,1),
					 image='img/btn2.png',
					 image_scale=(2.50,1,.7),
					 image_pos=(0,1,.25),
					 relief=None,
					 rolloverSound = self.hover,
					 clickSound=self.click)
		start_btn.setTransparency(TransparencyAttrib.MAlpha)

	'''
	    Creates a button that contains an image of a stage or if it was not yet created it contains an image of a lock
	    @param parent - who the button will be parented to
	    @param btn_text - text that will be displayed on button
	    @param btn_pos - position of the button
	    @param cmd - command that will be executed when button is clicked
	    @param level - each link created is based on a stage, this is the stage this btn represents
	'''
	def create_stage_button(self,parent,img,btn_text,btn_pos,cmd,level):

		click_sound = self.blocked
		hover_sound = self.blocked
		
		# This if statement sets the sound that each button will have. 
		# Everything that is not level 1 or level 2 will have the blocked sound effect and will do nothing
		if level == 'L1' or level == 'L2':
			click_sound = self.click
			hover_sound = self.hover

		btn = DirectButton(parent=parent,
					 text=btn_text,
					 pos=btn_pos,
					 scale=(.2,1,.15),
					 command=cmd,
					 pressEffect=1,
					 text_scale=(.4,.4),
					 text_pos=(.1,.1),
					 text_fg=(.1,.1,.1,1),
					 text_shadow=(1,1,1,1),
					 image=img,
					 image_scale=(1,1,1),
					 image_pos=(0,1,.25),
					 relief=None,
					 rolloverSound = hover_sound,
					 clickSound=click_sound,
					 extraArgs=[level])
		btn.setTransparency(TransparencyAttrib.MAlpha)

	'''
	    Creates a button with no relief and no background image or color.
	    @param parent - who the button will be parented to
	    @param btn_text - text that will be displayed on button
	    @param btn_pos - position of the button
	    @param cmd - command that will be executed when button is clicked
	    @param level - each link created is based on a stage, this is the stage this btn represents
	'''
	def link(self,parent,btn_text,btn_pos,cmd,level):
		btn = DirectButton(parent=parent,
					 text=btn_text,
					 pos=btn_pos,
					 scale=(.2,1,.15),
					 command=cmd,
					 pressEffect=1,
					 text_scale=(.4,.4),
					 text_pos=(.1,.1),
					 text_fg=(.1,.1,.1,1),
					 relief=None,
					 rolloverSound = self.hover,
					 clickSound=self.click,
					 extraArgs = [level])

	def link2(self,parent,btn_text,btn_pos,cmd):
		btn = DirectButton(parent=parent,
					 text=btn_text,
					 pos=btn_pos,
					 scale=(.2,1,.15),
					 command=cmd,
					 pressEffect=1,
					 text_scale=(.4,.4),
					 text_pos=(.1,.1),
					 text_fg=(.1,.1,.1,1),
					 relief=None,
					 rolloverSound = self.hover,
					 clickSound=self.click)


	#------------------------------------------------------------------------- TASK METHODS -----------------------------------------------------------------#
	
	'''
	    At the beginning of every stage the title is show. This task only runs for the first 2 seconds of each stage. It shows
	    the stage title for 2 seconds and then destroys the frame containing the title and the task ends.
	'''	
	def show_title(self,task):
		if globalClock.getRealTime() - self.__game.actual_start > 2:	# Wait two seconds
			self.stage_frame.destroy()
			self.show_game_interface()
			self.__game.eve.enable_character_controls()		# Enable character controls only after the two seconds have passed
			self.__game.accept('h', self.toggleHelp)
			self.__game.accept('f1', self.__game.toggleDebug)
			return Task.done
		return Task.cont
	
	'''
	    This task runs continuously throughout each stage. It updates the time remaining in the current level.
	    This task ends when the minutes and seconds reach 0.
	'''
	def update_timer(self,task):
		elapsed_time = globalClock.getRealTime() - self.__game.actual_start
		change_time = int(elapsed_time) % 60
		if change_time == 0 and self.previous != int(elapsed_time):
			self.min = self.min - int(elapsed_time) / 60
			self.sec = 59
		else:
			if self.previous != int(elapsed_time):
				self.sec = 59 - change_time 
	
		self.timer['text'] = str(self.min) + ' min ' + str(self.sec) + ' seconds'
		self.previous = int(elapsed_time)
		if self.min == 0 and self.sec == 0:
			self.__game.game_over = True
			return Task.done
		return Task.cont 

	'''
	    In debug mode the user can view the players current position in the left bottom corner. This task
	    takes care of updating that position onscreen text.
	'''
	def updateCoord(self, task):
        	x = self.__game.eve.currentNP.getX()
       		y = self.__game.eve.currentNP.getY()
        	z = self.__game.eve.currentNP.getZ()
        	self.coord.setText(str(x) + " , " + (str(y)) + " , "  + str(z))
        	return Task.cont


	def game_over(self):
		self.game_over_frame = DirectFrame(parent = self.main_frame,frameColor=(1, 1, 1, .7),frameSize=(-2, 2, 1, -1),pos=(0, 0, 0))
		OnscreenText(parent = self.game_over_frame,text = 'GAME OVER', pos = (0, 0), scale = .1, fg=(1,0,0,1))
		OnscreenText(parent = self.game_over_frame,text = 'RETRY?', pos = (0, -.2), scale = .07, fg=(1,0,0,1))
		self.link(self.game_over_frame,'YES',LVecBase3f(.3,0,-.3),self.__game.clean_and_set,self.__game.current_level)
		self.link2(self.game_over_frame,'NO',LVecBase3f(-.3,0,-.3),sys.exit)

		
	
	def level_passed(self):
		self.level_passed_frame = DirectFrame(parent = self.main_frame,frameColor=(1, 1, 1, .9),frameSize=(-2, 2, 1, -1),pos=(0, 0, 0))
		if self.__game.current_level == 'L1':
			t1 = OnscreenText(parent = self.level_passed_frame,text = 'STAGE 1 COMPLETE', pos = (0, 0), scale = .1, fg=(1,0,0,1))
		elif self.__game.current_level == 'L2':
			t1 = OnscreenText(parent = self.level_passed_frame,text = 'STAGE 2 COMPLETE', pos = (0, 0), scale = .1, fg=(1,0,0,1))
		t2 = OnscreenText(parent = self.level_passed_frame,text = 'Wheels Collected : ' + str(self.__game.eve.tiresCollected) + ' / ' + str(self.__game.e.total_tokens) , pos = (0, -.2), scale = .1, fg=(1,0,0,1))
		t3 = OnscreenText(parent = self.level_passed_frame,text = 'Score : ' + str(self.__game.user.score) , pos = (0, -.3), scale = .1, fg=(1,0,0,1))

		OnscreenText(parent = self.level_passed_frame,text = 'CONTINUE?', pos = (0, -.5), scale = .07, fg=(1,0,0,1))
		if self.__game.current_level == 'L1':
			self.link(self.level_passed_frame,'YES',LVecBase3f(.3,0,-.6),self.__game.clean_and_set,'L2')
		else:
			self.link(self.level_passed_frame,'YES',LVecBase3f(.3,0,-.6),self.__game.clean_and_set,'L1')
		self.link2(self.level_passed_frame,'NO',LVecBase3f(-.3,0,-.6),sys.exit)

	'''
	    After user inputs his/her name in the beginning of the game, this method is execute and a new user is instantiated and the game is setup.
	    Aside from this two things are added to the task manager...the timer and the stage title.
	'''
	def set_player(self,entry):
		print '\tWELCOME ' + entry + ' ...'
		print '\tSETTING UP USER ...'
		self.input_frame.destroy()				# Destroy the input frame
		self.__game.user = User(entry)		# Frame title

		self.stage_select_frame.show()

	
	'''
	   Method used to toggle between the help menu and the game.
	'''
	def toggleHelp(self):
		if self.help_frame.isHidden():
			# Stop update task and disable character controls when help is activated
			self.pause.play()
			self.__game.taskMgr.remove('update')
			self.hide_game_interface()
			self.__game.eve.disable_character_controls()
			self.help_frame.show()
		else:
			# Restart update task and enable character controls when help is deactivated
			self.pause.play()
			self.__game.taskMgr.add(self.__game.update,'update')            # Add task to task manager
			self.show_game_interface()
			self.__game.eve.enable_character_controls()
			self.help_frame.hide()
	
	'''
	    Method does nothing but is important to stop the h key from working when help menu is in a sub menu or frame
	'''
	def do_nothing(self):
		pass
Exemple #25
0
class PlayerHUD():
    def __init__(self):
        #
        # Player status section
        #
        heartscale = (0.1, 1, 0.1)
        self.heart1 = OnscreenImage(image="HeartIcon.png",
                                    scale=heartscale,
                                    pos=(0.2, 0, -0.15))
        self.heart1.setTransparency(True)
        self.heart1.reparentTo(base.a2dTopLeft)
        self.heart2 = OnscreenImage(image="HeartIcon.png",
                                    scale=heartscale,
                                    pos=(0.45, 0, -0.15))
        self.heart2.setTransparency(True)
        self.heart2.reparentTo(base.a2dTopLeft)
        self.heart3 = OnscreenImage(image="HeartIcon.png",
                                    scale=heartscale,
                                    pos=(0.7, 0, -0.15))
        self.heart3.setTransparency(True)
        self.heart3.reparentTo(base.a2dTopLeft)

        self.keys = DirectLabel(text="x0",
                                frameColor=(0, 0, 0, 0),
                                text_fg=(1, 1, 1, 1),
                                text_scale=1.8,
                                text_pos=(1, -0.25, 0),
                                text_align=TextNode.ALeft,
                                image="Keys.png",
                                pos=(0.2, 0, -0.4))
        self.keys.setScale(0.085)
        self.keys.setTransparency(True)
        self.keys.reparentTo(base.a2dTopLeft)

        self.actionKey = DirectLabel(frameColor=(0, 0, 0, 0),
                                     text_fg=(1, 1, 1, 1),
                                     scale=0.15,
                                     pos=(0, 0, 0.15),
                                     text=_("Action: E/Enter"))
        self.actionKey.setTransparency(True)
        self.actionKey.reparentTo(base.a2dBottomCenter)
        self.actionKey.hide()

    def show(self):
        self.keys.show()

    def hide(self):
        self.heart1.hide()
        self.heart2.hide()
        self.heart3.hide()
        self.keys.hide()
        self.hideActionKey()

    def setHealthStatus(self, value):
        """this function will set the health image in the top righthand corner
        according to the given value, where value is a integer between 0 and 100
        """
        if value >= 1: self.heart1.show()
        else: self.heart1.hide()
        if value >= 2: self.heart2.show()
        else: self.heart2.hide()
        if value >= 3: self.heart3.show()
        else: self.heart3.hide()

    def showActionKey(self):
        self.actionKey.show()

    def hideActionKey(self):
        self.actionKey.hide()

    def updateKeyCount(self, numKeys):
        self.keys["text"] = "x%d" % numKeys
Exemple #26
0
class MainMenu(DirectObject):
    
    def __init__(self):
        self.node = aspect2d.attachNewNode('MainMenu')
        self.buttons = []
        self.LoadContent()
        self.SetupEventHandlers()
        
    def SetupEventHandlers(self):
        self.accept(ServerJoinResponseEvent.EventName, self.OnServerJoinResponseEvent)
        
        
    def LoadContent(self):
        bg = OnscreenImage(image = 'Assets/Images/Menus/MainMenu/background.png', scale = (2, 1, 1))
        bg.setTransparency(TransparencyAttrib.MAlpha)
        bg.reparentTo(self.node)
        bg.setBin('fixed', 1)
        
        title = OnscreenImage(image = 'Assets/Images/Menus/MainMenu/title.png')
        title.setTransparency(TransparencyAttrib.MAlpha)
        title.reparentTo(self.node)
        
        self.spinner = OnscreenImage(image = 'Assets/Images/Menus/MainMenu/loadingSpinner.png', pos = (-0.15, 1, 0.15), scale = 128.0/1024.0)
        self.spinner.setTransparency(TransparencyAttrib.MAlpha)
        self.spinner.reparentTo(base.a2dBottomRight)
        self.spinner.setBin('gui-popup', 0)
        self.spinner.hide()
        
        self.LoadButton('Button_Offline', 'offline', 'offline_over', 0, 0.2, self.OnButtonClicked, ['offline'])
        self.LoadButton('Button_Multiplayer', 'multiplayer', 'multiplayer_over', 0, 0, self.OnButtonClicked, ['multiplayer'])
        self.LoadButton('Button_Options', 'options', 'options_over', 0, -0.2, self.OnButtonClicked, ['options'])
        self.LoadButton('Button_Exit', 'exit', 'exit_over', 0, -0.4, self.OnButtonClicked, ['exit'])
        
    def LoadButton(self, egg, up, over, x, y, cmd, args):
        maps = loader.loadModel("Assets/Images/Menus/MainMenu/%s" % (egg))
        b = DirectButton(geom = (maps.find('**/%s' % (up)),
                         maps.find('**/%s' % (over)),
                         maps.find('**/%s' % (over)),
                         maps.find('**/%s' % (up))),
                         command = cmd,
                         extraArgs = args,
                         pressEffect = 0,
                         relief = None,
                         rolloverSound = None, 
                         clickSound = None,
                         pos = (x, 1, y),
                         scale = (1, 1, 75.0/500.0))
        b.reparentTo(self.node)
        self.buttons.append(b)
        
    def OnButtonClicked(self, buttonText):
        if(buttonText == 'multiplayer'):
            Globals.ROCKET_CONTEXT.LoadDocument('Assets/libRocket/multiplayer.rml').Show()
            self.DisableButtons()
            self.acceptOnce('multiplayerPopupClose', self.OnMultiplayerClose)
        
        elif(buttonText == 'options'):
            Globals.ROCKET_CONTEXT.LoadDocument('Assets/libRocket/options.rml').Show()
            self.DisableButtons()
            self.acceptOnce('optionsPopupClose', self.OnOptionsClose)
            
        elif(buttonText == 'exit'):
            self.CreateAlertPopup('Exit Game', 'Do you really want to exit?', self.OnExitPopupOkay, self.OnExitPopupCancel)
            
        elif(buttonText == 'offline'):
            Globals.ROCKET_CONTEXT.LoadDocument('Assets/libRocket/offline.rml').Show()
            self.DisableButtons()
            self.acceptOnce('offlinePopupClose', self.OnOfflineClose)
            
    def CreatePopup(self, title, fields, values, onOkay, onCancel):
        p = Popup(title, fields, values, onOkay, onCancel)
        self.OnPopupCreated(p)
        
    def CreateAlertPopup(self, title, text, onOkay, onCancel):
        p = AlertPopup(title, text, onOkay, onCancel)
        self.OnPopupCreated(p)
        
    def CreateFullScreenPopup(self, title, fields, values, onOkay, onCancel):
        p = FullscreenPopup(title, fields, values, onOkay, onCancel)
        self.OnPopupCreated(p)                              
            
    def OnOfflineClose(self, accept):
        if(accept):
            SettingsController.SaveClientSettings()
            taskMgr.doMethodLater(0.1, messenger.send, 'as', ['startOffline'])
        self.EnableButtons()
        
    def OnOptionsClose(self, accept):
        if(accept):
            SettingsController.SaveClientSettings()
        self.EnableButtons()
            
    def OnMultiplayerClose(self, accept):
        if(accept):
            SettingsController.SaveClientSettings()
            self.StartLoadingSpinner()
            self.DisableButtons()
            taskMgr.doMethodLater(0.1, messenger.send, 'as1', ['mainMenuMulti'])
        else:
            self.EnableButtons()
        
    def DisableButtons(self):
        for b in self.buttons:
            b['state'] = DGG.DISABLED
            
    def EnableButtons(self):
        for b in self.buttons:
            b['state'] = DGG.NORMAL
        
    def OnAlertPopupClose(self, popup):
        self.DestroyPopup(popup)
        
    def OnExitPopupOkay(self, popup):
        self.DestroyPopup(popup)
        messenger.send('mainMenuExit')
        
    def OnExitPopupCancel(self, popup):
        self.DestroyPopup(popup)
            
    def OnPopupCreated(self, popup):
        self.DisableButtons()
            
    def DestroyPopup(self, popup):
        popup.Destroy()
        del popup
        
        self.EnableButtons()
            
    def Hide(self):
        self.node.hide()
        
    def Show(self):
        self.node.show()
        
    def StartLoadingSpinner(self):
        self.spinner.show()
        self.spinSequence = Sequence(LerpHprInterval(self.spinner, 2, VBase3(0, 0, 180), VBase3(0, 0, 0)),
                                     LerpHprInterval(self.spinner, 2, VBase3(0, 0, 360), VBase3(0, 0, 180)))
        self.spinSequence.loop()
        
    def StopLoadingSpinner(self):
        self.spinSequence.finish()
        self.spinner.hide()
        
    def OnServerJoinResponseEvent(self, event):
        self.StopLoadingSpinner()
        self.EnableButtons()
        if(not event.GetResponse()):
            p = AlertPopup('Join Game Failed', event.GetReason(), self.ClosePopup, self.ClosePopup)
            self.OnPopupCreated(p)
        
    def ClosePopup(self, popup):
        self.DestroyPopup(popup)
        
        
        
Exemple #27
0
class BEnergy (Bar):
    def __init__(self):
        Bar.__init__(self)
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.amount = 0
        self.tmpAmount = 0
        
        # Background bar
        self.bar = OnscreenImage(image="./tex/energy_bar.png", pos = (-0.74, 0, 0.90),hpr=None, scale = (0.59,1.0,0.09), color=None, parent=None, sort=1)
        self.bar.setTransparency(TransparencyAttrib.MAlpha)
        
        # Energy spites
        self.energyBar = [];
        
        # It prepares sprites amount bar
        i = 0
        while(i<40):
            self.energyBar.append(None)
            self.energyBar.insert(i,OnscreenImage(image="./tex/energy/"+str(i+1)+".png", pos = (-1.27+((i*5)*0.0053), 0, 0.92),hpr=None, scale = (0.01,1.0,0.03), color=None, parent=None, sort=2))
            self.energyBar[i].setTransparency(TransparencyAttrib.MAlpha)
            self.energyBar[i].hide()
            i = i+1
            
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It increases the amount of the bar given
    def increase(self, amnt):
        finalAmount = self.amount+amnt
        if finalAmount <= 200:
            while( self.amount<finalAmount ):
                self.energyBar[self.amount/5].show()
                self.amount = self.amount + 5
    #end increase
    
    # It decreases the amount of the bar given
    def decrease(self, amnt):
        if amnt<5:
            self.tmpAmount = self.tmpAmount + amnt
            if self.tmpAmount >= 5:
                num = (self.amount-5)/5
                self.energyBar[num].hide();
                self.amount = self.amount - 5
                self.tmpAmount = 0
                
        else:
            if self.amount>0:
                initAmount = self.amount
                while( self.amount>(initAmount-amnt) ):
                    num = (self.amount-5)/5
                    if num>=0:
                        self.energyBar[num].hide();
                    self.amount = self.amount - 5 
    #end decrease
    
    # It makes disappear the bar
    def hide(self):
        self.bar.hide()
        
        i = 0
        while(i<40):
            self.energyBar[i].hide()
            i = i+1
    #end hide
    
    # It makes appear the bar
    def show(self):
        self.bar.show()
        
        i = 0
        while(i<(self.amount/5)):
            self.energyBar[i].show()
            i = i+1
    #end show
    
    # It makes that sprite have an intermitent alpha effect for 2 seconds
    def taskGlowing(self, task):
        if task.time > 2:
            self.bar.show()
            i = 0
            while(i<(self.amount/5)):
                self.energyBar[i].show()
                i = i+1
            
            self.isVisible = True
            self.lastTime = 0.0
            return task.done
        else:
            if (task.time - self.lastTime) > 0.15:
                self.lastTime = task.time
                if self.isVisible == True:  
                    self.bar.hide()
                    i = 0
                    while(i<(self.amount/5)):
                        self.energyBar[i].hide()
                        i = i+1
                
                    self.isVisible = False
                else:
                    self.bar.show()
                    i = 0
                    while(i<(self.amount/5)):
                        self.energyBar[i].show()
                        i = i+1
                        
                    self.isVisible = True
                
            return task.cont
    #end taskInvincible
Exemple #28
0
class ClawScreen(GameScreen):
    tex = None

    def __init__(self, screen_manager):
        super(ClawScreen, self).__init__(screen_manager, "claw")

        self.positions = []
        #self.positions.append((-0.78320,0,0.29866))
        #elf.positions.append((-0.64843,0,0.27343))
        #self.positions.append((-0.5,0,0.28385))
        #self.positions.append((-0.32031,0,0.38802))
        #self.positions.append((-0.13867,0,0.58333))

        self.positions.append((-1.08320, 0, 0.29866))
        self.positions.append((-0.84843, 0, 0.27343))
        self.positions.append((-0.6, 0, 0.28385))
        self.positions.append((-0.39, 0, 0.38802))
        self.positions.append((-0.23867, 0, 0.58333))

        self.claw_5combos = OnscreenImage(
            image='assets/images/claw_5combos.png',
            pos=self.positions[0],
            parent=self.node2d,
            scale=.1)
        self.claw_eb = OnscreenImage(image='assets/images/claw_eb.png',
                                     pos=self.positions[1],
                                     parent=self.node2d,
                                     scale=.1)
        self.claw_10m = OnscreenImage(image='assets/images/claw_10m.png',
                                      pos=self.positions[0],
                                      parent=self.node2d,
                                      scale=.1)
        self.claw_addexplode = OnscreenImage(
            image='assets/images/claw_addexplode.png',
            pos=self.positions[3],
            parent=self.node2d,
            scale=.1)
        self.claw_bonusx = OnscreenImage(image='assets/images/claw_bonusx.png',
                                         pos=self.positions[2],
                                         parent=self.node2d,
                                         scale=.1)
        self.claw_carchase = OnscreenImage(
            image='assets/images/claw_carchase.png',
            pos=self.positions[2],
            parent=self.node2d,
            scale=.1)
        self.claw_cfb = OnscreenImage(image='assets/images/claw_cfb.png',
                                      pos=self.positions[4],
                                      parent=self.node2d,
                                      scale=.1)
        self.claw_lock = OnscreenImage(image='assets/images/claw_lock.png',
                                       pos=self.positions[1],
                                       parent=self.node2d,
                                       scale=.1)
        self.claw_superjets = OnscreenImage(
            image='assets/images/claw_superjets.png',
            pos=self.positions[3],
            parent=self.node2d,
            scale=.1)
        self.claw_ss = OnscreenImage(image='assets/images/claw_ss.png',
                                     pos=self.positions[4],
                                     parent=self.node2d,
                                     scale=.1)

        self.claw_5combos.hide()
        self.claw_eb.hide()
        self.claw_10m.hide()
        self.claw_addexplode.hide()
        self.claw_bonusx.hide()
        self.claw_carchase.hide()
        self.claw_cfb.hide()
        self.claw_lock.hide()
        self.claw_superjets.hide()
        self.claw_ss.hide()

        self.awards = []

    def show(self):
        super(ClawScreen, self).show()
        self.fill_slots()

    def hide(self):
        super(ClawScreen, self).hide()

    def get_slots(self):
        return self.awards

    def fill_slots(self):
        self.awards = []
        self.claw_5combos.hide()
        self.claw_eb.hide()
        self.claw_10m.hide()
        self.claw_addexplode.hide()
        self.claw_bonusx.hide()
        self.claw_carchase.hide()
        self.claw_cfb.hide()
        self.claw_lock.hide()
        self.claw_superjets.hide()
        self.claw_ss.hide()

        # Pos 1: 5 COMBOS | 10M
        # POS 2: EB | LOCK
        # POS 3: CAR CHASE | BONUS X
        # POS 4: SUPERJETS | ADD EXPLODE
        # POS 5: CFB | TZ

        for i in range(5):
            r = random.randint(1, 2)
            if i == 0:
                if random.randint(1, 2) == 1:
                    self.claw_5combos.show()
                    self.awards.append("5 combos")
                else:
                    self.claw_10m.show()
                    self.awards.append("10 million")
            if i == 1:
                if random.randint(1, 3) == 1:
                    self.claw_eb.show()
                    self.awards.append("extra ball")
                else:
                    self.claw_lock.show()
                    self.awards.append("lock")
            if i == 2:
                if random.randint(1, 2) == 1:
                    self.claw_carchase.show()
                    self.awards.append("car chase")
                else:
                    self.claw_bonusx.show()
                    self.awards.append("bonus x")
            if i == 3:
                if random.randint(1, 2) == 1:
                    self.claw_superjets.show()
                    self.awards.append("superjets")
                else:
                    self.claw_addexplode.show()
                    self.awards.append("add explode")
            if i == 4:
                if random.randint(
                        1, 2
                ) == 1 and not base.hwgame.current_player().call_for_backup:
                    self.claw_cfb.show()
                    self.awards.append("cfb")
                else:
                    self.claw_ss.show()
                    self.awards.append("ss")
Exemple #29
0
class Player(object, DirectObject.DirectObject):
    #------------------------------------------------------------------------------------------------------
    #Class constructor
    #------------------------------------------------------------------------------------------------------
    def __init__(self):
        self.node = 0  #the player main node
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 10
        self.speedMax = 100
        self.agility = 3
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        #self

        #add text speed
        #---------------------------------------------------------------------------------
        #self.textSpeed = OnscreenText(text = 'Speed: '+str(self.speed), pos = (-1.34, 0.95), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft)
        #self.textHP = OnscreenText(text = 'Health:    '+str(self.HP), pos = (-1.33, 0.85), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft)
        #---------------------------------------------------------------------------------

        self.roll = 0
        self.camHeight = 0

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)

        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    #------------------------------------------------------------------------------------------------------
    #Function to load models and set physics
    #------------------------------------------------------------------------------------------------------
    def loadModel(self):
        #node path for player
        self.node = NodePath('player')
        self.node.setPos(1000, 1000, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('gaivota')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #self.contrail.loadConfig('media/contrail.ptf')
        #self.contrail.start(self.node,render)
        '''
        --------------------------------------------------------------------------------
        #gravity (aceleration 9.82)
        self.gravityFN=ForceNode('world-forces')
        self.gravityFNP=render.attachNewNode(self.gravityFN)
        self.gravityForce=LinearVectorForce(0,0,-9.82) 
        self.gravityFN.addForce(self.gravityForce)
        
        #add gravity to engine
        #base.physicsMgr.addLinerForce(self.gravityForce)
        
        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)
        
        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)
        
        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)
        
        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)
        --------------------------------------------------------------------------------
        '''

    #------------------------------------------------------------------------------------------------------
    #Function that add camera to airplane
    #------------------------------------------------------------------------------------------------------
    def addCamera(self):
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    #------------------------------------------------------------------------------------------------------
    #Functions for airplane events
    #------------------------------------------------------------------------------------------------------
    def addEvents(self):
        self.accept("wheel_up", self.evtSpeedUp)
        self.accept("wheel_down", self.evtSpeedDown)
        self.accept('hit', self.evtHit)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        self.accept('mouse3', self.evtBoostOn)
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    #------------------------------------------------------------------------------------------------------
    #Functions that add collisions for the airplane
    #------------------------------------------------------------------------------------------------------
    def addCollisions(self):
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNode.setFromCollideMask(BitMask32(0x1A))
        self.cNode.setIntoCollideMask(BitMask32(0x4))

        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        self.collisionHandler.addInPattern('hit')
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        # landing segment:
        self.landingCNodeSegment = CollisionNode('playerRay')
        self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20))
        self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8))

        self.landingCNodeSegmentPath = self.node.attachNewNode(
            self.landingCNodeSegment)
        #self.landingCNodeSegmentPath.show()
        base.cTrav.addCollider(self.landingCNodeSegmentPath,
                               self.collisionHandlerQueue)

    #------------------------------------------------------------------------------------------------------
    #Function to add sound to airplane
    #------------------------------------------------------------------------------------------------------
    def addSound(self):
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        #self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

        #Add environment music
        #-------------------------------------------------------------------------------
        self.MusicSound = loader.loadSfx("warm-interlude.mp3")
        self.MusicSound.setLoop(True)
        #self.MusicSound.play()
        self.MusicSound.setVolume(1.5)
        self.MusicSound.setPlayRate(0)

    #------------------------------------------------------------------------------------------------------
    #Function to delete task
    #------------------------------------------------------------------------------------------------------
    def deleteTask(self, task):
        self.__del__()
        return task.done

    #------------------------------------------------------------------------------------------------------
    #Function that update mouse moviments
    #------------------------------------------------------------------------------------------------------
    def mouseUpdateTask(self, task):
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)
        #base.camera.setY(-30+self.speed/10)
        #base.camera.setX(self.roll*0.5)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that update players position
    #------------------------------------------------------------------------------------------------------
    def moveUpdateTask(self, task):
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))

        #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed)
        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that control the explosion of the airplane
    #------------------------------------------------------------------------------------------------------
    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()

        #add explosion sound
        #------------------------------------------------------------------------------
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('explosion.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        #self.Sound.play()
        #------------------------------------------------------------------------------

        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    #------------------------------------------------------------------------------------------------------
    #Function for zoom
    #------------------------------------------------------------------------------------------------------
    def zoomTask(self, task):
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that increase speed
    #------------------------------------------------------------------------------------------------------
    def evtBoostOn(self):
        #taskMgr.remove(self.mouseTask)
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    #------------------------------------------------------------------------------------------------------
    #Function that decrease speed
    #------------------------------------------------------------------------------------------------------
    def evtBoostOff(self):
        self.speed -= 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.ignore('mouse3-up')
        self.addEvents()
        #self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        #self.contrail.loadConfig('../../media/contrail.ptf')
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    #------------------------------------------------------------------------------------------------------
    #Function that controls the event when the airplane hit something
    #------------------------------------------------------------------------------------------------------
    def evtHit(self, entry):
        if entry.getIntoNodePath().getParent().getTag(
                "orign") != self.node.getName():

            #if entry.getIntoNodePath().getName() == "projectile":
            #self.HP -= 1
            #self.textHP.setText('HP   : '+str(self.HP))
            if self.HP == 0:
                self.explode()
            else:
                self.explode()

    #------------------------------------------------------------------------------------------------------
    #Function for freelook on
    #------------------------------------------------------------------------------------------------------
    def evtFreeLookON(self):
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    #------------------------------------------------------------------------------------------------------
    #Function for freelook off
    #------------------------------------------------------------------------------------------------------
    def evtFreeLookOFF(self):
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    #------------------------------------------------------------------------------------------------------
    #Function that delete features of the airplane
    #------------------------------------------------------------------------------------------------------
    def __del__(self):
        self.ignoreAll()
        self.contrail.cleanup()

        #delete stop the sound
        #-------------------------------------------------------------------------------
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.engineSound.stop()
        self.MusicSound.stop()
        #-------------------------------------------------------------------------------

        base.camera.reparentTo(render)
        base.camera.setPos(2000, 2000, 800)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        messenger.send('player-death')

    #------------------------------------------------------------------------------------------------------
    #Function that conrol event that increse speed
    #------------------------------------------------------------------------------------------------------
    def evtSpeedUp(self):
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1.5)
        self.zoom = -5 - (self.speed / 10)
        #speed text
        #self.textSpeed.setText('Speed: '+str(self.speed))

    #------------------------------------------------------------------------------------------------------
    #Function that control event that decrease speed
    #------------------------------------------------------------------------------------------------------
    def evtSpeedDown(self):
        if self.landing:
            return 0
        #speed text
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            #self.engineSound.setVolume(0)
            self.engineSound.setPlayRate(0.5)
        self.zoom = -5 - (self.speed / 10)

    #------------------------------------------------------------------------------------------------------
    #Function that control open menu event(ESC)
    #------------------------------------------------------------------------------------------------------
    def evtMenuOpen(self):
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)
        #disable physics when esc is pressed
        base.disableParticles()
        #control volume
        self.engineSound.stop()
        self.MusicSound.setVolume(0.5)

    #------------------------------------------------------------------------------------------------------
    #Function that control close menu event(ESC)
    #------------------------------------------------------------------------------------------------------
    def evtMenuClose(self):
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
        #enable physics after menu closed
        base.enableParticles()
        #control volume
        #self.engineSound.play()
        self.MusicSound.setVolume(1.5)
Exemple #30
0
class Menu(DirectObject):
    def __init__(self, cursor):
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.title = None
        self.play = None
        self.credits = None
        self.ins = None
        self.selected = "PLAY"

        self.pastTime = 0.0
        self.oldX = 0.0
        self.run = True
        self.moved = 0.0

        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #----------------------------------------------------------------MENU INIT----------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.title = OnscreenImage("./tex/menu/glooveth.png", (0, 0, -0.25),
                                   None, (1.0, 1.0, 0.25), None, None, 10)
        self.title.setTransparency(TransparencyAttrib.MAlpha)

        self.credits = OnscreenImage("./tex/menu/credits.png",
                                     (-1.0, 0, -0.75), None,
                                     (0.25, 1.0, 0.125), None, None, 10)
        self.credits.setTransparency(TransparencyAttrib.MAlpha)

        self.ins = OnscreenImage("./tex/menu/ins.png", (1.0, 0, -0.75), None,
                                 (0.25, 1.0, 0.125), None, None, 10)
        self.ins.setTransparency(TransparencyAttrib.MAlpha)

        self.play = OnscreenImage("./tex/menu/playOver.png", (0, 0, -0.75),
                                  None, (0.35, 1.0, 0.20), None, None, 10)
        self.play.setTransparency(TransparencyAttrib.MAlpha)

        # Cursor
        self.cursor = cursor

        # Start tasks
        taskMgr.add(self.taskMenuMovement, 'taskMenuMovement')

    #end __init__

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It hides the main menu of the game
    def hide(self):
        self.title.hide()
        self.play.hide()
        self.credits.hide()
        self.ins.hide()
        self.run = False

    #end hide

    # It shows the main menu of the game
    def show(self):
        self.title.show()
        self.play.show()
        self.credits.show()
        self.ins.show()
        taskMgr.add(self.taskMenuMovement, 'taskMenuMovement')
        self.run = True

    #end show

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------TASKS,THREADS------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # Menu interaction
    def taskMenuMovement(self, task):
        if (self.run == True):
            mpos = self.cursor.getCursorPos()

            if ((mpos.getX() < -0.33) and (self.oldX >= -0.33)):
                self.selected = "CREDITS"
            elif ((mpos.getX() > -0.33) and (self.oldX <= -0.33)):
                self.selected = "PLAY"
            elif ((mpos.getX() < 0.33) and (self.oldX >= 0.33)):
                self.selected = "PLAY"
            elif ((mpos.getX() > 0.33) and (self.oldX <= 0.33)):
                self.selected = "INS"

            # Making bigger the button selected depending on the region of the cursor
            if (self.selected == "PLAY"):
                self.play.setImage("./tex/menu/playOver.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.35, 1.0, 0.20))
            elif (self.selected == "CREDITS"):
                self.credits.setImage("./tex/menu/creditsOver.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.35, 1.0, 0.20))
            elif (self.selected == "INS"):
                self.ins.setImage("./tex/menu/insOver.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.35, 1.0, 0.20))

            self.oldX = mpos.getX()

            # Setting the others to a smaller size
            if (self.selected == "PLAY"):
                self.credits.setImage("./tex/menu/credits.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.25, 1.0, 0.125))

                self.ins.setImage("./tex/menu/ins.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.25, 1.0, 0.125))
            elif (self.selected == "CREDITS"):
                self.play.setImage("./tex/menu/play.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.25, 1.0, 0.125))

                self.ins.setImage("./tex/menu/ins.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.25, 1.0, 0.125))
            elif (self.selected == "INS"):
                self.play.setImage("./tex/menu/play.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.25, 1.0, 0.125))

                self.credits.setImage("./tex/menu/credits.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.25, 1.0, 0.125))

            return task.cont
        else:
            return task.done

    #end taskMenuMovement


#end class Menu
Exemple #31
0
class MyApp(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)
        self.base = self
        self.font = loader.loadFont('1.ttf')
        self.buttonget= base.loader.loadSfx("buttonget.mp3")
        self.buttondown= base.loader.loadSfx("buttondown.mp3")
        self.victorymusic= base.loader.loadSfx("victory.mp3")
        self.falsemusic= base.loader.loadSfx("false.mp3")
        self.jiechu1 = 0
        self.jiechu2 = 0
        self.down = 0
        self.menuon = 0
        # ESC退出
        self.accept("escape", self.caidan)
        self.accept("q", self.victory)
        self.accept("w", self.false)
        # 背景
        self.beijing = OnscreenImage(
            image='1.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02))
        # 开始游戏碰之前图片
        self.a1 = OnscreenImage(image='buttontemp2.png',
                                pos=(0.8, 0, -0.5), scale=(0.2, 0.1, 0.065))
        self.a1.setTransparency(TransparencyAttrib.MAlpha)
        # 碰到开始游戏后显示的按钮
        self.zjmkaishi = DirectButton(text=('', '', '', 'disabled'), image='button2.png', frameColor=(255, 255, 255, 0),
                                      image_scale=(1.8, 1, 0.6), pos=(0.8, 0, -0.5), scale=0.1,
                                      rolloverSound=self.buttonget,clickSound=self.buttondown,
                                      command=self.putdown)
                                      #(2, 1, 0.7)
        self.zjmkaishi.hide()
        self.b1 = OnscreenImage(image='buttontemp1.png',
                                pos=(0.8, 0, -0.5), scale=(0.25, 0.1, 0.13))
        self.b1.setTransparency(TransparencyAttrib.MAlpha)
        self.b1.hide()
        # 点击开始游戏后图片
        self.c1 = OnscreenImage(image='buttontemp3.png',
                                pos=(0.8, 0, -0.5), scale=(0.2, 0.1, 0.065))
        self.c1.setTransparency(TransparencyAttrib.MAlpha)
        self.c1.hide()
        # 开始游戏显示的文字
        self.textObjectstart1 = OnscreenText(
            text='开始游戏', pos=(0.8, -0.51, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.textObjectstart2 = OnscreenText(
            text='开始游戏', pos=(0.8, -0.51, 0), scale=0.055, fg=(255, 255, 255, 1))
        self.textObjectstart2.hide()
        self.textObjectstart3 = OnscreenText(
            text='开始游戏', pos=(0.8, -0.51, 0), scale=0.06, fg=(255, 255, 255, 1))
        self.textObjectstart3.hide()
        self.textObjectstart1.setFont(self.font)
        self.textObjectstart2.setFont(self.font)
        self.textObjectstart3.setFont(self.font)

        # 退出游戏碰之前图片
        self.a2 = OnscreenImage(image='buttontemp2.png',
                                pos=(0.8, 0, -0.7), scale=(0.2, 0.1, 0.065))
        self.a2.setTransparency(TransparencyAttrib.MAlpha)
        # 碰到退出游戏后显示的按钮
        self.zjmkaishi2 = DirectButton(text=('', '', '', 'disabled'), image='button2.png', frameColor=(255, 255, 255, 0),
                                       image_scale=(1.8, 1, 0.6), pos=(0.8, 0, -0.7), scale=0.1, command=self.quit,
                                       rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.zjmkaishi2.hide()
        self.b2 = OnscreenImage(image='buttontemp1.png',
                                pos=(0.8, 0, -0.7), scale=(0.25, 0.1, 0.13))
        self.b2.setTransparency(TransparencyAttrib.MAlpha)
        self.b2.hide()
        # 点击退出游戏后图片
        self.c2 = OnscreenImage(image='buttontemp3.png',
                                pos=(0.8, 0, -0.7), scale=(0.2, 0.1, 0.071))
        self.c2.setTransparency(TransparencyAttrib.MAlpha)
        self.c2.hide()
        # 退出游戏显示的文字
        self.textObjectstart4 = OnscreenText(
            text='退出', pos=(0.8, -0.71, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.textObjectstart5 = OnscreenText(
            text='退出', pos=(0.8, -0.71, 0), scale=0.055, fg=(255, 255, 255, 1))
        self.textObjectstart5.hide()
        self.textObjectstart6 = OnscreenText(
            text='退出', pos=(0.8, -0.71, 0), scale=0.06, fg=(255, 255, 255, 1))
        self.textObjectstart6.hide()
        self.textObjectstart4.setFont(self.font)
        self.textObjectstart5.setFont(self.font)
        self.textObjectstart6.setFont(self.font)

        # ESC菜单
        self.caidanjiemian = OnscreenImage(
            image='caidan.jpg', pos=(0, 0, 0), scale=(0.5, 0.1, 0.41))
        self.caidanjiemian.hide()

        self.bangzhu1button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7), pos=(0, 0, 0.23), scale=0.1, command=self.putdown1,
                                           rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.bangzhu1button.hide()
        self.bangzhu1 = OnscreenText(text='游戏帮助', pos=(
            0, 0.21, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.bangzhu1.setFont(self.font)
        self.bangzhu1.hide()

        self.bangzhu2button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7), pos=(0, 0, 0.03), scale=0.1, command=self.putdown2,
                                           rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.bangzhu2button.hide()
        self.bangzhu2 = OnscreenText(text='继续游戏', pos=(
            0, 0.01, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.bangzhu2.setFont(self.font)
        self.bangzhu2.hide()

        self.bangzhu3button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7), pos=(0, 0, -0.18), scale=0.1, command=self.putdown3,
                                           rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.bangzhu3button.hide()
        self.bangzhu3 = OnscreenText(text='退出游戏', pos=(
            0, -0.2, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.bangzhu3.setFont(self.font)
        self.bangzhu3.hide()

        self.bangzhujiemian = OnscreenImage(
            image='caidan.jpg', pos=(-0, 0, 0), scale=(1, 0.1, 0.81))
        self.bangzhujiemian.hide()
        self.bangzhuxinxi = OnscreenText(
            text='coooooooooooooooool', pos=(0, 0, 0), scale=0.1)
        self.bangzhuxinxi.hide()
        self.bangzhuxinxibutton = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0),
                                               image_scale=(2.2, 1, 0.7), pos=(0.55, 0, -0.55), scale=0.1, command=self.help1,
                                               rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.bangzhuxinxibutton.hide()
        self.bangzhuxinxi1 = OnscreenText(
            text='返回', pos=(0.55, -0.56, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.bangzhuxinxi1.setFont(self.font)
        self.bangzhuxinxi1.hide()

        # 游戏胜利
        self.victorypic = OnscreenImage(
            image='victory.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02))
        self.victorypic.hide()
        # 游戏失败
        self.falsepic = OnscreenImage(
            image='false.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02))
        self.falsepic.hide()
        self.rebornbutton = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0),
                                         image_scale=(2.2, 1, 0.7), pos=(0.75, 0, -0.75), scale=0.1, command=self.reborn,
                                         rolloverSound=self.buttonget,clickSound=self.buttondown)
        self.rebornbutton.hide()
        self.reborntext = OnscreenText(
            text='返回主菜单', pos=(0.75, -0.76, 0), scale=0.05, fg=(255, 255, 255, 1))
        self.reborntext.setFont(self.font)
        self.reborntext.hide()

        #事件队列
        taskMgr.add(self.example, 'MyTaskName')

# 按下ESC触发
    def caidan(self):
        if(self.menuon == 0):
            self.menuon = 1
            self.caidanjiemian.show()
            self.bangzhu1button.show()
            self.bangzhu2button.show()
            self.bangzhu3button.show()
            self.bangzhu1.show()
            self.bangzhu2.show()
            self.bangzhu3.show()
        else:
            self.menuon = 0
            self.caidanjiemian.hide()
            self.bangzhu1button.hide()
            self.bangzhu2button.hide()
            self.bangzhu3button.hide()
            self.bangzhu1.hide()
            self.bangzhu2.hide()
            self.bangzhu3.hide()
            self.bangzhujiemian.hide()
            self.bangzhuxinxi.hide()
            self.bangzhuxinxi1.hide()
            self.bangzhuxinxibutton.hide()

# 无限循环
    def example(self, task):
        mpos = base.mouseWatcherNode.getMouse()
        if mpos.getY() < -0.42 and mpos.getY() > -0.55 and mpos.getX() > 0.45 and mpos.getX() < 0.75:
            #print(mpos.getY())
            self.jiechu1 = 1
        elif mpos.getY() < -0.62 and mpos.getY() > -0.75 and mpos.getX() > 0.45 and mpos.getX() < 0.75:
            # print(mpos.getY())
            self.jiechu2 = 1
        else:
            self.jiechu1 = 0
            self.jiechu2 = 0
        if(self.jiechu1 == 1 and self.down == 0):
            self.zjmkaishi.show()
            # self.textObjectstart1.hide()
            self.textObjectstart2.show()
            self.b1.show()
        elif(self.jiechu2 == 1 and self.down == 0):
            self.zjmkaishi2.show()
            # self.textObjectstart4.hide()
            self.textObjectstart5.show()
            self.b2.show()
        elif(self.down == 0):
            self.c1.hide()
            self.c2.hide()
            self.b1.hide()
            self.b2.hide()
            self.a1.show()
            self.a2.show()
            self.zjmkaishi.hide()
            self.textObjectstart3.hide()
            self.textObjectstart2.hide()
            self.textObjectstart1.show()
            self.zjmkaishi2.hide()
            self.textObjectstart6.hide()
            self.textObjectstart5.hide()
            self.textObjectstart4.show()
        else:
            self.b1.hide()
            self.b2.hide()
            self.zjmkaishi.hide()
            self.textObjectstart2.hide()
            self.zjmkaishi2.hide()
            self.textObjectstart5.hide()
        return task.cont
        # return task.done
# 按下开始游戏触发

    def putdown(self):
        print('start')
        self.down = 1
        self.a1.hide()
        self.b1.hide()
        self.zjmkaishi.hide()
        self.c1.show()
        self.textObjectstart1.hide()
        self.textObjectstart2.hide()
        self.textObjectstart3.show()

        self.beijing.hide()
        self.textObjectstart1.hide()
        self.textObjectstart2.hide()
        self.textObjectstart3.hide()
        self.textObjectstart4.hide()
        self.textObjectstart5.hide()
        self.textObjectstart6.hide()
        self.a1.hide()
        self.a2.hide()
        self.b1.hide()
        self.b2.hide()
        self.c1.hide()
        self.c2.hide()

# 按下退出游戏触发

    def quit(self):
        print('exit')
        self.down = 1
        self.a2.hide()
        self.zjmkaishi2.hide()
        self.c2.show()
        self.textObjectstart4.hide()
        self.textObjectstart5.hide()
        self.textObjectstart6.show()
        sys.exit()
# 按下菜单界面按钮触发

    def putdown1(self):
        self.caidanjiemian.hide()
        self.bangzhu1button.hide()
        self.bangzhu2button.hide()
        self.bangzhu3button.hide()
        self.bangzhu1.hide()
        self.bangzhu2.hide()
        self.bangzhu3.hide()
        self.bangzhujiemian.show()
        self.bangzhuxinxi.show()
        self.bangzhuxinxibutton.show()
        self.bangzhuxinxi1.show()

    def putdown2(self):
        self.menuon = 0
        self.caidanjiemian.hide()
        self.bangzhu1button.hide()
        self.bangzhu2button.hide()
        self.bangzhu3button.hide()
        self.bangzhu1.hide()
        self.bangzhu2.hide()
        self.bangzhu3.hide()
        self.bangzhujiemian.hide()
        self.bangzhuxinxi.hide()
        self.bangzhuxinxi1.hide()
        self.bangzhuxinxibutton.hide()


    def putdown3(self):
        sys.exit()
        # self.b.show()
# 按下帮助界面的返回触发

    def help1(self):
        self.caidanjiemian.show()
        self.bangzhu1button.show()
        self.bangzhu2button.show()
        self.bangzhu3button.show()
        self.bangzhu1.show()
        self.bangzhu2.show()
        self.bangzhu3.show()
        self.bangzhujiemian.hide()
        self.bangzhuxinxi.hide()
        self.bangzhuxinxibutton.hide()
        self.bangzhuxinxi1.hide()
# 胜利和失败触发

    def victory(self):
        self.victorypic.show()
        self.rebornbutton.show()
        self.reborntext.show()
        self.victorymusic.play()

    def false(self):
        self.falsepic.show()
        self.rebornbutton.show()
        self.reborntext.show()
        self.falsemusic.play()
    def reborn(self):
        print("reborn")
        self.rebornbutton.hide()
        self.reborntext.hide()
        self.victorypic.hide()
        self.falsepic.hide()
        self.down=0
        self.beijing.show()
Exemple #32
0
class Player(object,
             DirectObject.DirectObject):  #Class Player for the airplane
    def __init__(self):  #Class constructor
        self.node = 0  #the player main node
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 70
        self.speedMax = 100
        self.agility = 5
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        self.msg = MessageManager()
        self.roll = 0
        self.camHeight = 0
        global actualScore
        global firstRun
        firstRun = 0
        self.thisScore = OnscreenText(text='Score: ' + str(actualScore),
                                      pos=(1.32, 0.95),
                                      scale=0.07,
                                      fg=(1, 1, 1, 1),
                                      bg=(0.2, 0.2, 0.2, 0.4),
                                      align=TextNode.ARight)
        self.death = 0

        self.ultimaColisao = "InicioUltimaColisao"
        self.atualColisao = "InicioAtualColisao"

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)
        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    def loadModel(self):  #Function to load models and set physics
        #node path for player
        self.node = NodePath('player')
        self.node.setPos(1000, 500, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('gaivota')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #gravity (aceleration 9.82)
        self.gravityFN = ForceNode('world-forces')
        self.gravityFNP = render.attachNewNode(self.gravityFN)
        self.gravityForce = LinearVectorForce(0, 0, -9.82 / 8)
        self.gravityFN.addForce(self.gravityForce)

        #add gravity to engine
        base.physicsMgr.addLinearForce(self.gravityForce)

        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)

        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)

        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)

        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)

    def addCamera(self):  #Function that add camera to airplane
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    def addEvents(self):  #Functions for airplane events
        #self.accept( "wheel_up" , self.evtSpeedUp )#DEBUG
        #self.accept( "wheel_down" , self.evtSpeedDown )#DEBUG
        self.accept('hit', self.evtHit)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        #self.accept('mouse3',self.evtBoostOn) #DEBUG
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    def addCollisions(self):  #Functions that add collisions for the airplane
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNodePath = self.node.attachNewNode(self.cNode)

        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        #raio de colisao:
        self.cNodeRay = CollisionNode('playerDuto')
        self.cNodeRay.addSolid(CollisionRay(0, 0, -1, 0, 0, -1))
        self.cNodePathRay = self.node.attachNewNode(self.cNodeRay)
        base.cTrav.addCollider(self.cNodePathRay, self.collisionHandler)

        self.collisionHandler.addInPattern('hit')
        self.cNode.setIntoCollideMask(0)
        self.cNodeRay.setIntoCollideMask(0)

    def addSound(self):  #Function to add sound to airplane
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

        #Add environment music
        self.MusicSound = loader.loadSfx("warm-interlude.mp3")
        self.MusicSound.setLoop(True)
        self.MusicSound.play()
        self.MusicSound.setVolume(1.5)
        self.MusicSound.setPlayRate(1)

    def deleteTask(self, task):  #Function to delete task
        self.__del__()
        return task.done

    def mouseUpdateTask(self, task):  #Function that update mouse moviments
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    def moveUpdateTask(self, task):  #Function that update players position
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))
        # update scoring system
        global actualScore
        actualScore = actualScore - int((100 * globalClock.getDt()))
        self.thisScore.setText('Score: ' + str(actualScore))
        return task.cont

    def explode(self):  #Function that control the explosion of the airplane
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()

        #add explosion sound
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('explosion.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        self.Sound.play()

        self.deleteTask = taskMgr.doMethodLater(
            2, self.deleteTask,
            'delete task')  # will delete Player within 1 second

    def beatLevel(self):  #Function that control the explosion of the airplane
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        self.MusicSound.stop()
        #Add end of level music
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('FF7Fanfare.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        self.Sound.play()

        messenger.send('game-levelwin')
        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    def zoomTask(self, task):  #Function for zoom
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    def evtBoostOn(self):  #Function that increase speed
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    def evtBoostOff(self):  #Function that decrease speed
        self.speed -= 200
        self.ignore('mouse3-up')
        self.addEvents()
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    def evtHit(
        self, entry
    ):  #Function that controls the event when the airplane hit something
        #print "INTO " + entry.getIntoNodePath().getName()
        #print "FROM " + entry.getFromNodePath().getName()
        #print "PARENT " + entry.getIntoNodePath().getParent().getName()

        if entry.getFromNodePath().getName(
        ) == "playerDuto":  #if it's the collision ray
            self.ultimaColisao = self.atualColisao
            self.atualColisao = entry.getIntoNodePath().getName()
            #print "Ultima Colisao: "+self.ultimaColisao +" | Atual Colisao: " +self.atualColisao #Activate this when debugging
            if self.atualColisao == "duto":  #Plane entering wind area
                #print "ENTROU NO VENTO"  #Activate this when debugging
                #self.msg.addMessage("ENTROU NO VENTO", 1) #DEBUG
                self.vento = LinearVectorForce(0, 0, 50)
                self.gravityFN.addForce(self.vento)
                self.gNode.getPhysical(0).addLinearForce(self.vento)
            if self.ultimaColisao == "duto" and self.atualColisao != "duto":  #Plane entering wind area
                #print "SAIU DO VENTO"  #Activate this when debugging
                #self.msg.addMessage("SAIU DO VENTO", 1) #DEBUG
                self.vento = LinearVectorForce(0, 0, -65)
                self.gravityFN.addForce(self.vento)
                self.gNode.getPhysical(0).addLinearForce(self.vento)

        if entry.getFromNodePath().getName() == self.node.getName(
        ):  #if it's the player itself
            if entry.getIntoNodePath().getParent().getName(
            ) == "EndOfLevel":  #Plane entering Finish area
                self.myImage.hide()  #hide cursor image during death animation
                self.beatLevel()
                base.disableParticles()  #disable physics when hit
                self.engineSound.stop()  #control volume
                self.MusicSound.setVolume(0.5)  #control volume
                #self.msg.addMessage("FINAL DA FASE", 3) #DEBUG
                #print "FINAL DA FASE" #Activate this when debugging
            else:
                self.myImage.hide()  #hide cursor image during death animation
                self.explode()
                self.death = 1
                base.disableParticles()  #disable physics when hit
                self.engineSound.stop()  #control volume
                self.MusicSound.setVolume(0.5)  #control volume

    def evtFreeLookON(self):  #Function for freelook on
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    def evtFreeLookOFF(self):  #Function for freelook off
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    def __del__(self):  #Function that delete features of the airplane
        self.ignoreAll()
        self.contrail.cleanup()

        #delete stop the sound
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.engineSound.stop()
        self.MusicSound.stop()

        base.camera.reparentTo(render)
        base.camera.setPos(1000, 1000, 200)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        #hide cursor image after death
        self.myImage.hide()

        if self.death == 1:
            messenger.send('player-death')

    def evtSpeedUp(self):  #Function that conrol event that increse speed
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1.5)
        self.zoom = -5 - (self.speed / 10)

    def evtSpeedDown(self):  #Function that control event that decrease speed
        if self.landing:
            return 0
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            self.engineSound.setPlayRate(0.5)
        self.zoom = -5 - (self.speed / 10)

    def evtMenuOpen(self):  #Function that control open menu event(ESC)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)
        #disable physics when esc is pressed
        base.disableParticles()
        #control volume
        self.engineSound.stop()
        self.MusicSound.setVolume(0.5)

    def evtMenuClose(self):  #Function that control close menu event(ESC)
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
        #enable physics after menu closed
        base.enableParticles()
        #control volume
        self.engineSound.play()
        self.MusicSound.setVolume(1.5)
Exemple #33
0
class ServiceScreenBase(GameScreen):
    '''
    classdocs
    '''
    def loadBackground(self, imagepath):
        ''' Load a background image behind the models '''

        # We use a special trick of Panda3D: by default we have two 2D renderers: render2d and render2dp, the two being equivalent. We can then use render2d for front rendering (like modelName), and render2dp for background rendering.
        self.background = OnscreenImage(
            parent=render2dp, image=imagepath)  # Load an image object
        base.cam2dp.node().getDisplayRegion(0).setSort(
            -20
        )  # Force the rendering to render the background image first (so that it will be put to the bottom of the scene since other models will be necessarily drawn on top)

    def __init__(self, screen_manager, screen_name):
        '''
        Constructor
        '''
        self.loadBackground("assets/images/service_bg.jpg")
        super(ServiceScreenBase, self).__init__(screen_manager, screen_name)
        self.title_text = OnscreenText(
            self.name,
            1,
            fg=(1, 1, 1, 1),
            pos=(-1.3, 0.90),
            align=TextNode.ALeft,
            scale=.12,
            mayChange=True,
            # font = base.fontLoader.load('Arial Bold.ttf'),
            parent=self.node2d)

        self.uiitems = []
        self.ui_selection_idx = 0
        self.selection_mode = 'view'
        self._menuSelectionEvents = {}

    def hide(self):
        self.background.hide()
        super(ServiceScreenBase, self).hide()

    def show(self):
        self.background.show()
        super(ServiceScreenBase, self).show()

    ##################################################################
    ## BUTTON HANDLING LOGIC
    ##
    ## The logic here is divided into two modes. 'view' and 'edit'.
    ## In 'view' mode, hitting the down/up buttons scrolls through the
    ## focus of the UI elements on the screen (only ones that can
    ## accept input). Hitting 'enter' when an item is in focus will
    ## change the state to 'edit' mode.
    ##
    ## In 'edit' mode, hitting the down/up buttons will scroll through
    ## the values of that particular item. Hitting exit will change
    ## the screen back into view mode so scrolling from item to item
    ## works again. Hitting 'enter' will save the current value of the
    ## item and change the screen back into 'view' mode.
    ##################################################################

    def down(self):
        if len(self.uiitems) < 1: return

        # If we're in view mode, toggle to the next ui display item
        if self.selection_mode == 'view':
            if self.ui_selection_idx == len(self.uiitems) - 1:
                self.ui_selection_idx = 0
            else:
                self.ui_selection_idx += 1

            self.uiitems[self.ui_selection_idx].focus()
        # If we're in edit mode, forward the event to the selected UI item
        else:
            self.uiitems[self.ui_selection_idx].down()

    def up(self):
        if len(self.uiitems) < 1: return
        # If we're in view mode, toggle to the next ui display item
        if self.selection_mode == 'view':
            if self.ui_selection_idx == 0:
                self.ui_selection_idx = len(self.uiitems) - 1
            else:
                self.ui_selection_idx -= 1

            self.uiitems[self.ui_selection_idx].focus()
        # If we're in edit mode, forward the event to the selected UI item
        else:
            self.uiitems[self.ui_selection_idx].up()

    def enter(self):
        if len(self.uiitems) < 1: return
        # If we're currently in view mode, switch to edit mode
        if self.selection_mode == 'view':
            self.selection_mode = 'edit'
        else:
            self.selection_mode = 'view'
        self.uiitems[self.ui_selection_idx].enter()

    def exit(self):
        if len(self.uiitems) < 1: return
        # If we're currently in edit mode, switch back to view mode
        if self.selection_mode == 'edit':
            self.selection_mode = 'view'
            self.uiitems[self.ui_selection_idx].exit()

    def addMenuSelectionHandler(self, menu_item, callback):
        if menu_item in self._menuSelectionEvents.keys():
            self._menuSelectionEvents[menu_item].append(callback)
        else:
            self._menuSelectionEvents[menu_item] = [callback]

    def _menuSelectionMade(self, menu_item):
        if menu_item in self._menuSelectionEvents.keys():
            callback_list = self._menuSelectionEvents[menu_item]
            for callback in callback_list:
                callback()

    def set_title(self, title):
        pass

    def set_instruction(self, instruction):
        pass

    def set_value(self, value):
        pass

    def set_item(self, value):
        pass
Exemple #34
0
class Console:
    def __init__(self):
        return None

    def create(self, renderBase, CommandDictionary):
        base.a2dBottomLeft.set_bin('background',
                                   123)  # avoid drawing order conflict
        self.CommandDictionary = {
            **CommandDictionary,
            **{
                "usage": self.helper,
                "help": self.showCommands
            }
        }  #copy for further use in other methods
        self.hidden = False
        self.textscale = 0.04
        self.Lines = 43
        self.background = OnscreenImage(image=str(MAINDIR) + "/files/bg.png",
                                        pos=(0.65, 0, 1),
                                        parent=base.a2dBottomLeft)
        self.background.setTransparency(TransparencyAttrib.MAlpha)
        self.SavedLines = [
            OnscreenText(text='',
                         pos=(0.02, 0.1 + x * 1.1 * self.textscale),
                         scale=self.textscale,
                         align=TextNode.ALeft,
                         fg=(1, 1, 1, 1),
                         parent=base.a2dBottomLeft) for x in range(self.Lines)
        ]
        self.loadConsoleEntry()
        self.commands = self.CommandDictionary
        #self.entry.reparent_to(App)
        base.accept('f1', self.toggle, [base])
        self.toggle(base)  # initialize as hidden
        return None

    def loadConsoleEntry(self):  #-1.76, 0, -0.97
        self.entry = DirectEntry(scale=self.textscale,
                                 frameColor=(0, 0, 0, 1),
                                 text_fg=(1, 1, 1, 1),
                                 pos=(0.025, 0, 0.03),
                                 overflow=1,
                                 command=self.ConvertToFunction,
                                 initialText="",
                                 numLines=1,
                                 focus=True,
                                 width=40,
                                 parent=base.a2dBottomLeft)
        return None

    def toggle(self, base):
        if self.hidden:
            for i in self.SavedLines:
                i.show()
            self.entry.show()
            self.background.show()
        else:
            for i in self.SavedLines:
                i.hide()
            self.entry.hide()
            self.background.hide()
        self.hidden = not (self.hidden)
        return None

    def clearText(self):
        self.entry.enterText('')
        return None

    def ConvertToFunction(self, data):
        self.entry.destroy()
        self.loadConsoleEntry()
        self.ConsoleOutput(" ")
        self.ConsoleOutput(str(MAINDIR) + ">  " + data)
        self.ConsoleOutput(" ")
        Buffer = [""]
        for x in range(
                len(data)
        ):  # I know the way I did this sucks but I didn't want to think a lot
            if data[x] == "(":
                Buffer.append("(")
                if x != len(data) - 1:
                    Buffer.append("")
            elif data[x] == ")":
                Buffer.append(")")
                if x != len(data) - 1:
                    Buffer.append("")
            elif data[x] == ",":
                if x != len(data) - 1:
                    Buffer.append("")
            else:
                Buffer[len(Buffer) - 1] += data[x]
        try:
            ChosenCommand = self.commands[
                Buffer[0]]  # check if the command exists
            if len(Buffer) - 1 and Buffer[1] == "(" and Buffer[
                    len(Buffer) -
                    1] == ")":  # check if the command has some arguments
                args = Buffer[2:len(Buffer) - 1]
                for i in range(len(args)):
                    try:
                        args[i] = float(args[i])
                    except:
                        args[i] = str(args[i])
                try:
                    ChosenCommand(*args)
                except:
                    self.ConsoleOutput("Wrong arguments provided")
            elif len(Buffer) - 1 and Buffer[len(Buffer) - 1] != ")":
                self.ConsoleOutput('Missing parenthesis ")" in "' + data + '"')
            else:
                try:
                    ChosenCommand()
                except:
                    self.ConsoleOutput(
                        'This command requires (at least) one argument')

        except:
            self.CommandError(Buffer[0])

        return None

    def SError(self, report):
        self.ConsoleOutput("Traceback (most recent call last):")
        self.ConsoleOutput("Incorrect use of the " + str(report) + " command")
        return None

    def CommandError(self, report):
        self.ConsoleOutput("Traceback (most recent call last):")
        self.ConsoleOutput("SyntaxError: command " + str(report) +
                           " is not defined")

    def ConsoleOutput(self, output):
        #maxsize = self.entry['width']
        maxsize = 73
        discretized = [
            output[i:i + maxsize] for i in range(0, len(output), maxsize)
        ]
        for i in discretized:
            for x in range(self.Lines - 1, 0, -1):
                self.SavedLines[x].text = self.SavedLines[x - 1].text
            self.SavedLines[0].text = i
        return None

    def helper(self, index):
        i = self.CommandDictionary[index]
        self.ConsoleOutput("Help concerning command '" + str(index) + "':")
        self.ConsoleOutput("    associated function name is " +
                           str(i.__name__))
        self.ConsoleOutput("Documentation provided: ")
        doc = self.TextToLine(str(i.__doc__))
        self.ConsoleOutput("    " + doc)
        self.ConsoleOutput("Known arguments: ")
        self.ConsoleOutput("    " + str(i.__code__.co_varnames))
        return None

    def showCommands(self):
        self.ConsoleOutput("List of available commands: ")
        for i in self.CommandDictionary:
            self.ConsoleOutput("- " + str(i))
        self.ConsoleOutput(" ")
        self.ConsoleOutput(
            "Use usage(command) for more details on a specific command")
        return None

    def TextToLine(self, text):
        try:
            text = text.replace("\n", "")
        except:
            pass
        return text
Exemple #35
0
class Menu (DirectObject):
    def __init__(self, cursor):        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.title = None
        self.play = None
        self.credits = None
        self.ins = None
        self.selected = "PLAY"
        
        self.pastTime = 0.0
        self.oldX = 0.0
        self.run = True
        self.moved = 0.0
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #----------------------------------------------------------------MENU INIT----------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.title = OnscreenImage("./tex/menu/glooveth.png", (0, 0, -0.25), None, (1.0,1.0,0.25), None, None, 10)
        self.title.setTransparency(TransparencyAttrib.MAlpha)
        
        self.credits = OnscreenImage("./tex/menu/credits.png", (-1.0, 0, -0.75), None, (0.25,1.0,0.125), None, None, 10)
        self.credits.setTransparency(TransparencyAttrib.MAlpha)
        
        self.ins = OnscreenImage("./tex/menu/ins.png", (1.0, 0, -0.75), None, (0.25,1.0,0.125), None, None, 10)
        self.ins.setTransparency(TransparencyAttrib.MAlpha)
        
        self.play = OnscreenImage("./tex/menu/playOver.png", (0, 0, -0.75), None, (0.35,1.0,0.20), None, None, 10)
        self.play.setTransparency(TransparencyAttrib.MAlpha)
        
        # Cursor
        self.cursor = cursor
        
        # Start tasks
        taskMgr.add(self.taskMenuMovement, 'taskMenuMovement')
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------    
    # It hides the main menu of the game
    def hide(self):
        self.title.hide()
        self.play.hide()
        self.credits.hide()
        self.ins.hide()
        self.run = False
    #end hide
    
    # It shows the main menu of the game
    def show(self):
        self.title.show()
        self.play.show()
        self.credits.show()
        self.ins.show()
        taskMgr.add( self.taskMenuMovement, 'taskMenuMovement' )
        self.run = True
    #end show
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------TASKS,THREADS------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # Menu interaction
    def taskMenuMovement(self, task):
        if( self.run == True ):
            mpos = self.cursor.getCursorPos()
            
            if( (mpos.getX() < -0.33) and (self.oldX >= -0.33 ) ):      self.selected = "CREDITS"
            elif( (mpos.getX() > -0.33) and (self.oldX <= -0.33) ):     self.selected = "PLAY"
            elif( (mpos.getX() < 0.33) and (self.oldX >= 0.33) ):       self.selected = "PLAY"                 
            elif( (mpos.getX() > 0.33) and (self.oldX <= 0.33) ):       self.selected = "INS"
            
            # Making bigger the button selected depending on the region of the cursor
            if( self.selected == "PLAY" ):
                self.play.setImage("./tex/menu/playOver.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.35,1.0,0.20))
            elif( self.selected == "CREDITS" ):
                self.credits.setImage("./tex/menu/creditsOver.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.35,1.0,0.20))
            elif( self.selected == "INS" ):
                self.ins.setImage("./tex/menu/insOver.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.35,1.0,0.20))
                
            self.oldX = mpos.getX()
            
            # Setting the others to a smaller size
            if( self.selected == "PLAY" ):
                self.credits.setImage("./tex/menu/credits.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.25,1.0,0.125))
                
                self.ins.setImage("./tex/menu/ins.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.25,1.0,0.125))
            elif( self.selected == "CREDITS" ):
                self.play.setImage("./tex/menu/play.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.25,1.0,0.125))
                
                self.ins.setImage("./tex/menu/ins.png")
                self.ins.setTransparency(TransparencyAttrib.MAlpha)
                self.ins.setScale((0.25,1.0,0.125))
            elif( self.selected == "INS" ):
                self.play.setImage("./tex/menu/play.png")
                self.play.setTransparency(TransparencyAttrib.MAlpha)
                self.play.setScale((0.25,1.0,0.125))
                
                self.credits.setImage("./tex/menu/credits.png")
                self.credits.setTransparency(TransparencyAttrib.MAlpha)
                self.credits.setScale((0.25,1.0,0.125))
            
            return task.cont
        else:   return task.done
    #end taskMenuMovement
        
#end class Menu
Exemple #36
0
class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.base = self
        self.font = loader.loadFont('1.ttf')
        self.jiechu1 = 0
        self.jiechu2 = 0
        self.down = 0
        self.menuon = 0
        # ESC退出
        self.accept("escape", self.caidan)
        # 背景
        self.beijing = OnscreenImage(image='1.jpg',
                                     pos=(0, 0, 0.02),
                                     scale=(1.4, 1, 1))
        # 开始游戏碰之前图片
        self.a1 = OnscreenImage(image='button3.png',
                                pos=(-0.8, 0, 0.7),
                                scale=(0.2, 0.1, 0.071))
        # 碰到开始游戏后显示的按钮
        self.zjmkaishi = DirectButton(text=('', '', '', 'disabled'),
                                      image='button2.png',
                                      frameColor=(255, 255, 255, 0),
                                      image_scale=(2, 1, 0.7),
                                      pos=(-0.8, 0, 0.7),
                                      scale=0.1,
                                      command=self.putdown)
        self.zjmkaishi.hide()
        # 点击开始游戏后图片
        self.c1 = OnscreenImage(image='button1.png',
                                pos=(-0.8, 0, 0.7),
                                scale=(0.2, 0.1, 0.071))
        self.c1.hide()
        # 开始游戏显示的文字
        self.textObjectstart1 = OnscreenText(text='开始游戏',
                                             pos=(-0.8, 0.68, 0),
                                             scale=0.05,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart2 = OnscreenText(text='开始游戏',
                                             pos=(-0.8, 0.68, 0),
                                             scale=0.055,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart2.hide()
        self.textObjectstart3 = OnscreenText(text='开始游戏',
                                             pos=(-0.8, 0.68, 0),
                                             scale=0.06,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart3.hide()
        self.textObjectstart1.setFont(self.font)
        self.textObjectstart2.setFont(self.font)
        self.textObjectstart3.setFont(self.font)

        # 退出游戏碰之前图片
        self.a2 = OnscreenImage(image='button3.png',
                                pos=(-0.8, 0, 0.5),
                                scale=(0.2, 0.1, 0.071))
        # 碰到退出游戏后显示的按钮
        self.zjmkaishi2 = DirectButton(text=('', '', '', 'disabled'),
                                       image='button2.png',
                                       frameColor=(255, 255, 255, 0),
                                       image_scale=(2, 1, 0.7),
                                       pos=(-0.8, 0, 0.5),
                                       scale=0.1,
                                       command=self.quit)
        self.zjmkaishi2.hide()
        # 点击退出游戏后图片
        self.c2 = OnscreenImage(image='button1.png',
                                pos=(-0.8, 0, 0.5),
                                scale=(0.2, 0.1, 0.071))
        self.c2.hide()
        # 退出游戏显示的文字
        self.textObjectstart4 = OnscreenText(text='退出',
                                             pos=(-0.8, 0.48, 0),
                                             scale=0.05,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart5 = OnscreenText(text='退出',
                                             pos=(-0.8, 0.48, 0),
                                             scale=0.055,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart5.hide()
        self.textObjectstart6 = OnscreenText(text='退出',
                                             pos=(-0.8, 0.48, 0),
                                             scale=0.06,
                                             fg=(255, 255, 255, 1))
        self.textObjectstart6.hide()
        self.textObjectstart4.setFont(self.font)
        self.textObjectstart5.setFont(self.font)
        self.textObjectstart6.setFont(self.font)

        # ESC菜单
        self.caidanjiemian = OnscreenImage(image='caidan.jpg',
                                           pos=(0, 0, 0),
                                           scale=(0.5, 0.1, 0.41))
        self.caidanjiemian.hide()

        self.bangzhu1button = DirectButton(text=('', '', '', 'disabled'),
                                           image='button1.png',
                                           frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7),
                                           pos=(0, 0, 0.23),
                                           scale=0.1,
                                           command=self.putdown1)
        self.bangzhu1button.hide()
        self.bangzhu1 = OnscreenText(text='游戏帮助',
                                     pos=(0, 0.21, 0),
                                     scale=0.05,
                                     fg=(255, 255, 255, 1))
        self.bangzhu1.setFont(self.font)
        self.bangzhu1.hide()

        self.bangzhu2button = DirectButton(text=('', '', '', 'disabled'),
                                           image='button1.png',
                                           frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7),
                                           pos=(0, 0, 0.03),
                                           scale=0.1,
                                           command=self.putdown2)
        self.bangzhu2button.hide()
        self.bangzhu2 = OnscreenText(text='继续游戏',
                                     pos=(0, 0.01, 0),
                                     scale=0.05,
                                     fg=(255, 255, 255, 1))
        self.bangzhu2.setFont(self.font)
        self.bangzhu2.hide()

        self.bangzhu3button = DirectButton(text=('', '', '', 'disabled'),
                                           image='button1.png',
                                           frameColor=(255, 255, 255, 0),
                                           image_scale=(2.2, 1, 0.7),
                                           pos=(0, 0, -0.18),
                                           scale=0.1,
                                           command=self.putdown3)
        self.bangzhu3button.hide()
        self.bangzhu3 = OnscreenText(text='退出游戏',
                                     pos=(0, -0.2, 0),
                                     scale=0.05,
                                     fg=(255, 255, 255, 1))
        self.bangzhu3.setFont(self.font)
        self.bangzhu3.hide()

        self.bangzhujiemian = OnscreenImage(image='caidan.jpg',
                                            pos=(-0, 0, 0),
                                            scale=(1, 0.1, 0.81))
        self.bangzhujiemian.hide()
        self.bangzhuxinxi = OnscreenText(text='coooooooooooooooool',
                                         pos=(0, 0, 0),
                                         scale=0.1)
        self.bangzhuxinxi.hide()
        self.bangzhuxinxibutton = DirectButton(text=('', '', '', 'disabled'),
                                               image='button1.png',
                                               frameColor=(255, 255, 255, 0),
                                               image_scale=(2.2, 1, 0.7),
                                               pos=(0.55, 0, -0.55),
                                               scale=0.1,
                                               command=self.help1)
        self.bangzhuxinxibutton.hide()
        self.bangzhuxinxi1 = OnscreenText(text='返回',
                                          pos=(0.55, -0.56, 0),
                                          scale=0.05,
                                          fg=(255, 255, 255, 1))
        self.bangzhuxinxi1.setFont(self.font)
        self.bangzhuxinxi1.hide()

        taskMgr.add(self.example, 'MyTaskName')

# 按下ESC触发

    def caidan(self):
        if (self.menuon == 0):
            self.menuon = 1
            self.caidanjiemian.show()
            self.bangzhu1button.show()
            self.bangzhu2button.show()
            self.bangzhu3button.show()
            self.bangzhu1.show()
            self.bangzhu2.show()
            self.bangzhu3.show()
        else:
            self.menuon = 0
            self.caidanjiemian.hide()
            self.bangzhu1button.hide()
            self.bangzhu2button.hide()
            self.bangzhu3button.hide()
            self.bangzhu1.hide()
            self.bangzhu2.hide()
            self.bangzhu3.hide()
            self.bangzhujiemian.hide()
            self.bangzhuxinxi.hide()
            self.bangzhuxinxi1.hide()
            self.bangzhuxinxibutton.hide()

# 无限循环

    def example(self, task):
        mpos = base.mouseWatcherNode.getMouse()
        if mpos.getY() < 0.77 and mpos.getY() > 0.63 and mpos.getX(
        ) > -0.75 and mpos.getX() < -0.45:
            # print(mpos.getX())
            self.jiechu1 = 1
        elif mpos.getY() < 0.57 and mpos.getY() > 0.43 and mpos.getX(
        ) > -0.75 and mpos.getX() < -0.45:
            self.jiechu2 = 1
        else:
            self.jiechu1 = 0
            self.jiechu2 = 0
        if (self.jiechu1 == 1 and self.down == 0):
            self.zjmkaishi.show()
            #self.textObjectstart1.hide()
            self.textObjectstart2.show()
        elif (self.jiechu2 == 1 and self.down == 0):
            self.zjmkaishi2.show()
            #self.textObjectstart4.hide()
            self.textObjectstart5.show()
        else:
            self.zjmkaishi.hide()
            self.textObjectstart2.hide()
            self.textObjectstart1.show()
            self.zjmkaishi2.hide()
            self.textObjectstart5.hide()
            self.textObjectstart4.show()
        return task.cont
        # return task.done
# 按下开始游戏触发

    def putdown(self):
        print('start')
        self.down = 1
        self.a1.hide()
        self.zjmkaishi.hide()
        self.c1.show()
        self.textObjectstart1.hide()
        self.textObjectstart2.hide()
        self.textObjectstart3.show()
# 按下退出游戏触发

    def quit(self):
        print('exit')
        self.down = 1
        self.a2.hide()
        self.zjmkaishi2.hide()
        self.c2.show()
        self.textObjectstart4.hide()
        self.textObjectstart5.hide()
        self.textObjectstart6.show()
# 按下菜单界面按钮触发

    def putdown1(self):
        self.caidanjiemian.hide()
        self.bangzhu1button.hide()
        self.bangzhu2button.hide()
        self.bangzhu3button.hide()
        self.bangzhu1.hide()
        self.bangzhu2.hide()
        self.bangzhu3.hide()
        self.bangzhujiemian.show()
        self.bangzhuxinxi.show()
        self.bangzhuxinxibutton.show()
        self.bangzhuxinxi1.show()

    def putdown2(self):
        print(2)

    def putdown3(self):
        print(3)
        # self.b.show()


#按下帮助界面的返回触发

    def help1(self):
        self.caidanjiemian.show()
        self.bangzhu1button.show()
        self.bangzhu2button.show()
        self.bangzhu3button.show()
        self.bangzhu1.show()
        self.bangzhu2.show()
        self.bangzhu3.show()
        self.bangzhujiemian.hide()
        self.bangzhuxinxi.hide()
        self.bangzhuxinxibutton.hide()
Exemple #37
0
class WorldGenerator:
    ''' 3D scene generator class '''

    def __init__(self, nbElem=10, minClickablePercentage=2.0, maxClickablePercentage=100.0, uniqueColors=False, minModelSize=15, maxModelSize=25, modelsPath='models', modelsCacheList='modelscache.txt', modelsExceptionList='modelsexception.txt', backgroundsPath='backgrounds', backgroundsCacheList='backgroundslist.txt', colorTint=True, windowWidth=640, windowHeight=480, debug=False):
        # Vars
        self.debug = debug
        self.minClickablePercentage = minClickablePercentage
        self.maxClickablePercentage = maxClickablePercentage
        self.nbElem = nbElem
        self.uniqueColors = uniqueColors # The reference object has a unique color?
        self.modelsPath = modelsPath
        self.modelsCacheList = modelsCacheList
        self.modelsExceptionList = modelsExceptionList
        self.minModelSize = minModelSize
        self.maxModelSize = maxModelSize
        self.rangeModelSize = maxModelSize - minModelSize # precompute the range (optimization)
        self.backgroundsPath = backgroundsPath
        self.backgroundsCacheList = backgroundsCacheList
        self.colorTint = colorTint

        # Set commandline rendering mode (unloading as many rendering module as possible and hiding rendering window)
        if debug: # show rendering window if in debug mode
            loadPrcFileData("",
            """
               load-display p3tinydisplay # to force CPU only rendering (to make it available as an option if everything else fail, use aux-display p3tinydisplay)
               window-type onscreen # Spawn an offscreen buffer (use window-type none if you don't need any rendering)
               audio-library-name null # Prevent ALSA errors
               show-frame-rate-meter 0
               sync-video 0
               win-size """+str(windowWidth)+' '+str(windowHeight)+"""
            """)
        else: # hide rendering window if not in debug mode
            loadPrcFileData("",
            """
               load-display p3tinydisplay # to force CPU only rendering (to make it available as an option if everything else fail, use aux-display p3tinydisplay)
               window-type offscreen # Spawn an offscreen buffer (use window-type none if you don't need any rendering)
               audio-library-name null # Prevent ALSA errors
               show-frame-rate-meter 0
               sync-video 0
               win-size """+str(windowWidth)+' '+str(windowHeight)+"""
            """)

        # Init 3D world
        from direct.showbase.ShowBase import ShowBase
        self.base = ShowBase()

        # Init Cache
        self.cacher = WorldCacher(base=self.base)

        # Init scene camera
        self.base.camLens.setFov(45)

        # Reset colors (else we will see the clickable mask by default)
        #self.renderReset()
        #self.clickableModel.clearColorScale()
        #self.clickableModel.setColor(1,1,1,1)

    def generateScene(self):
        ''' Generate a random 3D scene '''
        # Load models and ensure that the clickable area is reasonable
        clickableAreaOk = False
        while (not clickableAreaOk):
            self.loadBackground()
            self.loadModels(self.nbElem, self.minModelSize, self.maxModelSize, self.modelsPath, self.modelsCacheList, self.modelsExceptionList, self.colorTint)                  # Load and position our models
            clickableAreaOk = self.checkClickableArea(self.minClickablePercentage, self.maxClickablePercentage) # Check that the clickable area is reasonable

    def loadBackground(self, bgdir=None, bgcache=None):
        ''' Load a random background image behind the models '''

        if not bgdir:
            bgdir = self.backgroundsPath
        if not bgcache:
            bgcache = self.backgroundsCacheList

        # Remove the previous background
        if (hasattr(self, 'background')):
            self.background.remove()

        # Create the cache (list of background images) if not already done
        if not os.path.isfile(bgcache):
            WorldCacher.cacheListOfModels(bgdir, bgcache)

        # Pick a random image from the cache
        (bgimage, cur) = fastRandLine(bgcache)

        # Load the background image in the scene
        # We use a special trick of Panda3D: by default we have two 2D renderers: render2d and render2dp, the two being equivalent. We can then use render2d for front rendering (like modelName), and render2dp for background rendering.
        self.background = OnscreenImage(parent=render2dp, image=os.path.join(bgdir, bgimage)) # Load an image object
        base.cam2dp.node().getDisplayRegion(0).setSort(-20) # Force the rendering to render the background image first (so that it will be put to the bottom of the scene since other models will be necessarily drawn on top)

    def loadModels(self, nbElem=None, minModelSize=None, maxModelSize=None, modelsPath=None, modelsCacheList=None, modelsExceptionList=None, colorTint=True):
        ''' Load a given number of models (picked randomly) and set their parameters randomly
        This generates a scene with a unique reference model, and repeatable non clickable models
        '''

        if not nbElem:
            nbElem = self.nbElem
        if not modelsPath:
            modelsPath = self.modelsPath
        if not modelsCacheList:
            modelsCacheList = self.modelsCacheList
        if not modelsExceptionList:
            modelsExceptionList = self.modelsExceptionList
        if not minModelSize:
            minModelSize = self.minModelSize
        if not maxModelSize:
            maxModelSize = self.maxModelSize

        # Open the models list (we cache the list to avoid fetching the whole list of files, which may be very big! and slow down a lot the application)
        if not os.path.isfile(modelsCacheList):
            self.cacher.cacheListOfModelsWithBounds(modelsPath, modelsCacheList) # create the models list if it doesn't exist
            # cacheListOfModels(modelsPath, modelsCacheList)
        modelsList = open(modelsCacheList, 'rb') # open the models list

        # Open the models exception list (these models will be excluded for the reference model)
        if modelsExceptionList and os.path.isfile(modelsExceptionList):
            f = open(modelsExceptionList, 'rb') # open the models list
            exceptionList = [line.strip() for line in f]
        else:
            exceptionList = None

        # Drop all previous objects if we're regenerating the scene
        if (hasattr(self, 'nonClickable')):
            self.nonClickable.remove()

        if (hasattr(self, 'clickable')):
            self.clickable.remove()

        # Create 2 group nodes: one for the clickable model (reference model), and one for all the other objects (the non clickable models)
        self.nonClickable = render.attachNewNode("Non Clickable Objects");
        self.clickable = render.attachNewNode("Clickable Object");

        # Loading randomly picked objects with random parameters
        exceptionCur = [] # list that will contain the reference model, so that we don't load it twice
        for i in xrange(nbElem): # Loading nbElem objects

            # == Loading a random model

            # Pick a random model from the list
            if i == 0: # reference model: picking a random model except the ones listed as exceptions
                (line, cur) = fastRandLine(modelsList, exceptlist=exceptionList)
            else: # other models: picking a random model except the reference model (other models can be repeated, but not the reference model which is unique)
                (line, cur) = fastRandLine(modelsList, exceptposlist=exceptionCur)
            (randomModel, modelSize) = line.split("|") # model name and size are separated by | delimiter
            modelSize = float(modelSize) # get the model size as float instead of string

            # Try to load the random model
            try:
                model = loader.loadModel(os.path.join(modelsPath, randomModel))
            # If the model loading failed, probably the model doesn't exist anymore and the cache isn't up-to-date
            except:
                # in this case, we regenerate the models list
                modelsList.close()
                self.cacher.cacheListOfModelsWithBounds(modelsPath, modelsCacheList)
                #cacheListOfModels(modelsPath, modelsCacheList)
                modelsList = open(modelsCacheList, 'rb')

                # Pick a random model from the list TODO: this is not an elegant code, this is just a copy paste of the code above...
                if i == 0: # reference model: picking a random model except the ones listed as exceptions
                    (line, cur) = fastRandLine(modelsList, exceptlist=exceptionList)
                else: # other models: picking a random model except the reference model (other models can be repeated, but not the reference model which is unique)
                    (line, cur) = fastRandLine(modelsList, exceptposlist=exceptionCur)
                (randomModel, modelSize) = line.split("|") # model name and size are separated by | delimiter
                modelSize = float(modelSize) # get the model size as float instead of string

                model = loader.loadModel(os.path.join(modelsPath, randomModel))



            # == Set random parameters for the model

            # Pick a random color
            randomColor = [random.random(), random.random(), random.random()]
            # Attach the model to the scene
            if i == 0: # the first object is the clickable object (reference model), we do special treatement for it
                self.clickableModel = model # memorize it as the clickable object
                model.reparentTo(self.clickable) # reparent the object to the scene (make it appear in the scene), in the clickable tree
                self.clickableColor = randomColor # memorize the color of the clickable object
                self.clickableColorSet = set(randomColor) # create a set for the clickable color (easiest, fastest and most pythonic way to check that this is a unique color)
                self.clickableModelSize = modelSize # store the model size (to easily and quickly scale and renormalize it)
                self.clickableModelName = randomModel.split('.')[0] # store model name (to be able to print it below the model) - get only the base name without the extension
                exceptionCur.append(cur) # add this model to the list of exceptions (so that any other object cannot be the same as the reference model)
            else: # else for all other non clickable object
                model.reparentTo(self.nonClickable) # reparent the object to the scene, in the nonClickable tree

            # Set random parameters
            model.setPos(random.uniform(20,-20),random.uniform(35, 120),random.uniform(-10, 15)) # set position
            model.setHpr(random.uniform(0, 360), random.uniform(-30, 30), random.uniform(30, -30)) # set orientation
            model = self.normalizeModelSize(model, minModelSize, maxModelSize, modelSize) # set size (normalize size and set a random size in the normalized range)

            # Set color tint
            # check that the color of the non clickable models are not the same as the clickable model
            if self.uniqueColors and i > 0:
                while (self.clickableColorSet.intersection(randomColor)): # check that the same color isn't already applied to the clickable object
                    randomColor = [random.random(), random.random(), random.random()] # generate a new color until we get one that is not assigned to the clickable object
            randomColor.append(1.0) # set color alpha transparency (opaque)
            # Set color tint (keep object's texture)
            if colorTint:
                model.setColorScale(*randomColor)
            # Or set the whole color (overwrites the object's texture)
            else:
                model.setColor(*randomColor)

        # close the models list (freeing memory)
        modelsList.close()

    def normalizeModelSize(self, model, minModelSize, maxModelSize, modelSize=None):
        ''' Normalize a model size in the scene between the given lower and higher bounds '''
        # Check if the range was already precomputed (optimization)
        if self.rangeModelSize:
            rangeModelSize = self.rangeModelSize
        else:
            rangeModelSize = maxModelSize - minModelSize

        # If model size was already precomputed and stored in cache, we don't need to recompute it. Else, we recompute it here.
        if not modelSize:
            # Get the tight bound of the model (return two points representing the tightest axis-aligned box enclosing the model)
            minLimit, maxLimit = model.getTightBounds()

            # Convert to a 3D dimensions object
            dimensions = Point3(maxLimit - minLimit)

            # Get the size of the object from its maximum size in either the X,Y or Z direction
            modelSize = max([dimensions.getX(), dimensions.getY(), dimensions.getZ()])

        # If the model's size is not already in the specified bounds, we resize it
        if not (minModelSize < modelSize < maxModelSize):
            model.setScale( ((random.random()*rangeModelSize) + minModelSize) / modelSize ) # resize the object between the bounds, normalized to 1.0 (since the original scale of the object is set to 1.0, here it is hidden in the numerator)

        # return the new normalized rescaled model
        return model

    def renderClickableArea(self):
        ''' Render the clickable area (visible areas of the reference model painted in white and everything else black)'''
        self.base.setBackgroundColor(0,0,0,1) # set background to black
        self.background.hide()
        if hasattr(self, 'clickableText'):
            self.clickableText.hide()
        self.nonClickable.setColor(0,0,0) # set non clickable objects to black
        self.clickableModel.clearColorScale() # clear clickable object's color (to set a whole new color, else it will be another layer over the previous color)
        self.clickableModel.setColor(1,1,1) # set clickable object to white

    def renderClickableModel(self, showModel=True, showName=False):
        ''' Render just the clickable (reference) model '''
        # Hide all non clickable objects
        self.nonClickable.clearColor()
        self.nonClickable.hide()
        # Show the clickable model with the original texture and color
        self.clickableModel.clearColor()
        self.clickableModel.clearColorScale()
        if showModel:
            # Place it in front of the user, face-to-face (we try to randomly parametrize the position and orientation of the reference model but in a way that the user can clearly see it face-to-face)
            self.clickableModel.setPos(0,40,0)
            self.clickableModel = self.normalizeModelSize(self.clickableModel, self.minModelSize, self.maxModelSize, self.clickableModelSize) # set size (normalize size and set a random size in the normalized range)
            self.clickableModel.setHpr(random.uniform(-45, 45), random.uniform(-15, 15), 0)
            self.clickableModel.setColorScale(random.random(), random.random(), random.random(), 1.0)
        else:
            self.clickable.hide()

        if showName:
            if not hasattr(self, 'clickableText') or self.clickableText != self.clickableModelName:
                if hasattr(self, 'clickableText'):
                    self.clickableText.remove()
                text = TextNode('reference model name')
                text.setText(self.clickableModelName)
                text.setAlign(TextNode.ACenter)
                self.clickableText = render2d.attachNewNode(text)
                self.clickableText.setScale( 0.2 )
                self.clickableText.setPos( 0, 0, -0.8 )

    def renderReset(self):
        ''' Reset the colors and stuffs '''
        self.base.setBackgroundColor(0, 0, 0, a=1) # Clear the background color (we set it to fully transparent, just the same way it is done inside Panda3D core)
        self.background.show() # show the background image
        if hasattr(self, 'clickableText'):
            self.clickableText.hide()
        self.nonClickable.clearColor()
        self.nonClickable.clearColorScale()
        self.nonClickable.show()
        self.clickable.show()
        self.clickableModel.clearColor()
        self.clickableModel.clearColorScale()
        color = list(self.clickableColor) # copy the clickable color
        color.append(1)
        self.clickableModel.setColorScale(*color)
        #self.clickableModel.setColor(*self.clickableColor)


    def checkClickableArea(self, threshold, maxthreshold):
        ''' Facade function that returns True or False if the total visible clickable area of the reference model is above a given threshold '''
        if threshold <= self.getTotalClickableArea() <= maxthreshold:
            return True
        else:
            return False


    #def checkBiggestClickableArea(self, threshold):
        #'''Compute the biggest contiguous area of clickable pixels, and compute its percentage relative to the image total size'''
        #print('TODO!')
        #retun True


    def getTotalClickableArea(self):
        '''Compute the total clickable area, and compute its percentage relative to the image total size'''
        ### RENDERING CLICKABLE AREA
        # Prepare the rendering of the clickable area
        self.renderClickableArea()
        # Render the frame
        self.base.graphicsEngine.renderFrame()

        ### FETCHING THE RENDERED IMAGE
        # Prepare the variable that will store the frame image (in a PNMImage class, this is NOT a file format, but a convenient image manipulation class offered by Panda3D)
        screenshot = PNMImage()
        # Set display region to the default
        dr = base.camNode.getDisplayRegion(0)
        # Store the rendered frame into the variable screenshot
        dr.getScreenshot(screenshot)

        ### COMPUTE THE CLICKABLE AREA PERCENTAGE
        # Prepare an histogram object
        hist = PNMImage().Histogram()
        # Compute the histogram
        screenshot.makeHistogram(hist)
        # Get the number of white opaque pixels (the clickable area)
        totalClickableArea = hist.getCount(PNMImageHeader.PixelSpec(255,255,255, 255))
        # Get the percentage of clickable area relative to the total image size
        totalClickableAreaPercentage = float(totalClickableArea) * 100 / (screenshot.getReadXSize() * screenshot.getReadYSize())

        if self.debug:
            print("Total unique intensity pixels: %f" % hist.getNumPixels())
            print("Total clickable area: %f" % totalClickableArea)
            totalClickableAreaSqrt = sqrt(float(totalClickableArea))
            print("Total clickable area sqrt: %f" % totalClickableAreaSqrt)
            print("Size of image X*Y: %f * %f" %(screenshot.getReadXSize(), screenshot.getReadYSize()))
            print("Total clickable area percentage: %f" % totalClickableAreaPercentage)

            blackarea = hist.getCount(PNMImageHeader.PixelSpec(0,0,0, 255))
            print("Total black area: %f" % blackarea)
            print("Total black area percentage: %f" % (float(blackarea) * 100 / (screenshot.getReadXSize() * screenshot.getReadYSize()))  )

        return totalClickableAreaPercentage


    def renderToPNM(self):
        ### RENDER IMAGE
        # Render the frame
        self.base.graphicsEngine.renderFrame()

        ### FETCHING THE RENDERED IMAGE
        # Prepare the variable that will store the frame image (in a PNMImage class, this is NOT a file format, but a convenient image manipulation class offered by Panda3D)
        image = PNMImage()
        # Set display region to the default
        dr = base.camNode.getDisplayRegion(0)
        # Store the rendered frame into the variable screenshot
        dr.getScreenshot(image)

        return image


    def renderAndSave(self, path='screenshot'):
        ''' Render the scene and save it directly to an image file on disk '''
        base.graphicsEngine.renderFrame()
        base.screenshot(namePrefix=path, defaultFilename=0, source=None, imageComment="")
class BetterOnscreenImage(DebugObject):

    """ Simple wrapper arroun OnscreenImage, providing a simpler interface and
    better visuals """

    def __init__(self, image=None, parent=None, x=0, y=0, w=10, h=10,
                 transparent=True, nearFilter=True, anyFilter=True):
        """ Creates a new image, taking (x,y) as topleft coordinates.

        When nearFilter is set to true, a near filter will be set to the
        texture passed. This provides sharper images.

        When anyFilter is set to false, the passed image won't be modified at
        all. This enables you to display existing textures, otherwise the
        texture would get a near filter in the 3D View, too. """

        DebugObject.__init__(self, "BetterOnscreenImage")

        self.w, self.h = w, h
        self.initialPos = self.translatePos(x, y)

        self._node = OnscreenImage(
            image=image, parent=parent, pos=self.initialPos,
            scale=(w / 2.0, 1, h / 2.0))

        if transparent:
            self._node.setTransparency(TransparencyAttrib.MAlpha)

        tex = self._node.getTexture()

        if nearFilter and anyFilter:
            tex.setMinfilter(Texture.FTNearest)
            tex.setMagfilter(Texture.FTNearest)

        if anyFilter:
            tex.setAnisotropicDegree(8)
            tex.setWrapU(Texture.WMClamp)
            tex.setWrapV(Texture.WMClamp)

    def getInitialPos(self):
        """ Returns the initial position of the image. This can be used for
        animations """
        return self.initialPos

    def posInterval(self, *args, **kwargs):
        """ Returns a pos interval, this is a wrapper arround
        NodePath.posInterval """
        return self._node.posInterval(*args, **kwargs)

    def setImage(self, img):
        """ Sets the current image """
        self._node.setImage(img)

    def setPos(self, x, y):
        """ Sets the position """
        self.initialPos = self.translatePos(x, y)
        self._node.setPos(self.initialPos)

    def translatePos(self, x, y):
        """ Converts 2d coordinates to pandas coordinate system """
        return Vec3(x + self.w / 2.0, 1, -y - self.h / 2.0)


    def hide(self):
        self._node.hide()

    def show(self):
        self._node.show()
Exemple #39
0
class Tutorial (DirectObject):
    def __init__(self, background, cursor, pointer):
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Background
        self.back = background
        
        # Level
        self.level = Level_Tutorial(background)
        
        # Graphic components
        #Blackboard
        self.blackboard = OnscreenImage(image="./tex/blackboard_empty.png", pos = (0, 0, 0),hpr=None, scale = (1.25,1.0,0.90), color=None, parent=None, sort=0)
        self.blackboard.setTransparency(TransparencyAttrib.MAlpha)
        self.blackboard.hide()
        #Main Character
        self.char = CMain(-18,-5,59)
        #Energy Bar
        self.energyBar = BEnergy()
        self.energyBar.increase(50)
        #Abilies Bar
        self.grainAbility = BAbility("GRAIN")
        self.fruitAbility = BAbility("FRUIT")
        self.milkAbility = BAbility("MILK")
        self.vegetableAbility = BAbility("VEGETABLE")
        self.fishAbility = BAbility("FISH")
        #Shape
        self.shape = OnscreenImage(image="./tex/cereal_ability_shape.png", pos = (-0.75, 0, 0),hpr=None, scale = 0.25, color=None, parent=None, sort=1)
        self.shape.setTransparency(TransparencyAttrib.MAlpha)
        self.shape.hide()
        #Item
        self.item = OnscreenImage(image="./tex/rice.png", pos = (-0.75, 0, -0.4),hpr=None, scale = 0.09, color=None, parent=None, sort=1)
        self.item.setTransparency(TransparencyAttrib.MAlpha)
        self.item.hide()
        #Texts
        self.text = OnscreenImage(image="./tex/tryToDrawThisShape.png", pos = (-0.75, 0, 0.6),hpr=None, scale = 0.35, color=None, parent=None, sort=1)
        self.text.setTransparency(TransparencyAttrib.MAlpha)
        self.text.hide()
        self.grassText = OnscreenImage(image="./tex/moveThroughTheGrass.png", pos = (0, 0, 0),hpr=None, scale = 0.7, color=None, parent=None, sort=1)
        self.grassText.setTransparency(TransparencyAttrib.MAlpha)
        #Info
        self.infError = OnscreenImage(image="./tex/wrong_attack.png", pos = (0.4, 0, 0),hpr=None, scale=(0.47,1.0,0.55), color=None, parent=None, sort=5)
        self.infError.setTransparency(TransparencyAttrib.MAlpha)
        self.infError.hide()
        self.infCereal = OnscreenImage(image="./tex/cereal_attack.png", pos = (0.4, 0, 0),hpr=None, scale=0.45, color=None, parent=None, sort=5)
        self.infCereal.setTransparency(TransparencyAttrib.MAlpha)
        self.infCereal.hide()
        self.infFish = OnscreenImage(image="./tex/fish_attack.png", pos = (0.4, 0, 0),hpr=None, scale=0.5, color=None, parent=None, sort=5)
        self.infFish.setTransparency(TransparencyAttrib.MAlpha)
        self.infFish.hide()
        self.infMilk = OnscreenImage(image="./tex/milk_attack.png", pos = (0.4, 0, 0),hpr=None, scale=0.5, color=None, parent=None, sort=5)
        self.infMilk.setTransparency(TransparencyAttrib.MAlpha)
        self.infMilk.hide()
        self.infVege = OnscreenImage(image="./tex/vege_attack.png", pos = (0.4, 0, 0),hpr=None, scale=0.4, color=None, parent=None, sort=5)
        self.infVege.setTransparency(TransparencyAttrib.MAlpha)
        self.infVege.hide()
        self.infFruit = OnscreenImage(image="./tex/fruit_attack.png", pos = (0.4, 0, 0),hpr=None, scale=0.4, color=None, parent=None, sort=5)
        self.infFruit.setTransparency(TransparencyAttrib.MAlpha)
        self.infFruit.hide()
        #Logo
        self.logo = OnscreenImage(image="./tex/laSalleAlpha.png", pos = (1.05, 0, -0.85),hpr=None, scale=(0.22,1.0,0.075), color=None, parent=None, sort=5)
        self.logo.setTransparency(TransparencyAttrib.MAlpha)
          
        # Others
        self.shapeNum = 0
        self.drawedOK = 0
        self.finished = False
        self.drawing = False
        self.readyForGame = False
        self.inGame = False
        self.busy = False
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #----------------------------------------------------------TUTORIAL INIT------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Glove gestures configuration
        self.cursor = cursor
        self.gestureHandler = GestureRecognition("Gesture_Handler", 
                                                 [("1",0), ("2",0), ("3",0), ("4",0), ("6",0), ("7",0), ("8",0), ("9",0),                               #NONE
                                                  ("12",0), ("13",0), ("16",0), ("18",0), ("17",0), ("14",0),                                           #NONE
                                                  ("23",0), ("26",0), ("29",0), ("27",0), ("24",0), ("21",0),                                           #NONE
                                                  ("36",0), ("39",0), ("38",0), ("34",0), ("31",0), ("32",0),                                           #NONE
                                                  ("41",0), ("42",0), ("43",0), ("49",0), ("48",0), ("47",0),                                           #NONE
                                                  ("69",0), ("68",0), ("67",0), ("61",0), ("62",0), ("63",0),                                           #NONE
                                                  ("74",0), ("71",0), ("72",0), ("76",0), ("79",0), ("78",0),                                           #NONE
                                                  ("87",0), ("84",0), ("81",0), ("83",0), ("86",0), ("89",0),                                           #NONE
                                                  ("98",0), ("97",0), ("94",0), ("92",0), ("93",0), ("96",0),                                           #NONE
                                                  ("93934",1),                                                                                          #FRUIT
                                                  ("7624",2),                                                                                           #MILK
                                                  ("67616",3),                                                                                          #VEGETABLE
                                                  ("183",4),                                                                                            #FISH
                                                  ("3434",5)],                                                                                          #CEREAL
                                                 self.cursor, True, 1, 0, 0)
                                                 
        self.accept("Gesture_Handler", self.gestureProcessing)
        
        self.pointer = pointer
        
        # Events declaration
        self.accept("WM_BUTTON_PRESSED", self.handleBtnPress)
        self.accept("WM_BUTTON_RELEASED", self.handleBtnRelease)
        
        taskMgr.add(self.taskMove, 'taskMove')
        taskMgr.add(self.taskCollision, 'taskCollision' )
        taskMgr.add(self.taskTextGrass, 'taskTextGrass' )
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # WiiMote button pressed handler
    def handleBtnPress(self, btn, dev, index):
        if( self.finished == False ):
            if(index == 1):
                if(btn == wiiuse.BUTTON_A):
                    if self.drawing == True: 
                        # We're on the second part of the tutorial
                        if( self.readyForGame == False ):
                            # We're ready for playing
                            if( self.inGame == False ): 
                                if( self.busy == False ):       self.gestureHandler.beginGesture()
    #end handleBrnPress
    
    # WiiMote button released handler
    def handleBtnRelease(self, btn, dev, index):
        if( self.finished == False ):
            if(index == 1):
                if(btn == wiiuse.BUTTON_A):
                    if self.drawing == True:
                        # We're on the second part of the tutorial      
                        if( self.readyForGame == True ):
                            # We're going to play the game
                            self.hide()
                            self.game = Game(self.back, self.cursor, self.pointer)
                            self.inGame = True
                            self.readyForGame = False
                        else:
                            #We're on the second part of the tutorial
                            if( self.inGame == False ): 
                                if( self.busy == False ):       self.gestureHandler.endGesture()
                    else:       
                        #We're on the first part of the tutorial
                        self.showBlackboard()
    #end handleBtnRelease
    
    # It makes appear the blackboard
    def showBlackboard(self):
        if self.level.scene2 == 2:
            self.grassText.hide()
            taskMgr.remove('taskMove')
            taskMgr.remove('taskGlowing6')
            self.energyBar.hide()
            self.blackboard.show()
            self.shape.show()
            self.item.show()
            self.text.show()
            self.drawing = True
    #end showBlackboard
    
    # It hides the tutorial application
    def hide(self):
        self.blackboard.hide()
        self.shape.hide()
        self.shape = None
        self.text.hide()
        self.text = None
        self.grassText.hide()
        self.grassText = None
        self.char.hide()
        taskMgr.remove('taskMove')
        self.char = None
        self.energyBar.hide()
        self.energyBar = None
        self.grainAbility.hide()
        self.grainAbility = None
        self.fruitAbility.hide()
        self.fruitAbility = None
        self.milkAbility.hide()
        self.milkAbility = None
        self.vegetableAbility.hide()
        self.vegetableAbility = None
        self.fishAbility.hide()
        self.fishAbility = None
        taskMgr.remove('taskCollision')
        self.level.removeItems()
        self.level = None
        self.item.hide()
        self.item = None
	#end hide
        
    # It identifies the shapes drawn.
    def gestureProcessing(self, id, x, y):
        if(self.inGame == False):
            #------------------------------------------------------------------FRUIT---------------------------------------------------------------------
            if id==1:
                if(self.shapeNum == 4):
                    self.infFruit.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add( self.taskCorrect, 'taskCorrect' )
                else:
                    self.infError.show()
                    taskMgr.add( self.taskError, 'taskError' )
                   
            #------------------------------------------------------------------MILK----------------------------------------------------------------------
            elif id==2:
                if(self.shapeNum == 2):
                    self.infMilk.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add( self.taskCorrect, 'taskCorrect' )           
                else:
                    self.infError.show()
                    taskMgr.add( self.taskError, 'taskError' )
            #---------------------------------------------------------------VEGETABLE-------------------------------------------------------------------
            elif id==3:
                if(self.shapeNum == 3):
                    self.infVege.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add( self.taskCorrect, 'taskCorrect' )
                else:
                    self.infError.show()
                    taskMgr.add( self.taskError, 'taskError' )
               
           #------------------------------------------------------------------FISH---------------------------------------------------------------------
            elif id==4:
                if(self.shapeNum == 1):
                    self.infFish.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add( self.taskCorrect, 'taskCorrect' )
                else:
                    self.infError.show()
                    taskMgr.add( self.taskError, 'taskError' )
                          
            #----------------------------------------------------------------CEREAL--------------------------------------------------------------------
            elif id==5:
                if(self.shapeNum == 0):
                    self.infCereal.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add( self.taskCorrect, 'taskCorrect' )
                else:
                    self.infError.show()
                    taskMgr.add( self.taskError, 'taskError' )
                    
            #------------------------------------------------------------------NONE-------------------------------------------------------------------
            else:
                taskMgr.add( self.taskError, 'taskError' )
                self.infError.show()
          
            self.gestureHandler.clearGestures();
            self.busy = True
        
    #end gestureProcessing
    
    # It changes the shape showed to the user, depending on the shape practised.
    def changeShape(self):
        if( self.shapeNum == 0 ):       
            self.shape.setImage("./tex/cereal_ability_shape.png")
            self.item.setImage("./tex/rice.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if( self.shapeNum == 1 ):       
            self.shape.setImage("./tex/fish_ability_shape.png")
            self.item.setImage("./tex/fish.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if( self.shapeNum == 2 ):       
            self.shape.setImage("./tex/milk_ability_shape.png")
            self.item.setImage("./tex/milk.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if( self.shapeNum == 3 ):       
            self.shape.setImage("./tex/vegetable_ability_shape.png")
            self.item.setImage("./tex/letuce.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if( self.shapeNum == 4 ):       
            self.shape.setImage("./tex/fruit_ability_shape.png")
            self.item.setImage("./tex/straw.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if( self.shapeNum == 5 ):
            self.shape.hide()
            self.text.setImage("./tex/youAreReady.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)
            self.item.hide()
    #end changeShape
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------TASKS,THREADS------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It moves the main character to the sun pointer point.
    def taskMove(self, task):
        mpos = self.cursor.getCursorPos()
        
        # Moving the main character
        self.char.movement(mpos.getX(),mpos.getY())
        
        if self.level.scene2 == 1:
            self.grassText.setImage("./tex/PressAButton.png")
            self.grassText.setTransparency(TransparencyAttrib.MAlpha)
            self.grassText.show()
            self.level.scene2 = 2
            
        return task.cont
    #end taskCursor
    
    # It checks Character-Item collision
    def taskCollision(self, task):
        #Character-Item collision
        for x in self.level.items:
            if x.collide(self.char):
                self.char.itemCollect(x)
                self.level.items.remove(x)
                x.posX = -100
                x.model.setX(x.posX)
                x.posY = -100
                x.model.setZ(x.posY)
                x.collectIt = True
                
                self.energyBar.increase(x.energy)
                
                if x.specialItem==True: self.specialItems.itemCollected(x.type)
                
                # Producing glowing on abilities bar
                if x.type == "GRAIN":
                    self.grainAbility.itemCollected(1)
                    taskMgr.add(self.grainAbility.taskGlowing, 'taskGlowing1')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "FRUIT":
                    self.fruitAbility.itemCollected(1)
                    taskMgr.add(self.fruitAbility.taskGlowing, 'taskGlowing2')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "MILK":
                    self.milkAbility.itemCollected(1)
                    taskMgr.add(self.milkAbility.taskGlowing, 'taskGlowing3')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "VEGETABLE":
                    self.vegetableAbility.itemCollected(1)
                    taskMgr.add(self.vegetableAbility.taskGlowing, 'taskGlowing4')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "FISH":
                    self.fishAbility.itemCollected(1)
                    taskMgr.add(self.fishAbility.taskGlowing, 'taskGlowing5')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                    
        return task.cont
    #end taskCollision
    
    # It manages the tutorial in order to teach all the shapes to the user.
    # Each shape is practised two times.
    def taskCorrect(self, task):
        if( task.time > 1 ):
            if(self.shapeNum == 0): self.infCereal.hide()
            if(self.shapeNum == 1): self.infFish.hide()
            if(self.shapeNum == 2): self.infMilk.hide()
            if(self.shapeNum == 3): self.infVege.hide()
            if(self.shapeNum == 4): self.infFruit.hide()
            
            self.busy = False
            self.text.setImage("./tex/onceAgain.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)
            if( self.drawedOK > 1 ):
                self.shapeNum = self.shapeNum + 1
                if( self.shapeNum == 5 ): self.readyForGame = True
                self.drawedOK = 0
                self.text.setImage("./tex/tryNewOne.png")
                self.text.setTransparency(TransparencyAttrib.MAlpha)
                self.changeShape()
                
            return task.done
        else:   return task.cont
    #end taskCursor
    
    # It shows a message of don't worry to the user.
    def taskError(self, task):
        if( task.time > 1 ):
            self.busy = False
            self.infError.hide()
            self.text.setImage("./tex/dontWorry.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)    
            return task.done
        else:   return task.cont
    #end taskCursor
    
    # It shows a determined text for 3 seconds.
    def taskTextGrass(self, task):
        if( task.time > 3):
            self.grassText.hide()
            return task.done
        else:   return task.cont
    #end taskTextGrass
Exemple #40
0
class Gauge:
    """
    Represents a dynamic gauge linked to a global variable of the shuttle.
    """
    def __init__(self,
                 screen,
                 name,
                 x=0,
                 low_value=-1,
                 high_value=101,
                 min=0,
                 max=100):
        """
        Creates a new gauge
        @param screen: the controlScreen instance
        @param name: the name of the corresponding global variable (soft_state).
        @param x:
        @param low_value: below this limit,
        @param high_value:
        @param min: minimum value
        @param max: maximum value
        """
        self.taskMgr = screen.gameEngine.taskMgr
        self.update_func = screen.update
        self.screen = screen
        self.name = name
        self.low_value = low_value
        self.high_value = high_value
        self._hardware = screen.gameEngine.hardware
        self._sound = screen.gameEngine.sound_manager
        self.texture = OnscreenImage(image=screen.image_path +
                                     "indicateur.png",
                                     parent=screen.gui_render_node)
        self.texture.setTransparency(True)
        iH = PNMImageHeader()
        iH.readHeader(Filename(screen.image_path + "indicateur.png"))

        self.time_for_goto = None
        self.half_sec_step_for_goto = 1.0

        self.w = iH.get_x_size()
        self.h = iH.get_y_size()
        self._limits = [min, max]

        iH.readHeader(Filename(screen.image_path + "screen.png"))
        self._x0 = x
        self._x = [-1 + self.w / iH.get_x_size(), 2 / iH.get_x_size()]
        self._y = [1 - self.h / iH.get_y_size(), -2 / iH.get_y_size()]
        self._gauge_min_y = 44 - 0.5 * self.h
        self._gauge_max_y = 466 - 0.5 * self.h

        self.texture.set_scale(
            LVector3f(self.w / iH.get_x_size(), 1, self.h / iH.get_y_size()))

        self._task_to_come = []
        self.value = self.screen.gameEngine.get_soft_state(self.name)
        self._is_destroyed = False

        self.set_value()
        self.hide()

    def set_time_for_goto(self, time):
        self.time_for_goto = time
        self.half_sec_step_for_goto = None

    def set_half_sec_step_for_goto(self, step):
        self.half_sec_step_for_goto = step
        self.time_for_goto = None

    def _set_gimp_pos(self, x, y):
        self.texture.set_pos(
            (self._x[0] + x * self._x[1], 0.0, self._y[0] + y * self._y[1]))

    def set_color(self, color):
        self.texture.set_color(color)

    def destroy(self):
        self.texture.destroy()
        self._is_destroyed = True
        for i in range(len(self._task_to_come)):
            self.taskMgr.remove(self._task_to_come.pop())

    def hide(self):
        self.texture.hide()

    def show(self):
        self.texture.show()

    def goto_value(self, new_value):
        # stop the previous tasks
        for i in range(len(self._task_to_come)):
            self.taskMgr.remove(self._task_to_come.pop())

        def func(v):
            self.set_value(v)
            self.update_func.__call__()

        def stop(t=None):
            self._hardware.set_led_off("l_" + self.name + "_down")
            self._hardware.set_led_off("l_" + self.name + "_up")
            if self.low_value >= self.value:
                self._sound.play(self.name + "_low")
            elif self.high_value <= self.value:
                self._sound.play(self.name + "_high")

        self._hardware.set_led_off("l_" + self.name + "_down")
        self._hardware.set_led_off("l_" + self.name + "_up")
        step_by_half_sec = self.half_sec_step_for_goto
        if self.half_sec_step_for_goto is None:
            dx = abs(self.value - new_value)
            step_by_half_sec = 0.5 * dx / self.time_for_goto

        if self.value >= new_value:
            self._hardware.set_led_on("l_" + self.name + "_down")
            step_by_half_sec = -step_by_half_sec
        else:
            self._hardware.set_led_on("l_" + self.name + "_up")

        n_steps = -int((self.value - new_value) / step_by_half_sec)
        old_value = self.value

        for i in range(n_steps):
            self._task_to_come.append(
                self.taskMgr.doMethodLater(
                    0.5 * i,
                    func,
                    name="gauge_move",
                    extraArgs=[old_value + (i + 1) * step_by_half_sec]))

        self._task_to_come.append(
            self.taskMgr.doMethodLater(0.5 * n_steps,
                                       stop,
                                       name="gauge_move_stop"))

    def set_value(self, value=None):
        if not self._is_destroyed:
            if self.value >= self._limits[1]:
                self.value = self._limits[1]
            elif self.value < self._limits[0]:
                self.value = self._limits[0]

            old_value = self.value
            if value is not None:
                if value >= self._limits[1]:
                    value = self._limits[1]
                elif value < self._limits[0]:
                    value = self._limits[0]
                self.value = value
            if old_value > self.low_value >= self.value:
                self._sound.play(self.name + "_low")
                self._hardware.set_led_on("l_" + self.name + "_low")
            elif old_value <= self.low_value < self.value:
                self._hardware.set_led_off("l_" + self.name + "_low")
            elif old_value < self.high_value <= self.value:
                self._sound.play(self.name + "_high")
                self._hardware.set_led_on("l_" + self.name + "_high")
            elif self.value < self.high_value <= old_value:
                self._hardware.set_led_off("l_" + self.name + "_high")

            self._set_gimp_pos(
                self._x0, self._gauge_max_y + (self.value - self._limits[0]) /
                (self._limits[1] - self._limits[0]) *
                (self._gauge_min_y - self._gauge_max_y))
Exemple #41
0
class CarPanel(GameObject):
    def __init__(self, car_props, player_idx, ncars, players):
        GameObject.__init__(self)
        self._players = players
        self.car_props = car_props
        self.player_idx = player_idx
        self.ncars = ncars
        sprops = self.car_props.race_props.season_props
        menu_props = sprops.gameprops.menu_props
        if ncars == 1:
            parent_tr = base.a2dTopRight
        elif ncars == 2:
            if self.player_idx == 0: parent_tr = base.a2dTopCenter
            else: parent_tr = base.a2dTopRight
        elif ncars == 3:
            if self.player_idx == 0: parent_tr = base.a2dTopRight
            elif self.player_idx == 1: parent_tr = base.aspect2d
            else: parent_tr = base.a2dRightCenter
        elif ncars == 4:
            if self.player_idx == 0: parent_tr = base.a2dTopCenter
            elif self.player_idx == 1: parent_tr = base.a2dTopRight
            elif self.player_idx == 2: parent_tr = base.aspect2d
            else: parent_tr = base.a2dRightCenter
        if ncars == 1:
            parent_tl = base.a2dTopLeft
        elif ncars == 2:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            else: parent_tl = base.a2dTopCenter
        elif ncars == 3:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            elif self.player_idx == 1: parent_tl = base.a2dLeftCenter
            else: parent_tl = base.aspect2d
        elif ncars == 4:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            elif self.player_idx == 1: parent_tl = base.a2dTopCenter
            elif self.player_idx == 2: parent_tl = base.a2dLeftCenter
            else: parent_tl = base.aspect2d
        if ncars == 1:
            parent_bl = base.a2dBottomLeft
        elif ncars == 2:
            if self.player_idx == 0: parent_bl = base.a2dBottomLeft
            else: parent_bl = base.a2dBottomCenter
        elif ncars == 3:
            if self.player_idx == 0: parent_bl = base.a2dLeftCenter
            elif self.player_idx == 1: parent_bl = base.a2dBottomLeft
            else: parent_bl = base.a2dBottomCenter
        elif ncars == 4:
            if self.player_idx == 0: parent_bl = base.a2dLeftCenter
            elif self.player_idx == 1: parent_bl = base.aspect2d
            elif self.player_idx == 2: parent_bl = base.a2dBottomLeft
            else: parent_bl = base.a2dBottomCenter
        # if ncars == 1: parent_t = base.a2dTopCenter
        # elif ncars == 2:
        #     if self.player_idx == 0: parent_t = base.a2dTopQuarter
        #     else: parent_t = base.a2dTopThirdQuarter
        # elif ncars == 3:
        #     if self.player_idx == 0: parent_t = base.a2dTop
        #     elif self.player_idx == 1: parent_t = base.a2dCenterQuarter
        #     else: parent_t = base.a2dCenterThirdQuarter
        # elif ncars == 4:
        #     if self.player_idx == 0: parent_t = base.a2dTopQuarter
        #     elif self.player_idx == 1: parent_t = base.a2dTopThirdQuarter
        #     elif self.player_idx == 2: parent_t = base.a2dCenterQuarter
        #     else: parent_t = base.a2dCenterThirdQuarter
        # if ncars == 1: parent_b = base.a2dBottomCenter
        # elif ncars == 2:
        #     if self.player_idx == 0: parent_b = base.a2dBottomQuarter
        #     else: parent_b = base.a2dBottomThirdQuarter
        # elif ncars == 3:
        #     if self.player_idx == 0: parent_b = base.aspect2d
        #     elif self.player_idx == 1: parent_b = base.a2dBottomQuarter
        #     else: parent_b = base.a2dBottomThirdQuarter
        # elif ncars == 4:
        #     if self.player_idx == 0: parent_b = base.a2dCenterQuarter
        #     elif self.player_idx == 1: parent_b = base.a2dCenterThirdQuarter
        #     elif self.player_idx == 2: parent_b = base.a2dBottomQuarter
        #     else: parent_b = base.a2dBottomThirdQuarter
        yellow_scale = .065 if ncars == 1 else .042
        white_scale = .05 if ncars == 1 else .038
        damages_img_scale = (.12, 1, .12) if ncars == 1 else (.08, 1, .08)
        self.__weap_scale = .12 if ncars == 1 else .08
        txt_x = -.24 if ncars == 1 else -.18
        lab_x = -.3 if ncars == 1 else -.24
        offset_z = .1 if ncars == 1 else .08
        top_z = -.1
        damages_txt_pos = (.3, .1) if ncars == 1 else (.24, .06)
        damages_img_pos = (.46, 1, .12) if ncars == 1 else (.36, 1, .07)
        weapon_txt_pos = (.18, -.08) if ncars == 1 else (.14, -.08)
        self.__weapon_img_pos = (.18, 1, -.24) if ncars == 1 else \
            (.14, 1, -.18)
        fwd_img_pos = (0, 1, -.2) if ncars == 1 else (0, 1, -.16)
        fwd_img_scale = .15 if ncars == 1 else .12
        pars = {
            'scale': yellow_scale,
            'parent': parent_tr,
            'fg': menu_props.text_active_col,
            'align': TextNode.A_left,
            'font': self.eng.font_mgr.load_font(sprops.font)
        }
        # self.glass_tl = OnscreenImage(
        #     'assets/images/gui/topleft.txo',
        #     scale=(.23, 1, .24), parent=parent_tl, pos=(.22, 1, -.23))
        # self.glass_tl.set_transparency(True)
        # self.glass_tr = OnscreenImage(
        #     'assets/images/gui/topright.txo',
        #     scale=(.36, 1, .36), parent=parent_tr, pos=(-.35, 1, -.35))
        # self.glass_tr.set_transparency(True)
        # self.glass_t = OnscreenImage(
        #     'assets/images/gui/top.txo',
        #     scale=(.24, 1, .22), parent=parent_t, pos=(0, 1, -.21))
        # self.glass_t.set_transparency(True)
        # self.glass_bl = OnscreenImage(
        #     'assets/images/gui/bottomleft.txo',
        #     scale=(.36, 1, .16), parent=parent_bl, pos=(.35, 1, .15))
        # self.glass_bl.set_transparency(True)
        # self.glass_br = OnscreenImage(
        #     'assets/images/gui/bottomright.txo', scale=(.26, 1, .26),
        #     parent=base.a2dBottomRight, pos=(-.25, 1, .25))
        # self.glass_br.set_transparency(True)
        # self.glass_b = OnscreenImage(
        #     'assets/images/gui/bottom.txo',
        #     scale=(1.02, 1, .26), parent=parent_b, pos=(0, 1, .25))
        # self.glass_b.set_transparency(True)
        # self.glass_tl.hide()
        # self.glass_t.hide()
        # self.glass_b.hide()
        self.speed_txt = OnscreenText(pos=(txt_x + .06, top_z), **pars)
        self.speed_txt['align'] = TextNode.A_center
        self.speed_c = Circle(size=.1,
                              pos=(txt_x + .06, top_z),
                              parent=parent_tr,
                              ray=.4,
                              thickness=.05,
                              col_start=(.9, .6, .1, 1),
                              col_end=(.2, .8, .2, 1))
        lap_str = '1/' + str(self.car_props.race_props.laps)
        self.lap_txt = OnscreenText(text=lap_str,
                                    pos=(txt_x, top_z - offset_z),
                                    **pars)
        self.time_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 4), **pars)
        self.best_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 5), **pars)
        self.ranking_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 2),
                                        **pars)
        self.damages_img = OnscreenImage('assets/images/gui/car_icon.txo',
                                         scale=damages_img_scale,
                                         parent=parent_bl,
                                         pos=damages_img_pos)
        self.damages_img.set_transparency(True)
        self.damages_img.set_color_scale(menu_props.text_normal_col)
        self.damages_img.set_r(90)
        pars = {
            'scale': white_scale,
            'parent': pars['parent'],
            'fg': menu_props.text_normal_col,
            'align': TextNode.A_right,
            'font': pars['font']
        }
        self.speed_lab = OnscreenText(_('speed:'), pos=(lab_x, top_z), **pars)
        self.lap_lab = OnscreenText(text=_('lap:'),
                                    pos=(lab_x, top_z - offset_z),
                                    **pars)
        self.time_lab = OnscreenText(_('time:'),
                                     pos=(lab_x, top_z - offset_z * 4),
                                     **pars)
        self.best_lab = OnscreenText(_('best lap:'),
                                     pos=(lab_x, top_z - offset_z * 5),
                                     **pars)
        self.ranking_lab = OnscreenText(_('ranking:'),
                                        pos=(lab_x, top_z - offset_z * 2),
                                        **pars)
        self.damages_lab = OnscreenText(_('damages:'),
                                        pos=damages_txt_pos,
                                        **pars)
        self.damages_lab.reparent_to(parent_bl)
        self.weapon_lab = OnscreenText(_('weapon'),
                                       pos=weapon_txt_pos,
                                       scale=white_scale,
                                       parent=parent_tl,
                                       fg=menu_props.text_normal_col,
                                       font=self.eng.font_mgr.load_font(
                                           sprops.font))
        self.weapon_img = None
        if ncars == 1: parent = base.a2dTopCenter
        elif ncars == 2:
            if player_idx == 0: parent = base.a2dTopQuarter
            else: parent = base.a2dTopThirdQuarter
        elif ncars == 3:
            if player_idx == 0: parent = base.a2dTopCenter
            elif player_idx == 0: parent = base.a2dCenterQuarter
            else: parent = base.a2dCenterThirdQuarter
        elif ncars == 4:
            if player_idx == 0: parent = base.a2dTopQuarter
            elif player_idx == 1: parent = base.a2dTopThirdQuarter
            elif player_idx == 2: parent = base.a2dCenterQuarter
            else: parent = base.a2dCenterThirdQuarter
        self.forward_img = OnscreenImage('assets/images/gui/direction.txo',
                                         scale=fwd_img_scale,
                                         parent=parent,
                                         pos=fwd_img_pos)
        self.forward_img.set_transparency(True)
        self.forward_img.hide()

    @staticmethod
    def __close_vec(vec1, vec2):
        return all(abs(b - a) < .01 for a, b in zip(vec1, vec2))

    def enter_waiting(self):
        pass
        # if self.ncars == 1: parent = base.aspect2d
        # elif self.ncars == 2:
        #     if self.player_idx == 0: parent = base.a2dCenterQuarter
        #     else: parent = base.a2dCenterThirdQuarter
        # elif self.ncars == 3:
        #     if self.player_idx == 0: parent = base.a2dQuarterCenter
        #     elif self.player_idx == 1: parent = base.a2dThirdQuarterQuarter
        #     else: parent = base.a2dThirdQuarterThirdQuarter
        # elif self.ncars == 4:
        #     if self.player_idx == 0: parent = base.a2dQuarterQuarter
        #     elif self.player_idx == 1: parent = base.a2dQuarterThirdQuarter
        #     elif self.player_idx == 2: parent = base.a2dThirdQuarterQuarter
        #     else: parent = base.a2dThirdQuarterThirdQuarter
        # menu_props = self.race_props.season_props.gameprops.menu_props
        # pars = {'scale': .065, 'parent': parent,
        #         'fg': menu_props.text_normal_col,
        #         'font': self.eng.font_mgr.load_font(
        #             self.race_props.season_props.font)}

    def exit_waiting(self):
        pass

    def set_weapon(self, wpn):
        # self.glass_tl.show()
        self.weapon_lab.show()
        ncars = len([
            player for player in self._players if player.kind == Player.human
        ])
        if ncars == 1:
            parent_tl = base.a2dTopLeft
        elif ncars == 2:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            else: parent_tl = base.a2dTopCenter
        elif ncars == 3:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            elif self.player_idx == 1: parent_tl = base.a2dLeftCenter
            else: parent_tl = base.aspect2d
        elif ncars == 4:
            if self.player_idx == 0: parent_tl = base.a2dTopLeft
            elif self.player_idx == 1: parent_tl = base.a2dTopCenter
            elif self.player_idx == 2: parent_tl = base.a2dLeftCenter
            else: parent_tl = base.aspect2d
        self.weapon_img = OnscreenImage('assets/images/weapons/%s.txo' % wpn,
                                        scale=self.__weap_scale,
                                        parent=parent_tl,
                                        pos=self.__weapon_img_pos)
        self.weapon_img.set_transparency(True)

    def unset_weapon(self):
        # self.glass_tl.hide()
        self.weapon_lab.hide()
        self.weapon_img.destroy()

    def show_forward(self):
        # self.glass_t.show()
        self.forward_img.show()

    def set_forward_angle(self, angle):
        curr_angle = self.forward_img.get_r()
        curr_incr = globalClock.getDt() * 30
        if abs(curr_angle - angle) < curr_incr:
            tgt_val = angle
        else:
            sign = 1 if angle > curr_angle else -1
            tgt_val = curr_angle + curr_incr * sign
        self.forward_img.set_r(tgt_val)

    def hide_forward(self):
        # self.glass_t.hide()
        self.forward_img.hide()

    def apply_damage(self, reset=False):
        col = self.car_props.race_props.season_props.gameprops.menu_props.text_normal_col
        if reset:
            self.damages_img.set_color_scale(col)
        else:
            yellow = (col[0], col[1] - .25, col[2] - .5, col[3])
            if self.__close_vec(self.damages_img.get_color_scale(), col):
                self.damages_img.set_color_scale(yellow)
            elif self.__close_vec(self.damages_img.get_color_scale(), yellow):
                red = (col[0], col[1] - .5, col[2] - .5, col[3])
                self.damages_img.set_color_scale(red)

    def hide(self):
        labels = [
            self.speed_txt,
            self.speed_c,
            self.time_txt,
            self.lap_txt,
            self.best_txt,
            self.speed_lab,
            self.time_lab,
            self.lap_lab,
            self.best_lab,
            self.damages_img,
            self.damages_lab,
            self.ranking_txt,
            self.ranking_lab,
            self.weapon_lab,
            # self.glass_tl, self.glass_tr, self.glass_t,
            # self.glass_bl, self.glass_br, self.glass_b
        ]
        list(map(lambda wdg: wdg.hide(), labels))
        if self.weapon_img and not self.weapon_img.is_empty():
            self.weapon_img.hide()
        self.forward_img.hide()

    def destroy(self):
        labels = [
            self.speed_txt,
            self.speed_c,
            self.time_txt,
            self.lap_txt,
            self.best_txt,
            self.speed_lab,
            self.time_lab,
            self.lap_lab,
            self.best_lab,
            self.damages_img,
            self.damages_lab,
            self.ranking_txt,
            self.ranking_lab,
            self.weapon_lab,
            # self.glass_tl, self.glass_tr, self.glass_t,
            # self.glass_bl, self.glass_br, self.glass_b
        ]
        list(map(lambda wdg: wdg.destroy(), labels))
        if self.weapon_img and not self.weapon_img.is_empty():
            self.weapon_img.destroy()
        self.forward_img.destroy()
Exemple #42
0
class Sprite(RPObject):

    """ Simple wrapper arround OnscreenImage, providing a simpler interface """

    def __init__(self, image=None, parent=None, x=0, y=0, w=None, h=None,
                 transparent=True, near_filter=True, any_filter=True):
        """ Creates a new image, taking (x,y) as topleft coordinates.

        When near_filter is set to true, a near filter will be set to the
        texture passed. This provides sharper images.

        When any_filter is set to false, the passed image won't be modified at
        all. This enables you to display existing textures, otherwise the
        texture would get a near filter in the 3D View, too. """

        RPObject.__init__(self)

        if not isinstance(image, Texture):
            if not isinstance(image, str):
                self.warn("Invalid argument to image parameter:", image)
                return
            image = RPLoader.load_texture(image)

            if w is None or h is None:
                w, h = image.get_x_size(), image.get_y_size()
        else:
            if w is None or h is None:
                w = 10
                h = 10

        self._width, self._height = w, h
        self._initial_pos = self._translate_pos(x, y)

        self.node = OnscreenImage(
            image=image, parent=parent, pos=self._initial_pos,
            scale=(self._width / 2.0, 1, self._height / 2.0))

        if transparent:
            self.node.set_transparency(TransparencyAttrib.M_alpha)

        tex = self.node.get_texture()

        # Apply a near filter, but only if the parent has no scale, otherwise
        # it will look weird
        if near_filter and any_filter and parent.get_sx() == 1.0:
            tex.set_minfilter(SamplerState.FT_nearest)
            tex.set_magfilter(SamplerState.FT_nearest)

        if any_filter:
            tex.set_anisotropic_degree(8)
            tex.set_wrap_u(SamplerState.WM_clamp)
            tex.set_wrap_v(SamplerState.WM_clamp)

    def get_initial_pos(self):
        """ Returns the initial position of the image. This can be used for
        animations """
        return self._initial_pos

    def pos_interval(self, *args, **kwargs):
        """ Returns a pos interval, this is a wrapper around
        NodePath.posInterval """
        return self.node.posInterval(*args, **kwargs)

    def hpr_interval(self, *args, **kwargs):
        """ Returns a hpr interval, this is a wrapper around
        NodePath.hprInterval """
        return self.node.hprInterval(*args, **kwargs)

    def color_scale_interval(self, *args, **kwargs):
        """ Returns a color scale interval, this is a wrapper around
        NodePath.colorScaleInterval """
        return self.node.colorScaleInterval(*args, **kwargs)

    def set_image(self, img):
        """ Sets the current image """
        self.node.set_image(img)

    def get_width(self):
        """ Returns the width of the image in pixels """
        return self._width

    def get_height(self):
        """ Returns the height of the image in pixels """
        return self._height

    def set_pos(self, x, y):
        """ Sets the position """
        self.node.set_pos(self._translate_pos(x, y))

    def _translate_pos(self, x, y):
        """ Converts 2d coordinates to pandas coordinate system """
        return Vec3(x + self._width / 2.0, 1, -y - self._height / 2.0)

    def set_shader(self, shader):
        """ Sets a shader to be used for rendering the image """
        self.node.set_shader(shader)

    def set_shader_input(self, *args):
        """ Sets a shader input on the image """
        self.node.set_shader_input(*args)

    def remove(self):
        """ Removes the image """
        self.node.remove()

    def hide(self):
        """ Hides the image """
        self.node.hide()

    def show(self):
        """ Shows the image if it was previously hidden """
        self.node.show()
Exemple #43
0
class CarPlayerGui(CarGui):

    panel_cls = CarPanel

    def __init__(self, mediator, car_props, players):
        self.car_props = car_props
        self._players = players
        ncars = self.ncars
        CarGui.__init__(self, mediator)
        self.pars = CarParameters(mediator.phys, mediator.logic)
        self.panel = self.panel_cls(car_props, mediator.player_car_idx, ncars,
                                    players)
        self.ai_panel = CarAIPanel()
        way_txt_pos = (0, .1) if ncars == 1 else (0, .04)
        way_txt_scale = .1 if ncars == 1 else .06
        way_img_pos = (0, 1, .3) if ncars == 1 else (0, 1, .16)
        way_img_scale = .12 if ncars == 1 else .06
        self.way_txt = OnscreenText(
            '',
            pos=way_txt_pos,
            scale=way_txt_scale,
            fg=self.car_props.race_props.season_props.gameprops.menu_props.
            text_err_col,
            parent=self.parent,
            font=self.eng.font_mgr.load_font(
                self.car_props.race_props.season_props.font))
        self.way_img = OnscreenImage('assets/images/gui/arrow_circle.txo',
                                     scale=way_img_scale,
                                     parent=self.parent,
                                     pos=way_img_pos)
        self.way_img.set_transparency(True)
        self.way_img.hide()

    @property
    def ncars(self):
        player_car_names = [
            player.car for player in self._players
            if player.kind == Player.human
        ]
        return len(player_car_names)

    @property
    def parent(self):
        if self.ncars == 1: parent = base.a2dBottomCenter
        elif self.ncars == 2:
            if self.mediator.player_car_idx == 0:
                parent = base.a2dBottomQuarter
            else:
                parent = base.a2dBottomThirdQuarter
        elif self.ncars == 3:
            if self.mediator.player_car_idx == 0: parent = base.aspect2d
            elif self.mediator.player_car_idx == 1:
                parent = base.a2dBottomQuarter
            else:
                parent = base.a2dBottomThirdQuarter
        elif self.ncars == 4:
            if self.mediator.player_car_idx == 0:
                parent = base.a2dCenterQuarter
            elif self.mediator.player_car_idx == 1:
                parent = base.a2dCenterThirdQuarter
            elif self.mediator.player_car_idx == 2:
                parent = base.a2dBottomQuarter
            else:
                parent = base.a2dBottomThirdQuarter
        return parent

    def upd_ranking(self, ranking):
        r_i = ranking.index(self.mediator.name) + 1
        self.panel.ranking_txt.setText(str(r_i) + "'")

    def upd_ai(self):
        self.ai_panel.update()

    def apply_damage(self, reset=False):
        self.panel.apply_damage(reset)

    def show_forward(self):
        self.panel.show_forward()

    def hide_forward(self):
        self.panel.hide_forward()

    def hide(self):
        CarGui.hide(self)
        self.pars.hide()
        self.panel.hide()
        self.ai_panel.hide()

    def on_wrong_way(self, way_str):
        if way_str:
            # self.panel.glass_b.show()
            self.way_txt.setText(way_str)
            self.way_img.show()
        elif not self.mediator.logic.is_moving or \
                self.mediator.logic.fly_time > 10:
            # self.panel.glass_b.show()
            keys = self.car_props.race_props.keys.players_keys[
                self.mediator.player_car_idx]
            txt = _('press %s to respawn') % \
                self.eng.event.key2desc(keys.respawn)
            self.way_txt.setText(txt)
            self.way_img.hide()
        else:
            # self.panel.glass_b.hide()
            self.way_txt.setText('')
            self.way_img.hide()

    def destroy(self):
        list(
            map(lambda wdg: wdg.destroy(),
                [self.pars, self.panel, self.ai_panel]))
        self.way_txt.destroy()
        self.way_img.destroy()
        GuiColleague.destroy(self)
Exemple #44
0
class Tutorial(DirectObject):
    def __init__(self, background, cursor, pointer):
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Background
        self.back = background

        # Level
        self.level = Level_Tutorial(background)

        # Graphic components
        #Blackboard
        self.blackboard = OnscreenImage(image="./tex/blackboard_empty.png",
                                        pos=(0, 0, 0),
                                        hpr=None,
                                        scale=(1.25, 1.0, 0.90),
                                        color=None,
                                        parent=None,
                                        sort=0)
        self.blackboard.setTransparency(TransparencyAttrib.MAlpha)
        self.blackboard.hide()
        #Main Character
        self.char = CMain(-18, -5, 59)
        #Energy Bar
        self.energyBar = BEnergy()
        self.energyBar.increase(50)
        #Abilies Bar
        self.grainAbility = BAbility("GRAIN")
        self.fruitAbility = BAbility("FRUIT")
        self.milkAbility = BAbility("MILK")
        self.vegetableAbility = BAbility("VEGETABLE")
        self.fishAbility = BAbility("FISH")
        #Shape
        self.shape = OnscreenImage(image="./tex/cereal_ability_shape.png",
                                   pos=(-0.75, 0, 0),
                                   hpr=None,
                                   scale=0.25,
                                   color=None,
                                   parent=None,
                                   sort=1)
        self.shape.setTransparency(TransparencyAttrib.MAlpha)
        self.shape.hide()
        #Item
        self.item = OnscreenImage(image="./tex/rice.png",
                                  pos=(-0.75, 0, -0.4),
                                  hpr=None,
                                  scale=0.09,
                                  color=None,
                                  parent=None,
                                  sort=1)
        self.item.setTransparency(TransparencyAttrib.MAlpha)
        self.item.hide()
        #Texts
        self.text = OnscreenImage(image="./tex/tryToDrawThisShape.png",
                                  pos=(-0.75, 0, 0.6),
                                  hpr=None,
                                  scale=0.35,
                                  color=None,
                                  parent=None,
                                  sort=1)
        self.text.setTransparency(TransparencyAttrib.MAlpha)
        self.text.hide()
        self.grassText = OnscreenImage(image="./tex/moveThroughTheGrass.png",
                                       pos=(0, 0, 0),
                                       hpr=None,
                                       scale=0.7,
                                       color=None,
                                       parent=None,
                                       sort=1)
        self.grassText.setTransparency(TransparencyAttrib.MAlpha)
        #Info
        self.infError = OnscreenImage(image="./tex/wrong_attack.png",
                                      pos=(0.4, 0, 0),
                                      hpr=None,
                                      scale=(0.47, 1.0, 0.55),
                                      color=None,
                                      parent=None,
                                      sort=5)
        self.infError.setTransparency(TransparencyAttrib.MAlpha)
        self.infError.hide()
        self.infCereal = OnscreenImage(image="./tex/cereal_attack.png",
                                       pos=(0.4, 0, 0),
                                       hpr=None,
                                       scale=0.45,
                                       color=None,
                                       parent=None,
                                       sort=5)
        self.infCereal.setTransparency(TransparencyAttrib.MAlpha)
        self.infCereal.hide()
        self.infFish = OnscreenImage(image="./tex/fish_attack.png",
                                     pos=(0.4, 0, 0),
                                     hpr=None,
                                     scale=0.5,
                                     color=None,
                                     parent=None,
                                     sort=5)
        self.infFish.setTransparency(TransparencyAttrib.MAlpha)
        self.infFish.hide()
        self.infMilk = OnscreenImage(image="./tex/milk_attack.png",
                                     pos=(0.4, 0, 0),
                                     hpr=None,
                                     scale=0.5,
                                     color=None,
                                     parent=None,
                                     sort=5)
        self.infMilk.setTransparency(TransparencyAttrib.MAlpha)
        self.infMilk.hide()
        self.infVege = OnscreenImage(image="./tex/vege_attack.png",
                                     pos=(0.4, 0, 0),
                                     hpr=None,
                                     scale=0.4,
                                     color=None,
                                     parent=None,
                                     sort=5)
        self.infVege.setTransparency(TransparencyAttrib.MAlpha)
        self.infVege.hide()
        self.infFruit = OnscreenImage(image="./tex/fruit_attack.png",
                                      pos=(0.4, 0, 0),
                                      hpr=None,
                                      scale=0.4,
                                      color=None,
                                      parent=None,
                                      sort=5)
        self.infFruit.setTransparency(TransparencyAttrib.MAlpha)
        self.infFruit.hide()
        #Logo
        self.logo = OnscreenImage(image="./tex/laSalleAlpha.png",
                                  pos=(1.05, 0, -0.85),
                                  hpr=None,
                                  scale=(0.22, 1.0, 0.075),
                                  color=None,
                                  parent=None,
                                  sort=5)
        self.logo.setTransparency(TransparencyAttrib.MAlpha)

        # Others
        self.shapeNum = 0
        self.drawedOK = 0
        self.finished = False
        self.drawing = False
        self.readyForGame = False
        self.inGame = False
        self.busy = False

        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #----------------------------------------------------------TUTORIAL INIT------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        # Glove gestures configuration
        self.cursor = cursor
        self.gestureHandler = GestureRecognition(
            "Gesture_Handler",
            [
                ("1", 0),
                ("2", 0),
                ("3", 0),
                ("4", 0),
                ("6", 0),
                ("7", 0),
                ("8", 0),
                ("9", 0),  #NONE
                ("12", 0),
                ("13", 0),
                ("16", 0),
                ("18", 0),
                ("17", 0),
                ("14", 0),  #NONE
                ("23", 0),
                ("26", 0),
                ("29", 0),
                ("27", 0),
                ("24", 0),
                ("21", 0),  #NONE
                ("36", 0),
                ("39", 0),
                ("38", 0),
                ("34", 0),
                ("31", 0),
                ("32", 0),  #NONE
                ("41", 0),
                ("42", 0),
                ("43", 0),
                ("49", 0),
                ("48", 0),
                ("47", 0),  #NONE
                ("69", 0),
                ("68", 0),
                ("67", 0),
                ("61", 0),
                ("62", 0),
                ("63", 0),  #NONE
                ("74", 0),
                ("71", 0),
                ("72", 0),
                ("76", 0),
                ("79", 0),
                ("78", 0),  #NONE
                ("87", 0),
                ("84", 0),
                ("81", 0),
                ("83", 0),
                ("86", 0),
                ("89", 0),  #NONE
                ("98", 0),
                ("97", 0),
                ("94", 0),
                ("92", 0),
                ("93", 0),
                ("96", 0),  #NONE
                ("93934", 1),  #FRUIT
                ("7624", 2),  #MILK
                ("67616", 3),  #VEGETABLE
                ("183", 4),  #FISH
                ("3434", 5)
            ],  #CEREAL
            self.cursor,
            True,
            1,
            0,
            0)

        self.accept("Gesture_Handler", self.gestureProcessing)

        self.pointer = pointer

        # Events declaration
        self.accept("WM_BUTTON_PRESSED", self.handleBtnPress)
        self.accept("WM_BUTTON_RELEASED", self.handleBtnRelease)

        taskMgr.add(self.taskMove, 'taskMove')
        taskMgr.add(self.taskCollision, 'taskCollision')
        taskMgr.add(self.taskTextGrass, 'taskTextGrass')

    #end __init__

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # WiiMote button pressed handler
    def handleBtnPress(self, btn, dev, index):
        if (self.finished == False):
            if (index == 1):
                if (btn == wiiuse.BUTTON_A):
                    if self.drawing == True:
                        # We're on the second part of the tutorial
                        if (self.readyForGame == False):
                            # We're ready for playing
                            if (self.inGame == False):
                                if (self.busy == False):
                                    self.gestureHandler.beginGesture()

    #end handleBrnPress

    # WiiMote button released handler
    def handleBtnRelease(self, btn, dev, index):
        if (self.finished == False):
            if (index == 1):
                if (btn == wiiuse.BUTTON_A):
                    if self.drawing == True:
                        # We're on the second part of the tutorial
                        if (self.readyForGame == True):
                            # We're going to play the game
                            self.hide()
                            self.game = Game(self.back, self.cursor,
                                             self.pointer)
                            self.inGame = True
                            self.readyForGame = False
                        else:
                            #We're on the second part of the tutorial
                            if (self.inGame == False):
                                if (self.busy == False):
                                    self.gestureHandler.endGesture()
                    else:
                        #We're on the first part of the tutorial
                        self.showBlackboard()

    #end handleBtnRelease

    # It makes appear the blackboard
    def showBlackboard(self):
        if self.level.scene2 == 2:
            self.grassText.hide()
            taskMgr.remove('taskMove')
            taskMgr.remove('taskGlowing6')
            self.energyBar.hide()
            self.blackboard.show()
            self.shape.show()
            self.item.show()
            self.text.show()
            self.drawing = True

    #end showBlackboard

    # It hides the tutorial application
    def hide(self):
        self.blackboard.hide()
        self.shape.hide()
        self.shape = None
        self.text.hide()
        self.text = None
        self.grassText.hide()
        self.grassText = None
        self.char.hide()
        taskMgr.remove('taskMove')
        self.char = None
        self.energyBar.hide()
        self.energyBar = None
        self.grainAbility.hide()
        self.grainAbility = None
        self.fruitAbility.hide()
        self.fruitAbility = None
        self.milkAbility.hide()
        self.milkAbility = None
        self.vegetableAbility.hide()
        self.vegetableAbility = None
        self.fishAbility.hide()
        self.fishAbility = None
        taskMgr.remove('taskCollision')
        self.level.removeItems()
        self.level = None
        self.item.hide()
        self.item = None
#end hide

# It identifies the shapes drawn.

    def gestureProcessing(self, id, x, y):
        if (self.inGame == False):
            #------------------------------------------------------------------FRUIT---------------------------------------------------------------------
            if id == 1:
                if (self.shapeNum == 4):
                    self.infFruit.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add(self.taskCorrect, 'taskCorrect')
                else:
                    self.infError.show()
                    taskMgr.add(self.taskError, 'taskError')

            #------------------------------------------------------------------MILK----------------------------------------------------------------------
            elif id == 2:
                if (self.shapeNum == 2):
                    self.infMilk.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add(self.taskCorrect, 'taskCorrect')
                else:
                    self.infError.show()
                    taskMgr.add(self.taskError, 'taskError')
            #---------------------------------------------------------------VEGETABLE-------------------------------------------------------------------
            elif id == 3:
                if (self.shapeNum == 3):
                    self.infVege.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add(self.taskCorrect, 'taskCorrect')
                else:
                    self.infError.show()
                    taskMgr.add(self.taskError, 'taskError')

        #------------------------------------------------------------------FISH---------------------------------------------------------------------
            elif id == 4:
                if (self.shapeNum == 1):
                    self.infFish.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add(self.taskCorrect, 'taskCorrect')
                else:
                    self.infError.show()
                    taskMgr.add(self.taskError, 'taskError')

            #----------------------------------------------------------------CEREAL--------------------------------------------------------------------
            elif id == 5:
                if (self.shapeNum == 0):
                    self.infCereal.show()
                    self.drawedOK = self.drawedOK + 1
                    taskMgr.add(self.taskCorrect, 'taskCorrect')
                else:
                    self.infError.show()
                    taskMgr.add(self.taskError, 'taskError')

            #------------------------------------------------------------------NONE-------------------------------------------------------------------
            else:
                taskMgr.add(self.taskError, 'taskError')
                self.infError.show()

            self.gestureHandler.clearGestures()
            self.busy = True

    #end gestureProcessing

    # It changes the shape showed to the user, depending on the shape practised.
    def changeShape(self):
        if (self.shapeNum == 0):
            self.shape.setImage("./tex/cereal_ability_shape.png")
            self.item.setImage("./tex/rice.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if (self.shapeNum == 1):
            self.shape.setImage("./tex/fish_ability_shape.png")
            self.item.setImage("./tex/fish.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if (self.shapeNum == 2):
            self.shape.setImage("./tex/milk_ability_shape.png")
            self.item.setImage("./tex/milk.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if (self.shapeNum == 3):
            self.shape.setImage("./tex/vegetable_ability_shape.png")
            self.item.setImage("./tex/letuce.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if (self.shapeNum == 4):
            self.shape.setImage("./tex/fruit_ability_shape.png")
            self.item.setImage("./tex/straw.png")
            self.item.setTransparency(TransparencyAttrib.MAlpha)
        if (self.shapeNum == 5):
            self.shape.hide()
            self.text.setImage("./tex/youAreReady.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)
            self.item.hide()

    #end changeShape

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------TASKS,THREADS------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It moves the main character to the sun pointer point.
    def taskMove(self, task):
        mpos = self.cursor.getCursorPos()

        # Moving the main character
        self.char.movement(mpos.getX(), mpos.getY())

        if self.level.scene2 == 1:
            self.grassText.setImage("./tex/PressAButton.png")
            self.grassText.setTransparency(TransparencyAttrib.MAlpha)
            self.grassText.show()
            self.level.scene2 = 2

        return task.cont

    #end taskCursor

    # It checks Character-Item collision
    def taskCollision(self, task):
        #Character-Item collision
        for x in self.level.items:
            if x.collide(self.char):
                self.char.itemCollect(x)
                self.level.items.remove(x)
                x.posX = -100
                x.model.setX(x.posX)
                x.posY = -100
                x.model.setZ(x.posY)
                x.collectIt = True

                self.energyBar.increase(x.energy)

                if x.specialItem == True:
                    self.specialItems.itemCollected(x.type)

                # Producing glowing on abilities bar
                if x.type == "GRAIN":
                    self.grainAbility.itemCollected(1)
                    taskMgr.add(self.grainAbility.taskGlowing, 'taskGlowing1')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "FRUIT":
                    self.fruitAbility.itemCollected(1)
                    taskMgr.add(self.fruitAbility.taskGlowing, 'taskGlowing2')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "MILK":
                    self.milkAbility.itemCollected(1)
                    taskMgr.add(self.milkAbility.taskGlowing, 'taskGlowing3')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "VEGETABLE":
                    self.vegetableAbility.itemCollected(1)
                    taskMgr.add(self.vegetableAbility.taskGlowing,
                                'taskGlowing4')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')
                if x.type == "FISH":
                    self.fishAbility.itemCollected(1)
                    taskMgr.add(self.fishAbility.taskGlowing, 'taskGlowing5')
                    taskMgr.add(self.energyBar.taskGlowing, 'taskGlowing6')

        return task.cont

    #end taskCollision

    # It manages the tutorial in order to teach all the shapes to the user.
    # Each shape is practised two times.
    def taskCorrect(self, task):
        if (task.time > 1):
            if (self.shapeNum == 0): self.infCereal.hide()
            if (self.shapeNum == 1): self.infFish.hide()
            if (self.shapeNum == 2): self.infMilk.hide()
            if (self.shapeNum == 3): self.infVege.hide()
            if (self.shapeNum == 4): self.infFruit.hide()

            self.busy = False
            self.text.setImage("./tex/onceAgain.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)
            if (self.drawedOK > 1):
                self.shapeNum = self.shapeNum + 1
                if (self.shapeNum == 5): self.readyForGame = True
                self.drawedOK = 0
                self.text.setImage("./tex/tryNewOne.png")
                self.text.setTransparency(TransparencyAttrib.MAlpha)
                self.changeShape()

            return task.done
        else:
            return task.cont

    #end taskCursor

    # It shows a message of don't worry to the user.
    def taskError(self, task):
        if (task.time > 1):
            self.busy = False
            self.infError.hide()
            self.text.setImage("./tex/dontWorry.png")
            self.text.setTransparency(TransparencyAttrib.MAlpha)
            return task.done
        else:
            return task.cont

    #end taskCursor

    # It shows a determined text for 3 seconds.
    def taskTextGrass(self, task):
        if (task.time > 3):
            self.grassText.hide()
            return task.done
        else:
            return task.cont
Exemple #45
0
class Sprite(RPObject):
    """ Simple wrapper arround OnscreenImage, providing a simpler interface """
    def __init__(self,
                 image=None,
                 parent=None,
                 x=0,
                 y=0,
                 w=None,
                 h=None,
                 transparent=True,
                 near_filter=True,
                 any_filter=True):
        """ Creates a new image, taking (x,y) as topleft coordinates.

        When near_filter is set to true, a near filter will be set to the
        texture passed. This provides sharper images.

        When any_filter is set to false, the passed image won't be modified at
        all. This enables you to display existing textures, otherwise the
        texture would get a near filter in the 3D View, too. """

        RPObject.__init__(self)

        if not isinstance(image, Texture):
            if not isinstance(image, str):
                self.warn("Invalid argument to image parameter:", image)
                return
            image = RPLoader.load_texture(image)

            if w is None or h is None:
                w, h = image.get_x_size(), image.get_y_size()
        else:
            if w is None or h is None:
                w = 10
                h = 10

        self._width, self._height = w, h
        self._initial_pos = self._translate_pos(x, y)

        self.node = OnscreenImage(image=image,
                                  parent=parent,
                                  pos=self._initial_pos,
                                  scale=(self._width / 2.0, 1,
                                         self._height / 2.0))

        if transparent:
            self.node.set_transparency(TransparencyAttrib.M_alpha)

        tex = self.node.get_texture()

        # Apply a near filter, but only if the parent has no scale, otherwise
        # it will look weird
        if near_filter and any_filter and parent.get_sx() == 1.0:
            tex.set_minfilter(SamplerState.FT_nearest)
            tex.set_magfilter(SamplerState.FT_nearest)

        if any_filter:
            tex.set_anisotropic_degree(8)
            tex.set_wrap_u(SamplerState.WM_clamp)
            tex.set_wrap_v(SamplerState.WM_clamp)

    def get_initial_pos(self):
        """ Returns the initial position of the image. This can be used for
        animations """
        return self._initial_pos

    def pos_interval(self, *args, **kwargs):
        """ Returns a pos interval, this is a wrapper around
        NodePath.posInterval """
        return self.node.posInterval(*args, **kwargs)

    def hpr_interval(self, *args, **kwargs):
        """ Returns a hpr interval, this is a wrapper around
        NodePath.hprInterval """
        return self.node.hprInterval(*args, **kwargs)

    def color_scale_interval(self, *args, **kwargs):
        """ Returns a color scale interval, this is a wrapper around
        NodePath.colorScaleInterval """
        return self.node.colorScaleInterval(*args, **kwargs)

    def set_image(self, img):
        """ Sets the current image """
        self.node.set_image(img)

    def get_width(self):
        """ Returns the width of the image in pixels """
        return self._width

    def get_height(self):
        """ Returns the height of the image in pixels """
        return self._height

    def set_pos(self, x, y):
        """ Sets the position """
        self.node.set_pos(self._translate_pos(x, y))

    def _translate_pos(self, x, y):
        """ Converts 2d coordinates to pandas coordinate system """
        return Vec3(x + self._width / 2.0, 1, -y - self._height / 2.0)

    def set_shader(self, shader):
        """ Sets a shader to be used for rendering the image """
        self.node.set_shader(shader)

    def set_shader_input(self, *args):
        """ Sets a shader input on the image """
        self.node.set_shader_input(*args)

    def remove(self):
        """ Removes the image """
        self.node.remove()

    def hide(self):
        """ Hides the image """
        self.node.hide()

    def show(self):
        """ Shows the image if it was previously hidden """
        self.node.show()
Exemple #46
0
class BAbility (Bar):
    def __init__(self, power):
        Bar.__init__(self)
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.amount = 0
        self.power = []
        
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------------BAR INIT------------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        if power == "GRAIN": 
            self.path = "./tex/ability_cereal_bar.png"
            self.path2 = "./tex/rice.png"
            self.path3 = "./tex/ability_cereal_amount.png"
            self.posX = -1.20
            self.posY = -0.85
        if power == "FRUIT": 
            self.path = "./tex/ability_fruit_bar.png"
            self.path2 = "./tex/straw.png"
            self.path3 = "./tex/ability_fruit_amount.png"
            self.posX = -1.08
            self.posY = -0.85
        if power == "MILK": 
            self.path = "./tex/ability_milk_bar.png"
            self.path2 = "./tex/milk.png"
            self.path3 = "./tex/ability_milk_amount.png"
            self.posX = -0.96
            self.posY = -0.85
        if power == "VEGETABLE": 
            self.path = "./tex/ability_vegetable_bar.png"
            self.path2 = "./tex/letuce.png"
            self.path3 = "./tex/ability_vegetable_amount.png"
            self.posX = -0.84
            self.posY = -0.85
        if power == "FISH": 
            self.path = "./tex/ability_fish_bar.png"
            self.path2 = "./tex/fish.png"
            self.path3 = "./tex/ability_fish_amount.png"
            self.posX = -0.72
            self.posY = -0.85
        
        # Initial sprite bar    
        self.bar = OnscreenImage(image=self.path, pos = (self.posX, 0, self.posY),hpr=None, scale = (0.05,1.0,0.035), color=None, parent=None, sort=1)
        self.bar.setTransparency(TransparencyAttrib.MAlpha)
        
        # Shape ability bar
        self.item = OnscreenImage(image=self.path2, pos = (self.posX, 0, -0.90),hpr=None, scale = 0.06, color=None, parent=None, sort=2)
        self.item.setTransparency(TransparencyAttrib.MAlpha)
        
        # It prepares sprites amount bar
        i=0
        while i<5:
            self.power.append(OnscreenImage(image=self.path3, pos = (self.posX, 0, self.posY+((i+1)*0.055)),hpr=None, scale = (0.05,1.0,0.025), color=None, parent=None, sort=1))
            self.power[i].setTransparency(TransparencyAttrib.MAlpha)
            self.power[i].hide()
            i=i+1
    #end __init__
    
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It increases the amount of the bar
    def itemCollected(self,amnt):
        if      self.amount > 4: self.amount = 5
        else:   
            self.power[self.amount].show()
            self.amount = self.amount + amnt
    #end itemCollected
    
    # It decreases the amount of the bar
    def powerUsed(self,amnt):
        self.amount = self.amount - 1
        self.power[self.amount].hide();        
    #end powerUsed
    
    # It makes empty the bar
    def setEmpty(self):
        while self.amount > 0:
            self.amount = self.amount - 1
            self.power[self.amount].hide()
    #end setEmpty

    # It makes disappear the bar
    def hide(self):
        self.bar.hide()
        self.item.hide()
        
        i=0
        while i<5:
            self.power[i].hide()
            i=i+1
    #end hide
    
    # It makes that sprite have an intermitent alpha effect for 2 seconds
    def taskGlowing(self, task):
        if task.time > 2:
            self.bar.show()
            self.item.show()
            i=0
            while i<self.amount:
                self.power[i].show()
                i=i+1
            
            self.isVisible = True
            self.lastTime = 0.0
            return task.done
        else:
            if (task.time - self.lastTime) > 0.15:
                self.lastTime = task.time
                if self.isVisible == True:  
                    self.bar.hide()
                    self.item.hide()
                    i=0
                    while i<self.amount:
                        self.power[i].hide()
                        i=i+1
                
                    self.isVisible = False
                else:
                    self.bar.show()
                    self.item.show()
                    i=0
                    while i<self.amount:
                        self.power[i].show()
                        i=i+1
                        
                    self.isVisible = True
                
            return task.cont
Exemple #47
0
    def ajouterFrameJoueur(self, ordre, joueur):
        size = 0.75
        gauche = 1
        if ordre == 0:
            gauche = -1
        elif ordre == 1:
            gauche = 1
        frameJoueur = DirectFrame(text="",
                                  frameSize=(-size, size, -size, size),
                                  pos=(0.75 * gauche, -1, 0))
        frameJoueur.reparentTo(self.frameTop)

        frameContenu = DirectFrame(text="",
                                   frameColor=(0, 25, 0, 0.1),
                                   frameSize=(-size * 0.75, size * 0.75,
                                              -size * 0.90, size * 0.90),
                                   pos=(0, -1, 0))
        frameContenu.reparentTo(frameJoueur)

        # ajouter les labels pour les infos sur le joueur
        labelNom = OnscreenText(text=joueur.nom,
                                pos=(0, 0.60),
                                scale=0.14,
                                bg=(255, 255, 255, 1))
        labelNom.reparentTo(frameContenu)

        messages = ["niveau: ", "exp initial: ", "exp gagné: ", "exp actuel: "]
        values = [
            joueur.level, joueur.ancienExperience, joueur.gainExperience,
            joueur.experience
        ]
        for i in range(4):
            message = messages[i] + str(values[i])
            self.ajouterLabelInfo(frameContenu, message, i)
        # labelNom = OnscreenText(text = 'Niveau: ', pos = (0, 0.45), scale = 0.07, bg = (255,255,255,1))
        # labelNom.reparentTo(frameContenu)

        # ajouter la couronne pour le joueur gagnant
        if joueur.vainqueur:
            self.imageCouronne = OnscreenImage(
                parent=frameContenu,
                image='../asset/Menu/couronne.png',
                pos=(-0.5, 0, 0.8),
                scale=(0.2, 1, 0.2),
                hpr=(0, 0, -35))
            self.imageCouronne.setTransparency(TransparencyAttrib.MAlpha)
            self.ajouterTexteGagnant(joueur.message)

        # si le joueur a gagné de niveau
        if joueur.levelUp:
            imageLevelUp = OnscreenImage(parent=frameContenu,
                                         image='../asset/Menu/levelUp.png',
                                         pos=(-0.6, 0, 0.1),
                                         scale=(0.2, 1, 0.2))
            imageLevelUp.setTransparency(TransparencyAttrib.MAlpha)

            # le label pour le level up
            labelLevelUp = OnscreenText(text="Level Up!",
                                        pos=(-0.6, 0.4),
                                        scale=0.11)
            labelLevelUp.reparentTo(frameContenu)
            labelLevelUp.hide()

            # interval
            duree = 2
            intervalUp = imageLevelUp.posInterval(duree,
                                                  Point3(-0.6, 0, 0.3),
                                                  startPos=Point3(
                                                      -0.6, 0, 0.1),
                                                  blendType='easeIn')
            sequence = Sequence(Func(lambda: imageLevelUp.show()), intervalUp,
                                Func(lambda: imageLevelUp.hide()),
                                Func(lambda: labelLevelUp.show()), Wait(1),
                                Func(lambda: labelLevelUp.hide()), Wait(1))

            sequence.loop()
Exemple #48
0
class BEnergy(Bar):
    def __init__(self):
        Bar.__init__(self)

        #-----------------------------------------------------------------------------------------------------------------------------------------------
        #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------
        #-----------------------------------------------------------------------------------------------------------------------------------------------
        self.amount = 0
        self.tmpAmount = 0

        # Background bar
        self.bar = OnscreenImage(image="./tex/energy_bar.png",
                                 pos=(-0.74, 0, 0.90),
                                 hpr=None,
                                 scale=(0.59, 1.0, 0.09),
                                 color=None,
                                 parent=None,
                                 sort=1)
        self.bar.setTransparency(TransparencyAttrib.MAlpha)

        # Energy spites
        self.energyBar = []

        # It prepares sprites amount bar
        i = 0
        while (i < 40):
            self.energyBar.append(None)
            self.energyBar.insert(
                i,
                OnscreenImage(image="./tex/energy/" + str(i + 1) + ".png",
                              pos=(-1.27 + ((i * 5) * 0.0053), 0, 0.92),
                              hpr=None,
                              scale=(0.01, 1.0, 0.03),
                              color=None,
                              parent=None,
                              sort=2))
            self.energyBar[i].setTransparency(TransparencyAttrib.MAlpha)
            self.energyBar[i].hide()
            i = i + 1

    #end __init__

    #-----------------------------------------------------------------------------------------------------------------------------------------------
    #----------------------------------------------------------------FUNCTIONS----------------------------------------------------------------------
    #-----------------------------------------------------------------------------------------------------------------------------------------------
    # It increases the amount of the bar given
    def increase(self, amnt):
        finalAmount = self.amount + amnt
        if finalAmount <= 200:
            while (self.amount < finalAmount):
                self.energyBar[self.amount / 5].show()
                self.amount = self.amount + 5

    #end increase

    # It decreases the amount of the bar given
    def decrease(self, amnt):
        if amnt < 5:
            self.tmpAmount = self.tmpAmount + amnt
            if self.tmpAmount >= 5:
                num = (self.amount - 5) / 5
                self.energyBar[num].hide()
                self.amount = self.amount - 5
                self.tmpAmount = 0

        else:
            if self.amount > 0:
                initAmount = self.amount
                while (self.amount > (initAmount - amnt)):
                    num = (self.amount - 5) / 5
                    if num >= 0:
                        self.energyBar[num].hide()
                    self.amount = self.amount - 5

    #end decrease

    # It makes disappear the bar
    def hide(self):
        self.bar.hide()

        i = 0
        while (i < 40):
            self.energyBar[i].hide()
            i = i + 1

    #end hide

    # It makes appear the bar
    def show(self):
        self.bar.show()

        i = 0
        while (i < (self.amount / 5)):
            self.energyBar[i].show()
            i = i + 1

    #end show

    # It makes that sprite have an intermitent alpha effect for 2 seconds
    def taskGlowing(self, task):
        if task.time > 2:
            self.bar.show()
            i = 0
            while (i < (self.amount / 5)):
                self.energyBar[i].show()
                i = i + 1

            self.isVisible = True
            self.lastTime = 0.0
            return task.done
        else:
            if (task.time - self.lastTime) > 0.15:
                self.lastTime = task.time
                if self.isVisible == True:
                    self.bar.hide()
                    i = 0
                    while (i < (self.amount / 5)):
                        self.energyBar[i].hide()
                        i = i + 1

                    self.isVisible = False
                else:
                    self.bar.show()
                    i = 0
                    while (i < (self.amount / 5)):
                        self.energyBar[i].show()
                        i = i + 1

                    self.isVisible = True

            return task.cont
class HUD(DirectObject):
	#TODO: Preload all images
	def __init__(self, base, player):
		self.base   = base
		self.player = player

		self.heartmax = 160
		self.heartmin = 80
		self.heartbpm = self.heartmin
		self.heartaccum = 0
		self.last = 0
		self.heartbasis = 'assets/images/heartbeat2-%d.png'
		self.heartframe = 0
		self.heartimage = OnscreenImage(self.heartbasis % (1,), scale=(0.1,0.1,0.1), pos=(-1,0, 0.8))
		self.keyimage = OnscreenImage('assets/images/key.png', scale=(0.08,0.08,0.08), pos=(-1,0,0.60))
		self.keyimage.setTransparency(TransparencyAttrib.MAlpha)
		self.text = OnscreenText('', pos=(-0.8, 0.8), scale=0.05, fg=(0,1,0,1),	bg=(0,0,0,0))

		self.hasKey = False

		self.base.taskMgr.add(self.update, 'hud')
		
	def __del__(self):
		self.base   = None
		self.player = None
		self.heartimage.destroy()
		self.text.destroy()

	def update(self, task):
		if self.player.isAlive():
			elapsed = task.time - self.last
			self.last = task.time

			# After a certain point, it should be cleared
			# Fear must also increase heartbeat
			f, b = self.player.fear, self.player.breath
			bpm = 80 + 200 * (0.75 + 0.25 * f) * (1 - b) + 40 * f

			self.heartaccum += elapsed * (bpm + self.heartbpm) / 2.0
			self.heartbpm = bpm
			self.heartframe = int(8 * self.heartaccum / 60) % 8
			self.heartimage.setImage(self.heartbasis % (self.heartframe + 1,))
			self.heartimage.setTransparency(TransparencyAttrib.MAlpha)

			#TODO: Update parameters
			heartampl = self.heartmax - self.heartmin
			if self.heartbpm < self.heartmax:
				s = float(self.heartbpm - self.heartmin) / heartampl
				self.text.setFg((s,1,0,1))
			else:
				s = float(self.heartbpm - self.heartmax) / heartampl
				self.text.setFg((1,1-s,0,1))

			self.text.setText('%d BPM' % (self.heartbpm,))
		else:
			self.text.setFg((1,1,1,1))
			self.text.setText('0 BPM')
			#TODO: send a 'death' event and, possibly, play back a nice heart stopping animation
			#return task.done

		if (self.hasKey):
			self.keyimage.show()
		else:
			self.keyimage.hide()
		self.heartimage.show()
		self.text.show()

		return task.cont

	def hide(self):
		self.heartimage.hide()
		self.text.hide()

	def setKey(self, key):
		self.hasKey = key