class CogdoMazeBossGui(DirectFrame): def __init__(self, code): DirectFrame.__init__(self, relief=None, state=DGG.NORMAL, sortOrder=DGG.BACKGROUND_SORT_INDEX) self._code = str(code) self._codeLength = len(self._code) self._markersShown = 0 self._markers = [] self._initModel() self.setPos(*Globals.BossGuiPos) self.setScale(Globals.BossGuiScale) self.hide() def destroy(self): ToontownIntervals.cleanup('bosscodedoor') self._model.removeNode() del self._model self._titleLabel.removeNode() del self._titleLabel for marker in self._markers: marker.destroy() del self._markers DirectFrame.destroy(self) def _initModel(self): codeFrameGap = Globals.BossCodeFrameGap codeFrameWidth = Globals.BossCodeFrameWidth self._model = CogdoUtil.loadMazeModel('bossCog', group='gui') self._model.reparentTo(self) self._model.find('**/frame').setBin('fixed', 1) titleLabelPos = self._model.find('**/title_label_loc').getPos() self._titleLabel = DirectLabel(parent=self, relief=None, scale=Globals.BossGuiTitleLabelScale, text=TTLocalizer.CogdoMazeGameBossGuiTitle.upper(), pos=titleLabelPos, text_align=TextNode.ACenter, text_fg=(0, 0, 0, 1), text_shadow=(0, 0, 0, 0), text_font=ToontownGlobals.getSuitFont()) self._titleLabel.setBin('fixed', 1) bossCard = self._model.find('**/bossCard') self._openDoor = self._model.find('**/doorOpen') self._closedDoor = self._model.find('**/doorClosed') self._openDoor.stash() spacingX = codeFrameWidth + codeFrameGap startX = -0.5 * ((self._codeLength - 1) * spacingX - codeFrameGap) for i in range(self._codeLength): marker = CogdoMazeBossCodeFrame(i, self._code[i], bossCard) marker.reparentTo(self) marker.setPos(bossCard, startX + spacingX * i, 0, 0) self._markers.append(marker) bossCard.removeNode() def showHit(self, bossIndex): self._markers[bossIndex].setHit(True) def showNumber(self, bossIndex): self._markers[bossIndex].setHit(False) self._markers[bossIndex].showNumber() self._markersShown += 1 if self._markersShown == self._codeLength: self._openDoor.unstash() self._closedDoor.stash() ToontownIntervals.start(ToontownIntervals.getPulseLargerIval(self._openDoor, 'bosscodedoor'))
class ScavengerHuntEffect: images = None def __init__(self, beanAmount): if not ScavengerHuntEffect.images: ScavengerHuntEffect.images = loader.loadModel('phase_4/models/props/tot_jar') self.npRoot = DirectFrame(parent=aspect2d, relief=None, scale=0.75, pos=(0, 0, 0.6)) if beanAmount > 0: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.jar = DirectFrame(parent=self.npRoot, relief=None, image=ScavengerHuntEffect.images.find('**/tot_jar')) self.jar.hide() self.eventImage = NodePath('EventImage') self.eventImage.reparentTo(self.npRoot) self.countLabel = DirectLabel(parent=self.jar, relief=None, text='+0', text_pos=(0.02, -0.2), text_scale=0.25, text_fg=(0.95, 0.0, 0, 1), text_font=ToontownGlobals.getSignFont()) def countUp(t, startVal, endVal): beanCountStr = startVal + t * (endVal - startVal) self.countLabel['text'] = '+' + `(int(beanCountStr))` def setCountColor(color): self.countLabel['text_fg'] = color self.track = Sequence(LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(1), Func(self.jar.show), LerpColorScaleInterval(self.eventImage, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Parallel(LerpScaleInterval(self.npRoot, 1, scale=0.5, startScale=0.75), LerpPosInterval(self.npRoot, 1, pos=VBase3(-0.9, 0, -0.83))), LerpFunc(countUp, duration=2, extraArgs=[0, beanAmount]), Func(setCountColor, VBase4(0.95, 0.95, 0, 1)), Wait(3), Func(self.destroy)) else: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.attemptFailedMsg() self.track = Sequence(LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(5), LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Func(self.destroy)) def play(self): if self.npRoot: self.track.start() def stop(self): if self.track != None and self.track.isPlaying(): self.track.finish() def destroy(self): self.stop() self.track = None if hasattr(self, 'eventImage') and self.eventImage: self.eventImage.detachNode() del self.eventImage if hasattr(self, 'countLabel') and self.countLabel: self.countLabel.destroy() del self.countLabel if hasattr(self, 'jar') and self.jar: self.jar.destroy() del self.jar if hasattr(self, 'npRoot') and self.npRoot: self.npRoot.destroy() del self.npRoot
def __init__(self): # # Player status section # heartscale = (0.1, 1, 0.1) self.heart1 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.2, 0, -0.15)) self.heart1.setTransparency(True) self.heart1.reparentTo(base.a2dTopLeft) self.heart2 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.45, 0, -0.15)) self.heart2.setTransparency(True) self.heart2.reparentTo(base.a2dTopLeft) self.heart3 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.7, 0, -0.15)) self.heart3.setTransparency(True) self.heart3.reparentTo(base.a2dTopLeft) self.keys = DirectLabel( text = "x0", frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), text_scale = 1.8, text_pos = (1, -0.25, 0), text_align = TextNode.ALeft, image = "Keys.png", pos = (0.2, 0, -0.4)) self.keys.setScale(0.085) self.keys.setTransparency(True) self.keys.reparentTo(base.a2dTopLeft) self.actionKey = DirectLabel( frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), scale = 0.15, pos = (0, 0, 0.15), text = _("Action: E/Enter")) self.actionKey.setTransparency(True) self.actionKey.reparentTo(base.a2dBottomCenter) self.actionKey.hide()
def __init__(self, phaseNames): self.phaseNames = phaseNames self.model = loader.loadModel('models/gui/pir_m_gui_gen_loadingBar') bar = self.model.findTexture('pir_t_gui_gen_loadingBar') self.model.find('**/loading_bar').hide() self.topFrame = DirectFrame(parent = base.a2dTopRight, pos = (-0.80000000000000004, 0, -0.10000000000000001), sortOrder = NO_FADE_SORT_INDEX + 1) self.text = DirectLabel(relief = None, parent = self.topFrame, guiId = 'DownloadWatcherText', pos = (0, 0, 0), text = ' ', text_fg = (1, 1, 1, 1), text_shadow = (0, 0, 0, 1), text_scale = 0.040000000000000001, textMayChange = 1, text_align = TextNode.ARight, text_pos = (0.17000000000000001, 0), sortOrder = 2) self.bar = DirectWaitBar(relief = None, parent = self.topFrame, guiId = 'DownloadWatcherBar', pos = (0, 0, 0), frameSize = (-0.40000000000000002, 0.38, -0.044999999999999998, 0.065000000000000002), borderWidth = (0.02, 0.02), range = 100, frameColor = (1, 1, 1, 1), barColor = (0, 0.29999999999999999, 0, 1), barTexture = bar, geom = self.model, geom_scale = 0.089999999999999997, geom_pos = (-0.014, 0, 0.01), text = '0%', text_scale = 0.040000000000000001, text_fg = (1, 1, 1, 1), text_align = TextNode.ALeft, text_pos = (0.19, 0), sortOrder = 1) self.bgFrame = DirectFrame(relief = DGG.FLAT, parent = self.topFrame, pos = (0, 0, 0), frameColor = (0.5, 0.27000000000000002, 0.35999999999999999, 0.20000000000000001), frameSize = (-0.44, 0.39000000000000001, -0.035999999999999997, 0.056000000000000001), borderWidth = (0.02, 0.02), scale = 0.90000000000000002, sortOrder = 0) self.accept('launcherPercentPhaseComplete', self.update)
class PiratesDownloadWatcher(DownloadWatcher.DownloadWatcher): positions = [ (Point3(1, 0, 0.90000000000000002), Point3(1, 0, 0.90000000000000002)), (Point3(1, 0, 0.90000000000000002), Point3(1, 0, 0.90000000000000002)), (Point3(1, 0, 0.90000000000000002), Point3(1, 0, 0.90000000000000002))] def __init__(self, phaseNames): self.phaseNames = phaseNames self.model = loader.loadModel('models/gui/pir_m_gui_gen_loadingBar') bar = self.model.findTexture('pir_t_gui_gen_loadingBar') self.model.find('**/loading_bar').hide() self.topFrame = DirectFrame(parent = base.a2dTopRight, pos = (-0.80000000000000004, 0, -0.10000000000000001), sortOrder = NO_FADE_SORT_INDEX + 1) self.text = DirectLabel(relief = None, parent = self.topFrame, guiId = 'DownloadWatcherText', pos = (0, 0, 0), text = ' ', text_fg = (1, 1, 1, 1), text_shadow = (0, 0, 0, 1), text_scale = 0.040000000000000001, textMayChange = 1, text_align = TextNode.ARight, text_pos = (0.17000000000000001, 0), sortOrder = 2) self.bar = DirectWaitBar(relief = None, parent = self.topFrame, guiId = 'DownloadWatcherBar', pos = (0, 0, 0), frameSize = (-0.40000000000000002, 0.38, -0.044999999999999998, 0.065000000000000002), borderWidth = (0.02, 0.02), range = 100, frameColor = (1, 1, 1, 1), barColor = (0, 0.29999999999999999, 0, 1), barTexture = bar, geom = self.model, geom_scale = 0.089999999999999997, geom_pos = (-0.014, 0, 0.01), text = '0%', text_scale = 0.040000000000000001, text_fg = (1, 1, 1, 1), text_align = TextNode.ALeft, text_pos = (0.19, 0), sortOrder = 1) self.bgFrame = DirectFrame(relief = DGG.FLAT, parent = self.topFrame, pos = (0, 0, 0), frameColor = (0.5, 0.27000000000000002, 0.35999999999999999, 0.20000000000000001), frameSize = (-0.44, 0.39000000000000001, -0.035999999999999997, 0.056000000000000001), borderWidth = (0.02, 0.02), scale = 0.90000000000000002, sortOrder = 0) self.accept('launcherPercentPhaseComplete', self.update) def update(self, phase, percent, reqByteRate, actualByteRate): phaseName = self.phaseNames[phase] self.text['text'] = OTPLocalizer.DownloadWatcherUpdate % phaseName + ' -' self.bar['text'] = '%s %%' % percent self.bar['value'] = percent def foreground(self): self.topFrame.reparentTo(base.a2dpTopRight) self.topFrame.setBin('gui-fixed', 55) self.topFrame['sortOrder'] = NO_FADE_SORT_INDEX + 1 def background(self): self.topFrame.reparentTo(base.a2dTopRight) self.topFrame.setBin('unsorted', 49) self.topFrame['sortOrder'] = -1 def cleanup(self): self.text.destroy() self.bar.destroy() self.bgFrame.destroy() self.topFrame.destroy() self.ignoreAll()
def __init__(self): self.winXhalf = base.win.getXSize() / 2 self.winYhalf = base.win.getYSize() / 2 croshairsize = 0.05#17.0 self.crosshair = OnscreenImage( image = os.path.join("..", "data", "crosshair.png"), scale = (croshairsize, 1, croshairsize), #pos = (self.winXhalf - croshairsize/2.0, 0, -self.winYhalf - croshairsize/2.0) pos = (0, 0, 0) ) self.crosshair.setTransparency(1) self.ammo = DirectLabel( scale = 0.15, text = "100/100", pos = (base.a2dLeft + 0.025, 0.0, base.a2dBottom + 0.05), text_align = TextNode.ALeft, frameColor = (0, 0, 0, 0), text_fg = (1,1,1,1), text_shadow = (0, 0, 0, 1), text_shadowOffset = (0.05, 0.05) ) self.ammo.setTransparency(1) self.nowPlaying = DirectLabel( scale = 0.05, text = "Now Playing: Echovolt - Nothing to Fear", pos = (base.a2dLeft + 0.025, 0.0, base.a2dTop - 0.05), text_align = TextNode.ALeft, frameColor = (0, 0, 0, 0), text_fg = (1,1,1,1) ) self.nowPlaying.setTransparency(1) self.accept("window-event", self.recalcAspectRatio) self.hide()
def __init__(self): #self.accept("RatioChanged", self.recalcAspectRatio) self.accept("window-event", self.recalcAspectRatio) self.frameMain = DirectFrame( # size of the frame frameSize = (base.a2dLeft, base.a2dRight, base.a2dTop, base.a2dBottom), # position of the frame pos = (0, 0, 0), # tramsparent bg color frameColor = (0, 0, 0, 0), sortOrder = 0) self.background = OnscreenImage("MenuBGLogo.png") self.background.reparentTo(self.frameMain) self.nowPlaying = DirectLabel( scale = 0.05, text = "Now Playing: Eraplee Noisewall Orchestra - Bermuda Fire", pos = (base.a2dLeft + 0.025, 0.0, base.a2dBottom + 0.05), text_align = TextNode.ALeft, frameColor = (0, 0, 0, 0), text_fg = (1,1,1,1) ) self.nowPlaying.setTransparency(1) self.nowPlaying.reparentTo(self.frameMain) maps = loader.loadModel('button_maps.egg') btnGeom = (maps.find('**/ButtonReady'), maps.find('**/ButtonClick'), maps.find('**/ButtonRollover'), maps.find('**/ButtonDisabled')) self.btnStart = self.createButton("Start", btnGeom, 0.25, self.btnStart_Click) self.btnStart.reparentTo(self.frameMain) self.btnQuit = self.createButton("Quit", btnGeom, -0.25, self.btnQuit_Click) self.btnQuit.reparentTo(self.frameMain) self.recalcAspectRatio(base.win) # hide all buttons at startup self.hide()
def _initModel(self): codeFrameGap = Globals.BossCodeFrameGap codeFrameWidth = Globals.BossCodeFrameWidth self._model = CogdoUtil.loadMazeModel('bossCog', group='gui') self._model.reparentTo(self) self._model.find('**/frame').setBin('fixed', 1) titleLabelPos = self._model.find('**/title_label_loc').getPos() self._titleLabel = DirectLabel(parent=self, relief=None, scale=Globals.BossGuiTitleLabelScale, text=TTLocalizer.CogdoMazeGameBossGuiTitle.upper(), pos=titleLabelPos, text_align=TextNode.ACenter, text_fg=(0, 0, 0, 1), text_shadow=(0, 0, 0, 0), text_font=ToontownGlobals.getSuitFont()) self._titleLabel.setBin('fixed', 1) bossCard = self._model.find('**/bossCard') self._openDoor = self._model.find('**/doorOpen') self._closedDoor = self._model.find('**/doorClosed') self._openDoor.stash() spacingX = codeFrameWidth + codeFrameGap startX = -0.5 * ((self._codeLength - 1) * spacingX - codeFrameGap) for i in range(self._codeLength): marker = CogdoMazeBossCodeFrame(i, self._code[i], bossCard) marker.reparentTo(self) marker.setPos(bossCard, startX + spacingX * i, 0, 0) self._markers.append(marker) bossCard.removeNode()
class CogdoMazeBossGui(DirectFrame): def __init__(self, code): DirectFrame.__init__(self, relief=None, state=DGG.NORMAL, sortOrder=DGG.BACKGROUND_SORT_INDEX) self._code = str(code) self._codeLength = len(self._code) self._markersShown = 0 self._markers = [] self._initModel() self.setPos(*Globals.BossGuiPos) self.setScale(Globals.BossGuiScale) self.hide() def destroy(self): ToontownIntervals.cleanup('bosscodedoor') self._model.removeNode() del self._model self._titleLabel.removeNode() del self._titleLabel for marker in self._markers: marker.destroy() del self._markers DirectFrame.destroy(self) def _initModel(self): codeFrameGap = Globals.BossCodeFrameGap codeFrameWidth = Globals.BossCodeFrameWidth self._model = CogdoUtil.loadMazeModel('bossCog', group='gui') self._model.reparentTo(self) self._model.find('**/frame').setBin('fixed', 1) titleLabelPos = self._model.find('**/title_label_loc').getPos() self._titleLabel = DirectLabel( parent=self, relief=None, scale=Globals.BossGuiTitleLabelScale, text=TTLocalizer.CogdoMazeGameBossGuiTitle.upper(), pos=titleLabelPos, text_align=TextNode.ACenter, text_fg=(0, 0, 0, 1), text_shadow=(0, 0, 0, 0), text_font=ToontownGlobals.getSuitFont()) self._titleLabel.setBin('fixed', 1) bossCard = self._model.find('**/bossCard') self._openDoor = self._model.find('**/doorOpen') self._closedDoor = self._model.find('**/doorClosed') self._openDoor.stash() spacingX = codeFrameWidth + codeFrameGap startX = -0.5 * ((self._codeLength - 1) * spacingX - codeFrameGap) for i in range(self._codeLength): marker = CogdoMazeBossCodeFrame(i, self._code[i], bossCard) marker.reparentTo(self) marker.setPos(bossCard, startX + spacingX * i, 0, 0) self._markers.append(marker) bossCard.removeNode() def showHit(self, bossIndex): self._markers[bossIndex].setHit(True) def showNumber(self, bossIndex): self._markers[bossIndex].setHit(False) self._markers[bossIndex].showNumber() self._markersShown += 1 if self._markersShown == self._codeLength: self._openDoor.unstash() self._closedDoor.stash() ToontownIntervals.start( ToontownIntervals.getPulseLargerIval(self._openDoor, 'bosscodedoor'))
class MPBtn(GameObject): tooltip_align = TextNode.A_right tooltip_offset = (.01, 0, -.08) def __init__(self, parent, owner, menu_args, img_path, msg_btn_x, cb, usr_name, tooltip): GameObject.__init__(self) self.owner = owner lab_args = menu_args.label_args lab_args['scale'] = .046 #lab_args['text_fg'] = menu_args.text_normal self.btn = ImgBtn(parent=parent, scale=.024, pos=(msg_btn_x, 1, .01), frameColor=(1, 1, 1, 1), frameTexture=img_path, command=cb, extraArgs=[usr_name], **menu_args.imgbtn_args) self.btn.bind(ENTER, self.on_enter) self.btn.bind(EXIT, self.on_exit) self.tooltip_btn = DirectButton(parent=parent, scale=.024, pos=(msg_btn_x, 1, .01), frameColor=(1, 1, 1, 0), frameSize=(-1, 1, -1, 1), command=None, **menu_args.imgbtn_args) self.tooltip_btn.bind(ENTER, self.on_enter) self.tooltip_btn.bind(EXIT, self.on_exit) self.on_create() self.tooltip = DirectLabel(text=tooltip, pos=self.btn.get_pos() + self.tooltip_offset, parent=parent, text_wordwrap=10, text_bg=(.2, .2, .2, .8), text_align=self.tooltip_align, **lab_args) self.tooltip.set_bin('gui-popup', 10) self.tooltip.hide() def on_create(self): self.btn.hide() self.tooltip_btn.hide() def is_hidden(self): return self.btn.is_hidden() def show(self): if self.btn['state'] == DISABLED: self.tooltip_btn.show() else: self.tooltip_btn.hide() return self.btn.show() def hide(self): self.tooltip_btn.hide() return self.btn.hide() def enable(self): self.tooltip_btn.hide() return self.btn.enable() def disable(self): self.tooltip_btn.show() return self.btn.disable() def on_enter(self, pos): self.owner.on_enter(pos) self.tooltip.show() def on_exit(self, pos): self.owner.on_exit(pos) self.tooltip.hide()
class Vehicle: """A steerable point mass with various steering behaviors.""" # FIXME: One fix that is needed is that wanderSide and wanderUp should be # reset whenever a character switches back to the wander behaviour. This # might prevent wandering characters from 'hugging' obstacles and # containers when wandering is combined with obstacle avoidance and/or # containment. What happens is that the characters wanders into the # obstacle, avoidance takes over and steers the character away from it, # then when wandering gets control again it picks up where it left off -- # steering toward the obstacle. # # So make Vehicle a state-machine, with the state being the currently # active steering behaviour, so that there can be transition-in and # transition-out functions for steering behaviours? def __init__(self,pos=None,mass=1,maxforce=0.1,maxspeed=1,radius=1, avoidVehicles=True,avoidObstacles=True,container=None): """Initialise the vehicle.""" self.mass = mass # mass = 1 means that acceleration = force self.maxforce = maxforce self.maxspeed = maxspeed self.radius = radius self.avoidVehicles = avoidVehicles # Avoid colliding with other Vehicles self.avoidObstacles = avoidObstacles # Avoid colliding with obstacles if pos is None: pos = Point3(0,0,0) # The Vehicle controls a primary NodePath to which other NodePath's for # CollisionSolids are parented. Other nodes, such as animated Actors, # can be attached to this NodePath by user classes. self.prime = NodePath('Vehicle primary NodePath') self.prime.reparentTo(render) self.prime.setPos(pos) # If the Vehicle finds itself outside of its container it will turn # back toward the container. The vehicle also stays within the global # container at all times. The idea is that Vehicle.container can be # used to restrict one particular vehicle to a space smaller than the # global container. self.container = container self._pos = SteerVec(pos.getX(),pos.getY()) # 2D pos for steering # calculations self._velocity = SteerVec(0,0) self._steeringforce = SteerVec(0,0) self._steeringbehavior = [] # Some steering behaviors make use of self._target, which can be # another Vehicle or a point in 2-space (SteerVec), or it might be None # indicating that no target is currently in use. self._target = None # Initialise the Vehicle's CollisionRay which is used with a # CollisionHandlerFloor to keep the Vehicle on the ground. self.raynp = self.prime.attachNewNode(CollisionNode('colNode')) self.raynp.node().addSolid(CollisionRay(0,0,3,0,0,-1)) self.floorhandler = CollisionHandlerFloor() self.floorhandler.addCollider(self.raynp,self.prime) cTrav.addCollider(self.raynp,self.floorhandler) # Uncomment this line to show the CollisionRay: #self.raynp.show() # We only want our CollisionRay to collide with the collision # geometry of the terrain only, se we set a mask here. self.raynp.node().setFromCollideMask(floorMASK) self.raynp.node().setIntoCollideMask(offMASK) # Initialise CollisionTube for detecting oncoming obstacle collisions. x,y,z = self.prime.getX(),self.prime.getY(),self.prime.getZ()+3 #FIXME: Don't hardcode how high the tube goes, add height parameter to __init__ for both tube and sphere vx,vy = self._velocity.getX(),self._velocity.getY() r = self.radius f = self.prime.getNetTransform().getMat().getRow3(1) s = 10 self.tube = CollisionTube(x,y,z,x+f.getX()*s,y+f.getY()*s,z,self.radius) self.tubenp = self.prime.attachNewNode(CollisionNode('colNode')) self.tubenp.node().addSolid(self.tube) # The tube should only collide with obstacles (and is an 'into' object) self.tubenp.node().setFromCollideMask(offMASK) self.tubenp.node().setIntoCollideMask(obstacleMASK) # Uncomment this line to show the CollisionTube #self.tubenp.show() # CollisionSphere for detecting when we've actuallyt collided with # something. self.sphere = CollisionSphere(x,y,z,self.radius) self.spherenp = self.prime.attachNewNode(CollisionNode('cnode')) self.spherenp.node().addSolid(self.sphere) # Only collide with the CollisionSphere's of other vehicles. self.spherenp.node().setFromCollideMask(obstacleMASK) # So the spheres of vehicles will collide with eachother self.spherenp.node().setIntoCollideMask(obstacleMASK) # So obstacles will collide into spheres of vehicles cTrav.addCollider(self.spherenp,collisionHandler) # Uncomment this line to show the CollisionSphere #self.spherenp.show() # Add a task for this Vehicle to the global task manager. self._prevtime = 0 self.stepTask=taskMgr.add(self._step,"Vehicle step task") # Add the Vehicle to the global list of Vehicles vehicles.append(self) # Initialise the DirectLabel used when annotating the Vehicle # FIXME: Needs to be destroyed in self.destroy self.text = "no steering" self.label = DirectLabel(parent=self.prime,pos=(4,4,4),text=self.text, text_wordwrap=10,relief=None, text_scale=(1.5,1.5),text_frame=(0,0,0,1), text_bg=(1,1,1,1)) self.label.component('text0').textNode.setCardDecal(1) self.label.setBillboardAxis() self.label.hide() self.label.setLightOff(1) # A second label for speaking ('Ouch!', 'Sorry!' etc.) self.callout = DirectLabel(parent=self.prime,pos=(4,4,4),text='', text_wordwrap=10,relief=None, text_scale=(1.5,1.5),text_frame=(0,0,0,1), text_bg=(1,1,1,1)) self.callout.component('text0').textNode.setCardDecal(1) self.callout.setBillboardAxis() self.callout.hide() self.callout.setLightOff(1) def destroy(self): """Prepare this Vehicle to be garbage-collected by Python: Remove all of the Vehicle's nodes from the scene graph, remove its CollisionSolids from the global CollisionTraverser, clear its CollisionHandler, remove tasks After executing this method, any remaining references to the Vehicle object can be destroyed by the user module, and the Vehicle will be garbage-collected by Python. """ cTrav.removeCollider(self.raynp) cTrav.removeCollider(self.spherenp) self.floorhandler.clearColliders() self.floorhandler = None self.prime.removeNode() taskMgr.remove(self.stepTask) vehicles.remove(self) def getspeed(self): """Return the speed (not the velocity) of this vehicle (float).""" return self._velocity.length() def getX(self): """Convenience method for accessing self._pos.getX()""" return self._pos.getX() def getY(self): """Convenience method for accessing self._pos.getY()""" return self._pos.getY() def getForward(self): """Return this vehicle's forward direction, a unit vector (SteerVec). """ forward = SteerVec(self._velocity.getX(),self._velocity.getY()) forward.normalize() return forward def getRight(self): """Return this vehicle's right direction, a unit vector (SteerVec). """ right = self._velocity.rotate(90) right.normalize() return right def predictFuturePosition(self, predictionTime): """ Return the predicted position (SteerVec) of this vehicle predictionTime units in the future using a simple linear predictor. """ return self._pos + (self._velocity * predictionTime) # Public methods used to activate steering behaviors. Once a steering # behavior is activated it will be applied every simulation frame until # another steering behavior is activated. Only one steering behavior can # be active at once. def stop(self): """Activate 'no steering' behavior. No steering force will be applied. """ self._steeringbehavior = [] def seek(self, target): """Activate seek steering behavior. target should be a SteerVec. """ self._steeringbehavior = ['Seek'] self._target = target def flee(self, target): """Activate flee steering behavior. target should be a SteerVec. """ self._steeringbehavior = ['Flee'] self._target = target def pursue(self, target): """Activate pursue steering behavior. target should be another Vehicle. """ self._steeringbehavior = ['Pursue'] self._target = target def follow(self, target): """Activate follow steering behavior. target should be another Vehicle. """ self._steeringbehavior = ['Follow'] self._target = target def evade(self, target): """Activate evade steering behavior. target should be another Vehicle. """ self._steeringbehavior = ['Evade'] self._target = target def arrive(self, target): """Activate the arrive steering behavior. target should be a SteerVec. """ self._steeringbehavior = ['Arrive'] self._target = target def wander(self): """Activate wander steering behavior. """ # FIXME: when mixin behaviours are in use, wanderSide and wanderUp # should be reset every time a mixin is activated. self.wanderSide=0 self.wanderUp=0 self._steeringbehavior = ['Wander'] def followPath(self,path,loop=False): self._steeringbehavior = ['FollowPath'] self._path = path self._waypoint = path.getNearestWaypoint(self._pos) self._loop = loop # Private methods to compute the steering vectors for steering behaviors. # These methods will be called by self._step(). Each method may return None # indicating that no steering is required at this time for the behavior. def _steerForSeek(self, target=None): """Return the steering_direction (SteerVec) required to seek target. target should be a SteerVec.""" if target == None: target = self._target desired_velocity = -(self._pos - target) * self.maxspeed desired_velocity.normalize() steering_direction = desired_velocity - self._velocity return steering_direction def _steerForFlee(self, target=None): """Return the steering_direction (SteerVec) required to flee target. target should be a SteerVec.""" if target == None: target = self._target desired_velocity = (self._pos - target) * self.maxspeed desired_velocity.normalize() steering_direction = desired_velocity - self._velocity return steering_direction def _steerForPursue(self, target=None): """Return the steering_direction (SteerVec) required to pursue target. target should be another Vehicle.""" # FIXME: Should the prediction interval be a parameter somewhere? if target == None: target = self._target prediction = target.predictFuturePosition(10) return self._steerForSeek(prediction) def _steerForFollow(self, target=None): """Return the steering_direction (SteerVec) required to follow target. target should be another Vehicle. Follow is like the pursue behavior but the vehicle will follow behind its target instead of catching up to it. The arrive behavior is place of seek in pursuit""" if target == None: target = self._target direction = SteerVec(target._velocity.getX(),target._velocity.getY()) direction.normalize() point = target._pos + direction*-5 return self._steerForArrive(point) def _steerForEvade(self, target=None): """Return the steering_direction (SteerVec) required to evade target. target should be another Vehicle.""" # FIXME: Should the prediction interval be a parameter somewhere? if target == None: target = self._target prediction = target.predictFuturePosition(10) return self._steerForFlee(prediction) def _steerForArrive(self, target=None): """Return the steering_direction (SteerVec) required to arrive at target. target should be a SteerVec.""" if target == None: target = self._target else: # Make sure it's a SteerVec (if it's not we assume it's something # with a getX() and getY() and we translate it) if not isinstance(target,SteerVec): target = SteerVec(target.getX(),target.getY()) # FIXME: slowing_distance should be a parameter somewhere. slowing_distance = 20 target_offset = target - self._pos distance = target_offset.length() if distance == 0: return SteerVec(0,0) ramped_speed = self.maxspeed * (distance / slowing_distance) clipped_speed = min(ramped_speed,self.maxspeed) desired_velocity = target_offset * (clipped_speed / distance) steering_direction = desired_velocity - self._velocity return steering_direction def _steerForWander(self): """Return a steering_direction for wandering.""" speed = 0.2 self.wanderSide = self._scalarRandomWalk(self.wanderSide,speed,-1,1) self.wanderUp = self._scalarRandomWalk(self.wanderUp,speed,-1,1) up = self._velocity up.normalize() # The vehicle's forward direction side = up.rotate(90) return ((side * self.wanderSide) + (up * self.wanderUp)).truncate(0.01) def _scalarRandomWalk(self,initial,walkspeed,minimum,maximum): """Helper function for Vehicle._steerForWander() below.""" next = initial + ((random.random()*2)-1)*walkspeed if next < minimum: return minimum if next > maximum: return maximum return next def _steerForAvoidObstacles(self): """ Return a steering force to avoid the nearest obstacle that is considered a collision threat, or None to indicate that no obstacle avoidance steering is required. """ # Check for collisions with obstacles. collision = False obstacleHandler.sortEntries() for i in range(obstacleHandler.getNumEntries()): entry = obstacleHandler.getEntry(i) if entry.getInto() == self.tube: collision = True pos = entry.getSurfacePoint(render) nrml = entry.getSurfaceNormal(render) if collision is False: return None # Compute steering to avoid the collision. nrml = SteerVec(nrml.getX(),nrml.getY()) forward = self._velocity forward.normalize() steeringdirection = nrml.perpendicularComponent(forward) steeringdirection.normalize() brakingdirection = -self._velocity brakingdirection.normalize() md = self._velocity.length() + self.radius mf = self.maxforce p = SteerVec(pos.getX(),pos.getY()) d = (self._pos - p).length() if d < 0: d = 0 steeringforce = mf - ((d/md)*mf) brakingforce = mf - ((sqrt(d)/md)*mf) return (brakingdirection*brakingforce)+(steeringdirection*steeringforce) def _steerForContainment(self): """ If this vehicle is outside either the global container or its local self.container return a steering force to turn the vehicle back towards the container. Else return None to indicate no containment steering is required. self.container is given priority over the global container. """ global container for container in (self.container,container): if container is None: continue if not container.isInside(self._pos): # We are outside of the container, steer back toward it seek = self._steerForSeek(container.pos) lateral = seek.perpendicularComponent(self.getForward()) return lateral return None def _steerForFollowPath(self): if (self._pos-self._path[self._waypoint]).length()<3: self._waypoint += 1 if self._waypoint >= len(self._path): if self._loop: self._waypoint = 0 else: self._waypoint = len(self._path)-1 if not self._loop and self._waypoint == len(self._path)-1: return self._steerForArrive(self._path[self._waypoint]) else: return self._steerForSeek(self._path[self._waypoint]) def _steerForAvoidVehicles(self): """ Return a steering force to avoid the site of the soonest potential collision with another vehicle, or None if there is no impending collision. Unaligned collision avoidance behavior: avoid colliding with other nearby vehicles moving in unconstrained directions. Determine which (if any) other other vehicle we would collide with first, then steer to avoid the site of that potential collision. """ # First priority is to steer hard to avoid very close vehicles steering = self._steerForAvoidCloseNeighbors(0) if steering is not False: return steering # Otherwise look for collisions further away. steer = 0 threat = None # Time (in seconds) until the most immediate collision threat found # so far. Initial value is a threshold: don't look more than this # many frames into the future. minTime = 60 # Determine which (if any) neighbor vehicle poses the most immediate # threat of collision. for vehicle in vehicles: if vehicle is self: continue # Avoid when future positions are this close (or less) collisionDangerThreshold = self.radius * 2 # Predicted time until nearest approach time = self._predictNearestApproachTime(vehicle) # If `time` is in the future, sooner than any other threatened # collision... if time >= 0 and time < minTime: # If the two will be close enough to collide make a note of it thrtPosAtNrstApprch,distance = self._computeNearestApproachPositions(time,vehicle) if distance < collisionDangerThreshold: minTime = time threat = vehicle # If a potential collision was found, compute steering to avoid if threat is None: return None else: parallelness = self.getForward().dot(threat.getForward()) angle = 0.707 if parallelness < -angle: # Anti-parallel "head on" paths: steer away from future threat # position offset = thrtPosAtNrstApprch - self._pos sideDot = offset.dot(self.getRight()) if sideDot > 0: steer = -1 else: steer = 1 elif parallelness > angle: # Parallel paths: steer away from threat offset = threat._pos - self._pos sideDot = offset.dot(self.getRight()) if sideDot > 0: steer = -1 else: steer = 1 elif threat.getspeed() <= self.getspeed(): # Perpendicular paths: steer behind threat (only the slower of # the two does this) sideDot = self.getRight().dot(threat._velocity) if sideDot > 0: steer = -1 else: steer = 1 return self.getRight() * steer def _predictNearestApproachTime(self,vehicle): """Return the time until nearest approach between this vehicle and another vehicle.""" # Imagine we are at the origin with no velocity, compute the relative # velocity of the other vehicle myVelocity = self._velocity hisVelocity = vehicle._velocity relVelocity = hisVelocity - myVelocity relSpeed = relVelocity.length() # For parallel paths, the vehicles will always be at the same distance, # so return 0 (aka "now") since "there is no time like the present" if relSpeed == 0: return 0 # Now consider the path of the other vehicle in this relative # space, a line defined by the relative position and velocity. # The distance from the origin (our vehicle) to that line is # the nearest approach. # Take the unit tangent along the other vehicle's path relTangent = relVelocity / relSpeed # Find distance from its path to origin (compute offset from # other to us, find length of projection onto path) relPosition = self._pos - vehicle._pos projection = relTangent.dot(relPosition) return projection / relSpeed def _computeNearestApproachPositions(self, time, vehicle): """Return a tuple containing the position of 'vehicle' at its nearest approach to this vehicle and the distance between the two at that point, given the time until the nearest approach of the two.""" myTravel = (self.getForward() * self.getspeed()) * time hisTravel = vehicle.getForward() * vehicle.getspeed() * time myFinal = self._pos + myTravel hisFinal = vehicle._pos + hisTravel distance = (myFinal - hisFinal).length() return (hisFinal,distance) def _steerForAvoidCloseNeighbors(self, criticalDistance): """Avoidance of "close neighbors" -- used only by _steerForAvoidNeighbors. Does a hard steer away from any other vehicle who comes withing a critical distance.""" for vehicle in vehicles: if vehicle is self: continue # No need to avoid yourself sumOfRadii = self.radius + vehicle.radius minCenterToCenter = criticalDistance + sumOfRadii offset = vehicle._pos - self._pos currentDistance = offset.length() if currentDistance < minCenterToCenter: return (-offset).perpendicularComponent(self.getForward()) return False def _step(self,task): """ Update the vehicle's position using a simple point-mass physics model based on self._steeringforce, self.maxforce, self.mass, and self.maxspeed, and applying the steering behavior indicated by self._steeringbehavior. """ dt = task.time - self._prevtime steeringbehavior = self._steeringbehavior if self.avoidObstacles: steeringbehavior = ['AvoidObstacles'] + steeringbehavior if self.avoidVehicles: steeringbehavior = ['AvoidVehicles'] + steeringbehavior if (self.container is not None) or (container is not None): steeringbehavior = ['Containment'] + steeringbehavior # Set self._steeringforce to be the result of the first method in # steeringbehavior that does not return None. self._steeringforce = SteerVec(0,0) self.label['text'] = 'no steering' for steeringmethod in steeringbehavior: method_name = '_steerFor' + steeringmethod method = getattr(self, method_name) steeringforce = method() if steeringforce is not None: self.label['text'] = steeringmethod self._steeringforce = steeringforce break global show if show: self.label.show() #self.tubenp.show() #self.spherenp.show() else: self.label.hide() #self.tubenp.hide() #self.spherenp.hide() # Compute new velocity according to point-mass physics. steering_force = self._steeringforce.truncate(self.maxforce) acceleration = steering_force/self.mass self._velocity = (self._velocity+acceleration).truncate(self.maxspeed) # Add a small random component to the velocity. The component is too # small to produce any visible result. It is added to avoid a bug in # the obstacle avoidance behavior: if a vehicle heads precisely # toward an obstacle then the surface normal at the point of # collision on the surface of the obstacle is parallel to the forward # direction of the vehicle. So the perpendicular component of the # surface normal to the vehicle's forward direction is zero, and hence # the steering force is zero, and the vehicle plows straight into the # obstacle. With a random element to the vehicle's velocity, this # precise situation will not exist for consecutive simulation frames. x = (random.random()-0.5)*0.01 y = (random.random()-0.5)*0.01 self._velocity.setX(self._velocity.getX()+self._velocity.getX()*x) self._velocity.setY(self._velocity.getY()+self._velocity.getY()*y) # Update vehicle's position. self._pos += self._velocity*(dt*50) self._enforceNonPenetrationConstraint() # Fluidly update the NodePath's X and Y positions to match self._pos. # Leave the NodePath's Z-axis position untouched (that is taken care of # by CollisionHandlerFloor). self.prime.setFluidPos(self._pos.getX(),self._pos.getY(), self.prime.getZ()) # Update the Vehicles's CollisionTube, varying the length of the tube # according to the Vehicle's speed. ##zuck ###tube=self.tubenp.node().getSolid(0) tube=self.tubenp.node().modifySolid(0) tube.setPointB(Point3( tube.getPointA()+Point3(0,15.*self._velocity.length(),0))) self._prevtime = task.time return Task.cont def _enforceNonPenetrationConstraint(self): """Forcibly prevent this vehicle from penetrating obstacles. Based on advice from Craig Reynolds: The obstacle and vehicle are both assumed to be spheres. Measure the distance between their centers. If this is less than the sum of their radii the two spheres intersect. If so, simply "slide" (that is, SET the position of) the vehicle along the line connecting their centers the distance by which they overlap. See code here: http://sourceforge.net/forum/message.php?msg_id=3928822 """ # Handle collisions with obstacles. obstacleHandler.sortEntries() for i in range(obstacleHandler.getNumEntries()): entry = obstacleHandler.getEntry(i) if entry.getInto() == self.sphere: other = entry.getFrom() pos = other.getCenter() pos = SteerVec(pos.getX(),pos.getY()) s = self.radius + other.getRadius() overlap = self._pos-pos d = overlap.length() if d>0: s = (s-d)/d overlap *= s self._pos += overlap return # Handle collisions with other vehicles. collisionHandler.sortEntries() for i in range(collisionHandler.getNumEntries()): entry = collisionHandler.getEntry(i) # FIXME: The collisionmasks in this module aren't quite right. # Want Vehicle.sphere to collide with other Vehicle.sphere's and # with obstacles.py/SphereObstacle's, and want Vehicle.tube to # collide with obstacles.py/SphereObstacle's, but we don't want # Vehicle.sphere to collide with the Vehicle.tube of another # vehicle! (or vice-versa) # For now just check for the unwanted tube collisions and ignore # them. if isinstance(entry.getInto(),CollisionTube): continue if entry.getFrom() == self.sphere: pos = entry.getIntoNodePath().getPos(render) pos = SteerVec(pos.getX(),pos.getY()) s = self.radius + entry.getInto().getRadius() overlap = self._pos-pos d = overlap.length() if d>0: s = (s-d)/d overlap *= s self._pos += overlap if self.callout['text'] == '': self.callout['text'] = random.choice(["Ouch!","Sorry!","Hey!"]) self.callout.show() return self.callout['text']='' self.callout.hide()
class PiratesDownloadWatcher(DownloadWatcher.DownloadWatcher): positions = [(Point3(1, 0, 0.9), Point3(1, 0, 0.9)), (Point3(1, 0, 0.9), Point3(1, 0, 0.9)), (Point3(1, 0, 0.9), Point3(1, 0, 0.9))] def __init__(self, phaseNames): self.phaseNames = phaseNames self.model = loader.loadModel('models/gui/pir_m_gui_gen_loadingBar') bar = self.model.findTexture('pir_t_gui_gen_loadingBar') self.model.find('**/loading_bar').hide() self.topFrame = DirectFrame(parent=base.a2dTopRight, pos=(-0.8, 0, -0.1), sortOrder=DGG.NO_FADE_SORT_INDEX + 1) self.text = DirectLabel(relief=None, parent=self.topFrame, guiId='DownloadWatcherText', pos=(0, 0, 0), text=' ', text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text_scale=0.04, textMayChange=1, text_align=TextNode.ARight, text_pos=(0.17, 0), sortOrder=2) self.bar = DirectWaitBar(relief=None, parent=self.topFrame, guiId='DownloadWatcherBar', pos=(0, 0, 0), frameSize=(-0.4, 0.38, -0.045, 0.065), borderWidth=(0.02, 0.02), range=100, frameColor=(1, 1, 1, 1), barColor=(0, 0.3, 0, 1), barTexture=bar, geom=self.model, geom_scale=0.09, geom_pos=(-0.014, 0, 0.01), text='0%', text_scale=0.04, text_fg=(1, 1, 1, 1), text_align=TextNode.ALeft, text_pos=(0.19, 0), sortOrder=1) self.bgFrame = DirectFrame(relief=DGG.FLAT, parent=self.topFrame, pos=(0, 0, 0), frameColor=(0.5, 0.27, 0.36, 0.2), frameSize=(-0.44, 0.39, -0.036, 0.056), borderWidth=(0.02, 0.02), scale=0.9, sortOrder=0) self.accept('launcherPercentPhaseComplete', self.update) return def update(self, phase, percent, reqByteRate, actualByteRate): phaseName = self.phaseNames[phase] self.text[ 'text'] = OTPLocalizer.DownloadWatcherUpdate % phaseName + ' -' self.bar['text'] = '%s %%' % percent self.bar['value'] = percent def foreground(self): self.topFrame.reparentTo(base.a2dpTopRight) self.topFrame.setBin('gui-fixed', 55) self.topFrame['sortOrder'] = DGG.NO_FADE_SORT_INDEX + 1 def background(self): self.topFrame.reparentTo(base.a2dTopRight) self.topFrame.setBin('unsorted', 49) self.topFrame['sortOrder'] = -1 def cleanup(self): self.text.destroy() self.bar.destroy() self.bgFrame.destroy() self.topFrame.destroy() self.ignoreAll()
def __init__(self, USERNAME, rootParent=None): self.pg149 = DirectLabel( frameSize=(-1.149999976158142, 1.25, -0.11250001192092896, 0.7250000238418579), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.525), scale=LVecBase3f(0.1, 0.1, 0.1), text='Top', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, ) self.pg149.setTransparency(0) self.pg1336 = DirectScrolledList( forceHeight=0.1, frameSize=(-0.5, 0.5, -0.01, 0.75), hpr=LVecBase3f(0, 0, 0), numItemsVisible=5, pos=LPoint3f(0.025, 0, -0.25), state='normal', text='scrolled list', decButton_borderWidth=(0.005, 0.005), decButton_hpr=LVecBase3f(0, 0, 0), decButton_pos=LPoint3f(-0.45, 0, 0.03), decButton_state='disabled', decButton_text='Prev', decButton_text_align=TextNode.A_left, decButton_text_scale=(0.05, 0.05), decButton_text_pos=(0, 0), decButton_text_fg=LVecBase4f(0, 0, 0, 1), decButton_text_bg=LVecBase4f(0, 0, 0, 0), decButton_text_wordwrap=None, incButton_borderWidth=(0.005, 0.005), incButton_hpr=LVecBase3f(0, 0, 0), incButton_pos=LPoint3f(0.45, 0, 0.03), incButton_state='disabled', incButton_text='Next', incButton_text_align=TextNode.A_right, incButton_text_scale=(0.05, 0.05), incButton_text_pos=(0, 0), incButton_text_fg=LVecBase4f(0, 0, 0, 1), incButton_text_bg=LVecBase4f(0, 0, 0, 0), incButton_text_wordwrap=None, itemFrame_frameColor=(1, 1, 1, 1), itemFrame_frameSize=(-0.47, 0.47, -0.5, 0.1), itemFrame_hpr=LVecBase3f(0, 0, 0), itemFrame_pos=LPoint3f(0, 0, 0.6), text_align=TextNode.A_center, text_scale=(0.1, 0.1), text_pos=(0, 0.015), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, ) self.pg1336.setTransparency(0) self.pg1693 = DirectScrolledListItem( frameSize=(-3.831250286102295, 3.9062500953674317, -0.21250001192092896, 0.85), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), scale=LVecBase3f(0.1, 0.1, 0.1), state='disabled', text='Admin', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.pg1336, command=base.messenger.send, extraArgs=['select_list_item_changed'], ) self.pg1693.setTransparency(0) self.pg1715 = DirectScrolledListItem( frameSize=(-3.831250286102295, 3.9062500953674317, -0.21250001192092896, 0.85), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.1), scale=LVecBase3f(0.1, 0.1, 0.1), text='NFSMW', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.pg1336, command=base.messenger.send, extraArgs=['select_list_item_changed'], ) self.pg1715.setTransparency(0) self.pg1740 = DirectScrolledListItem( frameSize=(-3.831250286102295, 3.9062500953674317, -0.21250001192092896, 0.85), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.2), scale=LVecBase3f(0.1, 0.1, 0.1), text='|X_X|', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.pg1336, command=base.messenger.send, extraArgs=['select_list_item_changed'], ) self.pg1740.setTransparency(0) self.pg1768 = DirectScrolledListItem( frameSize=(-3.831250286102295, 3.9062500953674317, -0.21250001192092896, 0.85), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.3), scale=LVecBase3f(0.1, 0.1, 0.1), text=USERNAME, text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.pg1336, command=base.messenger.send, extraArgs=['select_list_item_changed'], ) self.pg1768.setTransparency(0) self.pg1799 = DirectScrolledListItem( frameSize=(-3.831250286102295, 3.9062500953674317, -0.21250001192092896, 0.85), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.4), scale=LVecBase3f(0.1, 0.1, 0.1), text='.___.', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.pg1336, command=base.messenger.send, extraArgs=['select_list_item_changed'], ) self.pg1799.setTransparency(0) self.pg1336.addItem(self.pg1693) self.pg1336.addItem(self.pg1715) self.pg1336.addItem(self.pg1740) self.pg1336.addItem(self.pg1768) self.pg1336.addItem(self.pg1799)
def __init__(self, menu_args): GameObject.__init__(self) self.eng.log('created message form') self.chats = [] self.curr_chat = None self.curr_match_room = None self.msg_frm = DirectFrame( frameSize=(-.02, .8, 0, .45), frameColor=(.2, .2, .2, .5), pos=(-.82, 1, .02), parent=base.a2dBottomRight) self.presences_sent = [] self.menu_args = menu_args t_a = menu_args.text_args t_a['scale'] = .05 t_a['fg'] = menu_args.text_normal self.dst_txt = OnscreenText( text='', pos=(0, .4), parent=self.msg_frm, align=TextNode.A_left, **t_a) self.arrow_btn = ImgBtn( parent=self.msg_frm, scale=.024, pos=(.7, 1, .42), frameColor=(1, 1, 1, 1), frameTexture='assets/images/gui/arrow.txo', command=self.on_arrow, **menu_args.imgbtn_args) self.arrow_btn.disable() self.close_btn = ImgBtn( parent=self.msg_frm, scale=.024, pos=(.76, 1, .42), frameColor=(1, 1, 1, 1), frameTexture='assets/images/gui/close.txo', command=self.on_close, **menu_args.imgbtn_args) self.close_btn.disable() self.ent = Entry( scale=.04, pos=(0, 1, .03), entryFont=menu_args.font, width=19.5, frameColor=menu_args.btn_color, parent=self.msg_frm, initialText=_('write here your message'), command=self.on_typed_msg, focusInCommand=self.on_focus, focusInExtraArgs=['in'], focusOutCommand=self.on_focus, focusOutExtraArgs=['out'], text_fg=menu_args.text_active) self.ent['state'] = DISABLED self.txt_frm = DirectScrolledFrame( frameSize=(-.02, .76, -.02, .28), canvasSize=(-.02, .72, -.02, .28), scrollBarWidth=.036, verticalScroll_relief=FLAT, verticalScroll_frameColor=(.2, .2, .2, .4), verticalScroll_thumb_relief=FLAT, verticalScroll_thumb_frameColor=(.8, .8, .8, .6), verticalScroll_incButton_relief=FLAT, verticalScroll_incButton_frameColor=(.8, .8, .8, .6), verticalScroll_decButton_relief=FLAT, verticalScroll_decButton_frameColor=(.8, .8, .8, .6), horizontalScroll_relief=FLAT, frameColor=(1, 1, 1, 0), pos=(.02, 1, .11), parent=self.msg_frm) t_a['scale'] = .046 self.msg_txt = OnscreenText( text='', pos=(0, .24), parent=self.txt_frm.getCanvas(), align=TextNode.A_left, wordwrap=14, **t_a) lab_args = menu_args.label_args lab_args['scale'] = .046 lab_args['text_fg'] = menu_args.text_normal self.lab_frm = Btn( frameSize=(-.02, .64, -.01, .05), frameColor=(1, 1, 1, 0), pos=(0, 1, .4), parent=self.msg_frm) self.lab_frm.bind(ENTER, self.on_enter) self.lab_frm.bind(EXIT, self.on_exit) self.tooltip = DirectLabel( text='', pos=(.78, 1, -.06), parent=self.lab_frm, text_wordwrap=16, text_bg=(.2, .2, .2, .8), text_align=TextNode.A_right, **lab_args) self.tooltip.set_bin('gui-popup', 10) self.tooltip.hide()
def __makeStructureFrameTreeItem(self, elementNP, elementInfo, parentsLevel, z): if elementInfo is None: lbl = DirectLabel(text=elementNP.getName(), text_align=TextNode.ALeft, frameColor=(0, 0, 0, 0), relief=DGG.FLAT, pos=(self.structureFrame["frameSize"][0] + 20 * parentsLevel, 0, z), scale=16, parent=self.structureFrame.getCanvas()) self.maxWidth = max( self.maxWidth, lbl.getX() + lbl.getWidth() * lbl.getScale()[0]) else: margin = 5 shift = 6 if hasattr(elementNP, "getChildren"): if len(elementNP.getChildren()) > 0: # Collapse Button btnC = DirectCheckBox( relief=DGG.FLAT, pos=(self.structureFrame["frameSize"][0] + 20 * parentsLevel - 16 + margin, 0, z + shift), frameSize=(-8, 8, -8, 8), frameColor=(0, 0, 0, 0), command=self.__collapseElement, extraArgs=[elementInfo], image="icons/Collapsed.png" if elementInfo in self.collapsedElements else "icons/Collapse.png", uncheckedImage="icons/Collapse.png", checkedImage="icons/Collapsed.png", image_scale=8, isChecked=elementInfo in self.collapsedElements, parent=self.structureFrame.getCanvas()) btnC.setTransparency(TransparencyAttrib.M_alpha) btnC.bind(DGG.MWDOWN, self.scroll, [0.01]) btnC.bind(DGG.MWUP, self.scroll, [-0.01]) # Element Name btn = DirectButton( frameColor=( VBase4(1, 1, 1, 1), #normal VBase4(0.9, 0.9, 0.9, 1), #click VBase4(0.8, 0.8, 0.8, 1), #hover VBase4(0.5, 0.5, 0.5, 1)), #disabled text=elementInfo.name, text_align=TextNode.ALeft, relief=DGG.FLAT, pos=(self.structureFrame["frameSize"][0] + 20 * parentsLevel, 0, z), scale=16, command=self.__selectElement, extraArgs=[elementInfo], parent=self.structureFrame.getCanvas()) btn.bind(DGG.MWDOWN, self.scroll, [0.01]) btn.bind(DGG.MWUP, self.scroll, [-0.01]) if self.selectedElement is not None and self.selectedElement == elementInfo: btn.setColorScale(1, 1, 0, 1) # Delete Button btnX = DirectButton( relief=DGG.FLAT, pos=(self.structureFrame["frameSize"][0] + 8 + margin + 20 * parentsLevel + btn.getWidth() * btn.getScale()[0], 0, z + shift), frameSize=(-8, 8, -8, 8), frameColor=(0, 0, 0, 0), command=self.__removeElement, extraArgs=[elementInfo], image="icons/DeleteSmall.png", image_scale=8, parent=self.structureFrame.getCanvas()) btnX.setTransparency(TransparencyAttrib.M_multisample) btnX.bind(DGG.MWDOWN, self.scroll, [0.01]) btnX.bind(DGG.MWUP, self.scroll, [-0.01]) # Visibility Button btnV = DirectCheckBox( relief=DGG.FLAT, pos=(self.structureFrame["frameSize"][0] + 8 + margin * 2 + 20 * parentsLevel + btn.getWidth() * btn.getScale()[0] + btnX.getWidth(), 0, z + shift), frameSize=(-8, 8, -8, 8), frameColor=(0, 0, 0, 0), command=self.__toggleElementVisibility, extraArgs=[elementInfo], image="icons/VisibilityOffSmall.png" if elementInfo.element.isHidden() else "icons/VisibilityOnSmall.png", uncheckedImage="icons/VisibilityOffSmall.png", checkedImage="icons/VisibilityOnSmall.png", image_scale=8, isChecked=not elementInfo.element.isHidden(), parent=self.structureFrame.getCanvas()) btnV.setTransparency(TransparencyAttrib.M_multisample) btnV.bind(DGG.MWDOWN, self.scroll, [0.01]) btnV.bind(DGG.MWUP, self.scroll, [-0.01]) self.maxWidth = max(self.maxWidth, btnV.getX() + 8)
class JustDanceGUI(ShowBase): def __init__(self): # Basic initialization of panda3D engine ShowBase.__init__(self) self.songButtonList=[] self.createDefaultMusicList() self.loadMusicScores() self.difficultyLevel='easy' self.configureGUIPanels() self.displayPanel('options') self.BGM=base.loader.loadSfx("../music/Nyte - Lone Walker.mp3") self.BGM.play() # create a local file that stores local music paths and scores @staticmethod def createDefaultMusicList(): # check if the file is created if os.path.isfile('musicGameData.txt'): print('here') file=open('musicGameData.txt','r') else: file=open('musicGameData.txt','w') file.write('Rather Be\n') file.write('../music/Clean Bandit,Jess Glynne-Rather '+ 'Be (Robin Schulz Edit).mp3\n') file.write('0\n') file.write('Memory\n') file.write('../music/Elaine Paige-Memory.mp3\n') file.write('0\n') # Load history of music scores def loadMusicScores(self): file=open('musicGameData.txt','r') self.data=file.readlines() self.highestScores=dict() self.musicNames=[] self.musicPathes=dict() dataList=[] for line in self.data: dataList.append(line.strip()) for i in range(0,len(dataList),3): self.musicNames.append(dataList[i]) self.musicPathes[dataList[i]]=dataList[i+1] self.highestScores[dataList[i]]=float(dataList[i+2]) # configure all GUI panels def configureGUIPanels(self): self.setBackgroundColor((0, 0, 0, 1)) self.panels = dict() self.cam2dp.node().getDisplayRegion(0).setSort(-20) self.configureStartMenu() self.configureMainMenu() self.configureScoreBoard() self.configureSetting() self.configureDance() self.configureImportMenu() # the function displays a single panel and hides # all other panels def displayPanel(self, displayPanel): for panel in self.panels: if(panel == displayPanel): self.panels[panel].show() else: self.panels[panel].hide() def getPanel(self,panelName): return self.panels[panelName] def setPanel(self,panelName,panel): self.panels[panelName] = panel return # swich from displaying one panel to displaying the other panel def switchPanel(self,oldP,newP): self.panels[oldP].hide() self.panels[newP].show() # get activities from the keybboard def getEvent(self): return self.pressed # configure the start menu def configureStartMenu(self): optionBackground = OnscreenImage(parent=render2dp, image= '../textures/MENU_ORG_text.jpg') settingButton = DirectButton(pos=(0.1, 0, 0), text=" Setting", scale=.08, pad=(.2, .2), frameColor=(0.02,0.3,0.5,0.4), text_fg=(0,0.4,0.7,1), text_align=TextNode.ALeft,frameSize=(-4.3,4,-0.6,1), text_pos=(-1,0,0), rolloverSound=None, clickSound=None, command=lambda:self.switchPanel('options','setting')) settingButton.resetFrameSize() playButton = DirectButton(pos=(0.1, 0, .15), text="Start", scale=.08, pad=(.2, .2),frameColor=(0.02,0.3,0.5,0.4), text_fg=(0.1,0.4,0.7,1), text_align=TextNode.ALeft, frameSize=(-3,4,-0.6,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('options','mainMenu')) scoreBoardButton= DirectButton(pos=(0, 0, -.15), text="HighScore", scale=.08, pad=(.2, .2),frameColor=(0.02,0.3,0.5,0.4), text_pos=(-1,0,0), text_fg=(0.1,0.4,0.7,1),text_align=TextNode.ALeft,frameSize=(-5,5.3,-0.6,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('options','scoreBoard')) optionsList=DirectFrame(frameSize=(-0.3,0.3,-0.2,0.2),pos=(0.8,0,-0.5),frameColor=(0,0,0,0)) settingButton.reparentTo(optionsList) playButton.reparentTo(optionsList) scoreBoardButton.reparentTo(optionsList) self.setPanel('options', Panel(optionBackground, {'optionList': optionsList})) # configure the main menu (music list page) def configureMainMenu(self): self.mainMenuBackground = OnscreenImage(parent=render2dp, image='../textures/BGM_ORG_text.jpg') self.songList = DirectScrolledFrame(canvasSize = (-0.3,0.2,-1,1), frameSize = (-0.45,0.55,-0.2,0.2)) self.songList['frameColor']=(0.5,0.5,1,0) self.songList.setPos(0, 0, -0.3) self.songList['verticalScroll_thumb_frameColor']=(1,1,1,0.3) self.songList['verticalScroll_incButton_frameColor']=(1,1,1,0) self.songList['verticalScroll_decButton_frameColor']=(1,1,1,0) self.songList['verticalScroll_frameColor']=(0.5,0.5,1,0) for i in range(len(self.musicNames)): defaultSong=DirectButton(pos=(0, 0, 0.9-i*0.15), text=( self.musicNames[i],'clicked', self.musicNames[i],self.musicNames[i]), scale=.1, pad=(.2, .2), frameColor=(0.058,0.294,0.545,0.7), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), rolloverSound=None, clickSound=None, command=self.preInitDance,extraArgs=(i,)) defaultSong['frameSize']=(-4,6,-0.7,0.7) defaultSong.reparentTo(self.songList.getCanvas()) importButton=DirectButton(pos=(0,0,-0.6),text='+ IMPORT NEW MUSIC ', scale=0.1,pad=(.2,.2),frameColor=(0.058,.294,0.545,0.7), text_fg=(0.88,0.98,1,1),frameSize=(-6.5,6.5,-0.8,0.8), text_scale=(0.85,0.85), text_pos=(0.5,-0.4),rolloverSound=None, clickSound=None, command= lambda: self.switchPanel('mainMenu','import')) backToOptionButton=DirectButton(text='<<BACK TO MENU', pos=(-1,0,0.8),scale=.1,pad=(.2, .2), frameColor=(1,1,1,0), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('mainMenu','options')) self.setPanel('mainMenu', Panel(self.mainMenuBackground, {'songs': self.songList, 'import': importButton, 'back': backToOptionButton})) self.disableMouse() # configure the import menu def configureImportMenu(self): importBackground= OnscreenImage(parent=render2dp, image='../textures/BGM_ORG.jpg') newNameBox = DirectEntry(text = "" ,pos=(-0.4,0,0.5),scale=.08, frameColor=(1,1,1,0.3),initialText="", numLines = 3,focus=1) newPathBox = DirectEntry(text = "" ,pos=(-0.4,0,0.2), frameColor=(1,1,1,0.3), scale=.08, initialText="", numLines = 5,focus=1) confirmationButton=DirectButton(text='IMPORT',pos=(0, 0, -0.3), scale=.1, pad=(.2, .2), frameColor=(0.058,.294,0.545,0.7), text_pos=(0,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), frameSize=(-6.5,6.5,-0.8,0.8), rolloverSound=None, clickSound=None, command=self.importNewSong) backToOptionButton=DirectButton(text='<<BACK TO MUSIC LIST', pos=(-1,0,0.8),scale=.1,pad=(.2, .2), frameColor=(1,1,1,0), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('import','mainMenu')) self.setPanel('import',Panel(importBackground, {'newName': newNameBox, 'newPath': newPathBox,'confirmButton': confirmationButton, 'back':backToOptionButton})) # function that loads new music from the import page def importNewSong(self): songName = self.getPanel('import').getItem('newName') songPath = self.getPanel('import').getItem('newPath') self.musicPathes[songName.get()] = songPath.get() self.musicNames.append(songName.get()) file=open('musicGameData.txt','a') file.write(songName.get()+'\n') file.write(songPath.get()+'\n') file.write('0\n') self.updateSongs() songName.enterText("") songPath.enterText("") self.switchPanel('import','mainMenu') # update songs in the list def updateSongs(self): name = self.musicNames[-1] path=self.musicPathes[name] idx = len(self.musicNames)-1 song = DirectButton(text=name, pos=(0, 0,0.9-0.15*idx), scale=.1, pad=(.2, .2), frameColor=(0.058,.294,0.545,0.7), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), frameSize=(-4,6,-0.7,0.7), rolloverSound=None, clickSound=None, command=self.preInitDance,extraArgs= (-1,)) self.highestScores[name]=0 song.reparentTo(self.songList.getCanvas()) scoreLabel=DirectButton(frameSize=(-0.3,0.3,-0.2,.2),pos=(0,0,0-idx*0.2), text='%s: %d'%(name,self.highestScores[name]), text_align=TextNode.ALeft,text_scale=0.08,frameColor=(0,0,0,0), text_fg=(1,1,1,1)) scoreLabel.reparentTo(self.getPanel('scoreBoard').getItem('frame').getCanvas()) # function that configures the setting panel def configureSetting(self): self.settingBackground = OnscreenImage(parent=render2dp, image='../textures/SET_ORG.jpg') self.difficulty=OnscreenText(pos=(0.4,0.3),scale=0.08,fg=(0.88,0.98,1,1), text='Difficulty:') self.setDifficultyButton=DirectButton(pos=(0.6,0,0),scale=.1, pad=(.2, .2), frameColor=(0.058,0.294,0.545,0.7), frameSize=(-1.5,5,-0.8,0.8), text_pos=(1,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1),text=self.difficultyLevel, command=self.changeDifficulty) self.backToOptionButton3=DirectButton(text='<<BACK TO MENU', pos=(-1,0,0.8),scale=.1,pad=(.2, .2), frameColor=(1,1,1,0), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('setting', 'options')) self.panels['setting'] = Panel(self.settingBackground, {'level': self.difficulty, 'change': self.setDifficultyButton, 'back': self.backToOptionButton3}) # function that helps create the dance def preInitDance(self,index): self.currSong=self.musicNames[index] self.createDance(self.musicPathes[self.musicNames[index]]) self.switchPanel('mainMenu','dance') # switch difficult level of the game def changeDifficulty(self): if self.difficultyLevel=='hard': self.difficultyLevel='easy' self.setDifficultyButton['text']='easy' else: self.difficultyLevel='hard' self.setDifficultyButton['text']='hard' def createHighScoreFrame(self): highScoreFrame=DirectScrolledFrame(frameColor=(0.5,0.5,1,0), canvasSize = (-0.3,0.2,-2,1), frameSize = (-0.3,1.1,-0.8,0.3),pos=(0.2,0,0.2)) highScoreFrame['verticalScroll_thumb_frameColor']=(1,1,1,0.3) highScoreFrame['verticalScroll_incButton_frameColor']=(1,1,1,0) highScoreFrame['verticalScroll_decButton_frameColor']=(1,1,1,0) highScoreFrame['verticalScroll_frameColor']=(0.5,0.5,1,0) highScoreTitle1=DirectLabel(frameSize=(-0.6,0.6,-0.2,.2),pos=(0,0,0.9), text='Music',frameColor=(0,0,0,0), text_align=TextNode.ALeft,text_scale=0.08,text_fg=(1,1,1,1)) highScoreTitle2=DirectLabel(frameSize=(-0.6,0.6,-0.6,.6),pos=(0.4,0,0.9), text='Highest Score',text_fg=(1,1,1,1),frameColor=(0,0,0,0), text_align=TextNode.ALeft,text_scale=0.08) highScoreTitle1.reparentTo(highScoreFrame.getCanvas()) highScoreTitle2.reparentTo(highScoreFrame.getCanvas()) for i in range(len(self.musicNames)): scoreLabel=DirectButton(frameSize=(-0.3,0.3,-0.2,.2),pos=(0,0,0.7-i*0.2), text='%s: %d'%(self.musicNames[i],self.highestScores[self.musicNames[i]]), text_align=TextNode.ALeft,text_scale=0.08,frameColor=(0,0,0,0), text_fg=(1,1,1,1)) scoreLabel.reparentTo(highScoreFrame.getCanvas()) return highScoreFrame # configure the high score board def configureScoreBoard(self): scoreBoardBackground=OnscreenImage(parent=render2dp, image='../textures/HIGH_ORG_text.jpg') highScoreFrame = self.createHighScoreFrame() # for i in range(len(self.musicNames)): # scoreLabel=DirectButton(frameSize=(-0.3,0.3,-0.2,.2),pos=(0,0,0.7-i*0.2), # text='%s: %d'%(self.musicNames[i],self.highestScores[self.musicNames[i]]), # text_align=TextNode.ALeft,text_scale=0.08,frameColor=(0,0,0,0), # text_fg=(1,1,1,1)) # scoreLabel.reparentTo(self.highScoreFrame.getCanvas()) backToOptionButton2=DirectButton(text='<<BACK TO MENU', pos=(-1,0,0.8),scale=.1,pad=(.2, .2), frameColor=(1,1,1,0), text_pos=(1.3,-0.3),text_scale=(0.8,0.8), text_fg=(0.88,0.98,1,1), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('scoreBoard','options')) self.panels['scoreBoard'] = Panel(scoreBoardBackground, {'frame':highScoreFrame,'back':backToOptionButton2}) # configure the dance scene def configureDance(self): self.PRESSED,self.NPRESSED,self.PERFECT,self.GOOD,self.MISS=10,-10,2,1,0 danceNode = self.render.attachNewNode(PandaNode('dance')) # load and set up scene danceScene = self.loader.loadModel("../models/disco_hall") danceScene.reparentTo(danceNode) danceScene.setPosHpr(0, 50, -4, 90, 0, 0) self.configureLights(danceNode) self.configureDancer(danceNode) scoreCircle=OnscreenImage( image = '../textures/arrivalCircle.png', pos = (-1,0,0.8)) scoreCircle.setTransparency(TransparencyAttrib.MAlpha) scoreCircle.setScale(0.2) scoreText= OnscreenText(text =str(0), pos = (-1.02,0.76), scale = 0.1,fg=(1,1,1,1)) position=self.dancer.getPos() position[1]=0 position[2]=-0.4 GUIarrows=DirectFrame(frameColor=(0.3,0.3,0.7,0.3), frameSize=(-0.8,.8,0.2,-0.2), pos=position) hitSign=OnscreenImage(image ='../textures/circle.png', pos = (-0.6, 0, -0.4)) hitSign.setTransparency(TransparencyAttrib.MAlpha) hitSign.setScale(0.15) scoreReminder=OnscreenText(text ='PERFECT', pos = (-0.6,-0.4), scale = 0.04,fg=(1,1,1,1),shadow=(0.4,0.4,0.7,0.3)) self.setPanel('dance',Panel(danceNode, {'scoreCircle': scoreCircle, 'GUIarrows':GUIarrows,'hitSign': hitSign,'scoreText': scoreText, 'scoreReminder': scoreReminder})) # configure lights in the scene def configureLights(self, danceNode): # set up ambient light ambientLight = danceNode.attachNewNode(AmbientLight("ambientLight")) ambientLight.node().setColor((0.1, 0.1, 0.1, 1)) # set up directional light directional Light directionalLight = danceNode.attachNewNode(DirectionalLight("directionalLight")) directionalLight.node().setColor((.1, .1, .1, 1)) directionalLight.node().setDirection(LVector3(1, 1, -2)) directionalLight.setZ(6) dlens = directionalLight.node().getLens() dlens.setFilmSize(41, 21) dlens.setNearFar(50, 75) # set up spotlight spotlight = self.camera.attachNewNode(Spotlight("spotlight")) spotlight.node().setColor((.6, .6, .6, 0)) spotlight.node().setSpecularColor((0, 0, 0, 1)) spotlight.node().setLens(PerspectiveLens()) spotlight.node().getLens().setFov(24, 24) spotlight.node().setAttenuation(LVector3(0.6, 0.0, 0.0)) spotlight.node().setExponent(60.0) # set up red light ball redBall = loader.loadModel('../models/sphere') redBall.setColor((0.2, 0.2, .35, 1)) redBall.setPos(-6.5, -3.75, 0) redBall.setScale(.25) redPointLight = redBall.attachNewNode(PointLight("redPointLight")) redPointLight.node().setColor((.05, .3,.4, 1)) redPointLight.node().setAttenuation(LVector3(.1, 0.04, 0.0)) # set up green light ball greenBall = loader.loadModel('../models/sphere') greenBall.setColor((0.2, 0.2, .35, 1)) greenBall.setPos(0, 7.5, 0) greenBall.setScale(.25) greenPointLight = greenBall.attachNewNode( PointLight("greenPointLight")) greenPointLight.node().setAttenuation(LVector3(.1, .04, .0)) greenPointLight.node().setColor((.05, .3, .4, 1)) # set up blue light ball blueBall = loader.loadModel('../models/sphere') blueBall.setColor((0.2, 0.2, .35, 1)) blueBall.setPos(6.5, -3.75, 0) blueBall.setScale(.25) bluePointLight = blueBall.attachNewNode(PointLight("bluePointLight")) bluePointLight.node().setAttenuation(LVector3(.1, 0.04, 0.0)) bluePointLight.node().setColor((.1, .1, .4, 1)) bluePointLight.node().setSpecularColor((1, 1, 1, 1)) # set up light group lightGroup = danceNode.attachNewNode("pointLightHelper") lightGroup.setPos(0, 50, 11) redBall.reparentTo(lightGroup) greenBall.reparentTo(lightGroup) blueBall.reparentTo(lightGroup) danceNode.setLight(ambientLight) danceNode.setLight(directionalLight) danceNode.setLight(spotlight) danceNode.setLight(redPointLight) danceNode.setLight(greenPointLight) danceNode.setLight(bluePointLight) # spin three light balls in the scene pointLightsSpin = lightGroup.hprInterval(6, LVector3(360, 0, 0)) pointLightsSpin.loop() # configure the dancing avatar in the scene def configureDancer(self,danceNode): self.dancer = Actor("../animation/dancer.egg",{"pressKnee": '../animation/-pressKnee.egg', 'leapSwitch': "../animation/-leapSwitch.egg", 'pose':'../animation/-pose.egg', 'makeCircle':'../animation/-makeCircle.egg', 'jump':'../animation/-jump.egg', 'wave': '../animation/-wave.egg'}) self.dancer.setScale(1,1, 1) self.dancer.setPos(0,20,-4) self.dancer.reparentTo(danceNode) self.actionIndex=0 self.animationDown=['pose','makeCircle','pose','makeCircle','pressKnee'] self.animationRight=['jump','jump','wave','wave','leapSwitch'] # create the dance sequence according to the def createDance(self,path): self.game = musicGameCore.DanceGame(self, path,self.difficultyLevel) self.FULLSCORE, self.arrows = self.game.processMusic() self.accept('arrow_down', lambda: self.pressKey('h')) self.accept('arrow_right',lambda: self.pressKey('l')) self.createArrows() self.getPanel('dance').getItem('scoreText').setText('0') self.sound=self.loader.loadSfx(path) self.BGM.stop() self.mode = self.NPRESSED self.sound.play() self.game.startDance(globalClock.getFrameTime()) self.move2DArrows() self.colorStart=-1 self.pressedStart=0 self.taskMgr.add(self.checkInFrame,'checkInFrame') self.taskMgr.add(self.game.isArrowMissed,'checkArrows') self.taskMgr.add(self.checkColorStop,'checkColorStop') self.taskMgr.add(self.spinCam,'spinCam') self.accept('space',self.stopSound) self.taskMgr.add(self.checkStop,'checkStop') # load texture and create arrows def createArrows(self): self._2DleftArrow="../textures/left_arrow.png" self._2DupArrow="../textures/up_arrow.png" self._2DrightArrow=("../textures/right_arrow.png") self._2DdownArrow=("../textures/down_arrow.png") self.generate2DArrows(self.arrows) # generate a sequence of arrows to be displayed on screen def generate2DArrows(self,arrowList): self.movingArrows =[None] * self.FULLSCORE for i in range(len(arrowList)): imagePath = self._2DdownArrow if(arrowList[i].type == 'l'): imagePath = self._2DrightArrow arrow=OnscreenImage(image = imagePath, pos = (0.3, 0, 0)) arrow.setTransparency(TransparencyAttrib.MAlpha) arrow.setScale(0.1) x,y,z=-0.6,0,0 startX,startY,startZ=x+arrowList[i].getExpectedTime(),y,z arrow.setPos(startX,startY,startZ) arrow.reparentTo(self.getPanel('dance').getItem('GUIarrows')) arrow.hide() self.movingArrows[i] = arrow # let a sequence of arrows to move def move2DArrows(self): musicStartTime = self.game.getStartTime() for i in range(self.FULLSCORE): arrow = self.movingArrows[i] actualDuration = musicStartTime + self.arrows[i].getExpectedTime() - globalClock.getFrameTime() x,y,z=-0.6,0,0 startX,startY,startZ=x+self.arrows[i].getExpectedTime(),y,z animation=arrow.posInterval( actualDuration, Point3(-0.6,0,startZ), startPos=Point3(startX,startY,startZ)) animation.start() # function that stops the whole dance def stopSound(self): self.sound.stop() # check if the dance game ends def checkStop(self,task): if (self.sound.status()!=AudioSound.PLAYING): position=self.dancer.getPos() position[1]=0 position[2]=-0.4 self.getPanel('dance').getItem('GUIarrows').destroy() self.getPanel('dance').setItem('GUIarrows', DirectFrame(frameColor=(0.3,0.3,0.7,0.3), frameSize=(-0.8,.8,0.2,-0.2), pos=position)) self.taskMgr.remove('checkInFrame') self.taskMgr.remove('checkArrows') self.taskMgr.remove('checkColorStop') self.taskMgr.remove('checkStop') self.taskMgr.remove('spinCam') self.initGameScore() self.BGM.play() return task.cont # show all the arrows in displaying frame def checkInFrame(self,task): for i in range(len(self.movingArrows)): endTime=globalClock.getFrameTime() startTime = self.game.getStartTime() if int((self.arrows[i].getExpectedTime()-(endTime-startTime))*10)<=-1: self.movingArrows[i].hide() elif int(abs(self.arrows[i].getExpectedTime()-(endTime-startTime))*10)<=12: self.movingArrows[i].show() return task.cont # check if the effect of shining circle should stop def checkColorStop(self,task): endTime=globalClock.getFrameTime() time=endTime-self.colorStart if (endTime-self.pressedStart)>=0.001: self.pressed=None self.mode=self.NPRESSED if time>=0.2: hitSign = self.getPanel('dance').getItem('hitSign') scoreReminder = self.getPanel('dance').getItem('scoreReminder') hitSign.setImage('../textures/circle.png') hitSign.setTransparency(TransparencyAttrib.MAlpha) scoreReminder.hide() return task.cont # spin the camera def spinCam(self,task): time=task.time # THIS IS REALLY SIMILAR TO THE SAMPLE OF PANDA3D x,y,z=self.dancer.getPos() angleDegrees = task.time* 6.0 angleRadians = angleDegrees * (pi / 180.0) self.camera.setPos(x+20 * sin(angleRadians), y+-20.0 * cos(angleRadians), 0) self.camera.setHpr(angleDegrees, -5, 0) #END POINT OF SIMILARITY return Task.cont # function to be called after pressing key def pressKey(self, key): self.pressed=key self.pressedStart=globalClock.getFrameTime() self.game.keyPressed(key) # function that let the any icon to disappear def iconDisappear(self, icon, effectColor): LerpColorInterval(icon,0.2,color=(effectColor[0],effectColor[1],effectColor[2],0), startColor= (effectColor[0],effectColor[1],effectColor[2],1)).start() # the effect should display after some arrow events happen def pressEffect(self, type, idx): self.colorStart=globalClock.getFrameTime() self.getPanel('dance').getItem('scoreReminder').setText(type) if(type == 'MISS'): self.blinkColor((1,0,0)) self.mode = self.MISS if(idx != -1): self.iconDisappear(self.movingArrows[idx],(0.8,0.8,1)) elif(type == 'GOOD'): self.blinkColor((0,0,1)) self.mode = self.GOOD elif(type == 'PERFECT'): self.blinkColor((0,0,1)) self.mode = self.PERFECT if self.mode == self.GOOD or self.mode == self.PERFECT: self.dancer.play(self.animationDown[self.actionIndex]) self.actionIndex+=1 if self.actionIndex>=5: self.actionIndex=self.actionIndex%5 elif self.mode == self.MISS: self.dancer.stop() # let the stop circle blinks speficied light def blinkColor(self, effectColor): hitSign = self.getPanel('dance').getItem('hitSign') self.iconDisappear(hitSign,effectColor) scoreReminder = self.getPanel('dance').getItem('scoreReminder') scoreReminder.show() self.iconDisappear(scoreReminder, (0.4,0.4,0.7)) self.colorStart = globalClock.getFrameTime() # let the game score def initGameScore(self): score,miss,good,perfect = self.game.getScoreReport() self.setGameScoreBackground(score) self.highScoreTuple=self.updateHighestScore(score) self.gameScoreText=OnscreenText( text='Total: '+str(score),pos=(-0.8,0.7), scale = 0.2,fg=(1,0.78,0.18,1),mayChange=1) self.newHigh=OnscreenText( text='New High!',pos=(-0.7,0.5), scale = 0.15,fg=(1,1,1,1),mayChange=1) self.scoreFrame=DirectFrame(pos=(0.6,0,-0.6), frameSize = (-0.2,0.6,-0.2,0.2),frameColor=(0,0.1,0.3,1)) self.perfectLabel=DirectLabel( text='Perfect: '+str(perfect), pos=(0,0,.1),text_align=TextNode.ALeft, scale = 0.1,text_fg=(0.28,0.65,858,1), frameColor=(1,1,1,0),text_scale=(0.9,0.9)) self.goodLabel=DirectLabel( text='Good: '+str(good), pos=(0,0,0), scale = 0.1,text_fg=(0.52,0.67,0.52,1), text_align=TextNode.ALeft, frameColor=(1,1,1,0),text_scale=(0.9,0.9)) self.missLabel=DirectLabel( text='Miss: '+str(miss), pos=(0,0,-.1), scale = 0.1,text_fg=(0.72,0.67,0.67,1), text_align=TextNode.ALeft, frameColor=(1,1,1,0),text_scale=(0.9,0.9)) self.perfectLabel.reparentTo(self.scoreFrame) self.goodLabel.reparentTo(self.scoreFrame) self.missLabel.reparentTo(self.scoreFrame) self.retryButton=DirectButton(frameColor=(0,0.1,0.3,1), pos=(-1,0,-0.5), text="Retry", text_fg=(1,1,1,1),text_scale=(1,1), text_align=TextNode.ALeft, scale=.1, pad=(.2, .2),frameSize=(-1,6.6,-0.6,1), rolloverSound=None, clickSound=None, command=self.retry) self.mainMenuButton=DirectButton(frameColor=(0,0.1,0.3,1), pos=(-1,0,-0.7), text="Back To Menu", text_fg=(1,1,1,1),text_scale=(1,1),text_align=TextNode.ALeft, text_pos=(-0.5,-0.1), scale=.1, pad=(.2, .2),frameSize=(-1,6.6,-0.8,0.8), rolloverSound=None, clickSound=None, command=lambda: self.switchPanel('gameScore','mainMenu')) self.setPanel('gameScore',Panel(self.gameScoreBackground,{'scoreText':self.gameScoreText, 'newHigh':self.newHigh, 'scoreFrame':self.scoreFrame,'retry':self.retryButton,'mainMenu':self.mainMenuButton})) self.switchPanel('dance','gameScore') if self.highScoreTuple[1]: self.newHigh.show() else: self.newHigh.hide() # display different backgrounds for different scores def setGameScoreBackground(self, score): score=100*float(score)/self.FULLSCORE if score>=120: self.gameScoreBackground = OnscreenImage(parent=render2dp, image='../textures/SCORE_S.jpg') elif score>=100: self.gameScoreBackground = OnscreenImage(parent=render2dp, image='../textures/SCORE_A.jpg') elif score>=80: self.gameScoreBackground = OnscreenImage(parent=render2dp, image='../textures/SCORE_B.jpg') elif score>=60: self.gameScoreBackground=OnscreenImage(parent=render2dp, image='../textures/SCORE_C.jpg') else: self.gameScoreBackground=OnscreenImage(parent=render2dp, image='../textures/SCORE_F.jpg') # compare the score to the highest score of the music def updateHighestScore(self,score): highScore=self.highestScores[self.currSong] flag=False if score > highScore: highScore=score self.highestScores[self.currSong]=highScore oldFrame = self.getPanel('scoreBoard').getItem('frame') newFrame = self.createHighScoreFrame() self.getPanel('scoreBoard').setItem('frame',newFrame) newFrame.hide() oldFrame.destroy() file=open('musicGameData.txt','r') lines=file.readlines() newLines=lines changeLine=-1 for num,line in enumerate(lines): if line==self.currSong+'\n': changeLine=num+2 file.close() file=open('musicGameData.txt','w') newLines[changeLine]=str(highScore)+'\n' for line in newLines: file.write(line) file.close() flag=True return highScore,flag # function called to restart the dance def retry(self): self.createDance(self.musicPathes[self.currSong]) self.switchPanel('gameScore','dance')
def bld_page(self): mp_props = MultiplayerPageProps( self.props.cars, self.props.car_path, self.props.phys_path, self.props.tracks, self.props.tracks_tr, self.props.track_img, self.props.player_name, self.props.drivers_img, self.props.cars_img, self.props.drivers) sp_props = SingleplayerPageProps( self.props.cars, self.props.car_path, self.props.phys_path, self.props.tracks, self.props.tracks_tr, self.props.track_img, self.props.player_name, self.props.drivers_img, self.props.cars_img, self.props.has_save, self.props.season, self.props.season_tracks, self.props.drivers) sp_cb = lambda: self.menu.push_page( SingleplayerPage(self.menu.gui.menu_args, sp_props, self.menu)) mp_cb = lambda: self.menu.push_page( MultiplayerPage(self.menu.gui.menu_args, mp_props, self.menu)) supp_cb = lambda: eng.open_browser(self.props.support_url) cred_cb = lambda: self.menu.push_page( CreditPage(self.menu.gui.menu_args, self.menu)) menu_data = [('Single Player', _('Single Player'), sp_cb), ('Multiplayer', _('Multiplayer'), mp_cb), ('Options', _('Options'), self.on_options), ('Support us', _('Support us'), supp_cb), ('Credits', _('Credits'), cred_cb), ('Quit', _('Quit'), lambda: self.mdt.menu.gui.notify('on_exit'))] menu_gui = self.menu.gui widgets = [ DirectButton(text='', pos=(0, 1, .45 - i * .23), command=menu[2], **menu_gui.menu_args.btn_args) for i, menu in enumerate(menu_data) ] for i, wdg in enumerate(widgets): PageGui.transl_text(wdg, menu_data[i][0], menu_data[i][1]) if not self.props.multiplayer: widgets[-5]['state'] = DISABLED _fg = menu_gui.menu_args.btn_args['text_fg'] _fc = widgets[-5]['frameColor'] clc = lambda val: max(0, val) fgc = (_fg[0] - .3, _fg[1] - .3, _fg[2] - .3, _fg[3]) widgets[-5]['text_fg'] = fgc fcc = (clc(_fc[0] - .3), clc(_fc[1] - .3), clc(_fc[2] - .3), _fc[3]) widgets[-5]['frameColor'] = fcc widgets += [ OnscreenImage(self.props.title_img, scale=(.8, 1, .8 * (380.0 / 772)), parent=base.a2dTopRight, pos=(-.8, 1, -.4)) ] widgets[-1].setTransparency(True) lab_args = self.menu.gui.menu_args.label_args lab_args['scale'] = .12 lab_args['text_fg'] = self.menu.gui.menu_args.text_err lab = DirectLabel(text='', pos=(.05, 1, -.15), parent=base.a2dTopLeft, text_align=TextNode.A_left, **lab_args) PageGui.transl_text(lab, 'NB the game is work-in-progress', _('NB the game is work-in-progress')) self.widgets += [lab] map(self.add_widget, widgets) self.set_news() MainPageGui.bld_page(self)
def load(self): BookPage.load(self) # Let's load up the clouds. for pos, scale, hpr in self.cloudPos: cloud = loader.loadModel('phase_3.5/models/gui/cloud.bam') cloud.reparentTo(self) cloud.setPos(pos) cloud.setScale(scale) cloud.setHpr(hpr) self.clouds.append(cloud) for pos, scale, hpr, hood in self.hoodClouds: if not base.localAvatar.hasDiscoveredHood( ZoneUtil.getZoneId(hood)): cloud = loader.loadModel('phase_3.5/models/gui/cloud.bam') cloud.reparentTo(self) cloud.setPos(pos) cloud.setScale(scale) cloud.setHpr(hpr) self.clouds.append(cloud) for pos, name in self.labelData: if base.localAvatar.hasDiscoveredHood(ZoneUtil.getZoneId(name)): text = name if base.localAvatar.hasTeleportAccess( ZoneUtil.getZoneId(name)): text = 'Go To\n' + text label = DirectButton( parent=self, relief=None, pos=pos, pad=(0.2, 0.16), text=('', text, text, ''), text_bg=Vec4(1, 1, 1, 0.4), text_scale=0.055, text_wordwrap=8, rolloverSound=CIGlobals.getRolloverSound(), clickSound=None, pressEffect=0, sortOrder=1, text_font=CIGlobals.getToonFont()) if base.localAvatar.hasTeleportAccess( ZoneUtil.getZoneId(name)): label['command'] = self.book.finished label['extraArgs'] = [ZoneUtil.getZoneId(name)] label.resetFrameSize() self.labels.append(label) currHoodName = base.cr.playGame.hood.id currLocation = '' if base.localAvatar.zoneId == ZoneUtil.MinigameAreaId or base.localAvatar.getBattleZone( ) is not None: currLocation = '' elif ZoneUtil.getWhereName(base.localAvatar.zoneId) == 'playground': currLocation = 'Playground' elif ZoneUtil.getWhereName( base.localAvatar.zoneId) in ['street', 'interior']: currLocation = ZoneUtil.BranchZone2StreetName[ ZoneUtil.getBranchZone(base.localAvatar.zoneId)] self.infoLabel = DirectLabel(relief=None, text='You are in: {0}\n{1}'.format( currHoodName, currLocation), scale=0.06, pos=(-0.4, 0, -0.74), parent=self, text_align=TextNode.ACenter) if currHoodName in [ZoneUtil.MinigameArea, ZoneUtil.BattleTTC]: currHoodName = base.cr.playGame.lastHood btpText = 'Back to Playground' btpEA = [ZoneUtil.getZoneId(currHoodName)] self.BTPButton = DirectButton(relief=None, text=btpText, geom=CIGlobals.getDefaultBtnGeom(), text_pos=(0, -0.018), geom_scale=(1.3, 1.11, 1.11), text_scale=0.06, parent=self, text_font=CIGlobals.getToonFont(), pos=(0.25, 0, -0.75), command=self.book.finished, extraArgs=btpEA, scale=0.7) icons = loader.loadModel('phase_3.5/models/gui/sos_textures.bam') self.icon = icons.find('**/teleportIcon') icons.detachNode()
class MapPage(BookPage, DirectFrame): def __init__(self, book): BookPage.__init__(self, book, 'Map', wantHeader=False) DirectFrame.__init__(self, parent=book, relief=None, pos=(0, 0, 0.0775), image_scale=(1.8, 1, 1.35), scale=0.97) self['image'] = loader.loadModel( 'phase_3.5/models/gui/toontown_map.bam') self.initialiseoptions(MapPage) self.hide() self.cloudPos = [[(-0.61, 0, 0.18), (0.55, 0.25, 0.37), (180, 0, 0)], [(-0.54, 0, 0.34), (0.76, 0.4, 0.55), (180, 0, 0)], [(-0.55, 0, -0.09), (0.72, 0.4, 0.55), (0, 0, 0)], [(-0.67, 0, -0.51), (0.5, 0.29, 0.38), (180, 0, 0)], [(-0.67, 0, 0.51), (0.50, 0.29, 0.38), (0, 0, 0)], [(0.67, 0, 0.51), (0.5, 0.29, 0.38), (0, 0, 0)], [(0.35, 0, -0.46), (0.63, 0.35, 0.45), (0, 0, 0)], [(0.18, 0, -0.45), (0.52, 0.27, 0.32), (0, 0, 0)], [(0.67, 0, -0.44), (0.63, 0.35, 0.48), (180, 0, 0)]] self.hoodClouds = [ #[(0.02, 0, -0.17), (0.63, 0.35, 0.48), (180, 0, 0), ZoneUtil.ToontownCentral], [(0.63, 0, -0.13), (0.63, 0.35, 0.40), (0, 0, 0), ZoneUtil.DonaldsDock], [(0.51, 0, 0.25), (0.57, 0.35, 0.40), (0, 0, 0), ZoneUtil.TheBrrrgh], [(0.03, 0, 0.19), (0.63, 0.35, 0.40), (180, 0, 0), ZoneUtil.MinniesMelodyland], [(-0.08, 0, 0.46), (0.54, 0.35, 0.40), (0, 0, 0), ZoneUtil.DonaldsDreamland], [(-0.28, 0, -0.49), (0.60, 0.35, 0.45), (0, 0, 0), ZoneUtil.DaisyGardens] ] self.labelData = [[(0, 0, -0.2), ZoneUtil.ToontownCentral], [(0.65, 0, -0.125), ZoneUtil.DonaldsDock], [(0.07, 0, 0.18), ZoneUtil.MinniesMelodyland], [(-0.1, 0, 0.45), ZoneUtil.DonaldsDreamland], [(0.5, 0, 0.25), ZoneUtil.TheBrrrgh], [(-0.37, 0, -0.525), ZoneUtil.DaisyGardens]] # The buttons self.infoLabel = None self.BTPButton = None self.clouds = [] self.labels = [] def enter(self): BookPage.enter(self) self.show() def exit(self): BookPage.exit(self) self.hide() def load(self): BookPage.load(self) # Let's load up the clouds. for pos, scale, hpr in self.cloudPos: cloud = loader.loadModel('phase_3.5/models/gui/cloud.bam') cloud.reparentTo(self) cloud.setPos(pos) cloud.setScale(scale) cloud.setHpr(hpr) self.clouds.append(cloud) for pos, scale, hpr, hood in self.hoodClouds: if not base.localAvatar.hasDiscoveredHood( ZoneUtil.getZoneId(hood)): cloud = loader.loadModel('phase_3.5/models/gui/cloud.bam') cloud.reparentTo(self) cloud.setPos(pos) cloud.setScale(scale) cloud.setHpr(hpr) self.clouds.append(cloud) for pos, name in self.labelData: if base.localAvatar.hasDiscoveredHood(ZoneUtil.getZoneId(name)): text = name if base.localAvatar.hasTeleportAccess( ZoneUtil.getZoneId(name)): text = 'Go To\n' + text label = DirectButton( parent=self, relief=None, pos=pos, pad=(0.2, 0.16), text=('', text, text, ''), text_bg=Vec4(1, 1, 1, 0.4), text_scale=0.055, text_wordwrap=8, rolloverSound=CIGlobals.getRolloverSound(), clickSound=None, pressEffect=0, sortOrder=1, text_font=CIGlobals.getToonFont()) if base.localAvatar.hasTeleportAccess( ZoneUtil.getZoneId(name)): label['command'] = self.book.finished label['extraArgs'] = [ZoneUtil.getZoneId(name)] label.resetFrameSize() self.labels.append(label) currHoodName = base.cr.playGame.hood.id currLocation = '' if base.localAvatar.zoneId == ZoneUtil.MinigameAreaId or base.localAvatar.getBattleZone( ) is not None: currLocation = '' elif ZoneUtil.getWhereName(base.localAvatar.zoneId) == 'playground': currLocation = 'Playground' elif ZoneUtil.getWhereName( base.localAvatar.zoneId) in ['street', 'interior']: currLocation = ZoneUtil.BranchZone2StreetName[ ZoneUtil.getBranchZone(base.localAvatar.zoneId)] self.infoLabel = DirectLabel(relief=None, text='You are in: {0}\n{1}'.format( currHoodName, currLocation), scale=0.06, pos=(-0.4, 0, -0.74), parent=self, text_align=TextNode.ACenter) if currHoodName in [ZoneUtil.MinigameArea, ZoneUtil.BattleTTC]: currHoodName = base.cr.playGame.lastHood btpText = 'Back to Playground' btpEA = [ZoneUtil.getZoneId(currHoodName)] self.BTPButton = DirectButton(relief=None, text=btpText, geom=CIGlobals.getDefaultBtnGeom(), text_pos=(0, -0.018), geom_scale=(1.3, 1.11, 1.11), text_scale=0.06, parent=self, text_font=CIGlobals.getToonFont(), pos=(0.25, 0, -0.75), command=self.book.finished, extraArgs=btpEA, scale=0.7) icons = loader.loadModel('phase_3.5/models/gui/sos_textures.bam') self.icon = icons.find('**/teleportIcon') icons.detachNode() def unload(self): BookPage.unload(self) # Destroy the GUI elements. self.infoLabel.destroy() self.BTPButton.destroy() self.destroy() # Destroy the labels. for label in self.labels: label.destroy() # Destroy the clouds. for cloud in self.clouds: cloud.removeNode() self.clouds.remove(cloud) del self.labels del self.clouds del self.infoLabel del self.BTPButton
class MatchMsgFrm(GameObject): def __init__(self, menu_args): GameObject.__init__(self) self.eng.log('created match message form') self.chat = None self.msg_frm = DirectFrame( frameSize=(-.02, 2.5, 0, 1.22), frameColor=(.2, .2, .2, .5), pos=(.04, 1, -1.69), parent=base.a2dTopLeft) t_a = menu_args.text_args t_a['scale'] = .05 t_a['fg'] = menu_args.text_normal self.dst_txt = OnscreenText( text='', pos=(0, 1.16), parent=self.msg_frm, align=TextNode.A_left, **t_a) self.ent = Entry( scale=.04, pos=(0, 1, .03), entryFont=menu_args.font, width=62, frameColor=menu_args.btn_color, parent=self.msg_frm, initialText=_('write here your message'), command=self.on_typed_msg, focusInCommand=self.on_focus, focusInExtraArgs=['in'], focusOutCommand=self.on_focus, focusOutExtraArgs=['out'], text_fg=menu_args.text_active) self.ent['state'] = DISABLED self.txt_frm = DirectScrolledFrame( frameSize=(-.02, 2.46, -.02, 1.02), canvasSize=(-.02, 2.42, -.02, 1.02), scrollBarWidth=.036, verticalScroll_relief=FLAT, verticalScroll_frameColor=(.2, .2, .2, .4), verticalScroll_thumb_relief=FLAT, verticalScroll_thumb_frameColor=(.8, .8, .8, .6), verticalScroll_incButton_relief=FLAT, verticalScroll_incButton_frameColor=(.8, .8, .8, .6), verticalScroll_decButton_relief=FLAT, verticalScroll_decButton_frameColor=(.8, .8, .8, .6), horizontalScroll_relief=FLAT, frameColor=(1, 1, 1, .0), pos=(.02, 1, .11), parent=self.msg_frm) t_a['scale'] = .046 self.msg_txt = OnscreenText( text='', pos=(0, .24), parent=self.txt_frm.getCanvas(), align=TextNode.A_left, wordwrap=52, **t_a) lab_args = menu_args.label_args lab_args['scale'] = .046 lab_args['text_fg'] = menu_args.text_normal self.lab_frm = Btn( frameSize=(-.02, 2.5, -.01, .05), frameColor=(1, 1, 1, 0), pos=(0, 1, 1.15), parent=self.msg_frm) self.lab_frm.bind(ENTER, self.on_enter) self.lab_frm.bind(EXIT, self.on_exit) self.tooltip = DirectLabel( text='', pos=(2.4, 1, -.06), parent=self.lab_frm, text_wordwrap=50, text_bg=(.2, .2, .2, .8), text_align=TextNode.A_right, **lab_args) self.tooltip.set_bin('gui-popup', 10) self.tooltip.hide() def on_enter(self, pos): self.tooltip.show() def on_exit(self, pos): self.tooltip.hide() def add_msg_txt(self, msg): self.msg_txt['text'] += ('\n' if self.msg_txt['text'] else '') + msg txt_height = self.msg_txt.textNode.getUpperLeft3d()[2] - \ self.msg_txt.textNode.getLowerRight3d()[2] self.txt_frm['canvasSize'] = (-.02, .72, .28 - txt_height, .28) def set_title(self, title): ttitle = self.trunc(title, 160) fix_name = lambda name: name if '@' not in name else name.split('@')[0] + '\1smaller\1@' + name.split('@')[1] + '\2' if title: if ',' in ttitle: is_muc = True ttitle = ttitle names = ttitle.split(',') names = [name.strip() for name in names] names = [fix_name(name) for name in names] ttitle = ', '.join(names) else: ttitle = fix_name(ttitle) self.dst_txt['text'] = ttitle self.tooltip['text'] = title @staticmethod def trunc(name, lgt): if len(name) > lgt: return name[:lgt] + '...' return name def on_typed_msg(self, val): #self.add_msg_txt('\1italic\1' + _('you') + '\2: ' + val) self.ent.set('') self.eng.xmpp.client.send_message( mfrom=self.eng.xmpp.client.boundjid.full, mto=self.chat.dst, mtype='groupchat', mbody=val) self.ent['focus'] = 1 def on_groupchat_msg(self, msg): src = str(JID(msg['mucnick'])) src = src.split('@')[0] + '\1smaller\1@' + src.split('@')[1] + '\2' self.eng.log('received groupchat message from %s in the chat %s' %(msg['mucnick'], JID(msg['from']).bare)) str_msg = '\1italic\1' + src + '\2: ' + str(msg['body']) if not self.chat: self.chat = MUC(str(JID(msg['from']).bare)) self.chat.messages += [str_msg] if self.dst_txt['text'] == '': self.set_chat(self.chat) elif self.chat.dst == str(JID(msg['from']).bare): self.add_msg_txt(str_msg) def on_presence_available_room(self, msg): room = str(JID(msg['muc']['room']).bare) nick = str(msg['muc']['nick']) self.eng.log('user %s has logged in the chat %s' %(nick, room)) self.chat.users += [nick] self.set_title(self.chat.title) def on_presence_unavailable_room(self, msg): room = str(JID(msg['muc']['room']).bare) nick = str(msg['muc']['nick']) self.eng.log('user %s has left the chat %s' %(nick, room)) self.chat.users.remove(nick) self.set_title(self.chat.title) def add_groupchat(self, room, usr): self.set_title(usr) if not self.chat: self.chat = MUC(room) self.set_chat(self.chat) def set_chat(self, chat): self.set_title(chat.title) self.msg_txt['text'] = '\n'.join(chat.messages) txt_height = self.msg_txt.textNode.getUpperLeft3d()[2] - \ self.msg_txt.textNode.getLowerRight3d()[2] self.txt_frm['canvasSize'] = (-.02, .72, .28 - txt_height, .28) self.ent['state'] = NORMAL def on_focus(self, val): if val == 'in' and self.ent.get() == _('write here your message'): self.ent.set('') self.notify('on_match_msg_focus', val) def destroy(self): self.eng.log('message form destroyed') self.msg_frm.destroy() GameObject.destroy(self)
value=0, minValue=-10, maxValue=10, repeatdelay=0.125, buttonOrientation=DGG.HORIZONTAL, valueEntry_text_align=TextNode.ACenter, borderWidth=(.1, .1)) spinBox.setScale(0.1) spinBox["relief"] = 2 spinBoxSizer = DirectBoxSizer( orientation=DGG.VERTICAL, autoUpdateFrameSize=False, frameSize=(0, 0, spinBox["frameSize"][2] * spinBox.getScale()[0] * 2, spinBox["frameSize"][3] * spinBox.getScale()[0] * 2), itemAlign=DirectBoxSizer.A_Center | DirectBoxSizer.A_Middle) spinerInfo = DirectLabel(text="Change diagram value range: ", scale=0.1) spinBoxSizer.addItem(spinerInfo) spinBoxSizer.addItem(spinBox) spinAutoSizer = DirectAutoSizer(splitSizer.secondFrame, extendVertical=False, child=spinBoxSizer, childUpdateSizeFunc=spinBoxSizer.refresh) # DIAGRAM data = [10, -5, 1, -1, 1, -1, 1, -1, 1, -1] height = (1 + mainBox.itemsBottom) / 2 dd = DirectDiagram(data=data, numberAreaWidth=0.15, numNegSteps=20, numPosSteps=20, numNegStepsStep=2,
def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.777778, 1.77777778, -1.1638, 1.1638), hpr=LVecBase3f(0, 0, 0), image='assets/menu/Background.png', pos=LPoint3f(0, 0, 0), image_scale=LVecBase3f(1.77778, 1, 1.1638), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmRoomList = DirectScrolledFrame( canvasSize=(-1.0, 1.0, -2.0, 0.0), frameColor=(1, 1, 1, 1), frameSize=(-1.0, 1.08, -1.4, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.7), scrollBarWidth=0.08, state='normal', horizontalScroll_borderWidth=(0.01, 0.01), horizontalScroll_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_hpr=LVecBase3f(0, 0, 0), horizontalScroll_pos=LPoint3f(0, 0, 0), horizontalScroll_decButton_borderWidth=(0.01, 0.01), horizontalScroll_decButton_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_decButton_hpr=LVecBase3f(0, 0, 0), horizontalScroll_decButton_pos=LPoint3f(-0.96, 0, -1.36), horizontalScroll_incButton_borderWidth=(0.01, 0.01), horizontalScroll_incButton_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_incButton_hpr=LVecBase3f(0, 0, 0), horizontalScroll_incButton_pos=LPoint3f(0.96, 0, -1.36), horizontalScroll_thumb_borderWidth=(0.01, 0.01), horizontalScroll_thumb_hpr=LVecBase3f(0, 0, 0), horizontalScroll_thumb_pos=LPoint3f(0, 0, -1.36), verticalScroll_borderWidth=(0.01, 0.01), verticalScroll_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_hpr=LVecBase3f(0, 0, 0), verticalScroll_pos=LPoint3f(0, 0, 0), verticalScroll_decButton_borderWidth=(0.01, 0.01), verticalScroll_decButton_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_decButton_hpr=LVecBase3f(0, 0, 0), verticalScroll_decButton_pos=LPoint3f(1.04, 0, -0.04), verticalScroll_incButton_borderWidth=(0.01, 0.01), verticalScroll_incButton_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_incButton_hpr=LVecBase3f(0, 0, 0), verticalScroll_incButton_pos=LPoint3f(1.04, 0, -1.28), verticalScroll_thumb_borderWidth=(0.01, 0.01), verticalScroll_thumb_hpr=LVecBase3f(0, 0, 0), verticalScroll_thumb_pos=LPoint3f(1.04, 0, -0.4628), parent=self.frmMain, ) self.frmRoomList.setTransparency(0) self.btnBack = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.96, 0, -0.825), scale=LVecBase3f(0.1, 0.1, 0.1), text='Back', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=base.messenger.send, extraArgs=["roomList_back"], ) self.btnBack.setTransparency(0) self.lblRoomName = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-1, 0, 0.725), scale=LVecBase3f(0.07, 0.1, 0.07), text='Room Name', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblRoomName.setTransparency(0) self.lblPlayerCount = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.15, 0, 0.725), scale=LVecBase3f(0.07, 0.1, 0.07), text='Players', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblPlayerCount.setTransparency(0) self.btnCreateRoom = DirectButton( hpr=LVecBase3f(0, 0, 0), pad=(0.2, 0.2), pos=LPoint3f(-0.955, 0, -0.815), scale=LVecBase3f(0.1, 0.1, 0.1), text='+', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.btnCreateRoom.setTransparency(0) self.btnReloadRoomList = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.025, 0, -0.825), scale=LVecBase3f(0.1, 0.1, 0.1), text='Reload Rooms', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=base.messenger.send, extraArgs=["roomList_reload"], ) self.btnReloadRoomList.setTransparency(0) self.lblGameType = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.125, 0, 0.725), scale=LVecBase3f(0.07, 0.1, 0.07), text='Type', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblGameType.setTransparency(0) self.lblDifficulty = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.54, 0, 0.72), scale=LVecBase3f(0.07, 0.1, 0.07), text='Difficulty', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblDifficulty.setTransparency(0)
def __init__(self): self.canPlantLabel = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.15, pos=(0, 0, 0.25), pad=(0.2,0.2), text=_("Plant Seed")) self.canPlantLabel.setTransparency(True) self.canPlantLabel.reparentTo(base.a2dBottomCenter) self.canPlantLabel.hide() self.speekLabel = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.15, pos=(0, 0, 0.5), pad=(0.2,0.2), text="...") self.speekLabel.reparentTo(render) self.speekLabel.hide() self.speekLabel.setTransparency(True) self.speekLabel.setEffect(BillboardEffect.makePointEye()) self.speekLabel.setBin("fixed", 11) self.speekLabel.setDepthWrite(False) self.storyText = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.08, pos=(0, 0, 0.25), pad=(0.2,0.2), text="Story text") self.storyText.setTransparency(True) self.storyText.reparentTo(base.a2dBottomCenter) self.storyText.hide() self.points = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(0.05, 0, -0.1), pad=(0.2,0.2), text_align=TextNode.ALeft, text=_("Points: %d")%0) self.points.setTransparency(True) self.points.reparentTo(base.a2dTopLeft) self.playerWater = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(0.05, 0, -0.2), pad=(0.2,0.2), text_align=TextNode.ALeft, text=_("Remaining Water: %d")%100) self.playerWater.setTransparency(True) self.playerWater.reparentTo(base.a2dTopLeft) self.helpInfo = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(-0.05, 0, -0.1), pad=(0.2,0.2), text_align=TextNode.ARight, text=_("F1 - show help")) self.helpInfo.setTransparency(True) self.helpInfo.reparentTo(base.a2dTopRight) self.hide()
class FileBrowser(DirectObject): def __init__(self, command, fileBrowser=False, defaultPath="~", defaultFilename="unnamed.txt", fileExtensions=[], tooltip=None): """ A simple file and folder browser command: The command that will be called on closing the browser fileBrowser: If set to True the browser will show files, otherwise it will only show folders defaultPath: The initial path the browser will be set to show defaultFilename: The filename that will be set by default, only usefull if fileBrowser is True fileExtensions: A list of extensions. Only files with those extensions will be shown. Only usefull if fileBrowser is True tooltip: An instance of the Tooltip class to display tooltips for certain parts of the editor """ self.tt = tooltip self.command = command self.showFiles = fileBrowser self.fileExtensions = fileExtensions self.currentPath = os.path.expanduser(defaultPath) if not os.path.exists(self.currentPath): self.currentPath = os.path.expanduser("~") self.previousPath = self.currentPath self.screenWidthPx = base.getSize()[0] self.screenWidthPxHalf = self.screenWidthPx * 0.5 self.screenHeightPx = base.getSize()[1] self.screenHeightPxHalf = self.screenHeightPx * 0.5 self.mainFrame = DirectFrame( relief=1, frameSize=(-self.screenWidthPxHalf, self.screenWidthPxHalf, -self.screenHeightPxHalf, self.screenHeightPxHalf), frameColor=(1, 1, 1, 1), pos=LPoint3f(base.getSize()[0] / 2, 0, -base.getSize()[1] / 2), parent=base.pixel2d, state=DGG.NORMAL, ) self.pathEntryWidth = self.screenWidthPx - 125 self.pathEntry = DirectEntry( parent=self.mainFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f(-self.screenWidthPxHalf + 15, 0, self.screenHeightPxHalf - 25), scale=12, width=self.pathEntryWidth / 12, overflow=True, command=self.entryAccept, initialText=self.currentPath, focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) x = self.pathEntryWidth / 2 - 28 self.btnReload = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderReload, image="icons/Reload.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnReload.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnReload.bind(DGG.ENTER, self.tt.show, ["Reload Folder"]) self.btnReload.bind(DGG.EXIT, self.tt.hide) x += 28 self.btnFolderUp = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderUp, image="icons/FolderUp.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnFolderUp.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnFolderUp.bind(DGG.ENTER, self.tt.show, ["Move up one level"]) self.btnFolderUp.bind(DGG.EXIT, self.tt.hide) x += 28 self.btnFolderNew = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderNew, image="icons/FolderNew.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnFolderNew.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnFolderNew.bind(DGG.ENTER, self.tt.show, ["Create new folder"]) self.btnFolderNew.bind(DGG.EXIT, self.tt.hide) color = ( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)) # Disabled self.container = DirectScrolledFrame( relief=DGG.RIDGE, borderWidth=(2, 2), frameColor=(1, 1, 1, 1), frameSize=(-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -self.screenHeightPxHalf + 50, self.screenHeightPxHalf - 50), canvasSize=(-self.screenWidthPxHalf + 31, self.screenWidthPxHalf - 10, -self.screenHeightPxHalf + 50, self.screenHeightPxHalf - 50), pos=LPoint3f(0, 0, 0), parent=self.mainFrame, scrollBarWidth=20, verticalScroll_scrollSize=20, verticalScroll_thumb_relief=DGG.FLAT, verticalScroll_incButton_relief=DGG.FLAT, verticalScroll_decButton_relief=DGG.FLAT, verticalScroll_thumb_frameColor=color, verticalScroll_incButton_frameColor=color, verticalScroll_decButton_frameColor=color, horizontalScroll_thumb_relief=DGG.FLAT, horizontalScroll_incButton_relief=DGG.FLAT, horizontalScroll_decButton_relief=DGG.FLAT, horizontalScroll_thumb_frameColor=color, horizontalScroll_incButton_frameColor=color, horizontalScroll_decButton_frameColor=color, state=DGG.NORMAL, ) self.container.bind(DGG.MWDOWN, self.scroll, [0.01]) self.container.bind(DGG.MWUP, self.scroll, [-0.01]) self.btnOk = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 160, 0, -self.screenHeightPxHalf + 25), text="ok", text_scale=12, command=command, extraArgs=[1], ) self.btnCancel = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 55, 0, -self.screenHeightPxHalf + 25), text="Cancel", text_scale=12, command=command, extraArgs=[0]) if self.showFiles: self.txtFileName = DirectEntry( parent=self.mainFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f(-self.screenWidthPxHalf + 25, 0, -self.screenHeightPxHalf + 25), scale=12, width=200 / 12, overflow=True, command=self.filenameAccept, initialText=defaultFilename, focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) self.newFolderFrame = DirectFrame( parent=self.mainFrame, relief=1, frameSize=(-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -20, 20), pos=LPoint3f(0, 0, self.screenHeightPxHalf - 55), frameColor=(0.5, 0.5, 0.5, 1), ) self.txtNewFolderName = DirectLabel( parent=self.newFolderFrame, text="New Folder Name", text_scale=12, frameColor=(0, 0, 0, 0), text_align=TextNode.ALeft, pos=(-self.screenWidthPxHalf + 15, 0, -3), ) self.folderName = DirectEntry( parent=self.newFolderFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f( -self.screenWidthPxHalf + 25 + self.txtNewFolderName.getWidth(), 0, -4), scale=12, width=((self.screenWidthPxHalf - 25) * 2 - self.txtNewFolderName.getWidth() - 100) / 12, overflow=True, command=self.entryAccept, initialText="New Folder", focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) self.btnCreate = DirectButton( parent=self.newFolderFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 65, 0, -4), text="Create", text_scale=12, command=self.folderCreate, extraArgs=[0]) self.newFolderFrame.hide() self.folderReload() # handle window resizing self.prevScreenSize = base.getSize() self.accept("window-event", self.windowEventHandler) def show(self): self.mainFrame.show() self.accept("window-event", self.windowEventHandler) def hide(self): self.ignore("window-event") self.mainFrame.hide() def destroy(self): self.ignore("window-event") self.mainFrame.destroy() def scroll(self, scrollStep, event): self.container.verticalScroll.scrollStep(scrollStep) def get(self): if self.showFiles: return os.path.join(self.currentPath, self.txtFileName.get(True)) return self.currentPath def filenameAccept(self, filename): self.command(1) def entryAccept(self, path): self.folderReload() def folderReload(self): for element in self.container.getCanvas().getChildren(): element.removeNode() path = self.pathEntry.get(True) path = os.path.expanduser(path) path = os.path.expandvars(path) if not os.path.exists(path): return self.currentPath = path try: content = os.scandir(path) except PermissionError: base.messenger.send("showWarning", ["Access denied!"]) self.pathEntry.set(self.previousPath) self.currentPath = self.previousPath self.folderReload() return # start position for the folders and files xPos = -self.screenWidthPxHalf + 20 + 50 - 110 zPos = self.screenHeightPxHalf - 60 - 40 dirList = [] fileList = [] unkList = [] for entry in content: if entry.is_dir(): dirList.append(entry) elif entry.is_file() and self.showFiles: if len(self.fileExtensions) > 0: if os.path.splitext(entry.name)[1] in self.fileExtensions: fileList.append(entry) else: fileList.append(entry) elif self.showFiles: unkList.append(entry) def moveNext(entry): nonlocal xPos nonlocal zPos if entry.is_dir() or self.showFiles: if xPos + 110 > self.screenWidthPxHalf - 45: # move to the next line if we hit the right border (incl. scrollbar size) xPos = -self.screenWidthPxHalf + 20 + 50 zPos -= 110 else: # move right the next position xPos += 110 def getKey(item): return item.name.lower() for entry in sorted(dirList, key=getKey): moveNext(entry) self.__createFolder(entry, xPos, zPos) for entry in sorted(fileList, key=getKey): moveNext(entry) self.__createFile(entry.name, xPos, zPos) for entry in sorted(unkList, key=getKey): moveNext(entry) self.__createUnknown(entry.name, xPos, zPos) # recalculate the canvas size self.container["canvasSize"] = (-self.screenWidthPxHalf + 31, self.screenWidthPxHalf - 15, zPos - 90, self.screenHeightPxHalf - 50) self.container.setCanvasSize() def folderUp(self): self.previousPath = self.currentPath self.currentPath = os.path.normpath( os.path.join(self.currentPath, "..")) self.pathEntry.set(self.currentPath) self.folderReload() def folderMoveIn(self, path): path = os.path.expanduser(path) path = os.path.expandvars(path) self.previousPath = self.currentPath self.currentPath = path self.pathEntry.set(path) self.folderReload() self.container.verticalScroll["value"] = 0 def folderNew(self): if self.newFolderFrame.isHidden(): self.newFolderFrame.show() else: self.newFolderFrame.hide() def folderCreate(self, path=""): try: os.makedirs( os.path.join(self.currentPath, self.folderName.get(True))) except: base.messenger.send("showWarning", ["Can't create folder"]) self.newFolderFrame.hide() self.folderReload() def __createFolder(self, entry, xPos, zPos): name = entry.name if len(entry.name) > 10: name = "" for i in range(max(math.ceil(len(entry.name) / 10), 4)): name += entry.name[i * 10:i * 10 + 10] + "\n" name = name[:-1] if math.ceil(len(entry.name) / 10) > 4: name += "..." btn = DirectButton( parent=self.container.getCanvas(), image="icons/Folder.png", image_scale=35, relief=1, frameColor=( (0.9, 0.9, 0.9, 0), # Normal (0.95, 0.95, 1, 1), # Click (0.9, 0.9, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-40, 40, -40, 40), pos=LPoint3f(xPos, 0, zPos), text=name, text_scale=12, text_pos=(0, -40), command=self.folderMoveIn, extraArgs=[entry.path]) btn.bind(DGG.MWDOWN, self.scroll, [0.01]) btn.bind(DGG.MWUP, self.scroll, [-0.01]) btn.setTransparency(TransparencyAttrib.M_multisample) def __createFile(self, filename, xPos, zPos): name = filename if len(filename) > 10: name = "" for i in range(min(math.ceil(len(filename) / 10), 4)): name += filename[i * 10:i * 10 + 10] + "\n" name = name[:-1] if math.ceil(len(filename) / 10) > 4: name += "..." btn = DirectButton( parent=self.container.getCanvas(), image="icons/File.png", image_scale=35, relief=1, frameColor=( (0.9, 0.9, 0.9, 0), # Normal (0.95, 0.95, 1, 1), # Click (0.9, 0.9, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-40, 40, -40, 40), pos=LPoint3f(xPos, 0, zPos), text=name, text_scale=12, text_pos=(0, -40), command=self.txtFileName.set, extraArgs=[filename]) btn.bind(DGG.MWDOWN, self.scroll, [0.01]) btn.bind(DGG.MWUP, self.scroll, [-0.01]) btn.setTransparency(TransparencyAttrib.M_multisample) def __createUnknown(self, filename, xPos, zPos): name = filename if len(filename) > 10: name = "" for i in range(math.ceil(len(filename) / 10)): name += filename[i * 10:i * 10 + 10] + "\n" name = name[:-1] lbl = DirectLabel( parent=self.container.getCanvas(), image="icons/File.png", image_scale=35, image_color=(0.9, 0.5, 0.5, 1), relief=1, frameColor=(0.7, 0.7, 0.7, 0), frameSize=(-40, 40, -40, 40), pos=LPoint3f(xPos, 0, zPos), text=name, text_scale=12, text_pos=(0, -40), ) lbl.bind(DGG.MWDOWN, self.scroll, [0.01]) lbl.bind(DGG.MWUP, self.scroll, [-0.01]) lbl.setTransparency(TransparencyAttrib.M_multisample) def windowEventHandler(self, window=None): if window != base.win: # This event isn't about our window. return if window is not None: # window is none if panda3d is not started if self.prevScreenSize == base.getSize(): return self.prevScreenSize = base.getSize() self.screenWidthPx = base.getSize()[0] self.screenWidthPxHalf = self.screenWidthPx * 0.5 self.screenHeightPx = base.getSize()[1] self.screenHeightPxHalf = self.screenHeightPx * 0.5 # reposition and resize all gui elements self.mainFrame.setPos(self.screenWidthPx / 2, 0, -self.screenHeightPx / 2) self.mainFrame["frameSize"] = (-self.screenWidthPxHalf, self.screenWidthPxHalf, -self.screenHeightPxHalf, self.screenHeightPxHalf) self.pathEntryWidth = self.screenWidthPx - 125 self.pathEntry.setPos( LPoint3f(-self.screenWidthPxHalf + 15, 0, self.screenHeightPxHalf - 25)) self.pathEntry["width"] = self.pathEntryWidth / 12 x = self.pathEntryWidth / 2 - 28 self.btnReload.setPos(LPoint3f(x, 0, self.screenHeightPxHalf - 25)) x += 28 self.btnFolderUp.setPos( pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25)) x += 28 self.btnFolderNew.setPos( pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25)) self.container["frameSize"] = (-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -self.screenHeightPxHalf + 50, self.screenHeightPxHalf - 50) # Note: canvas size of the container will be reset in the # folder Reload call at the end of this function self.btnOk.setPos( LPoint3f(self.screenWidthPxHalf - 160, 0, -self.screenHeightPxHalf + 25)) self.btnCancel.setPos( LPoint3f(self.screenWidthPxHalf - 55, 0, -self.screenHeightPxHalf + 25)) if self.showFiles: self.txtFileName.setPos( LPoint3f(-self.screenWidthPxHalf + 25, 0, -self.screenHeightPxHalf + 25)) self.newFolderFrame.setPos( LPoint3f(0, 0, self.screenHeightPxHalf - 55)) self.newFolderFrame["frameSize"] = (-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -20, 20) self.txtNewFolderName.setPos(-self.screenWidthPxHalf + 15, 0, -3) self.folderName.setPos( LPoint3f( -self.screenWidthPxHalf + 25 + self.txtNewFolderName.getWidth(), 0, -4)) self.folderName["width"] = ( (self.screenWidthPxHalf - 25) * 2 - self.txtNewFolderName.getWidth() - 100) / 12 self.btnCreate.setPos(LPoint3f(self.screenWidthPxHalf - 65, 0, -4)) self.folderReload()
def __init__(self, rootParent=None): self.frmMain = DirectFrame( borderWidth=(2, 2), frameColor=(1, 1, 1, 1), frameSize=(-300.0, 300.0, -250.0, 250.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.frmHeader = DirectFrame( borderWidth=(2, 2), frameColor=(0.25, 0.25, 0.25, 1.0), frameSize=(-300.0, 300.0, -20.0, 20.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 230), parent=self.frmMain, ) self.frmHeader.setTransparency(0) self.lblHeader = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-295, 0, -5), scale=LVecBase3f(1, 1, 1), text='Settings', text_align=TextNode.A_left, text_scale=(16.0, 16.0), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmHeader, ) self.lblHeader.setTransparency(0) self.btnOk = DirectButton( borderWidth=(2, 2), frameSize=(-45.0, 45.0, -6.0, 14.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(120, 0, -220), relief=1, scale=LVecBase3f(1, 1, 1), text='OK', text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=messenger.send, extraArgs=["Settings_OK"], ) self.btnOk.setTransparency(0) self.btnCancel = DirectButton( borderWidth=(2, 2), frameSize=(-45.0, 45.0, -6.0, 14.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(230, 0, -220), relief=1, scale=LVecBase3f(1, 1, 1), text='Cancel', text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=messenger.send, extraArgs=["Settings_CANCEL"], ) self.btnCancel.setTransparency(0) self.lblCustomWidgets = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, 5), scale=LVecBase3f(1, 1, 1), text='Custom widgets path:', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblCustomWidgets.setTransparency(0) self.txtCustomWidgetsPath = DirectEntry( borderWidth=(0.167, 0.167), hpr=LVecBase3f(0, 0, 0), overflow=1, pos=LPoint3f(-50, 0, 5), scale=LVecBase3f(12, 1, 12), width=18.0, text_align=TextNode.A_left, text_scale=(1.0, 1.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.txtCustomWidgetsPath.setTransparency(0) self.lblAskForQuit = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, 140), scale=LVecBase3f(1, 1, 1), text='Ask before quit:', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblAskForQuit.setTransparency(0) self.cbAskForQuit = DirectCheckButton( borderWidth=(2, 2), frameColor=(1.0, 1.0, 1.0, 1.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(110, 0, 145), scale=LVecBase3f(1, 1, 1), text='', indicator_borderWidth=(2, 2), indicator_hpr=LVecBase3f(0, 0, 0), indicator_pos=LPoint3f(-11, 0, -7.2), indicator_relief='sunken', indicator_text_align=TextNode.A_center, indicator_text_scale=(24, 24), indicator_text_pos=(0, -0.2), indicator_text_fg=LVecBase4f(0, 0, 0, 1), indicator_text_bg=LVecBase4f(0, 0, 0, 0), text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.cbAskForQuit.setTransparency(0) self.lblExecutableScripts = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, 95), scale=LVecBase3f(1, 1, 1), text='Create executable Scripts:', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblExecutableScripts.setTransparency(0) self.cbExecutableScripts = DirectCheckButton( borderWidth=(2, 2), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(110, 0, 100), scale=LVecBase3f(1, 1, 1), text='', indicator_borderWidth=(2, 2), indicator_hpr=LVecBase3f(0, 0, 0), indicator_pos=LPoint3f(-11, 0, -7.2), indicator_relief='sunken', indicator_text_align=TextNode.A_center, indicator_text_scale=(24, 24), indicator_text_pos=(0, -0.2), indicator_text_fg=LVecBase4f(0, 0, 0, 1), indicator_text_bg=LVecBase4f(0, 0, 0, 0), text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.cbExecutableScripts.setTransparency(0) self.btnBrowseWidgetPath = DirectButton( borderWidth=(2, 2), frameSize=(-45.25, 45.25, -6.0, 14.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(230, 0, 5), relief=1, scale=LVecBase3f(1, 1, 1), text='Browse', text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.btnBrowseWidgetPath.setTransparency(0) self.lblShowToolbar = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, 50), scale=LVecBase3f(1, 1, 1), text='Show toolbar', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblShowToolbar.setTransparency(0) self.cbShowToolbar = DirectCheckButton( borderWidth=(2, 2), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(110, 0, 55), scale=LVecBase3f(1, 1, 1), text='', indicator_borderWidth=(2, 2), indicator_hpr=LVecBase3f(0, 0, 0), indicator_pos=LPoint3f(-11, 0, -7.2), indicator_relief='sunken', indicator_text_align=TextNode.A_center, indicator_text_scale=(24, 24), indicator_text_pos=(0, -0.2), indicator_text_fg=LVecBase4f(0, 0, 0, 1), indicator_text_bg=LVecBase4f(0, 0, 0, 0), text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.cbShowToolbar.setTransparency(0) self.lblSearchPath = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, -45), scale=LVecBase3f(1, 1, 1), text='Search paths', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblSearchPath.setTransparency(0) self.txtSearchPaths = DirectEntry( borderWidth=(0.167, 0.167), frameSize=(-0.167, 18.167, -0.463, 1.155), hpr=LVecBase3f(0, 0, 0), overflow=1, pos=LPoint3f(-50, 0, -45), scale=LVecBase3f(12, 1, 12), width=18.0, text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.txtSearchPaths.setTransparency(0) self.btnBrowseSearchPaths = DirectButton( borderWidth=(2, 2), frameSize=(-45.25, 45.25, -6.0, 14.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(230, 0, -45), relief=1, scale=LVecBase3f(1, 1, 1), text='Browse', text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.btnBrowseSearchPaths.setTransparency(0) self.lblWorkDir = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, -95), scale=LVecBase3f(1, 1, 1), text='Default work directory', text_align=TextNode.A_left, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblWorkDir.setTransparency(0) self.txtWorkDir = DirectEntry( borderWidth=(0.08333333333333333, 0.08333333333333333), hpr=LVecBase3f(0, 0, 0), overflow=1, pos=LPoint3f(-50, 0, -95), scale=LVecBase3f(12, 1, 12), width=18.0, text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.txtWorkDir.setTransparency(0) self.btnBrowseWorkDir = DirectButton( borderWidth=(2, 2), frameSize=(-45.25, 45.25, -6.0, 14.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(230, 0, -95), relief=1, scale=LVecBase3f(1, 1, 1), text='Browse', text_align=TextNode.A_center, text_scale=(12.0, 12.0), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, pressEffect=1, ) self.btnBrowseWorkDir.setTransparency(0) self.spinAutosaveDealy = DirectSpinBox( frameSize=(-2.1, 1.0, -0.742, 0.742), hpr=LVecBase3f(0, 0, 0), maxValue=3600, minValue=10, pos=LPoint3f(105, 0, -140), value=60, scale=LVecBase3f(12, 1, 12), decButton_hpr=LVecBase3f(0, 0, 0), decButton_pos=LPoint3f(0.583333, 0, -0.533333), decButton_text='6', decButton_text0_align=TextNode.A_center, decButton_text0_scale=(1, 1), decButton_text0_pos=(0, 0), decButton_text0_fg=LVecBase4f(0, 0, 0, 1), decButton_text0_bg=LVecBase4f(0, 0, 0, 0), decButton_text0_wordwrap=None, decButton_text1_align=TextNode.A_center, decButton_text1_scale=(1, 1), decButton_text1_pos=(0, 0), decButton_text1_fg=LVecBase4f(0, 0, 0, 1), decButton_text1_bg=LVecBase4f(0, 0, 0, 0), decButton_text1_wordwrap=None, decButton_text2_align=TextNode.A_center, decButton_text2_scale=(1, 1), decButton_text2_pos=(0, 0), decButton_text2_fg=LVecBase4f(0, 0, 0, 1), decButton_text2_bg=LVecBase4f(0, 0, 0, 0), decButton_text2_wordwrap=None, decButton_text3_align=TextNode.A_center, decButton_text3_scale=(1, 1), decButton_text3_pos=(0, 0), decButton_text3_fg=LVecBase4f(0, 0, 0, 1), decButton_text3_bg=LVecBase4f(0, 0, 0, 0), decButton_text3_wordwrap=None, incButton_hpr=LVecBase3f(0, 0, 0), incButton_pos=LPoint3f(0.583333, 0, -0.016667), incButton_text='5', incButton_text0_align=TextNode.A_center, incButton_text0_scale=(1, 1), incButton_text0_pos=(0, 0), incButton_text0_fg=LVecBase4f(0, 0, 0, 1), incButton_text0_bg=LVecBase4f(0, 0, 0, 0), incButton_text0_wordwrap=None, incButton_text1_align=TextNode.A_center, incButton_text1_scale=(1, 1), incButton_text1_pos=(0, 0), incButton_text1_fg=LVecBase4f(0, 0, 0, 1), incButton_text1_bg=LVecBase4f(0, 0, 0, 0), incButton_text1_wordwrap=None, incButton_text2_align=TextNode.A_center, incButton_text2_scale=(1, 1), incButton_text2_pos=(0, 0), incButton_text2_fg=LVecBase4f(0, 0, 0, 1), incButton_text2_bg=LVecBase4f(0, 0, 0, 0), incButton_text2_wordwrap=None, incButton_text3_align=TextNode.A_center, incButton_text3_scale=(1, 1), incButton_text3_pos=(0, 0), incButton_text3_fg=LVecBase4f(0, 0, 0, 1), incButton_text3_bg=LVecBase4f(0, 0, 0, 0), incButton_text3_wordwrap=None, valueEntry_hpr=LVecBase3f(0, 0, 0), valueEntry_initialText='60', valueEntry_pos=LPoint3f(0, 0, -0.345625), valueEntry_text_align=TextNode.A_right, valueEntry_text_scale=(1, 1), valueEntry_text_pos=(0, 0), valueEntry_text_fg=LVecBase4f(0, 0, 0, 1), valueEntry_text_bg=LVecBase4f(0, 0, 0, 0), valueEntry_text_wordwrap=None, parent=self.frmMain, ) self.spinAutosaveDealy.setTransparency(0) self.lblAutosaveDelay = DirectLabel( borderWidth=(2, 2), frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=LVecBase4f(0.3, 84.45, -3.9, 8.7), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-260, 0, -140), scale=LVecBase3f(1, 1, 1), text='Autosave delay in seconds', text0_align=TextNode.A_left, text0_scale=(12.0, 12.0), text0_pos=(0, 0), text0_fg=LVecBase4f(0, 0, 0, 1), text0_bg=LVecBase4f(0, 0, 0, 0), text0_wordwrap=None, parent=self.frmMain, ) self.lblAutosaveDelay.setTransparency(0)
def __init__(self, command, fileBrowser=False, defaultPath="~", defaultFilename="unnamed.txt", fileExtensions=[], tooltip=None): """ A simple file and folder browser command: The command that will be called on closing the browser fileBrowser: If set to True the browser will show files, otherwise it will only show folders defaultPath: The initial path the browser will be set to show defaultFilename: The filename that will be set by default, only usefull if fileBrowser is True fileExtensions: A list of extensions. Only files with those extensions will be shown. Only usefull if fileBrowser is True tooltip: An instance of the Tooltip class to display tooltips for certain parts of the editor """ self.tt = tooltip self.command = command self.showFiles = fileBrowser self.fileExtensions = fileExtensions self.currentPath = os.path.expanduser(defaultPath) if not os.path.exists(self.currentPath): self.currentPath = os.path.expanduser("~") self.previousPath = self.currentPath self.screenWidthPx = base.getSize()[0] self.screenWidthPxHalf = self.screenWidthPx * 0.5 self.screenHeightPx = base.getSize()[1] self.screenHeightPxHalf = self.screenHeightPx * 0.5 self.mainFrame = DirectFrame( relief=1, frameSize=(-self.screenWidthPxHalf, self.screenWidthPxHalf, -self.screenHeightPxHalf, self.screenHeightPxHalf), frameColor=(1, 1, 1, 1), pos=LPoint3f(base.getSize()[0] / 2, 0, -base.getSize()[1] / 2), parent=base.pixel2d, state=DGG.NORMAL, ) self.pathEntryWidth = self.screenWidthPx - 125 self.pathEntry = DirectEntry( parent=self.mainFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f(-self.screenWidthPxHalf + 15, 0, self.screenHeightPxHalf - 25), scale=12, width=self.pathEntryWidth / 12, overflow=True, command=self.entryAccept, initialText=self.currentPath, focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) x = self.pathEntryWidth / 2 - 28 self.btnReload = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderReload, image="icons/Reload.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnReload.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnReload.bind(DGG.ENTER, self.tt.show, ["Reload Folder"]) self.btnReload.bind(DGG.EXIT, self.tt.hide) x += 28 self.btnFolderUp = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderUp, image="icons/FolderUp.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnFolderUp.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnFolderUp.bind(DGG.ENTER, self.tt.show, ["Move up one level"]) self.btnFolderUp.bind(DGG.EXIT, self.tt.hide) x += 28 self.btnFolderNew = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-14, 14, -10, 18), pos=LPoint3f(x, 0, self.screenHeightPxHalf - 25), command=self.folderNew, image="icons/FolderNew.png", image_scale=14, image_pos=(0, 0, 4), ) self.btnFolderNew.setTransparency(TransparencyAttrib.M_multisample) if self.tt is not None: self.btnFolderNew.bind(DGG.ENTER, self.tt.show, ["Create new folder"]) self.btnFolderNew.bind(DGG.EXIT, self.tt.hide) color = ( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)) # Disabled self.container = DirectScrolledFrame( relief=DGG.RIDGE, borderWidth=(2, 2), frameColor=(1, 1, 1, 1), frameSize=(-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -self.screenHeightPxHalf + 50, self.screenHeightPxHalf - 50), canvasSize=(-self.screenWidthPxHalf + 31, self.screenWidthPxHalf - 10, -self.screenHeightPxHalf + 50, self.screenHeightPxHalf - 50), pos=LPoint3f(0, 0, 0), parent=self.mainFrame, scrollBarWidth=20, verticalScroll_scrollSize=20, verticalScroll_thumb_relief=DGG.FLAT, verticalScroll_incButton_relief=DGG.FLAT, verticalScroll_decButton_relief=DGG.FLAT, verticalScroll_thumb_frameColor=color, verticalScroll_incButton_frameColor=color, verticalScroll_decButton_frameColor=color, horizontalScroll_thumb_relief=DGG.FLAT, horizontalScroll_incButton_relief=DGG.FLAT, horizontalScroll_decButton_relief=DGG.FLAT, horizontalScroll_thumb_frameColor=color, horizontalScroll_incButton_frameColor=color, horizontalScroll_decButton_frameColor=color, state=DGG.NORMAL, ) self.container.bind(DGG.MWDOWN, self.scroll, [0.01]) self.container.bind(DGG.MWUP, self.scroll, [-0.01]) self.btnOk = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 160, 0, -self.screenHeightPxHalf + 25), text="ok", text_scale=12, command=command, extraArgs=[1], ) self.btnCancel = DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 55, 0, -self.screenHeightPxHalf + 25), text="Cancel", text_scale=12, command=command, extraArgs=[0]) if self.showFiles: self.txtFileName = DirectEntry( parent=self.mainFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f(-self.screenWidthPxHalf + 25, 0, -self.screenHeightPxHalf + 25), scale=12, width=200 / 12, overflow=True, command=self.filenameAccept, initialText=defaultFilename, focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) self.newFolderFrame = DirectFrame( parent=self.mainFrame, relief=1, frameSize=(-self.screenWidthPxHalf + 10, self.screenWidthPxHalf - 10, -20, 20), pos=LPoint3f(0, 0, self.screenHeightPxHalf - 55), frameColor=(0.5, 0.5, 0.5, 1), ) self.txtNewFolderName = DirectLabel( parent=self.newFolderFrame, text="New Folder Name", text_scale=12, frameColor=(0, 0, 0, 0), text_align=TextNode.ALeft, pos=(-self.screenWidthPxHalf + 15, 0, -3), ) self.folderName = DirectEntry( parent=self.newFolderFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f( -self.screenWidthPxHalf + 25 + self.txtNewFolderName.getWidth(), 0, -4), scale=12, width=((self.screenWidthPxHalf - 25) * 2 - self.txtNewFolderName.getWidth() - 100) / 12, overflow=True, command=self.entryAccept, initialText="New Folder", focusInCommand=base.messenger.send, focusInExtraArgs=["unregisterKeyboardEvents"], focusOutCommand=base.messenger.send, focusOutExtraArgs=["reregisterKeyboardEvents"], ) self.btnCreate = DirectButton( parent=self.newFolderFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(self.screenWidthPxHalf - 65, 0, -4), text="Create", text_scale=12, command=self.folderCreate, extraArgs=[0]) self.newFolderFrame.hide() self.folderReload() # handle window resizing self.prevScreenSize = base.getSize() self.accept("window-event", self.windowEventHandler)
def __init__(self, rootParent=None): self.frmBack = DirectFrame( frameColor=(0.0, 0.0, 0.0, 1.0), frameSize=(-0.8, 0.8, -0.8, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.025), parent=rootParent, ) self.frmBack.setTransparency(0) self.pg671 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-0.893750011920929, 1.0187499523162842, -0.11250001192092896, 0.7124999761581421), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.5), scale=LVecBase3f(0.2, 0.2, 0.2), text='END', text_align=TextNode.A_center, text_scale=(1.0, 1.0), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg671.setTransparency(0) self.lblEnding = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-8.0, 8.0, -0.325, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.025, 0, -0.675), scale=LVecBase3f(0.1, 0.1, 0.1), text="You've found ending x/x", text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.lblEnding.setTransparency(0) self.pg6340 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-0.893750011920929, 1.0187499523162842, -0.11250001192092896, 0.7124999761581421), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.125, 0, 0.65), scale=LVecBase3f(0.05, 0.05, 0.05), text='the', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg6340.setTransparency(0) self.pg1228 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-8.0, 8.0, -0.325, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.35), scale=LVecBase3f(0.05, 0.1, 0.056), text='A Game By', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg1228.setTransparency(0) self.pg1785 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-8.0, 8.0, -0.325, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.275), scale=LVecBase3f(0.08, 0.1, 0.08), text='Fireclaw', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg1785.setTransparency(0) self.pg4435 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-8.0, 8.0, -0.325, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.175), scale=LVecBase3f(0.05, 0.1, 0.056), text='Music from Jamendo by Golden Antelope', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg4435.setTransparency(0) self.pg5320 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-8.0, 8.0, -0.325, 0.75), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0.1), scale=LVecBase3f(0.05, 0.1, 0.056), text='Audio from freesound by reinsamba', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=self.frmBack, ) self.pg5320.setTransparency(0)
def attemptFailedMsg(self): pLabel = DirectLabel(parent=self.npRoot, relief=None, pos=(0.0, 0.0, -0.15), text=TTLocalizer.WinterCarolingMsg, text_fg=(0.9, 0.9, 1.0, 1.0), text_scale=0.12, text_font=ToontownGlobals.getSignFont())
class Menu(DirectObject): def __init__(self): #self.accept("RatioChanged", self.recalcAspectRatio) self.accept("window-event", self.recalcAspectRatio) self.frameMain = DirectFrame( # size of the frame frameSize = (base.a2dLeft, base.a2dRight, base.a2dTop, base.a2dBottom), # position of the frame pos = (0, 0, 0), # tramsparent bg color frameColor = (0, 0, 0, 0), sortOrder = 0) self.background = OnscreenImage("MenuBGLogo.png") self.background.reparentTo(self.frameMain) self.nowPlaying = DirectLabel( scale = 0.05, text = "Now Playing: Eraplee Noisewall Orchestra - Bermuda Fire", pos = (base.a2dLeft + 0.025, 0.0, base.a2dBottom + 0.05), text_align = TextNode.ALeft, frameColor = (0, 0, 0, 0), text_fg = (1,1,1,1) ) self.nowPlaying.setTransparency(1) self.nowPlaying.reparentTo(self.frameMain) maps = loader.loadModel('button_maps.egg') btnGeom = (maps.find('**/ButtonReady'), maps.find('**/ButtonClick'), maps.find('**/ButtonRollover'), maps.find('**/ButtonDisabled')) self.btnStart = self.createButton("Start", btnGeom, 0.25, self.btnStart_Click) self.btnStart.reparentTo(self.frameMain) self.btnQuit = self.createButton("Quit", btnGeom, -0.25, self.btnQuit_Click) self.btnQuit.reparentTo(self.frameMain) self.recalcAspectRatio(base.win) # hide all buttons at startup self.hide() def show(self): self.frameMain.show() self.recalcAspectRatio(base.win) def hide(self): self.frameMain.hide() def recalcAspectRatio(self, window): """get the new aspect ratio to resize the mainframe""" screenResMultiplier = window.getXSize() / window.getYSize() self.frameMain["frameSize"] = ( base.a2dLeft, base.a2dRight, base.a2dTop, base.a2dBottom) self.btnQuit["text_scale"] = (0.5*screenResMultiplier, 0.5, 0.5) self.btnStart["text_scale"] = (0.5*screenResMultiplier, 0.5, 0.5) def createButton(self, text, btnGeom, yPos, command): btn = DirectButton( scale = (0.25, 0.25, 0.25), # some temp text text = text, text_scale = (0.5, 0.5, 0.5), # set the alignment to right text_align = TextNode.ACenter, # put the text on the right side of the button text_pos = (0, -0.15), # set the text color to black text_fg = (1,1,0,1), text_shadow = (0.3, 0.3, 0.1, 1), text_shadowOffset = (0.05, 0.05), # set the buttons images geom = btnGeom, relief = 1, frameColor = (0,0,0,0), pressEffect = False, pos = (0, 0, yPos), command = command, rolloverSound = None, clickSound = None) btn.setTransparency(1) return btn def btnStart_Click(self): base.messenger.send("start") def btnQuit_Click(self): base.messenger.send("quit")
class InputPageGui(ThanksPageGui): def __init__(self, mdt, menu, joystick, keys): self._joypad_cb = None self.joystick = joystick self.keys = keys ThanksPageGui.__init__(self, mdt, menu) def build_page(self): menu_gui = self.menu.gui self.pagewidgets = [] self.buttons = [] joypad_lab = DirectLabel( text=_('Use the joypad when present'), pos=(-.1, 1, .8), text_align=TextNode.ARight, **menu_gui.label_args) PageGui.transl_text(joypad_lab, 'Use the joypad when present', _('Use the joypad when present')) self._joypad_cb = DirectCheckButton( pos=(.09, 1, .82), text='', indicatorValue=self.joystick, indicator_frameColor=menu_gui.menu_args.text_fg, **menu_gui.checkbtn_args) if not has_pygame(): self._joypad_cb['state'] = DISABLED def add_lab(text, z): self.pagewidgets += [DirectLabel( text=text, pos=(-.1, 1, z), text_align=TextNode.ARight, **menu_gui.label_args)] def add_btn(text, z): btn = DirectButton(pos=(.46, 1, z), text=text, command=self.start_rec, **menu_gui.btn_args) btn['extraArgs'] = [btn] self.pagewidgets += [btn] self.buttons += [btn] buttons_data = [ (_('Accelerate'), 'forward', .6), (_('Brake/Reverse'), 'rear', .4), (_('Left'), 'left', .2), (_('Right'), 'right', 0), (_('Weapon'), 'button', -.2), (_('Respawn'), 'button', -.4)] for btn_data in buttons_data: add_lab(btn_data[0], btn_data[2]) add_btn(self.keys[btn_data[1]], btn_data[2]) la = menu_gui.label_args.copy() la['scale'] = .065 self.hint_lab = DirectLabel( text=_('Press the key to record it'), pos=(0, 1, -.6), **la) self.hint_lab.hide() self.pagewidgets += [joypad_lab, self._joypad_cb, self.hint_lab] map(self.add_widget, self.pagewidgets) ThanksPageGui.build_page(self) def start_rec(self, btn): numbers = [str(n) for n in range(10)] self.keys = list(ascii_lowercase) + numbers + [ 'backspace', 'insert', 'home', 'page_up', 'num_lock', 'tab', 'delete', 'end', 'page_down', 'caps_lock', 'enter', 'arrow_left', 'arrow_up', 'arrow_down', 'arrow_right', 'lshift', 'rshift', 'lcontrol', 'lalt', 'space', 'ralt', 'rcontrol'] self.hint_lab.show() acc = lambda key: self.mdt.event.accept(key, self.rec, [btn, key]) map(acc, self.keys) def rec(self, btn, val): btn['text'] = val self.hint_lab.hide() map(self.mdt.event.ignore, self.keys)
class UsersFrm(GameObject): def __init__(self, menu_args, yorg_srv): GameObject.__init__(self) self.eng.log('create users form') self.ver_check = VersionChecker() self.yorg_srv = yorg_srv self.room_name = None self.labels = [] self.invited_users = [] self.menu_args = menu_args lab_args = menu_args.label_args lab_args['scale'] = .046 self.users_lab = DirectLabel(text=_('Current online users'), pos=(-.85, 1, -.02), hpr=(0, 0, -90), parent=base.a2dTopRight, text_align=TextNode.A_right, **lab_args) self.frm = DirectScrolledFrame( frameSize=(-.02, .8, .45, 2.43), canvasSize=(-.02, .76, -.08, 3.8), scrollBarWidth=.036, verticalScroll_relief=FLAT, verticalScroll_frameColor=(.2, .2, .2, .4), verticalScroll_thumb_relief=FLAT, verticalScroll_thumb_frameColor=(.8, .8, .8, .6), verticalScroll_incButton_relief=FLAT, verticalScroll_incButton_frameColor=(.8, .8, .8, .6), verticalScroll_decButton_relief=FLAT, verticalScroll_decButton_frameColor=(.8, .8, .8, .6), horizontalScroll_relief=FLAT, frameColor=(.2, .2, .2, .5), pos=(-.82, 1, -2.44), parent=base.a2dTopRight) self.conn_lab = DirectLabel(text='', pos=(.38, 1, 1.5), parent=self.frm, text_wordwrap=10, **lab_args) self.set_connection_label() self.in_match_room = None self.invited = False def show(self): self.frm.show() self.users_lab.show() def hide(self): self.frm.hide() self.users_lab.hide() def set_connection_label(self): lab_args = self.menu_args.label_args lab_args['scale'] = .046 txt = '' if not self.ver_check.is_uptodate(): txt = _("Your game isn't up-to-date, please update") elif not self.eng.xmpp.client: txt = _("You aren't logged in") elif not self.eng.xmpp.is_server_up: txt = _("Yorg's server isn't running") self.conn_lab['text'] = txt def set_size(self, full=True): if full: self.frm.setPos(-.82, 1, -2.44) self.frm['frameSize'] = (-.02, .8, .45, 2.43) else: self.frm.setPos(-.82, 1, -1.97) self.frm['frameSize'] = (-.02, .8, .45, 1.96) @staticmethod def trunc(name, lgt): if len(name) > lgt: return name[:lgt] + '...' return name def on_users(self): self.set_connection_label() bare_users = [ self.trunc(user.name, 20) for user in self.eng.xmpp.users_nodup ] for lab in self.labels[:]: _lab = lab.lab.lab['text'].replace('\1smaller\1', '').replace('\2', '') if _lab not in bare_users: if _lab not in self.eng.xmpp.client.client_roster.keys(): lab.destroy() self.labels.remove(lab) nusers = len(self.eng.xmpp.users_nodup) invite_btn = len(self.invited_users) < 8 invite_btn = invite_btn and not self.in_match_room and not self.invited top = .08 * nusers + .08 self.frm['canvasSize'] = (-.02, .76, 0, top) label_users = [lab.lab.lab['text'] for lab in self.labels] clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '') label_users = map(clean, label_users) for i, user in enumerate(self.eng.xmpp.users_nodup): usr_inv = invite_btn and user.is_in_yorg if self.trunc(user.name, 20) not in label_users: if self.eng.xmpp.client.boundjid.bare != user.name: lab = UserFrmList(self.trunc(user.name, 20), user, user.is_supporter, user.is_online, self.eng.xmpp.is_friend(user.name), user.is_in_yorg, user.is_playing, (0, 1, top - .08 - .08 * i), self.frm.getCanvas(), self.menu_args) else: lab = UserFrmListMe(self.trunc(user.name, 20), user, user.is_supporter, (0, 1, top - .08 - .08 * i), self.frm.getCanvas(), self.menu_args) self.labels += [lab] lab.attach(self.on_invite) lab.attach(self.on_friend) lab.attach(self.on_unfriend) lab.attach(self.on_add_chat) for i, user in enumerate(self.eng.xmpp.users_nodup): clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '') lab = [ lab for lab in self.labels if clean(lab.lab.lab['text']) == self.trunc(user.name, 20) ][0] enb_val = usr_inv and user.name not in self.invited_users and user.is_in_yorg and not user.is_playing and self.eng.upnp if hasattr(lab, 'invite_btn'): inv_btn = lab.invite_btn if enb_val: inv_btn.tooltip['text'] = _('invite the user to a match') elif len(self.invited_users) == 8: inv_btn.tooltip['text'] = _( "you can't invite more players") elif self.in_match_room: inv_btn.tooltip['text'] = _("you're already in a match") elif not user.is_in_yorg: inv_btn.tooltip['text'] = _("the user isn't playing yorg") elif user.name in self.invited_users: inv_btn.tooltip['text'] = _( "you've already invited this user") elif user.is_playing: inv_btn.tooltip['text'] = _( "the user is already playing a match") elif not self.eng.upnp: inv_btn.tooltip['text'] = _("can't set UPnP") lab.enable_invite_btn(enb_val) lab.frm.set_z(top - .08 - .08 * i) lab.lab.set_supporter(user.is_supporter) lab.lab.set_online(user.is_online) def on_invite(self, usr): self.notify('on_invite', usr) if not (self.eng.server.public_addr and self.eng.server.local_addr): return self.invited_users += [usr.name] self.on_users() if not self.room_name: jid = self.eng.xmpp.client.boundjid time_code = strftime('%y%m%d%H%M%S') srv = self.eng.xmpp.client.conf_srv self.room_name = 'yorg' + jid.user + time_code + '@' + srv self.eng.xmpp.client.plugin['xep_0045'].joinMUC( self.room_name, self.eng.xmpp.client.boundjid.bare, pfrom=self.eng.xmpp.client.boundjid.full) cfg = self.eng.xmpp.client.plugin['xep_0045'].getRoomConfig( self.room_name) values = cfg.get_values() values['muc#roomconfig_publicroom'] = False cfg.set_values(values) self.eng.xmpp.client.plugin['xep_0045'].configureRoom( self.room_name, cfg) self.eng.log('created room ' + self.room_name) for usr_name in [self.yorg_srv] + \ [_usr.name_full for _usr in self.eng.xmpp.users if _usr.is_in_yorg]: self.eng.xmpp.client.send_message( mfrom=self.eng.xmpp.client.boundjid.full, mto=usr_name, mtype='ya2_yorg', msubject='is_playing', mbody='1') self.eng.xmpp.client.send_message( mfrom=self.eng.xmpp.client.boundjid.full, mto=usr.name_full, mtype='ya2_yorg', msubject='invite', mbody=self.room_name + '\n' + self.eng.server.public_addr + '\n' + self.eng.server.local_addr) self.eng.log('invited ' + str(usr.name_full)) self.notify('on_add_groupchat', self.room_name, usr.name) def on_declined(self, msg): self.eng.log('declined from ' + str(JID(msg['from']).bare)) usr = str(JID(msg['from']).bare) self.invited_users.remove(usr) self.on_users() def on_add_chat(self, msg): self.notify('on_add_chat', msg) def on_logout(self): map(lambda lab: lab.destroy(), self.labels) self.labels = [] def on_friend(self, usr_name): self.eng.log('send friend to ' + usr_name) self.eng.xmpp.client.send_presence_subscription( usr_name, ptype='subscribe', pfrom=self.eng.xmpp.client.boundjid.full) def on_unfriend(self, usr): self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster)) self.eng.xmpp.client.del_roster_item(usr) self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster)) def destroy(self): self.eng.log('destroyed usersfrm') self.frm = self.frm.destroy() GameObject.destroy(self)
def add_lab(text, z): self.pagewidgets += [DirectLabel( text=text, pos=(-.1, 1, z), text_align=TextNode.ARight, **menu_gui.label_args)]
def __init__(self,pos=None,mass=1,maxforce=0.1,maxspeed=1,radius=1, avoidVehicles=True,avoidObstacles=True,container=None): """Initialise the vehicle.""" self.mass = mass # mass = 1 means that acceleration = force self.maxforce = maxforce self.maxspeed = maxspeed self.radius = radius self.avoidVehicles = avoidVehicles # Avoid colliding with other Vehicles self.avoidObstacles = avoidObstacles # Avoid colliding with obstacles if pos is None: pos = Point3(0,0,0) # The Vehicle controls a primary NodePath to which other NodePath's for # CollisionSolids are parented. Other nodes, such as animated Actors, # can be attached to this NodePath by user classes. self.prime = NodePath('Vehicle primary NodePath') self.prime.reparentTo(render) self.prime.setPos(pos) # If the Vehicle finds itself outside of its container it will turn # back toward the container. The vehicle also stays within the global # container at all times. The idea is that Vehicle.container can be # used to restrict one particular vehicle to a space smaller than the # global container. self.container = container self._pos = SteerVec(pos.getX(),pos.getY()) # 2D pos for steering # calculations self._velocity = SteerVec(0,0) self._steeringforce = SteerVec(0,0) self._steeringbehavior = [] # Some steering behaviors make use of self._target, which can be # another Vehicle or a point in 2-space (SteerVec), or it might be None # indicating that no target is currently in use. self._target = None # Initialise the Vehicle's CollisionRay which is used with a # CollisionHandlerFloor to keep the Vehicle on the ground. self.raynp = self.prime.attachNewNode(CollisionNode('colNode')) self.raynp.node().addSolid(CollisionRay(0,0,3,0,0,-1)) self.floorhandler = CollisionHandlerFloor() self.floorhandler.addCollider(self.raynp,self.prime) cTrav.addCollider(self.raynp,self.floorhandler) # Uncomment this line to show the CollisionRay: #self.raynp.show() # We only want our CollisionRay to collide with the collision # geometry of the terrain only, se we set a mask here. self.raynp.node().setFromCollideMask(floorMASK) self.raynp.node().setIntoCollideMask(offMASK) # Initialise CollisionTube for detecting oncoming obstacle collisions. x,y,z = self.prime.getX(),self.prime.getY(),self.prime.getZ()+3 #FIXME: Don't hardcode how high the tube goes, add height parameter to __init__ for both tube and sphere vx,vy = self._velocity.getX(),self._velocity.getY() r = self.radius f = self.prime.getNetTransform().getMat().getRow3(1) s = 10 self.tube = CollisionTube(x,y,z,x+f.getX()*s,y+f.getY()*s,z,self.radius) self.tubenp = self.prime.attachNewNode(CollisionNode('colNode')) self.tubenp.node().addSolid(self.tube) # The tube should only collide with obstacles (and is an 'into' object) self.tubenp.node().setFromCollideMask(offMASK) self.tubenp.node().setIntoCollideMask(obstacleMASK) # Uncomment this line to show the CollisionTube #self.tubenp.show() # CollisionSphere for detecting when we've actuallyt collided with # something. self.sphere = CollisionSphere(x,y,z,self.radius) self.spherenp = self.prime.attachNewNode(CollisionNode('cnode')) self.spherenp.node().addSolid(self.sphere) # Only collide with the CollisionSphere's of other vehicles. self.spherenp.node().setFromCollideMask(obstacleMASK) # So the spheres of vehicles will collide with eachother self.spherenp.node().setIntoCollideMask(obstacleMASK) # So obstacles will collide into spheres of vehicles cTrav.addCollider(self.spherenp,collisionHandler) # Uncomment this line to show the CollisionSphere #self.spherenp.show() # Add a task for this Vehicle to the global task manager. self._prevtime = 0 self.stepTask=taskMgr.add(self._step,"Vehicle step task") # Add the Vehicle to the global list of Vehicles vehicles.append(self) # Initialise the DirectLabel used when annotating the Vehicle # FIXME: Needs to be destroyed in self.destroy self.text = "no steering" self.label = DirectLabel(parent=self.prime,pos=(4,4,4),text=self.text, text_wordwrap=10,relief=None, text_scale=(1.5,1.5),text_frame=(0,0,0,1), text_bg=(1,1,1,1)) self.label.component('text0').textNode.setCardDecal(1) self.label.setBillboardAxis() self.label.hide() self.label.setLightOff(1) # A second label for speaking ('Ouch!', 'Sorry!' etc.) self.callout = DirectLabel(parent=self.prime,pos=(4,4,4),text='', text_wordwrap=10,relief=None, text_scale=(1.5,1.5),text_frame=(0,0,0,1), text_bg=(1,1,1,1)) self.callout.component('text0').textNode.setCardDecal(1) self.callout.setBillboardAxis() self.callout.hide() self.callout.setLightOff(1)
class PlayerHUD(): def __init__(self): # # Player status section # heartscale = (0.1, 1, 0.1) self.heart1 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.2, 0, -0.15)) self.heart1.setTransparency(True) self.heart1.reparentTo(base.a2dTopLeft) self.heart2 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.45, 0, -0.15)) self.heart2.setTransparency(True) self.heart2.reparentTo(base.a2dTopLeft) self.heart3 = OnscreenImage( image = "HeartIcon.png", scale = heartscale, pos = (0.7, 0, -0.15)) self.heart3.setTransparency(True) self.heart3.reparentTo(base.a2dTopLeft) self.keys = DirectLabel( text = "x0", frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), text_scale = 1.8, text_pos = (1, -0.25, 0), text_align = TextNode.ALeft, image = "Keys.png", pos = (0.2, 0, -0.4)) self.keys.setScale(0.085) self.keys.setTransparency(True) self.keys.reparentTo(base.a2dTopLeft) self.actionKey = DirectLabel( frameColor = (0, 0, 0, 0), text_fg = (1, 1, 1, 1), scale = 0.15, pos = (0, 0, 0.15), text = _("Action: E/Enter")) self.actionKey.setTransparency(True) self.actionKey.reparentTo(base.a2dBottomCenter) self.actionKey.hide() def show(self): self.keys.show() def hide(self): self.heart1.hide() self.heart2.hide() self.heart3.hide() self.keys.hide() self.hideActionKey() def setHealthStatus(self, value): """this function will set the health image in the top righthand corner according to the given value, where value is a integer between 0 and 100 """ if value >= 1: self.heart1.show() else: self.heart1.hide() if value >= 2: self.heart2.show() else: self.heart2.hide() if value >= 3: self.heart3.show() else: self.heart3.hide() def showActionKey(self): self.actionKey.show() def hideActionKey(self): self.actionKey.hide() def updateKeyCount(self, numKeys): self.keys["text"] = "x%d" % numKeys
def __init__(self, rootParent=None): self.frmInventory = DirectFrame( frameColor=(0.2, 0.2, 0.2, 1.0), frameSize=(-0.3, 0.3, -0.5, 0.5), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.725, 0, 0.2), parent=rootParent, ) self.frmInventory.setTransparency(0) self.frmContent = DirectScrolledFrame( canvasSize=(-0.8, 0.8, -0.8, 0.8), frameColor=(0.2, 0.2, 0.2, 1.0), frameSize=(-0.8, 0.8, -0.8, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.475, 0, 0.1), scrollBarWidth=0.08, state='normal', horizontalScroll_borderWidth=(0.01, 0.01), horizontalScroll_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_hpr=LVecBase3f(0, 0, 0), horizontalScroll_pos=LPoint3f(0, 0, 0), horizontalScroll_decButton_borderWidth=(0.01, 0.01), horizontalScroll_decButton_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_decButton_hpr=LVecBase3f(0, 0, 0), horizontalScroll_decButton_pos=LPoint3f(0, 0, 0), horizontalScroll_incButton_borderWidth=(0.01, 0.01), horizontalScroll_incButton_frameSize=(-0.05, 0.05, -0.04, 0.04), horizontalScroll_incButton_hpr=LVecBase3f(0, 0, 0), horizontalScroll_incButton_pos=LPoint3f(0, 0, 0), horizontalScroll_thumb_borderWidth=(0.01, 0.01), horizontalScroll_thumb_hpr=LVecBase3f(0, 0, 0), horizontalScroll_thumb_pos=LPoint3f(0, 0, 0), verticalScroll_borderWidth=(0.01, 0.01), verticalScroll_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_hpr=LVecBase3f(0, 0, 0), verticalScroll_pos=LPoint3f(0, 0, 0), verticalScroll_decButton_borderWidth=(0.01, 0.01), verticalScroll_decButton_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_decButton_hpr=LVecBase3f(0, 0, 0), verticalScroll_decButton_pos=LPoint3f(0, 0, 0), verticalScroll_incButton_borderWidth=(0.01, 0.01), verticalScroll_incButton_frameSize=(-0.04, 0.04, -0.05, 0.05), verticalScroll_incButton_hpr=LVecBase3f(0, 0, 0), verticalScroll_incButton_pos=LPoint3f(0, 0, 0), verticalScroll_thumb_borderWidth=(0.01, 0.01), verticalScroll_thumb_hpr=LVecBase3f(0, 0, 0), verticalScroll_thumb_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmContent.setTransparency(1) self.btnQuit = DirectButton( frameSize=(-3.0, 3.0, -0.3, 0.9), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.725, 0, -0.85), scale=LVecBase3f(0.1, 0.1, 0.1), text='Quit', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, command=base.messenger.send, extraArgs=["quitGame"], pressEffect=1, ) self.btnQuit.setTransparency(0) self.btnAudioToggle = DirectButton( frameSize=(-3.0, 3.0, -0.3, 0.9), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.725, 0, -0.7), scale=LVecBase3f(0.1, 0.1, 0.1), text='Audio On', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, command=base.messenger.send, extraArgs=["toggleAudio"], pressEffect=1, ) self.btnAudioToggle.setTransparency(0) self.frmBorderOverlay = DirectFrame( frameColor=(1.0, 1.0, 1.0, 0.0), frameSize=(-0.8, 0.8, -0.8, 0.8), hpr=LVecBase3f(0, 0, 0), image='gameScreen/border.png', pos=LPoint3f(-0.475, 0, 0.1), image_scale=LVecBase3f(0.8, 1, 0.8), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmBorderOverlay.setTransparency(1) self.lblInventory = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.725, 0, 0.775), scale=LVecBase3f(0.1, 0.1, 0.1), text='Inventory', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0.9, 0.9, 0.9, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, ) self.lblInventory.setTransparency(0) self.lblStory = DirectLabel( frameSize=(-0.125, 12.0, -0.313, 0.925), hpr=LVecBase3f(0, 0, 0), pad=(0.2, 0.2), pos=LPoint3f(-1.26, 0, -0.845), scale=LVecBase3f(0.1, 0.1, 0.1), text='', text_align=TextNode.A_left, text_scale=(0.4, 0.4), text_pos=(0.0, 0.4), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=29.8, parent=rootParent, ) self.lblStory.setTransparency(0) self.btnContinue = DirectButton( frameSize=(-1.8, 1.8, -0.3, 0.9), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.145, 0, -0.845), scale=LVecBase3f(0.1, 0.1, 0.1), text='Cont.', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), text_wordwrap=None, parent=rootParent, command=base.messenger.send, extraArgs=["story_continue"], pressEffect=1, ) self.btnContinue.setTransparency(0) self.frmFadeOverlay = DirectFrame( frameColor=(0.0, 0.0, 0.0, 1.0), frameSize=(-0.8, 0.8, -0.8, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.475, 0, 0.1), parent=rootParent, ) self.frmFadeOverlay.setTransparency(1)
class GUI: def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(0.25, 0.25, 0.25, 1.0), frameSize=(0.0, 2.0, -0.1, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.btnLeave = DirectButton( hpr=LVecBase3f(0, 0, 0), pad=(0.1, 0.1), pos=LPoint3f(0.115, 0, -0.075), relief=1, scale=LVecBase3f(0.1, 0.1, 0.1), text='Leave', text_align=TextNode.A_center, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=base.messenger.send, extraArgs=["leaveRoom"], ) self.btnLeave.setTransparency(0) self.lblPlayerName = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.55, 0, -0.075), scale=LVecBase3f(0.1, 0.1, 0.1), text='Label', text_align=TextNode.A_left, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0.8, 0.8, 0.8, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblPlayerName.setTransparency(0) self.pg1983 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.42, 0, -0.075), scale=LVecBase3f(0.1, 0.1, 0.1), text='Name:', text_align=TextNode.A_center, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0.6, 0.6, 0.6, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.pg1983.setTransparency(0) def show(self): self.frmMain.show() def hide(self): self.frmMain.hide() def destroy(self): self.frmMain.destroy()
class ScavengerHuntEffect: images = None def __init__(self, beanAmount): if not ScavengerHuntEffect.images: ScavengerHuntEffect.images = loader.loadModel( 'phase_4/models/props/tot_jar') self.npRoot = DirectFrame(parent=aspect2d, relief=None, scale=0.75, pos=(0, 0, 0.59999999999999998)) if beanAmount > 0: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.jar = DirectFrame( parent=self.npRoot, relief=None, image=ScavengerHuntEffect.images.find('**/tot_jar')) self.jar.hide() self.eventImage = NodePath('EventImage') self.eventImage.reparentTo(self.npRoot) self.countLabel = DirectLabel( parent=self.jar, relief=None, text='+0', text_pos=(0.02, -0.20000000000000001), text_scale=0.25, text_fg=(0.94999999999999996, 0.0, 0, 1), text_font=ToontownGlobals.getSignFont()) def countUp(t, startVal, endVal): beanCountStr = startVal + t * (endVal - startVal) self.countLabel['text'] = '+' + ` int(beanCountStr) ` def setCountColor(color): self.countLabel['text_fg'] = color self.track = Sequence( LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(1), Func(self.jar.show), LerpColorScaleInterval(self.eventImage, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Parallel( LerpScaleInterval(self.npRoot, 1, scale=0.5, startScale=0.75), LerpPosInterval(self.npRoot, 1, pos=VBase3(-0.90000000000000002, 0, -0.82999999999999996))), LerpFunc(countUp, duration=2, extraArgs=[0, beanAmount]), Func(setCountColor, VBase4(0.94999999999999996, 0.94999999999999996, 0, 1)), Wait(3), Func(self.destroy)) else: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.attemptFailedMsg() self.track = Sequence( LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(5), LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Func(self.destroy)) def play(self): if self.npRoot: self.track.start() def stop(self): if self.track != None: if self.track.isPlaying(): self.track.finish() def cleanupIntervals(self, interval): while len(interval) > 0: if isinstance(interval[0], Sequence) or isinstance( interval[0], Parallel): self.cleanupIntervals(interval[0]) interval.pop(0) continue interval.pop(0) def destroy(self): self.stop() self.track = None if hasattr(self, 'eventImage') and self.eventImage: self.eventImage.detachNode() del self.eventImage if hasattr(self, 'countLabel') and self.countLabel: self.countLabel.destroy() del self.countLabel if hasattr(self, 'jar') and self.jar: self.jar.destroy() del self.jar if hasattr(self, 'npRoot') and self.npRoot: self.npRoot.destroy() del self.npRoot
def __init__(self, command, headerText, actionText, affirmText, filePath, tooltip): self.command = command self.darkenFrame = DirectFrame( relief=1, frameSize=(0, base.getSize()[0], -base.getSize()[1], 0), frameColor=(0, 0, 0, 0.45), state=DGG.NORMAL, parent=base.pixel2d, ) self.mainFrame = DirectFrame( relief=1, frameSize=(-300, 300, -150, 150), frameColor=(1, 1, 1, 1), pos=LPoint3f(base.getSize()[0] / 2, 0, -base.getSize()[1] / 2), parent=base.pixel2d, ) # Header headerFrame = DirectFrame( parent=self.mainFrame, relief=1, frameSize=(-300, 300, -20, 20), frameColor=(0.25, 0.25, 0.25, 1.0), pos=LPoint3f(0, 0, 130), scale=LVecBase3f(1, 0.1, 1), ) DirectLabel( parent=headerFrame, frameColor=(0.8, 0.8, 0.8, 0.0), pos=LPoint3f(-295, 0, -5), text=headerText, text_align=0, text_fg=(1, 1, 1, 1), scale=16, ) # Entry DirectLabel( parent=self.mainFrame, frameColor=(0.8, 0.8, 0.8, 0.0), pos=LPoint3f(-250, 0, 0), scale=12, text=actionText, text_align=0, ) self.pathEntry = DirectEntry(parent=self.mainFrame, relief=DGG.SUNKEN, frameColor=(1, 1, 1, 1), pad=(0.2, 0.2), pos=LPoint3f(-250, 0, -20), scale=12, width=(500 - 90) / 12, overflow=True, command=self.entryCommandHandler, initialText=filePath) DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(235, 0, -20), text="Browse", text_scale=12, command=self.browse, ) self.browser = DirectFolderBrowser(self.selectPath, True, os.path.dirname(filePath), os.path.split(filePath)[1], tooltip=tooltip) self.browser.hide() # Command Buttons DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(140, 0, -135), text=affirmText, text_scale=12, command=command, extraArgs=[1], ) DirectButton( parent=self.mainFrame, relief=1, frameColor=( (0.8, 0.8, 0.8, 1), # Normal (0.9, 0.9, 1, 1), # Click (0.8, 0.8, 1, 1), # Hover (0.5, 0.5, 0.5, 1)), # Disabled frameSize=(-45, 45, -6, 14), pos=LPoint3f(245, 0, -135), text="Cancel", text_scale=12, command=command, extraArgs=[0]) # handle window resizing self.prevScreenSize = base.getSize() self.accept("window-event", self.windowEventHandler) self.accept("escape", command, extraArgs=[0])
class HUD(): def __init__(self): self.canPlantLabel = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.15, pos=(0, 0, 0.25), pad=(0.2,0.2), text=_("Plant Seed")) self.canPlantLabel.setTransparency(True) self.canPlantLabel.reparentTo(base.a2dBottomCenter) self.canPlantLabel.hide() self.speekLabel = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.15, pos=(0, 0, 0.5), pad=(0.2,0.2), text="...") self.speekLabel.reparentTo(render) self.speekLabel.hide() self.speekLabel.setTransparency(True) self.speekLabel.setEffect(BillboardEffect.makePointEye()) self.speekLabel.setBin("fixed", 11) self.speekLabel.setDepthWrite(False) self.storyText = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.08, pos=(0, 0, 0.25), pad=(0.2,0.2), text="Story text") self.storyText.setTransparency(True) self.storyText.reparentTo(base.a2dBottomCenter) self.storyText.hide() self.points = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(0.05, 0, -0.1), pad=(0.2,0.2), text_align=TextNode.ALeft, text=_("Points: %d")%0) self.points.setTransparency(True) self.points.reparentTo(base.a2dTopLeft) self.playerWater = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(0.05, 0, -0.2), pad=(0.2,0.2), text_align=TextNode.ALeft, text=_("Remaining Water: %d")%100) self.playerWater.setTransparency(True) self.playerWater.reparentTo(base.a2dTopLeft) self.helpInfo = DirectLabel( frameColor=(0, 0, 0, 0.25), text_fg=(1, 1, 1, 1), scale=0.075, pos=(-0.05, 0, -0.1), pad=(0.2,0.2), text_align=TextNode.ARight, text=_("F1 - show help")) self.helpInfo.setTransparency(True) self.helpInfo.reparentTo(base.a2dTopRight) self.hide() def show(self): self.points.show() self.playerWater.show() self.helpInfo.show() def hide(self): self.points.hide() self.playerWater.hide() self.helpInfo.hide() def hideAll(self): self.canPlantLabel.hide() self.speekLabel.hide() self.points.hide() self.playerWater.hide() self.helpInfo.hide() def showStory(self): self.storyText.show() def hideStory(self): self.storyText.hide() def cleanup(self): self.hideAll() self.canPlantLabel.destroy() self.speekLabel.destroy() self.points.destroy() self.playerWater.destroy() self.helpInfo.destroy() def showCanPlant(self): self.canPlantLabel.show() def hideCanPlant(self): self.canPlantLabel.hide() def setPoints(self, points): self.points["text"] = _("Points: %d")%points self.points.resetFrameSize() def setWater(self, water): self.playerWater["text"] = _("Remaining Water: %d")%water self.playerWater.resetFrameSize() def setStory(self, storytext): self.storyText["text"] = storytext self.storyText.resetFrameSize() def showSpeekText(self, text, newPos): self.speekLabel.setPos(newPos) self.speekLabel["text"] = text self.speekLabel.resetFrameSize() self.speekLabel.show() def hideSpeekText(self): self.speekLabel.hide()
def __init__(self, rootParent=None): self.frmRoomEntry = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1.0, 1.0, -0.1, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmRoomEntry.setTransparency(0) self.lblRoomName = DirectLabel( frameSize=(0.075, 15.0, -0.2, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.975, 0, -0.065), scale=LVecBase3f(0.05, 0.05, 0.05), text='Room Name', text_align=TextNode.A_left, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmRoomEntry, ) self.lblRoomName.setTransparency(0) self.lblPlayerCount = DirectLabel( frameSize=(-1.15, 1.25, -0.2, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(-0.15, 0, -0.065), scale=LVecBase3f(0.05, 0.05, 0.05), text='0/4', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmRoomEntry, ) self.lblPlayerCount.setTransparency(0) self.lblGameType = DirectLabel( frameSize=(-4.0, 4.0, -0.2, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.125, 0, -0.065), scale=LVecBase3f(0.05, 0.05, 0.05), text='Game Type', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmRoomEntry, ) self.lblGameType.setTransparency(0) self.btnJoin = DirectButton( hpr=LVecBase3f(0, 0, 0), pad=(0.1, 0.1), pos=LPoint3f(0.855, 0, -0.075), scale=LVecBase3f(0.075, 0.075, 0.075), text='Join', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmRoomEntry, command=base.messenger.send, extraArgs=["room_join"], ) self.btnJoin.setTransparency(0) self.lblDifficulty = DirectLabel( frameSize=(-4.0, 4.0, -0.2, 0.8), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.545, 0, -0.065), scale=LVecBase3f(0.05, 0.05, 0.05), text='Difficulty', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmRoomEntry, ) self.lblDifficulty.setTransparency(0)
def __init__(self, beanAmount): if not ScavengerHuntEffect.images: ScavengerHuntEffect.images = loader.loadModel( 'phase_4/models/props/tot_jar') self.npRoot = DirectFrame(parent=aspect2d, relief=None, scale=0.75, pos=(0, 0, 0.6)) if beanAmount > 0: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.jar = DirectFrame( parent=self.npRoot, relief=None, image=ScavengerHuntEffect.images.find('**/tot_jar')) self.jar.hide() self.eventImage = NodePath('EventImage') self.eventImage.reparentTo(self.npRoot) self.countLabel = DirectLabel( parent=self.jar, relief=None, text='+0', text_pos=(0.02, -0.2), text_scale=0.25, text_fg=(0.95, 0.0, 0, 1), text_font=ToontownGlobals.getSignFont()) def countUp(t, startVal, endVal): beanCountStr = startVal + t * (endVal - startVal) self.countLabel['text'] = '+' + ` (int(beanCountStr)) ` def setCountColor(color): self.countLabel['text_fg'] = color self.track = Sequence( LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(1), Func(self.jar.show), LerpColorScaleInterval(self.eventImage, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Parallel( LerpScaleInterval(self.npRoot, 1, scale=0.5, startScale=0.75), LerpPosInterval(self.npRoot, 1, pos=VBase3(-0.9, 0, -0.83))), LerpFunc(countUp, duration=2, extraArgs=[0, beanAmount]), Func(setCountColor, VBase4(0.95, 0.95, 0, 1)), Wait(3), Func(self.destroy)) else: self.npRoot.setColorScale(VBase4(1, 1, 1, 0)) self.attemptFailedMsg() self.track = Sequence( LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 1), startColorScale=VBase4(1, 1, 1, 0)), Wait(5), LerpColorScaleInterval(self.npRoot, 1, colorScale=VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Func(self.destroy)) return
class MessageFrm(GameObject): def __init__(self, menu_args): GameObject.__init__(self) self.eng.log('created message form') self.chats = [] self.curr_chat = None self.curr_match_room = None self.msg_frm = DirectFrame( frameSize=(-.02, .8, 0, .45), frameColor=(.2, .2, .2, .5), pos=(-.82, 1, .02), parent=base.a2dBottomRight) self.presences_sent = [] self.menu_args = menu_args t_a = menu_args.text_args t_a['scale'] = .05 t_a['fg'] = menu_args.text_normal self.dst_txt = OnscreenText( text='', pos=(0, .4), parent=self.msg_frm, align=TextNode.A_left, **t_a) self.arrow_btn = ImgBtn( parent=self.msg_frm, scale=.024, pos=(.7, 1, .42), frameColor=(1, 1, 1, 1), frameTexture='assets/images/gui/arrow.txo', command=self.on_arrow, **menu_args.imgbtn_args) self.arrow_btn.disable() self.close_btn = ImgBtn( parent=self.msg_frm, scale=.024, pos=(.76, 1, .42), frameColor=(1, 1, 1, 1), frameTexture='assets/images/gui/close.txo', command=self.on_close, **menu_args.imgbtn_args) self.close_btn.disable() self.ent = Entry( scale=.04, pos=(0, 1, .03), entryFont=menu_args.font, width=19.5, frameColor=menu_args.btn_color, parent=self.msg_frm, initialText=_('write here your message'), command=self.on_typed_msg, focusInCommand=self.on_focus, focusInExtraArgs=['in'], focusOutCommand=self.on_focus, focusOutExtraArgs=['out'], text_fg=menu_args.text_active) self.ent['state'] = DISABLED self.txt_frm = DirectScrolledFrame( frameSize=(-.02, .76, -.02, .28), canvasSize=(-.02, .72, -.02, .28), scrollBarWidth=.036, verticalScroll_relief=FLAT, verticalScroll_frameColor=(.2, .2, .2, .4), verticalScroll_thumb_relief=FLAT, verticalScroll_thumb_frameColor=(.8, .8, .8, .6), verticalScroll_incButton_relief=FLAT, verticalScroll_incButton_frameColor=(.8, .8, .8, .6), verticalScroll_decButton_relief=FLAT, verticalScroll_decButton_frameColor=(.8, .8, .8, .6), horizontalScroll_relief=FLAT, frameColor=(1, 1, 1, 0), pos=(.02, 1, .11), parent=self.msg_frm) t_a['scale'] = .046 self.msg_txt = OnscreenText( text='', pos=(0, .24), parent=self.txt_frm.getCanvas(), align=TextNode.A_left, wordwrap=14, **t_a) lab_args = menu_args.label_args lab_args['scale'] = .046 lab_args['text_fg'] = menu_args.text_normal self.lab_frm = Btn( frameSize=(-.02, .64, -.01, .05), frameColor=(1, 1, 1, 0), pos=(0, 1, .4), parent=self.msg_frm) self.lab_frm.bind(ENTER, self.on_enter) self.lab_frm.bind(EXIT, self.on_exit) self.tooltip = DirectLabel( text='', pos=(.78, 1, -.06), parent=self.lab_frm, text_wordwrap=16, text_bg=(.2, .2, .2, .8), text_align=TextNode.A_right, **lab_args) self.tooltip.set_bin('gui-popup', 10) self.tooltip.hide() def on_enter(self, pos): self.tooltip.show() def on_exit(self, pos): self.tooltip.hide() def show(self): self.msg_frm.show() def hide(self): self.msg_frm.hide() def add_msg_txt(self, msg): self.msg_txt['text'] += ('\n' if self.msg_txt['text'] else '') + msg txt_height = self.msg_txt.textNode.getUpperLeft3d()[2] - \ self.msg_txt.textNode.getLowerRight3d()[2] self.txt_frm['canvasSize'] = (-.02, .72, .28 - txt_height, .28) def set_title(self, title): ttitle = self.trunc(title, 32) fix_name = lambda name: name if '@' not in name else name.split('@')[0] + '\1smaller\1@' + name.split('@')[1] + '\2' if title: if ',' in ttitle: is_muc = True ttitle = ttitle names = ttitle.split(',') names = [name.strip() for name in names] names = [fix_name(name) for name in names] ttitle = ', '.join(names) else: ttitle = fix_name(ttitle) self.dst_txt['text'] = ttitle self.tooltip['text'] = title @staticmethod def trunc(name, lgt): if len(name) > lgt: return name[:lgt] + '...' return name def set_chat(self, chat): self.curr_chat = chat self.set_title(chat.title) self.msg_txt['text'] = '\n'.join(chat.messages) txt_height = self.msg_txt.textNode.getUpperLeft3d()[2] - \ self.msg_txt.textNode.getLowerRight3d()[2] self.txt_frm['canvasSize'] = (-.02, .72, .28 - txt_height, .28) if not self.chats: self.close_btn.disable() self.ent['state'] = DISABLED elif len(self.chats) == 1: self.close_btn.enable() self.ent['state'] = NORMAL self.arrow_btn.disable() else: self.close_btn.enable() self.ent['state'] = NORMAL self.arrow_btn.enable() if all(_chat.read for _chat in self.chats): self.arrow_btn['frameTexture'] = 'assets/images/gui/arrow.txo' else: self.arrow_btn['frameTexture'] = 'assets/images/gui/message.txo' def on_arrow(self): chat_idx = self.chats.index(self.curr_chat) next_idx = (chat_idx + 1) % len(self.chats) chat = self.chats[next_idx] self.set_title(chat.title) chat.read = True self.set_chat(chat) @property def open_chats(self): return [chat for chat in self.chats if not chat.closed] def on_close(self): if self.curr_chat not in self.open_chats: return curr_idx = self.open_chats.index(self.curr_chat) #self.chats.remove(self.curr_chat) self.curr_chat.closed = True if self.open_chats: self.set_chat(self.open_chats[curr_idx - 1]) else: self.set_chat(Chat('')) self.notify('on_close_all_chats') def on_typed_msg(self, val): self.add_msg_txt('\1italic\1' + _('you') + '\2: ' + val) self.ent.set('') if self.curr_chat.dst not in self.presences_sent and \ not str(self.curr_chat.dst).startswith('yorg'): self.eng.xmpp.client.send_presence( pfrom=self.eng.xmpp.client.boundjid.full, pto=self.curr_chat.dst) self.presences_sent += [self.curr_chat.dst] if str(self.curr_chat.dst).startswith('yorg'): self.eng.xmpp.client.send_message( mfrom=self.eng.xmpp.client.boundjid.full, mto=self.curr_chat.dst, mtype='groupchat', mbody=val) else: self.eng.xmpp.client.send_message( mfrom=self.eng.xmpp.client.boundjid.full, mto=self.curr_chat.dst, msubject='chat', mbody=val) msg = '\1italic\1' + _('you') + '\2: ' + val self.curr_chat.messages += [msg] self.ent['focus'] = 1 def on_msg(self, msg): src = str(JID(msg['from']).bare) src = src.split('@')[0] + '\1smaller\1@' + src.split('@')[1] + '\2' str_msg = '\1italic\1' + src + '\2: ' + str(msg['body']) chat = self.__find_chat(msg['from']) if not chat: chat = Chat(msg['from']) self.chats += [chat] chat.messages += [str_msg] if self.dst_txt['text'] == '': self.set_chat(chat) elif self.curr_chat.dst == JID(msg['from']).bare: self.add_msg_txt(str_msg) else: chat.read = False chat.closed = False self.arrow_btn['frameTexture'] = 'assets/images/gui/message.txo' def on_groupchat_msg(self, msg): if str(JID(msg['from']).bare) == self.curr_match_room: if self.match_msg_frm: # we're still in the room page self.match_msg_frm.on_groupchat_msg(msg) src = str(JID(msg['mucnick'])) src = src.split('@')[0] + '\1smaller\1@' + src.split('@')[1] + '\2' self.eng.log('received groupchat message from %s in the chat %s' %(msg['mucnick'], JID(msg['from']).bare)) str_msg = '\1italic\1' + src + '\2: ' + str(msg['body']) chat = self.curr_chat if not chat: chat = MUC(str(JID(msg['from']).bare)) self.chats += [chat] chat.messages += [str_msg] if self.dst_txt['text'] == '': self.set_chat(chat) elif self.curr_chat.dst == str(JID(msg['from']).bare): self.add_msg_txt(str_msg) else: chat.read = False chat.closed = False self.arrow_btn['frameTexture'] = 'assets/images/gui/message.txo' def on_presence_available_room(self, msg): if str(JID(msg['from']).bare) == self.curr_match_room: self.match_msg_frm.on_presence_available_room(msg) return room = str(JID(msg['muc']['room']).bare) nick = str(msg['muc']['nick']) self.eng.log('user %s has logged in the chat %s' %(nick, room)) chat = self.__find_chat(room) chat.users += [nick] if self.curr_chat.dst == room: self.set_title(chat.title) def on_presence_unavailable_room(self, msg): if self.match_msg_frm and str(JID(msg['from']).bare) == self.curr_match_room: self.match_msg_frm.on_presence_unavailable_room(msg) return room = str(JID(msg['muc']['room']).bare) nick = str(msg['muc']['nick']) self.eng.log('user %s has left the chat %s' %(nick, room)) chat = self.__find_chat(room) if nick == self.eng.xmpp.client.boundjid.bare: self.on_close() else: chat.users.remove(nick) if self.curr_chat.dst == room: self.set_title(chat.title) def __find_chat(self, dst): chats = [chat for chat in self.chats if chat.dst == dst] if chats: return chats[0] def add_chat(self, usr): self.set_title(JID(usr).bare) chat = self.__find_chat(usr) if not chat: chat = Chat(usr) self.chats += [chat] self.set_chat(chat) self.ent['focus'] = 1 def add_groupchat(self, room, usr): self.set_title(usr) chat = self.__find_chat(room) if not chat: chat = MUC(room) self.chats += [chat] chat.users += [usr] self.set_chat(chat) self.add_match_chat(room, usr) def remove_groupchat(self): self.match_msg_frm.detach(self.on_match_msg_focus) self.match_msg_frm = self.match_msg_frm.destroy() def on_focus(self, val): if val and self.ent.get() == _('write here your message'): self.ent.set('') self.notify('on_msg_focus', val) def on_match_msg_focus(self, val): self.notify('on_msg_focus', val) def on_room_back(self): self.curr_match_room = None self.match_msg_frm.destroy() def add_match_chat(self, room, usr): if self.curr_match_room: return self.curr_match_room = room self.match_msg_frm = MatchMsgFrm(self.menu_args) self.match_msg_frm.attach(self.on_match_msg_focus) self.match_msg_frm.add_groupchat(room, usr)
def setOpponentName(self, name, skillLevel, dnaString): # first create our own frame # create our own frame, the opponent's frame will be created in a later update frame = loader.loadModel('phase_3.5/models/modules/trophy_frame') dot = loader.loadModel('phase_6/models/golf/checker_marble') self.ourFrame = DirectLabel(parent=base.a2dBottomLeft, relief=None, geom=frame, geom_scale=(0.25, 0.1, 0.25), text=base.localAvatar.getName(), text_wordwrap=7.504, text_align=TextNode.A_center, text_font=FONT, text_scale=0.07, text_pos=(0, -0.2), sortOrder=70, pos=(0.24, 0, 0.32)) if not config.GetBool('show-player-names', True): self.ourFrame['text'] = '' dna = ToonDNA.ToonDNA() dna.makeFromNetString(base.localAvatar.getDNAString()) ourToon = ToonHead.ToonHead() ourToon.setH(180) ourToon.setupHead(dna, forGui=1) ourToon.reparentTo(self.ourFrame) ourToon.startBlink() ourToon.setScale(HEAD_SCALES.get(dna.head, 0.11)) self.opponentFrame = DirectLabel(parent=base.a2dTopRight, relief=None, geom=frame, geom_scale=(0.25, 0.1, 0.25), text=name, text_wordwrap=7.504, text_align=TextNode.A_center, text_font=FONT, text_scale=0.07, text_pos=(0, -0.2), sortOrder=70, pos=(-0.31, 0, -0.35)) if not config.GetBool('show-player-names', True): self.opponentFrame['text'] = '' dna = ToonDNA.ToonDNA() dna.makeFromNetString(dnaString) opponent = ToonHead.ToonHead() opponent.setH(180) opponent.setupHead(dna, forGui=1) opponent.reparentTo(self.opponentFrame) opponent.startBlink() opponent.setScale(HEAD_SCALES.get(dna.head, 0.11)) if config.GetBool('show-player-ranks', True): ourSkillLevel = base.localAvatar.getBeltLevel() if ourSkillLevel != NONE: self.ourDot = DirectLabel( parent=self.ourFrame, relief=None, geom=dot, geom_scale=0.3, sortOrder=80, geom_color=RANK_COLORS[ourSkillLevel], geom_hpr=(0, 90, 0), geom_pos=(0.11, 0, 0.17)) if skillLevel != NONE: self.opponentSkillDot = DirectLabel( parent=self.opponentFrame, relief=None, geom=dot, geom_scale=0.3, sortOrder=80, geom_color=RANK_COLORS[skillLevel], geom_hpr=(0, 90, 0), geom_pos=(0.11, 0, 0.17)) dot.removeNode() frame.removeNode()
class CustomizeScreen(DirectFrame): notify = directNotify.newCategory('CustomizeScreen') def __init__(self, callback, **kw): self._callback = callback geom = loader.loadModel('phase_6/models/gui/ui_frame') optiondefs = (('relief', None, None), ('geom', geom, None), ('geom_scale', 1.5, 1.5), ('text', base.localAvatar.getName(), None), ('text_align', TextNode.ACenter, None), ('text_font', FONT, None), ('text_scale', 0.075, None), ('text_pos', (0, 0.65), None), ('pos', (-0.7, 0, 0.16), None)) self.defineoptions(kw, optiondefs) DirectFrame.__init__(self, aspect2d) self.initialiseoptions(CustomizeScreen) self.genderOptions = None self.genderLabel = None self.speciesOptions = None self.speciesLabel = None self.legOptions = None self.legLabel = None self.torsoOptions = None self.torsoLabel = None self.headOptions = None self.headLabel = None self.muzzleOptions = None self.muzzleLabel = None self.gloveOptions = None self.gloveLabel = None self.headColorOptions = None self.headColorLabel = None self.armColorOptions = None self.armColorLabel = None self.legColorOptions = None self.legColorLabel = None self.shirtColorOptions = None self.shirtColorLabel = None self.bottomsColorOptions = None self.bottomsColorLabel = None self.shirtLabel = None self.shirtEntry = None self.shortsLabel = None self.shortsEntry = None self.doneButton = None geom.removeNode() rotateGeoms = loader.loadModel('phase_6/models/gui/ui_arrow_buttons') leftGeom = (rotateGeoms.find('**/*ArrowLeft*Up'), rotateGeoms.find('**/*ArrowLeft*Down'), rotateGeoms.find('**/*ArrowLeft*Rollover')) rightGeom = (rotateGeoms.find('**/*ArrowRight*Up'), rotateGeoms.find('**/*ArrowRight*Down'), rotateGeoms.find('**/*ArrowRight*Rollover')) self.leftButton = DirectButton(parent=self, relief=None, image=leftGeom, pos=(-0.11, 0, -0.07)) self.rightButton = DirectButton(parent=self, relief=None, image=rightGeom, pos=(0.11, 0, -0.07)) self.leftButton.bind(DGG.B1PRESS, self.__rotateToon, [-3]) self.leftButton.bind(DGG.B1RELEASE, self.__stopRotation) self.rightButton.bind(DGG.B1PRESS, self.__rotateToon, [3]) self.rightButton.bind(DGG.B1RELEASE, self.__stopRotation) rotateGeoms.removeNode() self.toon = None self.dna = None self.pitch = self.attachNewNode('pitch') self.rotate = self.pitch.attachNewNode('rotate') self.scale = self.rotate.attachNewNode('scale') self.pitch.setP(0) self.makeToon() def makeToon(self, dna=None): if self.toon: self.toon.cleanup() self.toon.delete() self.toon.removeNode() self.toon = None self.dna = None if not dna: dna = base.localAvatar.getDNAString() self.toon = Toon.Toon() self.dna = ToonDNA.ToonDNA() self.dna.makeFromNetString(dna) self.toon.setDNA(self.dna) self.toon.getGeomNode().setDepthWrite(1) self.toon.getGeomNode().setDepthTest(1) self.toon.setHpr(180, 0, 0) self.toon.setZ(-0.45) scaleFactor = 0.2 if self.dna.legs == 'l': scaleFactor = 0.19 self.toon.setScale(scaleFactor) self.toon.reparentTo(self.scale) def __rotateToon(self, *args): taskMgr.add(self.__rotateTask, 'toonRotateTask', extraArgs=[args[0]], appendTask=True) def __rotateTask(self, direction, task): if hasattr(self, 'pitch'): self.pitch.setH((self.pitch.getH() % 360) + 0.4 * direction) return task.cont else: return task.done def __stopRotation(self, *args): taskMgr.remove('toonRotateTask') def __selectHead(self, *args): species = name2code.get(args[0].lower()) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(head=species + self.dna.head[1:]) self.makeToon(newDNA.makeNetString()) def __selectLegs(self, *args): legs = args[0].lower() if legs == 'long': legs = 'l' elif legs == 'medium': legs = 'm' else: legs = 's' newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(legs=legs) self.makeToon(newDNA.makeNetString()) def __selectGloves(self, *args): color = args[0] if color == 'White': index = len(ToonDNA.NumToColor) + 1 else: index = ToonDNA.NumToColor.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(gloveColor=index) self.makeToon(newDNA.makeNetString()) def __selectTorso(self, *args): torso = args[0][0].lower() if self.dna.gender == 'f': torso += 'd' else: torso += 's' newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(torso=torso) self.makeToon(newDNA.makeNetString()) def __selectHeadSize(self, *args): size = args[0][0].lower() head = self.dna.head newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(head=head[0] + size + head[2]) self.makeToon(newDNA.makeNetString()) def __selectMuzzleSize(self, *args): size = args[0][0].lower() head = self.dna.head newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(head=head[0] + head[1] + size) if newDNA.head in ToonDNA.toonHeadTypes: self.makeToon(newDNA.makeNetString()) def __selectGender(self, *args): gender = args[0].lower() if gender == 'boy': gender = 'm' else: gender = 'f' newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) #newDNA.updateToonProperties(gender=gender) newDNA.updateToonProperties(gender=gender, bottomTexture=0) self.makeToon(newDNA.makeNetString()) def __choseHeadColor(self, *args): color = args[0] if color == 'White': index = len(ToonDNA.NumToColor) + 1 else: index = ToonDNA.NumToColor.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(headColor=index) self.makeToon(newDNA.makeNetString()) def __choseArmColor(self, *args): color = args[0] if color == 'White': index = len(ToonDNA.NumToColor) + 1 else: index = ToonDNA.NumToColor.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(armColor=index) self.makeToon(newDNA.makeNetString()) def __choseLegColor(self, *args): color = args[0] if color == 'White': index = len(ToonDNA.NumToColor) + 1 else: index = ToonDNA.NumToColor.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(legColor=index) self.makeToon(newDNA.makeNetString()) def __choseShirtColor(self, *args): color = args[0] index = ToonDNA.ClothesColorNames.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(topTextureColor=index, sleeveTextureColor=index) self.makeToon(newDNA.makeNetString()) def __choseShortsColor(self, *args): color = args[0] index = ToonDNA.ClothesColorNames.index(color) newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(bottomTextureColor=index) self.makeToon(newDNA.makeNetString()) def __changeShirt(self, *args): index = int(args[0]) if index not in range(0, len(ToonDNA.Shirts)): return newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(topTexture=index) self.makeToon(newDNA.makeNetString()) def __changeShorts(self, *args): index = int(args[0]) bottoms = ToonDNA.BoyShorts if self.dna.gender == 'm' else ToonDNA.GirlBottoms if index not in range(0, len(bottoms)): return newDNA = ToonDNA.ToonDNA() newDNA.makeFromNetString(self.dna.makeNetString()) newDNA.updateToonProperties(bottomTexture=index) self.makeToon(newDNA.makeNetString()) def load(self): genders = ['Boy', 'Girl'] gMap = {'m': genders[0], 'f': genders[1]} gIndex = gMap.get(self.dna.gender) self.genderOptions = CustomizeOption(parent=self, command=self.__selectGender, initialitem=gIndex, items=genders, pos=(1.15, 0, 0.7)) self.genderLabel = DirectLabel(parent=self.genderOptions, relief=None, text_font=FONT, text='Gender:', text_scale=0.85, pos=(-2.59, 0, 0)) species = [ 'Bear', 'Cat', 'Dog', 'Duck', 'Horse', 'Monkey', 'Mouse', 'Pig', 'Rabbit' ] sIndex = species.index(code2name.get(self.dna.head[0]).capitalize()) self.speciesOptions = CustomizeOption(parent=self, command=self.__selectHead, initialitem=sIndex, items=species, pos=(1.15, 0, 0.55)) self.speciesLabel = DirectLabel(parent=self.speciesOptions, relief=None, text_font=FONT, text='Species:', text_scale=0.85, pos=(-2.7, 0, 0)) headOptions = ['Short', 'Long'] types = {'s': headOptions[0], 'l': headOptions[1]} hIndex = headOptions.index(types.get(self.dna.head[1])) self.headOptions = CustomizeOption(parent=self, command=self.__selectHeadSize, initialitem=hIndex, items=headOptions, pos=(1.15, 0, 0.4)) self.headLabel = DirectLabel(parent=self.headOptions, relief=None, text_font=FONT, text='Head Size:', text_scale=0.85, pos=(-3.07, 0, 0)) mIndex = headOptions.index(types.get(self.dna.head[2])) self.muzzleOptions = CustomizeOption(parent=self, command=self.__selectMuzzleSize, initialitem=mIndex, items=headOptions, pos=(1.15, 0, 0.25)) self.muzzleLabel = DirectLabel(parent=self.muzzleOptions, relief=None, text_font=FONT, text='Muzzle Size:', text_scale=0.85, pos=(-3.4, 0, 0)) legs = ['Small', 'Medium', 'Long'] legType = {'s': 'Small', 'm': 'Medium', 'l': 'Long'} lIndex = legs.index(legType.get(self.dna.legs)) self.legOptions = CustomizeOption(parent=self, command=self.__selectLegs, initialitem=lIndex, items=legs, pos=(1.15, 0, 0.1)) self.legLabel = DirectLabel(parent=self.legOptions, relief=None, text_font=FONT, text='Leg Length:', text_scale=0.85, pos=(-3.21, 0, 0)) tIndex = legs.index(legType.get(self.dna.torso[0])) self.torsoOptions = CustomizeOption(parent=self, command=self.__selectTorso, initialitem=tIndex, items=legs, pos=(1.15, 0, -0.05)) self.torsoLabel = DirectLabel(parent=self.torsoOptions, relief=None, text_font=FONT, text='Torso Length:', text_scale=0.85, pos=(-3.57, 0, 0)) gloveColor = self.dna.gloveColor length = len(ToonDNA.NumToColor) if gloveColor > length: gloveColor = 0 headColor = self.dna.headColor if headColor > length: headColor = 0 armColor = self.dna.armColor if armColor > length: armColor = 0 legColor = self.dna.legColor if legColor > length: legColor = 0 self.gloveOptions = CustomizeOption(parent=self, command=self.__selectGloves, initialitem=gloveColor, items=ToonDNA.NumToColor, pos=(1.15, 0, -0.2), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.gloveLabel = DirectLabel(parent=self.gloveOptions, relief=None, text_font=FONT, text='Glove Color:', text_scale=0.85, pos=(-3.35, 0, 0)) self.headColorOptions = CustomizeOption(parent=self, command=self.__choseHeadColor, initialitem=headColor, items=ToonDNA.NumToColor, pos=(1.15, 0, -0.35), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.headColorLabel = DirectLabel(parent=self.headColorOptions, relief=None, text_font=FONT, text='Head Color:', text_scale=0.85, pos=(-3.27, 0, 0)) self.armColorOptions = CustomizeOption(parent=self, command=self.__choseArmColor, initialitem=armColor, items=ToonDNA.NumToColor, pos=(1.15, 0, -0.5), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.armColorLabel = DirectLabel(parent=self.armColorOptions, relief=None, text_font=FONT, text='Arm Color:', text_scale=0.85, pos=(-3.074, 0, 0)) self.legColorOptions = CustomizeOption(parent=self, command=self.__choseLegColor, initialitem=legColor, items=ToonDNA.NumToColor, pos=(1.15, 0, -0.65), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.legColorLabel = DirectLabel(parent=self.legColorOptions, relief=None, text_font=FONT, text='Leg Color:', text_scale=0.85, pos=(-3, 0, 0)) self.shirtColorOptions = CustomizeOption( parent=self, command=self.__choseShirtColor, initialitem=self.dna.topTexColor - 1, items=ToonDNA.ClothesColorNames[1:], pos=(1.15, 0, -0.8), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.shirtColorLabel = DirectLabel(parent=self.shirtColorOptions, relief=None, text_font=FONT, text='Shirt Color:', text_scale=0.85, pos=(-3, 0, 0)) self.bottomsColorOptions = CustomizeOption( parent=self, command=self.__choseShortsColor, initialitem=self.dna.botTexColor - 1, items=ToonDNA.ClothesColorNames[1:], pos=(1.15, 0, -0.95), image_pos=(1.55, 0, 0.15), text_pos=(-0.13, -.1)) self.bottomsColorLabel = DirectLabel(parent=self.bottomsColorOptions, relief=None, text_font=FONT, text='Shorts Color:', text_scale=0.85, pos=(-3, 0, 0)) self.shirtEntry = DirectEntry(parent=self, relief=DGG.GROOVE, scale=0.08, pos=(1.6, 0, 0.3), borderWidth=(0.05, 0.05), state=DGG.NORMAL, text_font=FONT, frameColor=((1, 1, 1, 1), (1, 1, 1, 1), (0.5, 0.5, 0.5, 0.5)), text_align=TextNode.ALeft, text_scale=0.8, width=3.5, numLines=1, focus=1, backgroundFocus=0, cursorKeys=1, text_fg=(0, 0, 0, 1), suppressMouse=1, autoCapitalize=0, command=self.__changeShirt) self.shirtEntry.enterText(str(self.dna.topTex)) self.shirtLabel = DirectLabel(parent=self.shirtEntry, relief=None, text_font=FONT, text='Shirt:', text_scale=0.85, pos=(1.25, 0, 1.25)) self.shortsEntry = DirectEntry(parent=self, relief=DGG.GROOVE, scale=0.08, pos=(1.6, 0, 0.0), borderWidth=(0.05, 0.05), state=DGG.NORMAL, text_font=FONT, frameColor=((1, 1, 1, 1), (1, 1, 1, 1), (0.5, 0.5, 0.5, 0.5)), text_align=TextNode.ALeft, text_scale=0.8, width=3.5, numLines=1, focus=1, backgroundFocus=0, cursorKeys=1, text_fg=(0, 0, 0, 1), suppressMouse=1, autoCapitalize=0, command=self.__changeShorts) self.shortsEntry.enterText(str(self.dna.botTex)) self.shortsLabel = DirectLabel(parent=self.shortsEntry, relief=None, text_font=FONT, text='Shorts:', text_scale=0.85, pos=(1.25, 0, 1.25)) buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui') upButton = buttonModels.find('**//InventoryButtonUp') downButton = buttonModels.find('**/InventoryButtonDown') rolloverButton = buttonModels.find('**/InventoryButtonRollover') self.doneButton = DirectButton(parent=self, text_font=FONT, text='Done', command=self.__handleDone, scale=0.2, image=(upButton, downButton, rolloverButton), relief=None, text_fg=(1, 1, 0.65, 1), pos=(0, 0, -0.94), text_pos=(0, -.23), image_color=(1, 0, 0, 1), image_scale=(20, 1, 15), sortOrder=DGG.GEOM_SORT_INDEX) buttonModels.removeNode() def __handleDone(self): base.localAvatar.b_setDNAString(self.dna.makeNetString()) self.unload() def unload(self): if self.genderLabel: self.genderLabel.destroy() self.genderLabel = None if self.genderOptions: self.genderOptions.destroy() self.genderOptions = None if self.speciesLabel: self.speciesLabel.destroy() self.speciesLabel = None if self.speciesOptions: self.speciesOptions.destroy() self.speciesOptions = None if self.headLabel: self.headLabel.destroy() self.headLabel = None if self.headOptions: self.headOptions.destroy() self.headOptions = None if self.muzzleLabel: self.muzzleLabel.destroy() self.muzzleLabel = None if self.muzzleOptions: self.muzzleOptions.destroy() self.muzzleOptions = None if self.torsoLabel: self.torsoLabel.destroy() self.torsoLabel = None if self.torsoOptions: self.torsoOptions.destroy() self.torsoOptions = None if self.legLabel: self.legLabel.destroy() self.legLabel = None if self.legOptions: self.legOptions.destroy() self.legOptions = None if self.gloveLabel: self.gloveLabel.destroy() self.gloveLabel = None if self.gloveOptions: self.gloveOptions.destroy() self.gloveOptions = None if self.headColorOptions: self.headColorOptions.destroy() self.headColorOptions = None if self.headColorLabel: self.headColorLabel.destroy() self.headColorLabel = None if self.armColorOptions: self.armColorOptions.destroy() self.armColorOptions = None if self.armColorLabel: self.armColorLabel.destroy() self.armColorLabel = None if self.legColorOptions: self.legColorOptions.destroy() self.legColorOptions = None if self.legColorLabel: self.legColorLabel.destroy() self.legColorLabel = None if self.shirtColorLabel: self.shirtColorLabel.destroy() self.shirtColorLabel = None if self.shirtColorOptions: self.shirtColorOptions.destroy() self.shirtColorOptions = None if self.bottomsColorLabel: self.bottomsColorLabel.destroy() self.bottomsColorLabel = None if self.bottomsColorOptions: self.bottomsColorOptions.destroy() self.bottomsColorOptions = None if self.shirtLabel: self.shirtLabel.destroy() self.shirtLabel = None if self.shirtEntry: self.shirtEntry.destroy() self.shirtEntry = None if self.shortsLabel: self.shortsLabel.destroy() self.shortsLabel = None if self.shortsEntry: self.shortsEntry.destroy() self.shortsEntry = None if self.doneButton: self.doneButton.destroy() self.doneButton = None if self.toon: self.toon.cleanup() self.toon.delete() self.toon.removeNode() self.toon = None self.dna = None self._callback(self) self.destroy()