Beispiel #1
0
 def CreateField(self, fieldLabel, initText, yIndex, focus):
     label = OnscreenText(text = fieldLabel, pos = (-0.4, 0.35 - yIndex * 0.2), scale = 0.07, fg = (1, 1, 1, 1))
     label.reparentTo(self.node)
     f = DirectEntry(text = '' ,
                     scale = 0.05,
                     initialText = initText, 
                     numLines = 1,
                     rolloverSound = None,
                     clickSound = None,
                     pos = (-0.4, 1, 0.25 - yIndex * 0.2),
                     focus = (not focus))
     f.reparentTo(self.frame)
     return f
Beispiel #2
0
class World(DirectObject.DirectObject):
    def __init__(self):
        self.creeps = None
        self.open = False
        self.sec = 0
        self.min = 0
        self.pindex = 1  # This is the Pause Index
        self.index = -1  # This is the hero Index
        self.rindex = False  # This is the Repick Index
        self.hpicked = []  # This List Stores All The Heroes Picked and Removes Them
        for i in range(0, 110):
            self.hpicked.append(-1)  # Gotta change and check this
        self.hindex = 0  # When a hero is picked this index saves it and stores it in the list
        self.RND = render.attachNewNode("rend")
        self.LightHandler = None
        self.Players()
        self.LoadTerrain()  # Load the Map
        self.SetupCamera()
        self.SetupLight()
        self.SetupEvents()
        self.SetupTimer()
        self.chooseHero()
        self.SetupMap()
        self.SetupCreeps()
        self.SetupCollision()
        self.displayed = False
        self.keyMap = {"cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0, "zoom-in": 0, "zoom-out": 0}
        self.chatindex = 0
        self.chat = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.text = ["text1", "text2", "text3", "text4", "text5" "text6" "text7" "text8" "text9", "text10", "text11"]
        self.task = None

    def Players(self):
        self.hero1 = None
        self.hero2 = None
        self.hero3 = None
        self.hero4 = None
        self.hero5 = None
        self.hero6 = None
        self.hero7 = None
        self.hero8 = None
        self.hero9 = None
        self.hero10 = None
        self.player1 = None
        self.player2 = None
        self.player3 = None
        self.player4 = None
        self.player5 = None
        self.player6 = None
        self.player7 = None
        self.player8 = None
        self.player9 = None
        self.player10 = None

    def LoadTerrain(self):
        self.terrain = loader.loadModel("models/environment")
        self.terrain.setTag("Map", "1")
        self.terrain.reparentTo(self.RND)
        self.itmpan1 = OnscreenImage(image=MYDIRIMG + "/3.png", scale=(0.3, 0, 0.09), pos=(0.61, 0, -0.915))
        self.itmpan2 = OnscreenImage(image=MYDIRIMG + "/3.png", scale=(0.3, 0, 0.09), pos=(0.61, 0, -0.740))
        self.t2 = OnscreenImage(image=MYDIRIMG + "/t2.png", scale=(0.25, 0, 0.06), pos=(1.160, 0, -0.71))
        self.t1 = OnscreenImage(image=MYDIRIMG + "/t1.png", scale=(0.25, 0, 0.06), pos=(1.160, 0, -0.83))
        self.end = OnscreenImage(image=MYDIRIMG + "/end.png", scale=(0.1, 0, 0.2), pos=(1.510, 0, -0.80))
        self.back = OnscreenImage(image=MYDIRIMG + "/back.png", scale=(0.57, 0, 0.2), pos=(-0.26, 0, -0.80))

    def SetupCollision(self):
        base.cTrav = CollisionTraverser()
        self.collHandler = CollisionHandlerQueue()
        self.pickerNode = CollisionNode("mouseRay")
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        base.cTrav.addCollider(self.pickerNP, self.collHandler)

    def ObjectClick(self):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        base.cTrav.traverse(render)  # Assume for simplicity's sake that myHandler is a CollisionHandlerQueue.
        if self.collHandler.getNumEntries() > 0:  # This is so we get the closest object.
            self.collHandler.sortEntries()
            self.pickedObj = self.collHandler.getEntry(0).getIntoNodePath()
            self.pickedObj1 = self.pickedObj.findNetTag("Unit")
            self.pickedObj2 = self.pickedObj.findNetTag("MyHero")
            self.pickedObj3 = self.pickedObj.findNetTag("Map")
            self.pickedObj4 = self.pickedObj.findNetTag("MyHero")
            if self.pickedObj1 == self.creeps.getModel():
                if self.displayed is False:
                    self.displayed = True
                    self.creeps.display()
            else:
                if self.displayed is True:
                    self.displayed = False
                    self.creeps.displaynot()
            if self.hero != None:
                if self.pickedObj2 == self.hero1.getModel():
                    if self.displayed is False:
                        self.displayed = True
                        self.hero1.display()
                else:
                    if self.displayed is True:
                        self.displayed = False
                        self.hero1.displaynot()

    def SetupCamera(self):
        base.camera.setPos(0, 0, 180)
        base.camera.setP(-30)
        base.camera.lookAt(0, 0, 0)

    def SetupTimer(self):
        self.btn = aspect2d.attachNewNode("btn")
        self.btn.setTransparency(1)
        self.timesec = OnscreenText(text="", pos=(1.3, -0.71), fg=(1, 1, 1, 1), mayChange=1, scale=0.05)
        self.timemin = OnscreenText(text="", pos=(1.1, -0.71), fg=(1, 1, 1, 1), mayChange=1, scale=0.05)
        self.pausebtn = DirectButton(
            text="Pause (%d)" % (self.pindex),
            parent=self.btn,
            text_fg=(0, 0.2, 0, 1),
            text_pos=(0.05, -0.15),
            text_scale=(0.48, 0.53),
            image=(MYDIRIMG + "btnof.png", MYDIRIMG + "btnon.png", MYDIRIMG + "btnon.png", None),
            frameColor=(0, 0, 0, 0),
            pos=(-1.0, 0, -0.81),
            image_scale=(1.0, 0, 0.7),
            scale=(0.15, 0, 0.10),
            command=self.Pause,
        )
        self.infobtn = DirectButton(
            text="Info",
            parent=self.btn,
            text_fg=(0, 0.2, 0, 1),
            text_pos=(0.05, -0.15),
            text_scale=0.6,
            image=(MYDIRIMG + "btnof.png", MYDIRIMG + "btnon.png", MYDIRIMG + "btnon.png", None),
            frameColor=(0, 0, 0, 0),
            pos=(-1.0, 0, -0.68),
            image_scale=(1.0, 0, 0.7),
            scale=(0.15, 0, 0.10),
            command=self.Pause,
        )
        taskMgr.doMethodLater(1, self.Timer, "tickTask")

    def SetupMap(self):
        self.minimap = minimap(None)

    def SetupLight(self):
        self.LightHandler = Lights(None)

    def SetupEvents(self):
        self.DEntry = DirectEntry(
            text="",
            pos=(-0.6, 0.0, -0.7),
            image=MYDIRIMG + "/tooltips9.png",
            frameColor=(0, 0, 0, 1),
            width=27,
            image_pos=(13.5, 0, 0.2),
            image_scale=(15, 0, 0.6),
            scale=0.05,
            initialText="",
            numLines=1,
            focus=1,
            command=self.Parser,
        )
        self.DEntry.setTransparency(1)
        self.DEntry.detachNode()
        taskMgr.add(self.MoveCamera, "CameraControl")
        self.accept("enter", self.MsgBox)
        self.accept("wheel_up", self.setKey, ["zoom-in", 1])
        self.accept("wheel_down", self.setKey, ["zoom-out", 1])
        #   self.accept("wheel_up-up",self.setKey, ["zoom-in",0])
        #    self.accept("wheel_down-up",self.setKey, ["zoom-out",0])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("d", self.setKey, ["cam-right", 1])
        self.accept("w", self.setKey, ["cam-up", 1])
        self.accept("s", self.setKey, ["cam-down", 1])
        self.accept("+", self.setKey, ["zoom-in", 1])
        self.accept("-", self.setKey, ["zoom-out", 1])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("d-up", self.setKey, ["cam-right", 0])
        self.accept("w-up", self.setKey, ["cam-up", 0])
        self.accept("s-up", self.setKey, ["cam-down", 0])
        self.accept("+-up", self.setKey, ["zoom-in", 0])
        self.accept("--up", self.setKey, ["zoom-out", 0])
        self.accept("mouse1", self.ObjectClick)

    def UnSetupEvents(self):
        self.ignore("a")
        self.ignore("s")
        self.ignore("w")
        self.ignore("s")
        self.ignore("+")
        self.ignore("-")
        self.ignore("enter")
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        taskMgr.remove("CameraControl")

    def setKey(self, key, value):
        self.keyMap[key] = value

    def MoveCamera(self, task):
        mpos = base.mouseWatcherNode.getMouse()
        elapsed = globalClock.getDt()
        self.dt = elapsed
        self.mx = mpos.getX()
        self.my = mpos.getY()
        if self.keyMap["cam-left"] != 0:
            base.camera.setX(base.camera, -(self.dt * 20))
        if self.keyMap["cam-right"] != 0:
            base.camera.setX(base.camera, +(self.dt * 20))
        if self.keyMap["zoom-in"] != 0:
            base.camera.setY(base.camera, -(self.dt * 20))
        if self.keyMap["zoom-out"] != 0:
            base.camera.setY(base.camera, +(self.dt * 20))
        if self.keyMap["cam-down"] != 0:
            base.camera.setZ(base.camera, -(self.dt * 20))
        if self.keyMap["cam-up"] != 0:
            base.camera.setZ(base.camera, +(self.dt * 20))
        if self.mx > 0.95:
            if base.camera.getX() < MAPLIMIT:
                base.camera.setX(base.camera, +(self.dt * SCROLLSPEED))
        if self.mx < -0.95:
            if base.camera.getX() > -MAPLIMIT:
                base.camera.setX(base.camera, -(self.dt * SCROLLSPEED))
        if self.my > 0.95:
            if base.camera.getY() < MAPLIMIT:
                base.camera.setZ(base.camera, +(self.dt * SCROLLSPEED))
        if self.my < -0.95:
            if base.camera.getY() > -MAPLIMIT:
                base.camera.setZ(base.camera, -(self.dt * SCROLLSPEED))
        return task.cont

    def chooseHero(self):
        if self.hero1 == None:
            self.BTNnode = aspect2d.attachNewNode("buttons")
            for i in range(0, 3):
                for j in range(0, 4):
                    self.index += 1
                    if icons[self.index] == None:
                        continue
                    if self.hpicked[self.index] == self.index:
                        continue
                    self.worldHeroButton(-1.8 + j * 0.1, -i * 0.1, self.index)

    def worldHeroButton(self, x, y, arg):
        DirectButton(
            text="",
            parent=self.BTNnode,
            text_font=font,
            image=MYDIRICONS + icons[arg] + ".tga",
            frameColor=(0, 0, 0, 0),
            pad=(-0.1, -0.1),
            image_scale=(IconSx + 0.2, 0, IconSy + 0.2),
            pos=(posx - 0.5 + x, 0, posy + y),
            scale=(0.20, 0, 0.20),
            command=self.SetupHero,
            extraArgs=[arg],
        )

    def SetupCreeps(self):
        self.creeps = Unit1()

    def SetupHero(self, no):
        self.hpicked.insert(self.hindex, no)
        self.hindex += 1
        self.BTNnode.detachNode()
        self.hero1 = Hero(no)
        self.hero1.getModel().setTag("Hero1", "1")

    def Timer(self, task):
        self.task = task
        self.sec += 1
        if self.hero1 != None:
            self.hero1.sendTime(self.min, self.sec)
        if self.sec >= 60:
            self.sec = 0
            self.min += 1
            self.timemin.setText(str(self.min))
        self.timesec.setText(str(self.sec))
        return task.again

    def MsgBox(self):
        if self.open == False:
            self.DEntry.reparentTo(aspect2d)
            self.open = True
        else:
            self.DEntry.detachNode()
            self.open = False

    def Parser(self, text):
        Text = text
        # Within 120 seconds on the game
        if self.hero1 == None:
            self.BTNnode.detachNode()
            if Text == "-random":
                self.hero1 = Hero(random.randint(0, 96))
            elif Text == "-random int":
                self.hero1 = Hero(random.randint(66, 96))
            elif Text == "-random str":
                self.hero1 = Hero(random.randint(0, 36))
            elif Text == "-random agi":
                self.hero1 == Hero(random.randint(36, 66))
        if Text == "-repick":
            if self.rindex == False:
                if self.hero1 != None:
                    self.hero1.destroy()
                    self.hero1 = None
                    self.index = -1
                    self.chooseHero()
                    self.rindex = True
            else:
                Error("Cannot Repick")
        elif Text == "-":
            pass
        else:
            pass

    #      self.Chat(Text,self.task)
    #     taskMgr.add(self.Chat,"nn",extraArgs=[Text])
    # this sends text to allies

    def ChatTimer(self, task, chat, i):
        chat.destroy()
        self.chat.insert(i, 0)
        self.chatindex -= 1
        return task.done

    def Chat(self, text, task):
        for i in range(1, 15):
            if self.chat[i] == 0:
                self.text[i] = OnscreenText(text=text, pos=(-1.3, -0.4), fg=(0, 0, 0, 1), scale=0.07)
                self.chat.insert(self.chatindex, 1)
                taskMgr.doMethodLater(5, self.ChatTimer, "chat", [task, self.text[i], i])
                self.chatindex += 1
                break
            else:
                self.text[i].setY(-(0.1 * i) + 0.4)
        return task.done

    def Pause(self):
        if self.pindex != 0:
            self.pindex -= 1
            time.sleep(2)
            self.pausebtn["text"] = "Pause (%d)" % (self.pindex)
        else:
            Error("Pause Limits Used")

    def destroy(self):
        if self.hero1 != None:
            self.hero1.destroy()
        self.minimap.destroy()
        self.btn.detachNode()
        self.BTNnode.detachNode()
        taskMgr.remove("timer")
        self.terrain.detachNode()
        del self.LightHandler
        del self.creeps
        self.UnSetupEvents()

    def MousePos(self, task):  # This Took me 1.5 Months to Learn
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pos3d = Point3()
            self.nearPoint = Point3()
            self.farPoint = Point3()
            base.camLens.extrude(mpos, self.nearPoint, self.farPoint)
        if self.plane.intersectsLine(
            self.pos3d, render.getRelativePoint(camera, self.nearPoint), render.getRelativePoint(camera, self.farPoint)
        ):
            pass
        return task.again
Beispiel #3
0
class FrameAutenticacao(object):
    '''
    FrameAutenticacao
    '''
    def __init__(self, parent=None, **kw):
        self.__qtd_conexao = 0

        self.__frmAuth = DirectFrame(frameColor=(0, 0, 0, .3),
                                     frameSize=(-.5, .5, 0, 0.45),
                                     pos=(0, 0, -.1),
                                     enableEdit=1)

        self.__lblLogin = DirectLabel(text="Login: "******"Senha: ",
                                      scale=0.05,
                                      pos=(-0.3, 0, 0.2),
                                      frameColor=(0, 0, 0, 0),
                                      text_fg=(1, 1, 1, 1))

        self.__etySenha = DirectEntry(
            scale=0.05,
            width=12,
            pos=(-.2, 0, 0.2),
            cursorKeys=1,
            obscured=1,
            focusInCommand=self.__command_clear_senha)

        self.__btnEntrar = DirectButton(frameColor=(0, 0, 0, 1),
                                        text="Entrar",
                                        scale=0.06,
                                        pos=(0.3, 0, 0.1),
                                        text_fg=(1, 1, 1, 1),
                                        rolloverSound=None,
                                        clickSound=None,
                                        command=self.__command_entrar)

        self.__lblLogin.reparentTo(self.__frmAuth)
        self.__etyLogin.reparentTo(self.__frmAuth)
        self.__lblSenha.reparentTo(self.__frmAuth)
        self.__etySenha.reparentTo(self.__frmAuth)
        self.__btnEntrar.reparentTo(self.__frmAuth)

        self.__etyLogin.set("viner")
        self.__etySenha.set("viner")

    def __command_clear_senha(self):
        self.__etySenha.set("")

    def __command_entrar(self, txt=None):
        login = self.__etyLogin.get()
        senha = self.__etySenha.get()

        valido = True

        if login == "":
            addMensagem("O campo Login e obrigatorio !", COR_BRANCO)
            valido = False

        if senha == "":
            addMensagem("O campo Senha e obrigatorio !", COR_BRANCO)
            valido = False

        if valido:
            self.__btnEntrar["state"] = DGG.DISABLED

            taskMgr.add(self.__task_conectar_servidor,
                        'ConectarServidor',
                        extraArgs=[login, senha],
                        appendTask=True)

            #inicia_nova_thread(1, 0, "Conectar Servidor", self.__conectar_servidor, login, senha)

    def __task_conectar_servidor(self, login, senha, task):

        if self.__qtd_conexao < TENTATIVAS:

            if vinerOnline.flg_conectado == vinerOnline.ERROLOGIN:
                vinerOnline.flg_conectado = vinerOnline.DESCONECT

                self.__btnEntrar["state"] = DGG.NORMAL
                self.__qtd_conexao = 0

                addMensagem('Login ou senha invalido', COR_VERMELHO)

                self.__etyLogin.setFocus()

            elif vinerOnline.flg_conectado == vinerOnline.CONECTADO:
                #addMensagem("Conectado 12 !!!")
                #self.destroy()
                pass

            else:
                vinerOnline.conectar_servidor(login, senha)
                self.__qtd_conexao += 1

                taskMgr.doMethodLater(INTERVALO_TENTATIVAS,
                                      self.__task_conectar_servidor,
                                      'ConectarServidorLater',
                                      extraArgs=[login, senha],
                                      appendTask=True)

                msg = "Tentativa %s/5 -  Conectando..." % (self.__qtd_conexao)
                addMensagem(msg, COR_BRANCO)

        else:
            vinerOnline.flg_conectado = vinerOnline.DESCONECT
            self.__btnEntrar["state"] = DGG.NORMAL
            self.__qtd_conexao = 0
            addMensagem("Servidor nao encontrado", COR_VERMELHO)

        return task.done

    def destroy(self):
        self.__frmAuth.destroy()

        del self.__lblLogin
        del self.__etyLogin
        del self.__lblSenha
        del self.__etySenha
        del self.__btnEntrar
        del self.__frmAuth
Beispiel #4
0
class FileDialog(DirectObject):
    def __init__(self, title, initial_status, callback):
        self.frmLeft = -.7
        self.frmBottom = -.12
        self.frmRight = .7
        self.frmTop = .12

        self.frmWidth = self.frmRight - self.frmLeft
        self.frmHeight = self.frmTop - self.frmBottom

        self.title = title
        self.initial_status = initial_status
        self.callback = callback

        self.result = None
        self.done = 0

    def activate(self):
        # create main dialog frame
        # Note: frame position references the CENTER of the frame
        self.frm = DirectFrame(pos=(0, 0, 0),
                               frameSize=(self.frmLeft, self.frmRight,
                                          self.frmBottom, self.frmTop),
                               relief=DGG.RIDGE,
                               borderWidth=(0.01, 0.01),
                               frameColor=(0.6, 0.6, 0.6, 1.0))

        self.frm.reparentTo(base.aspect2d)

        # Note: wonderfully enough, label position on the other hand
        # references the CENTER of the LEFT border of the label!
        titleLabel = DirectLabel(text=self.title,
                                 scale=0.04,
                                 frameColor=(0.5, 0.5, 0.5, 1),
                                 relief=DGG.RIDGE,
                                 borderWidth=(0.01, 0.01),
                                 text_align=TextNode.ALeft)

        titleLabel.setPos(-self.frmWidth / 2 + .02, 0,
                          self.frmHeight / 2 - .045)
        titleLabel.reparentTo(self.frm)

        sc = .04
        self.dir_edit_field = DirectEntry(
            text='',  # prompt text
            scale=sc,
            frameColor=(0.65, 0.65, 0.65, 1),
            command=self.setText,
            width=32,
            numLines=1,
            focus=1,
            focusInCommand=self.efFocusIn,
        )

        self.dir_edit_field.setPos(-self.frmWidth / 2 + .02, 0,
                                   self.frmHeight / 2 - .13)
        self.dir_edit_field.reparentTo(self.frm)

        self.statusLabel = DirectLabel(
            text=self.initial_status,
            scale=0.04,
            frameColor=(0.6, 0.6, 0.6, 1),
            # relief = DGG.RIDGE,
            # borderWidth = (0.01, 0.01),
            text_align=TextNode.ALeft)

        self.statusLabel.setPos(-self.frmWidth / 2 + .02, 0,
                                self.frmHeight / 2 - .2)
        self.statusLabel.reparentTo(self.frm)

    # call this if you need to run a form before your mainloop starts steppping the taskMgr
    def run(self):
        while self.done != 1:
            taskMgr.step()

        taskMgr.step(
        )  # once more to make the last output from the dialog visible
        # while we load a zone
        self.frm.removeNode()

    def end(self):
        self.frm.removeNode()

    # callback function to set  text: called by the Panda3d taskMgr when the user
    # has entered something into the DirectEntry widget
    def setText(self, textEntered):
        print 'dir_edit_field::setText:', textEntered
        self.done = self.callback(textEntered)
        if self.done != 1:
            self.dir_edit_field['focus'] = 1

    #clear the text
    def efFocusIn(self):
        print 'focus in'
        self.dir_edit_field.enterText('')

    def setStatus(self, status):
        self.statusLabel['text'] = status
Beispiel #5
0
class FileDialog(DirectObject):

    def __init__(self, title, initial_status, callback):
        self.frmLeft = -.7
        self.frmBottom = -.12
        self.frmRight = .7
        self.frmTop = .12
        
        self.frmWidth = self.frmRight - self.frmLeft
        self.frmHeight = self.frmTop - self.frmBottom
        
        self.title = title
        self.initial_status = initial_status
        self.callback = callback
        
        self.result = None
        self.done = 0
            
            
    def activate(self):
        # create main dialog frame
        # Note: frame position references the CENTER of the frame
        self.frm = DirectFrame(
            pos = (0,0,0),
            frameSize = (self.frmLeft, self.frmRight,self.frmBottom, self.frmTop),
            relief = DGG.RIDGE,
            borderWidth = (0.01, 0.01),
            frameColor = (0.6, 0.6, 0.6, 1.0))
        
        self.frm.reparentTo(base.aspect2d)
        
        # Note: wonderfully enough, label position on the other hand
        # references the CENTER of the LEFT border of the label!
        titleLabel = DirectLabel(text = self.title,
            scale = 0.04,
            frameColor = (0.5, 0.5, 0.5, 1),
            relief = DGG.RIDGE,
            borderWidth = (0.01, 0.01),
            text_align = TextNode.ALeft)
            
        titleLabel.setPos(-self.frmWidth/2+.02, 0, self.frmHeight/2-.045)
        titleLabel.reparentTo(self.frm)
        
        sc = .04     
        self.dir_edit_field = DirectEntry(
            text = '',      # prompt text
            scale = sc,
            frameColor = (0.65, 0.65, 0.65, 1),
            command=self.setText,
            width = 32,
            numLines = 1,
            focus = 1,
            focusInCommand=self.efFocusIn,
            )

        self.dir_edit_field.setPos(-self.frmWidth/2+.02, 0, self.frmHeight/2-.13)
        self.dir_edit_field.reparentTo(self.frm)

        self.statusLabel = DirectLabel(text = self.initial_status,
            scale = 0.04,
            frameColor = (0.6, 0.6, 0.6, 1),
            # relief = DGG.RIDGE,
            # borderWidth = (0.01, 0.01),
            text_align = TextNode.ALeft)
            
        self.statusLabel.setPos(-self.frmWidth/2+.02, 0, self.frmHeight/2-.2)
        self.statusLabel.reparentTo(self.frm)

    # call this if you need to run a form before your mainloop starts steppping the taskMgr
    def run(self):
        while self.done != 1:
            taskMgr.step()

        taskMgr.step()          # once more to make the last output from the dialog visible
                                # while we load a zone
        self.frm.removeNode()

    def end(self):
        self.frm.removeNode()
        

    # callback function to set  text: called by the Panda3d taskMgr when the user
    # has entered something into the DirectEntry widget
    def setText(self, textEntered):
        print 'dir_edit_field::setText:', textEntered
        self.done = self.callback(textEntered)
        if self.done != 1:
            self.dir_edit_field['focus'] = 1

                
    #clear the text
    def efFocusIn(self):
        print 'focus in'
        self.dir_edit_field.enterText('')
        
    def setStatus(self, status):
        self.statusLabel['text'] = status
class MainMenu(DirectObject):
    """This class represents the main menu as seen directly after the
    application has been started"""
    def __init__(self):

        # loading music
        self.menuMusic = loader.loadMusic("music/01Menu.mp3")
        self.menuMusic.setLoop(True)

        # create a main frame as big as the window
        self.frameMain = DirectFrame(
            # set framesize the same size as the window
            frameSize = (base.a2dLeft, base.a2dRight,
                         base.a2dTop, base.a2dBottom),
            # position center
            pos = (0, 0, 0),
            # set tramsparent background color
            frameColor = (0.15, 0.15, 0.15, 1))
        #self.frameMain.reparentTo(render2d)

        self.menuBackground = OnscreenImage(
            image = 'gui/Background.png',
            scale = (1.66, 1, 1),
            pos = (0, 0, 0))
        self.menuBackground.reparentTo(self.frameMain)

        self.defaultBtnMap = base.loader.loadModel("gui/button_map")
        self.buttonGeom = (
            self.defaultBtnMap.find("**/button_ready"),
            self.defaultBtnMap.find("**/button_click"),
            self.defaultBtnMap.find("**/button_rollover"),
            self.defaultBtnMap.find("**/button_disabled"))
        self.defaultTxtMap = base.loader.loadModel("gui/textbox_map")
        self.textboxGeom = self.defaultTxtMap.find("**/textbox")

        monospace = loader.loadFont('gui/DejaVuSansMono.ttf')
        defaultFont = loader.loadFont('gui/eufm10.ttf')

        # create the title
        self.textscale = 0.25
        self.title = DirectLabel(
            # scale and position
            scale = self.textscale,
            pos = (0.0, 0.0, base.a2dTop - self.textscale),
            # frame
            frameColor = (0, 0, 0, 0),
            # Text
            text = "Dungeon Crawler",
            text_align = TextNode.ACenter,
            text_fg = (0.82,0.85,0.87,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (-0.02, -0.02),
            text_font = defaultFont)
        self.title.setTransparency(1)
        self.title.reparentTo(self.frameMain)

        # create a host button
        self.btnHostPos = Vec3(0, 0, .45)
        self.btnHostScale = 0.25
        self.btnHost = DirectButton(
            # Scale and position
            scale = self.btnHostScale,
            pos = self.btnHostPos,
            # Text
            text = "Host",
            text_scale = 0.8,
            text_pos = (0, -0.2),
            text_fg = (0.82,0.85,0.87,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (-0.02, -0.02),
            text_font = defaultFont,
            # Frame
            geom = self.buttonGeom,
            frameColor = (0, 0, 0, 0),
            relief = 0,
            pressEffect = False,
            # Functionality
            command = self.host,
            rolloverSound = None,
            clickSound = None)
        self.btnHost.setTransparency(1)
        self.btnHost.reparentTo(self.frameMain)

        # create a join button
        self.btnJoinPos = Vec3(0, 0, 0)
        self.btnJoinScale = 0.25
        self.btnJoin = DirectButton(
            scale = self.btnJoinScale,
            pos = self.btnJoinPos,
            text = "Join",
            text_scale = 0.8,
            text_pos = (0, -0.2),
            text_fg = (0.82,0.85,0.87,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (-0.02, -0.02),
            text_font = defaultFont,
            geom = self.buttonGeom,
            frameColor = (0, 0, 0, 0),
            relief = 0,
            pressEffect = False,
            command = self.join,
            rolloverSound = None,
            clickSound = None)
        self.btnJoin.setTransparency(1)
        self.btnJoin.reparentTo(self.frameMain)

        # create the IP input field
        self.txtIPPos = Vec3(0, 0, -.30)
        self.txtIPScale = 0.25
        self.txtIPWidth = 9
        self.txtIP = DirectEntry(
            # scale and position
            pos = self.txtIPPos,
            scale = self.txtIPScale,
            width = self.txtIPWidth,
            # Text
            entryFont = monospace,
            text_align = TextNode.ACenter,
            text = "",
            text_scale = 0.5,
            text_pos = (0, -0.2),
            text_fg = (0.82,0.85,0.87,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (0.04, 0.04),
            initialText = "127.0.0.1",
            numLines = 1,
            # Frame
            geom = self.textboxGeom,
            frameColor = (0, 0, 0, 0),
            relief = 0,
            # Functionality
            command = self.join,
            focusInCommand = self.clearText)
        self.txtIP.reparentTo(self.frameMain)

        # create an exit button
        self.btnExitPos = Vec3(0, 0, -.75)
        self.btnExitScale = 0.25
        self.btnExit = DirectButton(
            scale = self.btnExitScale,
            pos = self.btnExitPos,
            text = "Exit",
            text_scale = 0.8,
            text_pos = (0, -0.2),
            text_fg = (0.82,0.85,0.87,1),
            text_shadow = (0, 0, 0, 1),
            text_shadowOffset = (-0.02, -0.02),
            text_font = defaultFont,
            geom = self.buttonGeom,
            frameColor = (0, 0, 0, 0),
            relief = 0,
            pressEffect = False,
            command = lambda: base.messenger.send("escape"),
            rolloverSound = None,
            clickSound = None)
        self.btnExit.setTransparency(1)
        self.btnExit.reparentTo(self.frameMain)

        # create a mute checkbox
        self.cbVolumeMute = DirectCheckBox(
            # set size
            scale = (0.1, 0.1, 0.1),
            frameSize = (-1, 1, 1, -1),
            # functionality and visuals
            command = self.cbVolumeMute_CheckedChanged,
            isChecked = True,
            checkedImage = "gui/SoundSwitch_off.png",
            uncheckedImage = "gui/SoundSwitch_on.png",
            # mouse behaviour
            relief = 0,
            pressEffect = False,
            rolloverSound = None,
            clickSound = None
            )
        self.cbVolumeMute.setTransparency(1)
        self.cbVolumeMute.reparentTo(self.frameMain)
        self.cbVolumeMute.commandFunc(None)

        # catch window resizes and recalculate the aspectration
        self.accept("window-event", self.recalcAspectRatio)
        self.accept("showerror", self.showError)

        # show the menu right away
        self.show()

    def host(self):
        """Function which will be called by pressing the host button"""
        self.hide()
        base.messenger.send("start_server")

    def join(self, ip=None):
        """Function which will be called by pressing the join button"""
        if ip == None: ip = self.txtIP.get(True)
        if ip == "": return
        self.hide()
        base.messenger.send("start_client", [ip])

    def showError(self, msg):
        self.show()
        self.dialog = OkDialog(
            dialogName="ErrorDialog",
            text="Error: {}".format(msg),
            command=self.closeDialog)

    def closeDialog(self, args):
        self.dialog.hide()

    def show(self):
        """Show the GUI"""
        self.frameMain.show()
        self.menuMusic.play()

    def hide(self):
        """Hide the GUI"""
        self.frameMain.hide()
        self.menuMusic.stop()

    def clearText(self):
        """Function to clear the text that was previously entered in the
        IP input field"""
        self.txtIP.enterText("")

    def cbVolumeMute_CheckedChanged(self, checked):
        if bool(checked):
            base.disableAllAudio()
        else:
            base.enableAllAudio()

    def recalcAspectRatio(self, window):
        """get the new aspect ratio to resize the mainframe"""
        # set the mainframe size to the window borders again
        self.frameMain["frameSize"] = (
            base.a2dLeft, base.a2dRight,
            base.a2dTop, base.a2dBottom)

        # calculate new aspec tratio
        wp = window.getProperties()
        aspX = 1.0
        aspY = 1.0
        wpXSize = wp.getXSize()
        wpYSize = wp.getYSize()
        if wpXSize > wpYSize:
            aspX = wpXSize / float(wpYSize)
        else:
            aspY = wpYSize / float(wpXSize)
        # calculate new position/size/whatever of the gui items
        self.title.setPos(0.0, 0.0, base.a2dTop - self.textscale)
        self.menuBackground.setScale(1.0 * aspX, 1.0, 1.0 * aspY)
        self.cbVolumeMute.setPos(base.a2dRight - 0.15, 0, base.a2dBottom + 0.15)
class DroneManager(DirectObject.DirectObject):
    def __init__(self, base, droneList, delay):
        self.base = base
        # the actual dimensions of the bcs drone lab in meters
        # self.roomSize = Vec3(3.40, 4.56, 2.56)
        # confined dimensions because the room and drone coordinates dont match up yet.
        # Also, flying near the windows/close to walls/too high often makes the llighthouse positioning system loose track
        self.roomSize = Vec3(1.5, 2.5, 1.7)
        self.initDrones(droneList)
        self.initUI()

        self.currentFormation = 0
        self.isRotating = False

        self.currentTimeslot = 0

        self.timeslotLengthMilli = delay

    def initDrones(self, droneList):
        """Initializes the drones defined in droneList."""
        self.isStarted = False
        self.isConnected = False
        self.drones = []  # this is the list of all drones
        self.currentDronePos = [
        ]  # this is the list of the most recent position that was sent by each drone

        if droneList == []:
            print("No drones to spawn")
        else:
            for i in range(0, len(droneList)):
                position = droneList[i][0]
                uri = droneList[i][1]
                self.drones.append(Drone(self, position, uri=uri))

        self.base.taskMgr.add(self.updateDronesTask, "UpdateDrones")
        self.base.taskMgr.add(self.updateTimeslotTask, "UpdateTimeslot")

    def updateDronesTask(self, task):
        """Run the update methods of all drones."""
        for drone in self.drones:
            drone.update()
        return task.cont

    def updateTimeslotTask(self, task):
        timeslotAmount = 2
        task.delayTime = self.timeslotLengthMilli / 1000

        self.currentTimeslot += 1
        if self.currentTimeslot >= timeslotAmount:
            self.currentTimeslot = 0

        for drone in self.drones:
            drone.updateSentPosition(self.currentTimeslot)

        return task.again

    def initUI(self):
        # initialize drone control panel
        buttonSize = (-4, 4, -.2, .8)
        buttonDistance = 0.15

        entrySize = (0, 2, -.2, .8)

        # frame = DirectFrame(frameColor=(.2, .2, .2, 1), frameSize=(-.5, .5, -.7, .15), pos=(-.9, 0, -.6), scale=.5)
        frame = DirectFrame(frameColor=(.2, .2, .2, 1),
                            frameSize=(-.5, .5, -.7, .15),
                            pos=(-.9, 0, -.4),
                            scale=.5)

        button = DirectButton(text="Start",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.startLandAll)
        button["extraArgs"] = [button]
        button.reparentTo(frame)

        button = DirectButton(text="Random Target",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.setRandomTargets)
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -1 * buttonDistance))

        button = DirectButton(text="Stop",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.stopAll)
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -2 * buttonDistance))

        button = DirectButton(text="Return",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.returnToWaitingPosition)
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -3 * buttonDistance))

        button = DirectButton(text="Connect",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.toggleConnections)
        button["extraArgs"] = [button]
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -4 * buttonDistance))

        button = DirectButton(text="Rotate",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.toggleRotation)
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -5 * buttonDistance))

        button = DirectButton(text="Move",
                              scale=.1,
                              frameSize=buttonSize,
                              command=self.moveFormation)
        button.reparentTo(frame)
        button.setPos(Vec3(0, 0, -6 * buttonDistance))

        self.moveX = DirectEntry(text="",
                                 initialText="0",
                                 scale=.1,
                                 frameSize=entrySize)
        self.moveX.reparentTo(frame)
        self.moveX.setPos(Vec3(0.5, 0, -6 * buttonDistance))

        self.moveY = DirectEntry(text="",
                                 initialText="0",
                                 scale=.1,
                                 frameSize=entrySize)
        self.moveY.reparentTo(frame)
        self.moveY.setPos(Vec3(0.75, 0, -6 * buttonDistance))

        self.moveZ = DirectEntry(text="",
                                 initialText="0",
                                 scale=.1,
                                 frameSize=entrySize)
        self.moveZ.reparentTo(frame)
        self.moveZ.setPos(Vec3(1, 0, -6 * buttonDistance))

        self.rotSpeed = DirectEntry(text="",
                                    initialText="3",
                                    scale=.1,
                                    frameSize=entrySize)
        self.rotSpeed.reparentTo(frame)
        self.rotSpeed.setPos(Vec3(0.5, 0, -5 * buttonDistance))

        # initialize an UI element with all available formations
        loadFormationSelectionFrame(self)

    def startLandAll(self, button):
        if not self.isStarted:
            self.isStarted = True
            button["text"] = "Land"
            print("starting all")
            for drone in self.drones:
                pos = drone.getPos()
                drone.setTarget(target=Vec3(pos[0], pos[1], 1))
        else:
            self.isStarted = False
            button["text"] = "Start"
            print("landing all")
            for drone in self.drones:
                pos = drone.getPos()
                drone.setTarget(target=Vec3(pos[0], pos[1], 0))

    def returnToWaitingPosition(self):
        """Makes all drones hover above their starting position. Useful to make the drones land just where they started."""
        if not self.isStarted:
            print("can't return to waiting position, drones are not started")
            return
        print("returning to waiting positions")
        for drone in self.drones:
            drone.setTarget(drone.waitingPosition)

    def setRandomTargets(self):
        """Set random targets for all drones."""
        if not self.isStarted:
            print("can't set random targets, drones are not started")
            return
        print("setting random targets")
        for drone in self.drones:
            drone.setRandomTarget()

    def stopAll(self):
        """Stops all drones and makes them hover where they are."""
        if not self.isStarted:
            print("can't stop drones, drones are not started")
            return
        print("stopping drones")
        for drone in self.drones:
            drone.setTarget(target=drone.getPos())

    def toggleConnections(self, button):
        """Connects/Disconnects the virtual drones to/from the real drones."""
        # connect drones
        if not self.isConnected:
            self.isConnected = True
            button["text"] = "Disconnect"
            print("initializing drivers")
            cflib.crtp.init_drivers(enable_debug_driver=False)
            print("connecting drones")
            for drone in self.drones:
                drone.connect()
            # time.sleep(5)  # wait a moment so that the position estimator reports a consisten position
        # disconnect drones
        else:
            self.isConnected = False
            button["text"] = "Connect"
            print("disconnecting drones")
            for drone in self.drones:
                if drone.isConnected:
                    drone.disconnect()

    def applyFormation(self, formation):
        """Applies the supplied formation to the drones."""
        if not self.isStarted:
            print("Can't apply formation, drones are not started")
            return

        # name = formation[0]
        dronePositions = formation[1]
        requiredDrones = len(dronePositions)

        availableDrones = self.drones.__len__()
        maxNumber = availableDrones
        if requiredDrones > availableDrones:
            print(
                "The formation contains {0} points but there are only {1} available drones"
                .format(requiredDrones, availableDrones))

        if requiredDrones < availableDrones:
            print(
                "The formation contains {0} points but there are {1} available drones, some drones will remain stationary"
                .format(requiredDrones, availableDrones))
            maxNumber = requiredDrones

        # print("applying {} formation".format(formation[0]))
        for i in range(0, maxNumber):
            self.drones[i].setNewRandVec()
            self.drones[i].setTarget(
                Vec3(dronePositions[i, 0], dronePositions[i, 1],
                     dronePositions[i, 2]))

        self.currentFormation = formation

    def moveFormation(self):
        if (self.currentFormation == 0):
            return
        newFormation = self.currentFormation
        newFormation[1] += [
            float(self.moveX.get()),
            float(self.moveY.get()),
            float(self.moveZ.get())
        ]
        self.applyFormation(newFormation)

    def toggleRotation(self):
        if (self.currentFormation == 0):
            return
        if not self.isRotating:
            self.isRotating = True
            self.base.taskMgr.doMethodLater(0, self.rotateFormationTask,
                                            "RotateDrones")
        else:
            self.isRotating = False
            self.base.taskMgr.remove("RotateDrones")

    def rotateFormationTask(self, task):
        task.delayTime = 0.1
        newFormation = self.currentFormation
        speed = 2
        try:
            speed = float(self.rotSpeed.get())
        except:
            speed = 2
        r = R.from_euler('xyz', [0, 0, speed], degrees=True)
        newFormation[1] = r.apply(newFormation[1])
        self.applyFormation(newFormation)
        return task.again

    def getRandomRoomCoordinate(self) -> Vec3:
        """Returns random 3D coordinates withing the confines of the room."""
        newX = random.uniform(-self.roomSize.x / 2, self.roomSize.x / 2)
        newY = random.uniform(-self.roomSize.y / 2, self.roomSize.y / 2)
        newZ = random.uniform(0 + 0.3, self.roomSize.z)
        return Vec3(newX, newY, newZ)

    def getAllPositions(self):
        """Returns a list of the positions of all drones. Usefull when recording their paths for later."""
        lst = []
        for drone in self.drones:
            pos = drone.getPos()
            lst.append([pos.x, pos.y, pos.z])
        return lst

    def getAllVelocities(self):
        """Returns a list of the velocities of all drones. Usefull when recording their paths for later."""
        lst = []
        for drone in self.drones:
            vel = drone.getVel()
            lst.append([vel.x, vel.y, vel.z])
        return lst
