def __init__(self, mainActor): self.teamMateImage = 'models/hexahedron.png' self.heroImage = 'models/mainHero2.png' self.miniMapImage = 'models/miniMap000.png' self.towerImage = 'models/tower_neitral.png' self.towerRed = 'models/tower_red.png' self.towerBlue = 'models/tower_blue.png' self.map = OnscreenImage(image = self.miniMapImage, pos=(-0.7, 0, 0.8), scale=(MAP_SCALEX, 0, MAP_SCALEY)) self.map.setTransparency(1) #self.map.reparentTo(rander) self.hero = OnscreenImage(image=self.heroImage, pos=(mainActor.getX()/525, 0, mainActor.getY()/160), scale=(HERO_SCALE, 1, HERO_SCALE), hpr=(0, 0, mainActor.getH())) self.hero.reparentTo(self.map) self.hero.setTransparency(1) self.npc = {} self.tower = {} self.team = {}
def show_map(self, task): main_char=self.gameEngine.vehicleContainer if main_char != None: x=main_char.chassisNP.getX() y=main_char.chassisNP.getY() h=main_char.chassisNP.getH() #temporary value size=200 bound=80 # connected player for i in self.gameEngine.vehiclelist: car= self.gameEngine.vehiclelist[i] if car != None: i_x=car.chassisNP.getX() i_y=car.chassisNP.getY() i_h=car.chassisNP.getH() if(i_x<bound and i_y<bound and i_y>(bound*-1) and i_x>(bound*-1) ): self.otherchar.destroy() self.otherchar = OnscreenImage(image='models/power_ups/pow1.png', scale=.07, parent=self.mini_map , pos=(i_x/size, 0, i_y/size),color=(1,1,0,1)) self.otherchar.setR(-i_h) self.screenBtns.append(self.otherchar) #powerup if(x<bound and y<bound and x>(bound*-1) and x>(bound*-1)): self.char.destroy() self.char = OnscreenImage(image='models/triangle.png', scale=.1, parent=self.mini_map ,pos=(x/size, 0, y/size)) self.char.setR(-h) self.screenBtns.append(self.char) return task.cont
def __init__(self): self.frameCharStatus = DirectFrame( # size of the frame frameSize = (0, .8, -.20, 0), # bg color Transparent frameColor = (0, 0, 0, 0)) self.frameCharStatus.reparentTo(base.a2dTopLeft) self.statusHealth = OnscreenImage( image = "HUD_Life100.png", scale = (0.1, 1, 0.1), pos = (0.085, 0, -0.085)) self.statusHealth.setTransparency(True) self.statusHealth.reparentTo(self.frameCharStatus) self.statusWeapon = OnscreenImage( image = "WeaponMG.png", scale = (0.1, 1, 0.1), pos = (0.285, 0, -0.085)) self.statusWeapon.setTransparency(True) self.statusWeapon.reparentTo(self.frameCharStatus) self.highscore = DirectLabel( text = "0", text_fg = (0,0,0,1), text_align = TextNode.ALeft, frameColor = (0,0,0,0), pos = (0.4,0,-0.12), scale = 0.15) self.highscore.setTransparency(True) self.highscore.reparentTo(self.frameCharStatus)
def setupSpeedImages(self): self.display_speed = OnscreenText(text="0", style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Display Gear self.display_gear = OnscreenText(text="N", style=3, fg=(1, 1, 1, 1), pos=(0.917, -0.80), align=TextNode.ARight, scale=.10, font=self.font_digital) # Speedometer self.speed_img = OnscreenImage(image="models/dashb/meterBG.png", scale=.25, pos=(0.9, 0, -.65)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) # Needle self.MaxNeedleAngle = 260 self.speedNeedleAngle = 0 self.speedNeedle_img = OnscreenImage(image="models/dashb/meterNeedle.png", scale=.25, pos=(0.9, 0, -.65), hpr = (0,0,self.speedNeedleAngle)) self.speedNeedle_img.setTransparency(TransparencyAttrib.MAlpha) # Meter Top self.speedTop = OnscreenImage(image="models/dashb/meterTop.png", scale=.25, pos=(0.9, 0, -.65)) self.speedTop.setTransparency(TransparencyAttrib.MAlpha) self.screenBtns.append(self.display_speed) self.screenBtns.append(self.display_gear) self.screenBtns.append(self.speed_img) self.screenBtns.append(self.speedNeedle_img) self.screenBtns.append(self.speedTop)
def Preload(): loader.loadModel('Assets/Models/Items/SMGAuto') loader.loadModel('Assets/Models/Items/RifleAuto') loader.loadModel('Assets/Models/Items/SniperBolt') loader.loadModel('Assets/Models/Players/ralph') currentDir = os.getcwd() for root, dirs, files in os.walk(currentDir): for f in files: if f.endswith('.png'): i = root.find('Assets') s = '%s/%s' % (root[i:].replace('\\', '/'), f) #loader.loadTexture(s) x = OnscreenImage(image = s) x.reparentTo(render) x.destroy() print 'Loaded', s Globals.FONT_SAF = loader.loadFont('Assets/Fonts/SAF.otf') Globals.FONT_SAF.setPixelsPerUnit(60) print 'Loaded Assets/Fonts/SAF.otf' Globals.AUDIO_3D = Audio3DManager.Audio3DManager(base.sfxManagerList[0], base.camera) Globals.AUDIO_3D.setDistanceFactor(15.0) Globals.LoadRocket()
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) base.disableMouse() # Allow manual positioning of the camera camera.setPos(0, -10, 1) # Set the cameras' position camera.setHpr(0, 0, 0) # and orientation self.keyMap = { "left": 0, "right": 0, "up": 0, "down": 0} taskMgr.add(self.startCarousel, "moveTask") imageObject = OnscreenImage(image = 'env_sky.jpg', pos = (-10,0,-10)) imageObject.setImage('env_sky.jpg') imageObject.setTransparency(TransparencyAttrib.MAlpha) self.loadModels() # Load and position our models self.setupLights() # Add some basic lighting self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["up", True]) self.accept("arrow_down", self.setKey, ["down", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["up", False]) self.accept("arrow_down-up", self.setKey, ["down", False])
def __init__(self, cursor): #----------------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------ #----------------------------------------------------------------------------------------------------------------------------------------------- self.title = None self.play = None self.credits = None self.ins = None self.selected = "PLAY" self.pastTime = 0.0 self.oldX = 0.0 self.run = True self.moved = 0.0 #----------------------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------MENU INIT---------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------------------- self.title = OnscreenImage("./tex/menu/glooveth.png", (0, 0, -0.25), None, (1.0,1.0,0.25), None, None, 10) self.title.setTransparency(TransparencyAttrib.MAlpha) self.credits = OnscreenImage("./tex/menu/credits.png", (-1.0, 0, -0.75), None, (0.25,1.0,0.125), None, None, 10) self.credits.setTransparency(TransparencyAttrib.MAlpha) self.ins = OnscreenImage("./tex/menu/ins.png", (1.0, 0, -0.75), None, (0.25,1.0,0.125), None, None, 10) self.ins.setTransparency(TransparencyAttrib.MAlpha) self.play = OnscreenImage("./tex/menu/playOver.png", (0, 0, -0.75), None, (0.35,1.0,0.20), None, None, 10) self.play.setTransparency(TransparencyAttrib.MAlpha) # Cursor self.cursor = cursor # Start tasks taskMgr.add(self.taskMenuMovement, 'taskMenuMovement')
class SplashCard(object): '''this class shows up a splash message''' #------------------------------------------------------------ # def __init__(self, image, backgroundColor): self.loadingimage = OnscreenImage(image, color=(1, 1, 1, 1), scale=.5, parent=aspect2d) self.loadingimage.setTransparency(1) # this image will be on top of all therefore we use setBin 'fixed' and with the higher sort value self.loadingimage.setBin("fixed", 20) self.curtain = OnscreenImage('textures/curtain.png', parent=render2d, color=backgroundColor) self.curtain.setTransparency(1) # this is to set it below the loading panel self.curtain.setBin("fixed", 10) # the loading panel faders self.loadingOut = self.loadingimage.colorInterval(1, Vec4(1, 1, 1, 0), Vec4(1, 1, 1, 1)) # the black curtain faders self.openCurtain = self.curtain.colorScaleInterval(1, Vec4(1, 1, 1, 0), Vec4(1, 1, 1, 1)) for i in range(4): base.graphicsEngine.renderFrame() #------------------------------------------------------------ # def destroy(self): Sequence(self.loadingOut, self.openCurtain).start() #Sequence(self.openCurtain).start() #self.loadingimage.destroy() #self.curtain.destroy()
def add_counter (self, attr, pic): root = NodePath (PandaNode ('new-root')) root.reparentTo (self.node) img = OnscreenImage ( image = pic, pos = self._next_position, parent = root, scale = 0.1) img.setTransparency (TransparencyAttrib.MAlpha) setattr (self, 'img_' + attr, img) txt_pos = self._next_position + Vec3 (.12, 0, -.05) txt = OnscreenText ( text = '0', shadow = (1, 1, 1, 1), font = self.font, mayChange = True, pos = (txt_pos.getX (), txt_pos.getZ ()), scale = .16, align = TextNode.ALeft, parent = root) setattr (self, 'txt_' + attr, txt) self._next_position += Vec3 (0, 0, -.22) self._counter_nodes.append (root)
def guiLoop(self, task): #Scroll up and down to scroll through weapons if self.keys["swap-up"]: if self.wepCounter < 2: self.wepCounter += 1 else: self.wepCounter = 0 self.wepDisplay.remove() self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) self.wepIcon.remove() self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1)) self.wepIcon.setTransparency(TransparencyAttrib.MAlpha) self.keys["swap-up"] = 0 if self.keys["swap-down"]: if self.wepCounter > 0: self.wepCounter -= 1 else: self.wepCounter = 2 self.wepDisplay.remove() self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) self.wepIcon.remove() self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1)) self.wepIcon.setTransparency(TransparencyAttrib.MAlpha) self.keys["swap-down"] = 0 return Task.cont
def __init__(self, main): self.main = main self.mainFrame = DirectFrame(parent = base.render2d, frameColor = (1,0,0,0), pos = (0,0,0), frameSize = (-1,1,-1,1)) self.mainImage = OnscreenImage(parent = self.mainFrame, image = 'Models/menu/menu.png', pos = (0, 0, 0)) self.startImage = OnscreenImage(image = 'Models/menu/Start.png', pos = (-0.8,0,0), scale = 0.3) self.startImage.setTransparency(TransparencyAttrib.MMultisampleMask) self.exitImage = OnscreenImage(image = 'Models/menu/Exit.png', pos = (0.8,0,0), scale = 0.3) self.exitImage.setTransparency(TransparencyAttrib.MMultisampleMask) self.menuFrame = DirectFrame(frameColor=(0,0,0,0), pos = (0,0,-0.2), frameSize=(-0.5,0.5,0.7,-0.4 )) self.start = DirectButton(parent = self.menuFrame, pos = (-0.8,0,0.2), frameColor = (0,0,0,0), frameSize = (-1,1,-1,1), scale = 0.3, command = self.start) self.start.guiItem.setActive(True) self.start.bind(DGG.WITHIN, self.mouseOverStart, [self.start]) self.start.bind(DGG.WITHOUT, self.mouseOutStart, [self.start]) self.exit = DirectButton(parent = self.menuFrame, pos = (0.8,0,0.2), frameColor = (0,0,0,0), frameSize = (-1,1,-1,1), scale = 0.3, command = main.exit) self.exit.guiItem.setActive(True) self.exit.bind(DGG.WITHIN, self.mouseOverExit, [self.exit]) self.exit.bind(DGG.WITHOUT, self.mouseOutExit, [self.exit])
def __init__(self): taskMgr.add(self.step,"MinimapTask") pos = Vec3(1.4, 0, -0.64) self.scale = (180) self.constant = 22 cpos = Vec3(0,0,0) #center mapImage = "models/gui/minimap/minimap.png" self.mapRadius = 75 self.distanceScale = (20*self.mapRadius/self.scale) self.map = aspect2d.attachNewNode('Map') props = base.win.getProperties() self.Height = float(props.getYSize()) self.Hscale = (1/self.Height) self.map.setScale(self.Hscale) self.map.setPos(pos) self.dots = [] self.dotPlayer = OnscreenImage(image = "models/gui/minimap/Player.png", scale = 3,pos = (base.camera.getX()/self.constant,0,base.camera.getY()/self.constant), parent = self.map) self.planetTargets = None self.starTargets = None image = OnscreenImage(image = mapImage, scale = self.scale, parent = self.map) image.setTransparency(True)
class OnscreenInterface(): def __init__(self): pass def createStartScreen(self): self.startScreen = OnscreenImage(image = "images/HopperStartScreen.png", pos = (0, 0, 0), scale = (1.35, 1, 1)) def destroyStartScreen(self): self.startScreen.destroy() def startButton(self): #maps = loader.loadModel('maps/button_maps') return DirectButton(text = ("Start", "Start", "Start", "disabled"), scale = .18, pos = (0, 0, -0.3))#, geom = (maps.find('**/button_ready'), maps.find('**/button_click'), maps.find('**/button_rollover'), maps.find('**/button_disabled'))) def createLevelSelectScreen(self): self.levelSelectScreen = OnscreenImage(image = "images/levelSelect.png", pos = (0, 0, 0), scale = (1.35, 1, 1)) def destroyLevelSelectScreen(self): self.levelSelectScreen.destroy() def levelSelectButton(self, level, pos): return DirectButton(text = ("Level "+str(level), "Level "+str(level), "Level "+str(level), "disabled"), scale = .09, pos = (pos, 0, -0.6)) def createMenu(self): self.blackFrame = DirectFrame(frameColor=(0, 0, 0, 0.5), frameSize=(-3,3,-3,1),pos=(-1,1,1)) def destroyMenu(self): self.blackFrame.destroy() def menuButton(self, text, pos): return DirectButton(text=(text,text,text,text), scale = .1, pos = (0, 0, pos))
class Preloader: def __init__(self, fonts): self.createGraphics(fonts) file = open("models.txt", "r") self.models = file.readlines() file.close() for N in range(len(self.models)): self.models[N] = self.models[N].replace("\n", "") self.totalItems = len(self.models) self.loaderBar.setTexOffset(self.modTS, .015, 0) base.graphicsEngine.renderFrame() #base.graphicsEngine.renderFrame() self.itemCount = 0 for M in self.models: item = loader.loadModel(M) self.itemCount += 1 progress = self.itemCount / float(self.totalItems) self.loaderBar.setTexOffset(self.modTS, -progress + .005, 0) base.graphicsEngine.renderFrame() #base.graphicsEngine.renderFrame() self.destroy() def createGraphics(self, fonts): self.modTS = TextureStage("Modulate") self.modTS.setMode(TextureStage.MModulate) self.frame = DirectFrame(frameSize = (-.3, .3, -.2, .2), frameColor = (1,1,1,0), parent = base.aspect2d) loaderEgg = loader.loadModel("Models/EnergyBar.egg") self.loaderBG = loaderEgg.find("**/EnergyBG") self.loaderBar = loaderEgg.find("**/EnergyBar") self.loaderFrame = loaderEgg.find("**/EnergyFrame") self.loaderBG.reparentTo(self.frame) self.loaderBar.reparentTo(self.loaderBG) self.loaderFrame.reparentTo(self.loaderBG) self.loaderBG.setPos(0, 0, -.2) alpha = loader.loadTexture("Models/LoaderAlpha.png") alpha.setFormat(Texture.FAlpha) alpha.setWrapU(Texture.WMClamp) self.loaderBar.setTexture(self.modTS, alpha) self.image = OnscreenImage(image = 'Models2/3dcrlogo.png', pos = (0, 0, -.05), scale = (0.799,0,0.152)) self.image.setTransparency(TransparencyAttrib.MAlpha) return def destroy(self): self.loaderBG.removeNode() self.image.destroy() self.frame.destroy()
class Shockley: def __init__(self, preload=False): self.sceneRoot = None self.preload = preload def load(self): self.sceneRoot = NodePath('Shockley') base.setBackgroundColor(0, 0, 0, 1) self.title = OnscreenText(text='Shockley ', pos=(0.6, 0.15, 0.0), scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=TextNode.ACenter) self.description = OnscreenText(text='Lead Developer\nNetwork Technician\nGame Systems Engineer', pos=(0.25, 0.05, 0.0), scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=TextNode.ALeft) self.image = OnscreenImage(image='phase_4/maps/news/11-17-13_garden.jpg', pos=(-0.5, 0.0, 0.0), scale=(0.5, 0.30, 0.30)) self.elements = [self.title, self.description, self.image] for node in self.elements: node.setTransparency(1) if self.preload: node.setColorScale(1, 1, 1, 0) def makeInterval(self): return Sequence( ParentInterval(self.sceneRoot, render), # This fades in during the election's WrapUp state to prevent jittering when loading this first scene. Wait(3), Func(doFade, 'out', self.elements), Wait(0.5), ParentInterval(self.sceneRoot, hidden) ) def unload(self): self.sceneRoot.removeNode() self.title.removeNode() self.description.removeNode() self.image.removeNode()
def __init__(self): Bar.__init__(self) #----------------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------ #----------------------------------------------------------------------------------------------------------------------------------------------- # Init the bar with alpha sprites self.cereal = False self.specialCereal = OnscreenImage(image="./tex/cereal_not_special.png", pos = (0.43, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1) self.specialCereal.setTransparency(TransparencyAttrib.MAlpha) self.banana = False self.specialBanana = OnscreenImage(image="./tex/banana_not_special.png", pos = (0.63, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1) self.specialBanana.setTransparency(TransparencyAttrib.MAlpha) self.cheese = False self.specialCheese = OnscreenImage(image="./tex/cheese_not_special.png", pos = (0.83, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1) self.specialCheese.setTransparency(TransparencyAttrib.MAlpha) self.tomato = False self.specialTomato = OnscreenImage(image="./tex/tomato_not_special.png", pos = (1.03, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1) self.specialTomato.setTransparency(TransparencyAttrib.MAlpha) self.egg = False self.specialEgg= OnscreenImage(image="./tex/egg_not_special.png", pos = (1.23, 0, 0.87),hpr=None, scale = 0.11, color=None, parent=None, sort=1) self.specialEgg.setTransparency(TransparencyAttrib.MAlpha)
class ResultScreen: def __init__(self, rank, score, stats): text_list = [] text_list.append(OnscreenText(text = 'Level Ended', pos = (0.0, 0.7), scale = 0.3, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1))) judgements = ["PERFECT","GOOD","OK","BAD","MISS"] text_j = "\n".join(judgements) text_n = "\n".join(["%d" % stats[j] for j in judgements]) text_list.append(OnscreenText(text = text_j, pos = (-1.2, 0.35), scale = 0.2, font=babelfish_font, align=TextNode.ALeft, fg=(1,1,1,1))) text_list.append(OnscreenText(text = text_n, pos = (0.2, 0.35), scale = 0.2, font=babelfish_font, align=TextNode.ARight, fg=(1,1,1,1))) text_list.append((OnscreenText(text = "RANK", pos = (0.85, 0.35), scale = 0.15, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)))) self.rank_image = OnscreenImage(image = "./image/rank_%s.png" % rank, pos = (0.7, 0.0, -0.2), scale = (256.0/base.win.getXSize()*0.8, 1.0, 256.0/base.win.getYSize()*0.8), parent=render2d) self.rank_image.setTransparency(TransparencyAttrib.MAlpha) #text_list.append((OnscreenText(text = rank, pos = (0.75, -0.25), scale = 0.9, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)))) text_list.append((OnscreenText(text = 'SCORE %d'%score, pos = (0.0, -0.7), scale = 0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)))) text_list.append((OnscreenText(text = 'press "SPACE " to continue', pos = (0.0, -0.9), scale = 0.16, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)))) self.text_list = text_list def clear(self): self.rank_image.destroy() for txt in self.text_list: txt.destroy()
class Interface(): def __init__(self): self.show_window() def show_window(self): self.window = OnscreenImage(image = "Interface/login_window.png", pos = (0,0,0), scale = (0.5, 1, 0.7) ) self.window.setTransparency(TransparencyAttrib.MAlpha) #add button self.usernameButton = DirectEntry(text = "" ,scale=.05, pos = (-0.3, 0, 0.3), initialText="Username", numLines = 2,focusInCommand=self.clearText1) self.passwordButton = DirectEntry(text = "" ,scale=.05, pos = (-0.3, 0, 0.1), initialText="Password", numLines = 2,focusInCommand=self.clearText2) self.submitButton = DirectButton(image = "Interface/submit2.png", pos = (-0.05, 0, -0.2),scale = (0.2, 1, 0.07)) self.submitButton.setTransparency(TransparencyAttrib.MAlpha) #clear the text def clearText1(self): self.usernameButton.enterText('') def clearText2(self): self.passwordButton.enterText('')
class LoadingScreen: def __init__(self, main): self.main = main self.imageObject = OnscreenImage(image = 'IMAGES/loading.jpg', pos = (0, 0, 0)) self.imageObject.reparentTo(render2d) #base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() def finish(self): self.imageObject.destroy() self.countDownText = OnscreenText(text=str(countDownStart), style=1, fg=(1,1,1,1), pos=(0.01, 0.1), align = TextNode.ACenter, scale = .2, mayChange = 1) taskMgr.add(self.countDown,"countDownTask") def countDown(self,task): timeLeft = "%01d" % (countDownStart - task.time) if (countDownStart - task.time) > 1: self.countDownText.setText(timeLeft) return task.cont elif 1 > (countDownStart - task.time) > 0: self.countDownText.setText("GO!") return task.cont else: self.canMove = True if not self.main.isActive: print "Activate" self.main.isActive = True taskMgr.add(self.main.update, 'updateWorld') self.main.activateKeys() self.countDownText.destroy() return task.done
class Game: """Game Instance, contains the menus, world, etc.""" def __init__(self, game): self.state = None self.world = None ##self.cfont = loader.loadFont('Coalition_v2.ttf') self.add_menu() def start_game(self): self.remove_menu() self.world = game.World() def exit_game(self): self.remove_menu() sys.exit() def add_menu(self): self.bg = OnscreenImage(image = "textures/Title_Screen_Final.png", pos=(0,0,0), scale=(1.35,1,1)) self.start_button = DirectButton(text = "START", scale = .12, text_fg = ((0,0,0,1)), command = self.start_game, pos=(0, 0, 0.4)) self.exit_button = DirectButton(text = ("EXIT"), scale = 0.12, command = self.exit_game, pos=(0, 0, 0)) self.bar = DirectWaitBar(text = "", value = 0, range = 10000, pos = (0,-.9,-.9), relief = DGG.SUNKEN, borderWidth = (.01,.01), barColor = (0,180,0,1)) self.bar.setSz(0.5) def remove_menu(self): if self.start_button: self.bar.finish(9000) self.start_button.removeNode() if self.bar: self.bar.removeNode() if self.bg: self.bg.removeNode() if self.exit_button: self.exit_button.removeNode()
def loadRareCandyImage(pos=(0.17,0,-0.75)): path = r"../google_drive/ball/data/img/rareCandy.png" rareCandyImage = OnscreenImage(parent=aspect2d, image=path, pos=pos, scale=_SCALE_RARE_CANDY) rareCandyImage.setTransparency(TransparencyAttrib.MAlpha) return rareCandyImage
class BetterOnscreenImage(DebugObject): def __init__(self, image=None, parent=None, x=0, y=0, w=10, h=10, transparent=True, nearFilter=True): DebugObject.__init__(self, "BOnscreenImage") self.initialPos = Vec3(x + w / 2.0, 1, -y - h / 2.0) self._node = OnscreenImage( image=image, parent=parent, pos=self.initialPos, scale=(w / 2.0, 1, h / 2.0)) if transparent: self._node.setTransparency(TransparencyAttrib.MAlpha) tex = self._node.getTexture() tex.setMinfilter(Texture.FTNearest) tex.setMagfilter(Texture.FTNearest) tex.setAnisotropicDegree(8) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) def getInitialPos(self): return self.initialPos def posInterval(self, *args, **kwargs): return self._node.posInterval(*args, **kwargs)
def set_manager(self, *args, **kwargs): preloader = OnscreenImage(image=S.preloader, scale=(1, 1, 1)) preloader.reparentTo(render2d) def callback(task): self.manager = Manager(*args, **kwargs) taskMgr.add(self.manager, 'manager') preloader.destroy() taskMgr.doMethodLater(0.1, callback, 'set_manager')
def LoadContent(self): bg = OnscreenImage(image = 'Assets/Images/Inventory/BlackScreen.png', scale = (2, 1, 1)) bg.setTransparency(TransparencyAttrib.MAlpha) bg.reparentTo(self.node) self.LoadButton('Button_Multiplayer', 'multiplayer', 'multiplayer_over', 0, 0, self.OnButtonClicked, ['multiplayer']) self.LoadButton('Button_Options', 'options', 'options_over', 0, -0.3, self.OnButtonClicked, ['options']) self.LoadButton('Button_Exit', 'exit', 'exit_over', 0, -0.6, self.OnButtonClicked, ['exit'])
def __init__(self, power): Bar.__init__(self) #----------------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------VARIABLE DECLARATION------------------------------------------------------------------------ #----------------------------------------------------------------------------------------------------------------------------------------------- self.amount = 0 self.power = [] #----------------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------BAR INIT------------------------------------------------------------------------------ #----------------------------------------------------------------------------------------------------------------------------------------------- if power == "GRAIN": self.path = "./tex/ability_cereal_bar.png" self.path2 = "./tex/rice.png" self.path3 = "./tex/ability_cereal_amount.png" self.posX = -1.20 self.posY = -0.85 if power == "FRUIT": self.path = "./tex/ability_fruit_bar.png" self.path2 = "./tex/straw.png" self.path3 = "./tex/ability_fruit_amount.png" self.posX = -1.08 self.posY = -0.85 if power == "MILK": self.path = "./tex/ability_milk_bar.png" self.path2 = "./tex/milk.png" self.path3 = "./tex/ability_milk_amount.png" self.posX = -0.96 self.posY = -0.85 if power == "VEGETABLE": self.path = "./tex/ability_vegetable_bar.png" self.path2 = "./tex/letuce.png" self.path3 = "./tex/ability_vegetable_amount.png" self.posX = -0.84 self.posY = -0.85 if power == "FISH": self.path = "./tex/ability_fish_bar.png" self.path2 = "./tex/fish.png" self.path3 = "./tex/ability_fish_amount.png" self.posX = -0.72 self.posY = -0.85 # Initial sprite bar self.bar = OnscreenImage(image=self.path, pos = (self.posX, 0, self.posY),hpr=None, scale = (0.05,1.0,0.035), color=None, parent=None, sort=1) self.bar.setTransparency(TransparencyAttrib.MAlpha) # Shape ability bar self.item = OnscreenImage(image=self.path2, pos = (self.posX, 0, -0.90),hpr=None, scale = 0.06, color=None, parent=None, sort=2) self.item.setTransparency(TransparencyAttrib.MAlpha) # It prepares sprites amount bar i=0 while i<5: self.power.append(OnscreenImage(image=self.path3, pos = (self.posX, 0, self.posY+((i+1)*0.055)),hpr=None, scale = (0.05,1.0,0.025), color=None, parent=None, sort=1)) self.power[i].setTransparency(TransparencyAttrib.MAlpha) self.power[i].hide() i=i+1
class Overlay(): def __init__(self, parent): taskMgr.add(self.guiLoop, "guiLoop") #HUD self.font = loader.loadFont("../assets/font/Orbitron Light.otf") self.momPercent = 100 self.wepCounter = 0 self.wepAmmo = [30, 5, 2] self.lefthudback = OnscreenImage(image = "../assets/2d/icons/hudback.png", pos = (-1.05, 0, -.9), scale=(.3,1,.2)) self.righthudback = OnscreenImage(image = "../assets/2d/icons/hudbackR.png", pos = (1.05, 0, -.9), scale=(.3,1,.2)) self.percentDisplay = OnscreenText(text = "%s %s" % (self.momPercent, "%"), fg = (0,1,1,1), pos = (-1.05, -.9), scale = .125, font = self.font) self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1)) self.wepIcon.setTransparency(TransparencyAttrib.MAlpha) #Define controls self.keys = {"swap-up": 0, "swap-down": 0} parent.accept("wheel_up", self.setKey, ["swap-up", 1]) parent.accept("wheel_down", self.setKey, ["swap-down", 1]) def setKey(self, key, val): self.keys[key] = val #Called to add or remove ammo def changeAmmo(self, counter, val): self.wepAmmo[counter] += val if self.wepCounter == counter: self.wepDisplay.remove() self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[counter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) def guiLoop(self, task): #Scroll up and down to scroll through weapons if self.keys["swap-up"]: if self.wepCounter < 2: self.wepCounter += 1 else: self.wepCounter = 0 self.wepDisplay.remove() self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) self.wepIcon.remove() self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1)) self.wepIcon.setTransparency(TransparencyAttrib.MAlpha) self.keys["swap-up"] = 0 if self.keys["swap-down"]: if self.wepCounter > 0: self.wepCounter -= 1 else: self.wepCounter = 2 self.wepDisplay.remove() self.wepDisplay = OnscreenText(text = "%s" % (self.wepAmmo[self.wepCounter]), fg = (0,1,1,1), pos = (.95, -.9), scale = .125, font = self.font) self.wepIcon.remove() self.wepIcon = OnscreenImage(image = "../assets/2d/icons/weapon%s.png" % (self.wepCounter), pos = (1.19, 0, -.875), scale=(.1,1,.1)) self.wepIcon.setTransparency(TransparencyAttrib.MAlpha) self.keys["swap-down"] = 0 return Task.cont
class ButtonViewer: def __init__(self, bpm, z_pos = -0.7): self.BTN_SPACE_PER_BEAT = 0.2 self.BTN_SIZE = 64.0 self.BTN_SIZE = 64.0 self.BTN_SCALE = (self.BTN_SIZE/base.win.getXSize(), 1 ,self.BTN_SIZE/base.win.getYSize()) self.z_pos = z_pos self.delay_per_beat = beat_delay(bpm) self.tex_buttons = {} for b, i in zip(["A", "B", "C", "D"],["down", "right", "left", "up"]): self.tex_buttons[b] = loader.loadTexture("image/wii_%s.png" % i) #~ else: #~ for b, i in zip(["A", "B", "C", "D"],["cross", "circle", "square", "triangle"]): #~ self.tex_buttons[b] = loader.loadTexture("image/b_%s.png" % i) ## Button marker self.button_marker = OnscreenImage(image="image/b_marker.png",pos=(0, 2, self.z_pos), scale=self.BTN_SCALE, parent=render2d) self.button_marker.setTransparency(TransparencyAttrib.MAlpha) self.button_node = render2d.attachNewNode("Button Root Node") self.initial_x = self.button_node.getX() self.next_button = 0 def append_button(self, button, beat): btn_image = OnscreenImage(image=self.tex_buttons[button], pos=(-beat*self.BTN_SPACE_PER_BEAT, 0, self.z_pos), scale=self.BTN_SCALE, parent=render2d) btn_image.setTransparency(TransparencyAttrib.MAlpha) btn_image.reparentTo(self.button_node) def update(self, time): self.button_node.setX(self.initial_x + time2pos(time, self.delay_per_beat, self.BTN_SPACE_PER_BEAT)) def button_hit(self): pass #~ button = self.button_node.getChild(self.next_button) #~ button.setAlphaScale(.0) #~ self.next_button += 1 #~ button = self.button_node.getChild(self.next_button ) #~ pos = render2d.getRelativePoint(self.button_node, button.getPos()) #~ button.reparentTo(render2d) #~ button.setPos(pos) #~ LerpFunc(button.setAlphaScale, duration=0.2, fromData=1, toData=0, blendType='easeOut').start() def button_miss(self): pass #self.next_button += 1 def __del__(self): self.button_node.removeNode() self.button_marker.removeNode()
def loadBackground(self, imagepath, imagepath1, imagepath2): self.background = OnscreenImage(parent=self.__base.render2dp, image=imagepath, pos=self.backgroundPos) self.preserveImageAspect(self.background) self.background1 = OnscreenImage(parent=self.__base.render2dp, image=imagepath1, pos=self.backgroundPos) self.background1.setTransparency(TransparencyAttrib.MAlpha) self.preserveImageAspect(self.background1) self.background2 = OnscreenImage(parent=self.__base.render2dp, image=imagepath2, pos=self.backgroundPos) self.background2.setTransparency(TransparencyAttrib.MAlpha) self.preserveImageAspect(self.background2) self.__base.cam2dp.node().getDisplayRegion(0).setSort(-20) # Force the rendering to render the background image first (so that it will be put to the bottom of the scene since other models will be necessarily drawn on top)
class LifebarUI(UIBase): def __init__(self,world): UIBase.__init__(self,world) #self.mainChar = world.hero self.liferoundImage = DirectFrame(image='./LEGameAssets/Textures/health_tray.png', pos = (1.34,0,-1), scale = (1.34,1,1), frameColor = (1,1,1,0)) self.lifebarImage = OnscreenImage(image='./LEGameAssets/Textures/lifebar.png', pos = (0.285,0,-0.125),scale=(0.215, 1, 0.026)) self.liferoundImage.setTransparency(1) self.liferoundImage.reparentTo(base.a2dTopLeft) self.lifebarImage.reparentTo(base.a2dTopLeft) self.entirelife = self.world.hero.getMaxHealth() #self.accept("a", self.update) #self.accept("s", self.reset) #self.update() def update(self): self.life = self.world.hero.getHealth() self.lifebarupdate(self.entirelife, self.life) #self.accept("a", self.lifebarupdate) #self.accept("s", self.hide) #self.accept("d", self.show) # print "lifebar" #pass def lifebarupdate(self, entirelife, life): #entirelife = 100 #self.life = self.life-10 if life>0: self.lifebarImage['scale'] = (float(life)/entirelife*0.215,1,0.026) self.lifebarImage['pos'] = (0.285-(1-float(life)/entirelife)*0.215,0,-0.125) else: self.lifebarImage.hide() def reset(self): self.life = self.world.hero.getMaxHealth() self.lifebarImage['scale'] = (0.215, 1, 0.026) self.lifebarImage['pos'] = (0.285,0,-0.125) self.lifebarImage.show() def hide(self): self.liferoundImage.hide() self.lifebarImage.hide() def show(self): self.liferoundImage.show() self.lifebarImage.show() #w = LifebarUI() #run()
def makeOnscreenVariable(self,fileName,x,y,z,width,height): imageVariable = OnscreenImage(image = fileName) imageVariable.reparentTo(pixel2d) imageVariable.setPos(x,y,z) imageVariable.setScale(width,1,height) #probably needs an include of some sort imageVariable.setTransparency(TransparencyAttrib.MAlpha) return imageVariable
class Enemy: def __init__(self, base, n, x, y, z): self.base = base self.n = n self.health = 4 self.np = base.loader.loadModel("./mdl/enemy.egg") self.np.setColor(1, 1, 0, 1) self.np.reparentTo(base.render) self.np.setPos(x, y, z) self.np.setAlphaScale(0.) base.target = self self.radar = OnscreenImage(image="./png/radar.png", pos=Vec3(0), scale=0.01) self.radar.setTransparency(TransparencyAttrib.MAlpha) # collisions cn = CollisionNode("enemy" + str(n)) cn.addSolid(CollisionBox(0, 2.5, 2, 0.5)) cn.setCollideMask(BitMask32(0x1) | BitMask32(0x2)) # cc = self.np.attachNewNode(cn) self.np.attachNewNode(cn) base.accept("fighter-into-enemy" + str(n), self.ship_collision) base.accept("bullet-into-enemy" + str(n), self.bullet_collision) base.accept("missile-into-enemy" + str(n), self.missile_collision) # sound self.snd_crash = base.loader.loadSfx("./snd/crash.flac") self.snd_blip = base.audio3d.loadSfx("./snd/blip.flac") self.snd_hit = base.loader.loadSfx("./snd/hit.flac") self.snd_explode = base.loader.loadSfx("./snd/explosion.flac") base.audio3d.attachSoundToObject(self.snd_blip, self.np) base.audio3d.setSoundVelocityAuto(self.snd_blip) base.audio3d.attachSoundToObject(self.snd_crash, self.np) base.audio3d.setSoundVelocityAuto(self.snd_crash) base.audio3d.attachSoundToObject(self.snd_hit, self.np) base.audio3d.setSoundVelocityAuto(self.snd_hit) base.audio3d.attachSoundToObject(self.snd_explode, self.np) base.audio3d.setSoundVelocityAuto(self.snd_explode) self.snd_blip.setLoop(True) self.snd_blip.play() self.setAI() def setAI(self): self.AIchar = AICharacter("enemy", self.np, 100, 10., 50) self.base.AIworld.addAiChar(self.AIchar) self.AIbehaviors = self.AIchar.getAiBehaviors() # self.AIbehaviors.wander(50, 0, 1000, 1.0) # self.AIbehaviors.seek(self.base.fighter) self.AIbehaviors.evade(self.base.fighter, 1000, 2000) # self.base.taskMgr.doMethodLater(1, self.call_status, "task-call-status") def call_status(self, task): status = self.AIbehaviors.behaviorStatus("evade") print("status: ", status) return task.again def explode(self): self.snd_blip.stop() self.base.audio3d.detachSound(self.snd_blip) self.base.audio3d.detachSound(self.snd_crash) self.base.audio3d.detachSound(self.snd_hit) self.radar.hide() self.np.hide() self.base.taskMgr.remove("fighter-into-enemy" + str(self.n)) self.base.taskMgr.remove("bullet-into-enemy" + str(self.n)) self.base.taskMgr.remove("missile-into-enemy" + str(self.n)) self.base.taskMgr.remove("enemy-hit-task") self.base.taskMgr.remove("enemy-crash-task") self.snd_explode.play() self.part = Explosion(self.base) self.part.pn.setPos(self.np.getPos()) self.base.taskMgr.doMethodLater(5, self.remove_part, "task-remove-part") def cleanup(self): self.base.audio3d.detachSound(self.snd_explode) self.base.AIworld.removeAiChar("enemy") self.base.target = None self.radar.destroy() self.np.removeNode() self.base.fuel += 500 self.base.gen_enemy() def ship_collision(self, entry): # degree of shaking depends on my speed/velocity (mvel) self.health -= 1 self.base.fuel -= 500 d = exp(0.047 * self.base.mvel - 7.) self.snd_crash.play() self.base.taskMgr.add(self.enemy_crash, "enemy-crash-task", extraArgs=[d], appendTask=True) def enemy_crash(self, d, task): if task.time < 5: f = (5. - task.time) / 5. s = 3000. * f x = uniform(-s, s) y = uniform(-s, s) self.base.repos(x, y, d) return task.cont return task.done def bullet_collision(self, entry): self.snd_hit.play() objNP = entry.getFromNodePath().findNetTag("bullet") objNP.removeNode() self.health -= 1 if self.health == 0: self.explode() else: self.base.taskMgr.add(self.enemy_hit, "enemy-hit-task") def missile_collision(self, entry): self.snd_hit.play() objNP = entry.getFromNodePath().findNetTag("missile") objNP.removeNode() self.explode() def enemy_hit(self, task): if task.time < 3: f = (3. - task.time) / 3. self.np.setColor(1, 1 - f, 0, 1) self.np.setAlphaScale(f) return task.cont return task.done def remove_part(self, task): self.part.pe.cleanup() self.cleanup() return task.done
class Jack(HUDElement): def __init__(self): HUDElement.__init__(self) self.dir = ani.model_dir / 'hud' / 'jack' self.text_scale = 0.4 self.text_color = (1, 1, 1, 1) self.arc = OnscreenImage(image=panda_path(self.dir / 'arc.png'), pos=(1.4, 0, -0.45), parent=aspect2d, scale=0.075) self.arc.setTransparency(TransparencyAttrib.MAlpha) self.cue_cartoon = OnscreenImage( image=panda_path(self.dir / 'cue.png'), parent=aspect2d, pos=(0, 0, 0), scale=(0.15, 1, 0.01), ) self.cue_cartoon.setTransparency(TransparencyAttrib.MAlpha) autils.alignTo(self.cue_cartoon, self.dummy_right, autils.CL, autils.C) self.cue_cartoon.setZ(-0.40) autils.alignTo(self.arc, self.cue_cartoon, autils.LR, autils.CR) self.rotational_point = OnscreenImage(image=panda_path( ani.model_dir / 'hud' / 'english' / 'circle.png'), parent=self.arc, scale=0.15) self.rotational_point.setTransparency(TransparencyAttrib.MAlpha) autils.alignTo(self.rotational_point, self.arc, autils.C, autils.LR) self.cue_cartoon.wrtReparentTo(self.rotational_point) self.text = OnscreenText( text="0 deg", pos=(-1, -1.4), scale=self.text_scale, fg=self.text_color, align=TextNode.ACenter, mayChange=True, parent=self.arc, ) def set(self, theta): self.text.setText(f"{theta:.1f} deg") self.rotational_point.setR(theta) def init(self): self.show() def show(self): self.arc.show() self.cue_cartoon.show() def hide(self): self.arc.hide() self.cue_cartoon.hide() def destroy(self): self.hide() del self.arc
def doPlayerTests(self): # Player's position plPos = self.playerObj.getPosition() px = plPos.getX() py = plPos.getY() pz = plPos.getZ() # Raycast directly down for terrain steepness rayYetiA = Point3(px, py, pz) rayYetiB = Point3(px, py, pz - 300) self.downRayTest = self.worldBullet.rayTestClosest( rayYetiA, rayYetiB).getHitNormal() rx = self.downRayTest.getX() ry = self.downRayTest.getY() rz = self.downRayTest.getZ() self.terrSteepness = 1.0 - rz # Redo collision flags later objCollisionFlag = False # Snow/Ice height adjust self.playerObj.updateTerrain() # Collision: Player x Objects for i in xrange(0, self.colObjectCount): if (self.colObj.didCollide(self.playerNP.node(), self.colObjects[i].AINode)): objCollisionFlag = True self.playerObj.setAirborneFlag(False) self.canAirDash = True self.playerObj.setFactor(1, 1, 1) # Collision: Player x Snowball if (self.ballObj.exists() and self.colObj.didCollide( self.playerNP.node(), self.ballObj.getRigidbody())): self.sbCollideFlag = True self.playerObj.setAirborneFlag(False) self.playerObj.setFactor(1, 1, 1) else: self.sbCollideFlag = False # Collision: Player x Terrain if (self.colObj.didCollide(self.playerNP.node(), self.heightMap)): if (self.playerObj.getAirborneFlag()): self.audioMgr.playSFX("snowCrunch01") self.playerObj.setAirborneFlag(False) self.canAirDash = True self.playerObj.setFactor(1, 1, 1) objCollisionFlag = False # Collision: Player x Death Zone # if(pz - 7 <= self.deathHeight or (self.colObj.didCollide(self.playerNP.node(), self.deathZone.node()))): if (self.colObj.didCollide(self.playerNP.node(), self.deathZone.node())): print("Player confirmed #REKT") self.playerObj.respawn() # Out of bounds checking if (abs(px) > 254 or abs(py) > 254): print("Player out of bounds!") self.playerObj.respawn() # Snap to terrain if... something. I need to restructure this. Don't read it. if (not (self.playerObj.getAirborneFlag()) and not (self.sbCollideFlag) and not (objCollisionFlag)): z = self.getTerrainHeight(Point3(px, py, pz)) self.playerObj.snapToTerrain(z) # self.playerObj.snapToTerrain(th, self.hmHeight) # Collision: Player x Snowflakes for i in xrange(0, self.snowflakeCount): if (self.snowflakes[i].exists() and self.colObj.didCollide( self.playerNP.node(), self.snowflakes[i].getNode())): self.snowflakes[i].destroy() self.snowflakeCounter.increment() self.snowCount += 1 self.snowMeter.updateSnow(self.playerObj) #Check if there is a "next" level. If there is, load it. Otherwise display end game screen. if (self.snowCount >= self.snowflakeCount): file_path = "../maps/map" + str(self.mapID + 1) + "/map" + str(self.mapID + 1) + ".yetimap" if os.path.lexists(file_path): self.snowCount = 0 self.snowflakeCount = 0 self.snowflakeCounter.setValue(0) self.snowflakeCounter.setState(2) #Loading Screen self.transition.fadeScreen(0.7) self.loadingText = OnscreenText("Loading...", 1, fg=(1, 1, 1, 0), pos=(0, 0), align=TextNode.ACenter, scale=.07, mayChange=1) base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() self.transition.noFade() #destroy objects self.worldBullet.removeRigidBody(self.heightMap) self.hmTerrainNP.removeNode() self.objNP.removeNode() self.treeNP.removeNode() self.rockNP.removeNode() self.rock2NP.removeNode() self.rock3NP.removeNode() # self.caveNP.removeNode() # self.planeFrontNP.removeNode() # self.planeWingNP.removeNode() self.hmNP.removeNode() if (int(self.mapID) == 1): self.ropeBridge.AIChar.setPos(-200, -300, -200) # self.ropeBridge.AIChar.removeNode() self.planeFront.AIChar.removeNode() self.planeTail.AIChar.setPos(-200, -200, -200) # self.planeTail.AIChar.removeNode() self.caveNew.AIChar.setPos(-1000, -1000, -1000) self.caveModel.AIChar.removeNode() #Added More Props here! self.boulder = SMCollide("../res/models/rock_3.egg", self.worldBullet, self.worldObj, Point3(117, 123, 17), 15, Vec3(0, 0, 0)) elif (int(self.mapID) == 2): self.boulder.AIChar.setPos(-222, -222, -222) self.caveNew.AIChar.setScale(150) self.caveNew.AIChar.setPos(-50, 95, -50) # self.skybox.setScale(600) # self.caveNew.setH(0) # self.boulder.removeNode() self.mapID += 1 print self.mapID # EX: maps/map-1/map-1.yetimap metaFile = open( "../maps/map" + str(self.mapID) + "/map" + str(self.mapID) + ".yetimap", 'r') metaLines = metaFile.readlines() lineCount = len(metaLines) self.snowflakeCount = lineCount - 2 # First Line: Player's starting position # EX: 50,50,50 (NO SPACES) playerLine = metaLines[0] playerPosList = playerLine.split(",") playerInitX = int(playerPosList[0]) playerInitY = int(playerPosList[1]) playerInitZ = int(playerPosList[2]) self.playerObj.playerNP.setPos(playerInitX, playerInitY, playerInitZ) self.playerObj.startX = playerInitX self.playerObj.startY = playerInitY self.playerObj.startZ = playerInitZ # 2nd Line: Deathzone Height # ONE INTEGER self.deathHeight = int(metaLines[1]) self.snowflakePositions = [] print("Snowflake Count: " + str(self.snowflakeCount)) for i in xrange(0, self.snowflakeCount): sfline = metaLines[i + 2] sfList = sfline.split(",") sfx = int(sfList[0]) sfy = int(sfList[1]) sfz = int(sfList[2]) self.snowflakePositions.append(Point3(sfx, sfy, sfz)) print("New snowflake to add: (" + str(sfx) + "," + str(sfy) + "," + str(sfz) + ")") self.snowflakeCounter.setMaxValue(self.snowflakeCount) #load new map self.mapName = str(self.mapID) self.heightMap = self.setupHeightmap(self.mapName) self.deathZone = self.setupDeathzone(self.deathHeight) self.loadingText.cleanup() else: taskMgr.remove('UpdateTask') self.endImage = OnscreenImage( image="../res/icons/endgame1.png", pos=(0.0, 0.0, 0.0), scale=(1.35, 2, 1))
class CarPlayerGui(CarGui): panel_cls = CarPanel def __init__(self, mediator, car_props, players): self.car_props = car_props self._players = players ncars = self.ncars CarGui.__init__(self, mediator) self.pars = CarParameters(mediator.phys, mediator.logic) self.panel = self.panel_cls(car_props, mediator.player_car_idx, ncars, players) self.ai_panel = CarAIPanel() way_txt_pos = (0, .1) if ncars == 1 else (0, .04) way_txt_scale = .1 if ncars == 1 else .06 way_img_pos = (0, 1, .3) if ncars == 1 else (0, 1, .16) way_img_scale = .12 if ncars == 1 else .06 self.way_txt = OnscreenText( '', pos=way_txt_pos, scale=way_txt_scale, fg=self.car_props.race_props.season_props.gameprops.menu_props. text_err_col, parent=self.parent, font=self.eng.font_mgr.load_font( self.car_props.race_props.season_props.font)) self.way_img = OnscreenImage('assets/images/gui/arrow_circle.txo', scale=way_img_scale, parent=self.parent, pos=way_img_pos) self.way_img.set_transparency(True) self.way_img.hide() @property def ncars(self): player_car_names = [ player.car for player in self._players if player.kind == Player.human ] return len(player_car_names) @property def parent(self): if self.ncars == 1: parent = base.a2dBottomCenter elif self.ncars == 2: if self.mediator.player_car_idx == 0: parent = base.a2dBottomQuarter else: parent = base.a2dBottomThirdQuarter elif self.ncars == 3: if self.mediator.player_car_idx == 0: parent = base.aspect2d elif self.mediator.player_car_idx == 1: parent = base.a2dBottomQuarter else: parent = base.a2dBottomThirdQuarter elif self.ncars == 4: if self.mediator.player_car_idx == 0: parent = base.a2dCenterQuarter elif self.mediator.player_car_idx == 1: parent = base.a2dCenterThirdQuarter elif self.mediator.player_car_idx == 2: parent = base.a2dBottomQuarter else: parent = base.a2dBottomThirdQuarter return parent def upd_ranking(self, ranking): r_i = ranking.index(self.mediator.name) + 1 self.panel.ranking_txt.setText(str(r_i) + "'") def upd_ai(self): self.ai_panel.update() def apply_damage(self, reset=False): self.panel.apply_damage(reset) def show_forward(self): self.panel.show_forward() def hide_forward(self): self.panel.hide_forward() def hide(self): CarGui.hide(self) self.pars.hide() self.panel.hide() self.ai_panel.hide() def on_wrong_way(self, way_str): if way_str: # self.panel.glass_b.show() self.way_txt.setText(way_str) self.way_img.show() elif not self.mediator.logic.is_moving or \ self.mediator.logic.fly_time > 10: # self.panel.glass_b.show() keys = self.car_props.race_props.keys.players_keys[ self.mediator.player_car_idx] txt = _('press %s to respawn') % \ self.eng.event.key2desc(keys.respawn) self.way_txt.setText(txt) self.way_img.hide() else: # self.panel.glass_b.hide() self.way_txt.setText('') self.way_img.hide() def destroy(self): list( map(lambda wdg: wdg.destroy(), [self.pars, self.panel, self.ai_panel])) self.way_txt.destroy() self.way_img.destroy() GuiColleague.destroy(self)
class CarPanel(GameObject): def __init__(self, car_props, player_idx, ncars, players): GameObject.__init__(self) self._players = players self.car_props = car_props self.player_idx = player_idx self.ncars = ncars sprops = self.car_props.race_props.season_props menu_props = sprops.gameprops.menu_props if ncars == 1: parent_tr = base.a2dTopRight elif ncars == 2: if self.player_idx == 0: parent_tr = base.a2dTopCenter else: parent_tr = base.a2dTopRight elif ncars == 3: if self.player_idx == 0: parent_tr = base.a2dTopRight elif self.player_idx == 1: parent_tr = base.aspect2d else: parent_tr = base.a2dRightCenter elif ncars == 4: if self.player_idx == 0: parent_tr = base.a2dTopCenter elif self.player_idx == 1: parent_tr = base.a2dTopRight elif self.player_idx == 2: parent_tr = base.aspect2d else: parent_tr = base.a2dRightCenter if ncars == 1: parent_tl = base.a2dTopLeft elif ncars == 2: if self.player_idx == 0: parent_tl = base.a2dTopLeft else: parent_tl = base.a2dTopCenter elif ncars == 3: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d elif ncars == 4: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dTopCenter elif self.player_idx == 2: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d if ncars == 1: parent_bl = base.a2dBottomLeft elif ncars == 2: if self.player_idx == 0: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter elif ncars == 3: if self.player_idx == 0: parent_bl = base.a2dLeftCenter elif self.player_idx == 1: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter elif ncars == 4: if self.player_idx == 0: parent_bl = base.a2dLeftCenter elif self.player_idx == 1: parent_bl = base.aspect2d elif self.player_idx == 2: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter # if ncars == 1: parent_t = base.a2dTopCenter # elif ncars == 2: # if self.player_idx == 0: parent_t = base.a2dTopQuarter # else: parent_t = base.a2dTopThirdQuarter # elif ncars == 3: # if self.player_idx == 0: parent_t = base.a2dTop # elif self.player_idx == 1: parent_t = base.a2dCenterQuarter # else: parent_t = base.a2dCenterThirdQuarter # elif ncars == 4: # if self.player_idx == 0: parent_t = base.a2dTopQuarter # elif self.player_idx == 1: parent_t = base.a2dTopThirdQuarter # elif self.player_idx == 2: parent_t = base.a2dCenterQuarter # else: parent_t = base.a2dCenterThirdQuarter # if ncars == 1: parent_b = base.a2dBottomCenter # elif ncars == 2: # if self.player_idx == 0: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter # elif ncars == 3: # if self.player_idx == 0: parent_b = base.aspect2d # elif self.player_idx == 1: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter # elif ncars == 4: # if self.player_idx == 0: parent_b = base.a2dCenterQuarter # elif self.player_idx == 1: parent_b = base.a2dCenterThirdQuarter # elif self.player_idx == 2: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter yellow_scale = .065 if ncars == 1 else .042 white_scale = .05 if ncars == 1 else .038 damages_img_scale = (.12, 1, .12) if ncars == 1 else (.08, 1, .08) self.__weap_scale = .12 if ncars == 1 else .08 txt_x = -.24 if ncars == 1 else -.18 lab_x = -.3 if ncars == 1 else -.24 offset_z = .1 if ncars == 1 else .08 top_z = -.1 damages_txt_pos = (.3, .1) if ncars == 1 else (.24, .06) damages_img_pos = (.46, 1, .12) if ncars == 1 else (.36, 1, .07) weapon_txt_pos = (.18, -.08) if ncars == 1 else (.14, -.08) self.__weapon_img_pos = (.18, 1, -.24) if ncars == 1 else \ (.14, 1, -.18) fwd_img_pos = (0, 1, -.2) if ncars == 1 else (0, 1, -.16) fwd_img_scale = .15 if ncars == 1 else .12 pars = { 'scale': yellow_scale, 'parent': parent_tr, 'fg': menu_props.text_active_col, 'align': TextNode.A_left, 'font': self.eng.font_mgr.load_font(sprops.font) } # self.glass_tl = OnscreenImage( # 'assets/images/gui/topleft.txo', # scale=(.23, 1, .24), parent=parent_tl, pos=(.22, 1, -.23)) # self.glass_tl.set_transparency(True) # self.glass_tr = OnscreenImage( # 'assets/images/gui/topright.txo', # scale=(.36, 1, .36), parent=parent_tr, pos=(-.35, 1, -.35)) # self.glass_tr.set_transparency(True) # self.glass_t = OnscreenImage( # 'assets/images/gui/top.txo', # scale=(.24, 1, .22), parent=parent_t, pos=(0, 1, -.21)) # self.glass_t.set_transparency(True) # self.glass_bl = OnscreenImage( # 'assets/images/gui/bottomleft.txo', # scale=(.36, 1, .16), parent=parent_bl, pos=(.35, 1, .15)) # self.glass_bl.set_transparency(True) # self.glass_br = OnscreenImage( # 'assets/images/gui/bottomright.txo', scale=(.26, 1, .26), # parent=base.a2dBottomRight, pos=(-.25, 1, .25)) # self.glass_br.set_transparency(True) # self.glass_b = OnscreenImage( # 'assets/images/gui/bottom.txo', # scale=(1.02, 1, .26), parent=parent_b, pos=(0, 1, .25)) # self.glass_b.set_transparency(True) # self.glass_tl.hide() # self.glass_t.hide() # self.glass_b.hide() self.speed_txt = OnscreenText(pos=(txt_x + .06, top_z), **pars) self.speed_txt['align'] = TextNode.A_center self.speed_c = Circle(size=.1, pos=(txt_x + .06, top_z), parent=parent_tr, ray=.4, thickness=.05, col_start=(.9, .6, .1, 1), col_end=(.2, .8, .2, 1)) lap_str = '1/' + str(self.car_props.race_props.laps) self.lap_txt = OnscreenText(text=lap_str, pos=(txt_x, top_z - offset_z), **pars) self.time_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 4), **pars) self.best_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 5), **pars) self.ranking_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 2), **pars) self.damages_img = OnscreenImage('assets/images/gui/car_icon.txo', scale=damages_img_scale, parent=parent_bl, pos=damages_img_pos) self.damages_img.set_transparency(True) self.damages_img.set_color_scale(menu_props.text_normal_col) self.damages_img.set_r(90) pars = { 'scale': white_scale, 'parent': pars['parent'], 'fg': menu_props.text_normal_col, 'align': TextNode.A_right, 'font': pars['font'] } self.speed_lab = OnscreenText(_('speed:'), pos=(lab_x, top_z), **pars) self.lap_lab = OnscreenText(text=_('lap:'), pos=(lab_x, top_z - offset_z), **pars) self.time_lab = OnscreenText(_('time:'), pos=(lab_x, top_z - offset_z * 4), **pars) self.best_lab = OnscreenText(_('best lap:'), pos=(lab_x, top_z - offset_z * 5), **pars) self.ranking_lab = OnscreenText(_('ranking:'), pos=(lab_x, top_z - offset_z * 2), **pars) self.damages_lab = OnscreenText(_('damages:'), pos=damages_txt_pos, **pars) self.damages_lab.reparent_to(parent_bl) self.weapon_lab = OnscreenText(_('weapon'), pos=weapon_txt_pos, scale=white_scale, parent=parent_tl, fg=menu_props.text_normal_col, font=self.eng.font_mgr.load_font( sprops.font)) self.weapon_img = None if ncars == 1: parent = base.a2dTopCenter elif ncars == 2: if player_idx == 0: parent = base.a2dTopQuarter else: parent = base.a2dTopThirdQuarter elif ncars == 3: if player_idx == 0: parent = base.a2dTopCenter elif player_idx == 0: parent = base.a2dCenterQuarter else: parent = base.a2dCenterThirdQuarter elif ncars == 4: if player_idx == 0: parent = base.a2dTopQuarter elif player_idx == 1: parent = base.a2dTopThirdQuarter elif player_idx == 2: parent = base.a2dCenterQuarter else: parent = base.a2dCenterThirdQuarter self.forward_img = OnscreenImage('assets/images/gui/direction.txo', scale=fwd_img_scale, parent=parent, pos=fwd_img_pos) self.forward_img.set_transparency(True) self.forward_img.hide() @staticmethod def __close_vec(vec1, vec2): return all(abs(b - a) < .01 for a, b in zip(vec1, vec2)) def enter_waiting(self): pass # if self.ncars == 1: parent = base.aspect2d # elif self.ncars == 2: # if self.player_idx == 0: parent = base.a2dCenterQuarter # else: parent = base.a2dCenterThirdQuarter # elif self.ncars == 3: # if self.player_idx == 0: parent = base.a2dQuarterCenter # elif self.player_idx == 1: parent = base.a2dThirdQuarterQuarter # else: parent = base.a2dThirdQuarterThirdQuarter # elif self.ncars == 4: # if self.player_idx == 0: parent = base.a2dQuarterQuarter # elif self.player_idx == 1: parent = base.a2dQuarterThirdQuarter # elif self.player_idx == 2: parent = base.a2dThirdQuarterQuarter # else: parent = base.a2dThirdQuarterThirdQuarter # menu_props = self.race_props.season_props.gameprops.menu_props # pars = {'scale': .065, 'parent': parent, # 'fg': menu_props.text_normal_col, # 'font': self.eng.font_mgr.load_font( # self.race_props.season_props.font)} def exit_waiting(self): pass def set_weapon(self, wpn): # self.glass_tl.show() self.weapon_lab.show() ncars = len([ player for player in self._players if player.kind == Player.human ]) if ncars == 1: parent_tl = base.a2dTopLeft elif ncars == 2: if self.player_idx == 0: parent_tl = base.a2dTopLeft else: parent_tl = base.a2dTopCenter elif ncars == 3: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d elif ncars == 4: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dTopCenter elif self.player_idx == 2: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d self.weapon_img = OnscreenImage('assets/images/weapons/%s.txo' % wpn, scale=self.__weap_scale, parent=parent_tl, pos=self.__weapon_img_pos) self.weapon_img.set_transparency(True) def unset_weapon(self): # self.glass_tl.hide() self.weapon_lab.hide() self.weapon_img.destroy() def show_forward(self): # self.glass_t.show() self.forward_img.show() def set_forward_angle(self, angle): curr_angle = self.forward_img.get_r() curr_incr = globalClock.getDt() * 30 if abs(curr_angle - angle) < curr_incr: tgt_val = angle else: sign = 1 if angle > curr_angle else -1 tgt_val = curr_angle + curr_incr * sign self.forward_img.set_r(tgt_val) def hide_forward(self): # self.glass_t.hide() self.forward_img.hide() def apply_damage(self, reset=False): col = self.car_props.race_props.season_props.gameprops.menu_props.text_normal_col if reset: self.damages_img.set_color_scale(col) else: yellow = (col[0], col[1] - .25, col[2] - .5, col[3]) if self.__close_vec(self.damages_img.get_color_scale(), col): self.damages_img.set_color_scale(yellow) elif self.__close_vec(self.damages_img.get_color_scale(), yellow): red = (col[0], col[1] - .5, col[2] - .5, col[3]) self.damages_img.set_color_scale(red) def hide(self): labels = [ self.speed_txt, self.speed_c, self.time_txt, self.lap_txt, self.best_txt, self.speed_lab, self.time_lab, self.lap_lab, self.best_lab, self.damages_img, self.damages_lab, self.ranking_txt, self.ranking_lab, self.weapon_lab, # self.glass_tl, self.glass_tr, self.glass_t, # self.glass_bl, self.glass_br, self.glass_b ] list(map(lambda wdg: wdg.hide(), labels)) if self.weapon_img and not self.weapon_img.is_empty(): self.weapon_img.hide() self.forward_img.hide() def destroy(self): labels = [ self.speed_txt, self.speed_c, self.time_txt, self.lap_txt, self.best_txt, self.speed_lab, self.time_lab, self.lap_lab, self.best_lab, self.damages_img, self.damages_lab, self.ranking_txt, self.ranking_lab, self.weapon_lab, # self.glass_tl, self.glass_tr, self.glass_t, # self.glass_bl, self.glass_br, self.glass_b ] list(map(lambda wdg: wdg.destroy(), labels)) if self.weapon_img and not self.weapon_img.is_empty(): self.weapon_img.destroy() self.forward_img.destroy()
def __init__(self, scenarioctrl): self.scctrl = scenarioctrl this_dir, this_filename = os.path.split(__file__) self.imageObject = OnscreenImage(image="./gui/banner250x1080.png", pos=(1.55, 0, 0), scale=(250 / 1080.0, 1, 1)) bcmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttoncapture_maps.egg")) maps = loader.loadModel(bcmappath) self.capturebtn = DirectButton( frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttoncapture_ready'), maps.find('**/buttoncapture_click'), maps.find('**/buttoncapture_rollover')), pos=(1.45, 0, .54), scale=(.06, .12, .12), command=self.captureFromTeacher) brmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttondelete_maps.egg")) maps = loader.loadModel(brmappath) self.runbtn = DirectButton( frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttondelete_ready'), maps.find('**/buttondelete_click'), maps.find('**/buttondelete_rollover')), pos=(1.575, 0, .54), scale=(.06, .12, .12), command=self.deleteCapture) brmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttonrecog_maps.egg")) maps = loader.loadModel(brmappath) self.runbtn = DirectButton(frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttonrecog_ready'), maps.find('**/buttonrecog_click'), maps.find('**/buttonrecog_rollover')), pos=(1.7, 0, .54), scale=(.06, .12, .12), command=self.recognize) brmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttonplan_maps.egg")) maps = loader.loadModel(brmappath) self.runbtn = DirectButton(frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttonplan_ready'), maps.find('**/buttonplan_click'), maps.find('**/buttonplan_rollover')), pos=(1.45, 0, .47), scale=(.06, .12, .12), command=self.execplan) brmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttonrun_maps.egg")) maps = loader.loadModel(brmappath) self.runbtn = DirectButton(frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttonrun_ready'), maps.find('**/buttonrun_click'), maps.find('**/buttonrun_rollover')), pos=(1.575, 0, .47), scale=(.06, .12, .12), command=self.execplan) brmappath = Filename.fromOsSpecific( os.path.join(this_dir, "gui", "buttonrestart_maps.egg")) maps = loader.loadModel(brmappath) self.runbtn = DirectButton( frameSize=(-1, 1, -.25, .25), geom=(maps.find('**/buttonrestart_ready'), maps.find('**/buttonrestart_click'), maps.find('**/buttonrestart_rollover')), pos=(1.7, 0, .47), scale=(.06, .12, .12), command=self.restart) self.nposes = 0 self.textNPose = OnscreenText(text='#Poses: ' + str(self.nposes), pos=(1.45, -.9, 0), scale=0.03, fg=(1., 1., 1., 1), align=TextNode.ALeft, mayChange=1) self.textCaptured = OnscreenText(text='Ready to capture', pos=(1.45, -.95, 0), scale=0.03, fg=(1., 1., 1., 1), align=TextNode.ALeft, mayChange=1)
def setMap(self, mapScale, x, y): map = OnscreenImage(image=self.miniMapImage, pos=(x, 0, y), scale=(mapScale, mapScale, mapScale)) return map
class miniMap(object): def __init__(self, mainActor): self.teamMateImage = 'models/teamMate.png' self.heroImage = 'models/mainHero.png' self.miniMapImage = 'models/miniMapImage.png' self.map = OnscreenImage(image=self.miniMapImage, pos=(-1, 0, 0.6), scale=(0.3, 0.3, 0.3)) self.map.setTransparency(1) self.hero = OnscreenImage(image=self.heroImage, pos=(mainActor.getX() / 200, 0, mainActor.getY() / 100), scale=(0.045, 0.045, 0.045), hpr=(0, 0, mainActor.getH())) self.hero.reparentTo(self.map) self.hero.setTransparency(1) self.npc = {} self.team = {} def setMap(self, mapScale, x, y): map = OnscreenImage(image=self.miniMapImage, pos=(x, 0, y), scale=(mapScale, mapScale, mapScale)) return map def setHero(self, heroScale, x, y, h): hero = OnscreenImage(image=self.heroImage, pos=(x, 0, y), scale=(heroScale, heroScale, heroScale), hpr=(0, 0, h)) return hero def setNpc(self, npcName, npcImage, npcScale, x, y): self.Nps = OnscreenImage(image=npcImage, pos=(x, 0, y), scale=(npcScale, npcScale, npcScale)) self.Nps.reparentTo(self.map) self.Nps.setTransparency(1) self.npc[npcName] = self.Nps return self.npc def delNpc(self, npcName): del self.npc[npcName] def setTeamMate(self, mateName, mateScale, getX, getY): ay = ((70 + (getY)) * 100) / 120 y = -1 + (ay * 2) / 100 ax = ((127 + (getX)) * 100) / 172 x = -1 + (ax * 2) / 100 self.teamMate = OnscreenImage(image=self.teamMateImage, pos=(x, 0, y), scale=(mateScale, mateScale, mateScale)) self.teamMate.reparentTo(self.map) self.teamMate.setTransparency(1) self.team[mateName] = self.teamMate return self.team def delTeamMate(self, mateName): del self.team[mateName] def updateHeroPos(self, getX, getY): ay = ((70 + (getY)) * 100) / 120 y = -1 + (ay * 2) / 100 ax = ((127 + (getX)) * 100) / 172 x = -1 + (ax * 2) / 100 self.hero.setPos(x, 0, y) def updateHeroHpr(self, getH): h = -getH self.hero.setHpr(0, 0, h) def updateTeamMatePos(self, mateName, getX, getY): ay = ((70 + (getY)) * 100) / 120 y = -1 + (ay * 2) / 100 ax = ((127 + (getX)) * 100) / 172 x = -1 + (ax * 2) / 100 self.team[mateName].setPos(x, 0, y) def updateTeamMateHpr(self, mateName, getH): h = -getH self.team[mateName].setHpr(0, 0, h) def changeTowerColor(self, npcName, toverImage): self.npc[npcName].setImage(toverImage)
def __init__(self): ShowBase.__init__(self) self.disableMouse() # Instrucciones en pantalla self.ralph_escape = addInstructions(.06, "[ESC]: Para Salir") self.ralph_run = addInstructions(.12, "[A]: Para Empezar Juego") # Variables globales para el control self.arrayGlobal = [] self.sonidoGlobal = -1 # Carga de imágenes self.Perro = OnscreenImage(image='src/images/Dog.png') self.Caballo = OnscreenImage(image='src/images/Horse.png') self.Leon = OnscreenImage(image='src/images/Lion.png') self.Gato = OnscreenImage(image='src/images/Cat.png') self.Elefante = OnscreenImage(image='src/images/Elephant.png') self.Oveja = OnscreenImage(image='src/images/Sheep.png') self.Correcto = OnscreenImage(image='src/images/correcto.png', pos=(100, 100, 100)) self.Incorrecto = OnscreenImage(image='src/images/incorrecto.png', pos=(100, 100, 100)) self.arrayRespuestas = [self.Correcto, self.Incorrecto] self.arrayImages = [ self.Perro, self.Caballo, self.Leon, self.Gato, self.Elefante, self.Oveja ] # Carga de audio self.audioElefante = loader.loadSfx("src/sounds/Dog.mp3") self.audioPerro = loader.loadSfx("src/sounds/Dog.mp3") self.audioCaballo = loader.loadSfx("src/sounds/Horse.mp3") self.audioLeon = loader.loadSfx("src/sounds/Lion.mp3") self.audioGato = loader.loadSfx("src/sounds/Cat.mp3") self.audioOveja = loader.loadSfx("src/sounds/Sheep.mp3") self.arrayAudios = [ self.audioPerro, self.audioCaballo, self.audioLeon, self.audioGato, self.audioElefante, self.audioOveja ] # Aprende a usar botones prro self.btn1 = DirectButton(text="1", scale=.1, command=self.verificaRespuesta, extraArgs=[0]) self.btn2 = DirectButton(text="2", scale=.1, command=self.verificaRespuesta, extraArgs=[1]) self.btn3 = DirectButton(text="3", scale=.1, command=self.verificaRespuesta, extraArgs=[2]) self.btn4 = DirectButton(text="4", scale=.1, command=self.verificaRespuesta, extraArgs=[3]) self.btn5 = DirectButton(text="5", scale=.1, command=self.verificaRespuesta, extraArgs=[4]) self.btn6 = DirectButton(text="6", scale=.1, command=self.verificaRespuesta, extraArgs=[5]) self.arrayBotones = [ self.btn1, self.btn2, self.btn3, self.btn4, self.btn5, self.btn6 ] # Primer evento para desaparecer all de pantalla self.limpiarPantalla(False) # Eventos con teclas self.accept("escape", sys.exit) self.accept("a", self.iniciaJuego)
class Player(object, DirectObject.DirectObject): #------------------------------------------------------------------------------------------------------ #Class constructor #------------------------------------------------------------------------------------------------------ def __init__(self): self.node = 0 #the player main node self.modelNode = 0 #the node of the actual model self.cNode = 0 #the player collision node attached to node self.cNodePath = 0 #node path to cNode self.contrail = ParticleEffect() #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB) self.contrail.setTransparency(TransparencyAttrib.MDual) self.contrail2 = ParticleEffect() #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB) self.contrail2.setTransparency(TransparencyAttrib.MDual) self.landing = False self.freeLook = False self.speed = 10 self.speedMax = 100 self.agility = 3 self.HP = 10 self.collisionHandler = CollisionHandlerEvent() # the collision handlers self.collisionHandlerQueue = CollisionHandlerQueue() self.zoom = -5 self.gnodePath = 0 #node to phisics self.gNode = 0 #node of gravity self.gNodePath = 0#node path to actorNode #self #add text speed #--------------------------------------------------------------------------------- #self.textSpeed = OnscreenText(text = 'Speed: '+str(self.speed), pos = (-1.34, 0.95), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft) #self.textHP = OnscreenText(text = 'Health: '+str(self.HP), pos = (-1.33, 0.85), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft) #--------------------------------------------------------------------------------- self.roll = 0 self.camHeight = 0 base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2) self.myImage=OnscreenImage(image = 'cursor.png', pos = (0, 0, -0.02), scale=(0.05)) self.myImage.setTransparency(TransparencyAttrib.MAlpha) self.loadModel() self.addCamera() self.addEvents() self.addCollisions() self.addSound() self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task') self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task') #------------------------------------------------------------------------------------------------------ #Function to load models and set physics #------------------------------------------------------------------------------------------------------ def loadModel(self): #node path for player self.node = NodePath('player') self.node.setPos(1000,1000,200) self.node.reparentTo(render) self.node.lookAt(0,0,200) self.modelNode = loader.loadModel('gaivota') self.modelNode.reparentTo(self.node) self.modelNode.setScale(0.3) playerMaterial = Material() playerMaterial.setShininess(22.0) #Make this material shiny playerMaterial.setAmbient(VBase4(1,1,1,1)) playerMaterial.setSpecular(VBase4(0.7,0.7,0.7,0.7)) self.modelNode.setMaterial(playerMaterial) self.modelNode.setShaderAuto() self.aimNode = NodePath('aimNode') self.aimNode.reparentTo(self.node) self.aimNode.setPos(0,15,2) #self.contrail.loadConfig('media/contrail.ptf') #self.contrail.start(self.node,render) ''' -------------------------------------------------------------------------------- #gravity (aceleration 9.82) self.gravityFN=ForceNode('world-forces') self.gravityFNP=render.attachNewNode(self.gravityFN) self.gravityForce=LinearVectorForce(0,0,-9.82) self.gravityFN.addForce(self.gravityForce) #add gravity to engine #base.physicsMgr.addLinerForce(self.gravityForce) #Physics node self.gnodePath = NodePath(PandaNode("physics")) self.gNode = ActorNode("plane-actornode") self.gNodePath = self.gnodePath.attachNewNode(self.gNode) #object weigth self.gNode.getPhysicsObject().setMass(0.004) #add gravity force base.physicsMgr.addLinearForce(self.gravityForce) base.physicsMgr.attachPhysicalNode(self.gNode) #render object with physics self.gnodePath.reparentTo(render) self.node.reparentTo(self.gNodePath) -------------------------------------------------------------------------------- ''' #------------------------------------------------------------------------------------------------------ #Function that add camera to airplane #------------------------------------------------------------------------------------------------------ def addCamera(self): base.disableMouse() base.camera.reparentTo(self.node) base.camera.setPos(0,self.zoom,2) base.camera.lookAt(self.aimNode) #------------------------------------------------------------------------------------------------------ #Functions for airplane events #------------------------------------------------------------------------------------------------------ def addEvents(self): self.accept( "wheel_up" , self.evtSpeedUp ) self.accept( "wheel_down" , self.evtSpeedDown ) self.accept('hit',self.evtHit) self.accept('f',self.evtFreeLookON) self.accept('f-up',self.evtFreeLookOFF) self.accept('mouse3',self.evtBoostOn) self.accept("menuOpen", self.evtMenuOpen) self.accept("menuClosed", self.evtMenuClose) #------------------------------------------------------------------------------------------------------ #Functions that add collisions for the airplane #------------------------------------------------------------------------------------------------------ def addCollisions(self): self.cNode = CollisionNode('player') self.cNode.addSolid(CollisionSphere(0,0,0,2.3)) self.cNode.setFromCollideMask(BitMask32(0x1A)) self.cNode.setIntoCollideMask(BitMask32(0x4)) self.cNodePath = self.node.attachNewNode(self.cNode) #self.cNodePath.show() self.collisionHandler.addInPattern('hit') base.cTrav.addCollider(self.cNodePath, self.collisionHandler) # landing segment: self.landingCNodeSegment = CollisionNode('playerRay') self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20)) self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff()) self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8)) self.landingCNodeSegmentPath = self.node.attachNewNode(self.landingCNodeSegment) #self.landingCNodeSegmentPath.show() base.cTrav.addCollider(self.landingCNodeSegmentPath, self.collisionHandlerQueue) #------------------------------------------------------------------------------------------------------ #Function to add sound to airplane #------------------------------------------------------------------------------------------------------ def addSound(self): self.engineSound = loader.loadSfx("engine.mp3") self.engineSound.setLoop(True) self.engineSound.play() self.engineSound.setVolume(2.0) self.engineSound.setPlayRate(0) #Add environment music #------------------------------------------------------------------------------- self.MusicSound = loader.loadSfx("warm-interlude.mp3") self.MusicSound.setLoop(True) self.MusicSound.play() self.MusicSound.setVolume(1.5) self.MusicSound.setPlayRate(0) #------------------------------------------------------------------------------------------------------ #Function to delete task #------------------------------------------------------------------------------------------------------ def deleteTask(self, task): self.__del__() return task.done #------------------------------------------------------------------------------------------------------ #Function that update mouse moviments #------------------------------------------------------------------------------------------------------ def mouseUpdateTask(self,task): md = base.win.getPointer(0) x = md.getX() y = md.getY() deltaX = 0 deltaY = 0 if base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2): deltaX = (x - base.win.getXSize()/2) *0.06 #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50) deltaY = (y - base.win.getYSize()/2)*0.06 if deltaX > self.agility: deltaX = self.agility if deltaX < -self.agility: deltaX = -self.agility if deltaY > self.agility: deltaY = self.agility if deltaY < -self.agility: deltaY = -self.agility # don't move ship while in freelook mode if not self.freeLook: self.node.setH(self.node.getH() - deltaX) self.node.setP(self.node.getP() - deltaY) # don't move ship while in freelook mode if not self.freeLook: self.roll += deltaX self.camHeight += deltaY self.roll *= 0.95 #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700 self.camHeight *= 0.95 #* globalClock.getDt() * 700 if self.roll < -25 * self.speed/self.speedMax: self.roll = -25 * self.speed/self.speedMax if self.roll > 25 * self.speed/self.speedMax: self.roll = 25 * self.speed/self.speedMax self.node.setR(self.roll*3) base.camera.setZ(2-self.camHeight*0.5* self.speed/self.speedMax) base.camera.lookAt(self.aimNode) base.camera.setR(-self.roll*2) #base.camera.setY(-30+self.speed/10) #base.camera.setX(self.roll*0.5) # freelook mode: if self.freeLook: self.camRotH -= deltaX *3 self.camRotV -= deltaY *3 if self.camRotV < 1: self.camRotV = 1 if self.camRotV > 179: self.camRotV = 179 base.camera.setX( math.cos(math.radians(self.camRotH))*math.sin(math.radians(self.camRotV)) *30 ) base.camera.setY( math.sin(math.radians(self.camRotH))*math.sin(math.radians(self.camRotV)) *30 ) base.camera.setZ( math.cos(math.radians(self.camRotV)) *30 ) base.camera.lookAt(self.node) return task.cont #------------------------------------------------------------------------------------------------------ #Function that update players position #------------------------------------------------------------------------------------------------------ def moveUpdateTask(self,task): # move where the keys set it self.node.setPos(self.node,Vec3(0,1.0*globalClock.getDt()*self.speed,0)) #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed) return task.cont #------------------------------------------------------------------------------------------------------ #Function that control the explosion of the airplane #------------------------------------------------------------------------------------------------------ def explode(self): self.ignoreAll() self.cNode.setIntoCollideMask(BitMask32.allOff()) taskMgr.remove(self.moveTask) taskMgr.remove(self.mouseTask) taskMgr.remove(self.zoomTaskPointer) self.moveTask = 0 self.mouseTask = 0 if self.contrail != 0: self.contrail.cleanup() self.modelNode.hide() self.contrail = ParticleEffect() self.contrail.loadConfig('media/explosion.ptf') self.contrail.start(self.node) self.contrail.setLightOff() self.contrail2.cleanup() #add explosion sound #------------------------------------------------------------------------------ self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], base.camera) self.audio3d.setDropOffFactor(0.2) self.Sound = self.audio3d.loadSfx('explosion.mp3') self.audio3d.detachSound(self.Sound) self.audio3d.attachSoundToObject( self.Sound, self.node ) self.Sound.play() #------------------------------------------------------------------------------ self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask, 'delete task') #------------------------------------------------------------------------------------------------------ #Function for zoom #------------------------------------------------------------------------------------------------------ def zoomTask(self, task): if base.camera.getY() != self.zoom and self.freeLook == False: base.camera.setY( base.camera.getY()+ (self.zoom- base.camera.getY())*globalClock.getDt()*2 ) return task.cont #------------------------------------------------------------------------------------------------------ #Function that increase speed #------------------------------------------------------------------------------------------------------ def evtBoostOn(self): #taskMgr.remove(self.mouseTask) self.ignore( "wheel_up") self.ignore( "wheel_down") self.ignore('f') self.ignore('f-up') self.accept('mouse3-up',self.evtBoostOff) self.speed +=200 #self.textSpeed.setText('Speed: '+str(self.speed)) self.contrail2.loadConfig('media/contrail-boost.ptf') self.contrail2.start(self.node) self.zoom = -25 self.evtFreeLookOFF() #------------------------------------------------------------------------------------------------------ #Function that decrease speed #------------------------------------------------------------------------------------------------------ def evtBoostOff(self): self.speed -=200 #self.textSpeed.setText('Speed: '+str(self.speed)) self.ignore('mouse3-up') self.addEvents() #self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') #self.contrail.loadConfig('../../media/contrail.ptf') self.contrail2.softStop() self.zoom = -5-(self.speed/10) #------------------------------------------------------------------------------------------------------ #Function that controls the event when the airplane hit something #------------------------------------------------------------------------------------------------------ def evtHit(self, entry): if entry.getIntoNodePath().getParent().getTag("orign") != self.node.getName(): #if entry.getIntoNodePath().getName() == "projectile": #self.HP -= 1 #self.textHP.setText('HP : '+str(self.HP)) if self.HP == 0: self.explode() else: self.explode() #------------------------------------------------------------------------------------------------------ #Function for freelook on #------------------------------------------------------------------------------------------------------ def evtFreeLookON(self): if self.landing == False: self.freeLook = True self.camRotH = 270 self.camRotV = 80 self.myImage.hide() #------------------------------------------------------------------------------------------------------ #Function for freelook off #------------------------------------------------------------------------------------------------------ def evtFreeLookOFF(self): if self.landing == False: self.freeLook = False base.camera.setPos(0,-20,2) base.camera.lookAt(self.aimNode) self.myImage.show() #------------------------------------------------------------------------------------------------------ #Function that delete features of the airplane #------------------------------------------------------------------------------------------------------ def __del__(self): self.ignoreAll() self.contrail.cleanup() #delete stop the sound #------------------------------------------------------------------------------- self.Sound.stop() self.audio3d.detachSound(self.Sound) self.engineSound.stop() self.MusicSound.stop() #------------------------------------------------------------------------------- base.camera.reparentTo(render) base.camera.setPos(2000,2000,800) base.camera.lookAt(0,0,0) if self.moveTask != 0: taskMgr.remove(self.moveTask) if self.mouseTask != 0: taskMgr.remove(self.mouseTask) self.node.removeNode() messenger.send( 'player-death' ) #------------------------------------------------------------------------------------------------------ #Function that conrol event that increse speed #------------------------------------------------------------------------------------------------------ def evtSpeedUp(self): if self.landing: return 0 self.speed += 5 self.engineSound.setPlayRate(self.engineSound.getPlayRate()+0.05) if self.speed > self.speedMax: self.speed = self.speedMax #self.engineSound.setVolume(1) self.engineSound.setPlayRate(1.5) self.zoom = -5-(self.speed/10) #speed text #self.textSpeed.setText('Speed: '+str(self.speed)) #------------------------------------------------------------------------------------------------------ #Function that control event that decrease speed #------------------------------------------------------------------------------------------------------ def evtSpeedDown(self): if self.landing: return 0 #speed text #self.textSpeed.setText('Speed: '+str(self.speed)) self.speed -= 5 self.engineSound.setPlayRate(self.engineSound.getPlayRate()-0.05) if self.speed < 0: self.speed = 0 #self.engineSound.setVolume(0) self.engineSound.setPlayRate(0.5) self.zoom = -5-(self.speed/10) #------------------------------------------------------------------------------------------------------ #Function that control open menu event(ESC) #------------------------------------------------------------------------------------------------------ def evtMenuOpen(self): taskMgr.remove(self.mouseTask) taskMgr.remove(self.moveTask) self.myImage.hide() props = WindowProperties() props.setCursorHidden(0) base.win.requestProperties(props) #disable physics when esc is pressed base.disableParticles() #control volume self.engineSound.stop() self.MusicSound.setVolume(0.5) #------------------------------------------------------------------------------------------------------ #Function that control close menu event(ESC) #------------------------------------------------------------------------------------------------------ def evtMenuClose(self): #self.addEvents() props = WindowProperties() props.setCursorHidden(1) base.win.requestProperties(props) self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task') self.myImage.show() #enable physics after menu closed base.enableParticles() #control volume self.engineSound.play() self.MusicSound.setVolume(1.5)
class Ground(ShowBase): def __init__(self): # Initialize the ShowBase class from which we inherit,which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.setBackgroundColor(240, 35, 35, 1) # Make a variable to store the unique collision string count self.collCount = 0 #set scale of ground self.scaleBy = 120 #disable mouse control of camera and manually place it base.disableMouse() camera.setPos(self.scaleBy // 2, self.scaleBy // 2, 2) #quit program when Escapse key pressed self.accept("escape", sys.exit) self.accept("a", self.runMiniGame) #set default settings of game self.setting = "forest" self.music = base.loader.loadSfx("music1.ogg") self.music.setVolume(.5) self.miniGameRun = False #initialization starting screen self.loadStartScreen() #display start screen w/ text and buttons def loadStartScreen(self): self.startBG = OnscreenImage(image='world.jpg', pos=(0, 0, 0), scale=3) self.title = OnscreenText(text="Onwards,Term Project", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, 0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.chooseGround = OnscreenText(text="Choose Land:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, 0.25), scale=.08, shadow=(0, 0, 0, 0.5)) self.buttonForest = DirectButton(pos=(-0.2, 0, 0.24), text="Forest", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["forest"], relief=SUNKEN) self.buttonDesert = DirectButton(pos=(0.4, 0, 0.24), text="Desert", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["desert"]) self.chooseMusic = OnscreenText(text="Choose Music:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, 0), scale=.08, shadow=(0, 0, 0, 0.5)) self.buttonMusic1 = DirectButton(pos=(-0.2, 0, -0.01), text="Piano 1", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["piano1"], relief=SUNKEN) self.buttonMusic2 = DirectButton(pos=(0.35, 0, -0.01), text="Piano 2", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["piano2"]) self.buttonMusic3 = DirectButton(pos=(0.8, 0, -0.01), text="None", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["stop"]) self.volume = OnscreenText(text="Volume:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, -0.3), scale=.08, shadow=(0, 0, 0, 0.5)) self.volumeSlider = DirectSlider(pos=(0.3, 0, -0.3), scale=0.7, value=.5, command=self.setMusicVolume) self.enterInstruction = OnscreenText(text="Press 'Enter' to Begin", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, -0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.accept("enter", self.loadModels) #change button reliefs if clicked or not & game settings based on button def selected(self, pressed): if pressed == "desert": self.setting = "desert" self.buttonForest['relief'] = RAISED self.buttonDesert['relief'] = SUNKEN elif pressed == "forest": self.setting = "forest" self.buttonForest['relief'] = SUNKEN self.buttonDesert['relief'] = RAISED if pressed == "piano1": self.music.stop() self.music = base.loader.loadSfx("music1.ogg") self.music.setLoop(True) self.music.play() self.buttonMusic1['relief'] = SUNKEN self.buttonMusic2['relief'] = RAISED self.buttonMusic3['relief'] = RAISED elif pressed == "piano2": self.music.stop() self.music = base.loader.loadSfx("music2.ogg") self.music.setLoop(True) self.music.play() self.buttonMusic1['relief'] = RAISED self.buttonMusic2['relief'] = SUNKEN self.buttonMusic3['relief'] = RAISED elif pressed == "stop": self.music.stop() self.buttonMusic1['relief'] = RAISED self.buttonMusic2['relief'] = RAISED self.buttonMusic3['relief'] = SUNKEN #change volume based on slider position def setMusicVolume(self): vol = self.volumeSlider.guiItem.getValue() self.music.setVolume(vol) #load models when 'enter' pressed def loadModels(self): self.startBG.destroy() self.title.destroy() self.chooseGround.destroy() self.buttonForest.destroy() self.buttonDesert.destroy() self.chooseMusic.destroy() self.buttonMusic1.destroy() self.buttonMusic2.destroy() self.buttonMusic3.destroy() self.enterInstruction.destroy() self.volumeSlider.destroy() self.volume.destroy() self.cTrav = CollisionTraverser() self.lastHitEntry = "is an entry" self.plants = [] self.plantColls = [] self.animals = [] self.animalColls = [] self.miniGameBoxes = [] self.axes = [] self.planters = [] self.haveAxe = False self.havePlanter = False self.selectedPlanterOpt = 0 self.planterOptionsForest = [("plants/foliage01.egg.pz", 11, 12), ("plants/foliage02.egg.pz", -12, 14), ("plants/foliage03.egg.pz", 14, 23), ("plants/foliage04.egg.pz", 0, 0), ("plants/foliage05.egg.pz", 6, 22), ("plants/foliage09.egg.pz", -3, 10), ("chicken.egg", 0, 0)] self.planterOptionsDesert = [("plants/shrubbery.egg.pz", 1, 14), ("plants/cactus1.egg", 0, 12), ("plants/cactus2.egg", 2.5, 11), ("chicken.egg", 0, 0)] #display instructions self.loadText() #respond when arrow keys are pressed self.accept("arrow_up", self.eventArrowPressed, ["up"]) self.accept("arrow_up-repeat", self.eventArrowPressed, ["up"]) self.accept("arrow_right", self.eventArrowPressed, ["right"]) self.accept("arrow_right-repeat", self.eventArrowPressed, ["right"]) self.accept("arrow_left", self.eventArrowPressed, ["left"]) self.accept("arrow_left-repeat", self.eventArrowPressed, ["left"]) self.accept("arrow_down", self.eventArrowPressed, ["down"]) self.accept("arrow_down-repeat", self.eventArrowPressed, ["down"]) self.accept("f", self.eventAerielView) self.accept("0", self.restartGame) self.accept("enter", self.doNothing) groundTexture = loader.loadTexture(self.setting + ".jpg") #load starting square of land land = loader.loadModel("box") land.setPos(0, 0, 0) land.setSy(self.scaleBy) land.setSx(self.scaleBy) land.setSz(0.5) land.setTexture(groundTexture, 1) self.spanGround = [(0, 0)] self.ground = land self.ground.reparentTo(render) #load main char self.mainChar = loader.loadModel("box") self.mainChar.reparentTo(camera) self.mainChar.setPos(0, 10, -2) self.mainChar.setColorScale(0.6, 0.6, 1.0, 1.0) self.moveMainCharX = 0.5 self.moveMainCharY = 0.75 #load main char's collision ray onto screen & make char a collider self.mainCharGroundRay = CollisionRay() self.mainCharGroundRay.setOrigin(0.5, 0, 30) self.mainCharGroundRay.setDirection(0, 0, -1) self.mainCharGroundCol = CollisionNode('mainCharRay') self.mainCharGroundCol.addSolid(self.mainCharGroundRay) self.mainCharGroundCol.setFromCollideMask(CollideMask.bit(0)) self.mainCharGroundCol.setIntoCollideMask(CollideMask.allOff()) self.mainCharGroundColNp = self.mainChar.attachNewNode(\ self.mainCharGroundCol) self.mainCharGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.mainCharGroundColNp,\ self.mainCharGroundHandler) #load camera's collision ray & make it a collider self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 30) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) #shows collision nodes (for debugging) # self.mainCharGroundColNp.show() # self.camGroundColNp.show() self.curPos = self.mainChar.getPos() self.cameraCurPos = camera.getPos() # shows collisions occuring (for debugging) # self.cTrav.showCollisions(render) #continuously check for collisions taskMgr.add(self.checkCollisions, "checkCollisionsTask") #initialize fog so that scene in distance is blocked from view color = (240, 35, 35) expfog = Fog("Scene-wide exponential Fog object") expfog.setColor(*color) expfog.setExpDensity(0.006) render.setFog(expfog) base.setBackgroundColor(color) #display instructions on screen top & title on botton def loadText(self): self.bottomTitle = \ OnscreenText(text="Onwards,Term Project", parent=base.a2dBottomRight,align=TextNode.ARight, fg=(1,1,1,1),pos=(-0.1,0.1),scale=.08, shadow=(0,0,0,0.5)) self.startInstructions = \ OnscreenText(text="Press Arrow Keys to explore. Press and hold 'f' "+ "to activate Aeriel View. Press Esc to exit."+ "\nPress '0' to go to Start Screen", parent=base.a2dTopLeft,align=TextNode.ALeft, pos=(0.05,-0.08),fg=(1,1,1,1),scale=.06, shadow=(0,0,0,0.5)) #set what happens when arrow keys pressed def eventArrowPressed(self, dir): self.curPos = self.mainChar.getPos() self.cameraCurPos = camera.getPos() x, y, z = base.camera.getPos() if dir == "up": camera.setPos(x, y + self.moveMainCharY, z) elif dir == "down": camera.setPos(x, y - self.moveMainCharY, z) elif dir == "right": camera.setPos(x + self.moveMainCharX, y, z) elif dir == "left": camera.setPos(x - self.moveMainCharX, y, z) self.checkExtend(dir) #set what happens when x pressed & axe activated def eventAxe(self): deleted = False if len(self.plantColls) > 0: for i in range(len(self.plantColls)): if (self.lastHitEntry in self.plantColls[i][0].getName()): self.plantColls[i][0].remove_node() self.plants[i].remove_node() self.plantColls = self.plantColls[:i] + self.plantColls[i + 1:] self.plants = self.plants[:i] + self.plants[i + 1:] deleted = True break if len(self.animalColls) > 0 and deleted == False: for i in range(len(self.animalColls)): if (self.lastHitEntry in self.animalColls[i][0].getName()): self.animalColls[i][0].remove_node() self.animals[i][0].remove_node() self.animalColls = self.animalColls[:i]+\ self.animalColls[i+1:] self.animals = self.animals[:i] + self.animals[i + 1:] deleted = True break if len(self.miniGameBoxes) > 0 and deleted == False: for i in range(len(self.miniGameBoxes)): if (self.lastHitEntry in self.miniGameBoxes[i][1][0].getName()): self.miniGameBoxes[i][1][0].remove_node() self.miniGameBoxes[i][0].remove_node() self.miniGameBoxes = self.miniGameBoxes[:i]+\ self.miniGameBoxes[i+1:] deleted = True self.acceptMiniGame() break #set what happens when w pressed & planter activated def eventPlanter(self): #create new object and position it in front of main character x, y, z = camera.getPos() if self.setting == "forest": plantType,shiftX,shiftY = \ self.planterOptionsForest[self.selectedPlanterOpt] else: plantType,shiftX,shiftY = \ self.planterOptionsDesert[self.selectedPlanterOpt] if plantType == "chicken.egg": self.newAnimal() else: plant = loader.loadModel(plantType) plant.setScale(0.2) plant.setPos(x + shiftX, y + shiftY, 0) plant.reparentTo(render) if plantType == "plants/cactus1.egg": plant.setTexture(loader.loadTexture("cactusskin.png"), 1) plant.setScale(1) plantColl = self.initCollisionSphere(plant, 0.1, False) elif plantType == "plants/cactus2.egg": plant.setScale(1) plant.setZ(0.5) plantColl = self.initCollisionSphere(plant, 0.8, False) elif plantType == "plants/shrubbery.egg.pz": plant.setScale(0.15) plantColl = self.initCollisionSphere(plant, 0.2, False) else: plantColl = self.initCollisionSphere(plant, 0.08, False) self.plants += [plant] self.plantColls += [plantColl] #shift camera upwards to show aeriel view def eventAerielView(self): self.x, self.y, self.z = camera.getPos() shiftPos = camera.posInterval(0.1,\ Point3(self.x,self.y + 30,self.z + 150)) shiftAngle = camera.hprInterval(0.2, Vec3(0, -90, 0)) aerielView = Sequence(shiftPos, shiftAngle) aerielView.start() self.moveMainCharX = 2 self.moveMainCharY = 3 self.accept("f-up", self.eventNormalView) #shift camera back to normal view def eventNormalView(self): shiftPos = camera.posInterval(0.1, Point3(self.x, self.y, self.z)) shiftAngle = camera.hprInterval(0.2, Vec3(0, 0, 0)) aerielView = Sequence(shiftPos, shiftAngle) aerielView.start() self.moveMainCharX = 0.5 self.moveMainCharY = 0.75 #check whether or not to extend ground def checkExtend(self, dir): x, y, z = base.camera.getPos() checkV = (0, 0) whole = self.scaleBy #Up checkX = x // self.scaleBy checkY = (y + whole) // self.scaleBy cUp = (checkX, checkY) if cUp not in self.spanGround: self.spanGround += [cUp] self.extendScene() #Down checkX = x // self.scaleBy checkY = (y - whole) // self.scaleBy cDown = (checkX, checkY) if cDown not in self.spanGround: self.spanGround += [cDown] self.extendScene() #Right checkX = (x + whole) // self.scaleBy checkY = y // self.scaleBy cRight = (checkX, checkY) if cRight not in self.spanGround: self.spanGround += [cRight] self.extendScene() #Left checkX = (x - whole) // self.scaleBy checkY = y // self.scaleBy cLeft = (checkX, checkY) if cLeft not in self.spanGround: self.spanGround += [cLeft] self.extendScene() #Upper Right Diagonal checkX = (x + whole) // self.scaleBy checkY = (y + whole) // self.scaleBy cUpRight = (checkX, checkY) if cUpRight not in self.spanGround: self.spanGround += [cUpRight] self.extendScene() #Upper Left Diagonal checkX = (x - whole) // self.scaleBy checkY = (y + whole) // self.scaleBy cUpLeft = (checkX, checkY) if cUpLeft not in self.spanGround: self.spanGround += [cUpLeft] self.extendScene() #Lower Right Diagonal checkX = (x + whole) // self.scaleBy checkY = (y - whole) // self.scaleBy cUpRight = (checkX, checkY) if cUpRight not in self.spanGround: self.spanGround += [cUpRight] self.extendScene() #Lower Left Diagonal checkX = (x - whole) // self.scaleBy checkY = (y - whole) // self.scaleBy cUpLeft = (checkX, checkY) if cUpLeft not in self.spanGround: self.spanGround += [cUpLeft] self.extendScene() #extend ground def extendScene(self): #add square of ground groundTexture = loader.loadTexture(self.setting + ".jpg") new = loader.loadModel("box") new.setSy(self.scaleBy) new.setSx(self.scaleBy) new.setSz(0.5) new.setTexture(groundTexture, 1) newPos = self.spanGround[-1] newPosX = newPos[0] * self.scaleBy newPosY = newPos[1] * self.scaleBy new.setPos(newPosX, newPosY, 0) self.newground = new self.newground.reparentTo(render) #load axe if haven't collided with one yet if not self.haveAxe: axe = loader.loadModel("axe") axe.setColor(0, 0, 0, 1.0) axe.setScale(0.5, 1, 0.5) axe.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0.3) axe.reparentTo(render) axeObject = loader.loadModel("axe01") axeObject.setScale(3) axeObject.setPos(0.5, 0, 2) axeObject.setHpr(0, 65, 35) axeObject.reparentTo(axe) axeColl = self.initCollisionSphere(axe, 1, False) self.axes += [axe] #load planter if haven't collided with one yet if not self.havePlanter: planter = loader.loadModel("planter") planter.setColor(0, 0, 1, 1) planter.setScale(1, 1, 1) planter.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0.3) planter.reparentTo(render) planterBag = loader.loadModel("planter01") planterBag.setScale(1.5) planterBag.setHpr(0, 30, 0) planterBag.setPos(0.75, 0, 1.25) planterBag.reparentTo(planter) planterColl = self.initCollisionSphere(planter, 1, False) self.planters += [planter] #load random number of mini game boxes for i in range(randint(1, 4)): miniGameBox = loader.loadModel("box") miniGameBox.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0.5) miniGameBox.reparentTo(render) miniGameBoxColl = self.initCollisionSphere(miniGameBox, 1.3, False) self.miniGameBoxes += [[miniGameBox, miniGameBoxColl]] #load certain plants in forest setting if self.setting == "forest": for i in range(randint(3, 15)): #place plant 1 plant1 = loader.loadModel("plants/foliage01.egg.pz") plant1.setScale(0.2) plant1.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant1.reparentTo(render) plantColl = self.initCollisionSphere(plant1, 0.08, False) self.plants += [plant1] self.plantColls += [plantColl] for i in range(randint(3, 15)): #place plant2 plant2 = loader.loadModel("plants/foliage02.egg.pz") plant2.setScale(0.2) plant2.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant2.reparentTo(render) plantColl = self.initCollisionSphere(plant2, 0.06, False) self.plants += [plant2] self.plantColls += [plantColl] for i in range(randint(3, 15)): #place plant3 plant3 = loader.loadModel("plants/foliage03.egg.pz") plant3.setScale(0.8) plant3.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant3.reparentTo(render) plantColl = self.initCollisionSphere(plant3, 0.06, False) self.plants += [plant3] self.plantColls += [plantColl] for i in range(randint(3, 15)): #place plant4 plant4 = loader.loadModel("plants/foliage04.egg.pz") plant4.setScale(0.6) plant4.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant4.reparentTo(render) plantColl = self.initCollisionSphere(plant4, 0.07, False) self.plants += [plant4] self.plantColls += [plantColl] for i in range(randint(3, 15)): #place plant5 plant5 = loader.loadModel("plants/foliage05.egg.pz") plant5.setScale(0.6) plant5.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant5.reparentTo(render) plantColl = self.initCollisionSphere(plant5, 0.05, False) self.plants += [plant5] self.plantColls += [plantColl] for i in range(randint(3, 15)): #place plant6 plant6 = loader.loadModel("plants/foliage09.egg.pz") plant6.setScale(0.6) plant6.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant6.reparentTo(render) plantColl = self.initCollisionSphere(plant6, 0.08, False) self.plants += [plant6] self.plantColls += [plantColl] #load walking animals if newPos[0] % 4 == 0 and newPos[1] % 3 == 0: animal = loader.loadModel("box") animal.setScale(1) animal.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), -0.75) animal.reparentTo(render) animalColl = self.initCollisionSphere(animal, 0.75, False) chicken = loader.loadModel("chicken") chicken.setScale(0.15) chicken.setPos(0.5, 0.5, 1.25) chicken.setHpr(0, 0, 0) chicken.reparentTo(animal) self.animalColls += [animalColl] animalGroundHandler = CollisionHandlerQueue() self.animals += [[animal, randint(0, 4), animalGroundHandler]] self.cTrav.addCollider(animalColl[0], animalGroundHandler) #load certain plants in desert setting elif self.setting == "desert": for i in range(randint(0, 6)): #place shrubbery plant0 = loader.loadModel("plants/shrubbery.egg.pz") plant0.setScale(0.1) plant0.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant0.reparentTo(render) plantColl = self.initCollisionSphere(plant0, 0.3, False) self.plants += [plant0] self.plantColls += [plantColl] for i in range(randint(0, 6)): #place cactus1 plant1 = loader.loadModel("plants/cactus1.egg") plant1.setScale(1) plant1.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0) plant1.setTexture(loader.loadTexture("cactusskin.png"), 1) plant1.reparentTo(render) plantColl = self.initCollisionSphere(plant1, 0.1, False) self.plants += [plant1] self.plantColls += [plantColl] for i in range(randint(0, 6)): #place cactus2 plant2 = loader.loadModel("plants/cactus2.egg") plant2.setScale(1) plant2.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), 0.5) plant2.reparentTo(render) plantColl = self.initCollisionSphere(plant2, 0.8, False) self.plants += [plant2] self.plantColls += [plantColl] #load walking animals if newPos[0] % 4 == 0 and newPos[1] % 3 == 0: animal = loader.loadModel("box") animal.setScale(1) animal.setPos(randint(newPosX, newPosX + self.scaleBy), randint(newPosY, newPosY + self.scaleBy), -0.75) animal.reparentTo(render) animalColl = self.initCollisionSphere(animal, 0.75, False) chicken = loader.loadModel("chicken") chicken.setScale(0.15) chicken.setPos(0.5, 0.5, 1.25) chicken.setHpr(0, 0, 0) chicken.reparentTo(animal) self.animalColls += [animalColl] animalGroundHandler = CollisionHandlerQueue() self.animals += [[animal, randint(0, 4), animalGroundHandler]] self.cTrav.addCollider(animalColl[0], animalGroundHandler) #load animal in front of main char def newAnimal(self): #load and initialize box for chicken to be rendered to x, y, z = self.cameraCurPos animal = loader.loadModel("box") animal.setScale(1) animal.setPos(x + 1, y + 15, -0.75) animal.reparentTo(render) animalColl = self.initCollisionSphere(animal, 0.75, False) #load chicken chicken = loader.loadModel("chicken") chicken.setScale(0.15) chicken.setPos(0.5, 0.5, 1.25) chicken.setHpr(0, 0, 0) chicken.reparentTo(animal) #store animal into self.animalColls += [animalColl] animalGroundHandler = CollisionHandlerQueue() self.animals += [[animal, 0, animalGroundHandler]] self.cTrav.addCollider(animalColl[0], animalGroundHandler) taskMgr.add(self.moveAnimal, "moveAnimalsTask") taskMgr.add(self.checkAnimalCollisions, "checkAnimalCollisionsTask") #move every animal in self.animals forward def moveAnimal(self, task): for animal in self.animals: x, y, z = animal[0].getPos() if animal[1] == 0: animal[0].setPos(x, y + 0.025, z) animal[0].setHpr(180, 0, 0) elif animal[1] == 2: animal[0].setPos(x + 0.025, y, z) animal[0].setHpr(90, 0, 0) elif animal[1] == 1: animal[0].setPos(x, y - 0.025, z) animal[0].setHpr(0, 0, 0) elif animal[1] == 3: animal[0].setPos(x - 0.025, y, z) animal[0].setHpr(270, 0, 0) return Task.cont #check if animal collided with surroundings def checkAnimalCollisions(self, task): #check collisions of each automatically moving animals for animal in self.animals: entries = list(animal[2].getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) if len(entries) > 0: x, y, z = animal[0].getPos() if animal[1] == 0: animal[0].setPos(x, y - 0.03, z) elif animal[1] == 2: animal[0].setPos(x - 0.03, y, z) elif animal[1] == 1: animal[0].setPos(x, y + 0.03, z) elif animal[1] == 3: animal[0].setPos(x + 0.03, y, z) animal[1] = (animal[1] + 1) % 4 return Task.cont #check if main character collided with surroundings def checkCollisions(self, task): #check collisions for mainChar entries = list(self.mainCharGroundHandler.getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) #if bump into tree,go back to last position so char doesn't go in tree if (len(entries) > 0 and ("axe" not in entries[0].getIntoNode().getName()) and ("planter" not in entries[0].getIntoNode().getName())): camera.setPos(self.cameraCurPos) #show what was last hit item if self.haveAxe: #unhighlight last entry unhighlighted = True if unhighlighted: for i in range(len(self.plantColls)): if (self.lastHitEntry in \ self.plantColls[i][0].getName()): self.plants[i].setColorScale(1, 1, 1, 1.0) unhighlighted = False break if unhighlighted: for i in range(len(self.animalColls)): if (self.lastHitEntry in \ self.animalColls[i][0].getName()): self.animals[i][0].setColorScale(1, 1, 1, 1.0) unhighlighted = False break if unhighlighted: for i in range(len(self.miniGameBoxes)): if(self.lastHitEntry in \ self.miniGameBoxes[i][1][0].getName()): self.miniGameBoxes[i][0].setColorScale( 1, 1, 1, 1.0) unhighlighted = False break #find last entry & highlight it if len(entries) > 0: self.lastHitEntry = entries[0].getIntoNode().getName() highlighted = True if highlighted: for i in range(len(self.plantColls)): if (self.lastHitEntry in \ self.plantColls[i][0].getName()): self.plants[i].setColorScale( 0.6, 0.6, 1.0, 1.0) highlighted = False break if highlighted: for i in range(len(self.animalColls)): if (self.lastHitEntry in \ self.animalColls[i][0].getName()): self.animals[i][0].setColorScale(0.6,\ 0.6,1.0,1.0) highlighted = False break if highlighted: for i in range(len(self.miniGameBoxes)): if(self.lastHitEntry in \ self.miniGameBoxes[i][1][0].getName()): self.miniGameBoxes[i][0].setColorScale(0.6,\ 0.6,1.0,1.0) highlighted = False break #if bump into axe,activate axe & delete it elif len(entries) > 0 and ("axe" in entries[0].getIntoNode().getName()): self.haveAxe = True for obj in self.axes: obj.remove_node() #if bump into planter,activate planter & delete it elif (len(entries) > 0 and ("planter" in entries[0].getIntoNode().getName())): self.havePlanter = True for obj in self.planters: obj.remove_node() #change onscreen text & add keyboard events if hit axe and/or planter if self.havePlanter: self.accept('w', self.eventPlanter) self.planterInstructions = OnscreenText( text="Press 'w' to plant." + "Press 'q' or 'e' to change plant", parent=base.a2dTopLeft, align=TextNode.ALeft, pos=(0.05, -0.28), fg=(1, 1, 1, 1), scale=.06, shadow=(0, 0, 0, 0.5)) self.accept('e', self.changeSelectedPlanterOpt, ["e"]) self.accept('q', self.changeSelectedPlanterOpt, ["q"]) if self.haveAxe: self.accept('x', self.eventAxe) self.axeInstructions = OnscreenText(text="Press 'x' to cut plant.", parent=base.a2dTopLeft, align=TextNode.ALeft, pos=(0.05, -0.20), fg=(1, 1, 1, 1), scale=.06, shadow=(0, 0, 0, 0.5)) return Task.cont #change selecter planter opt so that it stays w/in list def changeSelectedPlanterOpt(self, direction): #in forest,modify selectedPlantOpt if it goes out of range if self.setting == "forest": if direction == "e": self.selectedPlanterOpt += 1 if self.selectedPlanterOpt >= len(self.planterOptionsForest): self.selectedPlanterOpt -= len(self.planterOptionsForest) else: self.selectedPlanterOpt -= 1 if self.selectedPlanterOpt <= -1 * len( self.planterOptionsForest): self.selectedPlanterOpt += len(self.planterOptionsForest) #in desert,modify selectedPlantOpt if it goes out of range else: if direction == "e": self.selectedPlanterOpt += 1 if self.selectedPlanterOpt >= len(self.planterOptionsDesert): self.selectedPlanterOpt -= len(self.planterOptionsDesert) else: self.selectedPlanterOpt -= 1 if self.selectedPlanterOpt <= -1 * len( self.planterOptionsDesert): self.selectedPlanterOpt += len(self.planterOptionsDesert) #source: https://www.panda3d.org/manual/index.php/Event_Example #initialize collision sphere around object def initCollisionSphere(self, obj, circR, show=False): # Get the size of the object for the collision sphere. bounds = obj.getChild(0).getBounds() radius = bounds.getRadius() * circR center = bounds.getCenter() #make center of collision circle be on ground around tree trunks center[2] = 0 if obj.getName() == "foliage01.egg.pz": pass elif obj.getName() == "foliage02.egg.pz": center[0] -= 4 elif obj.getName() == "foliage03.egg.pz": center[0] -= 3.5 elif obj.getName() == "foliage04.egg.pz": center[0] += 11 center[1] -= 1 elif obj.getName() == "foliage05.egg.pz": center[0] += 1.5 center[1] -= 4 elif obj.getName() == "foliage09.egg.pz": center[0] -= 2.5 center[1] -= 2 # Create a collision sphere and name it something understandable. collSphereStr = 'CollisionHull' + str( self.collCount) + "_" + obj.getName() self.collCount += 1 cNode = CollisionNode(collSphereStr) cNode.addSolid(CollisionSphere(center, radius)) cNodepath = obj.attachNewNode(cNode) if show: cNodepath.show() # Return a tuple with the collision node and its corrsponding string so # that the bitmask can be set. return (cNodepath, collSphereStr) #remove functionality from keyboard key def doNothing(self): pass #ask player if they want to continue to minigame screen def acceptMiniGame(self): self.question = OnscreenText(text="Do you want to play a minigame?", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, 0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.buttonNo = DirectButton(pos=(-0.2, 0, 0.24), text="No", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.miniSelected, extraArgs=["no"], relief=SUNKEN) self.buttonYes = DirectButton(pos=(0.2, 0, 0.24), text="Yes", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.miniSelected, extraArgs=["yes"], relief=RAISED) self.enterInstruction = OnscreenText(text="Press 'enter' to continue", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, -0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.accept("enter", self.executeMiniButtons) #change values of button when pressed def miniSelected(self, pressed): if pressed == "yes": self.miniGameRun = True self.buttonNo['relief'] = RAISED self.buttonYes['relief'] = SUNKEN elif pressed == "no": self.miniGameRun = False self.buttonNo['relief'] = SUNKEN self.buttonYes['relief'] = RAISED #control whether to run mini game or continue normal game def executeMiniButtons(self): self.question.destroy() self.buttonNo.destroy() self.buttonYes.destroy() self.enterInstruction.destroy() if self.miniGameRun: self.runMiniGame() #run minigame if magic box is collected def runMiniGame(self): #remove game functionality from keys while minigame is being played self.accept("a", self.doNothing) self.accept("f", self.doNothing) self.accept("w", self.doNothing) self.accept("e", self.doNothing) self.accept("q", self.doNothing) self.accept("enter", self.doNothing) #temporarily stop checking collisions on main game level taskMgr.remove('checkCollisionsTask') #temporarily add task taskMgr.add(self.miniGameCheckCollisions, 'miniGameCheckCollisionsTask') #temporary mini game controls self.accept("arrow_up", self.eventUpMini) self.accept("arrow_up-repeat", self.eventUpMini) self.accept("arrow_right", self.eventRightMini) self.accept("arrow_right-repeat", self.eventRightMini) self.accept("arrow_left", self.eventLeftMini) self.accept("arrow_left-repeat", self.eventLeftMini) self.accept("arrow_down", self.eventDownMini) self.accept("arrow_down-repeat", self.eventDownMini) self.accept("x", self.eventAxe) self.miniGameRun = False #shift camera down to minigame level self.x, self.y, self.z = camera.getPos() shiftPos = camera.posInterval( 0.1, Point3(self.scaleBy // 2, self.scaleBy // 2, -148)) miniGameView = Sequence(shiftPos) miniGameView.start() #game objects (object,x,y,scale) self.miniGameModles = [("plants/foliage01.egg.pz", 11, 12, 1), ("plants/foliage02.egg.pz", -12, 14, 1), ("plants/shrubbery.egg.pz", 1, 14, 1), ("plants/cactus1.egg", 0, 0, 1), ("plants/cactus2.egg", 2.5, 11, 1), ("chicken.egg", 0, 0, 0.15)] #create minigame ground land = loader.loadModel("box") land.setPos(0, 0, -150) land.setSy(self.scaleBy) land.setSx(self.scaleBy) land.setSz(0.5) land.reparentTo(render) self.instructionsChicken = OnscreenText(text="Find chicken to return!", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, 0.5), scale=.08, shadow=(0, 0, 0, 0.5)) #load and initialize box for chicken to be rendered to x, y, z = self.cameraCurPos animal = loader.loadModel("box") animal.setScale(1) animal.setPos(randint(1, 118), randint(10, 106), -150.75) animal.reparentTo(render) animalColl = self.initCollisionSphere(animal, 0.75, False) #load chicken chicken = loader.loadModel("chicken") chicken.setScale(0.15) chicken.setPos(0.5, 0.5, 1.25) chicken.setHpr(0, 0, 0) chicken.reparentTo(animal) #store animal into self.animalColls += [animalColl] animalGroundHandler = CollisionHandlerQueue() self.animals += [[animal, 0, animalGroundHandler]] self.cTrav.addCollider(animalColl[0], animalGroundHandler) #when game is done,change setting back to original def miniGameDone(self): self.instructionsChicken.destroy() #delete new chicken self.animalColls[-1][0].remove_node() self.animals[-1][0].remove_node() self.animalColls = self.animalColls[:-1] self.animals = self.animals[:-1] #back to original game controls self.accept("arrow_up", self.eventArrowPressed, ["up"]) self.accept("arrow_up-repeat", self.eventArrowPressed, ["up"]) self.accept("arrow_right", self.eventArrowPressed, ["right"]) self.accept("arrow_right-repeat", self.eventArrowPressed, ["right"]) self.accept("arrow_left", self.eventArrowPressed, ["left"]) self.accept("arrow_left-repeat", self.eventArrowPressed, ["left"]) self.accept("arrow_down", self.eventArrowPressed, ["down"]) self.accept("arrow_down-repeat", self.eventArrowPressed, ["down"]) self.accept("f", self.eventAerielView) self.accept("w", self.eventPlanter) self.accept("e", self.changeSelectedPlanterOpt, ["e"]) self.accept("q", self.changeSelectedPlanterOpt, ["e"]) if not self.haveAxe: self.accept('x', self.doNothing) #redo taskMgr taskMgr.add(self.checkCollisions, 'checkCollisionsTask') taskMgr.remove('miniGameCheckCollisionsTask') #go back to normal view shiftPos = camera.posInterval(0.1, Point3(self.x, self.y, self.z)) normalGameView = Sequence(shiftPos) normalGameView.start() #check if main character collided with chicken def miniGameCheckCollisions(self, task): #check collisions for mainChar entries = list(self.mainCharGroundHandler.getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) #if bump into chicken,go back to normal gam if (len(entries) > 0): self.miniGameDone() return Task.cont #set what happens when up arrow pressed def eventUpMini(self): self.curPosMini = self.mainChar.getPos() self.cameraCurPosMini = camera.getPos() x, y, z = base.camera.getPos() if y + self.moveMainCharX < 107: camera.setPos(x, y + self.moveMainCharY, z) #set what happens when down arrow pressed def eventDownMini(self): self.curPosMini = self.mainChar.getPos() self.cameraCurPosMini = camera.getPos() x, y, z = base.camera.getPos() if y - self.moveMainCharX > -9: camera.setPos(x, y - self.moveMainCharY, z) #set what happens when right arrow pressed def eventRightMini(self): self.curPosMini = self.mainChar.getPos() self.cameraCurPosMini = camera.getPos() x, y, z = base.camera.getPos() if x + self.moveMainCharX < 119: camera.setPos(x + self.moveMainCharX, y, z) #set what happens when left arrow pressed def eventLeftMini(self): self.curPosMini = self.mainChar.getPos() self.cameraCurPosMini = camera.getPos() x, y, z = base.camera.getPos() if x - self.moveMainCharX > 0: camera.setPos(x - self.moveMainCharY, y, z) #reload game def restartGame(self): self.loadStartScreen()
class Pregame(): def __init__(self, showbase): self.showbase = showbase self.ready = False self.showbase.num_warlocks = 1 self.showbase.which = 0 # this will have its own chat i guess, just game server only (no channels or anything just the one chat, all to all) # also i guess all the players data (usernames, maybe others) will need to be collected here from the server for the chat/scoreboard/whatever # and whenever a new person joins/leaves an update will be sent to all the clients (like with the all chat i guess) # these will need to be created in here from data passed from the server (where it will be procedurally generated) # once it receives a 'preround' state change it should create all the required shit (warlocks per person and the Game() class and whatnot) # then client will switch to preround state # spell0 spell0 = Spell() spell0.damage = 10 spell0.target_knockback = 20 spell0.self_knockback = 0 spell0.range = 25 spell0.speed = 15 spell0.aoe = False spell0.aoe_range = 0 spell0.targeting = False spell0.casting_time = 0 spell0.interruptable = False spell0.model = "media/spells/blockyball" # spell1 spell1 = Spell() spell1.damage = 25 spell1.target_knockback = 10 spell1.self_knockback = 0 spell1.range = 50 spell1.speed = 25 spell1.aoe = False spell1.aoe_range = 0 spell1.targeting = False spell1.casting_time = 0 spell1.interruptable = False spell1.model = "media/spells/pointyball" # spell2 spell2 = Spell() spell2.damage = 50 spell2.target_knockback = 10 spell2.self_knockback = 30 spell2.range = 50 spell2.speed = 15 spell2.aoe = False spell2.aoe_range = 0 spell2.targeting = False spell2.casting_time = 0 spell2.interruptable = False spell2.model = "media/spells/blockyball" # spell3 spell3 = Spell() spell3.model = "media/spells/pointyball" showbase.spells = [] showbase.spells.append(spell0) showbase.spells.append(spell1) showbase.spells.append(spell2) showbase.spells.append(spell3) self.background = OnscreenImage(image='media/gui/lobby/lobby.png', parent=render2d) # Send Message Button self.send_button = DirectButton( command=self.send_message, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, .3), scale=.1, text="Send", ) # Text box for message entry self.entry = DirectEntry( focusInCommand=self.clearText, frameSize=(-3, 3, -.5, 1), initialText="Chat:", parent=self.send_button, pos=(0, 0, -1.5), text="", text_align=TextNode.ACenter, ) # button to tell server client is ready self.ready_button = DirectButton( command=self.toggle_ready, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, -.3), scale=.1, text="Ready?", ) # button to tell server client is not ready self.unready_button = DirectButton( command=self.toggle_unready, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, -.3), scale=.1, text="Unready?", ) # hide unready button until ready self.unready_button.hide() # button to quit game self.quit_button = DirectButton( command=showbase.quit, frameSize=(-4, -1, 0, 0), #-3, 3, -.5, 1), pos=(-1.0, 0.0, -1.0), scale=.1, text="QUIT!", ) # Add the game loop procedure to the task manager. taskMgr.doMethodLater(1.0, self.update_lobby, 'Update Lobby') def update_lobby(self, task): temp = self.showbase.client.getData() if temp != []: for i in range(len(temp)): valid_packet = False package = temp[i] if len(package) == 2: print "Received: " + str(package) # if username is sent, assign to client if package[0] == 'chat': print "Chat: " + package[1] valid_packet = True # updates warlocks in game elif package[0] == 'warlocks': print "warlocks: " + str(package[1]) self.showbase.num_warlocks = package[1] valid_packet = True elif package[0] == 'which': print "i am warlock: " + str(package[1]) self.showbase.which = package[1] valid_packet = True # changes to game state (i guess this could be done the same as the gamestate ones, all but this change state packet, which will be same elif package[0] == 'state': print "state: " + package[1] if package[1] == 'game': self.showbase.begin_preround() return task.done valid_packet = True if not valid_packet: data = {} data[0] = "error" data[1] = "Fail Server" self.showbase.client.sendData(data) print "Bad packet from server" else: print "Packet wrong size" return task.again def toggle_ready(self): self.ready = True data = {} data[0] = "ready" data[1] = "ready" self.ready_button.hide() self.unready_button.show() self.showbase.client.sendData(data) def toggle_unready(self): self.unready = True data = {} data[0] = "unready" data[1] = "unready" self.unready_button.hide() self.ready_button.show() self.showbase.client.sendData(data) def send_message(self): data = {} data[0] = "chat" data[1] = self.entry.get() self.entry.enterText('') self.showbase.client.sendData(data) def clearText(self): self.entry.enterText('') def hide(self): self.background.hide() self.send_button.hide() self.entry.hide() self.ready_button.hide() self.unready_button.hide() self.quit_button.hide()
class Engine(ShowBase): def __init__(self, mouse): ShowBase.__init__(self) self.mouse = mouse self.joy_x = None self.joy_y = None props = WindowProperties() props.setMouseMode(WindowProperties.MRelative) # keep mouse in screen self.disableMouse() self.win.requestProperties(props) self.setBackgroundColor(0, 0, 0) # Make missiles glow self.filters = CommonFilters(self.win, self.cam) self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="large") self.screen_width = self.win.getXSize() self.screen_height = self.win.getYSize() self.center_x = self.screen_width/2 self.center_y = self.screen_height/2 # self.win.movePointer(0, self.center_x, self.center_y) self.enableParticles() self.cTrav = CollisionTraverser() # self.cTrav.setRespectPrevTransform(True) self.pusher = PhysicsCollisionHandler() self.pusher.addInPattern('%fn-into-%in') self.target = None self.maxvel = 50 self.roll_time = 0 self.fuel = 1000 self.ship() self.sounds() self.hud() self.part = Spacedust(self) self.events() self.camLens.setFov(70) self.camLens.setNear(1) self.camLens.setFar(500) self.get_key = { "ACCEL": False, "DECEL": False, "FORWARD_THRUST": False, "REVERSE_THRUST": False, "ROLL_LEFT": False, "ROLL_RIGHT": False, "ROLL_LEFT_BEG": False, "ROLL_RIGHT_BEG": False, "FIRE": False, "FIRING": False, "LOCK": False, "LOCKING": False, } self.AIworld = AIWorld(self.render) self.taskMgr.add(self.update, "task-update") self.taskMgr.doMethodLater(1, self.fuel_usage, "task-fuel-usage") self.taskMgr.add(self.AI_update, "AI-update") self.gen_enemy() def gen_enemy(self): x = randint(-1000, 1000) y = randint(-1000, 1000) z = randint(-1000, 1000) Enemy(self, 0, x, y, z) def AI_update(self, task): self.AIworld.update() return task.cont def hud(self): self.font = self.loader.loadFont("./fnt/subatomic.tsoonami.ttf") self.aim = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.02) self.aim.setTransparency(TransparencyAttrib.MAlpha) self.locker = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.12) self.locker.setTransparency(TransparencyAttrib.MAlpha) self.locker.hide() self.txtFuel = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.8), text='FUEL', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True) self.txtSpeed = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.7), text='SPEED', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True) self.txtDist = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.6), text='DIST', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True) self.txtCoord = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.5), text='COORD', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True) self.taskMgr.doMethodLater(1, self.instruments, "task-instruments") def instruments(self, task): self.txtSpeed.setText("SPEED: %s" % str(int(self.mvel))) self.txtFuel.setText("FUEL: %s" % str(self.fuel)) if self.target is not None: self.txtDist.setText("DISTANCE: %s" % str(round(self.dist, 1))) else: self.txtDist.setText("DISTANCE: ---") self.txtCoord.setText("COORD: %s %s %s" % (str(round(self.fighter.getX(), 1)), str(round(self.fighter.getY(), 1)), str(round(self.fighter.getZ(), 1)))) return task.again def set_key(self, key, value): self.get_key[key] = value def toggle_key(self, key): self.set_key(key, not self.get_key[key]) def init_roll(self, a, task): if task.time <= 2: if self.roll_time <= task.time: self.roll_time = task.time else: self.roll_time += task.time if self.roll_time > 2: self.roll_time = 2 self.fighter.setR(self.fighter.getR() + a * self.roll_time) else: self.fighter.setR(self.fighter.getR() + a * 2) return task.cont def end_roll(self, a, b, task): if task.time < b: self.roll_time -= task.time if self.roll_time < 0: self.roll_time = 0 self.fighter.setR(self.fighter.getR() + a * (b - task.time)) return task.cont else: return task.done def roll(self, a): if a > 0: self.set_key("ROLL_RIGHT_BEG", True) else: self.set_key("ROLL_LEFT_BEG", True) self.taskMgr.add(self.init_roll, "task-init-roll", extraArgs=[a], appendTask=True) def unroll(self, a): if a > 0: self.set_key("ROLL_RIGHT_BEG", False) else: self.set_key("ROLL_LEFT_BEG", False) self.taskMgr.remove("task-init-roll") self.taskMgr.add(self.end_roll, "task-end-roll", extraArgs=[a, self.roll_time], appendTask=True) def to_roll(self): if self.get_key["ROLL_LEFT"]: if not self.get_key["ROLL_LEFT_BEG"]: if self.fuel > 5: self.roll(-1) self.snd_roller.play() else: if self.get_key["ROLL_LEFT_BEG"]: self.unroll(-1) self.snd_roller.stop() if self.get_key["ROLL_RIGHT"]: if not self.get_key["ROLL_RIGHT_BEG"]: if self.fuel > 5: self.roll(+1) self.snd_roller.play() else: if self.get_key["ROLL_RIGHT_BEG"]: self.unroll(+1) self.snd_roller.stop() def fuel_usage(self, task): if self.get_key["FORWARD_THRUST"] or self.get_key["REVERSE_THRUST"]: self.fuel -= 9 if self.get_key["ROLL_LEFT_BEG"] or self.get_key["ROLL_RIGHT_BEG"]: self.fuel -= 4 self.fuel -= 1 if self.fuel < 0: self.fuel = 0 return task.again def chk_speed(self, mvel): if mvel < 0.01: # stop fighter dead if self.prt.getActive(): self.set_key("DECEL", False) mvel = 0 if mvel > self.maxvel: # stop fighter accelerating if self.pft.getActive(): self.set_key("ACCEL", False) mvel = self.maxvel self.part.p.renderer.setLineScaleFactor(mvel*2) self.part.pn.setPos(self.fighter, 0, 10, 0) return mvel def thrust_shake(self, task): x = uniform(-1000, 1000) y = uniform(-1000, 1000) self.repos(x, y, 0.001) return task.cont def thrust_end(self, task): if task.time < 5: f = (5. - task.time) / 5. s = 1000.*f x = uniform(-s, s) y = uniform(-s, s) self.repos(x, y, 0.001) self.snd_thrust.setVolume(f) return task.cont self.snd_thrust.stop() return task.done def thrust(self, a): if a > 0: self.set_key("FORWARD_THRUST", True) else: self.set_key("REVERSE_THRUST", True) self.taskMgr.remove("task-thrust-end") self.snd_thrust.setVolume(1) self.snd_thrust.play() self.taskMgr.add(self.thrust_shake, "task-thrust-shake") def unthrust(self, a): if a > 0: self.set_key("FORWARD_THRUST", False) else: self.set_key("REVERSE_THRUST", False) self.taskMgr.remove("task-thrust-shake") self.taskMgr.add(self.thrust_end, "task-thrust-end") def to_thrust(self): if self.get_key["ACCEL"]: if self.mvel < self.maxvel - 1: if not self.get_key["FORWARD_THRUST"]: if self.fuel > 10: self.pft.setActive(True) self.thrust(+1) else: if self.get_key["FORWARD_THRUST"]: self.pft.setActive(False) self.unthrust(+1) if self.get_key["DECEL"]: if self.mvel > 0: if not self.get_key["REVERSE_THRUST"]: if self.fuel > 10: self.prt.setActive(True) self.thrust(-1) else: if self.get_key["REVERSE_THRUST"]: self.prt.setActive(False) self.unthrust(-1) def events(self): self.accept("escape", self.quit) self.accept('mouse1', self.set_key, ["FIRE", True]) self.accept('mouse1-up', self.set_key, ["FIRE", False]) self.accept('mouse3', self.set_key, ["LOCK", True]) self.accept('mouse3-up', self.set_key, ["LOCK", False]) self.accept("w", self.set_key, ["ACCEL", True]) self.accept("w-up", self.set_key, ["ACCEL", False]) self.accept("s", self.set_key, ["DECEL", True]) self.accept("s-up", self.set_key, ["DECEL", False]) self.accept("a", self.set_key, ["ROLL_LEFT", True]) self.accept("a-up", self.set_key, ["ROLL_LEFT", False]) self.accept("d", self.set_key, ["ROLL_RIGHT", True]) self.accept("d-up", self.set_key, ["ROLL_RIGHT", False]) def update(self, task): self.pos() self.speed() if self.fuel > 0: self.to_roll() self.to_thrust() self.to_fire() self.to_lock() self.rehud() return task.cont def rehud(self): if self.target is not None: c = self.target.np.getPos(self.fighter) self.dist = c.length() c.normalize() self.d2 = c - Vec3(0, 1, 0)*c.dot(Vec3(0, 1, 0)) self.target.radar.setPos(self.d2.getX(), 1, self.d2.getZ()) def sounds(self): self.audio3d = Audio3DManager.Audio3DManager(self.sfxManagerList[0], self.camera) self.audio3d.setListenerVelocityAuto() self.snd_space = self.loader.loadSfx("./snd/space.flac") self.snd_space.setLoop(True) self.snd_thrust = self.loader.loadSfx("./snd/thrust.flac") self.snd_thrust.setLoop(True) self.snd_roller = self.loader.loadSfx("./snd/roller.flac") self.snd_roller.setLoop(True) self.snd_launch = self.loader.loadSfx("./snd/launch.flac") self.snd_lock = self.loader.loadSfx("./snd/lock.flac") self.snd_space.play() def quit(self): self.taskMgr.running = False def repos(self, x, y, d): player_q = self.fighter.getQuat() up = player_q.getUp() right = player_q.getRight() up.normalize() right.normalize() up_q = copy(player_q) right_q = copy(player_q) up_q.setFromAxisAngle(-(x * d), up) right_q.setFromAxisAngle(y * d, right) self.fighter.setQuat(player_q.multiply(up_q.multiply(right_q))) def move_end(self, x, y, task): if task.time <= 1: d = 0.002*(1 - task.time) self.repos(x, y, d) return task.cont return task.done def pos(self): if self.mouse: md = self.win.getPointer(0) x = md.getX() y = md.getY() else: x = self.joy_x y = self.joy_y if self.win.movePointer(0, self.center_x, self.center_y): x -= self.center_x y -= self.center_y if x != 0 or y != 0: self.taskMgr.add(self.move_end, 'task-move-end', extraArgs=[x, y], appendTask=True) def speed(self): fwd = self.fighter.getQuat().getForward() fwd.normalize() self.mvel = self.anpo.getVelocity().length() # speed control self.mvel = self.chk_speed(self.mvel) self.anpo.setVelocity(fwd * self.mvel) def ship(self): an = ActorNode() an.getPhysicsObject().setMass(100) self.fighter = self.render.attachNewNode(an) self.physicsMgr.attachPhysicalNode(an) self.anpo = an.getPhysicsObject() fn = ForceNode("force-node-fighter") self.fighter.attachNewNode(fn) self.pft = LinearVectorForce(Vec3(0, +1, 0) * 500) # forward thrust self.prt = LinearVectorForce(Vec3(0, -1, 0) * 500) # reverse thrust self.pft.setMassDependent(1) self.prt.setMassDependent(1) self.pft.setActive(False) self.prt.setActive(False) fn.addForce(self.pft) fn.addForce(self.prt) an.getPhysical(0).addLinearForce(self.pft) an.getPhysical(0).addLinearForce(self.prt) self.camera.reparentTo(self.fighter) from_obj = self.fighter.attachNewNode(CollisionNode('fighter')) from_obj.node().setFromCollideMask(BitMask32(0x1)) from_obj.setCollideMask(BitMask32(0x1)) from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1)) # from_obj.show() self.pusher.addCollider(from_obj, self.fighter) self.cTrav.addCollider(from_obj, self.pusher) def launch_bullet(self): speed = 500. scale = Vec3(0.05) color = Vec4(0, 1, 0, 1) mask = BitMask32(0x2) lookat = Vec3(0, 100, 0) Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(-0.5, 0, 0), self.fighter, lookat, 0.5) Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(+0.5, 0, 0), self.fighter, lookat, 0.5) self.snd_launch.play() def to_fire(self): if self.get_key["FIRE"]: if not self.get_key["FIRING"]: self.set_key("FIRING", True) self.taskMgr.doMethodLater(0.16, self.fire_bullet, "task-fire-bullet") else: if self.get_key["FIRING"]: self.set_key("FIRING", False) self.taskMgr.remove("task-fire-bullet") def fire_bullet(self, task): if self.fuel >= 5: self.fuel -= 5 self.launch_bullet() return task.again def launch_missile(self): speed = 100 scale = Vec3(0.2) color = Vec4(1, 0, 0, 1) mask = BitMask32(0x2) lookat = Vec3(0, 0, 0) self.missile = Missile(self, "missile", speed, scale, color, mask, self.fighter, Vec3(0, 0, -2), self.target.np, lookat, 3) self.snd_launch.play() self.taskMgr.add(self.guide_missile, "task-guide-missile") def guide_missile(self, task): try: quat = Quat() lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up()) self.missile.anp.setQuat(quat) fwd = quat.getForward() fwd.normalize() mvel = self.missile.anpo.getVelocity().length() self.missile.anpo.setVelocity(fwd*mvel) except: return task.done return task.cont def can_lock(self): if self.dist >= 30 and self.dist <= 300 and abs(self.d2.getX()) <= 0.1 and abs(self.d2.getZ()) <= 0.1: return True else: return False def remove_lock(self): if self.get_key["LOCKING"]: self.set_key("LOCKING", False) self.locker.hide() self.snd_lock.stop() self.taskMgr.remove("task-fire-missile") def to_lock(self): if self.get_key["LOCK"]: if self.can_lock(): if self.fuel >= 100: if not self.get_key["LOCKING"]: self.set_key("LOCKING", True) self.locker.setScale(0.12) self.locker.setColor(1, 0, 0, 0.5) self.locker.show() self.snd_lock.play() self.taskMgr.add(self.fire_missile, "task-fire-missile") else: self.remove_lock() else: self.remove_lock() else: self.remove_lock() def fire_missile(self, task): if self.fuel >= 100: if task.time < 3.6: e = (3.6 - task.time)/3.6 f = 0.02 + e*0.1 self.locker.setScale(f) self.locker.setColor(e, 1-e, 0, 0.5) return task.cont else: self.fuel -= 100 self.launch_missile() return task.done
def setHero(self, heroScale, x, y, h): hero = OnscreenImage(image=self.heroImage, pos=(x, 0, y), scale=(heroScale, heroScale, heroScale), hpr=(0, 0, h)) return hero
class Sprite(RPObject): """ Simple wrapper arround OnscreenImage, providing a simpler interface """ def __init__(self, image=None, parent=None, x=0, y=0, w=None, h=None, transparent=True, near_filter=True, any_filter=True): """ Creates a new image, taking (x,y) as topleft coordinates. When near_filter is set to true, a near filter will be set to the texture passed. This provides sharper images. When any_filter is set to false, the passed image won't be modified at all. This enables you to display existing textures, otherwise the texture would get a near filter in the 3D View, too. """ RPObject.__init__(self) if not isinstance(image, Texture): if not isinstance(image, str): self.warn("Invalid argument to image parameter:", image) return image = RPLoader.load_texture(image) if w is None or h is None: w, h = image.get_x_size(), image.get_y_size() else: if w is None or h is None: w = 10 h = 10 self._width, self._height = w, h self._initial_pos = self._translate_pos(x, y) self.node = OnscreenImage( image=image, parent=parent, pos=self._initial_pos, scale=(self._width / 2.0, 1, self._height / 2.0)) if transparent: self.node.set_transparency(TransparencyAttrib.M_alpha) tex = self.node.get_texture() # Apply a near filter, but only if the parent has no scale, otherwise # it will look weird if near_filter and any_filter and parent.get_sx() == 1.0: tex.set_minfilter(SamplerState.FT_nearest) tex.set_magfilter(SamplerState.FT_nearest) if any_filter: tex.set_anisotropic_degree(8) tex.set_wrap_u(SamplerState.WM_clamp) tex.set_wrap_v(SamplerState.WM_clamp) def get_initial_pos(self): """ Returns the initial position of the image. This can be used for animations """ return self._initial_pos def pos_interval(self, *args, **kwargs): """ Returns a pos interval, this is a wrapper around NodePath.posInterval """ return self.node.posInterval(*args, **kwargs) def hpr_interval(self, *args, **kwargs): """ Returns a hpr interval, this is a wrapper around NodePath.hprInterval """ return self.node.hprInterval(*args, **kwargs) def color_scale_interval(self, *args, **kwargs): """ Returns a color scale interval, this is a wrapper around NodePath.colorScaleInterval """ return self.node.colorScaleInterval(*args, **kwargs) def set_image(self, img): """ Sets the current image """ self.node.set_image(img) def get_width(self): """ Returns the width of the image in pixels """ return self._width def get_height(self): """ Returns the height of the image in pixels """ return self._height def set_pos(self, x, y): """ Sets the position """ self.node.set_pos(self._translate_pos(x, y)) def _translate_pos(self, x, y): """ Converts 2d coordinates to pandas coordinate system """ return Vec3(x + self._width / 2.0, 1, -y - self._height / 2.0) def set_shader(self, shader): """ Sets a shader to be used for rendering the image """ self.node.set_shader(shader) def set_shader_input(self, *args): """ Sets a shader input on the image """ self.node.set_shader_input(*args) def set_shader_inputs(self, **kwargs): """ Sets multiple shader inputs on the image """ self.node.set_shader_inputs(**kwargs) def remove(self): """ Removes the image """ self.node.remove_node() def hide(self): """ Hides the image """ self.node.hide() def show(self): """ Shows the image if it was previously hidden """ self.node.show() def is_hidden(self): """ Returns whether the image is hidden """ return self.node.is_hidden()
class Cursor: def __init__(self, path, scale, hotspot): if not path: return self.__set_standard_curson(False) self.cursor_img = OnscreenImage(path) self.cursor_img.setTransparency(True) self.cursor_img.setScale(scale) self.cursor_img.setBin('gui-popup', 50) self.hotspot_dx = scale[0] * (1 - 2 * hotspot[0]) self.hotspot_dy = scale[2] * (1 - 2 * hotspot[1]) eng.event.attach(self.on_frame) def __set_standard_curson(self, show): props = WindowProperties() props.setCursorHidden(not show) base.win.requestProperties(props) def show(self): self.cursor_img.show() def show_standard(self): self.__set_standard_curson(True) def hide(self): self.cursor_img.hide() def hide_standard(self): self.__set_standard_curson(False) def cursor_top(self): self.cursor_img.reparent_to(self.cursor_img.get_parent()) def on_frame(self): if base.mouseWatcherNode.hasMouse(): x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() h_x = x * base.getAspectRatio() + self.hotspot_dx self.cursor_img.setPos(h_x, 0, y - self.hotspot_dy)
def __init__(self, car_props, player_idx, ncars, players): GameObject.__init__(self) self._players = players self.car_props = car_props self.player_idx = player_idx self.ncars = ncars sprops = self.car_props.race_props.season_props menu_props = sprops.gameprops.menu_props if ncars == 1: parent_tr = base.a2dTopRight elif ncars == 2: if self.player_idx == 0: parent_tr = base.a2dTopCenter else: parent_tr = base.a2dTopRight elif ncars == 3: if self.player_idx == 0: parent_tr = base.a2dTopRight elif self.player_idx == 1: parent_tr = base.aspect2d else: parent_tr = base.a2dRightCenter elif ncars == 4: if self.player_idx == 0: parent_tr = base.a2dTopCenter elif self.player_idx == 1: parent_tr = base.a2dTopRight elif self.player_idx == 2: parent_tr = base.aspect2d else: parent_tr = base.a2dRightCenter if ncars == 1: parent_tl = base.a2dTopLeft elif ncars == 2: if self.player_idx == 0: parent_tl = base.a2dTopLeft else: parent_tl = base.a2dTopCenter elif ncars == 3: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d elif ncars == 4: if self.player_idx == 0: parent_tl = base.a2dTopLeft elif self.player_idx == 1: parent_tl = base.a2dTopCenter elif self.player_idx == 2: parent_tl = base.a2dLeftCenter else: parent_tl = base.aspect2d if ncars == 1: parent_bl = base.a2dBottomLeft elif ncars == 2: if self.player_idx == 0: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter elif ncars == 3: if self.player_idx == 0: parent_bl = base.a2dLeftCenter elif self.player_idx == 1: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter elif ncars == 4: if self.player_idx == 0: parent_bl = base.a2dLeftCenter elif self.player_idx == 1: parent_bl = base.aspect2d elif self.player_idx == 2: parent_bl = base.a2dBottomLeft else: parent_bl = base.a2dBottomCenter # if ncars == 1: parent_t = base.a2dTopCenter # elif ncars == 2: # if self.player_idx == 0: parent_t = base.a2dTopQuarter # else: parent_t = base.a2dTopThirdQuarter # elif ncars == 3: # if self.player_idx == 0: parent_t = base.a2dTop # elif self.player_idx == 1: parent_t = base.a2dCenterQuarter # else: parent_t = base.a2dCenterThirdQuarter # elif ncars == 4: # if self.player_idx == 0: parent_t = base.a2dTopQuarter # elif self.player_idx == 1: parent_t = base.a2dTopThirdQuarter # elif self.player_idx == 2: parent_t = base.a2dCenterQuarter # else: parent_t = base.a2dCenterThirdQuarter # if ncars == 1: parent_b = base.a2dBottomCenter # elif ncars == 2: # if self.player_idx == 0: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter # elif ncars == 3: # if self.player_idx == 0: parent_b = base.aspect2d # elif self.player_idx == 1: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter # elif ncars == 4: # if self.player_idx == 0: parent_b = base.a2dCenterQuarter # elif self.player_idx == 1: parent_b = base.a2dCenterThirdQuarter # elif self.player_idx == 2: parent_b = base.a2dBottomQuarter # else: parent_b = base.a2dBottomThirdQuarter yellow_scale = .065 if ncars == 1 else .042 white_scale = .05 if ncars == 1 else .038 damages_img_scale = (.12, 1, .12) if ncars == 1 else (.08, 1, .08) self.__weap_scale = .12 if ncars == 1 else .08 txt_x = -.24 if ncars == 1 else -.18 lab_x = -.3 if ncars == 1 else -.24 offset_z = .1 if ncars == 1 else .08 top_z = -.1 damages_txt_pos = (.3, .1) if ncars == 1 else (.24, .06) damages_img_pos = (.46, 1, .12) if ncars == 1 else (.36, 1, .07) weapon_txt_pos = (.18, -.08) if ncars == 1 else (.14, -.08) self.__weapon_img_pos = (.18, 1, -.24) if ncars == 1 else \ (.14, 1, -.18) fwd_img_pos = (0, 1, -.2) if ncars == 1 else (0, 1, -.16) fwd_img_scale = .15 if ncars == 1 else .12 pars = { 'scale': yellow_scale, 'parent': parent_tr, 'fg': menu_props.text_active_col, 'align': TextNode.A_left, 'font': self.eng.font_mgr.load_font(sprops.font) } # self.glass_tl = OnscreenImage( # 'assets/images/gui/topleft.txo', # scale=(.23, 1, .24), parent=parent_tl, pos=(.22, 1, -.23)) # self.glass_tl.set_transparency(True) # self.glass_tr = OnscreenImage( # 'assets/images/gui/topright.txo', # scale=(.36, 1, .36), parent=parent_tr, pos=(-.35, 1, -.35)) # self.glass_tr.set_transparency(True) # self.glass_t = OnscreenImage( # 'assets/images/gui/top.txo', # scale=(.24, 1, .22), parent=parent_t, pos=(0, 1, -.21)) # self.glass_t.set_transparency(True) # self.glass_bl = OnscreenImage( # 'assets/images/gui/bottomleft.txo', # scale=(.36, 1, .16), parent=parent_bl, pos=(.35, 1, .15)) # self.glass_bl.set_transparency(True) # self.glass_br = OnscreenImage( # 'assets/images/gui/bottomright.txo', scale=(.26, 1, .26), # parent=base.a2dBottomRight, pos=(-.25, 1, .25)) # self.glass_br.set_transparency(True) # self.glass_b = OnscreenImage( # 'assets/images/gui/bottom.txo', # scale=(1.02, 1, .26), parent=parent_b, pos=(0, 1, .25)) # self.glass_b.set_transparency(True) # self.glass_tl.hide() # self.glass_t.hide() # self.glass_b.hide() self.speed_txt = OnscreenText(pos=(txt_x + .06, top_z), **pars) self.speed_txt['align'] = TextNode.A_center self.speed_c = Circle(size=.1, pos=(txt_x + .06, top_z), parent=parent_tr, ray=.4, thickness=.05, col_start=(.9, .6, .1, 1), col_end=(.2, .8, .2, 1)) lap_str = '1/' + str(self.car_props.race_props.laps) self.lap_txt = OnscreenText(text=lap_str, pos=(txt_x, top_z - offset_z), **pars) self.time_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 4), **pars) self.best_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 5), **pars) self.ranking_txt = OnscreenText(pos=(txt_x, top_z - offset_z * 2), **pars) self.damages_img = OnscreenImage('assets/images/gui/car_icon.txo', scale=damages_img_scale, parent=parent_bl, pos=damages_img_pos) self.damages_img.set_transparency(True) self.damages_img.set_color_scale(menu_props.text_normal_col) self.damages_img.set_r(90) pars = { 'scale': white_scale, 'parent': pars['parent'], 'fg': menu_props.text_normal_col, 'align': TextNode.A_right, 'font': pars['font'] } self.speed_lab = OnscreenText(_('speed:'), pos=(lab_x, top_z), **pars) self.lap_lab = OnscreenText(text=_('lap:'), pos=(lab_x, top_z - offset_z), **pars) self.time_lab = OnscreenText(_('time:'), pos=(lab_x, top_z - offset_z * 4), **pars) self.best_lab = OnscreenText(_('best lap:'), pos=(lab_x, top_z - offset_z * 5), **pars) self.ranking_lab = OnscreenText(_('ranking:'), pos=(lab_x, top_z - offset_z * 2), **pars) self.damages_lab = OnscreenText(_('damages:'), pos=damages_txt_pos, **pars) self.damages_lab.reparent_to(parent_bl) self.weapon_lab = OnscreenText(_('weapon'), pos=weapon_txt_pos, scale=white_scale, parent=parent_tl, fg=menu_props.text_normal_col, font=self.eng.font_mgr.load_font( sprops.font)) self.weapon_img = None if ncars == 1: parent = base.a2dTopCenter elif ncars == 2: if player_idx == 0: parent = base.a2dTopQuarter else: parent = base.a2dTopThirdQuarter elif ncars == 3: if player_idx == 0: parent = base.a2dTopCenter elif player_idx == 0: parent = base.a2dCenterQuarter else: parent = base.a2dCenterThirdQuarter elif ncars == 4: if player_idx == 0: parent = base.a2dTopQuarter elif player_idx == 1: parent = base.a2dTopThirdQuarter elif player_idx == 2: parent = base.a2dCenterQuarter else: parent = base.a2dCenterThirdQuarter self.forward_img = OnscreenImage('assets/images/gui/direction.txo', scale=fwd_img_scale, parent=parent, pos=fwd_img_pos) self.forward_img.set_transparency(True) self.forward_img.hide()
class World(DirectObject): def __init__(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.speed = 0 self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf') # Speedometer self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Display Speed self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Health Bar self.bars = {'H': 100, 'EH': 0, 'A': 0} # bk_text = "This is my Demo" # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) self.Health_bar = DirectWaitBar(text="", value=100, pos=(0.280, 0, 0.475), barColor=(1, 0, 0, 1), frameSize=(0, .705, .3, .35)) self.EHealth_bar = DirectWaitBar(text="", value=0, pos=(1, 0, 0.475), barColor=(0, 1, 0, 1), frameSize=(0, .23, .3, .35), range=50) self.Armour_bar = DirectWaitBar(text="", value=0, pos=(.43, 0, .593), barColor=(159, 0, 255, 1), frameSize=(0, .8, .3, .35)) self.Health = DirectWaitBar(text="", value=100, barColor=(1, 0, 0, 1), frameSize=(-1, 1, .3, .5), scale=2) # create a frame # myFrame = DirectFrame(frameColor=(1, 0, 0, 1), # frameSize=(0, .8, 0, .2)) # self.bar = DirectWaitBar(text = "hi", # value = 0, # range = 500, # pos = ( 0,0,0), # barColor = (0.97,0,0,1), # frameSize = (-0.3,0.3,0.5,0.8), # text_mayChange = 1, # text_shadow =(0,0,0,0.8), # text_fg = (0.9,0.9,0.9,1), # text_scale = 0.025, # text_pos = (0,0.01,0)) def getHealthStatus(): return self.bars def displayBars(): health = getHealthStatus() self.Health_bar['value'] = health['H'] self.EHealth_bar['value'] = health['EH'] self.Armour_bar['value'] = health['A'] self.Health['value'] = health['H'] def armourPickup(): self.bars['A'] += 25 displayBars() def healthPickup(): self.bars['EH'] += 25 displayBars() def decHealth(): self.bars['H'] -= 10 displayBars() def initialiseSound(audioManager): """Start the engine sound and set collision sounds""" # Set sounds to play for collisions # self.collisionSound = CollisionSound( # nodePath=self.np, # sounds=["data/sounds/09.wav"], # thresholdForce=600.0, # maxForce=800000.0) # np - nodePath self.engineSound = audioManager.loadSfx("sound/engine.wav") audioManager.attachSoundToObject(self.engineSound, self.ralph) self.engineSound.setLoop(True) self.engineSound.setPlayRate(0.6) self.engineSound.play() # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] / # self.specs["sound"]["numberOfGears"]) self.gearSpacing = (150 / 4) self.reversing = False # Post the instructions self.frame = OnscreenImage(image="models/gframe.png", pos=(0, 0, 0), scale=(1.25, 1, 1)) self.frame.setTransparency(TransparencyAttrib.MAlpha) # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0, 0, 0) # # Load and place the model # self.eNode = render.attachNewNode('enemyBaseNode') # self.eNode.setPos( 0,0,0 ) # self.model = loader.loadModel( 'models/ralph' ) # self.model.reparentTo( self.eNode ) # # Setup the rest of what the enemy needs # self.setupHealthBar() # self.Health.setBillboardAxis() # self.Health.setBillboardPointWorld() # self.Health.setBillboardPointEye() # self.Health.setLightOff() self.Health.setPos(0, 0, 5) self.Health.setBillboardPointEye() self.Health.setBin('fixed', 0) self.Health.setDepthWrite(False) self.Health.reparentTo(self.ralph) # myFrame.setPos(0, 0, 8) # myFrame.setBillboardPointEye() # myFrame.reparentTo(self.ralph) # self.Health.clearBillboard() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("h", decHealth) self.accept("j", healthPickup) self.accept("k", armourPickup) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Create an audio manager. This is attached to the camera for # player 1, so sounds close to other players might not be very # loud self.audioManager = Audio3DManager.Audio3DManager( base.sfxManagerList[0], base.camera) # Distance should be in m, not feet self.audioManager.setDistanceFactor(3.28084) initialiseSound(self.audioManager) displayBars() # updateSound() # Creates the health bar above the enemy def setupHealthBar(self): self.hpBar = DirectWaitBar(text="", value=100.0, pos=(0, 0, 1.5), scale=3, barColor=Vec4(1, 0, 0, 1)) self.hpBar.setBillboardPointEye() self.hpBar.reparentTo(self.eNode) print "dddddddddddddddddddd" self.hpBar.clearColor() def show_speed(self, task): # self.speed = str(format(self.ralph.getCurrentSpeedKmHour(), '0.2f')) # self.speed = 2 # print self.speed # Update Speed Display self.display_speed.destroy() self.display_speed = OnscreenText(text=str(self.speed), style=3, fg=(1, 1, 1, 1), pos=(1.2, -0.95), align=TextNode.ARight, scale=.15, font=self.font_digital) return task.cont #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def updateSound(self): """Use vehicle speed to update sound pitch""" # soundSpecs = self.specs["sound"] # Use rear wheel rotation speed as some measure of engine revs # wheels = (self.vehicle.getWheel(idx) for idx in (2, 3)) # wheelRate is in degrees per second # wheelRate = 0.5 * abs(sum(w.getDeltaRotation() / dt for w in wheels)) wheelRate = 0.5 * self.speed # Calculate which gear we're in, and what the normalised revs are if self.reversing: numberOfGears = 1 else: numberOfGears = 4 # gear = min(int(wheelRate / self.gearSpacing), # numberOfGears - 1) gear = min(int(wheelRate / self.gearSpacing), numberOfGears - 1) print gear if max(int(wheelRate / self.gearSpacing), numberOfGears - 1) < 4: # posInGear = (wheelRate - gear * self.gearSpacing) / self.gearSpacing posInGear = (wheelRate - gear * self.gearSpacing) / self.gearSpacing print posInGear targetPlayRate = 0.6 + posInGear * (1.5 - 0.6) print targetPlayRate currentRate = self.engineSound.getPlayRate() self.engineSound.setPlayRate(0.8 * currentRate + 0.2 * targetPlayRate) # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.ralph) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"] != 0): self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt()) if (self.keyMap["right"] != 0): self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) if (self.keyMap["forward"] != 0): self.ralph.setY(self.ralph, -25 * globalClock.getDt()) # print "walk", self.speed if self.speed < 100: self.speed = self.speed + self.speed / 100 + 1 else: self.speed = self.speed + self.speed / 200 + 1 # print self.speed self.updateSound() # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["forward"] != 0) or (self.keyMap["left"] != 0) or (self.keyMap["right"] != 0): if self.isMoving is False: self.ralph.loop("run") # print "run" self.isMoving = True else: if self.isMoving: self.ralph.stop() self.speed = 0 self.ralph.pose("walk", 5) self.isMoving = False # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.ralph.getPos()) self.floater.setZ(self.ralph.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont
def __init__(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) self.speed = 0 self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf') # Speedometer self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Display Speed self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) # Health Bar self.bars = {'H': 100, 'EH': 0, 'A': 0} # bk_text = "This is my Demo" # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1) self.Health_bar = DirectWaitBar(text="", value=100, pos=(0.280, 0, 0.475), barColor=(1, 0, 0, 1), frameSize=(0, .705, .3, .35)) self.EHealth_bar = DirectWaitBar(text="", value=0, pos=(1, 0, 0.475), barColor=(0, 1, 0, 1), frameSize=(0, .23, .3, .35), range=50) self.Armour_bar = DirectWaitBar(text="", value=0, pos=(.43, 0, .593), barColor=(159, 0, 255, 1), frameSize=(0, .8, .3, .35)) self.Health = DirectWaitBar(text="", value=100, barColor=(1, 0, 0, 1), frameSize=(-1, 1, .3, .5), scale=2) # create a frame # myFrame = DirectFrame(frameColor=(1, 0, 0, 1), # frameSize=(0, .8, 0, .2)) # self.bar = DirectWaitBar(text = "hi", # value = 0, # range = 500, # pos = ( 0,0,0), # barColor = (0.97,0,0,1), # frameSize = (-0.3,0.3,0.5,0.8), # text_mayChange = 1, # text_shadow =(0,0,0,0.8), # text_fg = (0.9,0.9,0.9,1), # text_scale = 0.025, # text_pos = (0,0.01,0)) def getHealthStatus(): return self.bars def displayBars(): health = getHealthStatus() self.Health_bar['value'] = health['H'] self.EHealth_bar['value'] = health['EH'] self.Armour_bar['value'] = health['A'] self.Health['value'] = health['H'] def armourPickup(): self.bars['A'] += 25 displayBars() def healthPickup(): self.bars['EH'] += 25 displayBars() def decHealth(): self.bars['H'] -= 10 displayBars() def initialiseSound(audioManager): """Start the engine sound and set collision sounds""" # Set sounds to play for collisions # self.collisionSound = CollisionSound( # nodePath=self.np, # sounds=["data/sounds/09.wav"], # thresholdForce=600.0, # maxForce=800000.0) # np - nodePath self.engineSound = audioManager.loadSfx("sound/engine.wav") audioManager.attachSoundToObject(self.engineSound, self.ralph) self.engineSound.setLoop(True) self.engineSound.setPlayRate(0.6) self.engineSound.play() # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] / # self.specs["sound"]["numberOfGears"]) self.gearSpacing = (150 / 4) self.reversing = False # Post the instructions self.frame = OnscreenImage(image="models/gframe.png", pos=(0, 0, 0), scale=(1.25, 1, 1)) self.frame.setTransparency(TransparencyAttrib.MAlpha) # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0, 0, 0) # # Load and place the model # self.eNode = render.attachNewNode('enemyBaseNode') # self.eNode.setPos( 0,0,0 ) # self.model = loader.loadModel( 'models/ralph' ) # self.model.reparentTo( self.eNode ) # # Setup the rest of what the enemy needs # self.setupHealthBar() # self.Health.setBillboardAxis() # self.Health.setBillboardPointWorld() # self.Health.setBillboardPointEye() # self.Health.setLightOff() self.Health.setPos(0, 0, 5) self.Health.setBillboardPointEye() self.Health.setBin('fixed', 0) self.Health.setDepthWrite(False) self.Health.reparentTo(self.ralph) # myFrame.setPos(0, 0, 8) # myFrame.setBillboardPointEye() # myFrame.reparentTo(self.ralph) # self.Health.clearBillboard() # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) self.accept("h", decHealth) self.accept("j", healthPickup) self.accept("k", armourPickup) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Create an audio manager. This is attached to the camera for # player 1, so sounds close to other players might not be very # loud self.audioManager = Audio3DManager.Audio3DManager( base.sfxManagerList[0], base.camera) # Distance should be in m, not feet self.audioManager.setDistanceFactor(3.28084) initialiseSound(self.audioManager) displayBars()
class EngineCore(ShowBase.ShowBase): DEBUG = False loadPrcFileData("", "window-title {}".format(EDITION)) loadPrcFileData("", "framebuffer-multisample 1") loadPrcFileData("", "multisamples 8") loadPrcFileData("", 'bullet-filter-algorithm groups-mask') loadPrcFileData("", "audio-library-name null") loadPrcFileData("", "model-cache-compressed-textures 1") # loadPrcFileData("", "transform-cache 0") # loadPrcFileData("", "state-cache 0") loadPrcFileData("", "garbage-collect-states 0") # loadPrcFileData("", " framebuffer-srgb truein") # loadPrcFileData("", "geom-cache-size 50000") # v-sync, it seems useless # loadPrcFileData("", "sync-video 1") # for debug use # loadPrcFileData("", "gl-version 3 2") def __init__(self, global_config): self.global_config = global_config if self.global_config["pstats"]: # pstats debug provided by panda3d loadPrcFileData("", "want-pstats 1") loadPrcFileData( "", "win-size {} {}".format(*self.global_config["window_size"])) # Setup onscreen render if self.global_config["use_render"]: self.mode = RENDER_MODE_ONSCREEN # Warning it may cause memory leak, Pand3d Official has fixed this in their master branch. # You can enable it if your panda version is latest. loadPrcFileData( "", "threading-model Cull/Draw" ) # multi-thread render, accelerate simulation when evaluate else: if self.global_config["offscreen_render"]: self.mode = RENDER_MODE_OFFSCREEN loadPrcFileData("", "threading-model Cull/Draw") else: self.mode = RENDER_MODE_NONE if is_mac() and (self.mode == RENDER_MODE_OFFSCREEN ): # Mac don't support offscreen rendering self.mode = RENDER_MODE_ONSCREEN # Setup some debug options if self.global_config["headless_machine_render"]: # headless machine support loadPrcFileData("", "load-display pandagles2") if self.global_config["debug"]: # debug setting EngineCore.DEBUG = True _free_warning() setup_logger(debug=True) self.accept('1', self.toggleDebug) self.accept('2', self.toggleWireframe) self.accept('3', self.toggleTexture) self.accept('4', self.toggleAnalyze) else: # only report fatal error when debug is False _suppress_warning() # a special debug mode if self.global_config["debug_physics_world"]: self.accept('1', self.toggleDebug) self.accept('4', self.toggleAnalyze) super(EngineCore, self).__init__(windowType=self.mode) # Change window size at runtime if screen too small # assert int(self.global_config["use_topdown"]) + int(self.global_config["offscreen_render"]) <= 1, ( # "Only one of use_topdown and offscreen_render options can be selected." # ) # main_window_position = (0, 0) if self.mode == RENDER_MODE_ONSCREEN: if self.global_config["fast"]: pass else: loadPrcFileData("", "compressed-textures 1") # Default to compress h = self.pipe.getDisplayHeight() w = self.pipe.getDisplayWidth() if self.global_config["window_size"][ 0] > 0.9 * w or self.global_config["window_size"][ 1] > 0.9 * h: old_scale = self.global_config["window_size"][ 0] / self.global_config["window_size"][1] new_w = int(min(0.9 * w, 0.9 * h * old_scale)) new_h = int(min(0.9 * h, 0.9 * w / old_scale)) self.global_config["window_size"] = tuple([new_w, new_h]) from panda3d.core import WindowProperties props = WindowProperties() props.setSize(self.global_config["window_size"][0], self.global_config["window_size"][1]) self.win.requestProperties(props) logging.warning( "Since your screen is too small ({}, {}), we resize the window to {}." .format(w, h, self.global_config["window_size"])) # main_window_position = ( # (w - self.global_config["window_size"][0]) / 2, (h - self.global_config["window_size"][1]) / 2 # ) # self.highway_render = None # if self.global_config["use_topdown"]: # self.highway_render = HighwayRender(self.global_config["use_render"], main_window_position) # screen scale factor self.w_scale = max( self.global_config["window_size"][0] / self.global_config["window_size"][1], 1) self.h_scale = max( self.global_config["window_size"][1] / self.global_config["window_size"][0], 1) if self.mode == RENDER_MODE_ONSCREEN: self.disableMouse() if not self.global_config["debug_physics_world"] and (self.mode in [ RENDER_MODE_ONSCREEN, RENDER_MODE_OFFSCREEN ]): initialize_asset_loader(self) gltf.patch_loader(self.loader) # Display logo if self.mode == RENDER_MODE_ONSCREEN and (not self.global_config["debug"]) \ and (not self.global_config["fast"]): self._loading_logo = OnscreenImage( image=AssetLoader.file_path("PGDrive-large.png"), pos=(0, 0, 0), scale=(self.w_scale, 1, self.h_scale)) self._loading_logo.setTransparency(True) for i in range(20): self.graphicsEngine.renderFrame() self.taskMgr.add(self.remove_logo, "remove _loading_logo in first frame") self.closed = False # add element to render and pbr render, if is exists all the time. # these element will not be removed when clear_world() is called self.pbr_render = self.render.attachNewNode("pbrNP") # attach node to this root root whose children nodes will be clear after calling clear_world() self.worldNP = self.render.attachNewNode("world_np") # same as worldNP, but this node is only used for render gltf model with pbr material self.pbr_worldNP = self.pbr_render.attachNewNode("pbrNP") self.debug_node = None # some render attribute self.pbrpipe = None self.world_light = None # physics world self.physics_world = PhysicsWorld( self.global_config["debug_static_world"]) # collision callback self.physics_world.dynamic_world.setContactAddedCallback( PythonCallbackObject(collision_callback)) # for real time simulation self.force_fps = ForceFPS(self, start=True) # init terrain self.terrain = Terrain() self.terrain.attach_to_world(self.render, self.physics_world) # init other world elements if self.mode != RENDER_MODE_NONE: from pgdrive.engine.core.our_pbr import OurPipeline self.pbrpipe = OurPipeline(render_node=None, window=None, camera_node=None, msaa_samples=4, max_lights=8, use_normal_maps=False, use_emission_maps=True, exposure=1.0, enable_shadows=False, enable_fog=False, use_occlusion_maps=False) self.pbrpipe.render_node = self.pbr_render self.pbrpipe.render_node.set_antialias(AntialiasAttrib.M_auto) self.pbrpipe._recompile_pbr() self.pbrpipe.manager.cleanup() # set main cam self.cam.node().setCameraMask(CamMask.MainCam) self.cam.node().getDisplayRegion(0).setClearColorActive(True) self.cam.node().getDisplayRegion(0).setClearColor(BKG_COLOR) lens = self.cam.node().getLens() lens.setFov(70) lens.setAspectRatio(1.2) self.sky_box = SkyBox() self.sky_box.attach_to_world(self.render, self.physics_world) self.world_light = Light(self.global_config) self.world_light.attach_to_world(self.render, self.physics_world) self.render.setLight(self.world_light.direction_np) self.render.setLight(self.world_light.ambient_np) self.render.setShaderAuto() self.render.setAntialias(AntialiasAttrib.MAuto) # ui and render property if self.global_config["show_fps"]: self.setFrameRateMeter(True) # onscreen message self.on_screen_message = ScreenMessage( debug=self.DEBUG ) if self.mode == RENDER_MODE_ONSCREEN and self.global_config[ "onscreen_message"] else None self._show_help_message = False self._episode_start_time = time.time() self.accept("h", self.toggle_help_message) self.accept("f", self.force_fps.toggle) else: self.on_screen_message = None # task manager self.taskMgr.remove('audioLoop') def render_frame(self, text: Optional[Union[dict, str]] = None): """ The real rendering is conducted by the igLoop task maintained by panda3d. Frame will be drawn and refresh, when taskMgr.step() is called. This function is only used to pass the message that needed to be printed in the screen to underlying renderer. :param text: A dict containing key and values or a string. :return: None """ if self.on_screen_message is not None: self.on_screen_message.update_data(text) self.on_screen_message.render() if self.mode == RENDER_MODE_ONSCREEN: self.sky_box.step() # if self.highway_render is not None: # self.highway_render.render() def step_physics_world(self): dt = self.global_config["physics_world_step_size"] self.physics_world.dynamic_world.doPhysics(dt, 1, dt) def _debug_mode(self): debugNode = BulletDebugNode('Debug') debugNode.showWireframe(True) debugNode.showConstraints(True) debugNode.showBoundingBoxes(False) debugNode.showNormals(True) debugNP = self.render.attachNewNode(debugNode) self.physics_world.dynamic_world.setDebugNode(debugNP.node()) self.debug_node = debugNP def toggleAnalyze(self): self.worldNP.analyze() print(self.physics_world.report_bodies()) # self.worldNP.ls() def toggleDebug(self): if self.debug_node is None: self._debug_mode() if self.debug_node.isHidden(): self.debug_node.show() else: self.debug_node.hide() def report_body_nums(self, task): logging.debug(self.physics_world.report_bodies()) return task.done def close_world(self): self.taskMgr.stop() # It will report a warning said AsynTaskChain is created when taskMgr.destroy() is called but a new showbase is # created. logging.debug( "Before del taskMgr: task_chain_num={}, all_tasks={}".format( self.taskMgr.mgr.getNumTaskChains(), self.taskMgr.getAllTasks())) self.taskMgr.destroy() logging.debug( "After del taskMgr: task_chain_num={}, all_tasks={}".format( self.taskMgr.mgr.getNumTaskChains(), self.taskMgr.getAllTasks())) self.physics_world.dynamic_world.clearContactAddedCallback() self.physics_world.destroy() self.destroy() close_asset_loader() import sys if sys.version_info >= (3, 0): import builtins else: import __builtin__ as builtins if hasattr(builtins, 'base'): del builtins.base def clear_world(self): self.worldNP.removeNode() self.pbr_worldNP.removeNode() def toggle_help_message(self): if self.on_screen_message: self.on_screen_message.toggle_help_message() def draw_line(self, start_p, end_p, color, thickness: float): """ Draw line use LineSegs coordinates system. Since a resolution problem is solved, the point on screen should be described by [horizontal ratio, vertical ratio], each of them are ranged in [-1, 1] :param start_p: 2d vec :param end_p: 2d vec :param color: 4d vec, line color :param thickness: line thickness """ line_seg = LineSegs("interface") line_seg.setColor(*color) line_seg.moveTo(start_p[0] * self.w_scale, 0, start_p[1] * self.h_scale) line_seg.drawTo(end_p[0] * self.w_scale, 0, end_p[1] * self.h_scale) line_seg.setThickness(thickness) line_np = self.aspect2d.attachNewNode(line_seg.create(False)) return line_np def remove_logo(self, task): alpha = self._loading_logo.getColor()[-1] if alpha < 0.1: self._loading_logo.destroy() return task.done else: new_alpha = alpha - 0.08 self._loading_logo.setColor((1, 1, 1, new_alpha)) return task.cont
class Preloader: def __init__(self, fonts): self.createGraphics(fonts) file = open("models.txt", "r") self.models = file.readlines() file.close() for N in range(len(self.models)): self.models[N] = self.models[N].replace("\n", "") self.totalItems = len(self.models) self.loaderBar.setTexOffset(self.modTS, .015, 0) base.graphicsEngine.renderFrame() #base.graphicsEngine.renderFrame() self.itemCount = 0 for M in self.models: item = loader.loadModel(M) self.itemCount += 1 progress = self.itemCount / float(self.totalItems) self.loaderBar.setTexOffset(self.modTS, -progress + .005, 0) base.graphicsEngine.renderFrame() #base.graphicsEngine.renderFrame() self.destroy() def createGraphics(self, fonts): self.modTS = TextureStage("Modulate") self.modTS.setMode(TextureStage.MModulate) self.frame = DirectFrame(frameSize=(-.3, .3, -.2, .2), frameColor=(1, 1, 1, 0), parent=base.aspect2d) loaderEgg = loader.loadModel("Models/EnergyBar.egg") self.loaderBG = loaderEgg.find("**/EnergyBG") self.loaderBar = loaderEgg.find("**/EnergyBar") self.loaderFrame = loaderEgg.find("**/EnergyFrame") self.loaderBG.reparentTo(self.frame) self.loaderBar.reparentTo(self.loaderBG) self.loaderFrame.reparentTo(self.loaderBG) self.loaderBG.setPos(0, 0, -.2) alpha = loader.loadTexture("Models/LoaderAlpha.png") alpha.setFormat(Texture.FAlpha) alpha.setWrapU(Texture.WMClamp) self.loaderBar.setTexture(self.modTS, alpha) self.image = OnscreenImage(image='Models2/3dcrlogo.png', pos=(0, 0, -.05), scale=(0.799, 0, 0.152)) self.image.setTransparency(TransparencyAttrib.MAlpha) return def destroy(self): self.loaderBG.removeNode() self.image.destroy() self.frame.destroy()
def __init__(self, global_config): self.global_config = global_config if self.global_config["pstats"]: # pstats debug provided by panda3d loadPrcFileData("", "want-pstats 1") loadPrcFileData( "", "win-size {} {}".format(*self.global_config["window_size"])) # Setup onscreen render if self.global_config["use_render"]: self.mode = RENDER_MODE_ONSCREEN # Warning it may cause memory leak, Pand3d Official has fixed this in their master branch. # You can enable it if your panda version is latest. loadPrcFileData( "", "threading-model Cull/Draw" ) # multi-thread render, accelerate simulation when evaluate else: if self.global_config["offscreen_render"]: self.mode = RENDER_MODE_OFFSCREEN loadPrcFileData("", "threading-model Cull/Draw") else: self.mode = RENDER_MODE_NONE if is_mac() and (self.mode == RENDER_MODE_OFFSCREEN ): # Mac don't support offscreen rendering self.mode = RENDER_MODE_ONSCREEN # Setup some debug options if self.global_config["headless_machine_render"]: # headless machine support loadPrcFileData("", "load-display pandagles2") if self.global_config["debug"]: # debug setting EngineCore.DEBUG = True _free_warning() setup_logger(debug=True) self.accept('1', self.toggleDebug) self.accept('2', self.toggleWireframe) self.accept('3', self.toggleTexture) self.accept('4', self.toggleAnalyze) else: # only report fatal error when debug is False _suppress_warning() # a special debug mode if self.global_config["debug_physics_world"]: self.accept('1', self.toggleDebug) self.accept('4', self.toggleAnalyze) super(EngineCore, self).__init__(windowType=self.mode) # Change window size at runtime if screen too small # assert int(self.global_config["use_topdown"]) + int(self.global_config["offscreen_render"]) <= 1, ( # "Only one of use_topdown and offscreen_render options can be selected." # ) # main_window_position = (0, 0) if self.mode == RENDER_MODE_ONSCREEN: if self.global_config["fast"]: pass else: loadPrcFileData("", "compressed-textures 1") # Default to compress h = self.pipe.getDisplayHeight() w = self.pipe.getDisplayWidth() if self.global_config["window_size"][ 0] > 0.9 * w or self.global_config["window_size"][ 1] > 0.9 * h: old_scale = self.global_config["window_size"][ 0] / self.global_config["window_size"][1] new_w = int(min(0.9 * w, 0.9 * h * old_scale)) new_h = int(min(0.9 * h, 0.9 * w / old_scale)) self.global_config["window_size"] = tuple([new_w, new_h]) from panda3d.core import WindowProperties props = WindowProperties() props.setSize(self.global_config["window_size"][0], self.global_config["window_size"][1]) self.win.requestProperties(props) logging.warning( "Since your screen is too small ({}, {}), we resize the window to {}." .format(w, h, self.global_config["window_size"])) # main_window_position = ( # (w - self.global_config["window_size"][0]) / 2, (h - self.global_config["window_size"][1]) / 2 # ) # self.highway_render = None # if self.global_config["use_topdown"]: # self.highway_render = HighwayRender(self.global_config["use_render"], main_window_position) # screen scale factor self.w_scale = max( self.global_config["window_size"][0] / self.global_config["window_size"][1], 1) self.h_scale = max( self.global_config["window_size"][1] / self.global_config["window_size"][0], 1) if self.mode == RENDER_MODE_ONSCREEN: self.disableMouse() if not self.global_config["debug_physics_world"] and (self.mode in [ RENDER_MODE_ONSCREEN, RENDER_MODE_OFFSCREEN ]): initialize_asset_loader(self) gltf.patch_loader(self.loader) # Display logo if self.mode == RENDER_MODE_ONSCREEN and (not self.global_config["debug"]) \ and (not self.global_config["fast"]): self._loading_logo = OnscreenImage( image=AssetLoader.file_path("PGDrive-large.png"), pos=(0, 0, 0), scale=(self.w_scale, 1, self.h_scale)) self._loading_logo.setTransparency(True) for i in range(20): self.graphicsEngine.renderFrame() self.taskMgr.add(self.remove_logo, "remove _loading_logo in first frame") self.closed = False # add element to render and pbr render, if is exists all the time. # these element will not be removed when clear_world() is called self.pbr_render = self.render.attachNewNode("pbrNP") # attach node to this root root whose children nodes will be clear after calling clear_world() self.worldNP = self.render.attachNewNode("world_np") # same as worldNP, but this node is only used for render gltf model with pbr material self.pbr_worldNP = self.pbr_render.attachNewNode("pbrNP") self.debug_node = None # some render attribute self.pbrpipe = None self.world_light = None # physics world self.physics_world = PhysicsWorld( self.global_config["debug_static_world"]) # collision callback self.physics_world.dynamic_world.setContactAddedCallback( PythonCallbackObject(collision_callback)) # for real time simulation self.force_fps = ForceFPS(self, start=True) # init terrain self.terrain = Terrain() self.terrain.attach_to_world(self.render, self.physics_world) # init other world elements if self.mode != RENDER_MODE_NONE: from pgdrive.engine.core.our_pbr import OurPipeline self.pbrpipe = OurPipeline(render_node=None, window=None, camera_node=None, msaa_samples=4, max_lights=8, use_normal_maps=False, use_emission_maps=True, exposure=1.0, enable_shadows=False, enable_fog=False, use_occlusion_maps=False) self.pbrpipe.render_node = self.pbr_render self.pbrpipe.render_node.set_antialias(AntialiasAttrib.M_auto) self.pbrpipe._recompile_pbr() self.pbrpipe.manager.cleanup() # set main cam self.cam.node().setCameraMask(CamMask.MainCam) self.cam.node().getDisplayRegion(0).setClearColorActive(True) self.cam.node().getDisplayRegion(0).setClearColor(BKG_COLOR) lens = self.cam.node().getLens() lens.setFov(70) lens.setAspectRatio(1.2) self.sky_box = SkyBox() self.sky_box.attach_to_world(self.render, self.physics_world) self.world_light = Light(self.global_config) self.world_light.attach_to_world(self.render, self.physics_world) self.render.setLight(self.world_light.direction_np) self.render.setLight(self.world_light.ambient_np) self.render.setShaderAuto() self.render.setAntialias(AntialiasAttrib.MAuto) # ui and render property if self.global_config["show_fps"]: self.setFrameRateMeter(True) # onscreen message self.on_screen_message = ScreenMessage( debug=self.DEBUG ) if self.mode == RENDER_MODE_ONSCREEN and self.global_config[ "onscreen_message"] else None self._show_help_message = False self._episode_start_time = time.time() self.accept("h", self.toggle_help_message) self.accept("f", self.force_fps.toggle) else: self.on_screen_message = None # task manager self.taskMgr.remove('audioLoop')
class EventManager(ShowBase): def __init__(self): ShowBase.__init__(self) #self.setFrameRateMeter(True) self.agui() self.initkeys() self.game_init = False self.rungame = False taskMgr.add( self.game, "Game", ) # this is setting the main information at the start page def agui(self): self.a, self.b = text_entry("Particpant ID", 0.6) self.c, self.d = text_entry("Age", 0.5) self.e, self.f = text_entry("Gender", 0.4, options=["Male", "Female"]) self.butt = button("Go!", -0.5, extras=[self.b, self.d, self]) self.p_ID = self.b.get() self.todelete = [ self.c, self.d, self.a, self.b, self.e, self.f, self.butt ] # code to start the game def game(self, task): if self.game_init: self.initgame() for thing in self.todelete: thing.destroy() self.game_init = False if self.rungame: if self.GameOver == False: if self.new_trial: self.init_trial() elif self.go: self.godisp() else: # if self.joystickon == 1: # self.getjoystick() # else: self.move() self.animate() self.dig() self.drag() self.movecam() if self.savelog: self.log() self.savelog = False else: if self.BlackScreen == 0: self.BlackScreen = 1 self.BlackTime = 1 OnscreenImage(image='textures/black.jpg', pos=(0, 0, 0), scale=100) self.starimage = OnscreenImage( image='textures/goldstar.png', pos=(0, 0, 0), scale=0.1) self.starimage.setTransparency(TransparencyAttrib.MAlpha) #self.EndText = OnscreenText(text = "GREAT JOB!" , pos = (-100, -0.5), scale = 0.1*self.goscale) else: self.BlackTime += 60. / self.framerate if self.BlackTime > 600: sys.exit() return task.done return task.cont # creating the log file - note that I added 1 column variable to the end of file. def log(self): #reopen the file self.file = open( 'logs/Reversal3D_end30_5of6_logfile_' + str(self.p_ID) + '.txt', 'a') """Save trial ID - Age - Gender - Reversal - """ self.file.write("\n") self.file.write("%s\t" % self.p_ID) self.file.write("%s\t" % self.p_age) self.file.write("%s\t" % self.p_gender) self.file.write("%s\t" % self.trial_no) self.file.write("%s\t" % self.reversal) self.file.write("%s\t" % self.trial[0]) self.file.write("%s\t" % self.dug) self.file.write("%s\t" % self.trialscore) self.file.write("%s\t" % self.TotalScore) self.file.write("%s\t" % self.RunningTotal) self.file.write("%s\t" % self.LastFiveSixCount) self.file.write("%s\t" % self.trial_num_phase) for visit_no in self.visits: self.file.write("%s\t" % visit_no) self.file.write("%s\t" % self.RT) self.file.write("%s\t" % strftime("%Y-%m-%d %H:%M:%S", gmtime())) self.file.close() #save the file # setting up the onscreen text for start of trial. def godisp(self): self.ReadyText.destroy() self.GoText.destroy() self.goscale += 60. / self.framerate if self.goscale < 60: self.ReadyText = OnscreenText(text="Ready!", pos=(0, -0.5), scale=0.1 * self.goscale / 2) elif self.goscale < 120: self.GoText.destroy() elif self.goscale < 180: self.GoText = OnscreenText(text="Go!", pos=(0, -0.5), scale=0.1 * (self.goscale - 120) / 2) else: self.go = False self.t0 = time.time() # not using the joystick so this doesn't work # def getjoystick(self): # dt = globalClock.getDt() # if self.canMove == True: # for event in pygame.event.get(): # pass # self.isMoving = False # self.isTurning = False # if self.joystick.get_axis( 4 )<-0.8: # self.isMoving=True # self.get_move(dt) # if self.joystick.get_axis( 3 )<-0.8: # self.kiki.setH(self.kiki.getH() + 300 * dt) # self.isTurning = True # if self.joystick.get_axis( 3 )>0.8: # self.kiki.setH(self.kiki.getH() - 300 * dt) # self.isTurning = True # if self.joystick.get_button( 1 ) > 0.8: # if self.get_dig()>-1: # self.digging = True # parameters to move character def move(self): dt = globalClock.getDt() #get time from last frame #check for keyboard input if self.canMove == True: self.isMoving = False if self.LRSpin == "Spin": if self.keyMap["spin"]: pass #self.camspin = True else: self.camspin = False if self.keyMap["left"]: self.kiki.setH(self.kiki.getH() + 300 * dt) self.isTurning = True if self.keyMap["right"]: self.kiki.setH(self.kiki.getH() - 300 * dt) self.isTurning = True if self.keyMap["forward"]: self.isMoving = True self.get_move(dt) if self.keyMap["back"]: self.isMoving = True self.get_move(dt, back=1) if not self.keyMap["left"] and not self.keyMap["right"]: self.isTurning = False else: a, b = -1, -1 self.isTurning = True if self.keyMap["left"]: self.kiki.setH(90) self.isMoving = True self.get_move(dt, side=1) a = 0 if self.keyMap["right"]: self.kiki.setH(270) self.isMoving = True self.get_move(dt, side=-1) a = 1 if self.keyMap["forward"]: self.kiki.setH(0) self.isMoving = True self.get_move(dt) b = 0 if self.keyMap["back"]: self.kiki.setH(180) self.isMoving = True self.get_move(dt, back=1) b = 1 if a > -1 and b > -1: self.kiki.setH([[45, 315], [135, 225]][b][a]) if self.keyMap["dig"]: if self.get_dig() > -1: self.digging = True # parameters to dig in the box def get_dig(self): x, y = self.kiki.getPos()[0], self.kiki.getPos()[1] dig = -1 for i, j in zip(self.presLoc, [0, 1, 2, 3]): if abs(x - self.boxloca[i][0]) < 3 and abs(y - self.boxloca[i][1]) < 3: dig = j if self.dug == -1: self.RT = time.time() - self.t0 self.savelog = True self.dug = j # if you got the trial correct if self.dug == self.trial[0]: if self.trialscore == 0: self.TotalScore += 1 self.addstar = 1 self.trialscore = 1 self.RunningTotal += 1 else: self.RunningTotal = 0 return dig # parameters to get feedback from the box (star or no star) def dig(self): if self.digging == True: self.plnp.setPos(self.boxloca[self.presLoc[self.dug]][0], self.boxloca[self.presLoc[self.dug]][1], 0) self.render.setLight(self.plnp) self.isMoving = False self.canMove = False if self.boxcam == True: if self.dug == self.trial[0]: self.star.reparentTo(self.render) self.starspin() elif self.negfeedbac == 1: if self.clouddisp == 1: self.clouddisp = 0 ex = 0 self.presents[self.dug].detachNode() self.clouds.reparentTo(self.render) self.clouds.setPos( self.boxloca[self.presLoc[self.dug]][0], self.boxloca[self.presLoc[self.dug]][1], 2) if self.dragback == False: if flipbook_2(self.clouds, self.cloudsframe, loop=0): self.dragback = True self.clouds.detachNode() self.clouds.currentframe = 0 self.digging = False else: flipbook_2(self.kiki, self.losingframe, loop=1) else: ex = 0 self.presents[self.dug].detachNode() self.digging = False self.dragback = True else: a = flipbook_2(self.kiki, self.digframe, 0) flipbook_2(self.presents[self.dug], self.presentsframe, 0) if a: self.boxcam = True # making the start spin def starspin(self): self.presents[self.dug].detachNode() self.spin += 60. / self.framerate if self.spin < 180: self.star.setH(self.spin * 5) self.star.setPos(self.boxloca[self.presLoc[self.dug]][0], self.boxloca[self.presLoc[self.dug]][1], 3 + self.spin / 30.) flipbook_2(self.kiki, self.winframe, loop=1) else: self.dragback = True self.star.detachNode() self.digging = False def get_move(self, dt, back=0, side=0): if self.LRSpin == "Spin": if back == 0: dir = -self.kiki.getH() / 360 * 2 * np.pi else: dir = -self.kiki.getH() / 360 * 2 * np.pi - np.pi else: dir = 0 if back == 1: dir = pi if side == -1: dir = pi / 2 if side == 1: dir = 3 * pi / 2 prop = [ self.kiki.getPos()[0] - 25 * np.sin(dir) * dt, self.kiki.getPos()[1] - 25 * np.cos(dir) * dt ] pos = self.kiki.getPos() i, j = prop if prop[0] < -13: i = -13 if prop[0] > 13: i = 13 if prop[1] > 13: j = 13 if prop[1] < -13: j = -13 if pos[1] >= -10 and prop[1] < -10 and (prop[0] < -10 or prop[0] > 10): j = -10 if pos[1] <= 10 and prop[1] > 10 and (prop[0] < -10 or prop[0] > 10): j = 10 if pos[0] >= -10 and prop[0] < -10 and (prop[1] < -10 or prop[1] > 10): i = -10 if pos[0] <= 10 and prop[0] > 10 and (prop[1] < -10 or prop[1] > 10): i = 10 self.kiki.setPos(i, j, self.kiki.getPos()[2]) self.check_location() def check_location(self): pos = self.kiki.getPos() if pos[0] <= -10 + self.change_dist and pos[ 1] <= -10 + self.change_dist: a = 0 elif pos[0] >= 10 - self.change_dist and pos[ 1] <= -10 + self.change_dist: a = 1 elif pos[0] >= 10 - self.change_dist and pos[ 1] >= 10 - self.change_dist: a = 2 elif pos[0] <= -10 + self.change_dist and pos[ 1] >= 10 - self.change_dist: a = 3 else: if self.atbox > -1: self.presents[self.atbox].setTexture(self.texgrey) self.atbox = -1 a = -1 if a > -1: if self.atbox == -1: self.visits[self.presLoc.index(a)] += 1 self.atbox = self.presLoc.index(a) self.presents[self.atbox].setTexture(self.textures[self.atbox]) def animate(self): if self.isMoving: flipbook_2(self.kiki, self.runframe) else: self.kiki.pose("go", 0) # parameters to drag back to the beginning def drag(self): if self.dragback: # adds star to the screen if they won if self.addstar == 1: self.starimage = OnscreenImage( image='textures/goldstar.png', pos=(-1.2 + self.starLoc[self.TotalScore - 1][0] * 0.2, -0.8, -0.8 + 0.1 * self.starLoc[self.TotalScore - 1][1]), scale=0.1) self.starimage.setTransparency(TransparencyAttrib.MAlpha) self.addstar = -1 self.floater.setZ(1.0) self.dragtime += 60. / self.framerate if self.dragtime < self.time_out: pos = self.kiki.getPos() step = [ -pos[0] / (self.time_out - self.dragtime), -pos[1] / (self.time_out - self.dragtime) ] self.kiki.setPos(pos[0] + step[0], pos[1] + step[1], 1) flipbook_2( self.kiki, self.dragframe, loop=1, ) else: # here is my code to end game... # elf.LastFiveSixCount if self.reversal == 0 and self.trial_num_phase == self.end_aq_after: self.GameOver = True elif self.reversal == 1 and self.trial_num_phase == self.end_rev_after: self.GameOver = True else: self.new_trial = True self.TrialScoreList.append(self.trialscore) if len(self.TrialScoreList) >= 6: self.TrialScoreLastFiveSix = self.TrialScoreList[-6:] self.LastFiveSixCount = self.TrialScoreLastFiveSix.count(1) elif len(self.TrialScoreList) == 5: self.TrialScoreLastFiveSix = self.TrialScoreList[-5:] self.LastFiveSixCount = self.TrialScoreLastFiveSix.count(1) if self.LastFiveSixCount == 5: self.reverse_now = True print("trial number", self.trial_no) print("trial score", self.trialscore) print("total trial score list", self.TrialScoreList) print("score list for last 6 trials", self.TrialScoreLastFiveSix) print("how many correct in last 6 trials", self.LastFiveSixCount) print("reverse now", self.reverse_now) print("running total", self.RunningTotal) print("self rev after", self.revafter) # starting each trial def init_trial(self): if self.reverse_now == True and self.reversal == 0: self.reversal = 1 # need to reset all of these variables back to zero!! self.RunningTotal = 0 self.TrialScoreList = [] self.TrialScoreLastFiveSix = [] self.LastFiveSixCount = 0 self.trial_num_phase = 0 self.reverse_now = False self.correctbox = fluffle( [i for i in range(3) if i != self.correctbox])[0] self.textures[-1] = self.tex5 elif self.reverse_now == True and self.reversal == 1: self.GameOver = True # if self.RunningTotal == self.revafter and self.reversal == 0: # self.reversal = 1 # self.RunningTotal = 0 # self.trial_num_phase = 0 # self.correctbox = fluffle([i for i in range(3) if i != self.correctbox])[0] # self.textures[-1] = self.tex5 #elif self.RunningTotal == self.revafter and self.reversal == 1: # self.GameOver = True self.camspinning = 0 self.camspin = False self.render.setLightOff(self.plnp) self.new_trial = False self.boxcam = False self.go = True self.goscale = 0 self.ReadyText = OnscreenText(text="Ready...", pos=(-100, -0.5), scale=0.1 * self.goscale) self.GoText = OnscreenText(text="Go!", pos=(-100, -0.5), scale=0.1 * self.goscale) self.floater.setZ(2.0) self.spin = 0 self.dragback = False self.dragtime = 0 self.trial_no += 1 self.trial_num_phase += 1 self.trialscore = 0 self.trial = [self.correctbox] self.pos = [0., 0.] self.kiki.setPos(0, 0, 1.) self.kiki.setH(0) self.presLoc = [0, 1, 2, 3] self.canMove = True self.digging = False self.atbox = -1 self.addstar = -1 self.clouddisp = 1 self.presLoc = fluffle(self.presLoc) self.boxloca = [[-12., -12.], [12., -12.], [12., 12.], [-12., 12.]] if self.trial_no > 0: self.presents[self.dug].reparentTo(self.render) self.dug = -1 for pres, loc in zip(self.presents, self.presLoc): pres.setPos(self.boxloca[loc][0], self.boxloca[loc][1], 2.1) pres.setTexture(self.texgrey) if self.boxloca[loc][1] == -12: pres.setH(180) else: pres.setH(0) pres.currentframe = 0 pres.pose("go", 0) self.visits = [0, 0, 0, 0] # setting the keys for moving the character and digging def initkeys(self): self.keyMap = { "left": 0, "right": 0, "forward": 0, "back": 0, "dig": 0, "spin": 0 } self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["back", True]) self.accept("d", self.setKey, ["dig", True]) self.accept("y", self.setKey, ["spin", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["back", False]) self.accept("d-up", self.setKey, ["dig", False]) self.accept("y-up", self.setKey, ["spin", False]) def setKey(self, key, value): self.keyMap[key] = value def initgame(self): self.transition = Transitions(loader) self.getparameters() self.GameOver = False self.BlackScreen = 0 self.p_ID = self.b.get() self.p_age = self.d.get() self.p_gender = self.f.get() self.file = open( 'logs/Reversal3D_end30_5of6_logfile_' + str(self.p_ID) + '.txt', 'w') # added two extra columns to the log file self.file.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t" % ("pID", "Age", "Gender", "TrialNumber", "Reversal", "Target", "Choice", "Correct", "TotalScore", "RunningTotal", "Last6TrialsTotal", "TrialNumPhase", "Visits0", "Visits1", "Visits2", "Visits3", "ResponseTime", "Date", "CurrentTime")) self.file.close() print "ID:", self.p_ID, "Gender:", self.p_gender, "Age:", self.p_age print "ID:", self.p_ID, "Gender:", self.p_gender, "Age:", self.p_age self.rungame = True self.TotalScore = 0 self.RunningTotal = 0 self.trial_no = -1 self.new_trial = True self.end_aq_after = 30 self.end_rev_after = 30 self.trial_num_phase = 0 self.reverse_now = False self.TrialScoreList = [] self.TrialScoreLastFiveSix = [] self.LastFiveSixCount = 0 # when starting a new trial, pick gender and kiki parameters self.new_trial = True if self.p_gender == "Male": self.kiki = CreateActor("Models/baseboy.x", "textures/baseboy2.png", 0, 0, 0, 0) else: self.kiki = CreateActor("Models/kiki.x", "textures/kiki.jpg", 0, 0, 0, 0) self.kiki.currentframe = 0 self.kiki.reparentTo(self.render) self.isTurning = False self.lag = 0 self.ScoreText = None # how often screen refreshes self.framerate = 30 globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(self.framerate) self.frames = [ int(round(i)) for i in np.arange(0, 1200, 60. / self.framerate) ] # creating the boxes self.present1 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present1.reparentTo(self.render) self.present2 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present2.reparentTo(self.render) self.present3 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present3.reparentTo(self.render) self.present4 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present4.reparentTo(self.render) self.presents = [ self.present1, self.present2, self.present3, self.present4 ] self.texgrey = loader.loadTexture("textures/presentgrey.png") if self.boxcol == "A": self.tex1 = loader.loadTexture("textures/presentblue.png") self.tex2 = loader.loadTexture("textures/presentyellow.jpg") self.tex3 = loader.loadTexture("textures/presentpink.jpg") self.tex4 = loader.loadTexture("textures/presentgreen.png") self.tex5 = loader.loadTexture("textures/presentpurple.png") else: self.tex1 = loader.loadTexture("textures/presentbrown.jpg") self.tex2 = loader.loadTexture("textures/presentorange.png") self.tex3 = loader.loadTexture("textures/presentred.png") self.tex4 = loader.loadTexture("textures/presentgreys.png") self.tex5 = loader.loadTexture("textures/presentlightpurple.png") self.textures = [self.tex1, self.tex2, self.tex3, self.tex4] # making the star and positions self.star = self.loader.loadModel("Models/star.x") tex = loader.loadTexture("textures/gold_texture.jpg") self.star.setTexture(tex) self.star.setScale(self.starsize) self.star.setPos(0, 0, 3) # making the black cloud and their positions self.clouds = CreateActor("Models/clouds.x", "textures/cotton.jpg", 0, 0, 0, 0) self.star.setScale(self.cloudsize) # setting up the room environment self.environ = self.loader.loadModel("Models/Room.x") self.environ.reparentTo(self.render) # setting the wall colors - note that Reversal task uses set "A" and # practice task uses set B if self.wallcol == "A": tex = loader.loadTexture("textures/arena.png") else: # set B tex = loader.loadTexture("textures/room2.png") self.environ.setTexture(tex) self.environ.setScale(2, 2, 2) self.environ.setPos(0, 0, 0) self.starLoc = [] for i in range(4): for j in range(10): self.starLoc.append([i, j]) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.kiki) self.floater.setZ(2.0) self.angle = -2 * np.pi * self.kiki.getH() / 360 alight = AmbientLight('alight') alight.setColor(VBase4(2, 2, 2, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0, 0, 0, 0)) self.plnp = render.attachNewNode(self.plight) #animation frames: self.runframe = get_frames(1, 40, self.framerate) self.digframe = get_frames(60, 240, self.framerate) self.presentsframe = get_frames(0, 180, self.framerate) self.winframe = get_frames(320, 360, self.framerate) self.losingframe = get_frames(380, 460, self.framerate) self.dragframe = get_frames(242, 302, self.framerate) self.cloudsframe = get_frames(0, 180, self.framerate) # this is the new way to randomize the correct box for each subject # this will also reset for reversal self.correctbox = fluffle([0, 1, 2])[0] #np.random.randint(0,3) self.reversal = 0 self.savelog = False # we don't have the joystick version # will always print error in console # self.joystickon = 0 # # try: # if joystick.get_count() > 0: # self.joystickon = 1 # self.joystick = joystick.Joystick(0) # self.joystick.init() # except: # print "Joystick Error" # self.joystickon = 0 # parameters from the menu.py GUI # can change any of these manually via the gui # note that we are using # view height 60 for distance # rev after 5 trials # neg feedback of smoke puff # box color A for reversal task, B for practice # wall colors A for reversal task, B for practice # spin is OFF for this task! def getparameters(self): with open("parameters.txt", 'r') as f: params = [x.strip().split('\t') for x in f] self.viewheight = int(params[1][1]) self.change_dist = float(params[3][1]) self.time_out = float(params[4][1]) self.revafter = int(params[2][1]) self.outof = int(params[12][1]) self.negfeedbac = {"Smoke-puff": 1, "None": 0}[params[5][1]] sizes = {"Small": 0.5, "Medium": 1, "Large": 2} self.cloudsize = sizes[params[7][1]] self.starsize = sizes[params[6][1]] self.boxcol = params[8][1] self.wallcol = params[9][1] self.camRot = params[10][1] self.LRSpin = params[11][1] # this is for moving the camera to follow the character around # note that we have spin turned off. def movecam(self): if self.camspin: self.camspinning += 1. / 10 self.camera.setPos( self.kiki.getX() + (10 * np.sin(self.angle + self.camspinning)), self.kiki.getY() + 10 * np.cos(self.angle + self.camspinning), self.viewheight) self.camera.lookAt(self.floater) elif self.camRot == "On": if self.isTurning: self.lag = 0.9 elif self.lag > 0: self.lag -= (0.01) * (60. / self.framerate) else: self.lag = 0 newangle = -2 * np.pi * self.kiki.getH() / 360 self.angle = newangle + (self.angle - newangle) * self.lag self.camera.setPos(self.kiki.getX() + (10 * np.sin(self.angle)), self.kiki.getY() + 10 * np.cos(self.angle), self.viewheight) i = self.camera.getPos()[0] j = self.camera.getPos()[1] if self.viewheight < 39: if self.camera.getPos()[0] > 13: i = 13 if self.camera.getPos()[0] < -13: i = -13 if self.camera.getPos()[1] > 13: j = 13 if self.camera.getPos()[1] < -13: j = -13 self.camera.setPos(i, j, self.camera.getPos()[2]) if self.boxcam == False: self.camera.lookAt(self.floater) else: self.camera.setPos( self.kiki.getX() + (10 * np.sin(self.angle)), self.kiki.getY() + 10 * np.cos(self.angle), self.viewheight) i = self.camera.getPos()[0] j = self.camera.getPos()[1] if self.camera.getPos()[0] > 13: i = 13 if self.camera.getPos()[0] < -13: i = -13 if self.camera.getPos()[1] > 13: j = 13 if self.camera.getPos()[1] < -13: j = -13 self.camera.setPos(i, j, self.camera.getPos()[2]) self.floater.setZ(2 + self.spin / 300.) self.camera.lookAt(self.floater) else: self.camera.setPos(self.kiki.getX(), self.kiki.getY() + 0.1, self.viewheight) self.camera.lookAt(self.floater) def seconds(self, secs): return secs * self.framerate
class Game(object): def __init__(self, m): """ :param m: Menu """ self.levelName = "tutorial" self.gameState = '' m.game = self self.menu = m self.initCollision() self.loadScene() self.initPlayer() base.accept("escape", self.pauseGame) base.disableMouse() props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) self.mutableMap = {} self.glowFilter() self.initMania() self.finalcard.reparentTo(hidden) self.initBag() self.menu.loadState = True # self.menu.passFrame.show() # self.node.erosionFrame.show() # self.node.currentItemFrame.show() # taskMgr.add(self.waitOne, "waitOne") self.maniaSound = loader.loadSfx("res/sounds/Darkness3.mp3") self.setupskillpattern() self.SetLight() if not self.menu.skipUseless: self.initVideo() self.attachControls() self.IgnoreControls() def IgnoreControls(self): for name in self.keyEven: base.ignore(name) print base.getAllAccepting() def attachControls(self): self.keyEven = ["tab", 'escape', 'b', 'space'] base.accept('b', self.openBag) base.accept("tab", self.toggleGlow) base.accept("escape", self.pauseGame) base.accept('space', self.mania) def initVideo(self): self.node.endTask() media_file = "res/videos/begining.avi" self.tex = MovieTexture("preVideo") success = self.tex.read(media_file) assert success, "Failed to load video!" cm = CardMaker("preVideo Card") # cm.setFrameFullscreenQuad() # cm.setFrame(-1.3, 1.3, -1, 1) cm.setFrame(-1.2, 1.2, -.95, .95) # Tell the CardMaker to create texture coordinates that take into # account the padding region of the texture. cm.setUvRange(self.tex) self.card = NodePath(cm.generate()) self.card.reparentTo(base.render2d) self.card.setTexture(self.tex) self.videoSound = loader.loadSfx(media_file) self.tex.synchronizeTo(self.videoSound) self.videoSound.play() taskMgr.add(self.playVideo, 'playGameVideo') def playVideo(self, task): if self.videoSound.status() != AudioSound.PLAYING: self.videoSound.stop() self.menu.soundMgr.setMusicVolume(0) self.menu.musicVolume = 0 self.card.hide() # self.menu.soundMgr.playMusic('bgm1.mp3') self.menu.passFrame.show() self.node.erosionFrame.show() self.node.currentItemFrame.show() taskMgr.add(self.waitOne, "waitOne") self.attachControls() self.node.initTask() return task.done return task.cont def waitOne(self, task): if task.time < 2: self.menu.passFrame['frameColor'] = (0, 0, 0, 1 - task.time) return task.cont self.menu.passFrame['frameColor'] = (0, 0, 0, 0) self.menu.passFrame.hide() self.beginPlot() return task.done def beginPlot(self): self.menu.tutorialDialog.show() props = WindowProperties() props.setCursorHidden(False) base.win.requestProperties(props) self.node.endTask() self.nextPlot(0) def nextPlot(self, index): if index == 1 or index == 0: self.menu.nextButton['text'] = self.node.mission.plotText[0][index] self.menu.nextButton['command'] = self.nextPlot self.menu.nextButton['extraArgs'] = [index + 1] elif index == 2: self.menu.ocanioButton['text'] = self.node.mission.plotText[0][ index] self.menu.ocanioButton['command'] = self.nextPlot self.menu.ocanioButton['extraArgs'] = [index + 1] self.menu.tutorialDialog.hide() self.menu.ocanioDialog.show() elif index == 3: self.menu.nextButton['text'] = self.node.mission.plotText[0][index] self.menu.nextButton['command'] = self.node.mission.hideTutorial self.menu.nextButton['extraArgs'] = [] self.menu.tutorialDialog.show() self.menu.ocanioDialog.hide() def initBag(self): self.bagState = True self.bagText = "" self.node.bag = Bag(self.node) base.accept("b", self.openBag) def openBag(self): # print 'b' if self.bagState: self.node.bag.bagframe.show() self.node.bag.showdisplay.setActive(True) self.node.bag.textObject.setText(self.bagText) self.bagState = not self.bagState props = WindowProperties() props.setCursorHidden(False) base.win.requestProperties(props) self.menu.selectDialog.hide() self.gameState = 'pause' self.node.state = 'pause' self.node.endTask() base.accept('escape', self.openBag) else: self.node.bag.bagframe.hide() self.node.bag.showdisplay.setActive(False) self.bagText = self.node.bag.textObject.getText() self.node.bag.textObject.setText("") self.node.bag.textObject.setWordwrap(0) self.bagState = not self.bagState props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) self.gameState = '' self.node.state = '' self.node.initTask() base.accept('escape', self.pauseGame) # threading.currentThread().join('gameThread') def initCollision(self): """ create the collision system """ base.cTrav = CollisionTraverser() base.pusher = CollisionHandlerPusher() base.cTrav.setRespectPrevTransform(True) def loadScene(self): """ load the self.sceneModel must have <Group> *something* { <Collide> { Polyset keep descend } in the egg file """ self.goodmanager = GoodsManager() # AddGoods(self,Node,CollisionName,Name,Interactive) # self.goodmanager.AddGoods(loader.loadModel('res/models/Scene3/Scene3_Ver3.0.egg'), ["Wall1", "Wall2", "floor"], # # "wall", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver7.0_wall.egg'), ["Wall1", "Wall2", "floor"], "wall", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_bed_2.egg'), ["bed_box"], "bed_box", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_bookshelf.egg'), ["bookshelf_box"], "bookshelf_box", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_box.egg'), ["box"], "box", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_light.egg'), ["light"], "light", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_chair1.egg'), ["chair1"], "chair1", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_chair2.egg'), ["chair2"], "chair2", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_chair3.egg'), ["chair3"], "chair3", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_chair4.egg'), ["chair4"], "chair4", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_desk2.egg'), ["desk2"], "desk2", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_desk3.egg'), ["desk3_2"], "desk3_2", False) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_matong.egg'), ["matong_box3"], "matong_box3", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_xishoupen.egg'), ["xishoupen"], "xishoupen", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Ver6.0_yaoshui.egg'), ["yaoshui"], "yaoshui", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_Exit.egg'), ["Scene1_Exit"], "Scene1_Exit", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_wallword_1.egg'), ["Scene1_wallword_1"], "Scene1_wallword_1", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_wallword_2.egg'), ["Scene1_wallword_2"], "Scene1_wallword_2", True) self.goodmanager.AddGoods( loader.loadModel('res/models/Scene1_MusicBox.egg'), ["MusicBox"], "MusicBox", True) self.goodmanager.GoodsIta["toilet_door"] = Door( Vec3(305, -762.5, 100), "toilet_door", 'res/models/Scene1_Ver6.0_toilet_door.egg', 0, Door.In) self.goodmanager.GoodsIta["yaoshui"].Node.setPos(0, -350, 0) self.goodmanager.GoodsIta['MusicBox'].Node.setPos(400, 200, 90) self.goodmanager.GoodsIta['MusicBox'].Node.setHpr(-90, 0, 0) self.goodmanager.GoodsIta['MusicBox'].Node.setScale(1.5) def itemCollision(self, model, name, radius): nodePath = NodePath(name) node = CollisionNode(name) node.addSolid(CollisionSphere(20, 0, radius, radius)) solid = model.attachNewNode(node) nodePath.reparentTo(model) solid.show() base.cTrav.addCollider(solid, base.pusher) base.pusher.addCollider(solid, nodePath, base.drive.node()) def initPlayer(self): """ loads the player and creates all the controls for him""" self.node = Player(self.goodmanager, self.menu, self) # self.enemy = Enemy(self.node) self.goodmanager.GoodsIta["enemy"] = Enemy(self.node) self.goodmanager.GoodsIta["enemy"].state = 1 def pauseGame(self): props = WindowProperties() props.setCursorHidden(False) base.win.requestProperties(props) self.menu.selectDialog.hide() self.gameState = 'pause' self.node.state = 'pause' self.node.endTask() self.node.erosionFrame.hide() self.node.currentItemFrame.hide() base.accept('escape', self.escapeEvent) base.accept('b', self.menu.nothing) self.menu.pauseFrame.show() def escapeEvent(self): self.menu.pauseFrame.hide() self.node.state = '' self.node.initTask() self.node.erosionFrame.show() self.node.currentItemFrame.show() base.accept('escape', self.pauseGame) base.accept('b', self.openBag) props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) def SetLight(self): render.setLightOff() alight = AmbientLight('alight') alnp = render.attachNewNode(alight) alight.setColor(LVector4(0.1, 0.1, 0.1, 1)) #render.setLight(alnp) plight = PointLight('plight') plight.setColor(VBase4(3, 3, 3, 1)) plight.setAttenuation(Point3(0.1, 0.1, 0)) plnp = render.attachNewNode(plight) plnp.setPos(0, 0, 200) render.setLight(plnp) plight = PointLight('plight') plight.setColor(VBase4(1, 1, 1, 1)) plight.setAttenuation(Point3(0.10, 0.1, 0)) plnp = render.attachNewNode(plight) plnp.setPos(333, -900, 217) render.setLight(plnp) plight = PointLight('plight') plight.setColor(VBase4(1, 1, 1, 1)) plight.setAttenuation(Point3(0.10, 0.1, 0)) plnp = render.attachNewNode(plight) plnp.setPos((-438.104, 377.736, 400)) render.setLight(plnp) def makeFilterBuffer(self, srcbuffer, name, sort, prog): blurBuffer = base.win.makeTextureBuffer(name, 512, 512) blurBuffer.setSort(sort) blurBuffer.setClearColor(LVector4(1, 0, 0, 1)) blurCamera = base.makeCamera2d(blurBuffer) blurScene = NodePath("new Scene") blurCamera.node().setScene(blurScene) shader = loader.loadShader(prog) card = srcbuffer.getTextureCard() card.reparentTo(blurScene) card.setShader(shader) return blurBuffer def glowFilter(self): glowShader = loader.loadShader("shaders/glowShader.sha") # dlight = DirectionalLight('dlight') # alight = AmbientLight('alight') # dlnp = render.attachNewNode(dlight) # alnp = render.attachNewNode(alight) # dlight.setColor(LVector4(0.3, 0.3, 0.3, 1)) # alight.setColor(LVector4(0.8, 0.8, 0.8, 1)) # dlnp.setHpr(0, -60, 0) # render.setLight(dlnp) # render.setLight(alnp) # create the glow buffer. This buffer renders like a normal scene, # except that only the glowing materials should show up nonblack. glowBuffer = base.win.makeTextureBuffer("Glow scene", 1024, 768) glowBuffer.setSort(-3) glowBuffer.setClearColor(LVector4(0, 0, 0, 1)) # We have to attach a camera to the glow buffer. The glow camera # must have the same frustum as the main camera. As long as the aspect # ratios match, the rest will take care of itself. self.glowCamera = base.makeCamera(glowBuffer, lens=base.cam.node().getLens()) # Tell the glow camera to use the glow shader tempnode = NodePath(PandaNode("temp node")) tempnode.setShader(glowShader) self.glowCamera.node().setInitialState(tempnode.getState()) self.glowCamera.node().setCameraMask(BitMask32.bit(0)) # set up the pipeline: from glow scene to blur x to blur y to main # window. blurXBuffer = self.makeFilterBuffer(glowBuffer, "Blur X", -2, "shaders/XBlurShader.sha") blurYBuffer = self.makeFilterBuffer(blurXBuffer, "Blur Y", -1, "shaders/YBlurShader.sha") self.finalcard = blurYBuffer.getTextureCard() self.finalcard.reparentTo(render2d) Attrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_incoming_alpha) self.finalcard.setAttrib(Attrib) base.bufferViewer.setPosition("llcorner") base.bufferViewer.setLayout("hline") base.bufferViewer.setCardSize(0.652, 0) base.accept("tab", self.toggleGlow) self.glowOn = False def limitGlow(self, task): if task.time < 5: return task.cont else: self.glowOn = False self.finalcard.reparentTo(hidden) self.goodmanager.GoodsIta["box"].CloseHighLight() self.goodmanager.GoodsIta["yaoshui"].CloseHighLight() self.goodmanager.GoodsIta["MusicBox"].CloseHighLight() self.goodmanager.GoodsIta["matong_box3"].CloseHighLight() self.goodmanager.GoodsIta["Scene1_Exit"].CloseHighLight() self.goodmanager.GoodsIta["Scene1_wallword_1"].CloseHighLight() self.goodmanager.GoodsIta["Scene1_wallword_2"].CloseHighLight() self.goodmanager.GoodsIta["enemy"].CloseHighLight() self.goodmanager.GoodsIta["xishoupen"].CloseHighLight() return task.done def toggleGlow(self): self.showskillpattern("eyepattern") if self.glowOn: return self.glowOn = True taskMgr.add(self.limitGlow, "limitGlow") if self.node.EROSION + 10 > 100: self.node.EROSION = 100 else: self.node.EROSION += 10 self.toggleGlowSound = loader.loadSfx("res/sounds/Raise3.mp3") self.toggleGlowSound.play() self.finalcard.reparentTo(render2d) self.goodmanager.GoodsIta["box"].OpenHighLight() self.goodmanager.GoodsIta["yaoshui"].OpenHighLight() self.goodmanager.GoodsIta["MusicBox"].OpenHighLight() self.goodmanager.GoodsIta["matong_box3"].OpenHighLight() self.goodmanager.GoodsIta["Scene1_Exit"].OpenHighLight() self.goodmanager.GoodsIta["Scene1_wallword_1"].OpenHighLight() self.goodmanager.GoodsIta["Scene1_wallword_2"].OpenHighLight() self.goodmanager.GoodsIta["enemy"].OpenHighLight() self.goodmanager.GoodsIta["xishoupen"].OpenHighLight() # if not self.glowOn: # self.finalcard.reparentTo(hidden) # self.goodmanager.GoodsIta["box"].CloseHighLight() # self.goodmanager.GoodsIta["yaoshui"].CloseHighLight() # self.goodmanager.GoodsIta["MusicBox"].CloseHighLight() # self.goodmanager.GoodsIta["matong_box3"].CloseHighLight() # self.goodmanager.GoodsIta["Scene1_Exit"].CloseHighLight() # self.goodmanager.GoodsIta["Scene1_wallword_1"].CloseHighLight() # self.goodmanager.GoodsIta["Scene1_wallword_2"].CloseHighLight() # self.goodmanager.GoodsIta["enemy"].CloseHighLight() # self.goodmanager.GoodsIta["xishoupen"].CloseHighLight() # else: # self.finalcard.reparentTo(render2d) # self.goodmanager.GoodsIta["box"].OpenHighLight() # self.goodmanager.GoodsIta["yaoshui"].OpenHighLight() # self.goodmanager.GoodsIta["MusicBox"].OpenHighLight() # self.goodmanager.GoodsIta["matong_box3"].OpenHighLight() # self.goodmanager.GoodsIta["Scene1_Exit"].OpenHighLight() # self.goodmanager.GoodsIta["Scene1_wallword_1"].OpenHighLight() # self.goodmanager.GoodsIta["Scene1_wallword_2"].OpenHighLight() # self.goodmanager.GoodsIta["enemy"].OpenHighLight() # self.goodmanager.GoodsIta["xishoupen"].OpenHighLight() # self.node.EROSION += 10 # #print self.goodmanager.staticGoods['wall'].Node # # self.glowOn = not (self.glowOn) def initMania(self): base.accept("space", self.mania) self.maniaState = False def mania(self): self.showskillpattern("maniapattern") if not self.maniaState: self.node.speed *= 1.4 self.maniaState = True if self.node.EROSION + 10 > 100: self.node.EROSION = 100 else: self.node.EROSION += 10 taskMgr.remove("fadeSpeed") taskMgr.add(self.fadeSpeed, "fadeSpeed") def fadeSpeed(self, task): if task.time < 10: return task.cont else: self.node.speed /= 1.4 self.maniaState = False return task.done def setupskillpattern(self): self.eyepattern = OnscreenImage(image="res/skill_icon/eye-white.png", pos=(-1.2, 1, -0.8)) self.eyepattern.setTransparency(TransparencyAttrib.MAlpha) self.eyepattern.setScale(0.1) self.eyepattern.setSa(0.8) self.eyepattern.hide() self.maniapattern = OnscreenImage( image="res/skill_icon/mania-white.png", pos=(-1.2 + 0.3, 1, -0.8)) self.maniapattern.setTransparency(TransparencyAttrib.MAlpha) self.maniapattern.setScale(0.1) self.maniapattern.setSa(0.8) self.maniapattern.hide() self.screen_patternArray = {} self.screen_patternArray["eyepattern"] = [self.eyepattern, False, 5.0] self.screen_patternArray["maniapattern"] = [ self.maniapattern, False, 5.0 ] self.patterntask = False def showskillpattern(self, patternname): self.screen_patternArray[patternname][2] = 10. self.screen_patternArray[patternname][1] = True self.screen_patternArray[patternname][0].show() if self.patterntask == False: taskMgr.add(self.showskillpatterntask, "showskillpatterntask") def showskillpatterntask(self, task): num = 0 for key in self.screen_patternArray: if self.screen_patternArray[key][1] == True: self.screen_patternArray[key][2] -= globalClock.getDt() if self.screen_patternArray[key][2] < 5.: if sin(self.screen_patternArray[key][2] * pi * 5) > 0: self.screen_patternArray[key][0].setSa(0) else: self.screen_patternArray[key][0].setSa(0.8) self.screen_patternArray[key][0].setPos( -1.2 + num * 0.3, 1, -0.8) if self.screen_patternArray[key][2] < 0: self.screen_patternArray[key][1] = False self.screen_patternArray[key][0].hide() self.screen_patternArray[key][0].setSa(0.8) num += 1 if num > 0: return task.cont self.patterntask = False return
class English(HUDElement): def __init__(self): HUDElement.__init__(self) self.dir = ani.model_dir / 'hud' / 'english' self.text_scale = 0.2 self.text_color = (1, 1, 1, 1) self.circle = OnscreenImage(image=panda_path(self.dir / 'circle.png'), parent=self.dummy_right, scale=0.15) self.circle.setTransparency(TransparencyAttrib.MAlpha) autils.alignTo(self.circle, self.dummy_right, autils.CL, autils.C) self.circle.setZ(-0.65) self.crosshairs = OnscreenImage(image=panda_path(self.dir / 'crosshairs.png'), pos=(0, 0, 0), parent=self.circle, scale=0.14) self.crosshairs.setTransparency(TransparencyAttrib.MAlpha) self.text = OnscreenText( text="(0.00, 0.00)", pos=(0, -1.15), scale=self.text_scale, fg=self.text_color, align=TextNode.ACenter, mayChange=True, parent=self.circle, ) def set(self, a, b): self.crosshairs.setPos(-a, 0, b) self.text.setText(f"({a:.2f},{b:.2f})") def init(self): self.show() def show(self): self.circle.show() def hide(self): self.circle.hide() def destroy(self): self.hide() del self.text del self.crosshairs del self.circle
class Player(object, DirectObject.DirectObject): def __init__(self): self.node = 0 #the player main node self.gnodePath = 0 #node to phisics self.gNode = 0 #node of gravity self.gNodePath = 0 #node path to actorNode self.modelNode = 0 #the node of the actual model self.cNode = 0 #the player collision node attached to node self.cNodePath = 0 #node path to cNode self.contrail = ParticleEffect( ) #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB) self.contrail.setTransparency(TransparencyAttrib.MDual) self.contrail2 = ParticleEffect( ) #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB) self.contrail2.setTransparency(TransparencyAttrib.MDual) self.landing = False self.freeLook = False self.speed = 10 self.speedMax = 100 self.agility = 3 self.HP = 10 self.collisionHandler = CollisionHandlerEvent( ) # the collision handlers self.collisionHandlerQueue = CollisionHandlerQueue() self.zoom = -5 #self self.textSpeed = OnscreenText(text='Speed: ' + str(self.speed), pos=(-1.34, 0.95), scale=0.07, fg=(1, 1, 1, 1), bg=(0.2, 0.2, 0.2, 0.4), align=TextNode.ALeft) self.textHP = OnscreenText(text='Health: ' + str(self.HP), pos=(-1.33, 0.85), scale=0.07, fg=(1, 1, 1, 1), bg=(0.2, 0.2, 0.2, 0.4), align=TextNode.ALeft) self.roll = 0 self.camHeight = 0 base.win.movePointer(0, base.win.getXSize() / 2, base.win.getYSize() / 2) self.myImage = OnscreenImage(image='cursor.png', pos=(0, 0, -0.02), scale=(0.05)) self.myImage.setTransparency(TransparencyAttrib.MAlpha) self.loadModel() self.addCamera() self.addEvents() self.addCollisions() self.addSound() self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task') self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task') ''' loadModel This will load all the visible stuff ''' def loadModel(self): """ make the nodepath for player """ self.node = NodePath('player') self.node.setPos(1000, 1000, 200) self.node.reparentTo(render) self.node.lookAt(0, 0, 200) self.modelNode = loader.loadModel('griffin') self.modelNode.reparentTo(self.node) self.modelNode.setScale(0.3) playerMaterial = Material() playerMaterial.setShininess(22.0) #Make this material shiny playerMaterial.setAmbient(VBase4(1, 1, 1, 1)) playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7)) self.modelNode.setMaterial(playerMaterial) self.modelNode.setShaderAuto() self.aimNode = NodePath('aimNode') self.aimNode.reparentTo(self.node) self.aimNode.setPos(0, 15, 2) #self.contrail.loadConfig('media/contrail.ptf') #self.contrail.start(self.node,render) #gravity (aceleration 9.82) self.gravityFN = ForceNode('world-forces') self.gravityFNP = render.attachNewNode(self.gravityFN) self.gravityForce = LinearVectorForce(0, 0, -9.82) self.gravityFN.addForce(self.gravityForce) #add gravity to engine #base.physicsMgr.addLinerForce(self.gravityForce) #Physics node self.gnodePath = NodePath(PandaNode("physics")) self.gNode = ActorNode("plane-actornode") self.gNodePath = self.gnodePath.attachNewNode(self.gNode) #object weigth self.gNode.getPhysicsObject().setMass(0.004) #add gravity force base.physicsMgr.addLinearForce(self.gravityForce) base.physicsMgr.attachPhysicalNode(self.gNode) #render object with physics self.gnodePath.reparentTo(render) self.node.reparentTo(self.gNodePath) ''' addCamera camera setup ''' def addCamera(self): base.disableMouse() base.camera.reparentTo(self.node) base.camera.setPos(0, self.zoom, 2) base.camera.lookAt(self.aimNode) ''' addEvents This will set up the events the class will accept ''' def addEvents(self): self.accept("wheel_up", self.evtSpeedUp) self.accept("wheel_down", self.evtSpeedDown) self.accept('hit', self.evtHit) self.accept('l', self.evtLand) self.accept('o', self.evtStart) self.accept('f', self.evtFreeLookON) self.accept('f-up', self.evtFreeLookOFF) self.accept('mouse3', self.evtBoostOn) self.accept("menuOpen", self.evtMenuOpen) self.accept("menuClosed", self.evtMenuClose) ''' addCollisions This will add a collision sphere for the player and a segment to check weather the ground is close/flat enough for landing ''' def addCollisions(self): self.cNode = CollisionNode('player') self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3)) self.cNode.setFromCollideMask(BitMask32(0x1A)) self.cNode.setIntoCollideMask(BitMask32(0x4)) self.cNodePath = self.node.attachNewNode(self.cNode) #self.cNodePath.show() self.collisionHandler.addInPattern('hit') base.cTrav.addCollider(self.cNodePath, self.collisionHandler) # landing segment: self.landingCNodeSegment = CollisionNode('playerRay') self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20)) self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff()) self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8)) self.landingCNodeSegmentPath = self.node.attachNewNode( self.landingCNodeSegment) #self.landingCNodeSegmentPath.show() base.cTrav.addCollider(self.landingCNodeSegmentPath, self.collisionHandlerQueue) ''' addSound adds the engine sound @TODO add more ''' def addSound(self): self.engineSound = loader.loadSfx("engine.mp3") self.engineSound.setLoop(True) self.engineSound.play() self.engineSound.setVolume(2.0) self.engineSound.setPlayRate(0) ''' deleteTask task which calls the destructor after a given time (after the explosion animation) ''' def deleteTask(self, task): self.__del__() return task.done ''' mouseUpdateTask This task will handle mouse movement and control the planes rotation. If free look is enabled, it will rotate the camera around the player. ''' def mouseUpdateTask(self, task): """ this task updates the mouse """ md = base.win.getPointer(0) x = md.getX() y = md.getY() deltaX = 0 deltaY = 0 if base.win.movePointer(0, base.win.getXSize() / 2, base.win.getYSize() / 2): deltaX = ( x - base.win.getXSize() / 2 ) * 0.06 #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50) deltaY = (y - base.win.getYSize() / 2) * 0.06 if deltaX > self.agility: deltaX = self.agility if deltaX < -self.agility: deltaX = -self.agility if deltaY > self.agility: deltaY = self.agility if deltaY < -self.agility: deltaY = -self.agility # don't move ship while in freelook mode if not self.freeLook: self.node.setH(self.node.getH() - deltaX) self.node.setP(self.node.getP() - deltaY) # don't move ship while in freelook mode if not self.freeLook: self.roll += deltaX self.camHeight += deltaY self.roll *= 0.95 #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700 self.camHeight *= 0.95 #* globalClock.getDt() * 700 if self.roll < -25 * self.speed / self.speedMax: self.roll = -25 * self.speed / self.speedMax if self.roll > 25 * self.speed / self.speedMax: self.roll = 25 * self.speed / self.speedMax self.node.setR(self.roll * 3) base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax) base.camera.lookAt(self.aimNode) base.camera.setR(-self.roll * 2) #base.camera.setY(-30+self.speed/10) #base.camera.setX(self.roll*0.5) # freelook mode: if self.freeLook: self.camRotH -= deltaX * 3 self.camRotV -= deltaY * 3 if self.camRotV < 1: self.camRotV = 1 if self.camRotV > 179: self.camRotV = 179 base.camera.setX( math.cos(math.radians(self.camRotH)) * math.sin(math.radians(self.camRotV)) * 30) base.camera.setY( math.sin(math.radians(self.camRotH)) * math.sin(math.radians(self.camRotV)) * 30) base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30) base.camera.lookAt(self.node) return task.cont ''' moveUpdateTask Will update players position depending on speed and direction ''' def moveUpdateTask(self, task): """ this task makes the player move """ # move where the keys set it self.node.setPos(self.node, Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0)) #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed) return task.cont def landTask(self, task): if self.collisionHandlerQueue.getNumEntries() == 0 and task.frame > 3: print 'to faar' self.landing = False self.evtFreeLookOFF() return task.done elif self.collisionHandlerQueue.getNumEntries() == 0: return task.cont self.collisionHandlerQueue.sortEntries() entry = self.collisionHandlerQueue.getEntry(0) if entry.getInto != self.cNode: n = entry.getSurfaceNormal(render) n.normalize() if n.getZ() < 0.8: print 'too steep' self.landing = False self.evtFreeLookOFF() return task.done self.cNode.setFromCollideMask(BitMask32(0x0)) self.cNode.setIntoCollideMask(BitMask32(0x0)) self.node.setZ(self.node.getZ() - 0.05) if entry.getSurfacePoint(self.node).getZ() > -0.5: #self.landing = tr #self.evtFreeLookOFF() return task.done return task.cont def startTask(self, task): self.collisionHandlerQueue.sortEntries() entry = self.collisionHandlerQueue.getEntry(0) self.node.setZ(self.node.getZ() + 0.05) if entry.getSurfacePoint(self.node).getZ() < -10: self.landing = False self.evtFreeLookOFF() self.cNode.setFromCollideMask(BitMask32(0x18)) self.cNode.setIntoCollideMask(BitMask32(0x4)) return task.done return task.cont ''' explode this will cause the plane to explode with a nice particle effect. ''' def explode(self): self.ignoreAll() self.cNode.setIntoCollideMask(BitMask32.allOff()) taskMgr.remove(self.moveTask) taskMgr.remove(self.mouseTask) taskMgr.remove(self.zoomTaskPointer) self.moveTask = 0 self.mouseTask = 0 if self.contrail != 0: self.contrail.cleanup() self.modelNode.hide() self.contrail = ParticleEffect() self.contrail.loadConfig('media/explosion.ptf') self.contrail.start(self.node) self.contrail.setLightOff() self.contrail2.cleanup() self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask, 'delete task') ''' zoomTask will adjust camera position according to zoom factor specified in self.zoom in a smooth way. ''' def zoomTask(self, task): if base.camera.getY() != self.zoom and self.freeLook == False: base.camera.setY(base.camera.getY() + (self.zoom - base.camera.getY()) * globalClock.getDt() * 2) return task.cont ''' evtBoostOn Will set most inputs to ignore, add a speed boost and an additional particle effect ''' def evtBoostOn(self): taskMgr.remove(self.mouseTask) self.ignore("wheel_up") self.ignore("wheel_down") self.ignore('mouse1') self.ignore('l') self.ignore('o') self.ignore('f') self.ignore('f-up') self.accept('mouse3-up', self.evtBoostOff) self.speed += 200 self.textSpeed.setText('Speed: ' + str(self.speed)) self.contrail2.loadConfig('media/contrail-boost.ptf') self.contrail2.start(self.node) self.zoom = -25 self.evtFreeLookOFF() ''' evtBoostOff Will reactivate inputs, substract speed boost and stop the additional particle effect ''' def evtBoostOff(self): self.speed -= 200 self.textSpeed.setText('Speed: ' + str(self.speed)) self.ignore('mouse3-up') self.addEvents() self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') #self.contrail.loadConfig('../../media/contrail.ptf') self.contrail2.softStop() self.zoom = -5 - (self.speed / 10) ''' evtHit This event will be called if the player gets hit by an object. It will reduce the HP by 1 each time we hit a missile. If HP reaches 0, the player will explode. If we hit an other object like a rock, the player will explode imidiatly ''' def evtHit(self, entry): if entry.getIntoNodePath().getParent().getTag( "orign") != self.node.getName(): #if entry.getIntoNodePath().getName() == "projectile": #self.HP -= 1 #self.textHP.setText('HP : '+str(self.HP)) if self.HP == 0: self.explode() else: self.explode() ''' evtFreeLookON Event that activates free look mode and therefore changes cam position ''' def evtFreeLookON(self): if self.landing == False: self.freeLook = True self.camRotH = 270 self.camRotV = 80 self.myImage.hide() ''' evtFreeLookOFF Event that deactivates free look mode and therefore changes cam position back to original ''' def evtFreeLookOFF(self): if self.landing == False: self.freeLook = False base.camera.setPos(0, -20, 2) base.camera.lookAt(self.aimNode) self.myImage.show() ''' __del__ destructor will remove particle effect, tasks and the whole node ''' def __del__(self): self.ignoreAll() self.contrail.cleanup() base.camera.reparentTo(render) base.camera.setPos(2000, 2000, 800) base.camera.lookAt(0, 0, 0) if self.moveTask != 0: taskMgr.remove(self.moveTask) if self.mouseTask != 0: taskMgr.remove(self.mouseTask) self.node.removeNode() messenger.send('player-death') ''' evtSpeedUp Will be called if player wants to increase speed. - engine sound will become louder - camera will zoom out - speed display will be updated ''' def evtSpeedUp(self): if self.landing: return 0 self.speed += 5 self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05) if self.speed > self.speedMax: self.speed = self.speedMax #self.engineSound.setVolume(1) self.engineSound.setPlayRate(1) self.zoom = -5 - (self.speed / 10) self.textSpeed.setText('Speed: ' + str(self.speed)) ''' evtSpeedDown Will be called if player wants to decrease speed. - engine sound will become more silent - camera will zoom in - speed display will be updated ''' def evtSpeedDown(self): if self.landing: return 0 self.textSpeed.setText('Speed: ' + str(self.speed)) self.speed -= 5 self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05) if self.speed < 0: self.speed = 0 #self.engineSound.setVolume(0) self.engineSound.setPlayRate(0) self.zoom = -5 - (self.speed / 10) def evtLand(self): if self.speed != 0 or self.landing: return 0 self.evtFreeLookON() # landing will enable freelook mode self.landing = True self.node.setP(0) taskMgr.add(self.landTask, 'land-task') def evtStart(self): if not self.landing: return 0 taskMgr.add(self.startTask, 'start-task') def evtMenuOpen(self): """event that will be called if main menu is opened (esc)""" taskMgr.remove(self.mouseTask) taskMgr.remove(self.moveTask) self.myImage.hide() props = WindowProperties() props.setCursorHidden(0) base.win.requestProperties(props) def evtMenuClose(self): """event that will be called if main menu is closed (esc)""" #self.addEvents() props = WindowProperties() props.setCursorHidden(1) base.win.requestProperties(props) self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task') self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task') self.myImage.show()
class Dashboard(DirectObject): def __init__(self, character, taskMgr): self.font_digital = loader.loadFont( 'models/font/SFDigitalReadout-Heavy.ttf') self.total_players = 30 self.rank = 21 self.main_char = character self.speed = "0.0 km/h" self.start_time = datetime.datetime.now() self.time_elapsed = datetime.timedelta(milliseconds=0) self.countdown_time = datetime.timedelta(minutes=8) # insert total time self.game_time = self.countdown_time - self.time_elapsed # print self.game_time # Timer self.display_timer = OnscreenText(text=str(self.game_time), style=1, fg=(1, 1, 1, 1), pos=(0, .9), scale=.1, font=self.font_digital) # Mini-Map self.mini_map = OnscreenImage(image="models/dashb/minimap.png", scale=.15, pos=(-1.15, 0, .8)) self.mini_map.setTransparency(TransparencyAttrib.MAlpha) # Speedometer self.speed_img = OnscreenImage(image="models/dashb/speedometer.png", scale=.5, pos=(1.1, 0, -.95)) self.speed_img.setTransparency(TransparencyAttrib.MAlpha) OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1), font=self.font_digital, scale=.07, pos=(1.25, -.92)) # Your Rank OnscreenText(text="Rank", style=1, fg=(1, 1, 1, 1), pos=(-.9, .89), align=TextNode.ALeft, font=self.font_digital, scale=.06) rank = str(self.rank) + "/" + str(self.total_players) self.display_rank = OnscreenText(text=rank, style=1, fg=(1, 1, 1, 1), pos=(-.8, .85), align=TextNode.ALeft, scale=.15, font=self.font_digital) OnscreenText(text="Players\nLeft", style=1, fg=(1, 1, 1, 1), pos=(-.5, .89), align=TextNode.ALeft, font=self.font_digital, scale=.06) # Leaderboard Ranking self.leader1 = OnscreenText(text="1:", style=1, fg=(1, 1, 1, 1), pos=(-1.3, .5), align=TextNode.ALeft, scale=.07, font=self.font_digital) self.leader2 = OnscreenText(text="2:", style=1, fg=(1, 1, 1, 1), pos=(-1.3, .45), align=TextNode.ALeft, scale=.07, font=self.font_digital) self.leader3 = OnscreenText(text="3:", style=1, fg=(1, 1, 1, 1), pos=(-1.3, .4), align=TextNode.ALeft, scale=.07, font=self.font_digital) # Power-ups OnscreenText(text="1", style=1, fg=(1, 1, 1, 1), pos=(-1.25, -.95), scale=.07) OnscreenText(text="2", style=1, fg=(1, 1, 1, 1), pos=(-1.15, -.95), scale=.07) OnscreenText(text="3", style=1, fg=(1, 1, 1, 1), pos=(-1.05, -.95), scale=.07) self.power1 = OnscreenImage(image='models/power_ups/pow1.png', pos=(-1.25, 0, -0.85), scale=.05) self.power2 = OnscreenImage(image='models/power_ups/pow2.png', pos=(-1.15, 0, -0.85), scale=.05) self.power3 = OnscreenImage(image='models/power_ups/pow3.png', pos=(-1.05, 0, -0.85), scale=.05) # Display Speed self.display_speed = OnscreenText(text=self.speed, style=1, fg=(1, 1, 1, 1), pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital) taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed') taskMgr.doMethodLater(.1, self.show_timer, 'updateTimer') taskMgr.doMethodLater(.1, self.update_rank, 'updateRank') def show_speed(self, task): self.speed = str( format(self.main_char.vehicle.getCurrentSpeedKmHour(), '0.2f')) # print self.speed # Update Speed Display self.display_speed.destroy() self.display_speed = OnscreenText(text=self.speed, style=3, fg=(1, 1, 1, 1), pos=(1.2, -0.95), align=TextNode.ARight, scale=.15, font=self.font_digital) return task.cont def show_timer(self, task): self.time_elapsed = datetime.datetime.now() - self.start_time game_time = str(self.countdown_time - self.time_elapsed)[2:11] self.display_timer.destroy() self.display_timer = OnscreenText(text=game_time, style=3, fg=(1, 1, 1, 1), pos=(0, .9), scale=.15, font=self.font_digital) return task.cont # server updates client time in ms def force_timer(self, server_time): self.start_time = datetime.datetime.now() self.countdown_time = datetime.timedelta(milliseconds=server_time) def update_rank(self, task): self.display_rank.destroy() # Your Rank rank = str(self.rank) + "/" + str(self.total_players) self.display_rank = OnscreenText(text=rank, style=1, fg=(1, 1, 1, 1), pos=(-.8, .85), align=TextNode.ALeft, scale=.15, font=self.font_digital) # Leader board self.leader1.destroy() self.leader2.destroy() self.leader3.destroy() lead1 = "1:" lead2 = "2:" lead3 = "3:" self.leader1 = OnscreenText(text=lead1, style=1, fg=(1, 1, 1, 1), pos=(-1.3, .5), align=TextNode.ALeft, scale=.07, font=self.font_digital) self.leader2 = OnscreenText(text=lead2, style=1, fg=(1, 1, 1, 1), pos=(-1.3, .45), align=TextNode.ALeft, scale=.07, font=self.font_digital) self.leader3 = OnscreenText(text=lead3, style=1, fg=(1, 1, 1, 1), pos=(-1.3, .4), align=TextNode.ALeft, scale=.07, font=self.font_digital) return task.cont
def construct_scene(lbase, modelpath, bgpath, scale, pos, hpr, bgscale, bghp, texture=None, internal_canonical=False, check_penetration=False, light_spec=None, use_envmap=False, shader=None, world_coords=False): """ Constructs the scene per the parameters. """ # Default scene is lbase's rootnode if bgpath is not None: bgpath = mt.resolve_bg_path(bgpath) rootnode = lbase.rootnode # Modelpath points to the model .egg/.bam file if isstring(modelpath): modelpaths = [modelpath] scales = [scale] poses = [pos] hprs = [hpr] textures = [texture] else: modelpaths = modelpath scales = scale poses = pos hprs = hpr textures = texture texmodes = [] for _i, _t in enumerate(textures): if isinstance(_t, tuple): texfile, texmode = _t texmodes.append(texmode) textures[_i] = texfile else: texmodes.append(TexGenAttrib.MWorldNormal) assert hasattr(modelpaths, '__iter__') assert hasattr(scales, '__iter__') assert hasattr(poses, '__iter__') assert hasattr(hprs, '__iter__') assert hasattr(textures, '__iter__') assert len(modelpaths) == len(scales) == len(hprs) == len(poses) == len( textures), (len(modelpaths), len(scales), len(hprs), len(poses), len(textures)) modelpaths = map(mt.resolve_model_path, modelpaths) modelpaths = map(cm.autogen_egg, modelpaths) textures = map(mt.resolve_texture_path, textures) objnodes = [] for mpth, scale, hpr, pos, t, tm in zip(modelpaths, scales, hprs, poses, textures, texmodes): objnode = tools.read_file(lbase.loader.loadModel, mpth) if t is not None: #ts = TextureStage('ts') ts = TextureStage.get_default() ts.setMode(TextureStage.MReplace) tex = tools.read_file(lbase.loader.loadTexture, t) objnode.setTexGen(ts, tm) objnode.setTexture(tex, 6) robjnode = rootnode.attachNewNode('root_' + objnode.get_name()) objnode.reparentTo(robjnode) if internal_canonical: vertices = np.array(objnode.getTightBounds()) initial_scale_factor = max(abs(vertices[0] - vertices[1])) cscale = 1.2 / initial_scale_factor ppos = vertices.mean(0) * cscale objnode.setPos(-ppos[0], -ppos[1], -ppos[2]) objnode.setScale(cscale, cscale, cscale) if world_coords: refnodeX = rootnode.attachNewNode('world_coords_x') refnodeY = rootnode.attachNewNode('world_coords_y') refnodeZ = rootnode.attachNewNode('world_coords_z') robjnode.wrtReparentTo(refnodeZ) refnodeZ.setH(refnodeX, hpr[2]) robjnode.wrtReparentTo(refnodeY) refnodeY.setP(refnodeX, hpr[1]) robjnode.wrtReparentTo(refnodeX) refnodeX.setR(refnodeX, hpr[0]) robjnode.wrtReparentTo(rootnode) else: robjnode.setHpr(hpr[2], hpr[1], hpr[0]) robjnode.setScale(scale[0], scale[0], scale[0]) robjnode.setPos(pos[0], -pos[2], pos[1]) robjnode.setTwoSided(1) objnodes.append(robjnode) if check_penetration: for (i, n1) in enumerate(objnodes): for j, n2 in enumerate(objnodes[i + 1:]): p = is_penetrating(n1, n2) if p: for onode in objnodes: onode.removeNode() raise PenetrationError(i, j, n1, n2) # Environment map if bgpath and use_envmap: envtex = tools.read_file(lbase.loader.loadTexture, bgpath) # Map onto object ts = TextureStage('env') ts.setMode(TextureStage.MBlendColorScale) if not isinstance(use_envmap, list): use_envmap = [use_envmap] * len(objnodes) for _objnode, ue in zip(objnodes, use_envmap): if ue: if isstring(ue): envtex0 = tools.read_file(lbase.loader.loadTexture, mt.resolve_texture_path(ue)) else: envtex0 = envtex _objnode.setTexGen(ts, TexGenAttrib.MEyeSphereMap) _objnode.setTexture(ts, envtex0) if bgpath and not np.isinf(bghp[0]): bgtex = tools.read_file(lbase.loader.loadTexture, bgpath) # Set as background #plane = cm.autogen_egg(mt.resolve_model_path('plane2d')) bgnode = lbase.loader.loadModel('smiley') # Get material list bgnode.clearMaterial() bgnode.clearTexture() bgnode.setAttrib( CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) bgnode.setTexture(bgtex, 2) c = 5. bgnode.setScale(c * bgscale[0], c * bgscale[0], c * bgscale[0]) bgnode.setPos(0, 0, 0) #0) bgnode.setHpr(bghp[0], bghp[1], 0.) # Detach point light plight1 = lbase.rootnode.find('**/plight1') if plight1: plight1.detachNode() elif bgpath: bgnode = NodePath("empty-bgnode") imageObject = OnscreenImage(image=bgpath, pos=(0, 0, 0), scale=tuple(bgscale), parent=bgnode, base=lbase) else: bgnode = NodePath("empty-bgnode") bgnode.reparentTo(rootnode) if shader is not None: vshaderpath, fshaderpath = shader rootnode.setShaderAuto() shader = Shader.load(Shader.SLGLSL, vshaderpath, fshaderpath) rootnode.setShader(shader) if light_spec is not None: lbase.rootnode.clearLight() lights = LightBase.make_lights(light_spec=light_spec, lname='scene_lights') lights.reparentTo(rootnode) for light in lights.getChildren(): rootnode.setLight(light) return objnodes, bgnode
def __init__(self, showbase): self.showbase = showbase self.ready = False self.showbase.num_warlocks = 1 self.showbase.which = 0 # this will have its own chat i guess, just game server only (no channels or anything just the one chat, all to all) # also i guess all the players data (usernames, maybe others) will need to be collected here from the server for the chat/scoreboard/whatever # and whenever a new person joins/leaves an update will be sent to all the clients (like with the all chat i guess) # these will need to be created in here from data passed from the server (where it will be procedurally generated) # once it receives a 'preround' state change it should create all the required shit (warlocks per person and the Game() class and whatnot) # then client will switch to preround state # spell0 spell0 = Spell() spell0.damage = 10 spell0.target_knockback = 20 spell0.self_knockback = 0 spell0.range = 25 spell0.speed = 15 spell0.aoe = False spell0.aoe_range = 0 spell0.targeting = False spell0.casting_time = 0 spell0.interruptable = False spell0.model = "media/spells/blockyball" # spell1 spell1 = Spell() spell1.damage = 25 spell1.target_knockback = 10 spell1.self_knockback = 0 spell1.range = 50 spell1.speed = 25 spell1.aoe = False spell1.aoe_range = 0 spell1.targeting = False spell1.casting_time = 0 spell1.interruptable = False spell1.model = "media/spells/pointyball" # spell2 spell2 = Spell() spell2.damage = 50 spell2.target_knockback = 10 spell2.self_knockback = 30 spell2.range = 50 spell2.speed = 15 spell2.aoe = False spell2.aoe_range = 0 spell2.targeting = False spell2.casting_time = 0 spell2.interruptable = False spell2.model = "media/spells/blockyball" # spell3 spell3 = Spell() spell3.model = "media/spells/pointyball" showbase.spells = [] showbase.spells.append(spell0) showbase.spells.append(spell1) showbase.spells.append(spell2) showbase.spells.append(spell3) self.background = OnscreenImage(image='media/gui/lobby/lobby.png', parent=render2d) # Send Message Button self.send_button = DirectButton( command=self.send_message, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, .3), scale=.1, text="Send", ) # Text box for message entry self.entry = DirectEntry( focusInCommand=self.clearText, frameSize=(-3, 3, -.5, 1), initialText="Chat:", parent=self.send_button, pos=(0, 0, -1.5), text="", text_align=TextNode.ACenter, ) # button to tell server client is ready self.ready_button = DirectButton( command=self.toggle_ready, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, -.3), scale=.1, text="Ready?", ) # button to tell server client is not ready self.unready_button = DirectButton( command=self.toggle_unready, frameSize=(-3, 3, -.5, 1), pos=(0.0, 0.0, -.3), scale=.1, text="Unready?", ) # hide unready button until ready self.unready_button.hide() # button to quit game self.quit_button = DirectButton( command=showbase.quit, frameSize=(-4, -1, 0, 0), #-3, 3, -.5, 1), pos=(-1.0, 0.0, -1.0), scale=.1, text="QUIT!", ) # Add the game loop procedure to the task manager. taskMgr.doMethodLater(1.0, self.update_lobby, 'Update Lobby')
def loadStartScreen(self): self.startBG = OnscreenImage(image='world.jpg', pos=(0, 0, 0), scale=3) self.title = OnscreenText(text="Onwards,Term Project", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, 0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.chooseGround = OnscreenText(text="Choose Land:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, 0.25), scale=.08, shadow=(0, 0, 0, 0.5)) self.buttonForest = DirectButton(pos=(-0.2, 0, 0.24), text="Forest", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["forest"], relief=SUNKEN) self.buttonDesert = DirectButton(pos=(0.4, 0, 0.24), text="Desert", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["desert"]) self.chooseMusic = OnscreenText(text="Choose Music:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, 0), scale=.08, shadow=(0, 0, 0, 0.5)) self.buttonMusic1 = DirectButton(pos=(-0.2, 0, -0.01), text="Piano 1", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["piano1"], relief=SUNKEN) self.buttonMusic2 = DirectButton(pos=(0.35, 0, -0.01), text="Piano 2", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["piano2"]) self.buttonMusic3 = DirectButton(pos=(0.8, 0, -0.01), text="None", scale=.1, pad=(.2, .2), rolloverSound=None, clickSound=None, command=self.selected, extraArgs=["stop"]) self.volume = OnscreenText(text="Volume:", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(-0.8, -0.3), scale=.08, shadow=(0, 0, 0, 0.5)) self.volumeSlider = DirectSlider(pos=(0.3, 0, -0.3), scale=0.7, value=.5, command=self.setMusicVolume) self.enterInstruction = OnscreenText(text="Press 'Enter' to Begin", align=TextNode.ACenter, fg=(1, 1, 1, 1), pos=(0, -0.5), scale=.08, shadow=(0, 0, 0, 0.5)) self.accept("enter", self.loadModels)