def terminarPartida(self): # Solicita al usuario un nombre para la tabla de puntuaciones self.entrada = DirectEntry(width = 15, numLines = 1, scale = 0.07, cursorKeys = 1, frameSize = (0, 15, 0, 1), command = self.almacenarPuntuacion, pos = (-0.3, 0, 0.1), focus = True, text_pos = (0.2, 0.2)) self.puntos = self.ship.puntos self.ship.ship.detachNode() self.ship.ship.remove() taskMgr.remove("Mover Nave") taskMgr.remove("Generar Enemigos") taskMgr.remove("Comprobar Impactos") taskMgr.remove("Actualizar Puntuacion") taskMgr.remove("Explosionar*") self.mostrarFinPartida() # Libera los recursos de la partida que ha terminado self.ship.eliminarObjetos() del self.ship del self.menuGraphics del self.menu self.marcadorNP.detachNode() self.marcadorNP.remove() self.barraEnergia.destroy() del self.marcador del self.barraEnergia
def __init__(self, placeholder, pos, on_enter, focus=False, sort_order=0): """ Object of a simple entry field @param placeholder: text to appear in textbox automatically @type placeholder: string @param pos: where to place the textbox @type pos: (float, float, float) @param on_enter: function to call upon them submitting a response @type on_enter: function @param focus: Should the entry auto-focus? @type focus: bool @param sort_order: Where should Entry display? (Alert is at 1000) @type sort_order: int """ DirectObject.__init__(self) self.accept('mouse1', self.click_out) self.placeholder = placeholder self.on_enter = on_enter self.entry = DirectEntry(initialText=self.placeholder, scale=0.05, focus=focus, focusOutCommand=self.focus_out, focusInCommand=self.focus_in, pos=pos, sortOrder=sort_order)
def __init__(self, _client): # Ref self.client = _client # create a host button self.btnConnect = DirectButton( # Scale and position scale=0.25, pos=(0, 0, 0), # Text text="Connect", # Frame # Functionality command=self.connect) # create the IP input field self.txtIP = DirectEntry( # scale and position pos=(0, 0, -.35), scale=0.25, width=9, # Text text="", text_align=TextNode.ACenter, initialText="127.0.0.1", numLines=1, # Functionality command=self.connect, focusInCommand=self.clearText) self.hide()
def enterSysMsgSection(self): geom = CIGlobals.getDefaultBtnGeom() self.infoLbl = OnscreenText( text="Inform all online players about something.", pos=(0, 0.45)) self.msgEntry = DirectEntry( initialText="System Message...", scale=0.055, width=15, numLines=4, command=self.sendSystemMessageCommand, focusInCommand=base.localAvatar.chatInput.disableKeyboardShortcuts, focusOutCommand=base.localAvatar.chatInput.enableKeyboardShortcuts, pos=(-0.4, 0, 0)) self.sendBtn = DirectButton( geom=geom, text_scale=0.04, relief=None, scale=1.0, text="Send", pos=(0, 0, -0.35), text_pos=(0, -0.01), command=self.sendSystemMessageCommand, ) self.cancelBtn = DirectButton(geom=geom, text_scale=0.04, relief=None, scale=1.0, text="Cancel", pos=(-0.45, 0.15, -0.55), text_pos=(0, -0.01), command=self.fsm.request, extraArgs=['basePage'])
def setup(self, label, range, value, orientation, *args, **kwargs): def updateField(widget, field, value): widget[field] = value def finalCommand(): val = self.slider['value'] updateField(self.slider, 'text', '%1.3f' % val) self.slider = DirectSlider(parent=self, relief=DGG.FLAT, range=range, value=value, orientation=orientation, scale=0.25, thumb_relief=DGG.FLAT, thumb_color=(0, 1, 1, 1), pos=(0, 0, 0), text='0.0', text_scale=0.20000000000000001, text_pos=(0, 0.10000000000000001, 0)) updateField(self.slider, 'command', finalCommand) width = 3 if orientation == DGG.HORIZONTAL: pos = (-0.27500000000000002 - width * 0.050000000000000003, 0, -0.02) else: pos = (-0.025000000000000001 * width, 0, -0.34999999999999998) self.min = DirectEntry(parent=self, initialText=` float(self.slider['range'][0]) `, scale=0.050000000000000003, width=width, pos=pos) updateField( self.min, 'command', lambda x: updateField(self.slider, 'range', (float(x), self.slider['range'][1]))) if orientation == DGG.HORIZONTAL: pos = (0.27500000000000002, 0, -0.02) else: pos = (-0.025000000000000001 * width, 0, 0.29999999999999999) self.max = DirectEntry(parent=self, initialText=` float(self.slider['range'][1]) `, scale=0.050000000000000003, width=width, pos=pos) updateField( self.max, 'command', lambda x: updateField(self.slider, 'range', (self.slider['range'][0], float(x)))) self.label = DirectLabel( parent=self, relief=None, text=label, text_scale=0.050000000000000003, text_pos=(0.029999999999999999 - 0.39500000000000002, 0.34999999999999998 - 0.23999999999999999, 0), text_align=TextNode.ALeft)
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 loginScreen(self, statusText): # creates a basic login screen that asks for a username/password boxloc = Vec3(0.0, 0.0, 0.0) # all items in the login form will have a position relative to this # this makes it easier to shift the entire form around once we have # some graphics to display with it without having to change the # positioning of every form element # p is the position of the form element relative to the boxloc # coordinates set above it is changed for every form element p = boxloc + Vec3(-0.22, 0.09, 0.0) self.usernameText = OnscreenText(text = "Username:"******"Username: "******"", pos = p, scale=.04, initialText = self.username, numLines = 1) # Username textbox where you type in your username p = boxloc + Vec3(0.4, 0.0, 0.09) self.usernameStoreBox = DirectCheckButton(text = "Save Username?", pos = p, scale = .04, indicatorValue = self.storeUsername) # Toggle to save/not save your username p = boxloc + Vec3(-0.22, 0.0, 0.0) self.passwordText = OnscreenText(text = "Password:"******"Password: "******"", pos = p, scale = .04, initialText = self.password, numLines = 1, obscured = 1) # Password textbox where you type in your password # Note - obscured = 1 denotes that all text entered will be replaced # with a * like a standard password box p = boxloc + Vec3(0.4, 0.0, 0.0) self.passwordStoreBox = DirectCheckButton(text = "Save Password?", pos = p, scale = .04, indicatorValue = self.storePassword) # Toggle to save/not save your username p = boxloc + Vec3(0, 0, -0.090) self.loginButton = DirectButton(text = "Login", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.attemptLogin) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0.95, 0, -0.9) self.createAccButton = DirectButton(text = "Create Account", scale = 0.050, pos = p, relief = DGG.GROOVE, command = self.attemptCreateAccount) # Made a quick button for adding accounts. Its fugly p = boxloc + Vec3(1.20, 0, -0.9) self.quitButton = DirectButton(text = "Quit", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.showbase.quit) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0, -0.4, 0) self.statusText = OnscreenText(text = statusText, pos = p, scale = 0.043, fg = (1, 0.5, 0, 1), align = TextNode.ACenter)
def __init__(self, parent=render2d, pos=(0.0, 0.0, 0.0), scale=1.0, value=0, callback=None, increment=0.01): DirectFrame.__init__(self, parent, pos=pos, scale=1.0) self.increment = increment self.value = Decimal(value) self.callback = callback self.display = DirectEntry(parent=self, relief=None, initialText="%.2f" % value, scale=1, text_scale=0.055, text_align=TextNode.ACenter, pos=(0.0, 0.0, 0.0), frameColor=(0.8, 0.8, 0.5, 1), borderWidth=(0.1, 0.1), numLines=1, width=6, frameSize=(-0.1, 0.1, -0.1, 0.1), cursorKeys=1) self.display.bind(DGG.TYPE, self.typeCallback) # This allows the text box to handle mouse events self.display.guiItem.setActive(True) gui = loader.loadModel('phase_3/models/gui/tt_m_gui_mat_mainGui.bam') image = (gui.find('**/tt_t_gui_mat_shuffleArrowUp'), gui.find('**/tt_t_gui_mat_shuffleArrowDown'), gui.find('**/tt_t_gui_mat_shuffleArrowUp'), gui.find('**/tt_t_gui_mat_shuffleArrowDisabled')) self.upArrow = DirectButton(self, relief=None, image=image, image_scale=(0.6, 0.6, 0.6), image1_scale=(0.7, 0.7, 0.7), image2_scale=(0.7, 0.7, 0.7), pos=(0.0, 0.0, 0.08), command=self.__handleUpClicked) self.upArrow.setR(90) self.downArrow = DirectButton(self, relief=None, image=image, image_scale=(0.6, 0.6, 0.6), image1_scale=(0.7, 0.7, 0.7), image2_scale=(0.7, 0.7, 0.7), pos=(0.0, 0.0, -0.05), command=self.__handleDownClicked) self.downArrow.setR(-90)
def __init__(self, parent: DirectFrame, text: str, value: float, slider_edit_callback: Callable[['ColourChannel', float], None], entry_edit_callback: Callable[['ColourChannel', float], None], mouse1_press_callbacks: List[Callable[[], None]]): self.__frame = DirectFrame(parent=parent) self.__slider_edit_callback = slider_edit_callback self.__entry_edit_callback = entry_edit_callback self.__label = DirectLabel(parent=self.__frame, text=text, text_fg=WHITE, text_bg=WINDOW_BG_COLOUR, pos=(-0.5, 0.0, 0.0), scale=(0.1, 1.0, 0.1)) self.__slider = DirectSlider(parent=self.__frame, orientation=DGG.HORIZONTAL, borderWidth=(0.0, 0.0), frameColor=WIDGET_BG_COLOUR, frameSize=(-1.0, 1.0, -0.4, 0.4), thumb_frameSize=(-0.075, 0.075, -0.2, 0.2), value=value, pos=(0.05, 0.0, 0.0255), scale=(0.45, 1.0, 0.5)) self.__entry_hovered = False mouse1_press_callbacks.append(self.__entry_mouse_click_callback) self.__entry = DirectEntry(parent=self.__frame, frameColor=WIDGET_BG_COLOUR, text_fg=WHITE, initialText=str(value), scale=0.1, width=3, suppressKeys=True, pos=(0.55, 0.0, -0.01105)) self.__entry.bind(DGG.EXIT, self.__entry_exit_callback) self.__entry.bind(DGG.ENTER, self.__entry_enter_callback) self.__entry.bind(DGG.B1PRESS, self.__entry_mouse_click_callback) self.accept("mouse1", self.__entry_mouse_click_callback) self.__disable_frame_overlay = DirectButton(parent=self.__frame, frameColor=TRANSPARENT, borderWidth=(0.0, 0.0), frameSize=(-0.6, 0.9, -0.2, 0.2), suppressMouse=True) self.__disable_frame_overlay.hide() self.__enabled = True self.__set_callbacks()
def open_query(self, owner): self.owner = owner bg_color = LColor(*self.color) bg_color[3] = 0.2 scale3 = LVector3(self.scale[0], 1.0, self.scale[1]) self.background = DirectFrame( frameColor=bg_color, frameSize=(-1 / self.scale[0], 1.0 / self.scale[0], 0.15 + self.scale[1] * self.text_size, 0.0), parent=base.a2dBottomLeft) self.prefix = OnscreenText( text=_("Target name:"), font=self.font, fg=self.color, align=TextNode.ALeft, parent=base.a2dBottomLeft, scale=tuple(self.scale * self.text_size), pos=(0, .15), ) bounds = self.prefix.getTightBounds() length = bounds[1][0] - bounds[0][ 0] + self.scale[0] * self.text_size / 2 self.query = DirectEntry(text="", text_fg=self.color, scale=tuple(scale3 * self.text_size), command=self.do_query, parent=base.a2dBottomLeft, frameColor=(0, 0, 0, 0), pos=(length, 0, .15), initialText="", numLines=1, width=200, entryFont=self.font, focus=1, suppressKeys=1) self.query.bind("press-escape-", self.escape) self.query.bind("press-tab-", self.select) self.query.accept(self.query.guiItem.getTypeEvent(), self.completion) self.query.accept(self.query.guiItem.getEraseEvent(), self.completion) pos = self.prefix.getPos() bounds = self.query.getBounds() llz = bounds[2] / self.text_size self.suggestions = OnscreenText( text="", font=self.font, fg=self.color, align=TextNode.ALeft, mayChange=True, parent=base.a2dBottomLeft, scale=tuple(self.scale * self.suggestions_text_size), pos=(pos[0], pos[1] + llz), )
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)
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
def _drawControls(self, dialogueFrame): """ Draw Helper that draws client settings controls """ iTopMrgn = JOPTS_CONTROL_TOP_MARGIN spacing = JOPTS_CONTROL_SPACING height = JOPTS_CONTROL_HEIGHT width = dialogueFrame.getWidth() # Create containers for UI: ipFrame = DirectFrame(parent=dialogueFrame, pos=(width / 2, 0, -iTopMrgn - spacing), frameSize=(-width / 2, width / 2, -height / 2, height / 2), frameTexture=UI_WINDOW) #nameFrame = DirectFrame(parent=dialogueFrame, # pos=(width/2, 0, -iTopMrgn - spacing * 2), # frameSize=(-width/2, width/2, -height/2, # height/2)) # Create the UI: ctrlWidth = ipFrame.getWidth() * (1 / 3) ctrlFontSize = (0.15, 0.15) self._ipAddressEntry = DirectEntry(parent=ipFrame, pos=(ctrlWidth / 2 - ctrlWidth * 1, 0, 0), frameSize=(0, ctrlWidth * 2, -height / 2, height / 2), frameColor=(0, 0, 0, 0), text_font=self._font, text_scale=ctrlFontSize, text_pos=PIERCEROMAN_OFFSET_MC, initialText=DEFAULT_IP_ADDRESS, width=8, cursorKeys=1, numLines=1) ipLabel = DirectLabel(parent=ipFrame, pos=(ctrlWidth - ctrlWidth * 2, 0, 0), frameSize=(-ctrlWidth / 2, ctrlWidth / 2, -height / 2, height / 2), text="Host IP:", text_font=self._font, text_scale=ctrlFontSize, text_pos=PIERCEROMAN_OFFSET_MC, frameTexture=(IMG_GRADIENT_1)) """self._userNameEntry = DirectEntry(parent=nameFrame, pos=(ctrlWidth/2-ctrlWidth*1, 0, 0), frameSize=(0, ctrlWidth*2, -height/2, height/2), text_font=self._font, text_scale=ctrlFontSize, text_pos=PIERCEROMAN_OFFSET_MC, width=8, cursorKeys=1, numLines=1)""" """
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 _draw(self): winWidth = base.getAspectRatio() * 2 winHeight = 2 # Draw container: frameHeight = winHeight * NPKR_HEIGHT_PERCENTAGE frameWidth = winWidth * NPKR_WIDTH_PERCENTAGE cFCenterY = -winHeight / 2 + frameHeight / 2 self._rootFrame = DirectFrame( pos=(0, 0, cFCenterY), frameSize=(-frameWidth / 2, frameWidth / 2, -frameHeight / 2, frameHeight / 2), frameTexture=IMG_GRADIENT_1) self._rootFrame.setTransparency(TransparencyAttrib.MAlpha) # Draw Name Entry: entryWidth = self._rootFrame.getWidth() * NPKR_ENTRY_WIDTH_PERCENTAGE entryHeight = self._rootFrame.getHeight() entryCX = -(self._rootFrame.getWidth() - entryWidth) / 2 self._nameEntry = DirectEntry( parent=self._rootFrame, pos=(entryCX, 0, 0), frameSize=(-entryWidth / 2, entryWidth / 2, -entryHeight / 2, entryHeight / 2), frameColor=(0.25, 0.25, 0.25, 1), text_align=TextNode.ACenter, text_font=self._font, text_scale=NPKR_ENTRY_FONT_SIZE, text_pos=NPKR_ENTRY_FONT_OFFSET, initialText=NPKR_ENTRY_INITIAL_TEXT, numLines=1, focusOutCommand=self._syncName, focusInCommand=self._checkPlaceholderText, command=self._syncName, frameTexture=UI_WINDOW) # Draw Confirm Button: confirmWidth = self._rootFrame.getWidth()\ * (1-NPKR_ENTRY_WIDTH_PERCENTAGE) confirmHeight = self._rootFrame.getHeight() confirmCX = (self._rootFrame.getWidth() - confirmWidth) / 2 self._confirmButton = DirectButton( parent=self._rootFrame, pos=(confirmCX, 0, 0), frameSize=(-confirmWidth / 2, confirmWidth / 2, -confirmHeight / 2, confirmHeight / 2), command=self._onConfirmPressed, text_font=self._font, text_scale=NPKR_BUTTON_FONT_SIZE, text_pos=NPKR_BUTTON_FONT_OFFSET, text="Create Character", borderWidth=NPKR_BUTTON_BORDER_WIDTH)
def setMyEntry(self): self.myEntry = DirectEntry(text='', scale=self.scale, command=self.onCommand, numLines=self.lines, width=self.width, pos=(self.x, self.y, self.z), entryFont=self.myFont, focusInCommand=self.onFocus, focusOutCommand=self.onOutFocus, frameColor=(0, 0, 0, .7), text_fg=(1, 1, 1, 1), initialText=self.initial, clickSound=self.mode.game.app.beep01Sound, rolloverSound=None)
def bld_page(self): menu_gui = self.mdt.menu.gui menu_args = self.mdt.menu.gui.menu_args txt = OnscreenText(text=_('Client'), pos=(0, .4), **menu_gui.menu_args.text_args) widgets = [txt] self.ent = DirectEntry( scale=.12, pos=(-.68, 1, .2), entryFont=menu_args.font, width=12, frameColor=menu_args.btn_color, initialText=_('insert the server address')) self.ent.onscreenText['fg'] = menu_args.text_fg btn = DirectButton(text=_('Connect'), pos=(0, 1, -.2), command=self.connect, **menu_gui.menu_args.btn_args) widgets += [self.ent, btn] map(self.add_widget, widgets) ThanksPageGui.bld_page(self)
def __init__(self): self.instructions = OnscreenText(text='Type your name', scale=0.1, fg=(1, 1, 1, 1), pos=(0, 0.8, 0.8), shadow=(0, 0, 0, 1)) self.nameEntry = DirectEntry(focus=1, initialText='Toon', width=10, scale=0.1, pos=(-0.5, 0.3, 0.3), command=self.confirmNameAndContinue) self.confirmBtn = DirectButton(text='Confirm', scale=0.1, pos=(0, 0.1, 0.1), command=self.confirmNameAndContinue, extraArgs=[self.nameEntry.get()])
def __init__(self, manager, xml): sys.stdout = PseudoFile(self.writeOut) sys.stderr = PseudoFile(self.writeErr) tpErr = TextProperties() tpErr.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr) self.manager = manager font = loader.loadFont("cmss12") self.frame = DirectFrame(parent=base.a2dTopCenter, text_align=TextNode.ALeft, text_pos=(-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale=0.05, text_fg=(1, 1, 1, 1), frameSize=(-2.0, 2.0, -0.5, 0.0), frameColor=(0, 0, 0, 0.5), text='', text_font=font) self.entry = DirectEntry(parent=base.a2dTopLeft, command=self.command, scale=0.05, width=1000.0, pos=(-0.02, 0, -0.48), relief=None, text_pos=(1.5, 0, 0), text_fg=(1, 1, 0.5, 1), rolloverSound=None, clickSound=None, text_font=font) self.otext = OnscreenText(parent=self.entry, scale=1, align=TextNode.ALeft, pos=(1, 0, 0), fg=(1, 1, 0.5, 1), text=':', font=font) self.lines = [''] * 9 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False
class ClientPageGui(ThanksPageGui): def __init__(self, mdt, menu): self.ent = None ThanksPageGui.__init__(self, mdt, menu) def build_page(self): menu_gui = self.menu.gui menu_args = self.menu.gui.menu_args txt = OnscreenText(text=_('Client'), pos=(0, .4), **menu_gui.text_args) widgets = [txt] self.ent = DirectEntry(scale=.12, pos=(-.68, 1, .2), entryFont=menu_args.font, width=12, frameColor=menu_args.btn_color, initialText=_('insert the server address')) self.ent.onscreenText['fg'] = menu_args.text_fg btn = DirectButton(text=_('Connect'), pos=(0, 1, -.2), command=self.connect, **menu_gui.btn_args) widgets += [self.ent, btn] map(self.add_widget, widgets) ThanksPageGui.build_page(self) def connect(self): menu_gui = self.menu.gui try: eng.log(self.ent.get()) Client().start(self.mdt.event.process_msg, self.ent.get()) menu_args = self.menu.gui.menu_args self.add_widget( OnscreenText(text=_('Waiting for the server'), scale=.12, pos=(0, -.5), font=menu_gui.font, fg=menu_args.text_fg)) except ClientError: txt = OnscreenText(_('Error'), pos=(0, -.05), fg=(1, 0, 0, 1), scale=.16, font=menu_gui.menu_args.font) eng.do_later(5, txt.destroy)
class Entry(DirectObject): def __init__(self, placeholder, pos, on_enter, focus=False, sort_order=0): """ Object of a simple entry field @param placeholder: text to appear in textbox automatically @type placeholder: string @param pos: where to place the textbox @type pos: (float, float, float) @param on_enter: function to call upon them submitting a response @type on_enter: function @param focus: Should the entry auto-focus? @type focus: bool @param sort_order: Where should Entry display? (Alert is at 1000) @type sort_order: int """ DirectObject.__init__(self) self.accept('mouse1', self.click_out) self.placeholder = placeholder self.on_enter = on_enter self.entry = DirectEntry(initialText=self.placeholder, scale=0.05, focus=focus, focusOutCommand=self.focus_out, focusInCommand=self.focus_in, pos=pos, sortOrder=sort_order) def focus_out(self): if self.entry.get() == "": self.entry.enterText(self.placeholder) else: # they typed Something. # TODO validate self.on_enter(self.entry.get()) def focus_in(self): self.entry.set("") def click_out(self): self.entry.setFocus() def destroy(self): self.entry.destroy() self.ignoreAll()
class ThiefHud(GameHud): def __init__(self, clientState): super().__init__(clientState) self.entryLabel = self.label(text='', mayChange=True) self.entry = DirectEntry( initialText='Type card name...', scale=0.05, focus=1, command=self.useThiefAbility, focusInCommand=lambda: self.entry.enterText('')) self.entry.hide() self.thiefAbilityButton = self.button( text="Faction Ability", scale=1, pos=(0, 0, -1), parent=self.endTurnButton, command=self.onThiefAbilityButton) def useThiefAbility(self, cardname): toDiscard = self.toDiscard.getPythonTag('card') toSteal = self.toSteal.getPythonTag('card') base.clientActions.useThiefAbility(toDiscard, toSteal, cardname) base.audioMaster.thiefAbilitySound.play() base.mouseHandler.targeting = False self.entry.hide() def onThiefAbilityButton(self): def chooseTarget(target): if target is None: base.mouseHandler.targeting = False showCard(self.toDiscard) return elif target.getPythonTag('zone') is not base.enemy.facedowns: return self.toSteal = target self.entry.show() def chooseDiscard(target): if target is None: base.mouseHandler.targeting = False return elif target.getPythonTag('zone') is not base.player.hand: return self.toDiscard = target hideCard(target) base.mouseHandler.startTargeting("Choose a target.", chooseTarget) base.mouseHandler.startTargeting("Choose a card to discard.", chooseDiscard) def redraw(self): super().redraw() # TODO: kludge if hasattr(self, 'thiefAbilityButton'): self.thiefAbilityButton.show()
class connectGUI(): def __init__(self, _client): # Ref self.client = _client # create a host button self.btnConnect = DirectButton( # Scale and position scale=0.25, pos=(0, 0, 0), # Text text="Connect", # Frame # Functionality command=self.connect) # create the IP input field self.txtIP = DirectEntry( # scale and position pos=(0, 0, -.35), scale=0.25, width=9, # Text text="", text_align=TextNode.ACenter, initialText="127.0.0.1", numLines=1, # Functionality command=self.connect, focusInCommand=self.clearText) self.hide() def show(self): self.btnConnect.show() self.txtIP.show() def hide(self): self.btnConnect.hide() self.txtIP.hide() def clearText(self): """Function to clear the text that was previously entered in the IP input field""" self.txtIP.enterText("") #TODO: Do something with the ip def connect(self, ip=None): """Function which will be called by pressing the connect button or hit enter while the focus is on the inut field""" if ip == None: ip = self.txtIP.get(True) if ip != "": if self.client.connectionMgr.connectToServer(ip, 5001): gui = lobbyGUI(self.client) self.client.gui.hide() gui.show() else: return
def __init__(self): super().__init__() self.entryLabel = self.label(text='', mayChange=True) self.entry = DirectEntry( initialText='Type card name...', scale=0.05, focus=1, command=self.useThiefAbility, focusInCommand=lambda: self.entry.enterText('')) self.entry.hide() self.thiefAbilityButton = self.button( text="Faction Ability", scale=1, pos=(0, 0, -1), parent=self.endPhaseButton, command=self.onThiefAbilityButton)
def create_text_entry(self, frame, param): entry = DirectEntry(parent=frame, initialText=str(param.get_param()), numLines=1, width=10, command=self.do_update, extraArgs=[None, param], text_scale=self.font_size, text_align=TextNode.A_left, suppressKeys=1) widget = SizerWidget(entry) return widget
def add_entry(self, name='', text = "" , pos = (0, 0, 0), scale=1, command = None, initialText="", width = 15, numLines = 1, focus=1): """ docstring for add_entry """ if name == '': name = generate_hash(self) self[name] = DirectEntry(text = text, pos = pos, scale = scale, command = command, initialText = initialText, width = width, numLines = numLines, focus = focus) return self[name]
def makeTextBox(self, frame, text, invalid=False): colours = self.app.theme.colours if invalid: colour = colours.invalidServerEntry else: colour = colours.serverEntry result = DirectEntry( parent=frame, scale=0.04, width=12, pos=(-0.5, 0, 0), pad=(0.2, 0.1), text_fg=colour, frameColor=(1, 1, 1, 1), initialText=text, focusInCommand=self.textBoxEntered, focusInExtraArgs=[frame], focusOutCommand=self.textBoxExited, focusOutExtraArgs=[frame], ) result.entryInvalid = invalid return result
def createTextbox(parent=None, width=60, text='', pos=(0,1,0), scale=(0.1), focus=0): """docstring for createTextbox""" return DirectEntry(text = text, initialText=text, numLines=1, focus=focus, width=width, clickSound = None, rolloverSound = None, parent=parent, pos=pos, scale=scale, )
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()
class NamePicker: def __init__(self): self.instructions = OnscreenText(text="Type your name", scale=0.1, fg=(1,1,1,1), pos=(0, 0.8, 0.8), shadow=(0,0,0,1)) self.nameEntry = DirectEntry(focus=1, initialText="Toon", width=10, scale=0.1, pos=(-0.5, 0.3, 0.3), command=self.confirmNameAndContinue) self.confirmBtn = DirectButton(text="Confirm", scale=0.1, pos=(0, 0.1, 0.1), command=self.confirmNameAndContinue, extraArgs=[self.nameEntry.get()]) def confirmNameAndContinue(self, textEntered): try: self.badName_lbl.remove() del self.badName_lbl except: pass if self.nameEntry.get().isspace() or len(self.nameEntry.get()) <= 0: self.badName_lbl = OnscreenText(text=CIGlobals.InvalidName, scale=0.09, fg=(1,0,0,1), pos=(0, -0.1, -0.1), shadow=(0,0,0,1)) return else: self.instructions.remove() self.nameEntry.remove() self.confirmBtn.remove() try: self.badName_lbl.remove() except: pass messenger.send("nameConfirmed", [self.nameEntry.get()])
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)
def __init__(self, game): self.game = game self.lines = [] self.whisperTarget = None props = base.win.getProperties() ratio = float(props.getXSize()) / props.getYSize() self.frame = DirectFrame(frameColor=(0, 0, 0, 0), frameSize=(0, 1, 0, 1), pos=(-ratio, 0, -1)) self.text = OnscreenText( text="", pos=(0.01, 0.45), scale=0.05, fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.2), parent=self.frame, align=TextNode.ALeft, mayChange=True, ) self.entry = DirectEntry( parent=self.frame, text="", scale=0.05, pos=(0.01, 0, 0.02), initialText="", width=26, numLines=1 ) self.targetText = OnscreenText( text="", pos=(1.34, 0.025), scale=0.05, fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.4), parent=self.frame, align=TextNode.ALeft, mayChange=True, ) base.accept("t", self.startChatting) base.accept("shift-t", self.startChatting) base.accept("y", self.startWhispering) base.accept("shift-y", self.startWhispering) base.accept("arrow_up", lambda: self.changeTarget(1)) base.accept("shift-arrow_up", lambda: self.changeTarget(1)) base.accept("arrow_down", lambda: self.changeTarget(-1)) base.accept("shift-arrow_down", lambda: self.changeTarget(-1)) base.accept("enter", self.sendChat) base.accept("shift-enter", self.sendChat)
def __init__(self): sys.stdout = PseudoFile(self.writeOut) sys.stderr = PseudoFile(self.writeErr) tpErr = TextProperties() tpErr.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr) #font = loader.loadFont("cmss12") self.frame = DirectFrame(parent = base.a2dTopCenter, text_align = TextNode.ALeft, text_pos = (-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale = 0.05, text_fg = (1, 1, 1, 1), frameSize = (-2.0, 2.0, -0.5, 0.0), frameColor = (0, 0, 0, 0.5), text = '')#, text_font = font) self.entry = DirectEntry(parent = base.a2dTopLeft, command = self.command, scale = 0.05, width = 1000.0, pos = (-0.02, 0, -0.48), relief = None, text_pos = (1.5, 0, 0), text_fg = (1, 1, 0.5, 1), rolloverSound = None, clickSound = None)#, text_font = font) self.otext = OnscreenText(parent = self.entry, scale = 1, align = TextNode.ALeft, pos = (1, 0, 0), fg = (1, 1, 0.5, 1), text = ':')#, font = font) self.lines = [''] * 9 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False
def __init__(self): self.textNodes = [] self.messageType = None self.rootFrame = DirectFrame(pos = (0.03, 0, 0.2), frameColor = (0, 0, 0, 0), frameSize = (0, 1, 0, 1), parent = base.a2dBottomLeft) self.rootFrame.setBin('fixed', GUIOrder.ORDER[GUIOrder.CHAT]) self.entryFrame = DirectFrame(pos = (0, 0, 0), frameColor = (0, 0, 0, 0.1), frameSize = (0, 1, 0, 0.1), parent = self.rootFrame) self.chatarea = DirectEntry(width = 27, scale = Settings.CHAT_HEIGHT, pos = (0, 0, 0), frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), numLines = 1, cursorKeys = 1, rolloverSound = None, clickSound = None, focus = 0, command = self.OnChatEntered, parent = self.entryFrame) self.typeText = OnscreenText(text = '', pos = (0, Settings.CHAT_HEIGHT + 0.01), scale = Settings.CHAT_HEIGHT, fg = (1, 1, 1, 1), mayChange = True, align = TextNode.ALeft, parent = self.entryFrame) self.displayFrame = DirectFrame(pos = (0, 0, 0.1), frameColor = (0, 0, 0, 0), frameSize = (0, 1, 0, 0.42), parent = self.rootFrame) self.chatarea.enterText('') self.entryFrame.hide() self.chatarea['focus'] = 0 self.chatarea.setFocus()
def makeEntryField(caption, z, obscured): label = DirectLabel( parent=self.dialog, text=caption, text_scale=0.05, text_align=TextNode.ALeft, pos=(-0.82, 0, z + 0.1), ) entry = DirectEntry( parent=self.dialog, scale=0.05, width=32, pos=(-0.8, 0, z), pad=(0.2, 0.1), obscured=obscured, relief=DGG.GROOVE, ) return label, entry
class _GetchUnix: def __init__(self): import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon Carbon.Evt #see if it has this (in Unix, it doesn't) def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned
def build_text_question(self, question_dict): # , xPos, yPos): xPos = 0 yPos = 0.2 numLines = 5 if question_dict[ 'type'] == 3 else 1 # type == 3 is essay Qs DirectLabel(parent=self._rButtonFrame, text=question_dict['question'], scale=0.05, pos=(xPos, 0, yPos), frameColor=(0, 0, 0, 0), text_wordwrap=20) DirectEntry(text="", scale=.07, command=None, initialText="", numLines=numLines, focus=1)
def __init__(self): """ Initialize the MyApp class, including defining the GUI objects and layout. Inherits from ShowBase. """ # Because MyApp inherits from ShowBase, ShowBase needs to be initialized also (?) ShowBase.__init__(self) # doesn't disable the mouse, only disables the default setting of the mouse controlling the camera # can't import base and showbase at the same time. showbase is moreimportant right now. #base.disableMouse() # prints the coords of direct gui objects (DGO) when 'P' key is pressed or LMB is clicked self.accept("p", self.getDGOcoords) self.accept("mouse1", self.getDGOcoords) # only catches mouse when clicked on not gui elements >:| # add frmChatBox self.frmChatBox = DirectFrame(frameColor=(0, 255, 0, 1), frameSize=(-0.5, 0.5, -0.25, 0.25), pos=(0, 0, 0)) ### Add some gui objects and parent them to 'frmChatBox'. They move relative to 'frmChatBox', but are positioned relative to aspect2d. WHY?? ### Solution might be to create the frame at 0,0,0 and the DGOs relative to it (currently at 0,0,0) THEN move the frame. ### TODO: get mouse coords on screen to help with sizing DGOs? # add button btnClear = DirectButton(pos=(-0.15,0,-0.95),text = ("Clear", "CLEAR", "Clear", "disabled"), scale=.05, command=self.clearText, parent=self.frmChatBox) # add text entry box self.txtEntry = DirectEntry(text = "",pos=(-0.99,0,-0.95),scale=.05,command=self.setTextBox,initialText="Type Something", numLines = 2, focus=1, parent=self.frmChatBox) # add button btnCommit = DirectButton(pos=(-0.35,0,-0.95),text = ("Commit", "COMMIT", "Commit", "disabled"), scale=.05, command=self.changeText, parent=self.frmChatBox) # define some text to be used in bk_text = "This is my Demo" # add text label, not parented to 'frmChatBox' self.lblLabel = DirectLabel(text = bk_text, pos = (0.95, 0, -0.95), scale = 0.07, text_fg=(1,0.5,0.5,1), text_bg=(0,0,0,1), textMayChange=1)
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)
class Login(object): def __init__(self, main): self.main = main self.frame = None self.title = None self.error = None self.username = None self.userTextbox = None self.password = None self.passTextbox = None self.cpassword = None self.cpassTextbox = None self.submitBtn = None self.registerBtn = None self.cancelBtn = None # login screen def createLoginWindow(self): self.frame = DirectFrame(frameColor = (0, 0, 0, 1), frameSize = (-1.35, 1.35, -1, 1), pos = (0, 0, 0)) self.title = OnscreenText(text = 'Login', pos = (0, 0.3), scale = 0.15, fg = (1, 0.5, 0.5, 1), align = TextNode.ACenter, parent = self.frame, mayChange = False) # username self.username = OnscreenText(text = 'Username:'******'', scale = 0.05, pos = (0.1, 0, 0), initialText = '[username]', numLines = 1, focus = 1, focusInCommand = self.userTextFocus, focusOutCommand = self.userTextBlur) # password self.password = OnscreenText(text = 'Password:'******'', scale = 0.05, pos = (0.1, 0, -0.2), initialText = '[password]', numLines = 1, focus = 0, focusInCommand = self.passTextFocus, focusOutCommand = self.passTextBlur) # buttons self.submitBtn = DirectButton(self.frame, # parent text = 'Login', scale = 0.08, command = self.clickedSubmit, pos = (0.8, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) self.registerBtn = DirectButton(self.frame, # parent text = 'Register', scale = 0.08, command = self.clickedRegister, pos = (0.5, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) self.cancelBtn = DirectButton(self.frame, # parent text = 'Cancel', scale = 0.08, command = self.clickedCancel, pos = (0.2, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) def destroyLoginWindow(self): self.frame.destroy() self.frame = None self.title = None self.error = None self.username = None self.userTextbox = None self.password = None self.passTextbox = None self.submitBtn = None self.registerBtn = None self.cancelBtn = None # register screen def createRegisterWindow(self): self.frame = DirectFrame(frameColor = (0, 0, 0, 1), frameSize = (-1.35, 1.35, -1, 1), pos = (0, 0, 0)) self.title = OnscreenText(text = 'Register', pos = (0, 0.3), scale = 0.15, fg = (1, 0.5, 0.5, 1), align = TextNode.ACenter, parent = self.frame, mayChange = False) # username self.username = OnscreenText(text = 'Username:'******'', scale = 0.05, pos = (0.1, 0, 0), initialText = '[username]', numLines = 1, focus = 1, focusInCommand = self.userTextFocus, focusOutCommand = self.userTextBlur) # password self.password = OnscreenText(text = 'Password:'******'', scale = 0.05, pos = (0.1, 0, -0.2), initialText = '[password]', numLines = 1, focus = 0, focusInCommand = self.passTextFocus, focusOutCommand = self.passTextBlur) # confirm password self.cpassword = OnscreenText(text = 'Confirm Password:'******'', scale = 0.05, pos = (0.1, 0, -0.4), initialText = '[confirm password]', numLines = 1, focus = 0, focusInCommand = self.cpassTextFocus, focusOutCommand = self.cpassTextBlur) # buttons self.registerBtn = DirectButton(self.frame, # parent text = 'Register', scale = 0.08, command = self.clickedRegRegister, pos = (0.8, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) self.cancelBtn = DirectButton(self.frame, # parent text = 'Cancel', scale = 0.08, command = self.clickedRegCancel, pos=(0.2, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) def destroyRegisterWindow(self): self.frame.destroy() self.frame = None self.title = None self.error = None self.username = None self.userTextbox = None self.password = None self.passTextbox = None self.cpassword = None self.cpassTextbox = None self.registerBtn = None self.cancelBtn = None # error message helper def displayError(self, msg): if self.frame is None: return if self.error is not None: self.error.destroy() self.error = OnscreenText(text = msg, pos = (0, -0.65), scale = 0.06, fg = (1, 0.5, 0.5, 1), align = TextNode.ACenter, parent = self.frame, mayChange = False) # userTextbox handlers def userTextFocus(self): if self.userTextbox.get() == '[username]': self.userTextbox.enterText('') def userTextBlur(self): if self.userTextbox.get().strip() == '': self.userTextbox.enterText('[username]') # passTextbox handlers def passTextFocus(self): if self.passTextbox.get() == '[password]': self.passTextbox.enterText('') def passTextBlur(self): if self.passTextbox.get().strip() == '': self.passTextbox.enterText('[password]') # cpassTextbox handlers def cpassTextFocus(self): if self.cpassTextbox.get() == '[confirm password]': self.cpassTextbox.enterText('') def cpassTextBlur(self): if self.cpassTextbox.get().strip() == '': self.cpassTextbox.enterText('[confirm password]') # login button handlers def clickedSubmit(self): username = self.userTextbox.get().strip() password = self.passTextbox.get().strip() if username != '' and password != '': self.main.cManager.sendRequest(Constants.C_AUTH, {'username': username, 'password': password}) else: self.displayError('Please enter a username and password.') def clickedRegister(self): self.destroyLoginWindow() self.createRegisterWindow() def clickedCancel(self): exit() # register button handlers def clickedRegRegister(self): username = self.userTextbox.get().strip() password = self.passTextbox.get().strip() cpass = self.cpassTextbox.get().strip() if username != '': if password != '': if cpass == password: self.main.cManager.sendRequest(Constants.C_REGISTER, {'username': username, 'password': password}) self.destroyRegisterWindow() self.createLoginWindow() else: self.displayError('Your passwords do not match.') else: self.displayError('Please enter a password.') else: self.displayError('Please enter a username.') def clickedRegCancel(self): self.destroyRegisterWindow() self.createLoginWindow()
class MainScreen(): def __init__(self): self.txtPlayerName = DirectEntry( text="", scale=0.08, pos=(-0.15, 0, 0.6), initialText="Name", numLines = 1, width = 4, focus=False, focusInCommand=self.__clearText, focusOutCommand=self.__checkText) self.btnStart = DirectButton( text = "Start", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, .3), # the event which is thrown on clickSound command = self.btnStart_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnStart.setTransparency(1) self.btnHighscore = DirectButton( text = "Highscore", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, 0), # the event which is thrown on clickSound command = self.btnHighscore_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnHighscore.setTransparency(1) self.btnQuit = DirectButton( text = "Quit", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, -.3), # the event which is thrown on clickSound command = self.btnQuit_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnQuit.setTransparency(1) def show(self): self.txtPlayerName.show() self.btnStart.show() self.btnHighscore.show() self.btnQuit.show() def hide(self): self.txtPlayerName.hide() self.btnStart.hide() self.btnHighscore.hide() self.btnQuit.hide() def __clearText(self): if self.txtPlayerName.get() == "" or \ self.txtPlayerName.get() == "Name": self.txtPlayerName.enterText("") def __checkText(self): if self.txtPlayerName.get() == "": self.txtPlayerName.enterText("Name") def btnStart_Click(self): self.hide() base.messenger.send("MainMenu_start") def btnHighscore_Click(self): self.hide() base.messenger.send("Highscore_show") def btnQuit_Click(self): base.messenger.send("MainMenu_quit") def getPlayername(self): return self.txtPlayerName.get()
def __init__(self): self.txtPlayerName = DirectEntry( text="", scale=0.08, pos=(-0.15, 0, 0.6), initialText="Name", numLines = 1, width = 4, focus=False, focusInCommand=self.__clearText, focusOutCommand=self.__checkText) self.btnStart = DirectButton( text = "Start", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, .3), # the event which is thrown on clickSound command = self.btnStart_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnStart.setTransparency(1) self.btnHighscore = DirectButton( text = "Highscore", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, 0), # the event which is thrown on clickSound command = self.btnHighscore_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnHighscore.setTransparency(1) self.btnQuit = DirectButton( text = "Quit", # size of the button scale = (0.25, 0.25, 0.25), # set no relief relief = 1, frameColor = (0,0,0,0), # No sink in when press pressEffect = False, # position on the window pos = (0, 0, -.3), # the event which is thrown on clickSound command = self.btnQuit_Click, # sounds that should be played rolloverSound = None, clickSound = None) self.btnQuit.setTransparency(1)
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
class MainMenu(): def __init__(self, showbase): self.showbase = showbase self.status = OnscreenText(text = "", pos = Vec3(0, -0.35, 0), scale = 0.05, fg = (1, 0, 0, 1), align = TextNode.ACenter, mayChange = True) self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/mainmenu/menu.png', parent = self.showbase.render2d, ) self.title = OnscreenText( text = 'Main Menu', fg = (1, 1, 1, 1), parent = self.background, pos = (-0.6, 0.1), scale = 0.06 ) self.ip = '127.0.0.1' # Should make this write to file... so that the user can save ip's... # yep thats a good idea, there will be a few things i guess that need to be done like this # like settings and keys and whatnot # Buttons self.buttons = [] serverButtons = Vec3(-0.60, 0, -0.79) # Host self.params = ['3', '8'] p = serverButtons + Vec3(-0.25, 0, 0) self.hostButton = DirectButton(text = 'Host', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.showbase.hostGame, extraArgs = [self.params]) self.buttons.append(self.hostButton) # Join p = serverButtons + Vec3(0.0, 0.0, 0.0) self.joinButton = DirectButton(text = 'Join', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.joinServer) self.buttons.append(self.joinButton) # Refresh if self.showbase.online: p = serverButtons + Vec3(0.25, 0, 0) self.refreshButton = DirectButton(text = "Refresh", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.refreshStart) self.buttons.append(self.refreshButton) self.refreshStart() chatFrameCenter = (0.0, 0.325) chatFrameSize = (2.5, 1.2) self.chat = DirectFrame( frameColor = (0, 0, 0, 1), frameSize = (chatFrameSize[0] / 2, -chatFrameSize[0] / 2, chatFrameSize[1] / 2, -chatFrameSize[1] / 2), pos = (chatFrameCenter[0], 0, chatFrameCenter[1]) ) channelFrameSize = (chatFrameSize[0] / 4, chatFrameSize[1]) channelFrameCenter = (- chatFrameSize[0] / 2 + channelFrameSize[0] / 2, 0) numItemsVisible = 8 itemHeight = channelFrameSize[1] / (numItemsVisible + 1) self.channels = DirectScrolledList( parent = self.chat, pos = (channelFrameCenter[0], 0, channelFrameCenter[1]), frameSize = (-channelFrameSize[0] / 2, channelFrameSize[0] / 2, channelFrameSize[1] / 2, -channelFrameSize[1] / 2), frameColor = (1, 0, 0, 0.5), numItemsVisible = numItemsVisible, forceHeight = itemHeight, #itemFrame_frameSize = (-channelFrameSize[0] / 2.1, channelFrameSize[0] / 2.1, itemHeight, -channelFrameSize[1] + itemHeight), itemFrame_pos = (0, 0, channelFrameSize[1] / 2 - itemHeight), decButton_pos = (-0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4), decButton_text = 'Prev', decButton_text_scale = 0.05, decButton_borderWidth = (0.005, 0.005), incButton_pos = (0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4), incButton_text = 'Next', incButton_text_scale = 0.05, incButton_borderWidth = (0.005, 0.005), ) b1 = DirectButton(text = ("Button1", "click!", "roll", "disabled"), text_scale = 0.1, borderWidth = (0.01, 0.01), relief = 2) b2 = DirectButton(text = ("Button2", "click!", "roll", "disabled"), text_scale = 0.1, borderWidth = (0.01, 0.01), relief = 2) l1 = DirectLabel(text = "Test1", text_scale = 0.1) l2 = DirectLabel(text = "Test2", text_scale = 0.1) l3 = DirectLabel(text = "Test3", text_scale = 0.1) self.channels.addItem(b1) self.channels.addItem(b2) self.channels.addItem(l1) self.channels.addItem(l2) self.channels.addItem(l3) for fruit in ['apple', 'pear', 'banana', 'orange', 'cake', 'chocolate']: l = DirectLabel(text = fruit, text_scale = 0.1) self.channels.addItem(l) # need to add the chat stuff # i guess have like a chat manager which will hold an array of 'chat_instances' # and the chat manager can sort out which is displayed and which channel the text is sent from/received to # a bit more thinking needs to be done i guess # can discuss sometime (not really that important now :P) # also i guess the layout and shit will need to be sorted (for whoever is doing the designing) # current games list (need to implement this) # it should send a query to the master server to get the current list (just ip's atmo i guess) # options shit aswell needs to be sorted # maybe just an overlay or something # functionality for the host button (popup an overlay that will be able to set options and then 'start_game' button # then should auto connect and go to lobby (will be same as for all clients, except have a couple of different buttons i guess) # close game instead of disconnect, start game instead of ready (greyed until all others are ready), kick button i suppose # once the options are set the 'server_inst' should be started on the local computer (which will broadcast to master server, once host can successfully connect) # then game client will move to pregame state (connect to the server, and wait for others and ready) else: self.entry = DirectEntry( focusInCommand = self.clearText, frameSize = (-3, 3, -.5, 1), initialText = self.ip, parent = self.buttons[0], pos = (0, -0.6, -1.5), text_align = TextNode.ACenter, ) self.hide() def refreshStart(self): self.refreshButton["state"] = DGG.DISABLED if self.showbase.authCon.getConnected(): self.servers = [] self.showbase.authCon.sendData('serverQuery') self.showbase.taskMgr.doMethodLater(0.25, self.queryServers, 'Server Query') def queryServers(self, task): finished = False temp = self.showbase.authCon.getData() for package in temp: if len(package) == 2: # Handle Server Query if package[0] == 'server': self.servers.append(package[1]) print package[1] elif package[0] == 'final': self.refreshButton["state"] = DGG.NORMAL finished = True else: self.showbase.authCon.passData(package) if finished: return task.done return task.cont def joinChat(self): pass # Let the client mini auth with the lobby server(lobby_loop) by "Logging into the chat" # Since everything will be in the main menu? like a main chat window.. something similar to HoN i guess? # When the player opens the Join game by button, a list will be send from the lobby server telling it what games are active. # Then the player picks one and it connects via the host name/ip or whatever. # While this is busy happening the client stays connected to the lobby server. def joinServer(self): if self.showbase.online: self.ip = '127.0.0.1' else: self.ip = self.entry.get() self.status.setText('Attempting to join server @ ' + self.ip + '...') # attempt to connect to the game server self.showbase.client = Client(self.showbase, self.ip, 9099, compress = True) if self.showbase.client.getConnected(): print 'Connected to server, Awaiting authentication...' self.showbase.client.sendData(('username', self.showbase.username)) self.showbase.taskMgr.add(self.authorizationListener, 'Authorization Listener') else: self.status.setText('Could not Connect...') def authorizationListener(self, task): temp = self.showbase.client.getData() auth = False if temp != []: for package in temp: if len(package) == 2: if package[0] == 'auth': print 'Authentication Successful' auth = True elif package[0] == 'fail': self.status.setText('Authentication failed on server...') return task.done else: self.showbase.client.passData(package) if auth: self.showbase.startPregame() return task.done return task.again def clearText(self): self.entry.enterText('') def hide(self): self.showbase.taskMgr.remove('Server Query Timeout') self.background.hide() for b in self.buttons: b.hide() self.status.hide() if self.showbase.online: self.chat.hide() self.channels.hide() else: self.entry.hide() def show(self): self.background.show() for b in self.buttons: b.show() self.status.show() if self.showbase.online: self.chat.show() self.channels.show() else: self.entry.show()
def __init__(self, showbase): self.showbase = showbase self.status = OnscreenText(text = "", pos = Vec3(0, -0.35, 0), scale = 0.05, fg = (1, 0, 0, 1), align = TextNode.ACenter, mayChange = True) self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/mainmenu/menu.png', parent = self.showbase.render2d, ) self.title = OnscreenText( text = 'Main Menu', fg = (1, 1, 1, 1), parent = self.background, pos = (-0.6, 0.1), scale = 0.06 ) self.ip = '127.0.0.1' # Should make this write to file... so that the user can save ip's... # yep thats a good idea, there will be a few things i guess that need to be done like this # like settings and keys and whatnot # Buttons self.buttons = [] serverButtons = Vec3(-0.60, 0, -0.79) # Host self.params = ['3', '8'] p = serverButtons + Vec3(-0.25, 0, 0) self.hostButton = DirectButton(text = 'Host', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.showbase.hostGame, extraArgs = [self.params]) self.buttons.append(self.hostButton) # Join p = serverButtons + Vec3(0.0, 0.0, 0.0) self.joinButton = DirectButton(text = 'Join', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.joinServer) self.buttons.append(self.joinButton) # Refresh if self.showbase.online: p = serverButtons + Vec3(0.25, 0, 0) self.refreshButton = DirectButton(text = "Refresh", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.refreshStart) self.buttons.append(self.refreshButton) self.refreshStart() chatFrameCenter = (0.0, 0.325) chatFrameSize = (2.5, 1.2) self.chat = DirectFrame( frameColor = (0, 0, 0, 1), frameSize = (chatFrameSize[0] / 2, -chatFrameSize[0] / 2, chatFrameSize[1] / 2, -chatFrameSize[1] / 2), pos = (chatFrameCenter[0], 0, chatFrameCenter[1]) ) channelFrameSize = (chatFrameSize[0] / 4, chatFrameSize[1]) channelFrameCenter = (- chatFrameSize[0] / 2 + channelFrameSize[0] / 2, 0) numItemsVisible = 8 itemHeight = channelFrameSize[1] / (numItemsVisible + 1) self.channels = DirectScrolledList( parent = self.chat, pos = (channelFrameCenter[0], 0, channelFrameCenter[1]), frameSize = (-channelFrameSize[0] / 2, channelFrameSize[0] / 2, channelFrameSize[1] / 2, -channelFrameSize[1] / 2), frameColor = (1, 0, 0, 0.5), numItemsVisible = numItemsVisible, forceHeight = itemHeight, #itemFrame_frameSize = (-channelFrameSize[0] / 2.1, channelFrameSize[0] / 2.1, itemHeight, -channelFrameSize[1] + itemHeight), itemFrame_pos = (0, 0, channelFrameSize[1] / 2 - itemHeight), decButton_pos = (-0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4), decButton_text = 'Prev', decButton_text_scale = 0.05, decButton_borderWidth = (0.005, 0.005), incButton_pos = (0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4), incButton_text = 'Next', incButton_text_scale = 0.05, incButton_borderWidth = (0.005, 0.005), ) b1 = DirectButton(text = ("Button1", "click!", "roll", "disabled"), text_scale = 0.1, borderWidth = (0.01, 0.01), relief = 2) b2 = DirectButton(text = ("Button2", "click!", "roll", "disabled"), text_scale = 0.1, borderWidth = (0.01, 0.01), relief = 2) l1 = DirectLabel(text = "Test1", text_scale = 0.1) l2 = DirectLabel(text = "Test2", text_scale = 0.1) l3 = DirectLabel(text = "Test3", text_scale = 0.1) self.channels.addItem(b1) self.channels.addItem(b2) self.channels.addItem(l1) self.channels.addItem(l2) self.channels.addItem(l3) for fruit in ['apple', 'pear', 'banana', 'orange', 'cake', 'chocolate']: l = DirectLabel(text = fruit, text_scale = 0.1) self.channels.addItem(l) # need to add the chat stuff # i guess have like a chat manager which will hold an array of 'chat_instances' # and the chat manager can sort out which is displayed and which channel the text is sent from/received to # a bit more thinking needs to be done i guess # can discuss sometime (not really that important now :P) # also i guess the layout and shit will need to be sorted (for whoever is doing the designing) # current games list (need to implement this) # it should send a query to the master server to get the current list (just ip's atmo i guess) # options shit aswell needs to be sorted # maybe just an overlay or something # functionality for the host button (popup an overlay that will be able to set options and then 'start_game' button # then should auto connect and go to lobby (will be same as for all clients, except have a couple of different buttons i guess) # close game instead of disconnect, start game instead of ready (greyed until all others are ready), kick button i suppose # once the options are set the 'server_inst' should be started on the local computer (which will broadcast to master server, once host can successfully connect) # then game client will move to pregame state (connect to the server, and wait for others and ready) else: self.entry = DirectEntry( focusInCommand = self.clearText, frameSize = (-3, 3, -.5, 1), initialText = self.ip, parent = self.buttons[0], pos = (0, -0.6, -1.5), text_align = TextNode.ACenter, ) self.hide()
class DeveloperConsole(InteractiveInterpreter, DirectObject): """The name says it all.""" def __init__(self): sys.stdout = PseudoFile(self.writeOut) sys.stderr = PseudoFile(self.writeErr) tpErr = TextProperties() tpErr.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr) #font = loader.loadFont("cmss12") self.frame = DirectFrame(parent = base.a2dTopCenter, text_align = TextNode.ALeft, text_pos = (-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale = 0.05, text_fg = (1, 1, 1, 1), frameSize = (-2.0, 2.0, -0.5, 0.0), frameColor = (0, 0, 0, 0.5), text = '')#, text_font = font) self.entry = DirectEntry(parent = base.a2dTopLeft, command = self.command, scale = 0.05, width = 1000.0, pos = (-0.02, 0, -0.48), relief = None, text_pos = (1.5, 0, 0), text_fg = (1, 1, 0.5, 1), rolloverSound = None, clickSound = None)#, text_font = font) self.otext = OnscreenText(parent = self.entry, scale = 1, align = TextNode.ALeft, pos = (1, 0, 0), fg = (1, 1, 0.5, 1), text = ':')#, font = font) self.lines = [''] * 9 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False def prevCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: self.cscroll = len(self.commands) self.command = self.entry.get() elif self.cscroll <= 0: return else: self.commands[self.cscroll] = self.entry.get() self.cscroll -= 1 self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def nextCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: return self.commands[self.cscroll] = self.entry.get() self.cscroll += 1 if self.cscroll >= len(self.commands): self.cscroll = None self.entry.set(self.command) self.entry.setCursorPosition(len(self.command)) else: self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def writeOut(self, line, copy = True): if copy: sys.__stdout__.write(line) lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def writeErr(self, line, copy = True): if copy: sys.__stderr__.write(line) line = '\1err\1%s\2' % line lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def command(self, text): if not self.hidden: self.cscroll = None self.command = '' self.entry.set('') self.entry['focus'] = True self.writeOut(self.otext['text'] + ' ' + text + '\n', False) if text != '' and (len(self.commands) == 0 or self.commands[-1] != text): self.commands.append(text) # Insert plugins into the local namespace locals = __main__.__dict__ #locals['manager'] = self.manager #for plugin in self.manager.named.keys(): # locals[plugin] = self.manager.named[plugin] locals['panda3d'] = panda3d # Run it and print the output. if not self.initialized: InteractiveInterpreter.__init__(self, locals = locals) self.initialized = True try: if self.runsource(self.block + '\n' + text) and text != '': self.otext['text'] = '.' self.block += '\n' + text else: self.otext['text'] = ':' self.block = '' except Exception: # Not just "except", it will also catch SystemExit # Whoops! Print out a traceback. self.writeErr(traceback.format_exc()) def toggle(self): if self.hidden: self.show() else: self.hide() def show(self): self.accept('arrow_up', self.prevCommand) self.accept('arrow_up-repeat', self.prevCommand) self.accept('arrow_down', self.nextCommand) self.accept('arrow_down-repeat', self.nextCommand) self.hidden = False self.entry['focus'] = True self.frame.show() self.entry.show() self.otext.show() def hide(self): self.ignoreAll() self.hidden = True self.entry['focus'] = False self.frame.hide() self.entry.hide() self.otext.hide() def destroy(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.ignoreAll() self.frame.destroy() self.entry.destroy() self.otext.destroy()
class Chat(object): """Handles all chat.""" def __init__(self, game): self.game = game self.lines = [] self.whisperTarget = None props = base.win.getProperties() ratio = float(props.getXSize()) / props.getYSize() self.frame = DirectFrame(frameColor=(0, 0, 0, 0), frameSize=(0, 1, 0, 1), pos=(-ratio, 0, -1)) self.text = OnscreenText( text="", pos=(0.01, 0.45), scale=0.05, fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.2), parent=self.frame, align=TextNode.ALeft, mayChange=True, ) self.entry = DirectEntry( parent=self.frame, text="", scale=0.05, pos=(0.01, 0, 0.02), initialText="", width=26, numLines=1 ) self.targetText = OnscreenText( text="", pos=(1.34, 0.025), scale=0.05, fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.4), parent=self.frame, align=TextNode.ALeft, mayChange=True, ) base.accept("t", self.startChatting) base.accept("shift-t", self.startChatting) base.accept("y", self.startWhispering) base.accept("shift-y", self.startWhispering) base.accept("arrow_up", lambda: self.changeTarget(1)) base.accept("shift-arrow_up", lambda: self.changeTarget(1)) base.accept("arrow_down", lambda: self.changeTarget(-1)) base.accept("shift-arrow_down", lambda: self.changeTarget(-1)) base.accept("enter", self.sendChat) base.accept("shift-enter", self.sendChat) def startChatting(self): if not self.game.isChatting: self.game.isChatting = True # focus on the DirectEntry self.entry["focus"] = 1 # reset whisper target (just in case) self.whisperTarget = None # enable UI mode if self.game.camera is not None: self.game.camera.showMouse() def startWhispering(self): if not self.game.isChatting: if not self.game.characters: self.addLine("<<System>> Nobody to whisper!") else: self.startChatting() self.changeTarget(0) def changeTarget(self, amt): if self.game.isChatting: targets = self.game.characters.keys() targets.sort() # find target (or the closest id before target, or 0) index = 0 match = False for i in range(len(targets)): if targets[i] < self.whisperTarget: index = i elif targets[i] == self.whisperTarget: index = i match = True break else: break # if not found but going back 1 anyway, set amt to 0 if not match and amt == -1: amt = 0 # set new whisper target index = (index + amt) % len(targets) self.whisperTarget = targets[index] self.targetText.setText("to: " + str(self.game.characters[self.whisperTarget].name)) def sendChat(self): if self.game.isChatting: message = self.entry.get().strip() if len(message) > 0: # figure out target target = "" if self.whisperTarget in self.game.characters: target = self.game.characters[self.whisperTarget].name # submit message self.game.main.cManager.sendRequest(Constants.C_CHAT, {"message": message, "target": target}) # stop chatting self.stopChatting() def stopChatting(self): if self.game.isChatting: self.game.isChatting = False # disable chat entry self.entry["focus"] = 0 # clear text box self.entry.enterText("") # remove whisper target self.whisperTarget = None self.targetText.setText("") # disable UI mode if self.game.camera is not None: self.game.camera.hideMouse() def addLine(self, line): self.lines.append(line) self.text.setText("\n".join(self.lines[-8:]))
def createLoginWindow(self): self.frame = DirectFrame(frameColor = (0, 0, 0, 1), frameSize = (-1.35, 1.35, -1, 1), pos = (0, 0, 0)) self.title = OnscreenText(text = 'Login', pos = (0, 0.3), scale = 0.15, fg = (1, 0.5, 0.5, 1), align = TextNode.ACenter, parent = self.frame, mayChange = False) # username self.username = OnscreenText(text = 'Username:'******'', scale = 0.05, pos = (0.1, 0, 0), initialText = '[username]', numLines = 1, focus = 1, focusInCommand = self.userTextFocus, focusOutCommand = self.userTextBlur) # password self.password = OnscreenText(text = 'Password:'******'', scale = 0.05, pos = (0.1, 0, -0.2), initialText = '[password]', numLines = 1, focus = 0, focusInCommand = self.passTextFocus, focusOutCommand = self.passTextBlur) # buttons self.submitBtn = DirectButton(self.frame, # parent text = 'Login', scale = 0.08, command = self.clickedSubmit, pos = (0.8, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) self.registerBtn = DirectButton(self.frame, # parent text = 'Register', scale = 0.08, command = self.clickedRegister, pos = (0.5, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None) self.cancelBtn = DirectButton(self.frame, # parent text = 'Cancel', scale = 0.08, command = self.clickedCancel, pos = (0.2, 0.0, -0.90), text_bg = (1, 0.5, 0.5, 1), relief = None)
def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon Carbon.Evt #see if it has this (in Unix, it doesn't) def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] return chr(msg & 0x000000FF) # ---- character reading from console - END ---- class pandaInteractiveConsole( InteractiveConsole, DirectObject.DirectObject ): def __init__( self, locals, interfaces=GUI|CONSOLE ): print "I: pandaInteractiveConsole.__init__" InteractiveConsole.__init__( self, locals ) self.guiEnabled = (interfaces & GUI) if self.guiEnabled: print "I: - GUI enabled" top = 1/SCALE - (V_SPACE/SCALE) bottom = 1/SCALE - (V_SPACE/SCALE) - (V_SIZE/SCALE) # panda3d interface self.consoleFrame = DirectFrame( relief = DGG.GROOVE , frameColor = (200, 200, 200, 0.85), scale=SCALE , frameSize = (-1/SCALE, 1/SCALE, top, bottom)) self.accept( "f1", self.toggleConsole ) # text entry line self.consoleEntry = DirectEntry( self.consoleFrame, text = "", command=self.setText, width = 1/SCALE*2-2 , pos =(-1/SCALE+1,0,bottom+1), initialText="", numLines = 1, focus=1) # output lines self.consoleOutputList = list() for i in xrange( NUMLINES ): label = OnscreenText( parent = self.consoleFrame, text = "", pos = (-1/SCALE+1, bottom+1+NUMLINES-i) #-1-i) , align=TextNode.ALeft, mayChange=1, scale=1.0) self.consoleOutputList.append( label ) self.toggleConsole() self.consoleEnabled = (interfaces & CONSOLE) self.stdout = sys.stdout if self.consoleEnabled: print "I: - Console enabled" # function to read the keyboard inputs self.readKey = _Getch() # redirect input and output self.stdout = sys.stdout sys.stdout = self if sys.platform == 'linux2' or sys.platform == 'darwin': self.setConsoleNonBlocking( self.stdout ) self.write( "D: myInteractiveConsole.__init__\n" ) # buffer of current text self.linebuffer = '' self.linebufferPos = 0 def setConsoleBlocking( self, fd_in ): fd = fd_in.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) try: fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.FNDELAY) except: pass def setConsoleNonBlocking( self, fd_in ): fd = fd_in.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) try: fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) except: self.write( "D: console init failed\n" ) self.setConsoleBlocking( fd ) ''' # set read non blocking fd = sys.stdin.fileno() self.oldterm = termios.tcgetattr(fd) newattr = self.oldterm self.oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) fcntl.fcntl(fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK) ''' def __del__( self ): if self.consoleEnabled: sys.stdout = self.stdout if sys.platform == 'linux2' or sys.platform == 'darwin': self.write( "setting old terminal settings\n" ) fd = sys.stdin.fileno() termios.tcsetattr(fd, termios.TCSAFLUSH, self.oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, self.oldflags) def toggleConsole( self ): self.consoleFrame.toggleVis() self.consoleEntry['focus'] != self.consoleFrame.isHidden def setText(self, textEntered): self.write( ">%s" % textEntered ) output = self.push( textEntered ) # clear line self.consoleEntry.enterText('') self.consoleEntry['focus'] = 1 def writeP3dConsole( self, printString ): # remove carriage returns (causes disort in output) printString = printString.strip() # remove not printable characters (which can be input by console input) printString = re.sub( r"[^%s]" % string.printable, "", printString ) # only write lines which contain something if printString.strip() != '': while len(printString) > LINELENGTH: writeString = printString[0:LINELENGTH] printString = printString[LINELENGTH:] # output on panda3d interface for i in xrange( NUMLINES-1 ): self.consoleOutputList[i].setText( self.consoleOutputList[i+1].getText() ) self.consoleOutputList[NUMLINES-1].setText( writeString ) # output on panda3d interface for i in xrange( NUMLINES-1 ): self.consoleOutputList[i].setText( self.consoleOutputList[i+1].getText() ) self.consoleOutputList[NUMLINES-1].setText( printString ) def write( self, string ): # write a text the console try: if self.consoleEnabled: # output on console self.stdout.write( string )
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)
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()
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 panda3dIOClass( DirectObject.DirectObject ): # set gui key to None if you want to call toggleConsole from outside this class gui_key = CONSOLE_TOGGLE_KEY autocomplete_key = CONSOLE_AUTOCOMPLETE_KEY autohelp_key = CONSOLE_AUTOHELP_KEY scroll_up_repeat_key = CONSOLE_SCROLL_UP_KEY + "-repeat" scroll_down_repeat_key = CONSOLE_SCROLL_DOWN_KEY + "-repeat" # change size of text and number of characters on one line # scale of frame ( must be small (0.0x) scale = PANDA3D_CONSOLE_SCALE # to define a special font, if loading fails the default font is used (without warning) font = PANDA3D_CONSOLE_FONT fontWidth = PANDA3D_CONSOLE_FONT_WIDTH # frame position and size (vertical & horizontal) h_pos = PANDA3D_CONSOLE_HORIZONTAL_POS h_size = PANDA3D_CONSOLE_HORIZONTAL_SIZE # v_size + v_pos should not exceed 2.0, else parts of the interface will not be visible # space above the frame ( must be below 2.0, best between 0.0 and 1.0 ) v_pos = PANDA3D_CONSOLE_VERTICAL_POS # vertical size of the frame ( must be at max 2.0, best between 0.5 and 2.0 ) v_size = PANDA3D_CONSOLE_VERTICAL_SIZE linelength = int((h_size/scale - 5) / fontWidth) print "max number of characters on a length:", linelength numlines = int(v_size/scale - 5) defaultTextColor = (0.0,0.0,0.0,1.0) autoCompleteColor = (0.9,0.9,0.9,1.0) def __init__( self, parent ): self.parent = parent # line wrapper self.linewrap = textwrap.TextWrapper() self.linewrap.width = self.linelength # calculate window size left = (self.h_pos) / self.scale right = (self.h_pos + self.h_size) / self.scale bottom = (self.v_pos) / self.scale top = (self.v_pos + self.v_size) /self.scale # panda3d interface self.consoleFrame = DirectFrame ( relief = DGG.GROOVE , frameColor = (200, 200, 200, 0.5) , scale=self.scale , frameSize = (0, self.h_size / self.scale, 0, self.v_size / self.scale) ) self.windowEvent( base.win ) # try to load the defined font try: fixedWidthFont = loader.loadFont(self.font) except: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # if font is not valid use default font if not fixedWidthFont.isValid(): if self.font is None: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # text entry line self.consoleEntry = DirectEntry ( self.consoleFrame , text = "" , command = self.onEnterPress , width = self.h_size/self.scale - 2 , pos = (1, 0, 1.5) , initialText = "" , numLines = 1 , focus = 1 , entryFont = fixedWidthFont) # output lines self.consoleOutputList = list() for i in xrange( self.numlines ): label = OnscreenText( parent = self.consoleFrame , text = "" , pos = (1, -i+3+self.numlines) , align=TextNode.ALeft , mayChange=1 , scale=1.0 , fg = self.defaultTextColor ) label.setFont( fixedWidthFont ) self.consoleOutputList.append( label ) # list of the last commands of the user self.userCommandList = list() self.userCommandListLength = 100 for i in xrange(self.userCommandListLength): self.userCommandList.append('') self.userCommandPos = 0 # buffer for data self.textBuffer = list() self.textBufferLength = 1000 for i in xrange(self.textBufferLength): self.textBuffer.append(['', DEFAULT_COLOR]) self.textBufferPos = self.textBufferLength-self.numlines # toggle the window at least once to activate the events self.toggleConsole() self.toggleConsole() # call the help-command on start self.onEnterPress("help") # write a string to the panda3d console def write( self, printString, color=defaultTextColor ): # remove not printable characters (which can be input by console input) printString = re.sub( r'[^%s]' % re.escape(string.printable[:95]), "", printString) splitLines = self.linewrap.wrap(printString) for line in splitLines: self.textBuffer.append( [line, color] ) self.textBuffer.pop(0) self.updateOutput() def updateOutput( self ): for lineNumber in xrange(self.numlines): lineText, color = self.textBuffer[lineNumber + self.textBufferPos] self.consoleOutputList[lineNumber].setText( lineText ) self.consoleOutputList[lineNumber]['fg'] = color # toggle the gui console def toggleConsole( self ): self.consoleFrame.toggleVis() hidden = self.consoleFrame.isHidden() self.consoleEntry['focus'] != hidden if hidden: self.ignoreAll() self.accept( self.gui_key, self.toggleConsole ) #playerController.enableInput() #unpause("v") else: self.ignoreAll() #playerController.disableInput() #pause("v") self.accept( CONSOLE_SCROLL_UP_KEY, self.scroll, [-5] ) self.accept( self.scroll_up_repeat_key, self.scroll, [-5] ) self.accept( CONSOLE_SCROLL_DOWN_KEY, self.scroll, [5] ) self.accept( self.scroll_down_repeat_key, self.scroll, [5] ) self.accept( 'window-event', self.windowEvent) self.accept( CONSOLE_PREVIOUS_COMMAND_KEY , self.scrollCmd, [ 1] ) self.accept( CONSOLE_NEXT_COMMAND_KEY, self.scrollCmd, [-1] ) self.accept( self.gui_key, self.toggleConsole ) #self.accept( self.autocomplete_key, self.autocomplete ) #self.accept( self.autohelp_key, self.autohelp ) # accept v, c and x, where c & x copy's the whole console text #messenger.toggleVerbose() #for osx use ('meta') if sys.platform == 'darwin': self.accept( 'meta', self.unfocus ) self.accept( 'meta-up', self.focus ) self.accept( 'meta-c', self.copy ) self.accept( 'meta-x', self.cut ) self.accept( 'meta-v', self.paste ) #for windows use ('control') if sys.platform == 'win32' or sys.platform == 'linux2': self.accept( 'control', self.unfocus ) self.accept( 'control-up', self.focus ) self.accept( 'control-c', self.copy ) self.accept( 'control-x', self.cut ) self.accept( 'control-v', self.paste ) # def autohelp( self ): # currentText = self.consoleEntry.get() # currentPos = self.consoleEntry.guiItem.getCursorPosition() # self.parent.autohelp( currentText, currentPos ) def focus( self ): self.consoleEntry['focus'] = 1 def unfocus( self ): self.consoleEntry['focus'] = 0 def copy( self ): copy = self.consoleEntry.get() clipboard.setText( copy ) def paste( self ): oldCursorPos = self.consoleEntry.guiItem.getCursorPosition() clipboardText = clipboard.getText() # compose new text line oldText = self.consoleEntry.get() newText = oldText[0:oldCursorPos] + clipboardText + oldText[oldCursorPos:] clipboardTextLines = newText.split(os.linesep) for i in xrange( len(clipboardTextLines)-1 ): currentLine = clipboardTextLines[i] # we only want printable characters currentLine = re.sub( r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) # set new text and position self.consoleEntry.set( currentLine ) self.onEnterPress( currentLine ) currentLine = clipboardTextLines[-1] currentLine = re.sub( r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) self.consoleEntry.set( currentLine ) self.consoleEntry.setCursorPosition( len(self.consoleEntry.get()) ) self.focus() def cut( self ): clipboard.setText( self.consoleEntry.get() ) self.consoleEntry.enterText('') self.focus() def scroll( self, step ): self.textBufferPos += step self.textBufferPos = min( self.textBufferLength-self.numlines, max( 0, self.textBufferPos ) ) self.updateOutput() def scrollCmd( self, step ): oldCmdPos = self.userCommandPos self.userCommandPos += step self.userCommandPos = min( self.userCommandListLength-1, max( 0, self.userCommandPos ) ) self.userCommandList[oldCmdPos] = self.consoleEntry.get() newCmd = self.userCommandList[self.userCommandPos] self.consoleEntry.set( newCmd ) self.consoleEntry.setCursorPosition( len(newCmd) ) def onEnterPress( self, textEntered ): # set to last message self.textBufferPos = self.textBufferLength-self.numlines # clear line self.consoleEntry.enterText('') self.focus() # add text entered to user command list & remove oldest entry self.userCommandList.insert( 1, textEntered ) self.userCommandList[0] = '' self.userCommandList.pop( -1 ) self.userCommandPos = 0 # call the interpreter to handle the input interpreter = cliClass() result = interpreter.interpreter(textEntered) # write the entered text to the output self.write(textEntered, (0.0, 0.0, 1, 1)) print textEntered # write each line seperately to the output for line in result.split('\n'): line = " " + line self.write(line, (0, 0, 0, 1)) print line def windowEvent( self, window ): """ This is a special callback. It is called when the panda window is modified. """ wp = window.getProperties() width = wp.getXSize() / float(wp.getYSize()) height = wp.getYSize() / float(wp.getXSize()) if width > height: height = 1.0 else: width = 1.0 # aligned to center consolePos = Vec3(-self.h_size/2, 0, -self.v_size/2) # aligned to left bottom #consolePos = Vec3(-width+self.h_pos, 0, -height+self.v_pos) # aligned to right top #consolePos = Vec3(width-self.h_size, 0, height-self.v_size) # set position self.consoleFrame.setPos( consolePos )
def __init__( self, parent ): self.parent = parent # line wrapper self.linewrap = textwrap.TextWrapper() self.linewrap.width = self.linelength # calculate window size left = (self.h_pos) / self.scale right = (self.h_pos + self.h_size) / self.scale bottom = (self.v_pos) / self.scale top = (self.v_pos + self.v_size) /self.scale # panda3d interface self.consoleFrame = DirectFrame ( relief = DGG.GROOVE , frameColor = (200, 200, 200, 0.5) , scale=self.scale , frameSize = (0, self.h_size / self.scale, 0, self.v_size / self.scale) ) self.windowEvent( base.win ) # try to load the defined font try: fixedWidthFont = loader.loadFont(self.font) except: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # if font is not valid use default font if not fixedWidthFont.isValid(): if self.font is None: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # text entry line self.consoleEntry = DirectEntry ( self.consoleFrame , text = "" , command = self.onEnterPress , width = self.h_size/self.scale - 2 , pos = (1, 0, 1.5) , initialText = "" , numLines = 1 , focus = 1 , entryFont = fixedWidthFont) # output lines self.consoleOutputList = list() for i in xrange( self.numlines ): label = OnscreenText( parent = self.consoleFrame , text = "" , pos = (1, -i+3+self.numlines) , align=TextNode.ALeft , mayChange=1 , scale=1.0 , fg = self.defaultTextColor ) label.setFont( fixedWidthFont ) self.consoleOutputList.append( label ) # list of the last commands of the user self.userCommandList = list() self.userCommandListLength = 100 for i in xrange(self.userCommandListLength): self.userCommandList.append('') self.userCommandPos = 0 # buffer for data self.textBuffer = list() self.textBufferLength = 1000 for i in xrange(self.textBufferLength): self.textBuffer.append(['', DEFAULT_COLOR]) self.textBufferPos = self.textBufferLength-self.numlines # toggle the window at least once to activate the events self.toggleConsole() self.toggleConsole() # call the help-command on start self.onEnterPress("help")
class Pregame(): def __init__(self, showbase): self.showbase = showbase self.ready = False self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/mainmenu/menu.png', parent = self.showbase.render2d, ) self.title = OnscreenText( text = 'Lobby!', fg = (1, 1, 1, 1), parent = self.background, pos = (-0.6, 0.1), scale = 0.06 ) self.buttons = [] controlButtons = Vec3(-0.60, 0, -0.79) # Toggle ready p = controlButtons + Vec3(-0.25, 0, 0) self.toggleReadyButton = DirectButton( text = 'Ready/Unready', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.toggleReady, ) self.buttons.append(self.toggleReadyButton) # Disconnect p = controlButtons + Vec3(0.0, 0.0, 0.0) self.disconnectButton = DirectButton( text = 'Disconnect', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.disconnect, ) self.buttons.append(self.disconnectButton) # Send message p = controlButtons + Vec3(0.25, 0.0, 0.0) self.sendMessageButton = DirectButton( text = 'Send Message', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.sendMessage, extraArgs = [''], ) self.buttons.append(self.sendMessageButton) # Message input self.message = DirectEntry( command = self.sendMessage, focusInCommand = self.clearText, frameSize = (-3, 3, -.5, 1), initialText = '', parent = self.buttons[2], pos = (0, -0.6, -1.5), text_align = TextNode.ACenter, ) self.showbase.gameData = GameData() self.showbase.users = [] self.hide() def clearText(self): self.message.set('') def reset(self): self.messages = [] self.showbase.users = [] def updateLobby(self, task): temp = self.showbase.client.getData() for package in temp: if len(package) == 2: print 'Received: ', str(package) if package[0] == 'chat': if len(package[1]) == 2: self.messages.append(package[1]) print self.messages elif package[0] == 'client': self.showbase.users.append(User(package[1])) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'ready': for user in self.showbase.users: if user.name == package[1][0]: user.ready = package[1][1] for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'disconnect': for user in self.showbase.users: if user.name == package[1]: self.showbase.users.remove(user) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'gamedata': self.showbase.gameData.unpackageData(package[1]) elif package[0] == 'state': print 'state: ', package[1] if package[1] == 'preround': self.showbase.startRound() return task.done return task.again def toggleReady(self): self.ready = not self.ready self.showbase.client.sendData(('ready', self.ready)) def disconnect(self): self.showbase.client.sendData(('disconnect', 'disconnect')) self.showbase.authCon = self.showbase.client self.showbase.returnToMenu() def sendMessage(self, message): if message == '': message = self.message.get() if message != '': self.showbase.client.sendData(('chat', message)) self.message.set('') def hide(self): self.background.hide() self.message.hide() for b in self.buttons: b.hide() self.showbase.taskMgr.remove('Update Lobby') def show(self): self.background.show() self.message.show() for b in self.buttons: b.show() # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
class Fighter(DirectObject): def __init__(self): base.disableMouse() # Carga el fondo del juego self.bg = loader.loadModel("models/plane") self.bg.reparentTo(camera) self.bg.setPos(0, 200, 0) self.bg.setScale(300, 0, 146) self.bg.setTexture(loader.loadTexture("models/Backgrounds/farback.png"), 1) # Inicializa el gestor de teclado y los objetos del juego self.inputManager = InputManager() # Inicializa el menu del juego self.inicializarMenu() self.marcador = None self.barraEnergia = None self.marcadorFinalNP = None self.entrada = None self.rankingNP = None self.mostrarMenuJuego() self.accept("m", self.cambiarMenuJuego) self.accept("q", self.salir) # Inicializa el menu def inicializarMenu(self): self.menuGraphics = loader.loadModel("models/MenuGraphics") self.fonts = {"silver" : loader.loadFont("fonts/LuconSilver"), "blue" : loader.loadFont("fonts/LuconBlue"), "orange" : loader.loadFont("fonts/LuconOrange")} self.menu = Menu(self.menuGraphics, self.fonts, self.inputManager) self.menu.initMenu([0, None, ["Nueva Partida", "Salir"], [[self.nuevaPartida], [self.salir]], [[None], [None]]]) # Comienza una partida def nuevaPartida(self): if (not self.marcadorFinalNP is None): self.marcadorFinalNP.detachNode() self.marcadorFinalNP.remove() if (not self.rankingNP is None): self.rankingNP.detachNode() self.rankingNP.remove() self.ship = Ship(self.inputManager) self.mostrarInfo() taskMgr.add(self.actualizarInfo, "Actualizar Puntuacion") # Inicializa y muestra el marcador del jugador def mostrarInfo(self): self.marcador = TextNode("Marcador") self.marcador.setText("Puntos: " + str(self.ship.puntos)) self.marcador.setCardColor(0, 0, 0, 1) self.marcador.setCardDecal(True) self.marcador.setCardAsMargin(0.4, 0.4, 0.4, 0.4) self.marcadorNP = aspect2d.attachNewNode(self.marcador) self.marcadorNP.reparentTo(base.a2dTopLeft) self.marcadorNP.setPos(0.02, 0, -0.05) self.marcadorNP.setScale(0.07) self.barraEnergia = DirectWaitBar(text = "Energia", value = 5, range = 5, scale = 0.3, pos = (0, 0, 0.95)) # Actualiza la puntuacion del jugador en pantalla def actualizarInfo(self, tarea): self.marcador.setText("Puntos: " + str(self.ship.puntos)) self.barraEnergia["value"] = self.ship.vida self.barraEnergia.setValue() # Termina la partida if (self.ship.terminarPartida): self.terminarPartida() return tarea.done return tarea.cont # Termina partida liberando recursos para poder empezar una nueva # sin reiniciar el juego def terminarPartida(self): # Solicita al usuario un nombre para la tabla de puntuaciones self.entrada = DirectEntry(width = 15, numLines = 1, scale = 0.07, cursorKeys = 1, frameSize = (0, 15, 0, 1), command = self.almacenarPuntuacion, pos = (-0.3, 0, 0.1), focus = True, text_pos = (0.2, 0.2)) self.puntos = self.ship.puntos self.ship.ship.detachNode() self.ship.ship.remove() taskMgr.remove("Mover Nave") taskMgr.remove("Generar Enemigos") taskMgr.remove("Comprobar Impactos") taskMgr.remove("Actualizar Puntuacion") taskMgr.remove("Explosionar*") self.mostrarFinPartida() # Libera los recursos de la partida que ha terminado self.ship.eliminarObjetos() del self.ship del self.menuGraphics del self.menu self.marcadorNP.detachNode() self.marcadorNP.remove() self.barraEnergia.destroy() del self.marcador del self.barraEnergia #self.inicializarMenu() # Almacena la puntuacion del jugador def almacenarPuntuacion(self, valor): self.crearBDD() db = sqlite3.connect("datos.db") cursor = db.cursor() parametros = (valor, self.puntos) cursor.execute("insert into puntuaciones values (?, ?)", parametros) db.commit() cursor.close() self.entrada.destroy() self.mostrarTopPuntuacion() self.inicializarMenu() # Crea la Base de Datos si no existe ya def crearBDD(self): db = sqlite3.connect("datos.db") cursor = db.cursor() args = ("puntuaciones",) cursor.execute("select name from sqlite_master where name = ?", args) if len(cursor.fetchall()) == 0: cursor.execute("create table puntuaciones (nombre text, puntuacion numeric)") db.commit() cursor.close() # Muestra las 10 mejores puntuaciones def mostrarTopPuntuacion(self): # Extrae las 10 mejores puntuaciones de la base de datos db = sqlite3.connect("datos.db") cursor = db.cursor() cursor.execute("select nombre, puntuacion from puntuaciones order by puntuacion desc limit 10") puntuaciones = cursor.fetchall() cursor.close() resultado = "-- MEJORES PUNTUACIONES --\n-Jugador- -Puntuacion-\n\n" for nombre, puntuacion in puntuaciones: resultado += nombre + " " + str(puntuacion) + "\n" # Muestra las 10 mejores puntuaciones self.ranking = TextNode("Ranking") self.ranking.setText(resultado) self.ranking.setCardColor(0, 0, 0, 1) self.ranking.setCardDecal(True) self.ranking.setCardAsMargin(0.4, 0.4, 0.4, 0.4) self.rankingNP = aspect2d.attachNewNode(self.ranking) self.rankingNP.reparentTo(base.a2dTopLeft) self.rankingNP.setPos(1, 0, -1) self.rankingNP.setScale(0.07) # Muestra el mensaje de fin de partida def mostrarFinPartida(self): self.marcadorFinal = TextNode("Marcador Final") self.marcadorFinal.setText("Game Over!\nPuntuacion: " + str(self.ship.puntos) +"\n\n" + "Escribe tu nombre:") self.marcadorFinal.setCardColor(0, 0, 0, 1) self.marcadorFinal.setCardDecal(True) self.marcadorFinal.setCardAsMargin(0.4, 0.4, 0.4, 0.4) self.marcadorFinalNP = aspect2d.attachNewNode(self.marcadorFinal) self.marcadorFinalNP.setPos(-0.3, 0, 0.5) self.marcadorFinalNP.setScale(0.07) # Muestra un menu con las opciones durante el juego def mostrarMenuJuego(self): self.textoMenu = {} self.textoMenu["titulo"] = OnscreenText(text = "", pos = (0, 0.92), scale = 0.08, fg = (1, 1, 1, 1), bg = (0, 0, 1, 0.7)) self.textoMenu["descripcion"] = OnscreenText(text = "", pos = (0, 0.84), scale = 0.05, fg = (1, 1, 0, 1), bg = (0, 0, 0, 0.5)) self.textoMenu["opciones"] = OnscreenText(text = "", pos = (-1.3, 0), scale = 0.05, fg = (1, 1, 1, 1), bg = (1, 0.3, 0, 0.6), align=TextNode.ALeft, wordwrap = 15) self.textoMenu["opciones"].setText("** OPCIONES **\n" + "m = ocultar menu\n" + "q = salir") # Inicialmente el menu se deja oculto for linea in self.textoMenu.values(): linea.hide() # Muestra / Oculta el menu de juego def cambiarMenuJuego(self): for linea in self.textoMenu.values(): if linea.isHidden(): linea.show() else: linea.hide() # Sale del juego def salir(self): print("Saliendo . . .") sys.exit()
def __init__(self, showbase): self.showbase = showbase self.ready = False self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/mainmenu/menu.png', parent = self.showbase.render2d, ) self.title = OnscreenText( text = 'Lobby!', fg = (1, 1, 1, 1), parent = self.background, pos = (-0.6, 0.1), scale = 0.06 ) self.buttons = [] controlButtons = Vec3(-0.60, 0, -0.79) # Toggle ready p = controlButtons + Vec3(-0.25, 0, 0) self.toggleReadyButton = DirectButton( text = 'Ready/Unready', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.toggleReady, ) self.buttons.append(self.toggleReadyButton) # Disconnect p = controlButtons + Vec3(0.0, 0.0, 0.0) self.disconnectButton = DirectButton( text = 'Disconnect', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.disconnect, ) self.buttons.append(self.disconnectButton) # Send message p = controlButtons + Vec3(0.25, 0.0, 0.0) self.sendMessageButton = DirectButton( text = 'Send Message', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.sendMessage, extraArgs = [''], ) self.buttons.append(self.sendMessageButton) # Message input self.message = DirectEntry( command = self.sendMessage, focusInCommand = self.clearText, frameSize = (-3, 3, -.5, 1), initialText = '', parent = self.buttons[2], pos = (0, -0.6, -1.5), text_align = TextNode.ACenter, ) self.showbase.gameData = GameData() self.showbase.users = [] self.hide()
class Query: def __init__(self, scale, font, color, text_size, suggestions_text_size, query_delay): self.scale = scale self.font = font self.color = color self.text_size = text_size self.suggestions_text_size = suggestions_text_size self.query_delay = query_delay self.background = None self.prefix = None self.query = None self.suggestions = None self.owner = None self.current_selection = None self.current_list = [] self.completion_task = None self.max_columns = 4 self.max_lines = 3 self.max_elems = self.max_columns * self.max_lines def do_query(self, text): body = None if self.current_selection is not None: if self.current_selection < len(self.current_list): body = self.current_list[self.current_selection][1] else: text = self.query.get() body = self.owner.get_object(text) self.owner.select_object(body) self.close() def close(self): self.background.destroy() self.background = None self.prefix.destroy() self.prefix = None self.query.destroy() self.query = None self.suggestions.destroy() self.suggestions = None self.current_selection = None self.current_list = [] if self.completion_task is not None: taskMgr.remove(self.completion_task) self.completion_task = None def escape(self, event): self.close() def update_suggestions(self): if self.current_selection is not None: page = self.current_selection // self.max_elems else: page = 0 start = page * self.max_elems end = min(start + self.max_elems - 1, len(self.current_list) - 1) suggestions = "" for i in range(start, end + 1): if i != start and ((i - start) % self.max_columns) == 0: suggestions += '\n' if i == self.current_selection: suggestions += "\1md_bold\1%s\2" % self.current_list[i][0] else: suggestions += self.current_list[i][0] suggestions += '\t' self.suggestions.setText(suggestions) def completion(self, event): text = self.query.get() if text != '': self.current_list = self.owner.list_objects(text) else: self.current_list = [] self.current_selection = None if self.completion_task is not None: taskMgr.remove(self.completion_task) self.completion_task = taskMgr.doMethodLater(self.query_delay, self.update_suggestions, 'completion task', extraArgs=[]) def select(self, event): modifiers = event.getModifierButtons() if modifiers.isDown(KeyboardButton.shift()): incr = -1 else: incr = 1 if self.current_selection is not None: new_selection = self.current_selection + incr else: new_selection = 0 if new_selection < 0: new_selection = len(self.current_list) - 1 if new_selection >= len(self.current_list): new_selection = 0 self.current_selection = new_selection self.update_suggestions() def open_query(self, owner): self.owner = owner bg_color = LColor(*self.color) bg_color[3] = 0.2 scale3 = LVector3(self.scale[0], 1.0, self.scale[1]) self.background = DirectFrame( frameColor=bg_color, frameSize=(-1 / self.scale[0], 1.0 / self.scale[0], 0.15 + self.scale[1] * self.text_size, 0.0), parent=base.a2dBottomLeft) self.prefix = OnscreenText( text=_("Target name:"), font=self.font, fg=self.color, align=TextNode.ALeft, parent=base.a2dBottomLeft, scale=tuple(self.scale * self.text_size), pos=(0, .15), ) bounds = self.prefix.getTightBounds() length = bounds[1][0] - bounds[0][ 0] + self.scale[0] * self.text_size / 2 self.query = DirectEntry(text="", text_fg=self.color, scale=tuple(scale3 * self.text_size), command=self.do_query, parent=base.a2dBottomLeft, frameColor=(0, 0, 0, 0), pos=(length, 0, .15), initialText="", numLines=1, width=200, entryFont=self.font, focus=1, suppressKeys=1) self.query.bind("press-escape-", self.escape) self.query.bind("press-tab-", self.select) self.query.accept(self.query.guiItem.getTypeEvent(), self.completion) self.query.accept(self.query.guiItem.getEraseEvent(), self.completion) pos = self.prefix.getPos() bounds = self.query.getBounds() llz = bounds[2] / self.text_size self.suggestions = OnscreenText( text="", font=self.font, fg=self.color, align=TextNode.ALeft, mayChange=True, parent=base.a2dBottomLeft, scale=tuple(self.scale * self.suggestions_text_size), pos=(pos[0], pos[1] + llz), )
class ChatBox(DirectObject): MESSAGE_LIFE = 10 MAX_NUM_MESSAGES = 15 (TYPE_GLOBAL, TYPE_TEAM, TYPE_CONSOLE) = range(3) messageTypeToPrefix = { TYPE_GLOBAL : 'Global:', TYPE_TEAM : 'Team:', TYPE_CONSOLE : 'Console' } def __init__(self): self.textNodes = [] self.messageType = None self.rootFrame = DirectFrame(pos = (0.03, 0, 0.2), frameColor = (0, 0, 0, 0), frameSize = (0, 1, 0, 1), parent = base.a2dBottomLeft) self.rootFrame.setBin('fixed', GUIOrder.ORDER[GUIOrder.CHAT]) self.entryFrame = DirectFrame(pos = (0, 0, 0), frameColor = (0, 0, 0, 0.1), frameSize = (0, 1, 0, 0.1), parent = self.rootFrame) self.chatarea = DirectEntry(width = 27, scale = Settings.CHAT_HEIGHT, pos = (0, 0, 0), frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), numLines = 1, cursorKeys = 1, rolloverSound = None, clickSound = None, focus = 0, command = self.OnChatEntered, parent = self.entryFrame) self.typeText = OnscreenText(text = '', pos = (0, Settings.CHAT_HEIGHT + 0.01), scale = Settings.CHAT_HEIGHT, fg = (1, 1, 1, 1), mayChange = True, align = TextNode.ALeft, parent = self.entryFrame) self.displayFrame = DirectFrame(pos = (0, 0, 0.1), frameColor = (0, 0, 0, 0), frameSize = (0, 1, 0, 0.42), parent = self.rootFrame) self.chatarea.enterText('') self.entryFrame.hide() self.chatarea['focus'] = 0 self.chatarea.setFocus() def OnChatEntered(self, enteredText): enteredText = enteredText.strip() self.Hide() if(len(enteredText) > 0): ChatEnteredEvent(self.messageType, enteredText).Fire() def AddMessage(self, prefix, prefixColor, message): parent = self.displayFrame.attachNewNode('messageParent') prefixTextNode = TextNode('prefixMessage') prefixTextNode.setText(prefix) prefixTextNode.setTextColor(prefixColor) prefixTextNode.setShadow(0.05, 0.05) prefixTextNode.setShadowColor(Globals.COLOR_BLACK) prefixTextNodePath = parent.attachNewNode(prefixTextNode) prefixTextNodePath.setScale(Settings.CHAT_HEIGHT) messageTextNode = TextNode('prefixMessage') messageTextNode.setText(message) messageTextNode.setTextColor(1, 1, 1, 1) messageTextNode.setShadow(0.05, 0.05) messageTextNode.setShadowColor(Globals.COLOR_BLACK) messageTextNodePath = parent.attachNewNode(messageTextNode) messageTextNodePath.setScale(Settings.CHAT_HEIGHT) messageTextNodePath.setPos(Vec3(prefixTextNode.calcWidth(prefix) * Settings.CHAT_HEIGHT, 0, 0)) taskMgr.remove('HideMessageLog') taskMgr.doMethodLater(ChatBox.MESSAGE_LIFE, self.HideMessageLog, 'HideMessageLog') self.ShowMessageLog() self.textNodes.append(parent) if(len(self.textNodes) > ChatBox.MAX_NUM_MESSAGES): self.RemoveMessage(self.textNodes[0]) self.RedrawMessages() def RedrawMessages(self): n = len(self.textNodes) for i, textNode in enumerate(self.textNodes): LerpPosInterval(textNode, 0.5, (0, 0, (n-i) * (Settings.CHAT_HEIGHT + 0.01))).start() def RemoveMessage(self, textNode): self.textNodes.remove(textNode) textNode.removeNode() def HideMessageLog(self, task = None): self.displayFrame.hide() def ShowMessageLog(self): self.displayFrame.show() def Hide(self): self.chatarea.enterText('') self.entryFrame.hide() self.chatarea['focus'] = 0 self.chatarea.setFocus() self.HideMessageLog() ChatCloseEvent().Fire() def Show(self, messageType): self.messageType = messageType self.entryFrame.show() self.chatarea['focus'] = 1 self.chatarea.setFocus() self.typeText.setText(ChatBox.GetPrefix(self.messageType)) self.ShowMessageLog() ChatOpenEvent().Fire() def EnableKeyboardListening(self): self.acceptOnce('escape', self.Hide) def DisableKeyboardListening(self): self.ignoreAll() @staticmethod def GetPrefix(messageType): return ChatBox.messageTypeToPrefix[messageType] def Destroy(self): taskMgr.remove('HideMessageLog') self.rootFrame.destroy() self.entryFrame.destroy() self.chatarea.destroy() self.typeText.destroy() self.displayFrame.destroy() self.ignoreAll()