class FrameAutenticacao(object):
    '''
    FrameAutenticacao
    '''

    def __init__(self, parent = None, **kw):
        self.__qtd_conexao = 0        
        
        self.__frmAuth = DirectFrame( frameColor = (0,0,0,.3),
                                      frameSize  = (-.5,.5,0,0.45), 
                                      pos        = (0,0,-.1),                                      
                                      enableEdit = 1 )        
        
        self.__lblLogin = DirectLabel( text       = "Login: "******"Senha: ",
                                       scale      = 0.05,
                                       pos        = (-0.3, 0, 0.2),
                                       frameColor = (0,0,0,0),
                                       text_fg    = (1,1,1,1) )        
        
        self.__etySenha = DirectEntry( scale          = 0.05,
                                       width          = 12,                                       
                                       pos            = (-.2, 0, 0.2),
                                       cursorKeys     = 1, 
                                       obscured       = 1,                                    
                                       focusInCommand = self.__command_clear_senha)
        
        
        self.__btnEntrar = DirectButton( frameColor    = (0,0,0,1),
                                         text          = "Entrar",
                                         scale         = 0.06,                                                                                
                                         pos           = (0.3, 0, 0.1),
                                         text_fg       = (1,1,1,1),                                                                                   
                                         rolloverSound = None,
                                         clickSound    = None,
                                         command       = self.__command_entrar)
        
        self.__lblLogin.reparentTo(self.__frmAuth)
        self.__etyLogin.reparentTo(self.__frmAuth)
        self.__lblSenha.reparentTo(self.__frmAuth)
        self.__etySenha.reparentTo(self.__frmAuth)        
        self.__btnEntrar.reparentTo(self.__frmAuth)
        
        self.__etyLogin.set("viner")
        self.__etySenha.set("viner")
    
    def __command_clear_senha(self):
        self.__etySenha.set("")
    
    def __command_entrar(self, txt = None):                
        login = self.__etyLogin.get()
        senha = self.__etySenha.get()
                
        valido = True
        
        if login == "":
            addMensagem("O campo Login e obrigatorio !", COR_BRANCO)
            valido = False
            
        if senha == "":
            addMensagem("O campo Senha e obrigatorio !", COR_BRANCO)
            valido = False
        
        if valido:
            self.__btnEntrar["state"] = DGG.DISABLED
                        
            taskMgr.add( self.__task_conectar_servidor,
                         'ConectarServidor',
                          extraArgs=[login,senha],
                          appendTask=True)                            
            
            #inicia_nova_thread(1, 0, "Conectar Servidor", self.__conectar_servidor, login, senha)
                        
    def __task_conectar_servidor(self, login, senha, task):            
                
        if self.__qtd_conexao < TENTATIVAS:                                        
            
            if vinerOnline.flg_conectado == vinerOnline.ERROLOGIN:
                vinerOnline.flg_conectado = vinerOnline.DESCONECT
                
                self.__btnEntrar["state"] = DGG.NORMAL
                self.__qtd_conexao        = 0
                                
                addMensagem('Login ou senha invalido', COR_VERMELHO)
                
                self.__etyLogin.setFocus()
                                
            elif vinerOnline.flg_conectado == vinerOnline.CONECTADO:
                #addMensagem("Conectado 12 !!!")
                #self.destroy()
                pass
                
            else:
                vinerOnline.conectar_servidor(login, senha)
                self.__qtd_conexao += 1
                
                taskMgr.doMethodLater( INTERVALO_TENTATIVAS,
                                   self.__task_conectar_servidor, 
                                   'ConectarServidorLater',
                                   extraArgs = [login,senha],
                                   appendTask = True)
                
                msg = "Tentativa %s/5 -  Conectando..." % (self.__qtd_conexao)
                addMensagem(msg, COR_BRANCO)                                            
                
        else:
            vinerOnline.flg_conectado = vinerOnline.DESCONECT
            self.__btnEntrar["state"] = DGG.NORMAL
            self.__qtd_conexao        = 0            
            addMensagem("Servidor nao encontrado", COR_VERMELHO)                        
            
        
        return task.done
        
    def destroy(self):        
        self.__frmAuth.destroy()
        
        del self.__lblLogin
        del self.__etyLogin
        del self.__lblSenha
        del self.__etySenha        
        del self.__btnEntrar
        del self.__frmAuth
            
Beispiel #9
0
class EntyButtonFrame(object):
    def __init__(self,
                 parent=None,
                 scale=.05,
                 limitText=100,
                 frameSize=(0, 1.3, 0.11, .2),
                 pos=(0, 0, .1)):

        self.__show = True

        self.frmMsg = DirectFrame(parent=parent,
                                  frameColor=(0, 0, 0, .5),
                                  frameSize=frameSize,
                                  pos=pos,
                                  enableEdit=1)

        self.etyMsg = DirectEntry(frameColor=(1, 1, 1, .5),
                                  scale=scale,
                                  width=22,
                                  numLines=1,
                                  pos=(.02, 0, .14),
                                  cursorKeys=1,
                                  focus=1,
                                  command=self.__command_enviar_msg,
                                  focusInCommand=self.__command_clear_msg)

        self.btnMsgr = DirectButton(frameColor=(0, 0, 0, 1),
                                    text="Enviar",
                                    scale=scale,
                                    pos=(1.21, 0, .14),
                                    text_fg=(1, 1, 1, 1),
                                    rolloverSound=None,
                                    clickSound=None,
                                    command=self.__command_enviar_msg)

        self.etyMsg.reparentTo(self.frmMsg)
        self.btnMsgr.reparentTo(self.frmMsg)

        self.hide()

    def hide(self):
        self.frmMsg.hide()
        self.__show = False

    def show(self):
        self.frmMsg.show()
        self.__show = True

        self.etyMsg.setFocus()

    def isShowing(self):
        return self.__show

    def __command_clear_msg(self):
        self.etyMsg.set("")

    def __command_enviar_msg(self, txt=None):

        msg = self.etyMsg.get()

        if msg != "":
            vinerOnline.envia_pacote_server(0, ACAO_SERVER_falar, [msg])
            self.__command_clear_msg()
            self.etyMsg.setFocus()
        return False