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 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()
class ItemIcon(): def __init__(self, itemName, parentNode): print 'itemicon', itemName, parentNode self.parentNode = parentNode # The node of its parent (e.g. the inventory) self.itemName = itemName # The filename of the icon self.image = None # The actual icon #self.iconNode = aspect2d.attachNewNode('iconnode') self.LoadContent() def LoadContent(self): self.itemImage = OnscreenImage(image = "Assets/Images/Items/%s.png" % (self.itemName)) self.itemImage.setScale((self.itemImage.getTexture().getOrigFileXSize() / 1024.0, 1, self.itemImage.getTexture().getOrigFileYSize() / 1024.0)) self.itemImage.setTransparency(TransparencyAttrib.MAlpha) self.itemImage.reparentTo(self.parentNode) def setBin(self, binType, value): print 'set bin', binType, value self.itemImage.setBin(binType, value) def SetPos(self, pos): self.itemImage.setPos(pos) def Destroy(self): self.itemImage.destroy()
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 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 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 MainMenu(object): """Draw a nice menu with some choices.""" def __init__(self): mainmenu = [ ("Adventure", lambda: base.core.demand("Loading", "Developmentenvironment")), ("Quick Game", lambda: self.p("not yet implemented")), ("Credits", lambda: self.p("not yet implemented")), ("Exit", sys.exit) ] self.font = loader.loadFont("fonts/aranea.ttf") self.font.setPixelsPerUnit(100) self.parent_node = aspect2d.attachNewNode("main menu") self.bg = OnscreenImage(image="backdrops/menubg.jpg", scale=(4.0 / 3, 1, 1), parent=self.parent_node) self.t = OnscreenText("Azure", pos=(-0.6, 0.7), font=self.font, fg=(1, 1, 1, 1), scale=0.3) margin = 0.0 button_options = { "text_fg": (1, 1, 1, 1), "text_font": self.font, "text_scale": 0.1, "relief": None, "rolloverSound": None, "clickSound": None, "pressEffect": 0, "frameVisibleScale": (0.1, 0.1), "sortOrder": 2, "text_wordwrap": 7, "parent": self.parent_node } self.buttons = [] lengths = 0 for caption, function in mainmenu: b = DirectButton(text=caption, command=function, **button_options) self.buttons.append(b) lengths += b.getWidth() space = (2 - margin * 2 - lengths) / (len(self.buttons) - 1) pos = -1 + margin for b in self.buttons: pos -= b.node().getFrame()[0] b.setPos(pos, 0, -0.7) pos += b.node().getFrame()[1] + space def p(self, arg): """Temporary convenience function.""" print arg def destroy(self): self.parent_node.removeNode() self.bg.destroy() self.t.destroy() for b in self.buttons: b.destroy()
class LifeBar: def __init__(self): ## Life bar self.image = OnscreenImage(image="image/life_bar.png",pos=(0, 0, 0), scale=(256.0/base.win.getXSize(),1,32.0/base.win.getYSize()), parent=render2d) self.image.setTransparency(TransparencyAttrib.MAlpha) self.image.setZ(-0.9) self.image.setY(2) def __del__(self): self.image.destroy()
class ScreenDecorationManager: def __init__(self): self.tex_judgements = {} for i in ["PERFECT","GOOD","OK","BAD","MISS"]: self.tex_judgements[i] = loader.loadTexture("image/j_%s.png" % i.lower()) ## Judgement message self.image_judgement = OnscreenImage(image=self.tex_judgements["OK"],pos=(0, 0, 0), scale=(256.0/base.win.getXSize(),1,32.0/base.win.getYSize()), parent=render2d) self.image_judgement.setTransparency(TransparencyAttrib.MAlpha) #self.image_judgement.setPos(-0.7, 1, 0.6) self.image_judgement.setAlphaScale(0) interval_pos = LerpPosInterval(self.image_judgement, duration=0.1, startPos=VBase3(-1.2, 1, 0.5), pos=VBase3(-0.7, 1, 0.5), blendType='easeOut') interval_alpha = LerpFunc(self.image_judgement.setAlphaScale, duration=0.1, blendType='easeOut') interval_fade = LerpFunc(self.image_judgement.setAlphaScale, fromData=1, toData=0, duration=1.0, blendType='easeOut') self.judgement_enters = Sequence(Parallel(interval_pos, interval_alpha), Wait(1.0), interval_fade) ## Chain message text_node = TextNode('chain_msg') text_node.setAlign(TextNode.ACenter) text_node.setFont(babelfish_font) text_node.setTextColor(1, 1, 0.16, .9) text_node.setShadow(0.05, 0.05) text_node.setShadowColor(0.05, 0, 0.43, .9) self.chain_msg = aspect2d.attachNewNode(text_node) self.chain_msg.setPos(-.9, 1, 0.35) self.chain_msg.setScale(0.11) def judgement_msg(self, msg, chain): if self.judgement_enters.isPlaying(): self.judgement_enters.clearToInitial() self.image_judgement.setTexture(self.tex_judgements[msg]) self.judgement_enters.start() if chain > 1: self.chain_msg.node().setText("%d CHAIN" % chain) taskMgr.add(self.task_ClearJudgementTask, "clear-judgement") def task_ClearJudgementTask(self, task): if task.time < 1.5: return Task.cont self.chain_msg.node().clearText() def __del__(self): self.judgement_enters.finish() self.image_judgement.destroy() self.chain_msg.removeNode()
class Splash: def __init__(self): props = WindowProperties(base.win.getProperties()) screen_width = props.getXSize() screen_height = props.getYSize() self.ratio = float(screen_width) / float(screen_height) self.text_scale = 0.03 self.text_offset = self.text_scale / 4 self.text_height = self.text_scale + self.text_offset self.image_scale = 0.3 self.bg_texture = loader.loadTexture("textures/splash-background.jpg") if settings.srgb: self.bg_texture.set_format(Texture.F_srgb) self.bg_texture.setWrapU(Texture.WM_clamp) self.bg_texture.setWrapV(Texture.WM_clamp) self.bg_texture_ratio = float( self.bg_texture.get_x_size()) / self.bg_texture.get_y_size() self.texture = loader.loadTexture("textures/cosmonium-name-tp.png") self.texture_ratio = float( self.texture.get_x_size()) / self.texture.get_y_size() if self.ratio >= 1.0: sx = self.ratio sy = self.ratio / self.bg_texture_ratio else: sx = 1.0 / self.ratio sy = 1.0 / (self.ratio * self.bg_texture_ratio) self.bg_image = OnscreenImage(self.bg_texture, color=(1, 1, 1, 1), pos=(0, 0, 0), scale=(sx, 1, sy), parent=base.aspect2d) self.image = OnscreenImage( self.texture, color=(1, 1, 1, 1), scale=(self.image_scale * self.texture_ratio, 1, self.image_scale), parent=base.aspect2d) self.image.setTransparency(TransparencyAttrib.MAlpha) self.text = DirectLabel( text="", text_align=TextNode.ACenter, text_scale=self.text_scale, #text_font=self.font_normal, text_fg=(0.5, 0.5, 0.5, 1), text_bg=(0, 0, 0, 0), text_pos=(0, -self.image_scale - self.text_height)) #frameSize = (-0.75, 0.75, self.text_height, 0)) self.text.reparent_to(base.aspect2d) def set_text(self, text): self.text.setText(text) def close(self): self.text.destroy() self.image.destroy() self.bg_image.destroy()
class MainMenu(object): def __init__(self): mainmenu = [ ("Adventure", lambda: base.core.request("World")), ("Quick Game", lambda: self.p("not yet implemented")), ("Credits", lambda: self.p("not yet implemented")), ("Exit", sys.exit), ] self.font = loader.loadFont("fonts/aranea.ttf") self.font.setPixelsPerUnit(100) self.parent_node = aspect2d.attachNewNode("main menu") self.bg = OnscreenImage(image="backdrops/menubg.jpg", scale=(1.333333, 1, 1), parent=self.parent_node) self.t = OnscreenText("Azure", pos=(-0.6, 0.7), font=self.font, fg=(1, 1, 1, 1), scale=0.3) margin = 0.0 button_options = { "text_fg": (1, 1, 1, 1), "text_font": self.font, "text_scale": 0.1, "relief": None, "rolloverSound": None, "clickSound": None, "pressEffect": 0, "frameVisibleScale": (0.1, 0.1), "sortOrder": 2, "text_wordwrap": 7, "parent": self.parent_node, } self.buttons = [] lengths = 0 for caption, function in mainmenu: b = DirectButton(text=caption, command=function, **button_options) self.buttons.append(b) lengths += b.getWidth() space = (2 - margin * 2 - lengths) / (len(self.buttons) - 1) pos = -1 + margin for b in self.buttons: pos -= b.node().getFrame()[0] b.setPos(pos, 0, -0.7) pos += b.node().getFrame()[1] + space def p(self, arg): """Temporary convenience function.""" print arg def destroy(self): self.parent_node.removeNode() self.bg.destroy() self.t.destroy() for b in self.buttons: b.destroy()
class minimap: #a strategic minimap to display on screen image = None #the PNMImage onscreen = None #the OnscreenImage to show mini-map on texture = None # the texture image is saved to map = None #the map as represented by a multi-dimensional array of many '1' and '2'. def __init__(self, map = None): if map == None: #if no map given, default image size self.image = PNMImage(256,256) self.image.fill(0,0,0) else: #if map given, image is size of map self.image = PNMImage(len(map[0]), len(map)) self.image.fill(0,0,0) # self.image.write("minimap.png") #saves the mini-map to hard drive (I just wanted to, not sure if necessary or not.) self.map = map self.texture = Texture() self.texture.load(os.path.join('Glues','minimap.tga')) self.onscreen = OnscreenImage(image=self.texture,pos=(-1.4,0,-0.81),scale=(0.2,0,0.19)) def createmap(self, map): #updates the map self.image.clear() del self.image self.image = PNMImage(len(map[0]),len(map)) #if map size has changed, for i in range(0, len(map)): for me in range(0, len(map[0])): if map[i][me] == 2: self.image.setXel( me , len(map)-1 - i , 0,1,0) if map[i][me] == 1: self.image.setXel( me , len(map)-1 - i , 0,0,1) def __update__(self, map): #a update function to be called every frame or every couple. pass self.createmap(map) #update map self.texture.load(self.image) #save map image to texture self.onscreen.setImage(self.texture) #set onscreenimage to that texture def destroy(self): self.onscreen.destroy()
class LifeBar: def __init__(self): ## Life bar self.image = OnscreenImage(image="image/life_bar.png", pos=(0, 0, 0), scale=(256.0 / base.win.getXSize(), 1, 32.0 / base.win.getYSize()), parent=render2d) self.image.setTransparency(TransparencyAttrib.MAlpha) self.image.setZ(-0.9) self.image.setY(2) def __del__(self): self.image.destroy()
class AppState(FSM): def enterMenu(self): self.image = OnscreenImage(image="images/startmenu.jpg", pos=(0,0,0), scale=(2.3,2.3,1)) self.intruction = None self.StartBtn = DirectButton(text = "Start", scale = 0.12, pos = Vec3(0, 0, -0.5), command = self.request, extraArgs = ["Start"]) self.InstructionsBtn = DirectButton(text = "Instructions", scale = 0.1, pos = Vec3(0, 0, -0.65), command = self.request, extraArgs = ["Instructions"]) self.QuitBtn = DirectButton(text = "Quit", scale = 0.1, pos = Vec3(0,0,-.8), command = self.request, extraArgs = ["Quit"]) def exitMenu(self): self.StartBtn.destroy() self.InstructionsBtn.destroy() self.QuitBtn.destroy() self.image.destroy() def enterStart(self): self.game = FoxTrail() def enterInstructions(self): self.image = OnscreenImage(image="images/Instructions.jpg", pos=(0,0,0), scale=(1.4,1.4,1)) self.menuBtn = DirectButton(text = "Menu", scale = 0.1, pos = Vec3(0, 0, -0.8), command = self.request, extraArgs = ["Menu"]) def exitInstructions(self): self.menuBtn.destroy() self.image.destroy() def enterQuit(self): sys.exit()
class OptionsScreen: def __init__(self, options): self.bg = OnscreenImage(image='./image/bg.png', pos = (0.0, -1.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) self.title = OnscreenText(text = 'Options', pos = (0.0, 0.7), scale = 0.3, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) self.option_title_txt = OnscreenText(text='Controller', scale=0.2, pos=(-1.0, 0.0), font=babelfish_font, align=TextNode.ALeft, fg=(1,1,1,1)) self.option_value = options.get('game-opts', 'controller') self.option_value_txt = OnscreenText(text=self.option_value, scale=0.2, pos=(.7, 0.0), font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) self.options = options self.curr_controller = 0 self.controllers = ['Keyboard','Joypad', 'Mouse'] #define o controle atual baseado no arquivo salvo for f in self.controllers: if f == self.option_value: break else: self.curr_controller += 1 def option_changed(self, command): self.toggle_value(command) def toggle_value(self, opt): if opt == 'nav-right': self.curr_controller += 1 elif opt == 'nav-left': self.curr_controller -= 1 if (self.curr_controller >= len(self.controllers)): self.curr_controller = 0 elif (self.curr_controller < 0): self.curr_controller = len(self.controllers) - 1 self.option_value = self.controllers[self.curr_controller] self.option_value_txt.destroy() self.option_value_txt = OnscreenText(text=self.option_value, scale=0.2, pos=(.7, 0.0), font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) def clear(self): self.bg.destroy() self.title.destroy() self.option_title_txt.destroy() self.option_value_txt.destroy() self.options.set('game-opts', 'controller', self.option_value)
class mainMenu: def __init__(self, mainMenuState, cameraActive): # Just try and destroy a menu if it already exists try: self.hideMainMenu() except: # If nothing exists we create the main menu self.bk_text = "Welcome to SHENKO" self.textObject = OnscreenText(text=self.bk_text, pos=(0.95, -0.95), scale=0.05, fg=(0, 1, 1, 1), bg=(0, 0, 0, .5), align=TextNode.ACenter, mayChange=1) # Draw the Shenko LOGO self.imageObject = OnscreenImage(image='logo.png', pos=(0, 0, .6), scale=0.5) self.imageObject.setImage('logo.png') # Menu buttons rollSound = base.loader.loadSfx("click.ogg") self.startbttn = DirectButton(text=("start", "---> start <---", "--> start <--", "disabled"), pos=(0, 0, .2), scale=.07, rolloverSound=rollSound, command=self.start) self.mainMenuState = False print('derp', self.mainMenuState) def hideMainMenu(self): print("#---#### ####---#") #DirectButton.destroy() self.textObject.destroy() # This is the text lower right of screen self.imageObject.destroy() # This is the Logo self.startbttn['state'] = DGG.DISABLED self.startbttn.destroy() def start(self): print("LOADING CENTRAL --------------------------_> ...") self.hideMainMenu()
class ImgOnscreen(object): """ Add a on screen image in the render 2d scene of Showbase """ def __init__(self, size, parent_np=None): """ :param size: (width, height) :param parent_np: Should be ShowBase or ExtraWindow """ self._size = size self.tx = Texture("video") self.tx.setup2dTexture(size[0], size[1], Texture.TUnsignedByte, Texture.FRgb8) # this makes some important setup call # self.tx.load(PNMImage(card_size[0], card_size[1])) self.onscreen_image = OnscreenImage(self.tx, pos=(0, 0, 0), parent=parent_np.render2d) def update_img(self, img: np.ndarray): """ Update the onscreen image :param img: :return: """ if img.shape[2] == 1: img = img_to_n_channel(img) resized_img = letter_box(img, new_shape=[self._size[1], self._size[0]], auto=False) self.tx.setRamImage(resized_img.tostring()) def remove(self): """ Release the memory :return: """ if self.onscreen_image is not None: self.onscreen_image.destroy() def __del__(self): self.remove()
class Menu(DirectObject): def __init__(self): self.title = OnscreenImage(image = 'img/titleScreen.png', pos = (0, 0, 0) ) self.pointer = OnscreenImage(image = 'img/titleSelector.png', pos = (-.2, 0 ,-.63)) self.pointer.setScale(.05) self.start = False self.instructions = False self.pointerPosition = 1 self.pointer.setTransparency(TransparencyAttrib.MAlpha) self.accept("enter", self.screenHandler) self.accept("arrow_up", self.movePointerUp) self.accept("arrow_down", self.movePointerDown) self.accept("backspace", self.back) self.accept("escape", sys.exit) def screenHandler(self): if self.pointerPosition == 1: self.start = True self.title.destroy() self.pointer.destroy() else: self.instructions = True self.title.setImage('img/instructions.png') def back(self): if self.instructions == True: self.instructions = False self.title.setImage('img/titleScreen.png') self.pointer.setImage('img/titleSelector.png') def movePointerUp(self): if self.pointerPosition == 2: self.pointer.setPos(-.2, 0, -.63) self.pointerPosition = 1 def movePointerDown(self): if self.pointerPosition == 1: self.pointer.setPos(-.2, 0, -.8) self.pointerPosition = 2 def destroy(self): self.ignoreAll()
class LoadScreen: def __init__(self, options): self.options = options if self.options.get('game-opts', 'controller') == 'Joypad': self.bg = OnscreenImage(image='./image/tela_joypad.png', pos = (0.0, 2.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) elif self.options.get('game-opts', 'controller') == 'Keyboard': self.bg = OnscreenImage(image='./image/tela_keyboard.png', pos = (0.0, 2.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) elif self.options.get('game-opts', 'controller') == 'Mouse': self.bg = OnscreenImage(image='./image/tela_mouse.png', pos = (0.0, 2.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) if uses_wii(self.options): self.press = self.wiimote_connection_text = OnscreenText(text='Press SPACE to continue and 1+2 to connect the Wiimote', shadow=(.0,.0,.0,1), scale=0.09, pos=(.0, -.95), align=TextNode.ACenter, fg=(1,1,1,1)) else: self.press = self.wiimote_connection_text = OnscreenText(text='Press SPACE to continue', shadow=(.0,.0,.0,1), scale=0.09, pos=(.0, -.95), align=TextNode.ACenter, fg=(1,1,1,1)) def alpha(self): Sequence(LerpFunc(self.bg.setAlphaScale, fromData=.1, toData=0, duration=.3)).start() def clear(self): self.bg.destroy() self.press.destroy()
class Menu(): def __init__(self, parent): self.parent = parent self.whichfrom = "" #For telling backClicked which menu it came from self.font = loader.loadFont("../assets/font/Orbitron Light.otf") self.back = OnscreenImage(image = "../assets/2d/title_bg01.png", pos = (0, 0, 0), scale=(1.4,1,1)) self.startButton = DirectButton(image = "../assets/2d/buttons/start_on.png", image_scale = (.8, 1, .14), image_pos = (0, 0, .2), relief = None, command = self.startClicked) self.rulesButton = DirectButton(image = "../assets/2d/buttons/rules_on.png", image_scale = (.8, 1, .14), image_pos = (0, 0, -.2), relief = None, command = self.rulesClicked) #self.optButton = DirectButton(image = "../assets/2d/buttons/opt_on.png", image_scale = (.8, 1, .14), image_pos = (0, 0, -.4), relief = None, command = self.optClicked) self.exitButton = DirectButton(image = "../assets/2d/buttons/exit_on.png", image_scale = (.8, 1, .14), image_pos = (0, 0, -.6), relief = None, command = self.exitClicked) def startClicked(self): self.startButton.destroy() self.rulesButton.destroy() #self.optButton.destroy() self.exitButton.destroy() self.back.destroy() self.parent.beginGame() #This will make the rest of the game happen! def rulesClicked(self): self.startButton.destroy() self.rulesButton.destroy() #self.optButton.destroy() self.exitButton.destroy() self.back.destroy() self.back = OnscreenImage(image = "../assets/2d/title_bg02.png", pos = (0, 0, 0), scale=(1.4,1,1)) self.line1 = OnscreenText(text = "Defeat enemy players by pushing them into the arena wall!", fg = (0,1,1,1), pos = (0, .8), scale = .07, font = self.font) self.line2 = OnscreenText(text = "Use traps to snag them, and throw balls to push them!", fg = (0,1,1,1), pos = (0, .6), scale = .07, font = self.font) self.line3 = OnscreenText(text = "Controls:", fg = (0,1,1,1), pos = (0, .4), scale = .1, font = self.font) self.line4 = OnscreenText(text = "Left Click: Throw Ball/Place Trap", fg = (0,1,1,1), pos = (0, .2), scale = .07, font = self.font) self.line5 = OnscreenText(text = "Scroll: Select Item", fg = (0,1,1,1), pos = (0, 0), scale = .07, font = self.font) self.line6 = OnscreenText(text = "W/S: Jet Forward/Backward", fg = (0,1,1,1), pos = (0, -.2), scale = .07, font = self.font) self.line7 = OnscreenText(text = "The more hits you take, the greater your momentum!", fg = (0,1,1,1), pos = (0, -.6), scale = .07, font = self.font) self.whichfrom = "rules" self.backButton = DirectButton(image = "../assets/2d/buttons/back_on.png", image_scale = (.4,1,.1), image_pos = (-.9, 0, -.87), relief = None, command = self.backClicked) def optClicked(self): print "options click!" def backClicked(self): self.backButton.destroy() self.back.destroy() if self.whichfrom == "rules": self.line1.destroy() self.line2.destroy() self.line3.destroy() self.line4.destroy() self.line5.destroy() self.line6.destroy() self.line7.destroy() self.__init__(self.parent) #Redoes the menu def exitClicked(self): sys.exit()
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) #countdown sound file from https://www.youtube.com/watch?v=KOoCEIwswYg self.cdMusic = loader.loadSfx("sounds/countdown.ogg") #race sound file from https://www.youtube.com/watch?v=eawQqkq8ROo self.rMusic = loader.loadSfx("sounds/race.ogg") self.r_1 = 700 self.r_2 = 900 self.rad_avg = (self.r_1 + self.r_2) / 2 self.rad_incr = (self.r_2 - self.r_1) / 3 #window and camera self.win.setClearColor((0, 0, 0, 1)) self.startPos = LPoint3f(100, 50, 0) self.disableMouse() self.x = self.startPos.getX() self.y = self.startPos.getY() self.z = 15 self.camera.setPos(self.r_1 + self.rad_incr, 10, 300) self.camera.setH(0) self.camMaxDist = 180 self.camMinDist = 150 #mario character (user player) #3d mario model file from past tp, with permission: #https://github.com/Kabartchlett/15-112-Term-Project self.mario = Actor("models/MarioKart") self.scale = 7 self.mario.setScale(self.scale) self.mario.setH(self.mario, 0) self.mario.reparentTo(render) self.marioX = 3 self.marioY = self.startPos.getY() / 3 self.marioZ = 11 self.mario.setPos(self.r_1 + self.rad_incr, -40, 15) self.mario.y_speed = -30 self.mario.h_speed = 0 self.mario.raceTime = 0 self.mario.finishTime = 0 self.drifted = False self.mario.numFellOff = 0 self.mario.falling = False self.mario.startFallTime = None self.mario.startFallPos = None self.mario.gameover = False self.mario_lapText = None self.mario.crossed = False self.mario.mush = False self.mario.megamush = False self.mario.bananaSpin = False self.mario.preSpinAngle = self.mario.getH() self.mario.lap = 1 self.mario.doubleMush = False #floater method from roaming ralph: #https://github.com/panda3d/panda3d/tree/master/samples/roaming-ralph self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.mario) self.floater.setZ(2) self.center = NodePath(PandaNode("center")) self.center.setZ(0) self.center.setZ(0) self.center.setZ(15) #computer player #3d yoshi model file from past tp, with permission: #https://github.com/Kabartchlett/15-112-Term-Project self.yoshi = Actor("models/YoshiKart") self.yoshi.setScale(self.scale) self.yoshi.setH(self.yoshi, 20) self.yoshi.reparentTo(render) self.yoshiX = 3 self.yoshiY = self.startPos.getY() * (2 / 3) self.yoshiZ = 10 self.yoshi.setPos(self.r_1 + 2 * self.rad_incr, -40, 15) self.yoshi.y_speed = -25 self.yoshi.h_speed = 0 self.AIadjust = 60 self.yoshi.raceTime = 0 self.yoshi.finishTime = 0 self.yoshi.numFellOff = 0 self.yoshi.falling = False self.yoshi.startFallTime = None self.yoshi.startFallPos = None self.yoshiStartH = None self.yoshi.gameover = False self.yoshi_lapText = None self.yoshi.crossed = False self.yoshi.mush = False self.yoshi.megamush = False self.yoshi.bananaSpin = False self.yoshi.preSpinAngle = self.yoshi.getH() self.yoshi.lap = 1 self.yoshi.doubleMush = False #statuses self.victory = False self.loss = False self.menuCount = 0 self.paused = False self.addMove = 1 self.timeDelay = 0 self.start = True self.escapeStart = False self.menuStart = True self.charFin = True self.counting = True self.playing = True self.playRaceMusic = False self.menuDisplayed = False #data init self.vDataRows = 100 self.finalX = self.x self.lines = [] self.isPaused = [] self.wait = 10 self.countdowns = [] self.startText = [] self.cirNodePath = None self.OSimageText = [] self.timeCharFin = None self.lives = [] #collision with items init from itemCir import Item self.itemClass = Item(self) #key events self.accept('escape', sys.exit) self.accept('q', self.menuToggle, ['display']) self.accept('e', self.menuToggle, ['remove']) self.accept('p', self.pause) #tasks if self.start: taskMgr.add(self.startScreen, 'start') def addTasks(self, task): self.circularRoad() self.displayLives() self.displayLaps() taskMgr.add(self.move, "move") taskMgr.add(self.moveSim, 'moveSim') taskMgr.add(self.countdown, 'countdown') taskMgr.add(self.mapPrev, 'map') taskMgr.add(self.takeLives, 'lives') taskMgr.add(self.moveCam, 'cam') def collideInit(self): mNode = CollisionNode('mario') mNode.addSolid(CollisionSphere(0, 0, 0, self.scale - 2)) marioCol = self.mario.attachNewNode(mNode) yNode = CollisionNode('yoshi') yNode.addSolid(CollisionSphere(0, 0, 0, self.scale - 2)) yoshiCol = self.yoshi.attachNewNode(yNode) return marioCol def circularRoad(self): #geom format and data z = 15 points = self.vDataRows // 2 #one circle #x = rcos(t) #y = rsin(t) t_incr = (2 * math.pi) / points format = GeomVertexFormat.getV3n3c4t2() vData = GeomVertexData('cRoad', format, Geom.UHStatic) vData.setNumRows(2 * self.vDataRows) vertex = GeomVertexWriter(vData, 'vertex') normal = GeomVertexWriter(vData, 'normal') color = GeomVertexWriter(vData, 'color') texcoord = GeomVertexWriter(vData, 'texcoord') for i in range(self.vDataRows): angle = t_incr * i x_1 = self.r_1 * math.cos(angle) y_1 = self.r_1 * math.sin(angle) x_2 = self.r_2 * math.cos(angle) y_2 = self.r_2 * math.sin(angle) vertex.addData3f(x_1, y_1, z) vertex.addData3f(x_2, y_2, z) for n in range(2): normal.addData3f(0, 0, z) if i > self.vDataRows / 2 - 2: #finish line for n in range(2): color.addData4f(255, 0, 0, 1) elif i % 2 == 0: #rainbow road color.addData4f(0, 255, 255, 1) color.addData4f(0, 255, 0, 1) color.addData4f(255, 255, 0, 1) color.addData4f(255, 0, 255, 1) texcoord.addData2f(x_1, y_1) texcoord.addData2f(x_2, y_2) #geom primitives cRoad = GeomTristrips(Geom.UHStatic) cRoad.add_consecutive_vertices(0, 2 * self.vDataRows) cRoad.close_primitive() #connect data and primitives cirGeom = Geom(vData) cirGeom.addPrimitive(cRoad) cirNode = GeomNode('geomNode') cirNode.addGeom(cirGeom) self.cirNodePath = render.attachNewNode(cirNode) self.cirNodePath.set_two_sided(True) def checkCharCol(self): if abs(self.yoshi.getX() - self.mario.getX()) < 10 and \ abs(self.yoshi.getY() - self.mario.getY()) < 10 and \ abs(self.yoshi.getZ() - self.mario.getZ()) < 10: self.collideYoshi() def collideYoshi(self): #altered use of conservation of momentum if self.mario.getH() != 0: mario_sign = self.mario.getH() / abs(self.mario.getH()) else: mario_sign = 0 if self.yoshi.getH() != 0: yoshi_sign = self.yoshi.getH() / abs(self.yoshi.getH()) else: yoshi_sign = 0 self.mario.setH(self.mario.getH() + mario_sign * 15) self.yoshi.setH(self.yoshi.getH() - mario_sign * 15) def isOffRoad(self, player): distFromCen = distance(0, 0, player.getX(), player.getY()) return distFromCen < self.r_1 or distFromCen > self.r_2 def almostOffRoad(self, player): #for computer player, detect when almost off the road distFromCen = distance(0, 0, player.getX(), player.getY()) inner = (distFromCen > self.r_1 and distFromCen < self.r_1 + 30) outer = (distFromCen < self.r_2 and distFromCen > self.r_2 - 30) return inner or outer def checkItemCol(self, player): #checks if player ran into an item box for i in range(len(self.itemClass.items)): items = self.itemClass.items[i] if self.itemClass.itemsPresent[i] and abs(items.getX() - player.getX()) <= 10 and\ abs(items.getY() - player.getY()) <= 10 and\ abs(items.getZ() - player.getZ()) <= 5: self.itemClass.collideItem(items, i, player) def checkBananaCol(self, player): #makes player react to running into a banana #banana collision detection for i in range(len(self.itemClass.bananas)): banana = self.itemClass.bananas[i] if self.itemClass.bananaPresent[i] and abs(banana.getX() - player.getX()) <= 10 and\ abs(banana.getY() - player.getY()) <= 10 and\ abs(banana.getZ() - player.getZ()) <= 10: self.itemClass.bananaReact(banana, i, player) player.preSpinAngle = player.getH() #spin player if player.bananaSpin and globalClock.getFrameTime() < \ self.itemClass.beginSpin + self.itemClass.spinTime: player.h_speed = 600 player.y_speed = 0 #end spin if player.bananaSpin and ( abs(globalClock.getFrameTime() - (self.itemClass.beginSpin + self.itemClass.spinTime)) < 1): player.bananaSpin = False player.h_speed = 0 if player == self.yoshi: player.y_speed = -25 elif player == self.mario: player.y_speed = -30 player.setH(player.preSpinAngle) def checkMushEnd(self, player): #ends the effect of mushroom or mega mushroom if player.mush: if player.falling or abs(player.getX() - self.itemClass.beginBoostX) >= \ self.itemClass.boostDistance: player.mush = False self.itemClass.mushroom(player) if player.megamush: if player.falling or abs(player.getX() - self.itemClass.beginBoostX) >= \ self.itemClass.boostDistance: player.megamush = False self.itemClass.megaMushroom(player) def checkFellOff(self, player): #checks if the player fell off the road if self.isOffRoad(player) and not player.falling: player.numFellOff += 1 player.startFallTime = globalClock.getFrameTime() player.startFallPos = player.getPos() if player == self.yoshi: self.yoshiStartH = self.yoshi.getH() player.falling = True if player.numFellOff > 2: if player == self.yoshi: player.gameover = True if player == self.mario: self.gameOver() def checkFinishLine(self, player): #checks if the player crossed the finish line if player.getX() > self.r_1 and player.getX() < self.r_2 and \ abs(player.getY()) < 30 and player.getZ() >= 15 and not player.crossed: player.lap += 1 player.crossed = True if player.lap > 3: #final lap completed player.finishTime = roundtoThou(player.raceTime) if player == self.mario: self.victory = True if self.loss == False and self.mario.gameover == False: vic = displayBigText('VICTORY!', (0.8, -1), (255, 255, 0, 1)) self.OSimageText.append(vic) escText = displaySmallText('press esc to quit program', (0.8, -1.2), (255, 255, 255, 0.7)) self.OSimageText.append(escText) elif player == self.yoshi: self.loss = True escText = displaySmallText('press esc to quit program', (0.8, -1.2), (255, 255, 255, 0.7)) self.OSimageText.append(escText) if self.mario.gameover == False and self.victory == False: compwins = displayBigText('COMPUTER WINS', (0.4, -1), (255, 0, 0, 0.5)) self.OSimageText.append(compwins) def moveSim(self, task): dt = globalClock.getDt() self.timeDelay += dt h_speed = self.yoshi.h_speed y_speed = self.yoshi.y_speed z_speed = 10 #checks for banana collision self.checkBananaCol(self.yoshi) #checks for item collision self.checkItemCol(self.yoshi) #adjust angle if almost run off road (AI) if self.almostOffRoad(self.yoshi): distFromCen = distance(0, 0, self.yoshi.getX(), self.yoshi.getY()) if distFromCen > self.r_1 and distFromCen < self.r_1 + 30: h_speed += self.AIadjust elif distFromCen < self.r_2 and distFromCen > self.r_2 - 30: h_speed -= self.AIadjust #change position, angle dh = h_speed * dt dy = y_speed * dt dz = z_speed * dt if self.timeDelay > self.wait: self.yoshi.raceTime += dt self.yoshi.setH(self.yoshi.getH() + dh) self.yoshi.setY(self.yoshi, dy) #fell off road self.checkFellOff(self.yoshi) if self.yoshi.falling: self.yoshi.setZ(self.yoshi.getZ() - dz) self.yoshi.y_speed = 0 self.resetPreFallPos(self.yoshi, self.yoshi.startFallPos) #crossed finish line self.checkFinishLine(self.yoshi) if self.yoshi.crossed: self.displayLaps(self.yoshi) #checks for power ups self.checkMushEnd(self.yoshi) return task.cont def move(self, task): # print(self.cdMusic.status()) if self.playing and self.playRaceMusic: self.rMusic.play() self.playing = False dt = globalClock.getDt() if not self.menuDisplayed: self.timeDelay += dt #enable moving mario with direction keys h_speed = self.mario.h_speed y_speed = 0 z_speed = 50 x_speed = 0 h_incr = 80 y_incr = self.mario.y_speed right_down = base.mouseWatcherNode.isButtonDown(KeyboardButton.right()) left_down = base.mouseWatcherNode.isButtonDown(KeyboardButton.left()) forward_down = base.mouseWatcherNode.isButtonDown(KeyboardButton.up()) backward_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.down()) d_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.asciiKey(b"d")) f_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.asciiKey(b"f")) if right_down: h_speed -= h_incr if left_down: h_speed += h_incr if forward_down: if d_down or f_down: y_speed += y_incr / 3 else: y_speed += y_incr if backward_down: if d_down or f_down: y_speed -= y_incr / 3 else: y_speed -= y_incr if d_down and self.timeDelay > self.wait: self.drifted = True self.mario.lookAt(self.center) self.mario.setH(self.mario.getH() + 180) x_speed -= y_incr * (4 / 3) if f_down and self.timeDelay > self.wait: self.drifted = True self.mario.lookAt(self.center) self.mario.setH(self.mario.getH() + 180) x_speed += y_incr * (4 / 3) if not d_down and not f_down and self.drifted and self.timeDelay > self.wait: self.drifted = False self.mario.setH(self.mario.getH() + 90) #checks for banana punishment self.checkBananaCol(self.mario) #checks for collision with item boxes self.checkItemCol(self.mario) #change position, angle dh = h_speed * dt dy = y_speed * dt dz = z_speed * dt dx = x_speed * dt if self.timeDelay > self.wait: self.mario.raceTime += dt self.mario.setH(self.mario.getH() + dh) self.mario.setY(self.mario, dy) self.mario.setX(self.mario, dx) #mario and yoshi collision self.checkCharCol() #fell off road self.checkFellOff(self.mario) if self.mario.falling: self.mario.setZ(self.mario.getZ() - dz) self.mario.y_speed = 0 self.resetPreFallPos(self.mario, self.mario.startFallPos) #crossed finish line self.checkFinishLine(self.mario) if self.mario.crossed: self.displayLaps(self.mario) #show leaderboard if someone completed 3 laps or gameover if (self.mario.gameover or self.victory or self.loss) and self.charFin: self.timeCharFin = globalClock.getFrameTime() self.charFin = False if self.timeCharFin != None and globalClock.getFrameTime( ) > self.timeCharFin + self.wait / 2: self.leaderboard() #checks for power ups self.checkMushEnd(self.mario) return task.cont def moveCam(self, task): dt = globalClock.getDt() #enable camera spinning around mario using a,s,w,x,k,l keys cam = 0 camSpeed = 700 vert = 0 hor = 0 a_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.asciiKey(b"a")) s_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.asciiKey(b"s")) if a_down: cam += camSpeed if s_down: cam -= camSpeed dCam = cam * dt self.camera.setX(self.camera, dCam) #keep camera close to mario, from roaming ralph: #https://github.com/panda3d/panda3d/tree/master/samples/roaming-ralph camVector = self.mario.getPos() - self.camera.getPos() camVector.setZ(0) #don't change camera's z distance camDist = camVector.length() #magnitude camVector.normalize() #unit vector (direction) if camDist > self.camMaxDist: self.camera.setPos(self.camera.getPos() + \ camVector * (camDist - self.camMaxDist)) camDist = self.camMaxDist if camDist < self.camMinDist: self.camera.setPos(self.camera.getPos() - \ camVector * (self.camMinDist - camDist)) camDist = self.camMinDist if self.camera.getZ() != self.mario.getZ() + 6.0: self.camera.setZ(self.mario.getZ() + 6.0) self.camera.setH(self.mario.getH()) self.camera.setZ(self.mario.getZ() + 25) self.camera.lookAt(self.floater) return task.cont def resetPreFallPos(self, player, pos): #place player back on the road if player.startFallTime != None and not player.gameover and globalClock.getFrameTime( ) > player.startFallTime + self.wait / 4: player.falling = False if distance(0, 0, player.getX(), player.getY()) >= self.r_2: sign = -1 #outer else: sign = 1 #inner if player.getX() < 0: adjustX = -70 * sign else: adjustX = 70 * sign if player.getY() < 0: adjustY = -70 * sign else: adjustY = 70 * sign player.setPos(pos + (adjustX, adjustY, 0)) if player == self.mario: self.mario.y_speed = -30 elif player == self.yoshi: self.yoshi.y_speed = -25 self.yoshi.setH(self.mario.getH()) def displayLaps(self, player=None): #display the lap number each player is on #past finish line if player != None and player.getX() > self.r_1 and player.getX() < self.r_2 and \ abs(player.getY()) > 30 and player.getZ() >= 15: player.crossed = False #destroy previous lap count if self.mario_lapText != None: self.mario_lapText.destroy() if self.yoshi_lapText != None: self.yoshi_lapText.destroy() #new lap count self.mario_lapText = OnscreenText(text='Lap: ' + str(self.mario.lap), fg=(255, 0, 0, 1), scale=0.05, parent=base.a2dTopLeft, pos=(2.5, -0.15), align=TextNode.ALeft) self.yoshi_lapText = OnscreenText(text='Lap: ' + str(self.yoshi.lap), fg=(0, 255, 0, 1), scale=0.05, parent=base.a2dTopLeft, pos=(2.5, -0.25), align=TextNode.ALeft) self.OSimageText.append(self.mario_lapText) self.OSimageText.append(self.yoshi_lapText) def displayLives(self): #display the number of lives user player has left livesText = displaySmallText('lives:', (0.1, -0.15), (255, 255, 255, 1)) self.OSimageText.append(livesText) #images made in preview self.life1 = OnscreenImage(image='images/life.png', pos=(-0.9, 0, 0.87), scale=0.03) self.life2 = OnscreenImage(image='images/life.png', pos=(-0.8, 0, 0.87), scale=0.03) self.life3 = OnscreenImage(image='images/life.png', pos=(-0.7, 0, 0.87), scale=0.03) self.OSimageText.append(self.life1) self.OSimageText.append(self.life2) self.OSimageText.append(self.life3) def takeLives(self, task): if self.mario.numFellOff == 1: self.life3.destroy() if self.mario.numFellOff == 2: self.life2.destroy() if self.mario.numFellOff == 3: self.life1.destroy() return task.cont def getPlayerAngle(self, player): #get player's current angle wrt the circular track x = player.getX() y = player.getY() if x == 0: if y <= 0: angle = 90 else: angle = -90 else: angle = math.degrees(math.atan(abs(y) / abs(x))) if y <= 0 and x <= 0: pass #Q1 elif y < 0 and x > 0: angle = 180 - angle #Q2 elif y > 0 and x < 0: angle = -angle #Q3 elif y > 0 and x > 0: angle = -180 + angle #Q4 return angle def mapPrev(self, task): #show map in corner with all player's positions radius = 0.085 mapX = 1 mapY = 0.8 #image made in preview mapP = OnscreenImage(image='images/map.png', pos=(mapX, 0, mapY), scale=0.1) self.OSimageText.append(mapP) marioAngle = self.getPlayerAngle(self.mario) marioX = mapX + radius * math.cos(math.radians(marioAngle)) marioY = mapY + radius * math.sin(math.radians(marioAngle)) yoshiAngle = self.getPlayerAngle(self.yoshi) yoshiX = mapX + radius * math.cos(math.radians(yoshiAngle)) yoshiY = mapY + radius * math.sin(math.radians(yoshiAngle)) finishX = mapX + radius * math.cos(math.radians(180)) finishY = mapY + radius * math.sin(math.radians(180)) #images made in preview marioSym = OnscreenImage(image='images/mariosym.png', pos=(marioX, 0, marioY), scale=0.01) yoshiSym = OnscreenImage(image='images/yoshisym.png', pos=(yoshiX, 0, yoshiY), scale=0.01) finishSym = OnscreenImage(image='images/finishsym.png', pos=(finishX, 0, finishY), scale=0.01) self.OSimageText.append(marioSym) self.OSimageText.append(yoshiSym) self.OSimageText.append(finishSym) return task.cont def startScreen(self, task): if self.escapeStart: return if self.start: #image from supermariorun.com logo = OnscreenImage(image='images/mario.png', pos=(0.01, 0, -0.5), scale=0.3) welcome = OnscreenText('Welcome to Mario Kart!', fg=(255, 0, 0, 1), scale=0.2, shadow=(255, 255, 255, 1), parent=base.a2dTopLeft, pos=(0.2, -0.5), align=TextNode.ALeft) show_menu = OnscreenText('press Q to see key instructions', fg=(255, 255, 255, 1), scale=0.1, shadow=(0, 255, 0, 1), parent=base.a2dTopLeft, pos=(0.6, -0.8), align=TextNode.ALeft) start_game = OnscreenText('press space to start game!', fg=(255, 255, 255, 1), scale=0.1, shadow=(0, 0, 255, 1), parent=base.a2dTopLeft, pos=(0.7, -1), align=TextNode.ALeft) self.startText.append(logo) self.startText.append(welcome) self.startText.append(show_menu) self.startText.append(start_game) q_down = base.mouseWatcherNode.isButtonDown( KeyboardButton.asciiKey(b"q")) space_down = base.mouseWatcherNode.isButtonDown(KeyboardButton.space()) if q_down: self.menuStart = True if q_down or space_down: self.start = False self.escapeStart = True for text in self.startText: text.destroy() if space_down: self.addTasks(task) return task.cont def countdown(self, task): #display countdown before game starts print(taskMgr) taskMgr.remove('start') dt = globalClock.getDt() # print(dt) if not self.menuDisplayed: self.timeDelay += dt interval = self.wait / 3 #countdown sound effect if self.counting: self.cdMusic.play() self.counting = False if self.timeDelay < interval * 1: # print(self.timeDelay, interval*1) display = displayBigText('3', (1.3, -1), (255, 255, 255, 1), (255, 0, 0, 1)) self.countdowns.append(display) elif self.timeDelay < interval * 2: # print(self.timeDelay, interval*2) for display in self.countdowns: display.destroy() display = displayBigText('2', (1.3, -1), (255, 255, 255, 1), (255, 255, 0, 1)) self.countdowns.append(display) elif self.timeDelay < interval * 3: # print(self.timeDelay, interval*3) for display in self.countdowns: display.destroy() display = displayBigText('1', (1.3, -1), (255, 255, 255, 1), (0, 255, 0, 1)) self.countdowns.append(display) elif self.timeDelay < interval * 4: # print(self.timeDelay, interval*4) for display in self.countdowns: display.destroy() display = displayBigText('GO!', (1.1, -1), (255, 255, 255, 1)) self.countdowns.append(display) elif self.timeDelay > interval * 4: for display in self.countdowns: display.destroy() self.playRaceMusic = True return task.cont def pause(self, fromFunction=None): self.paused = not self.paused if self.paused == True: if fromFunction == None: #not from menu displayPause = displayBigText('PAUSED', (0.85, -1), (255, 255, 255, 1)) self.isPaused.append(displayPause) self.OSimageText.append(displayPause) self.addMove -= 1 taskMgr.remove("move") taskMgr.remove("moveSim") taskMgr.remove("countdown") else: #unpause if fromFunction == None: for item in self.isPaused: item.destroy() if self.addMove > 0: return self.addMove += 1 taskMgr.add(self.move, "move") taskMgr.add(self.moveSim, "moveSim") taskMgr.add(self.countdown, 'countdown') def menuToggle(self, keyInput): #display menu of key instructions taskMgr.remove('start') for text in self.startText: text.destroy() #pause countdown music if playing if self.cdMusic.status() == self.cdMusic.PLAYING: self.cdMusicTime = self.cdMusic.getTime() self.cdMusic.setPlayRate(0) yIncr = -0.1 directions = [ 'esc: quit program', 'Q: view menu', 'E: escape menu', 'P: pause/unpause', 'Up/Down: move Mario forward/backward', "Right/Left: change Mario's direction", 'A/S: rotate camera', 'D/F: drift Mario forwards/backwards', "during drift, use Up/Down in place of Right/Left" ] if keyInput == 'display': self.menuDisplayed = True self.menuCount += 1 if self.menuCount > 1: return self.paused = False self.pause('menu') title = displaySmallText('Mario Kart Key Legend', (0.75, -0.1), (255, 255, 255, 1), (0, 0, 0, 1)) self.OSimageText.append(title) self.lines = [title] for i in range(2, len(directions) + 2): y = yIncr * i line = displaySmallText(directions[i - 2], (0.1, y), (255, 255, 255, 0.75), (0, 0, 0, 1)) self.lines.append(line) self.OSimageText.append(line) #access menu from start screen if self.menuStart: line = displaySmallText('press E to start game!', (0.8, -1.5), (255, 255, 0, 1), (0, 0, 0, 1)) self.lines.append(line) self.OSimageText.append(line) self.menuStart = False if keyInput == 'remove': self.menuDisplayed = False #escape menu self.menuCount = 0 self.paused = True self.pause('menu') for line in self.lines: line.destroy() self.circularRoad() self.displayLives() self.displayLaps() # taskMgr.add(self.moveSim, 'moveSim') # taskMgr.add(self.countdown, 'countdown') # taskMgr.add(self.move, "move") taskMgr.add(self.mapPrev, 'map') taskMgr.add(self.takeLives, 'lives') taskMgr.add(self.moveCam, 'cam') def gameOver(self): self.mario.gameover = True if self.victory == False and self.loss == False: gameText = displayBigText('GAME OVER', (0.65, -1), (255, 255, 255, 1)) self.OSimageText.append(gameText) escText = displaySmallText('press esc to quit program', (0.8, -1.2), (255, 255, 255, 0.7)) self.OSimageText.append(escText) def leaderboard(self): #remove everything else on the screen taskMgr.remove('moveSim') taskMgr.remove("move") taskMgr.remove('map') for child in render.getChildren(): child.removeNode() for item in self.OSimageText: item.destroy() leaderB = displayBigText('LEADERBOARD', (0.45, -0.3), (255, 255, 0, 1)) firstPlace = displaySmallText('1st:', (0.5, -0.5), (255, 255, 0, 1)) secondPlace = displaySmallText('2nd:', (0.5, -0.6), (255, 255, 0, 1)) #characters that didn't finish if self.mario.finishTime == 0: self.mario.finishTime = roundtoThou(self.mario.raceTime) if self.yoshi.finishTime == 0: self.yoshi.finishTime = roundtoThou(self.yoshi.raceTime) if self.mario.finishTime <= self.yoshi.finishTime: marioY = -0.5 yoshiY = -0.6 else: marioY = -0.6 yoshiY = -0.5 marioRight = displaySmallText('Mario (User)', (0.8, marioY), (255, 255, 0, 1)) marioLeft = displaySmallText(str(self.mario.finishTime), (1.8, marioY), (255, 255, 0, 1)) yoshiRight = displaySmallText('Yoshi (Computer)', (0.8, yoshiY), (255, 255, 0, 1)) marioLeft = displaySmallText(str(self.yoshi.finishTime), (1.8, yoshiY), (255, 255, 0, 1)) escText = displaySmallText('press esc to quit program', (0.7, -1.8), (255, 255, 255, 0.7)) #image from https://mariokart.fandom.com/wiki/Mario image = OnscreenImage(image='images/leaderboardmario.png', pos=(0.01, 0, -0.2), scale=0.4)
class Gauge: """ Represents a dynamic gauge linked to a global variable of the shuttle. """ def __init__(self, screen, name, x=0, low_value=-1, high_value=101, min=0, max=100): """ Creates a new gauge @param screen: the controlScreen instance @param name: the name of the corresponding global variable (soft_state). @param x: @param low_value: below this limit, @param high_value: @param min: minimum value @param max: maximum value """ self.taskMgr = screen.gameEngine.taskMgr self.update_func = screen.update self.screen = screen self.name = name self.low_value = low_value self.high_value = high_value self._hardware = screen.gameEngine.hardware self._sound = screen.gameEngine.sound_manager self.texture = OnscreenImage(image=screen.image_path + "indicateur.png", parent=screen.gui_render_node) self.texture.setTransparency(True) iH = PNMImageHeader() iH.readHeader(Filename(screen.image_path + "indicateur.png")) self.time_for_goto = None self.half_sec_step_for_goto = 1.0 self.w = iH.get_x_size() self.h = iH.get_y_size() self._limits = [min, max] iH.readHeader(Filename(screen.image_path + "screen.png")) self._x0 = x self._x = [-1 + self.w / iH.get_x_size(), 2 / iH.get_x_size()] self._y = [1 - self.h / iH.get_y_size(), -2 / iH.get_y_size()] self._gauge_min_y = 44 - 0.5 * self.h self._gauge_max_y = 466 - 0.5 * self.h self.texture.set_scale( LVector3f(self.w / iH.get_x_size(), 1, self.h / iH.get_y_size())) self._task_to_come = [] self.value = self.screen.gameEngine.get_soft_state(self.name) self._is_destroyed = False self.set_value() self.hide() def set_time_for_goto(self, time): self.time_for_goto = time self.half_sec_step_for_goto = None def set_half_sec_step_for_goto(self, step): self.half_sec_step_for_goto = step self.time_for_goto = None def _set_gimp_pos(self, x, y): self.texture.set_pos( (self._x[0] + x * self._x[1], 0.0, self._y[0] + y * self._y[1])) def set_color(self, color): self.texture.set_color(color) def destroy(self): self.texture.destroy() self._is_destroyed = True for i in range(len(self._task_to_come)): self.taskMgr.remove(self._task_to_come.pop()) def hide(self): self.texture.hide() def show(self): self.texture.show() def goto_value(self, new_value): # stop the previous tasks for i in range(len(self._task_to_come)): self.taskMgr.remove(self._task_to_come.pop()) def func(v): self.set_value(v) self.update_func.__call__() def stop(t=None): self._hardware.set_led_off("l_" + self.name + "_down") self._hardware.set_led_off("l_" + self.name + "_up") if self.low_value >= self.value: self._sound.play(self.name + "_low") elif self.high_value <= self.value: self._sound.play(self.name + "_high") self._hardware.set_led_off("l_" + self.name + "_down") self._hardware.set_led_off("l_" + self.name + "_up") step_by_half_sec = self.half_sec_step_for_goto if self.half_sec_step_for_goto is None: dx = abs(self.value - new_value) step_by_half_sec = 0.5 * dx / self.time_for_goto if self.value >= new_value: self._hardware.set_led_on("l_" + self.name + "_down") step_by_half_sec = -step_by_half_sec else: self._hardware.set_led_on("l_" + self.name + "_up") n_steps = -int((self.value - new_value) / step_by_half_sec) old_value = self.value for i in range(n_steps): self._task_to_come.append( self.taskMgr.doMethodLater( 0.5 * i, func, name="gauge_move", extraArgs=[old_value + (i + 1) * step_by_half_sec])) self._task_to_come.append( self.taskMgr.doMethodLater(0.5 * n_steps, stop, name="gauge_move_stop")) def set_value(self, value=None): if not self._is_destroyed: if self.value >= self._limits[1]: self.value = self._limits[1] elif self.value < self._limits[0]: self.value = self._limits[0] old_value = self.value if value is not None: if value >= self._limits[1]: value = self._limits[1] elif value < self._limits[0]: value = self._limits[0] self.value = value if old_value > self.low_value >= self.value: self._sound.play(self.name + "_low") self._hardware.set_led_on("l_" + self.name + "_low") elif old_value <= self.low_value < self.value: self._hardware.set_led_off("l_" + self.name + "_low") elif old_value < self.high_value <= self.value: self._sound.play(self.name + "_high") self._hardware.set_led_on("l_" + self.name + "_high") elif self.value < self.high_value <= old_value: self._hardware.set_led_off("l_" + self.name + "_high") self._set_gimp_pos( self._x0, self._gauge_max_y + (self.value - self._limits[0]) / (self._limits[1] - self._limits[0]) * (self._gauge_min_y - self._gauge_max_y))
class MainMenu(ShowBase): def __init__(self): ShowBase.__init__(self) self.accept("Exit",self.__exit) self.__rm = ResourcesManager() self.__destroySetting = False # 菜单界面 def start(self): #全屏 self.setFullScreen(0) #load background image self.__image = OnscreenImage(image='../../resources/images/menu/home1.png',scale=1) self.__image.setSx(self.getAspectRatio()) self.__image.setTransparency(TransparencyAttrib.MAlpha) # 监听输入 self.__keyInput = MenuPlayerInputHandler() self.accept("NewGame",self.__new_game) self.accept("LoadGame",self.__load_game) self.accept("Description",self.__description) self.accept("ChangeMenu",self.__change_menu) self.accept("a",self.setting_menu) self.accept("b",self.setting_destroy) # 设置全屏 def setFullScreen(self,full): if full == 1 : self.__setFullscreen(2560,1600,0,0,1) else: self.__setFullscreen(800,600,150,50,0) # 清除界面,清除监听 def destroy(self): self.__image.destroy() self.__keyInput.destroy() # 私有函数,选择全屏 def __setFullscreen(self, width, height, posX, posY, full): winProps = WindowProperties() winProps.setOrigin(posX, posY) winProps.setSize(width, height) winProps.setFullscreen(full) self.win.requestProperties(winProps) # 私有函数,进入新建游戏界面 def __new_game(self): print '进入new game' messenger.send("serious_new_game") print '发送了serious_new_game' # 私有函数,进入读取游戏界面 def __load_game(self): print '进入load game' messenger.send("serious_load_game") print '发送了serious_load_game' # 私有函数,进入about界面 def __description(self): print '进入description' messenger.send("serious_description") print '发送了serious_description' # 私有函数,用来自建的选择进入的游戏界面 def __change_mode(self,image_path): self.__image.setImage(image_path) def __exit(self): print '进入exit' # self.__del__() exit() # 私有函数,更改游戏目录 def __change_menu(self): switch_count = {0:'../../resources/images/menu/home1.png', 1:'../../resources/images/menu/home2.png', 2:'../../resources/images/menu/home3.png', 3:'../../resources/images/menu/home4.png',} self.__change_mode(switch_count[self.__keyInput.get_count()]) #设置界面 def setting_menu(self): if self.__destroySetting==False: # 设置界面背景图 self.__background = OnscreenImage(image='../../resources/images/settings/setting_frame.png', pos=(0, 0, 0), scale=(1.0, 0, 0.7)) self.__background.setTransparency(TransparencyAttrib.MAlpha) ##滑动条 self.__slider = DirectSlider(pos=(0.16, 0, 0.26), scale=0.5, value=0.5, command=self.__setMusicSliderVolume, frameSize=(-1.0, 0.9, -0.06, 0.06), image='../../resources/images/settings/slide_bar.png', image_pos=(-0.05, 0, 0.0), image_scale=(1.0, 0, 0.05), thumb_image='../../resources/images/settings/slide_btn.png', thumb_image_pos=(-0.0, 0, 0.0), thumb_image_scale=0.1, thumb_frameSize=(0.0, 0.0, 0.0, 0.0)) self.__slider.setTransparency(TransparencyAttrib.MAlpha) # self.__musicButton = DirectButton(pos=(0.9, 0, 0.75), text="Close", scale=0.1, pad=(0.2, 0.2), rolloverSound=None, # clickSound=None, command=self.toggleMusicBox,extraArgs=[base]) # 继续按钮 self.__continueButton = DirectButton(pos=(-0.25, 0, 0.0), text="", scale=(0.2, 0, 0.1), command=self.__continue_game, image=("../../resources/images/settings/btn_continue_0.png", "../../resources/images/settings/btn_continue_0.png" , "../../resources/images/settings/btn_continue_1.png"), frameColor=(0, 0, 0, 0)) self.__continueButton.setTransparency(TransparencyAttrib.MAlpha) # 存档按钮 self.__saveButton = DirectButton(pos=(0.33, 0, 0.0), text="", scale=(0.2, 0, 0.1), command=self.__save_game, image=("../../resources/images/settings/btn_save_0.png", "../../resources/images/settings/btn_save_0.png" , "../../resources/images/settings/btn_save_1.png"), frameColor=(0, 0, 0, 0)) self.__saveButton.setTransparency(TransparencyAttrib.MAlpha) # 帮助按钮 self.__helpButton = DirectButton(pos=(-0.25, 0, -0.25), text="", scale=(0.2, 0, 0.1), command=self.__help, image=("../../resources/images/settings/btn_help_0.png", "../../resources/images/settings/btn_help_0.png" , "../../resources/images/settings/btn_help_1.png"), frameColor=(0, 0, 0, 0)) self.__helpButton.setTransparency(TransparencyAttrib.MAlpha) # 回到主界面按钮 self.__homeButton = DirectButton(pos=(0.33, 0, -0.25), text="", scale=(0.2, 0, 0.1), command=self.__return_home, image=("../../resources/images/settings/btn_home_0.png", "../../resources/images/settings/btn_home_0.png" , "../../resources/images/settings/btn_home_1.png"), frameColor=(0, 0, 0, 0)) self.__homeButton.setTransparency(TransparencyAttrib.MAlpha) # 设置滑动条value self.__slider['value'] = self.__rm.get_volume() self.__destroySetting = True #移除设置界面所有控件 def setting_destroy(self): if self.__destroySetting==True: self.__background.destroy() self.__rm.set_volume(self.__slider['value']) self.__slider.destroy() # self.__musicButton.destroy() self.__continueButton.destroy() self.__saveButton.destroy() self.__helpButton.destroy() self.__homeButton.destroy() self.__destroySetting = False # 设置音乐声音大小 def __setMusicSliderVolume(self): newVolume = self.__slider.guiItem.getValue() self.__rm.set_volume(newVolume) # 设置界面,私有函数,继续游戏 def __continue_game(self): self.setting_destroy() # 设置界面,私有函数,存档 def __save_game(self): self.setting_destroy() # 设置界面,私有函数,游戏帮助 def __help(self): self.setting_destroy() # 设置界面,私有函数,回到主界面 def __return_home(self): self.setting_destroy()
class MainMenu(ShowBase): def __init__(self): ShowBase.__init__(self) #load background image self.__image = OnscreenImage(image='../../resources/images/main_menu.jpg', pos=(0, 0, 0), scale=1) self.__image.setSx(self.getAspectRatio()) self.__image.setTransparency(TransparencyAttrib.MAlpha) #Three main opertaions self.__newGameButton = DirectButton(pos=(-0.9, 0, 0.5,), text=("新的游戏"), scale=0.1, command=self.new_game,frameColor=(0,0,0,0), image=("../../resources/images/main_menu.jpg","../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) self.__selectArchiveButton = DirectButton(pos=(-0.9, 0, 0.3,), text="选择存档", scale=0.1,text_fg=(1,1,1,1), command=self.select_archives, frameColor=(0, 0, 0, 0), image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) self.__exitGameButton = DirectButton(pos=(-0.9, 0, 0.1,), text="退出游戏", scale=0.1,text_fg=(1,1,1,1), command=self.exit_game, frameColor=(0, 0, 0, 0), image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) #add task to update background-image scale self.taskMgr.add(self.example_task, 'exampleTask') self.__rm=ResourcesManager() # 移除界面上的按钮与图片 def destroy_all(self): self.__newGameButton.destroy() self.__selectArchiveButton.destroy() self.__exitGameButton.destroy() self.__image.destroy() self.taskMgr.remove('exampleTask') def new_game(self): self.destroy_all() self.__blood = Blood() # self.__rm.show_dialog(1) self.accept("a", self.__rm.show_dialog, [1]) self.accept("b", self.__rm.show_dialog, [2]) self.accept("x", self.__rm.show_dialog, [3]) self.accept("c", self.__rm.dialog_next) # self.accept("d", self.__rm.play_sound,[2]) # self.accept("e", self.__rm.stop_sound,[2]) # self.accept("f", self.__rm.play_sound,[4]) # self.accept("g", self.__rm.stop_sound,[4]) self.accept("z",self.__rm.set_path,["123"]) self.accept("y", self.__rm.show_dialog, [4]) self.accept("k", self.__rm.show_dialog, [9]) self.accept("0", self.__blood.init_blood) self.accept("1",self.__blood.bloodAdd) self.accept("2", self.__blood.bloodMinu) #调用对话 # lp=LoadPlot() # lp.init_interface() #调用声音 # ms=MySound() # ms.volume_slider() #调用视频 self.accept("h", self.__rm.play_media, [self.render2d,1]) self.accept("i", self.__rm.play_media, [self.render2d,2]) self.accept("i", self.__rm.destroy_media) def select_archives(self): self.destroy__all() def exit_game(self): self.destroy__all() def example_task(self,task): self.__image.setSx(self.getAspectRatio()) return Task.cont
class RankingGui(GuiColleague): def __init__(self, mediator, background_fpath, font, fg_col): GuiColleague.__init__(self, mediator) self.ranking_texts = [] self.background_path = background_fpath self.font = font self.fg_col = fg_col self.rank_menu = self.background = None @staticmethod def set_drv_txt_img(page, i, car_name, pos_x, top, text, players): drivers = [player.driver for player in players] info('drivers: ' + str([drv for drv in drivers])) info('i: %s - carname: %s - text: %s' % (i, car_name, text)) drv = next(player.driver for player in players if player.car == car_name) player_car_names = [ player.car for player in players if player.kind == Player.human ] is_player_car = car_name in player_car_names info('%s %s %s %s' % (text % drv.name, car_name, drv.img_idx, is_player_car)) name = text % drv.name if '@' in name: name = name.split('@')[0] + '\1smaller\1@' + name.split('@')[1] + \ '\2' txt = Text(name, align='left', scale=.072, pos=(pos_x, top - i * .16), font=page.font, fg=page.text_fg if is_player_car else page.text_bg) gprops = page.rprops.season_props.gameprops img = Img(gprops.cars_img % car_name, pos=(pos_x - .16, top + .02 - i * .16), scale=.074) filtervpath = RankingGui.eng.curr_path + \ 'yyagl/assets/shaders/filter.vert' with open(filtervpath) as fvs: vert = fvs.read() drvfpath = RankingGui.eng.curr_path + \ 'yyagl/assets/shaders/drv_car.frag' with open(drvfpath) as ffs: frag = ffs.read() shader = load_shader(vert, frag) if shader: img.set_shader(shader) img.set_transparent() t_s = TextureStage('ts') t_s.set_mode(TextureStage.MDecal) txt_path = gprops.drivers_img.path_sel % drv.img_idx img.set_texture(t_s, loader.loadTexture(txt_path)) return txt, img def show(self, rprops, sprops, ranking, players): self.background = OnscreenImage( sprops.gameprops.menu_props.background_img_path, scale=(1.77778, 1, 1)) self.background.setBin('background', 10) self.rank_menu = RankingMenu(rprops, sprops, ranking, players) def hide(self): self.background.destroy() self.rank_menu.destroy() def attach_obs(self, mth): self.rank_menu.attach_obs(mth) def detach_obs(self, mth): self.rank_menu.detach_obs(mth) def destroy(self): self.hide() self.rank_menu = self.ranking_texts = self.background = None GuiColleague.destroy(self)
class ToonFPS(DirectObject): notify = directNotify.newCategory("ToonFPS") WeaponName2DamageData = {"pistol": (30.0, 10.0, 150.0, 0.3), "shotgun": (40.0, 15.0, 155.0, 0.5), "sniper": (40.0, 15.0, 155.0, 0.5)} def __init__(self, mg, weaponName = "pistol"): self.mg = mg self.weaponName = weaponName self.v_model_root = None self.v_model = None self.weapon = None self.track = None self.draw = None self.shoot = None self.reload = None self.empty = None self.cockBack = None self.cockFwd = None self.player_node = None # blach (02Aug15) # Drastically improved the accuracy of bullets... DRASTICALLY self.shooterTrav = None self.shooterRay = None self.shooterRayNode = None self.shooterHandler = None self.gui = ToonFPSGui(self) self.fsm = ClassicFSM('ToonFPS', [State('off', self.enterOff, self.exitOff), State('alive', self.enterAlive, self.exitAlive), State('dead', self.enterDead, self.exitDead)], 'off', 'off') #self.deadFSM = ClassicFSM('dead', [State('off', self.enterOff, self.exitOff), # State(']) self.aliveFSM = ClassicFSM('alive', [State('off', self.enterOff, self.exitOff), State('draw', self.enterDraw, self.exitDraw, ['idle']), State('idle', self.enterIdle, self.exitIdle, ['shoot', 'reload']), State('shoot', self.enterShoot, self.exitShoot, ['idle']), State('reload', self.enterReload, self.exitReload, ['idle'])], 'off', 'off') self.fsm.getStateNamed('alive').addChild(self.aliveFSM) #self.fsm.getStateNamed('dead').addChild(self.deadFSM) self.fsm.enterInitialState() self.aliveFSM.enterInitialState() if self.weaponName == "pistol": self.ammo = 14 elif self.weaponName == "shotgun": self.ammo = 7 self.hp = 125 self.max_hp = 125 self.firstPerson = FirstPerson() def movementTask(self, task): if (inputState.isSet('jump') or base.localAvatar.walkControls.isAirborne): if base.localAvatar.getAnimState() != "jump": base.localAvatar.setAnimState("jump") base.localAvatar.playMovementSfx(None) self.mg.sendUpdate("jumpingAvatar", [base.localAvatar.doId]) return Task.cont def enterAlive(self): if not self.mg.fsm.getCurrentState().getName() in ['gameOver', 'announceGameOver', 'finalScores']: self.start() self.resetHp() self.resetAmmo() if self.mg.fsm.getCurrentState().getName() == "play": self.reallyStart() def exitAlive(self): self.end() self.v_model.reparentTo(hidden) if self.mg.fsm.getCurrentState().getName() != "play": self.reallyEnd() def updatePoints(self): self.points = self.kills - self.deaths def enterDead(self, killer): base.localAvatar.getGeomNode().show() self.gui.end() base.localAvatar.attachCamera() self.freezeCamSfx = base.loadSfx("phase_4/audio/sfx/freeze_cam.ogg") self.freezeCamImage = None self.freezeCamImageFile = None base.camera.setZ(base.camera.getZ() + 2.0) taskMgr.add( self.cameraLookAtKillerTask, "lookAtKiller", extraArgs = [killer], appendTask = True ) taskMgr.doMethodLater( 2.0, self.startZoomOnKiller, "startFreezeCam", extraArgs = [killer], appendTask = True ) def startZoomOnKiller(self, killer, task): taskMgr.add( self.__zoomOnKillerTask, "zoomOnKiller", extraArgs = [killer], appendTask = True ) return task.done def __zoomOnKillerTask(self, killer, task): if base.camera.getDistance(killer) <= 10.0 and self.freezeCamSfx.status() == self.freezeCamSfx.READY: base.playSfx(self.freezeCamSfx) if base.camera.getDistance(killer) < 7.0: self.doFreezeCam() return task.done base.camera.setY(base.camera, 60 * globalClock.getDt()) return task.again def doFreezeCam(self): taskMgr.remove("lookAtKiller") self.frameBuffer = PNMImage() base.win.getScreenshot(self.frameBuffer) self.freezeCamTex = Texture() self.freezeCamTex.load(self.frameBuffer) self.freezeCamImage = OnscreenImage(image = self.freezeCamTex, parent=render2d) def cameraLookAtKillerTask(self, killer, task): try: base.camera.lookAt(killer, 0, 0, 3) except AssertionError: pass return task.cont def exitDead(self): taskMgr.remove("zoomOnKiller") taskMgr.remove("lookAtKiller") taskMgr.remove("startFreezeCam") del self.freezeCamSfx if self.freezeCamImage: self.freezeCamImage.destroy() del self.freezeCamImage self.frameBuffer.clear() self.freezeCamTex.clear() del self.frameBuffer del self.freezeCamTex base.localAvatar.detachCamera() base.localAvatar.getGeomNode().hide() self.gui.start() def load(self): if self.weaponName == "pistol": self.draw = base.loadSfx("phase_4/audio/sfx/draw_secondary.ogg") self.shoot = base.loadSfx("phase_4/audio/sfx/pistol_shoot.ogg") self.reload = base.loadSfx("phase_4/audio/sfx/pistol_worldreload.ogg") elif self.weaponName == "sniper": self.draw = base.loadSfx("phase_4/audio/sfx/draw_primary.ogg") self.shoot = base.loadSfx("phase_4/audio/sfx/shotgun_shoot.ogg") self.cockBack = base.loadSfx("phase_4/audio/sfx/shotgun_cock_back.ogg") self.cockFwd = base.loadSfx("phase_4/audio/sfx/shotgun_cock_forward.ogg") elif self.weaponName == "shotgun": self.draw = base.loadSfx("phase_4/audio/sfx/draw_primary.ogg") self.shoot = base.loadSfx("phase_4/audio/sfx/shotgun_shoot.ogg") self.cockBack = base.loadSfx("phase_4/audio/sfx/shotgun_cock_back.ogg") self.cockFwd = base.loadSfx("phase_4/audio/sfx/shotgun_cock_forward.ogg") self.empty = base.loadSfx("phase_4/audio/sfx/shotgun_empty.ogg") self.v_model_root = base.camera.attachNewNode('v_model_root') self.v_model = Actor('phase_4/models/minigames/v_dgm.egg', {'pidle': 'phase_4/models/minigames/v_dgm-pistol-idle.egg', 'pshoot': 'phase_4/models/minigames/v_dgm-pistol-shoot.egg', 'preload': 'phase_4/models/minigames/v_dgm-pistol-reload.egg', 'pdraw': 'phase_4/models/minigames/v_dgm-pistol-draw.egg', 'sidle': 'phase_4/models/minigames/v_dgm-shotgun-idle.egg', 'sshoot': 'phase_4/models/minigames/v_dgm-shotgun-shoot.egg'}) if self.weaponName == "pistol": self.weapon = loader.loadModel("phase_4/models/props/water-gun.bam") self.weapon.reparentTo(self.v_model.exposeJoint(None, "modelRoot", "Bone.011")) self.weapon.setX(-0.125) self.weapon.setY(0.5) self.weapon.setScale(0.65) elif self.weaponName == "sniper": self.weapon = loader.loadModel("phase_4/models/props/sniper.egg") self.weapon.reparentTo(self.v_model.exposeJoint(None, "modelRoot", "Bone.029")) self.weapon.setScale(0.75) self.weapon.setPos(0.45, -1.03, -1.17) self.weapon.setHpr(9.46, 308.19, 75.78) elif self.weaponName == "shotgun": self.weapon = loader.loadModel("phase_4/models/props/shotgun.egg") self.weapon.reparentTo(self.v_model.exposeJoint(None, "modelRoot", "Bone.029")) self.weapon.setScale(0.75) self.weapon.setPos(0.45, -1.03, -1.17) self.weapon.setHpr(9.46, 308.19, 75.78) self.gui.load() def start(self): base.camLens.setNear(0.1) self.shooterTrav = CollisionTraverser('ToonFPS.shooterTrav') ray = CollisionRay() rayNode = CollisionNode('ToonFPS.rayNode') rayNode.addSolid(ray) rayNode.setCollideMask(BitMask32(0)) rayNode.setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask) self.shooterRay = ray self.shooterRayNode = base.camera.attachNewNode(rayNode) self.shooterHandler = CollisionHandlerQueue() self.shooterTrav.addCollider(self.shooterRayNode, self.shooterHandler) self.firstPerson.start() self.v_model_root.reparentTo(base.camera) self.v_model.reparentTo(self.v_model_root) if self.weaponName == "pistol": self.v_model_root.setZ(-1.8) self.v_model_root.setY(0.3) self.v_model_root.setX(-0.1) self.v_model_root.setH(2) elif self.weaponName == "sniper": self.v_model_root.setPos(-0.42, -0.81, -1.7) self.v_model_root.setHpr(359, 352.87, 0.00) elif self.weaponName == "shotgun": self.v_model_root.setPos(-0.42, -0.81, -1.7) self.v_model_root.setHpr(359, 352.87, 0.00) self.gui.start() self.firstPerson.disableMouse() self.aliveFSM.request('draw') def reallyStart(self): self.firstPerson.reallyStart() base.localAvatar.startTrackAnimToSpeed() #taskMgr.add(self.movementTask, "toonBattleMovement") def end(self): if self.aliveFSM.getCurrentState().getName() != 'off': self.aliveFSM.request('off') if self.firstPerson: self.firstPerson.enableMouse() self.firstPerson.end() taskMgr.remove("toonBattleMovement") if self.mg.fsm.getCurrentState().getName() != "play": self.fsm.request('off') def reallyEnd(self): try: self.ToonFPS_reallyEnded return except: self.ToonFPS_reallyEnded = 1 if self.shooterRayNode: self.shooterRayNode.removeNode() self.shooterRayNode = None self.shooterRay = None self.shooterTrav = None self.shooterHandler = None if self.firstPerson: self.firstPerson.reallyEnd() if self.v_model_root: self.v_model_root.reparentTo(hidden) if self.v_model: self.v_model.reparentTo(hidden) self.v_model.setPosHpr(0, 0, 0, 0, 0, 0) if self.gui: self.gui.end() base.camLens.setNear(1.0) def cleanup(self): try: self.ToonFPS_cleanedUp return except: self.ToonFPS_cleanedUp = 1 taskMgr.remove("lookAtKiller") taskMgr.remove("toonBattleMovement") if self.firstPerson: self.firstPerson.cleanup() self.firstPerson = None self.draw = None self.shoot = None self.reload = None self.empty = None self.ammo = None try: self.aliveFSM.requestFinalState() self.fsm.requestFinalState() except: self.notify.warning('Redundant call to enter the final state.') self.fsm = None self.aliveFSM = None self.player_node = None self.min_camerap = None self.max_camerap = None self.hp = None self.max_hp = None if self.v_model: self.v_model.cleanup() self.v_model = None if self.weapon: self.weapon.removeNode() self.weapon = None if self.weapon: self.v_model_root.removeNode() self.v_model_root = None if self.gui: self.gui.cleanup() def damageTaken(self, amount, avId): if self.hp <= 0.0: killer = self.mg.cr.doId2do.get(avId, None) self.fsm.request('dead', [killer]) self.gui.adjustHpMeter() def enterDraw(self): self.draw.play() if self.weaponName == "pistol": self.track = ActorInterval(self.v_model, 'pdraw', playRate = 1.6, name = 'drawTrack') elif self.weaponName == "shotgun": self.v_model.pose('sidle', 15) self.track = LerpQuatInterval(self.v_model, duration = 0.5, quat = (0, 0, 0), startHpr = (70, -50, 0), blendType = 'easeOut', name = 'drawTrack') elif self.weaponName == "sniper": self.v_model.pose('sidle', 15) self.track = LerpQuatInterval(self.v_model, duration = 0.5, quat = (0, 0, 0), startHpr = (70, -50, 0), blendType = 'easeOut', name = 'drawTrack') self.track.setDoneEvent(self.track.getName()) self.acceptOnce(self.track.getDoneEvent(), self.aliveFSM.request, ['idle']) self.track.start() def exitDraw(self): #self.draw.stop() if self.track: self.ignore(self.track.getDoneEvent()) self.track.finish() self.track = None def enterIdle(self): if self.weaponName == "pistol": self.v_model.loop('pidle') elif self.weaponName == "shotgun": self.track = Sequence(LerpQuatInterval(self.v_model, duration = 2.0, quat = (0, 1, 0), startHpr = (0, 0, 0), blendType = 'easeInOut'), LerpQuatInterval(self.v_model, duration = 2.0, quat = (0, 0, 0), startHpr = (0, 1, 0), blendType = 'easeInOut')) self.track.loop() elif self.weaponName == "sniper": self.track = Sequence(LerpQuatInterval(self.v_model, duration = 2.0, quat = (0, 1, 0), startHpr = (0, 0, 0), blendType = 'easeInOut'), LerpQuatInterval(self.v_model, duration = 2.0, quat = (0, 0, 0), startHpr = (0, 1, 0), blendType = 'easeInOut')) self.track.loop() self.accept('mouse1', self.requestShoot) if self.ammo <= 0: self.gui.notifyNoAmmo() if self.ammo < 14: self.accept('r', self.aliveFSM.request, ['reload']) def requestShoot(self): if self.mg.fsm.getCurrentState().getName() != "play": return if self.ammo > 0: self.aliveFSM.request('shoot') else: self.empty.play() def exitIdle(self): self.v_model.stop() if self.track: self.track.finish() self.track = None self.ignore('mouse1') self.ignore('r') def enterShoot(self): self.shoot.play() if self.weaponName == "pistol": self.track = ActorInterval(self.v_model, 'pshoot', playRate = 2, name = 'shootTrack') elif self.weaponName == "shotgun": self.track = Parallel( Sequence( LerpQuatInterval(self.v_model, duration = 0.05, quat = (0, 3, 0), startHpr = (0, 0, 0)), LerpQuatInterval(self.v_model, duration = 0.1, quat = (0, 0, 0), startHpr = (0, 3, 0)) ), Sequence( LerpPosInterval(self.v_model, duration = 0.05, pos = (0, -0.3, 0), startPos = (0, 0, 0)), LerpPosInterval(self.v_model, duration = 0.1, pos = (0, 0, 0), startPos = (0, -0.3, 0)), Wait(0.1) ), ) elif self.weaponName == "sniper": self.track = Parallel( Sequence( LerpQuatInterval(self.v_model, duration = 0.05, quat = (0, 3, 0), startHpr = (0, 0, 0)), LerpQuatInterval(self.v_model, duration = 0.1, quat = (0, 0, 0), startHpr = (0, 3, 0)) ), Sequence( LerpPosInterval(self.v_model, duration = 0.05, pos = (0, -0.3, 0), startPos = (0, 0, 0)), LerpPosInterval(self.v_model, duration = 0.1, pos = (0, 0, 0), startPos = (0, -0.3, 0)), Wait(0.1) ), ) self.track.setDoneEvent('shootTrack') self.acceptOnce(self.track.getDoneEvent(), self.aliveFSM.request, ['idle']) self.track.start() self.ammo -= 1 self.gui.adjustAmmoGui() self.mg.makeSmokeEffect(self.weapon.find('**/joint_nozzle').getPos(render)) self.traverse() def traverse(self): mpos = base.mouseWatcherNode.getMouse() self.shooterRay.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.shooterTrav.traverse(render) def calcDamage(self, avatar): dmgData = self.WeaponName2DamageData[self.weaponName] maxDamage = dmgData[0] minDistance = dmgData[1] maxDistance = dmgData[2] factor = dmgData[3] distance = base.localAvatar.getDistance(avatar) if distance < minDistance: distance = minDistance elif distance > maxDistance: distance = maxDistance damage = maxDamage - ((distance - minDistance) * factor) return damage def exitShoot(self): #self.shoot.stop() self.ignore('shootTrack') if self.track: self.track.finish() self.track = None def enterReload(self): self.gui.deleteNoAmmoLabel() if self.weaponName == "pistol": self.track = Parallel(Sequence(Wait(0.3), Func(self.reload.play), Func(self.resetAmmo)), ActorInterval(self.v_model, 'preload', playRate = 1.5), name = 'reloadTrack') elif self.weaponName == "shotgun": self.track = Sequence(Func(self.draw.play), LerpQuatInterval(self.v_model, duration = 0.5, quat = (70, -50, 0), startHpr = (0, 0, 0), blendType = 'easeIn'), SoundInterval(self.cockBack), SoundInterval(self.cockFwd), Func(self.resetAmmo), Func(self.draw.play), LerpQuatInterval(self.v_model, duration = 0.5, quat = (0, 0, 0), startHpr = (70, -50, 0), blendType = 'easeOut'), name = 'reloadTrack') elif self.weaponName == "sniper": self.track = Sequence(Func(self.draw.play), LerpQuatInterval(self.v_model, duration = 0.5, quat = (70, -50, 0), startHpr = (0, 0, 0), blendType = 'easeIn'), SoundInterval(self.cockBack), SoundInterval(self.cockFwd), Func(self.resetAmmo), Func(self.draw.play), LerpQuatInterval(self.v_model, duration = 0.5, quat = (0, 0, 0), startHpr = (70, -50, 0), blendType = 'easeOut'), name = 'reloadTrack') self.track.setDoneEvent('reloadTrack') self.acceptOnce(self.track.getDoneEvent(), self.aliveFSM.request, ['idle']) self.track.start() def exitReload(self): #self.reload.stop() self.ignore('reloadTrack') if self.track: self.track.finish() self.track = None def resetAmmo(self): if self.weaponName == "pistol": self.ammo = 14 elif self.weaponName == "shotgun": self.ammo = 7 elif self.weaponName == "sniper": self.ammo = 7 self.gui.resetAmmo() def resetHp(self): self.hp = self.max_hp self.gui.adjustHpMeter() def enterOff(self): pass def exitOff(self): pass
class TitleScreen: def __init__(self): self.bg_particle = particle.StarParticles() self.bg_particle.start(render2d) self.bg_particle.setPos(.0, 1.5, 1.0) self.TITLE_SCALE = (512.0/base.win.getXSize(), 1 ,256.0/base.win.getYSize()) self.bg = OnscreenImage(image='./image/bg.png', pos = (0.0, 2.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) self.title_img = OnscreenImage(image='./image/title.png', pos = (0.0, 1.0, 0.6), scale = self.TITLE_SCALE, parent=render2d) self.title_img.setTransparency(TransparencyAttrib.MAlpha) texts = [OnscreenText(text='Start', scale=0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)), OnscreenText(text='Training', scale=0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)), OnscreenText(text='Options', scale=0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)), OnscreenText(text='Exit', scale=0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1))] for i in range(len(texts)): node = aspect2d.attachNewNode("TextPos%d" % i) texts[i].reparentTo(node) node.setZ(-0.15*(i+1) - .08) self.options = [ { 'action':'start', 'node': texts[0], }, { 'action':'training', 'node': texts[1] }, { 'action':'options', 'node': texts[2] }, { 'action':'exit', 'node': texts[3] }, ] for opt in self.options: opt['sel_interval'] = Parallel(LerpScaleInterval(opt["node"], duration=0.2, startScale=1.0, scale=1.4, blendType='easeOut'), SoundInterval(menuSfx)) opt['des_interval'] = LerpScaleInterval(opt["node"], duration=0.2, startScale=1.4, scale=1.0, blendType='easeOut') self.curr_option = 0 self.options[self.curr_option]['sel_interval'].finish() self.copyright_text = OnscreenText(text='MoonBunny (c) TrombaSoft 2007', shadow=(.0,.0,.0,1), scale=0.09, pos=(.0, -.95), align=TextNode.ACenter, fg=(1,1,1,1)) def option_changed(self, command): int1 = self.options[self.curr_option]['des_interval'] if command=='up': self.curr_option = (self.curr_option - 1) % len(self.options) elif command=='down': self.curr_option = (self.curr_option + 1) % len(self.options) int2 = self.options[self.curr_option]['sel_interval'] Parallel(int1, int2).start() def option_pressed(self): return self.options[self.curr_option]['action'] def clear(self): self.bg_particle.cleanup() self.bg.destroy() self.title_img.destroy() for opt in self.options: opt['node'].destroy() self.copyright_text.destroy()
class GameTest(ShowBase): def __init__(self): ShowBase.__init__(self) base.disableMouse() self.makeAcog = loader.loadModel("phase_5/models/cogdominium/tt_m_ara_cbr_barrelRoom.bam") self.makeAcog.reparentTo(render) self.stomper1 = (self.makeAcog.find('**/stomper_GRP_01')) self.stomper2 = (self.makeAcog.find('**/stomper_GRP_02')) self.stomper3 = (self.makeAcog.find('**/stomper_GRP_03')) self.stomper4 = (self.makeAcog.find('**/stomper_GRP_04')) self.stomper5 = (self.makeAcog.find('**/stomper_GRP_05')) self.stomper6 = (self.makeAcog.find('**/stomper_GRP_06')) self.stomper7 = (self.makeAcog.find('**/stomper_GRP_07')) self.stomper8 = (self.makeAcog.find('**/stomper_GRP_08')) self.stomper9 = (self.makeAcog.find('**/stomper_GRP_09')) self.stomper10 = (self.makeAcog.find('**/stomper_GRP_10')) self.stomper11 = (self.makeAcog.find('**/stomper_GRP_11')) self.stomper12 = (self.makeAcog.find('**/stomper_GRP_12')) self.stomper3.setPos(0, 0, 18.00) self.stomper5.setPos(0, 0, 10.00) self.stomper4.setPos(0, 0, 22.00) self.stomper2.setPos(0, 0, 7.00) self.stomper7.setPos(0, 0, 0) self.stomper8.setPos(0, 0, 5.00) self.stomper9.setPos(0, 0, 13.00) self.stomper10.setPos(0, 0, 10.00) self.stomper11.setPos(0, 0, 22.00) self.stomper12.setPos(0, 0, 7.00) self.music = loader.loadMusic("phase_3/audio/bgm/cco_make_a_cog.wav") self.music.play() self.music.setLoop(True) self.elevator = loader.loadModel("phase_5/models/cogdominium/cogdominiumElevator.bam") self.elevator.reparentTo(self.render) self.elevator.setY(25.37) self.elevator.find('**/floor_light_buttons').removeNode() self.rightDoor = (self.elevator.find('**/right_door')) self.leftDoor = (self.elevator.find('**/left_door')) self.leftDoor.setX(3.50) self.rightDoor.setX(-3.50) self.skelCog = Actor("phase_5/models/char/cogC_robot-lose-mod.bam", {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.skelCog.reparentTo(self.render) self.skelCog.setPos(-16, 0, -4.76) self.skelCog.setH(180) self.Lawbot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Lawbot.reparentTo(render) self.Lawbot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/l_blazer.jpg') self.Lawbot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/l_sleeve.jpg') self.Lawbot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/l_leg.jpg') self.Lawbot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/suitC-heads.bam').find('**/flunky') self.headTexture = loader.loadTexture("phase_3.5/maps/bottom-feeder.jpg") self.Head.reparentTo(self.Lawbot.find('**/joint_head')) self.Lawbot.findAllMatches('**/joint_head').setTexture(self.headTexture, 1) self.icon = loader.loadModel('phase_3/models/gui/cog_icons.bam') self.icon.reparentTo(render) self.icon.reparentTo(self.Lawbot.find('**/joint_attachMeter')) self.icon.find('**/MoneyIcon').removeNode() self.icon.find('**/cog').removeNode() self.icon.find('**/SalesIcon').removeNode() self.icon.find('**/CorpIcon').removeNode() self.icon.setH(180) self.icon.setScale(0.70) self.Lawbot.setH(180.00) self.Lawbot.hide() self.Cashbot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Cashbot.reparentTo(render) self.Cashbot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/m_blazer.jpg') self.Cashbot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/m_sleeve.jpg') self.Cashbot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/m_leg.jpg') self.Cashbot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/suitC-heads.bam').find('**/coldcaller') self.Head.reparentTo(self.Cashbot.find('**/joint_head')) self.icon = loader.loadModel('phase_3/models/gui/cog_icons.bam') self.icon.reparentTo(render) self.icon.reparentTo(self.Cashbot.find('**/joint_attachMeter')) self.icon.find('**/SalesIcon').removeNode() self.icon.find('**/cog').removeNode() self.icon.find('**/LegalIcon').removeNode() self.icon.find('**/CorpIcon').removeNode() self.icon.setH(180) self.icon.setScale(0.70) self.Cashbot.setH(180.00) self.Cashbot.hide() self.Sellbot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Sellbot.reparentTo(render) self.Sellbot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/s_blazer.jpg') self.Sellbot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/s_sleeve.jpg') self.Sellbot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/s_leg.jpg') self.Sellbot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/suitC-heads.bam').find('**/coldcaller') self.Head.reparentTo(self.Sellbot.find('**/joint_head')) self.Head.reparentTo(self.Sellbot.find('**/joint_head')) self.icon = loader.loadModel('phase_3/models/gui/cog_icons.bam') self.icon.reparentTo(render) self.icon.reparentTo(self.Sellbot.find('**/joint_attachMeter')) self.icon.find('**/MoneyIcon').removeNode() self.icon.find('**/cog').removeNode() self.icon.find('**/LegalIcon').removeNode() self.icon.find('**/CorpIcon').removeNode() self.icon.setH(180) self.icon.setScale(0.70) self.Sellbot.setH(180.00) self.Sellbot.hide() self.Bossbot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Bossbot.reparentTo(render) self.Bossbot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/c_blazer.jpg') self.Bossbot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/c_sleeve.jpg') self.Bossbot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/c_leg.jpg') self.Bossbot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/suitC-heads.bam') self.Head.find('**/coldcaller').hide() self.Head.find('**/gladhander').hide() self.Head.find('**/micromanager').hide() self.Head.find('**/moneybags').hide() self.Head.find('**/tightwad').hide() self.Head.reparentTo(self.Bossbot.find('**/joint_head')) self.icon = loader.loadModel('phase_3/models/gui/cog_icons.bam') self.icon.reparentTo(render) self.icon.reparentTo(self.Bossbot.find('**/joint_attachMeter')) self.icon.find('**/MoneyIcon').removeNode() self.icon.find('**/cog').removeNode() self.icon.find('**/LegalIcon').removeNode() self.icon.find('**/SalesIcon').removeNode() self.icon.setH(180) self.icon.setScale(0.70) self.Bossbot.setH(180.00) self.Bossbot.hide() self.Sourcebot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Sourcebot.reparentTo(render) self.Sourcebot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/t_blazer.jpg') self.Sourcebot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/t_sleeve.jpg') self.Sourcebot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/t_leg.jpg') self.Sourcebot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/FlairDirector.egg') self.headTexture = loader.loadTexture("phase_3.5/maps/flair-director.jpg") self.Head.reparentTo(self.Sourcebot.find('**/joint_head')) self.Sourcebot.findAllMatches('**/joint_head').setTexture(self.headTexture, 1) self.Sourcebot.setH(180.00) self.Sourcebot.hide() self.Techbot = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Techbot.reparentTo(render) self.Techbot.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/t_blazer.jpg') self.Techbot.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/t_sleeve.jpg') self.Techbot.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/t_leg.jpg') self.Techbot.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/PayrollConvertor.egg') self.headTexture = loader.loadTexture("phase_3.5/maps/PayrollConvertor.png") self.Head.reparentTo(self.Techbot.find('**/joint_head')) self.Head.setPos(0, 0, -0.15) self.Head.setScale(0.93) self.Techbot.findAllMatches('**/joint_head').setTexture(self.headTexture, 1) self.Techbot.setH(180.00) self.Techbot.hide() self.Pilotbots = Actor('phase_3.5/models/char/suitC-mod.bam', {'neutral': 'phase_3.5/models/char/suitC-neutral.bam', 'victory': 'phase_4/models/char/suitC-victory.bam', 'walk': 'phase_3.5/models/char/suitC-walk.bam'}) self.Pilotbots.reparentTo(render) self.Pilotbots.loop('neutral') self.TorsoTex = loader.loadTexture('phase_3.5/maps/t_blazer.jpg') self.Pilotbots.find('**/torso').setTexture(self.TorsoTex, 1) self.ArmTex = loader.loadTexture('phase_3.5/maps/t_sleeve.jpg') self.Pilotbots.find('**/arms').setTexture(self.ArmTex, 1) self.LegTex = loader.loadTexture('phase_3.5/maps/t_leg.jpg') self.Pilotbots.find('**/legs').setTexture(self.LegTex, 1) self.Head = loader.loadModel('phase_3.5/models/char/ConstructionBot.egg') self.headTexture = loader.loadTexture("phase_3.5/maps/Buildbot.png") self.Head.reparentTo(self.Pilotbots.find('**/joint_head')) self.Head.setPos(0, 0, -0.15) self.icon.setH(180) self.Pilotbots.findAllMatches('**/joint_head').setTexture(self.headTexture, 1) self.Pilotbots.setH(180.00) self.Pilotbots.hide() #-----Sequences------# Walk1 = self.stomper1.posInterval(9.50, Point3(0, 0, 18.00)) Walk2 = self.stomper1.posInterval(9.50, Point3(0, 0, 0)) self.stomperPound1 = Sequence(Walk1, Walk2) self.stomperPound1.loop() Walk1 = self.stomper6.posInterval(9.50, Point3(0, 0, 18.00)) Walk2 = self.stomper6.posInterval(9.50, Point3(0, 0, 0)) self.stomperPound2 = Sequence(Walk1, Walk2) self.stomperPound2.loop() Walk1 = self.stomper3.posInterval(9.50, Point3(0, 0, 0)) Walk2 = self.stomper3.posInterval(9.50, Point3(0, 0, 18.00)) self.stomperPound3 = Sequence(Walk1, Walk2) self.stomperPound3.loop() Walk1 = self.stomper5.posInterval(5.50, Point3(0, 0, 0)) Walk2 = self.stomper5.posInterval(5.50, Point3(0, 0, 10.00)) self.stomperPound4 = Sequence(Walk1, Walk2) self.stomperPound4.loop() Walk1 = self.stomper4.posInterval(5.50, Point3(0, 0, 0)) Walk2 = self.stomper4.posInterval(5.50, Point3(0, 0, 22.00)) self.stomperPound5 = Sequence(Walk1, Walk2) self.stomperPound5.loop() Walk1 = self.stomper2.posInterval(3.50, Point3(0, 0, 0)) Walk2 = self.stomper2.posInterval(3.50, Point3(0, 0, 7.00)) self.stomperPound6 = Sequence(Walk1, Walk2) self.stomperPound6.loop() Walk1 = self.stomper7.posInterval(9.50, Point3(0, 0, 18.00)) Walk2 = self.stomper7.posInterval(9.50, Point3(0, 0, 0)) self.stomperPound7 = Sequence(Walk1, Walk2) self.stomperPound7.loop() Walk1 = self.stomper8.posInterval(5.50, Point3(0, 0, 5.00)) Walk2 = self.stomper8.posInterval(9.50, Point3(0, 0, 0)) self.stomperPound8 = Sequence(Walk1, Walk2) self.stomperPound8.loop() Walk1 = self.stomper9.posInterval(6.50, Point3(0, 0, 0)) Walk2 = self.stomper9.posInterval(6.50, Point3(0, 0, 13.00)) self.stomperPound9 = Sequence(Walk1, Walk2) self.stomperPound9.loop() Walk1 = self.stomper10.posInterval(5.50, Point3(0, 0, 0)) Walk2 = self.stomper10.posInterval(5.50, Point3(0, 0, 10.00)) self.stomperPound10 = Sequence(Walk1, Walk2) self.stomperPound10.loop() Walk1 = self.stomper11.posInterval(5.50, Point3(0, 0, 0)) Walk2 = self.stomper11.posInterval(5.50, Point3(0, 0, 22.00)) self.stomperPound11 = Sequence(Walk1, Walk2) self.stomperPound11.loop() Walk1 = self.stomper12.posInterval(3.50, Point3(0, 0, 0)) Walk2 = self.stomper12.posInterval(3.50, Point3(0, 0, 7.00)) self.stomperPound12 = Sequence(Walk1, Walk2) self.stomperPound12.loop() Walk1 = self.camera.posInterval(2.50, Point3(-20.98, -14.61, 9.74)) Spin1 = self.camera.hprInterval(1.00, Vec3(321.34, 348.11, 0)) cogSpin = self.Sellbot.hprInterval(1.50, Vec3(0, 0, 0)) Walk2 = self.camera.posInterval(5.0, Point3(-20.98, -14.61, 9.74)) Walk3 = self.camera.posInterval(1.50, Point3(-20.98, 1.40, 7.97)) Spin2 = self.camera.hprInterval(1.00, Vec3(281.31, 348.11, 0)) Walk4 = self.camera.posInterval(8.50, Point3(-20.98, 1.40, 7.97)) Walk5 = self.camera.posInterval(2.50, Point3(0, -19.61, 2.61)) Spin3 = self.camera.hprInterval(1.00, Vec3(0, 0, 0)) self.cameraMove = Sequence(Walk1, Spin1, cogSpin, Walk2, Walk3, Spin2, Walk4, Walk5, Spin3) Walk1 = self.camera.posInterval(1.50, Point3(0, -77.48, 3.42)) Spin1 = self.camera.hprInterval(1.00, Vec3(0, 0, 0)) Walk2 = self.camera.posInterval(2.50, Point3(0, -77.48, 3.42)) Walk3 = self.camera.posInterval(3.00, Point3(0, -22.48, 3.42)) Walk4 = self.camera.posInterval(2.00, Point3(0, -22.48, 3.42)) skelMove1 = self.skelCog.posInterval(0.50, Point3(-16, -0, 0)) skelMove2 = self.skelCog.posInterval(2.00, Point3(0, -0, 0)) self.cameraStart = Sequence(Walk1, Spin1, Walk2, Walk3, Walk4, skelMove1, skelMove2) Walk1 = self.camera.posInterval(15.50, Point3(6.31, -45.31, 9.27)) Spin1 = self.camera.hprInterval(0.00, Vec3(337.52, 0, 0)) Walk2 = self.camera.posInterval(0.00, Point3(6.08, -100.53, 9.27)) Walk3 = self.camera.posInterval(12.00, Point3(14.07, -77.33, 9.27)) Walk4 = self.camera.posInterval(0.00, Point3(18.93, -82.36, 25.51)) Spin2 = self.camera.hprInterval(0.00, Vec3(30.26, 347.91, 0)) Walk5 = self.camera.posInterval(15.00, Point3(0.44, -51.38, 21.411)) Spin3 = self.camera.hprInterval(0.00, Vec3(337.52, 0, 0)) self.cameraIntro = Sequence(Walk1, Spin1, Walk2, Walk3, Walk4, Spin2, Walk5, Spin3) self.cameraIntro.loop() #----camera---# self.camera.setPos(6.31, -82.36, 9.27) self.camera.setHpr(35.71, 0, 0) #--------Start-up-Menu--------# #-----buttons-------# #-----texts-------# self.logoLeft = OnscreenImage(image='phase_3/maps/cogcitycodeaffix-logo-hor-left[OLD].png', pos=(-0.46, 0, 0.2), scale=(0.7)) self.logoLeft.setTransparency(TransparencyAttrib.MAlpha) self.logoRight = OnscreenImage(image='phase_3/maps/cogcitycodeaffix-logo-hor-right[OLD].png', pos=(0.56, 0, 0.18), scale=(0.7)) self.logoRight.setTransparency(TransparencyAttrib.MAlpha) font = self.loader.loadFont("phase_3/models/fonts/vtRemingtonPortable.ttf") text = TextNode("play") text.setText("Press F1 to play") text.setFont(font) self.textNodePath = aspect2d.attachNewNode(text) self.textNodePath.setScale(0.09) self.textNodePath.setPos(-0.5, 0, -0.7) #-----optionText-----------# fps = "Show FPS: f2" self.textObject1 = OnscreenText(text=fps, pos=(-1.4, -0.97), scale=0.09, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) self.textObject1.setFont(font) fullscreen = "Fullscreen: f2" self.textObject2 = OnscreenText(text=fullscreen, pos=(-1.34, -0.88), scale=0.09, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) self.textObject2.setFont(font) audio = "Audio: f4" self.textObject3 = OnscreenText(text=audio, pos=(-1.48, -0.78), scale=0.09, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) self.textObject3.setFont(font) #------doneButton--------# font = self.loader.loadFont("phase_3/models/fonts/vtRemingtonPortable.ttf") bk_text = "" textObject = OnscreenText(text=bk_text, pos=(0.00, 0.73), scale=0.16, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) textObject.setFont(font) textObject.setColor(0.3, 0.3, 0.35, 1.0) def setText(status): if (status): bk_text = "Do you want to continue?" else: bk_text = "" textObject.setText(bk_text) self.DoneButton = DirectCheckButton(text="Continue", scale=0.12, pos=(0, 0, -0.80), command=setText) self.DoneButton.hide() #----------key/click-events-------# self.acceptOnce("f1-up", self.play) self.accept("f2-up", self.frameRate) def moveCamera(self): if self.camera: self.cameraMove.start() else: self.cameraMove.stop() def popupGUI(self): if self.DoneButton: self.DoneButton.show() def frameRate(self): if self.textObject1: self.setFrameRateMeter(True) else: self.setFrameRateMeter(False) def play(self): if self.logoRight: self.logoRight.destroy() self.logoLeft.destroy() self.textObject3.hide() self.textObject2.hide() self.textObject1.hide() self.textNodePath.hide() self.cameraIntro.pause() self.cameraStart.start()
class LevelSelectScreen: def __init__(self, game_opts): self.ITEM_SPACING = 1.7 self.game_opts = game_opts self.title = OnscreenText(text = 'Select Level', pos = (0.0, 0.7), scale = 0.3, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) self.bg = OnscreenImage(image='./image/bg.png', pos = (0.0, -1.0, 0.0), parent=render2d) self.bg.setTransparency(TransparencyAttrib.MAlpha) self.curr_option = 0 self.levels = [] self.arrow_left = OnscreenImage(image='./image/arrow_left.png', scale=(64.0/base.win.getXSize(), 1 ,64.0/base.win.getYSize()), pos = (-.8, -3.0, 0.0), parent=aspect2d) self.arrow_left.setTransparency(TransparencyAttrib.MAlpha) self.arrow_right = OnscreenImage(image='./image/arrow_right.png', scale=(64.0/base.win.getXSize(), 1 ,64.0/base.win.getYSize()), pos = (.8, -3.0, 0.0), parent=aspect2d) self.arrow_right.setTransparency(TransparencyAttrib.MAlpha) level_list = parse.level_list() level_list.sort() self.item_list_node = aspect2d.attachNewNode("ItemList") self.initial_x = self.item_list_node.getX() for i, lvl in enumerate(level_list): header = parse.level_header(lvl) level_item = self.make_level_item(header) level_item.setX(self.ITEM_SPACING*i) level_item.setZ(-0.1) level_item.setScale(.8) level_item.reparentTo(self.item_list_node) self.levels.append(header['NAME']) self.cur_interval = None self.update() def create_cur_interval(self): return Sequence(LerpScaleInterval(self.item_list_node.getChild(self.curr_option), duration=0.4, startScale=.8, scale=.85), LerpScaleInterval(self.item_list_node.getChild(self.curr_option), duration=0.4, startScale=.85, scale=.8)) def option_changed(self, command): changed = False if command=='left' and self.curr_option > 0: self.curr_option = (self.curr_option - 1) changed = True elif command=='right' and self.curr_option < len(self.levels)-1: self.curr_option = (self.curr_option + 1) changed = True if changed: interval = Parallel(LerpPosInterval(self.item_list_node, duration=.2, startPos=VBase3(self.item_list_node.getX(),.0,.0), pos=VBase3(-self.ITEM_SPACING*self.curr_option,.0,.0)), SoundInterval(menuSfx)) interval.start() self.update() def update(self): if self.curr_option < 1: self.arrow_left.setAlphaScale(.0) else: self.arrow_left.setAlphaScale(1) if self.curr_option >= len(self.levels)-1: self.arrow_right.setAlphaScale(.0) else: self.arrow_right.setAlphaScale(1) if self.cur_interval: self.cur_interval.finish() del self.cur_interval self.cur_interval = self.create_cur_interval() self.cur_interval.loop() def option_pressed(self): return self.levels[self.curr_option] def clear(self): self.bg.destroy() self.arrow_left.destroy() self.arrow_right.destroy() self.title.destroy() self.item_list_node.removeNode() def make_level_item(self, level_header): level_name = level_header['NAME'] level_item = aspect2d.attachNewNode(level_name) level_img = OnscreenImage(image='./levels/%s/image.png' % level_name, scale=(512.0/base.win.getXSize(), 1 ,362.0/base.win.getYSize()), pos = (0.0, 0.0, 0.3), parent=level_item) level_img.setTransparency(TransparencyAttrib.MAlpha) level_img.reparentTo(level_item) if level_header.has_key("TITLE"): title_str = "%s" % level_header["TITLE"] else: title_str = "%s" % level_header["NAME"] artist_str = "" if level_header.has_key("ARTIST"): artist_str = "by %s" % level_header["ARTIST"] title_text = OnscreenText(text = title_str, pos = (0.0, 0.-0.3), scale = 0.2, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) title_text.reparentTo(level_item) next_y = -0.50 if artist_str: next_y -= 0.05 artist_text = OnscreenText(text = artist_str, pos = (0.0, 0.-0.4), scale = 0.15, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) artist_text.reparentTo(level_item) bpm_text = OnscreenText(text = "BPM %.2f" % level_header["BPM"], pos = (0.0, next_y), scale = 0.18, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) bpm_text.reparentTo(level_item) if self.game_opts.has_option('hiscores', level_name): his = self.game_opts.get('hiscores', level_name).split(',') maxrank = OnscreenText(text = "max rank %s" % his[0].upper(), pos = (0.0, next_y-0.15), scale = 0.18, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) hiscore = OnscreenText(text = "hiscore %s" % his[1], pos = (0.0, next_y-0.25), scale = 0.18, font=babelfish_font, align=TextNode.ACenter, fg=(1,1,1,1)) maxrank.reparentTo(level_item) hiscore.reparentTo(level_item) return level_item
class KlobWorld(ShowBase): def __init__(self): ShowBase.__init__(self) ## wp = WindowProperties(base.win.getProperties()) ## wp.setSize(1280,720) ## base.win.requestProperties(wp) base.setBackgroundColor(255,250,250) self.listAudio3d = [] self.allSounds() self.energyTime = 0 self.collHandQue = CollisionHandlerQueue() self.collHandQueEne = CollisionHandlerQueue() self.SPEED = .5 self.speedv = 4 base.cTrav = CollisionTraverser() self.bossLvl = False self.bossDead = False self.isMoving = False self.pause = True self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.currentLevel = "start" self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "cam-up":0, "cam-down":0, "fire-down":0, "p":0} ###Disable the default camera controls### base.disableMouse() self.pusher = CollisionHandlerPusher() base.cTrav.setRespectPrevTransform(True) #Uncomment to show collisions with environment #base.cTrav.showCollisions(render) self.setAcceptKeys() self.MainMenu() ## List to keep track of all actors added in each level ## to make it easier to cleanup level when destroyed self.crAct = [] self.extraElements = [] self.laserAmo = [] self.beamC = [] self.laserAmoCount = 0 self.enemyTimer = 0 self.gunAmmoCount = 0 self.loaded = [] self.bulletC = [] def allSounds(self): self.audio = Audio3DManager(self.sfxManagerList[0]) self.audio.attachListener(base.camera) self.heartBeat = base.loadMusic("sounds/heartbeat.wav") self.cheer = base.loadMusic("sounds/cheer.wav") self.intro = base.loadMusic("sounds/Mario.wav") self.bulletSound = base.loadMusic("sounds/gun_shot.wav") self.laserSound = base.loadMusic("sounds/gun_shot.wav") self.deadSound = base.loadMusic("sounds/pacman_death.wav") self.sound = self.audio.loadSfx("sounds/forest.wav") self.gust = base.loadMusic("sounds/gust.wav") self.siren = base.loadMusic("sounds/siren_2.wav") self.waterfallSound = self.audio.loadSfx("sounds/waterfall.wav") self.etSound = base.loadMusic("sounds/et-sound.wav") self.walking = base.loadMusic("sounds/running.wav") self.mainMenuMusic = base.loadMusic("sounds/intro.wav") self.rainforestMusic = self.loader.loadSfx("sounds/rainforest.wav") self.egyptMusic = self.loader.loadSfx("sounds/egypt.wav") self.asiaMusic = self.loader.loadSfx("sounds/asia.wav") self.newyorkMusic = self.loader.loadSfx("sounds/newyork.wav") self.mainMenuMusic.setLoop(True) self.rainforestMusic.setLoop(True) self.egyptMusic.setLoop(True) self.asiaMusic.setLoop(True) self.newyorkMusic.setLoop(True) self.gust.setLoop(True) self.sound.setLoop(True) self.siren.setLoop(True) self.walking.setVolume(5) self.heartBeat.setVolume(5) self.deadSound.setVolume(.5) self.laserSound.setVolume(.2) self.bulletSound.setVolume(.2) self.sound.setVolume(2) self.rainforestMusic.setVolume(.6) self.egyptMusic.setVolume(2) self.siren.setVolume(.3) def stopAllSounds(self): self.audio.detachSound(self.waterfallSound) self.audio.detachSound(self.sound) self.audio.detachSound(self.rainforestMusic) self.audio.detachSound(self.egyptMusic) self.audio.detachSound(self.newyorkMusic) self.intro.stop() self.bulletSound.stop() self.laserSound.stop() self.deadSound.stop() self.sound.stop() self.gust.stop() self.siren.stop() self.waterfallSound.stop() self.etSound.stop() self.walking.stop() self.mainMenuMusic.stop() self.rainforestMusic.stop() self.egyptMusic.stop() self.asiaMusic.stop() self.newyorkMusic.stop() def MainMenuLevels(self): if(self.currentLevel != "start"): self.destroyLevel() self.stopAllSounds() self.level1Btn = DirectButton( scale = (0.27,0.1,0.1), command = self.loadRainforestLevel, pos = Vec3(0, 0, 0.4), image = 'GUI/southamericabutton.png', relief = None) self.level2Btn = DirectButton( scale = (0.27,0.1,0.1), command = self.loadAfricaLevel, pos = Vec3(0, 0, 0.15), image = 'GUI/africabutton.png', relief = None) self.level3Btn = DirectButton( scale = (0.27,0.1,0.1), command = self.loadAsiaLevel, pos = Vec3(0, 0, -0.1), image = 'GUI/asiabutton.png', relief = None) self.level4Btn = DirectButton( scale = (0.27,0.1,0.1), command = self.loadNewYorkLevel, pos = Vec3(0, 0, -0.35), image = 'GUI/americabutton.png', relief = None) self.level2Btn.setTransparency(TransparencyAttrib.MAlpha) self.level3Btn.setTransparency(TransparencyAttrib.MAlpha) self.level4Btn.setTransparency(TransparencyAttrib.MAlpha) self.level1Btn.setTransparency(TransparencyAttrib.MAlpha) def destroyMainMenuLevels(self): self.level1Btn.destroy() self.level2Btn.destroy() self.level3Btn.destroy() self.level4Btn.destroy() self.mainMenuBtn = DirectButton( text="Main Menu", scale = (0.1,0.1,0.1), command = self.MainMenuLevels, pos = Vec3(0.8, 0, -0.9)) def MainMenu(self): if(self.currentLevel == "help"): self.destroyHelpMenu() elif(self.currentLevel != "start"): self.destroyLevel() self.mainMenuBtn.destroy() self.stopAllSounds() self.currentLevel="start" self.mainMenuImage = OnscreenImage("GUI/mainmenu.png",pos = Vec3(0, 0.0,-0.8), scale=(1.8, 0, 1.8)) self.mainMenuImage.reparentTo(aspect2d) self.mainMenuImage.setTransparency(1) self.mainMenuMusic.play() mapStart = loader.loadModel('GUI/button_maps.egg') self.startBtn = DirectButton(geom = (mapStart.find('**/start_but'), mapStart.find('**/start_but_click'), mapStart.find('**/start_but_roll'), mapStart.find('**/start_but_disabled')), relief = None, command = self.introScreen, scale = (0.7,0.7,0.7), pos = Vec3(0.6, 0, -0.35)) self.startBtn.setTransparency(TransparencyAttrib.MAlpha) mapHelp = loader.loadModel('GUI/helpbutton_maps.egg') self.helpBtn = DirectButton(geom = (mapHelp.find('**/help_but'), mapHelp.find('**/help_but_click'), mapHelp.find('**/help_but_roll'), mapHelp.find('**/help_but_disabled')), relief = None, command = self.HelpMenu, scale = (0.8,0.65,0.65), pos = Vec3(0.6, 0,-0.65)) self.helpBtn.setTransparency(TransparencyAttrib.MAlpha) def destroyMainMenu(self): self.startBtn.destroy() self.helpBtn.destroy() self.mainMenuImage.destroy() self.stopAllSounds() def HelpMenu(self): self.destroyMainMenu() self.currentLevel="help" self.helpMenuImage = OnscreenImage("GUI/helpmenu.png",pos = Vec3(0, 0.0,-0.8), scale=(1.8, 0, 1.8)) self.helpMenuImage.reparentTo(aspect2d) self.helpMenuImage.setTransparency(1) mapHelp = loader.loadModel('GUI/backbutton_maps.egg') self.backBtn = DirectButton(geom = (mapHelp.find('**/backBtn'), mapHelp.find('**/backBtn_click'), mapHelp.find('**/backBtn_roll'), mapHelp.find('**/backBtn_disabled')), relief = None, command = self.MainMenu, scale = (0.7,0.7,0.7), pos = Vec3(-1.4, 0, 0.8)) self.backBtn.setTransparency(TransparencyAttrib.MAlpha) ###...... #code missing. ### .... ##Records the state of the arrow keys### def setKey(self, key, value): if(self.pause is False): self.keyMap[key] = value if(self.keyMap["fire-down"] != 0 ): if( self.energy['value'] != 0 ): if(self.bossDead is False): self.beamC.append( self.loadLaser() ) self.laserAmo.append( self.laser() ) if(self.laserAmo): self.laserAmo[self.laserAmoCount].start() self.energy['value'] -= 3 self.laserAmoCount = self.laserAmoCount + 1 def loadEnviron(self, filename, scale): self.environ = self.loader.loadModel(filename) self.environ.setScale(scale) self.environ.reparentTo(self.render) self.environ.setPos(0, 0, 0) self.environ.setTag('wall','1') self.environ.setCollideMask(BitMask32(0x01)) alight = AmbientLight('alight') alight.setColor(VBase4(0.8, 0.8, 0.8, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) def loadAlien(self, point): ###Load alien actor### self.alien = Actor("models/alien/slugrocket-model", {"walk":"models/alien/slugrocket-anim"}) self.alien.reparentTo(render) self.alien.setScale(3) self.alien.setPos(point) self.alien.setPlayRate(1.2, "walk") self.alien.setBlend(frameBlend = True) self.dlight = DirectionalLight('my dlight') self.dlnp = render.attachNewNode(self.dlight) self.dlnp.reparentTo(base.camera) self.dlnp.lookAt(self.alien) self.dlight.setColor(VBase4(0.8, 0.8, 0.5, 1)) render.setLight(self.dlnp) base.camera.setPos(0,-10,2) base.camera.reparentTo(self.alien) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(2)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) csAlien = CollisionSphere(0,0,0.6,0.6) cnodeAlienPath = self.alien.attachNewNode(CollisionNode('csAlien')) cnodeAlienPath.node().addSolid(csAlien) self.pusher.addCollider(cnodeAlienPath, self.alien) base.cTrav.addCollider(cnodeAlienPath, self.pusher) ### Uncomment the following comment to show ### the Collision Sphere on the alien ## cnodeAlienPath.show() self.health = DirectWaitBar(scale = 0.5, range = 100, value = 100, barColor = (0,1,0,1), pos = Vec3(0.75, 0, 0.9)) self.energy = DirectWaitBar(scale = 0.5, range = 100, value = 100, barColor = (1,1,0,1), pos = Vec3(-0.75, 0, 0.9)) self.energy.reparentTo(aspect2d) self.health.reparentTo(aspect2d) self.hud = OnscreenImage("GUI/hud.png",scale = Vec3(1.43, 1.0, 1.03),pos = Vec3(0, 0.0,0.045)) self.hud.reparentTo(aspect2d) self.hud.setTransparency(1) self.extraElements.append(self.energy) self.extraElements.append(self.health) self.extraElements.append(self.hud) def alienDie(self, currLvl): self.alien.stop() self.pause=True temp = NodePath(PandaNode("temp")) base.camera.reparentTo(self.floater) base.camera.setZ(base.camera.getZ()+1) base.camera.setY(base.camera.getY()-25) self.deadSound.play() fall = LerpHprInterval(nodePath=self.alien, duration=1.5, hpr=(self.alien.getH(),self.alien.getP(), self.alien.getR()-80)) fall.start() taskMgr.remove("moveTask") taskMgr.remove("laterFc") transition = Transitions(loader) transition.setFadeColor(0, 0, 0) self.dieImage = OnscreenImage("GUI/died.png",scale = Vec3(0.7, 0, 0.2),pos = Vec3(0, 0,-0.5)) self.dieImage.reparentTo(aspect2d) self.dieImage.setTransparency(1) if(self.currentLevel == "rainforest"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(2.0),Func(self.destroyLevel),Func(self.loadRainforestLevel),Func(self.dieImage.destroy),Func(transition.fadeIn)).start() elif(self.currentLevel == "africa"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(2.0),Func(self.destroyLevel),Func(self.loadAfricaLevel),Func(self.dieImage.destroy),Func(transition.fadeIn)).start() elif(self.currentLevel == "asia"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(2.0),Func(self.destroyLevel),Func(self.loadAsiaLevel),Func(self.dieImage.destroy),Func(transition.fadeIn)).start() elif(self.currentLevel == "newyork"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(2.0),Func(self.destroyLevel),Func(self.loadNewYorkLevel),Func(self.dieImage.destroy),Func(transition.fadeIn)).start() def collide(self, collEntry): collEntry.getFromNodePath().getParent().removeNode() def setAcceptKeys(self): ###Accept the control keys for movement and rotation### self.accept("escape", sys.exit) self.accept("p", self.setKey, ["p",1]) self.accept("arrow_up", self.setKey, ["forward",1]) self.accept("arrow_up-up", self.setKey, ["forward",0]) self.accept("arrow_down", self.setKey, ["backward", 1]) self.accept("arrow_down-up", self.setKey, ["backward", 0]) self.accept("arrow_left", self.setKey, ["left",1]) self.accept("arrow_left-up", self.setKey, ["left",0]) self.accept("arrow_right", self.setKey, ["right",1]) self.accept("arrow_right-up", self.setKey, ["right",0]) self.accept("a", self.setKey, ["cam-left",1]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("z", self.setKey, ["cam-up",1]) self.accept("z-up", self.setKey, ["cam-up",0]) self.accept("x", self.setKey, ["cam-down", 1]) self.accept("x-up", self.setKey, ["cam-down", 0]) # Accept f to fire self.accept("f", self.setKey, ["fire-down",1]) self.accept("f-up", self.setKey, ["fire-down",0]) self.cTrav.traverse(render) #gun / laser code ommitted def getDistance(self, actor): self.vecAlien = Vec3(self.alien.getPos()) self.vecObj = Vec3(actor.getPos()) disVec = self.vecObj - self.vecAlien return disVec.length() def myFunction(self,task): self.walking.play() if(self.pause is False): for r in range(0, len(self.crAct)): self.crAct[r].setTarget(self.alien) self.bulletC.append( self.createBullet(self.crAct[r]) ) self.loaded.append( self.loadBullet( self.crAct[r]) ) self.loaded[self.gunAmmoCount].start() self.gunAmmoCount += 1 self.bulletSound.play() return task.again def bossLvlTask(self, dec, task): self.crAct[0].setAiPursue(self.alien) if(self.pause is False): self.deleteProjectiles() self.charcMoveKeys() startpos = self.alien.getPos() self.floater.setPos(self.alien.getPos()) self.floater.setZ(self.alien.getZ() + 2.0) base.camera.lookAt(self.floater) self.collHandQueEne.sortEntries() if(self.collHandQueEne.getNumEntries() > 0): entryb = self.collHandQueEne.getEntry(0) if( entryb.getIntoNodePath().getName() == "csAlien"): self.health['value'] -=5 if(self.bulletC): self.bulletC[self.gunAmmoCount-1].remove() self.bulletC.pop(self.gunAmmoCount-1) self.loaded.pop(self.gunAmmoCount-1) self.gunAmmoCount -= 1 if( self.health['value'] < 20 ): self.heartBeat.play() if(self.health['value'] == 0): self.alienDie(self.currentLevel) else: self.bulletC[self.gunAmmoCount-1].remove() self.bulletC.pop(self.gunAmmoCount-1) self.loaded.pop(self.gunAmmoCount-1) self.gunAmmoCount -= 1 self.collHandQue.sortEntries() if( self.collHandQue.getNumEntries() > 0 ): entry = self.collHandQue.getEntry(0) if( entry.getIntoNodePath().getName() == self.crAct[0].getCNP()): self.crAct[0].runAround(self.alien) self.crAct[0].setHitCount(1) self.crAct[0].decreaseHealth(dec) if( self.beamC): self.beamC[self.laserAmoCount-1].remove() self.beamC.pop(self.laserAmoCount-1) if(self.laserAmo): self.laserAmo.pop(self.laserAmoCount-1) self.laserAmoCount -= 1 if( self.crAct[0].getHealth()%4 == 0): self.crAct[0].jumpAway(self.alien) if( self.crAct[0].getHealth() == 0 ): ## print x.getDeaths() ## if( x.canRespawn() ): ## x.setDeaths(1) ## x.resetHitCount(0) ## x.setX(random.randint(0, 50)) ## x.setY(self.alien.getY()+15) ## else: self.crAct[0].cleanup() self.crAct[0].remove() self.crAct.pop(0) self.cutScene() if( self.crAct ): self.crAct[0].AIworld.update() if( self.keyMap["p"]!= 0): self.cutScene() return task.cont def move(self, task): ##ommmitted return task.cont def deleteProjectiles(self): ## if(self.pause is False): if(self.laserAmo): for i, x in enumerate(self.laserAmo): if( not x.isPlaying() ): self.beamC[i].remove() self.beamC.pop(i) self.laserAmo.pop(i) self.laserAmoCount = self.laserAmoCount -1 if(self.loaded): for i, x in enumerate(self.loaded): if(not x.isPlaying()): #self.crAct[i].setTarget(self.alien) self.bulletC[i].remove() self.bulletC.pop(i) self.loaded.pop(i) self.gunAmmoCount = self.gunAmmoCount -1 self.energyTime = self.energyTime + globalClock.getDt() if(self.energyTime > 2 ): if(self.energy['value'] != 100): self.energy['value'] +=5 self.energyTime = 0 def charcMoveKeys(self): 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()) if (self.keyMap["cam-up"]!=0): base.camera.setY(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-down"]!=0): base.camera.setY(base.camera, +20 * globalClock.getDt()) if (self.keyMap["forward"]!=0): self.alien.setY(self.alien, 10 * globalClock.getDt()) if (self.keyMap["backward"]!=0): self.alien.setY(self.alien, -10 * globalClock.getDt()) if (self.keyMap["left"]!=0): self.alien.setH(self.alien.getH() + 40 * globalClock.getDt()) if (self.keyMap["right"]!=0): self.alien.setH(self.alien.getH() - 40 * globalClock.getDt()) if (self.keyMap["forward"]!=0) or (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0) or (self.keyMap["backward"] != 0): if self.isMoving is False: self.alien.loop("walk") self.isMoving = True else: if self.isMoving: self.alien.stop() self.alien.pose("walk",5) self.isMoving = False def loadingScreen(self): self.intro.play() transition = Transitions(loader) transition.setFadeColor(0, 0, 0) text = TextNode('node name') dummy = NodePath(PandaNode("dummy")) black = OnscreenImage(image="GUI/black.png",pos=(0,0,0), scale=100) black.reparentTo(dummy) textNodePath = aspect2d.attachNewNode(text) textNodePath.reparentTo(aspect2d, 2) textNodePath.setScale(0.07) text.setTextColor(1, 1, 1, 1) if(self.currentLevel=="newyork"): Sequence(Func(transition.fadeOut),Func(black.reparentTo, aspect2d),Func(transition.fadeIn),Func(textNodePath.reparentTo,aspect2d, 10),Func(text.setText, "loading"),Wait(1.0),Func(text.setText, "loading."), Wait(1.0),Func(text.setText, "loading.."), Wait(1.0), Func(text.setText, "loading..."), Func(self.loadNextLevel),Wait(3.0),Func(transition.fadeIn),Func(textNodePath.remove), Func(black.destroy)).start() elif(self.currentLevel=="asia"): Sequence(Func(transition.fadeOut),Func(black.reparentTo, aspect2d),Func(transition.fadeIn),Func(textNodePath.reparentTo,aspect2d, 10),Func(text.setText, "loading"),Wait(1.0),Func(text.setText, "loading."), Wait(1.0),Func(text.setText, "loading.."), Wait(1.0), Func(text.setText, "loading..."), Func(self.loadNextLevel),Wait(3.0),Func(transition.fadeIn),Func(textNodePath.remove), Func(black.destroy)).start() else: Sequence(Func(transition.fadeOut),Func(black.reparentTo, aspect2d),Func(transition.fadeIn),Func(textNodePath.reparentTo,aspect2d, 10),Func(text.setText, "loading"),Wait(0.5),Func(text.setText, "loading."), Wait(0.5),Func(text.setText, "loading.."), Wait(0.5), Func(text.setText, "loading..."), Func(self.loadNextLevel),Wait(1.5),Func(transition.fadeIn),Func(textNodePath.remove), Func(black.destroy)).start() def cutScene(self): self.destroyLevel() self.stopAllSounds() self.cut = OnscreenImage("GUI/bossKilled.png",scale = Vec3(1.6, 0, 1.0),pos = Vec3(0, 0,0)) self.cut.reparentTo(aspect2d) self.cut.setTransparency(1) transition = Transitions(loader) transition.setFadeColor(0, 0, 0) self.cheer.play() if(self.currentLevel=="rainforest"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(1.0),Func(transition.fadeIn),Func(self.cut.setImage,"GUI/map_11.png"), Wait(1.5),Func(self.cut.setImage, "GUI/map_12.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_13.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_14.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_15.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_16.png"),Wait(3.5),Func(self.cut.destroy), Func(transition.fadeOut), Func(self.loadingScreen), Wait(1.0),Func(transition.fadeIn)).start() elif(self.currentLevel=="africa"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(1.0),Func(transition.fadeIn),Func(self.cut.setImage,"GUI/map_21.png"), Wait(1.5),Func(self.cut.setImage, "GUI/map_22.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_23.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_24.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_25.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_26.png"), Wait(3.5),Func(self.cut.destroy), Func(transition.fadeOut),Func(self.loadingScreen), Wait(1.0),Func(transition.fadeIn)).start() elif(self.currentLevel=="asia"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(1.0),Func(transition.fadeIn),Func(self.cut.setImage,"GUI/map_31.png"), Wait(1.5),Func(self.cut.setImage, "GUI/map_32.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_33.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_34.png"),Wait(0.5),Func(self.cut.setImage,"GUI/map_35.png"), Wait(0.5),Func(self.cut.setImage,"GUI/map_36.png"),Wait(3.5),Func(self.cut.destroy), Func(transition.fadeOut),Func(self.loadingScreen), Wait(1.0),Func(transition.fadeIn)).start() elif(self.currentLevel=="newyork"): Sequence(Wait(2.0),Func(transition.fadeOut),Wait(1.0),Func(transition.fadeIn),Func(self.cut.setImage,"GUI/win.png"), Wait(6.5),Func(self.cut.destroy), Func(transition.fadeOut),Func(self.loadingScreen), Wait(1.0),Func(transition.fadeIn)).start() def loadNextLevel(self): if(self.currentLevel=="start"): self.loadRainforestLevel() elif(self.currentLevel=="rainforest"): self.loadAfricaLevel() elif(self.currentLevel=="africa"): self.loadAsiaLevel() elif(self.currentLevel=="asia"): self.loadNewYorkLevel() else: self.MainMenu() def destroyLevel(self): self.mainMenuBtn.destroy() taskMgr.remove("moveTask") taskMgr.remove("bossTask") taskMgr.remove("myFunction") self.alien.cleanup() for enemy in self.crAct: enemy.cleanup() enemy.remove() self.alien.cleanup() self.alien.remove() for element in self.extraElements: element.removeNode() for beam in self.beamC: beam.removeNode() self.render.clearFog self.laserBeam2.removeNode() self.environ.removeNode() self.crAct[:] = [] self.extraElements[:] = [] self.laserAmo[:] =[] self.laserAmoCount = 0 def loadBossActor(self): self.bossLvl = True ###Load Ralph Boss actor### difficult = 10 taskMgr.remove("moveTask") taskMgr.remove("myFunction") self.health['value'] = 100 self.energy['value'] = 100 if(self.bossDead is False): self.bossImage = OnscreenImage("GUI/bossLoad.png",scale = Vec3(1.6, 0, 1.0),pos = Vec3(0, 0,0)) self.bossImage.reparentTo(aspect2d) self.bossImage.setTransparency(1) self.ralphBoss = EnemyActor(1,difficult,True) self.ralphBoss.enemy.setScale(2.0) self.crAct.append(self.ralphBoss) Sequence(Wait(3.0), Func(self.bossImage.destroy), Func(self.crAct[0].showHealthBar)).start() self.extraElements.append(self.crAct[0].bossHud) self.extraElements.append(self.crAct[0].health) self.crAct[0].setAiPursue(self.alien) self.pusher.addCollider(self.crAct[0].getFromObj(), self.crAct[0].enemy) base.cTrav.addCollider(self.crAct[0].getFromObj(), self.pusher) gunTex = loader.loadTexture('models/gun_tex.png') if(self.currentLevel == "rainforest"): dec = 5 self.ralphBoss.enemy.setPos(0,90,0) ralphTex = loader.loadTexture('models/ralph2rainforest.png') self.ralphBoss.enemy.setTexture(ralphTex, 1) self.ralphBoss.gunPos.setTexture(gunTex, 1) elif(self.currentLevel == "africa"): dec = 4 self.ralphBoss.enemy.setPos(-100,-90,0) ralphTex = loader.loadTexture('models/ralph2egypt.png') self.ralphBoss.enemy.setTexture(ralphTex, 1) self.ralphBoss.gunPos.setTexture(gunTex, 1) elif(self.currentLevel == "asia"): dec = 3 self.ralphBoss.enemy.setPos(0,0,0) ralphTex = loader.loadTexture('models/ralph2asia.png') self.ralphBoss.enemy.setTexture(ralphTex, 1) self.ralphBoss.gunPos.setTexture(gunTex, 1) elif(self.currentLevel == "newyork"): dec = 2 self.ralphBoss.enemy.setPos(120,10,0) taskMgr.add(self.bossLvlTask,"bossTask", extraArgs = [dec], appendTask=True) taskMgr.doMethodLater(1,self.myFunction,"myFunction") def loadRainforestLevel(self): self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "cam-up":0, "cam-down":0, "fire-down":0, "p":0} self.pause = False self.currentLevel = "rainforest" self.destroyIntro() difficulty = 2 self.bossLvl = False self.bossDead = False ###Load alien### startPos = Point3(0,0,0) self.loadAlien(startPos) self.rainforestMusic.play() ###Load the enemies### ralphTex = loader.loadTexture('models/ralph2rainforest.png') gunTex = loader.loadTexture('models/gun_tex.png') for i in range(0,2): enemy = EnemyActor(i, difficulty, False) enemy.enemy.setTexture(ralphTex, 1) enemy.gunPos.setTexture(gunTex, 1) enemy.setX(random.randint(-50,50)) enemy.setY(random.randint(-50,50)) enemy.setZ(0) self.crAct.append(enemy) self.crAct[i].setAiPursue(self.alien) self.pusher.addCollider(self.crAct[i].getFromObj(), self.crAct[i].enemy) base.cTrav.addCollider(self.crAct[i].getFromObj(), self.pusher) taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(3,self.myFunction,"myFunction") self.loadLaser2() self.loadLaser() ###Load the environment### self.loadEnviron("models/south_america/rainforest", 5) self.plants = self.loader.loadModel("models/south_america/rainforest-nocollision") self.plants.reparentTo(self.render) self.plants.setScale(4) self.plants.setTwoSided(True) self.extraElements.append(self.plants) self.myFog = Fog("FOG") self.myFog.setColor(0.5,0.6,0.5) self.myFog.setExpDensity(0.005) render.setFog(self.myFog) self.audio.attachSoundToObject(self.sound, self.environ) self.audio.setSoundVelocityAuto(self.sound) self.audio.setListenerVelocityAuto() self.sound.play() def loadAfricaLevel(self): self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "cam-up":0, "cam-down":0, "fire-down":0, "p":0} self.pause = False self.currentLevel="africa" difficulty = 3 self.bossLvl = False self.bossDead = False ###Load alien### startPos = Point3(-130,-130,0) self.loadAlien(startPos) self.alien.setH(-40) ###Load the enemies### ralphTex = loader.loadTexture('models/ralph2egypt.png') gunTex = loader.loadTexture('models/gun_tex.png') for i in range(0,3): enemy = EnemyActor(i, difficulty, False) enemy.enemy.setTexture(ralphTex, 1) enemy.gunPos.setTexture(gunTex, 1) enemy.setX(random.randint(-170,-50)) enemy.setY(random.randint(-170,-50)) enemy.setZ(0) self.crAct.append(enemy) self.crAct[i].setAiPursue(self.alien) self.pusher.addCollider(self.crAct[i].getFromObj(), self.crAct[i].enemy) base.cTrav.addCollider(self.crAct[i].getFromObj(), self.pusher) taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(3,self.myFunction,"myFunction") self.loadLaser2() self.loadLaser() ###Load environment### self.loadEnviron("models/africa/egypt", 7) self.egypt_nc = self.loader.loadModel("models/africa/egypt-nocollision") self.egypt_nc.reparentTo(self.render) self.egypt_nc.setPos(0,0,0) self.egypt_nc.setScale(7) self.extraElements.append(self.egypt_nc) self.sphinx = self.loader.loadModel("models/africa/sphinx") self.sphinx.setPos(0,80,0) self.sphinx.setH(180) self.sphinx.setScale(0.12) self.sphinx.reparentTo(self.render) self.extraElements.append(self.sphinx) cs = CollisionSphere(0,0,0,200) nodePath = self.sphinx.attachNewNode(CollisionNode('nodePath')) nodePath.node().addSolid(cs) self.gust.play() self.audio.attachSoundToObject(self.egyptMusic, self.environ) self.audio.setSoundVelocityAuto(self.egyptMusic) self.audio.setListenerVelocityAuto() self.egyptMusic.play() def loadAsiaLevel(self): self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "cam-up":0, "cam-down":0, "fire-down":0, "p":0} self.pause = False self.currentLevel = "asia" difficulty = 4 self.bossLvl = False self.bossDead = False ###Load alien### startPos = Point3(190,-140,0) self.loadAlien(startPos) ###Load the enemies### ralphTex = loader.loadTexture('models/ralph2asia.png') gunTex = loader.loadTexture('models/gun_tex.png') for i in range(0,4): enemy = EnemyActor(i, difficulty, False) enemy.enemy.setTexture(ralphTex, 1) enemy.gunPos.setTexture(gunTex, 1) enemy.setX(random.randint(0,100)) enemy.setY(random.randint(-150,-50)) enemy.setZ(0) self.crAct.append(enemy) self.crAct[i].setAiPursue(self.alien) self.pusher.addCollider(self.crAct[i].getFromObj(), self.crAct[i].enemy) base.cTrav.addCollider(self.crAct[i].getFromObj(), self.pusher) taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(3,self.myFunction,"myFunction") self.loadLaser2() self.loadLaser() ###Load the environment### self.loadEnviron("models/asia/asia2", 5) self.asia_nc = self.loader.loadModel("models/asia/asia-nocollision") self.asia_nc.reparentTo(self.render) self.asia_nc.setPos(0,0,0) self.asia_nc.setScale(5) self.extraElements.append(self.asia_nc) self.myFog = Fog("FOG") self.myFog.setColor(0.8,0.8,0.8) self.myFog.setExpDensity(0.002) render.setFog(self.myFog) self.bonzai = self.loader.loadModel("models/asia/bonzai") self.bonzai.reparentTo(self.render) self.bonzai.setPos(170,20,0) self.bonzai.setScale(0.015) self.bonzai.setH(90) self.extraElements.append(self.bonzai) cs = CollisionSphere(0,0,200,200) nodePath = self.bonzai.attachNewNode(CollisionNode('nodePath')) nodePath.node().addSolid(cs) self.pusher.addCollider(nodePath, self.bonzai) self.waterfall = self.loader.loadModel("models/asia/waterFall") self.waterfall.reparentTo(self.render) self.waterfall.setPos(200,80,-.5) self.waterfall.setScale(0.25) self.waterfall.setH(180) self.extraElements.append(self.waterfall) cs = CollisionSphere(0,15,-5,130) nodePath = self.waterfall.attachNewNode(CollisionNode('nodePath')) nodePath.node().addSolid(cs) self.pusher.addCollider(nodePath, self.waterfall) self.waterfallSound.setLoop(True) self.audio.attachSoundToObject(self.waterfallSound,self.waterfall) self.audio.setSoundVelocityAuto(self.waterfallSound) self.audio.setListenerVelocityAuto() self.audio.setDistanceFactor(1.5) self.waterfallSound.play() self.tree1 = self.loader.loadModel("models/asia/bamboo") self.tree1.reparentTo(self.render) self.tree1.setPos(-50,-50,0) self.tree1.setScale(0.6,0.6,0.6) self.tree1.setBillboardAxis() self.extraElements.append(self.tree1) #Child bamboos scattered around placeholder = render.attachNewNode("Bamboo-Placeholder") placeholder.setPos(180,-40,0) placeholder.setScale(0.8) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) placeholder = render.attachNewNode("Babmboo-Placeholder") placeholder.setPos(-20,-120,0) placeholder.setScale(1.0) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) placeholder = render.attachNewNode("Bamboo-Placeholder") placeholder.setPos(-50,180,0) placeholder.setScale(1.0) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) placeholder = render.attachNewNode("Bamboo-Placeholder") placeholder.setPos(-60,165,0) placeholder.setScale(0.6) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) placeholder = render.attachNewNode("Bamboo-Placeholder") placeholder.setPos(-110,70,0) placeholder.setScale(1.0) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) placeholder = render.attachNewNode("Bamboo-Placeholder") placeholder.setPos(-100,-50,0) placeholder.setScale(1.6) self.tree1.instanceTo(placeholder) self.extraElements.append(placeholder) self.asiaMusic.play() def loadNewYorkLevel(self): self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "cam-up":0, "cam-down":0, "fire-down":0,"p":0} self.pause = False self.currentLevel = "newyork" #self.destroyMainMenuLevels() difficulty = 5 ###Load alien### startPos = Point3(20,10,0) self.loadAlien(startPos) self.alien.setH(90) base.camera.setH(90) self.bossLvl = False self.bossDead = False ###Load the enemies### for i in range(0,5): enemy = EnemyActor(i, difficulty, False) enemy.setX(random.randint(-100,100)) enemy.setY(random.randint(8,12)) enemy.setZ(0) self.crAct.append(enemy) self.crAct[i].setAiPursue(self.alien) self.pusher.addCollider(self.crAct[i].getFromObj(), self.crAct[i].enemy) base.cTrav.addCollider(self.crAct[i].getFromObj(), self.pusher) taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(2,self.myFunction, "myFunction") self.loadLaser2() self.loadLaser() ###Load the environment### self.loadEnviron("models/america/newyork", 4) self.ny_nc = self.loader.loadModel("models/america/newyork-nocollision") self.ny_nc.reparentTo(self.render) self.ny_nc.setScale(4) self.extraElements.append(self.ny_nc) self.statue = self.loader.loadModel("models/america/statue") self.statue.reparentTo(self.render) self.statue.setPos(270,-100,13) self.statue.setScale(1) self.statue.setBillboardAxis() self.statue.setTwoSided(True) self.extraElements.append(self.statue) self.myFog = Fog("FOG") self.myFog.setColor(0.3,0.3,0.3) self.myFog.setExpDensity(0.005) render.setFog(self.myFog) self.siren.play() self.newyorkMusic.play()
class SideBySideImage(Element): """ Class to display a two images side by side Will get some configuration from the corresponding JSON node. """ def __init__(self, **kwargs): """ world is a reference to the main class text: is the name of the node in the XML config """ # build basic element # self.sceneNP and self.hudNP are defined here super(SideBySideImage, self).__init__(**kwargs) urlA = getattr(self, 's_urlA', None) urlB = getattr(self, 's_urlB', None) if (urlA is None or urlB is None): print "Missing references of images to compare" sys.quit() sx, sz = getattr(self, 'f_scale', [1.0, 1.0]) # load textures try: self.imageNodeA = OnscreenImage(image=urlA, scale=Vec3(sx, 1.0, sz)) self.imageNodeA.setTransparency(TransparencyAttrib.MAlpha) self.imageNodeA.setX(-0.5) self.imageNodeB = OnscreenImage(image=urlB, scale=Vec3(sx, 1.0, sz)) self.imageNodeB.setTransparency(TransparencyAttrib.MAlpha) self.imageNodeB.setX(0.5) #planeNP = loader.loadModel("models/plane") #planeNP.setName(name) #planeNP.setTexture(t) #planeNP.setTransparency(1) #planeNP.setScale(1.0, 1.0, 1.0) #planeNP.reparentTo(self.hudNP) except: print "Fatal error, could not load texture file or model in models/plane" print "Check the file path" self.hideElement() def showElement(self): self.imageNodeA.show() self.imageNodeB.show() def hideElement(self): self.imageNodeA.hide() self.imageNodeB.hide() def enterState(self): print "entering FullScreenImage" # super class enterState Element.enterState(self) # self.registerKeys() def exitState(self): print "leaving state FullScreenImage" Element.exitState(self) self.unregisterKeys() self.imageNodeA.destroy() self.imageNodeB.destroy()
class World(DirectObject): def __init__(self): base.disableMouse() self.accept("escape", sys.exit) self.accept("enter", self.loadGame) self.accept("C1_START_DOWN", self.loadGame) self.music = base.loader.loadMusic("Sounds/GameMusic2.wav") self.music.setLoop(True) self.music.setVolume(.33 ) self.music.play() self.tractorbeamsound = base.loader.loadSfx("Sounds/tractorbeam.wav") Lvl = 1 self.Lvl = Lvl gamepads = pyPad360() ##print gamepads.setupGamepads() if gamepads.setupGamepads() > 0: gamepads.setupGamepads() taskMgr.add(gamepads.gamepadPollingTask, "gamepadPollingTask") self.gameControls360() self.title = loader.loadModel("Art/skybox.egg") self.title.reparentTo(render) self.title.setScale(1) self.title.setPos(0, 0, -55) self.titleScreen = OnscreenImage(image = 'Art/images/title_screen.png') #self.text1 = OnscreenText(text="Press Enter to Start",style=1, fg=(0.8,0,0.1,1),pos=(0, 0.77), scale = .2,mayChange = 1,align=TextNode.ACenter) self.inGame = False #print self.text1 def loadGame(self): if not self.inGame: self.inGame = True self.title.removeNode() del self.title self.titleScreen.destroy() #self.text1.destroy() #del self.text1 self.startGame() def startGame(self): #if self.inGame == True: self.saucer = Saucer() camera.setPosHpr(0, -40, 73, 0, 0, 0) camera.lookAt(self.saucer.ship) camera.setP(camera.getP() -8) self.loadModels() self.loadHUD() self.setupLights() self.keyMap = {"left":0, "right":0,"w":0,"a":0,"s":0,"d":0,"k":0,"l":0} self.prevtime = 0 self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("w", self.setKey, ["w", 1]) self.accept("w-up", self.setKey, ["w", 0]) self.accept("s", self.setKey, ["s", 1]) self.accept("s-up", self.setKey, ["s", 0]) self.accept("a", self.setKey, ["a", 1]) self.accept("a-up", self.setKey, ["a", 0]) self.accept("d", self.setKey, ["d", 1]) self.accept("d-up", self.setKey, ["d", 0]) self.accept("k", self.setKey, ["k", 1]) self.accept("k-up", self.setKey, ["k", 0]) self.accept("l", self.setKey, ["l", 1]) self.accept("l-up", self.setKey, ["l", 0]) self.accept("enter", self.blank) self.accept("C1_START_DOWN", self.blank) self.mydir = os.path.abspath(sys.path[0]) self.mydir = Filename.fromOsSpecific(self.mydir).getFullpath() self.mydir = Filename(self.mydir) self.mydir = self.mydir.toOsSpecific() self.setupWASD() taskMgr.add(self.rotateWorld, "rotateWorldTask") taskMgr.add(self.missileSeek, "missileSeekTask") self.animalsleft = 0 self.missiles = [] taskMgr.add(self.textTask, "textTask") self.saucer.ship.setColorScale(1,1,1,1) self.missileSound = base.loader.loadSfx("Sounds/tankshot.wav") self.missileHitSound = base.loader.loadSfx("Sounds/missile.wav") self.xspeed = 0 self.yspeed = 0 #For recycler self.xbounds = 130 self.currentpickupable = 0 self.loadLevel() base.cTrav = CollisionTraverser() #set the collision handler to send event messages on collision self.cHandler = CollisionHandlerEvent() # %in is substituted with the name of the into object self.cHandler.setInPattern("%fn-%in") self.setupCollisions() self.accept("beam-pickupable", self.beamCollide) self.accept("ship-tankdetect", self.tankShoot) self.accept("missile-ship", self.missileHit) #print "Level " + str(self.Lvl) self.accept("space", self.loseGame)#Goes to Level Failed screen. For testing purposes self.accept("C1_X_DOWN", self.loseGame) self.accept("backspace", self.winGame) #Goes to Level Complete screen. For testing purposes self.accept("C1_Y_DOWN", self.winGame) def loseGame(self): self.levelComplete = False #Clear stuff taskMgr.remove('rotateWorldTask') taskMgr.remove('textTask') taskMgr.remove('abductTask') taskMgr.remove('moveTask') taskMgr.remove('missileSeekTask') taskMgr.remove('ParticleTaskTask') self.env.removeNode() del self.env self.saucer.ship.removeNode() del self.saucer.ship self.saucer.beam.removeNode() del self.saucer.beam #self.timeroutline.removeNode() #del self.timeroutline self.TimeText.destroy() del self.TimeText for i in range(0,len(self.pickupables)): self.pickupables[i].pickup.removeNode() del self.pickupables[i].pickup self.texte = OnscreenText(text="You Lose!",style=1, fg=(0.8,0,0.1,1),pos=(0, 0), scale = .2,mayChange = 1,align=TextNode.ACenter) self.textd = OnscreenText(text="Press Enter or Start to restart!",style=1, fg=(0.8,0,0.1,1),pos=(0, -.88), scale = .06,mayChange = 1,align=TextNode.ACenter) self.accept("enter", self.nextLevel) self.accept("C1_START_DOWN", self.nextLevel) def winGame(self): self.levelComplete = True #Clear Stuff taskMgr.remove('rotateWorldTask') taskMgr.remove('textTask') taskMgr.remove('abductTask') taskMgr.remove('moveTask') taskMgr.remove('missileSeekTask') self.env.removeNode() del self.env self.saucer.ship.removeNode() del self.saucer.ship self.saucer.beam.removeNode() del self.saucer.beam self.AnimalsLeft.destroy() del self.AnimalsLeft self.AnimalsLeftText.destroy() del self.AnimalsLeftText for i in range(0,len(self.pickupables)): self.pickupables[i].pickup.removeNode() del self.pickupables[i].pickup #if self.medal == "Gold": # self.medalImage = OnscreenImage(image = 'Art/gold.png', pos = (1.1, 0, .46), scale = (.2,1,.2)) #elif self.medal == "Silver": # self.medalImage = OnscreenImage(image = 'Art/silver.png', pos = (1.1, 0, .46), scale = (.125,1,.225)) #elif self.medal == "Bronze": # self.medalImage = OnscreenImage(image = 'Art/bronze.png', pos = (1.1, 0, .46), scale = (.15,.1,.2)) if self.Lvl < 4: self.texte = OnscreenText(text="Level Complete!",style=1, fg=(0.8,0,0.1,1),pos=(0, 0), scale = .2,mayChange = 1,align=TextNode.ACenter) self.textd = OnscreenText(text="Press Enter or Start to go to next level!",style=1, fg=(0.8,0,0.1,1),pos=(0, -.88), scale = .06,mayChange = 1,align=TextNode.ACenter) self.Lvl += 1 self.accept("enter", self.nextLevel) self.accept("C1_START_DOWN", self.nextLevel) else: self.creditsScreen = OnscreenImage(image = 'Art/images/credits_screen.png') #self.texte = OnscreenText(text="You Finished the Game!",style=1, fg=(0.8,0,0.1,1),pos=(0, 0), scale = .2,mayChange = 1,align=TextNode.ACenter) def nextLevel(self): self.skybox.removeNode() del self.skybox self.texte.destroy() del self.texte self.textd.destroy() del self.textd if self.levelComplete == True: #self.timeroutline.removeNode() #del self.timeroutline self.TimeText.destroy() del self.TimeText #self.medalImage.removeNode() #del self.medalImage if self.levelComplete == False: self.AnimalsLeft.destroy() del self.AnimalsLeft self.AnimalsLeftText.destroy() del self.AnimalsLeftText for p in self.pickupables: p.particle.disable() self.saucer.abductp.disable() self.startGame() def gameControls360(self): #Accept each message and do something based on the button self.accept("C1_A_DOWN", self.setKey, ["k", 1]) self.accept("C1_A_UP", self.setKey,["k",0]) self.accept("C1_B_DOWN", self.setKey, ["l", 1]) self.accept("C1_B_UP", self.setKey,["l",0]) self.accept("C1_DPAD_UP", self.setKey, ["w", 1]) self.accept("C1_DPAD_DOWN", self.setKey,["s",1]) self.accept("C1_DPAD_LEFT", self.setKey, ["a", 1]) self.accept("C1_DPAD_RIGHT", self.setKey, ["d", 1]) self.accept("C1_DPAD_NONE", self.stop,["w",0,"s",0,"a",0,"d",0]) self.accept("C1_DPAD_UPLEFT", self.diagkeys, ["w",1,"a",1]) self.accept("C1_DPAD_UPRIGHT", self.diagkeys, ["w",1,"d",1]) self.accept("C1_DPAD_DOWNLEFT", self.diagkeys, ["s",1,"a",1]) self.accept("C1_DPAD_DOWNRIGHT", self.diagkeys, ["s",1,"d",1]) self.accept("C1_LSTICK_HARDUP", self.setKey, ["w", 1]) self.accept("C1_LSTICK_SLIGHTUP", self.setKey, ["w", 0]) self.accept("C1_LSTICK_HARDDOWN", self.setKey,["s",1]) self.accept("C1_LSTICK_SLIGHTDOWN", self.setKey,["s",0]) self.accept("C1_LSTICK_HARDLEFT", self.setKey, ["a", 1]) self.accept("C1_LSTICK_SLIGHTLEFT", self.setKey, ["a", 0]) self.accept("C1_LSTICK_HARDRIGHT", self.setKey, ["d", 1]) self.accept("C1_LSTICK_SLIGHTRIGHT", self.setKey, ["d", 0]) def blank(self): x=1 def stop(self, key1, value1, key2, value2, key3, value3, key4, value4): self.keyMap[key1] = value1 self.keyMap[key2] = value2 self.keyMap[key3] = value3 self.keyMap[key4] = value4 def diagkeys(self, key1, value1, key2, value2): self.keyMap[key1] = value1 self.keyMap[key2] = value2 def setupWASD(self): self.accept("w", self.setKey, ["w", 1]) self.accept("w-up", self.setKey, ["w", 0]) self.accept("s", self.setKey, ["s", 1]) self.accept("s-up", self.setKey, ["s", 0]) self.accept("a", self.setKey, ["a", 1]) self.accept("a-up", self.setKey, ["a", 0]) self.accept("d", self.setKey, ["d", 1]) self.accept("d-up", self.setKey, ["d", 0]) def loadLevel(self): #self.map = open("C:\Users\Vanded3\Documents\ufo-game2\Code\Levels\level1.txt") #self.map = "CC0CCCCCCCC000CCCCCCCCCC00CCCCCCCCCCCCC" self.map = open (self.mydir + "\Levels\level" + str(self.Lvl) + ".txt") self.map = [line.rstrip() for line in self.map] self.tex = loader.loadTexture("\Art\images\world" + str(self.Lvl) + "_texture.png") self.env.setTexture(self.tex) #self.terrainlist = [] tsize = 4 self.pickupables = [] #self.animals = [] #self.inanimates = [] #self.hostiles = [] worldhalfwidth = 240 worldradius = 43 for i, row in enumerate(self.map): for j, column in enumerate(row): if column == "-": pass if column == "C": temp = Pickupable("animal","cow") temp.pickup.reparentTo(self.env) #print("in cow") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z = worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize #temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print (len(self.pickupables)) if column == "S": temp = Pickupable("animal", "sheep") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in S") if column == "P": temp = Pickupable("inanimate", "silo") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in P") if column == "0": temp = Pickupable("animal", "pig") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in B") if column == "M": temp = Pickupable("hostile", "tank") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in M") if column == "N": temp = Pickupable("inanimate", "tractor") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in N") if column == "B": temp = Pickupable("inanimate", "barn") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in N") if column == "W": temp = Pickupable("inanimate", "cage") temp.pickup.setScale(1) angle = i * .1 y = worldradius * math.cos(angle) z= worldradius * math.sin(angle) temp.pickup.setPos((j * tsize)-worldhalfwidth, y, z) rotangle = math.degrees(math.atan2((z - 0), (y - 0))) temp.pickup.setHpr(0,rotangle - 90,0) temp.pickup.setH(temp.pickup, random.randint(0,360)) #positioning : i*tsize temp.pickup.reparentTo(self.env) self.pickupables.append(temp) #print("in N") #print len(self.pickupables) #self.env.setX(self.env.getX() - 60) #self.env.setP(self.env.getP() + 60) def setKey(self, key, value): self.keyMap[key] = value def rotateWorld(self,task): #Handles saucer movement, world rotation etc elapsed = task.time - self.prevtime self.prevtime = task.time # Create a handle for pointer device #0 #m = base.win.getPointer( 0 ) # Get the absolute [x,y] screen coordinates of the cursor #x = m.getX( ) #y = m.getY( ) centerx = 400 centery = 300 xmov = 0 ymov = 0 accel = 0 dir = -1 if self.keyMap["l"]: self.saucer.drop(self.env) #for object in self.saucer.abductlist: #object.abduct = False #object.pickup.wrtReparentTo(self.env) #object.pickup.setPos(self.saucer.dummy2.getX(),self.saucer.dummy2.getY(),self.saucer.dummy2.getZ()) #camera.lookAt(object.pickup) if self.keyMap["k"]: if self.tractorbeamsound.status() != AudioSound.PLAYING: self.tractorbeamsound.play() self.saucer.beamon = True if self.xspeed > 30: self.xspeed = 30 elif self.xspeed < -30: self.xspeed = -30 if self.yspeed > 30: self.yspeed = 30 elif self.yspeed < -30: self.yspeed = -30 if self.keyMap["w"]: dir = 270 if self.keyMap["s"]: dir = 90 if self.keyMap["a"]: dir = 180 if self.keyMap["d"]: dir = 0 if self.keyMap["w"] and self.keyMap["d"]: dir = 315 if self.keyMap["w"] and self.keyMap["a"]: dir = 225 if self.keyMap["s"] and self.keyMap["a"]: dir = 135 if self.keyMap["s"] and self.keyMap["d"]: dir = 45 if dir != -1: xmov = 26 * math.cos(math.radians(dir)) ymov = 26 * math.sin(math.radians(dir)) if xmov == 0 and ymov == 0: accel = .1 else: accel = .035 else: self.saucer.beamon = False if self.tractorbeamsound.status() == AudioSound.PLAYING: self.tractorbeamsound.stop() if self.keyMap["w"]: dir = 270 if self.keyMap["s"]: dir = 90 if self.keyMap["a"]: dir = 180 if self.keyMap["d"]: dir = 0 if self.keyMap["w"] and self.keyMap["d"]: dir = 315 if self.keyMap["w"] and self.keyMap["a"]: dir = 225 if self.keyMap["s"] and self.keyMap["a"]: dir = 135 if self.keyMap["s"] and self.keyMap["d"]: dir = 45 if dir != -1: xmov = 40 * math.cos(math.radians(dir)) ymov = 40 * math.sin(math.radians(dir)) accel = .07 #if base.win.movePointer( 0, centerx, centery ): # xmov += ( x - centerx ) * 1 # ymov += ( y - centery ) * 1 if self.env.getX() > self.xbounds: if xmov < 0: xmov = 0 elif self.env.getX() < -self.xbounds: if xmov > 0: xmov = 0 self.xspeed = self.xspeed + ( (xmov - self.xspeed) * accel) self.yspeed = self.yspeed + ( (ymov - self.yspeed) * accel) self.env.setX(self.env.getX() + elapsed * -self.xspeed) self.env.setP(self.env.getP() + elapsed * -self.yspeed) self.skybox.setX(self.skybox.getX() + elapsed * -.3 * self.xspeed) self.skybox.setP(self.skybox.getP() + elapsed * -.1 * self.yspeed) self.saucer.ship.setR(self.xspeed * .2) self.saucer.ship.setP(self.yspeed * .2) ##print self.env.getX() return Task.cont def loadModels(self): self.env = loader.loadModel("Art/world1.egg") self.env.reparentTo(render) self.env.setScale(1) self.env.setPos(0, 0, -55) self.skybox = loader.loadModel("Art/skytube.egg") self.skybox.reparentTo(render) self.skybox.setScale(2) self.skybox.setPos(0, 0, 0) self.skybox.setHpr(0,-60,0) #Shadow Code: proj = render.attachNewNode(LensNode('proj')) lens = PerspectiveLens() proj.node().setLens(lens) #The following is for debugging: #proj.node().showFrustum() #proj.find('frustum').setColor(1, 0, 0, 1) proj.reparentTo(render) proj.setPos(self.saucer.ship.getPos()) proj.setZ(-2) proj.setHpr(0,-90,0) tex = loader.loadTexture('Art\UFO_Shadow.png') tex.setWrapU(Texture.WMBorderColor) tex.setWrapV(Texture.WMBorderColor) tex.setBorderColor(VBase4(1, 1, 1, 0)) ts = TextureStage('ts') ts.setSort(1) ts.setMode(TextureStage.MDecal) self.env.projectTexture(ts, tex, proj) def loadHUD(self): #Draw image as outline for timer #self.timeroutline = OnscreenImage(image = 'Art/timer.png', pos = (1.1, 0, .86), scale = (.15,.1,.1)) #self.timeroutline = OnscreenImage(image = 'Art/timer.png', pos = (-.98, 0, .88), scale = (.38,.50,.12)) #Draw num of animals left num = str(200000) self.AnimalsLeft = OnscreenText(text="Animals Collected:",style=1, fg=(1,1,1,1),pos=(-1,.9), scale = .07,mayChange = 1) self.AnimalsLeftText = OnscreenText(text=num,style=1, fg=(1,1,1,1),pos=(-1,0.8), scale = .09,mayChange = 1,align = TextNode.ALeft) #Draw time t = "0:00" self.TimeText = OnscreenText(text=t,style=1, fg=(1,1,1,1),pos=(1,0.85), scale = .09, mayChange = 1, align = TextNode.ALeft) def dCharstr(self,number): theString = str(number) if len(theString) != 2: theString = '0' + theString return theString def textTask(self,task): secondsTime = int(task.time) minutesTime = int(secondsTime/60) self.seconds = secondsTime%60 self.minutes = minutesTime self.mytimer = str(self.minutes) + ":" + self.dCharstr(int(self.seconds)) #self.mytimer = str(self.seconds) self.TimeText.setText(self.mytimer) medal = "No Medal" self.medal = medal if task.time <= 35: self.medal = "Gold" elif task.time > 35 and task.time <=50: self.medal = "Silver" elif task.time > 50: self.medal = "Bronze" self.AnimalsLeftText.setText(str(self.saucer.collected)) if self.saucer.collected > 30: self.winGame() return Task.cont def setupLights(self): """loads initial lighting""" self.dirLight = DirectionalLight("dirLight") self.dirLight.setColor((.6, .6, .6, 1)) #create a NodePath, and attach it directly into the scene self.dirLightNP = render.attachNewNode(self.dirLight) self.dirLightNP.setHpr(0, -25, 0) #the NP that calls setLight is what gets lit render.setLight(self.dirLightNP) # clearLight() turns it off self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((.25, .25, .25, 1)) self.ambientLightNP = render.attachNewNode(self.ambientLight) render.setLight(self.ambientLightNP) def setupCollisions(self): cSphere = CollisionSphere((0,0,0), 2) cNode = CollisionNode("ship") cNode.addSolid(cSphere) cNodePath = self.saucer.ship.attachNewNode(cNode) base.cTrav.addCollider(cNodePath, self.cHandler) #saucer collider cSphere = CollisionSphere((0,0,0), 2) cNode = CollisionNode("beam") cNode.addSolid(cSphere) #set to only be a "from" object cNode.setIntoCollideMask(BitMask32.allOff()) cNodePath = self.saucer.dummy.attachNewNode(cNode) cNodePath.setZ(-36) #cNodePath.show() base.cTrav.addCollider(cNodePath, self.cHandler) #target colliders for p in self.pickupables: cSphere = CollisionSphere((0,0,0), 1) cNode = CollisionNode("pickupable") cNode.addSolid(cSphere) cNodePath = p.pickup.attachNewNode(cNode) if p.type2 == "tank": cSphere = CollisionSphere((0,0,0), 45) cNode = CollisionNode("tankdetect") cNode.addSolid(cSphere) cNodePath = p.pickup.attachNewNode(cNode) #cNodePath.show() def beamCollide(self, cEntry): if self.saucer.beamon: obj = cEntry.getIntoNodePath().getParent() for x in self.pickupables: if (x.pickup == obj): self.saucer.pickUp(x) return def tankShoot(self, cEntry): tank = cEntry.getIntoNodePath() newMissile = Missile() newMissile.model.reparentTo(tank.getParent()) cSphere = CollisionSphere((0,0,0), 2) cNode = CollisionNode("missile") cNode.addSolid(cSphere) cNodePath = newMissile.model.attachNewNode(cNode) base.cTrav.addCollider(cNodePath, self.cHandler) self.missiles.append(newMissile) self.missileSound.play() def missileSeek(self, task): for i in self.missiles: i.seek(self.saucer.ship) return Task.cont def missileHit(self, cEntry): aMissile = cEntry.getFromNodePath().getParent() for i in self.missiles: if i.model == aMissile: self.missileHitSound.play() i.model.removeNode() self.missiles.remove(i) self.saucer.health -= 20 if self.saucer.health <=0: self.loseGame() elif self.saucer.health <= 50: self.saucer.ship.setColorScale(1,.5,.5,1) return
class Photos(object): def __init__(self, config, base, logging, deg_per_pixel=None): # photo location self.base = base self.config = config self.config.setdefault('RANDOM_PHOTOS', True) self.logging = logging self.x_node = None self.photo_path = None self.photo_names = [] self.photo_set = [] self.photo_timer_on = False # starts out assuming fixated self.imageObject = None self.photo_gen = None # tells calibration routine when it should care about fixation for photos self.photo_window = [] # where we will store the fixation window for photos self.photo_fix_time = 0 # used to keep track of timing self.start_plot_eye_task = None self.cross_sequence = None self.photo_sequence = None self.cross_hair = False num_photos_in_set = self.config['NUM_PHOTOS_IN_SET'] # was originally going to determine automatically how many sets we could show, # but now we always determine how many to show based on fitting in one calibration # routine # total_cal_points = self.config['POINT_REPEAT'] * self.config['X_POINTS'] * self.config['Y_POINTS'] # num_poss_photos = total_cal_points // self.config['CAL_PTS_PER_PHOTO'] # num_sets = num_poss_photos // num_photos_in_set # show each set twice, so just need half that many twice = self.config.setdefault('SHOW_PHOTOS_TWICE', False) # only show one set per calibration routine num_sets = 1 # print num_sets last_index = self.config.get('LAST_PHOTO_INDEX', 0) self.index_list = create_index_list(num_photos_in_set, num_sets, last_index, twice) # print('index list', self.index_list) self.end_index = 0 # photo_size = [1280, 800] # ratio of photo is approximately the same as the screen (3:4), which means # about same number of pixels in x and y to get same ratio. Not really intuitive. photo_size = [600, 600] # photo_size = [1000, 800] self.tolerance = tuple([x/2 for x in photo_size]) self.draw_cross(deg_per_pixel) self.cross_hair_int = self.config.get('CROSS_HAIR_FIX', (0, 0)) # print('photo tolerance', self.tolerance) self.loop_count = 0 self.task_timer = 0 self.verify_timer = None def load_all_photos(self): # print 'load all photos' for file_name in os.listdir(self.config['PHOTO_PATH']): # print file_name if file_name.endswith('.bmp'): self.photo_names.append(os.path.join(self.config['PHOTO_PATH'], file_name)) if self.index_list[-1] > len(self.photo_names): raise Exception("Not enough Photos in this directory") self.load_photo_set() # print test def load_photo_set(self): # print 'load photo set' try: start_ind = self.index_list.pop(0) end_ind = self.index_list.pop(0) self.end_index = end_ind except IndexError: # print 'end of index!' return False # check to see if photos should be presented in # different order second time, # print 'photos', self.photo_names[start_ind:end_ind] self.photo_set = self.photo_names[start_ind:end_ind] if self.config['RANDOM_PHOTOS']: random.shuffle(self.photo_set) # print self.photo_set self.photo_gen = self.get_photo() return True def get_photo(self): for photo in self.photo_set: yield photo def get_next_photo(self): # print 'show photo and tolerance' self.photo_path = None try: self.photo_path = self.photo_gen.next() except StopIteration: # print('stop iterating!') check_set = self.load_photo_set() if check_set: self.photo_path = self.photo_gen.next() else: # print 'out of photos, cleanup' return False return True def check_trial(self, good_trial, start_plot_eye_task): if good_trial: self.loop_count += 1 if self.loop_count == self.config['CAL_PTS_PER_PHOTO']: self.loop_count = 0 # check to see if we are out of photos new_photo = self.get_next_photo() # print 'stop showing photos?', new_photo else: # not time for photos, return return False if not new_photo: # if no more photos, return return False else: self.start_plot_eye_task = start_plot_eye_task # still here? start the photo loop! self.start_photo_loop() return True def start_photo_loop(self): self.setup_photo_sequences() self.cross_hair = True self.cross_sequence.start() def setup_photo_sequences(self): # start with cross hair, treat like fixation point, so first wait for fixation watch_eye = Func(self.start_plot_eye_task, check_eye=True) watch_eye_timer = Func(self.start_plot_eye_task, check_eye=True, timer=True) cross_on = Func(self.show_cross_hair) write_to_file_cross_on = Func(self.write_to_file, 'Cross on') write_to_file_fix = Func(self.write_to_file, 'Fixated') cross_off = Func(self.clear_cross_hair) write_to_file_cross_off = Func(self.write_to_file, 'Cross off') cross_interval = random.uniform(*self.cross_hair_int) photo_on = Func(self.show_photo) write_to_file_photo_on = Func(self.write_to_file, 'Photo on', self.photo_path) set_photo_timer = Func(self.set_photo_timer) self.cross_sequence = Parallel(cross_on, write_to_file_cross_on, watch_eye_timer) self.photo_sequence = Sequence( Parallel(write_to_file_fix, watch_eye), Wait(cross_interval), Func(self.stop_plot_eye_task), Parallel(cross_off, write_to_file_cross_off, watch_eye), Parallel(photo_on, write_to_file_photo_on, set_photo_timer)) def start_fixation_period(self): # print 'We have fixation, in subroutine' # start next sequence. Can still be aborted, if lose fixation # during first interval if self.cross_hair: # print 'on the cross hair' self.photo_sequence.start() else: # print 'on the photo' self.photo_timer_on = True def no_fixation(self, task=None): # print 'no fixation or broken, restart cross' self.stop_plot_eye_task() self.restart_cross_bad_fixation() return task.done def broke_fixation(self): if self.cross_hair: # stop checking the eye self.stop_plot_eye_task() # stop sequence self.photo_sequence.pause() self.restart_cross_bad_fixation() else: self.photo_timer_on = False def restart_cross_bad_fixation(self): self.clear_cross_hair() self.write_to_file('Bad Fixation') break_interval = random.uniform(*self.config['BREAK_INTERVAL']) self.base.taskMgr.doMethodLater(break_interval, self.start_photo_loop, 'start_over', extraArgs=[]) def get_fixation_target(self): # for photos, have to do checking of target in Photos # timer irrelevant. target = None on_interval = None if self.cross_hair: target = (0.0, 0.0) # cross fixation always in center on_interval = random.uniform(*self.config['ON_INTERVAL']) return target, on_interval def show_cross_hair(self): # print 'show cross hair' self.x_node.show() def clear_cross_hair(self): # print 'clear cross hair' self.cross_hair = False self.x_node.hide() def stop_plot_eye_task(self): self.base.taskMgr.remove('plot_eye') def show_photo(self): # is definitely fixating at start, otherwise # photo wouldn't come on self.photo_timer_on = True # print self.photo_path # print time() # print 'show window' self.show_window() # print 'show actual photo' self.imageObject = OnscreenImage(self.photo_path, pos=(0, 0, 0), scale=0.75) # print self.imageObject def set_photo_timer(self): self.a = datetime.datetime.now() # print 'add photo timer task' self.photo_fix_time = 0 self.task_timer = 0 self.base.taskMgr.add(self.timer_task, 'photo_timer_task', uponDeath=self.set_break_timer) def timer_task(self, task): # this task collects time. We will only collect time while subject # is fixating. After we collect enough viewing time, exit task # first data point does not count, because photo wasn't up yet. if self.task_timer != 0: dt = task.time - self.task_timer else: dt = 0 self.task_timer = task.time # dt = datetime.datetime.now() - self.task_timer # self.task_timer = datetime.datetime.now() if self.photo_timer_on: # print dt self.photo_fix_time += dt # print 'current timer', self.photo_fix_time if self.photo_fix_time >= self.config['PHOTO_TIMER']: # print datetime.datetime.now() - self.a return task.done else: return task.cont def set_break_timer(self, task): # print('remove photo, on break') self.imageObject.destroy() self.write_to_file('Photo off') for line in self.photo_window: line.detachNode() # print time() # print 'go on break after photo' self.base.taskMgr.doMethodLater(self.config['PHOTO_BREAK_TIMER'], self.send_cleanup, 'photo_send_cleanup') # print 'set break' # print time() return task.done def check_fixation(self, eye_data): # print 'check photo fixation' # print('eye', eye_data) # print('tolerance', self.tolerance) # tolerance is the x, y border that eye_data should # be contained in, both should be (x, y) tuple # photos are centered, so as long as the absolute value of the eye # is less than the absolute value of the tolerance, should be golden # if abs(eye_data[0]) < abs(self.tolerance[0]) and abs(eye_data[1]) < abs(self.tolerance[1]): # hack for giuseppe: if abs(eye_data[0]) < abs(self.tolerance[0]) and -self.tolerance[1] - 100 < eye_data[1] < self.tolerance[1]: return True return False def show_window(self): # draw line around target representing how close the subject has to be looking to get reward # print('show window around square', square_pos) photo_window = LineSegs() photo_window.setThickness(2.0) photo_window.setColor(1, 0, 0, 1) photo_window.moveTo(self.tolerance[0], 55, self.tolerance[1]) # print photo_window.getCurrentPosition() # photo_window.drawTo(self.tolerance[0], 55, -self.tolerance[1] - 100) photo_window.drawTo(self.tolerance[0], 55, -self.tolerance[1]) # print photo_window.getCurrentPosition() # photo_window.drawTo(-self.tolerance[0], 55, -self.tolerance[1] - 100) photo_window.drawTo(-self.tolerance[0], 55, -self.tolerance[1]) # print photo_window.getCurrentPosition() photo_window.drawTo(-self.tolerance[0], 55, self.tolerance[1]) # print photo_window.getCurrentPosition() photo_window.drawTo(self.tolerance[0], 55, self.tolerance[1]) # print photo_window.getCurrentPosition() node = self.base.render.attachNewNode(photo_window.create(True)) node.show(BitMask32.bit(0)) node.hide(BitMask32.bit(1)) self.photo_window.append(node) def draw_cross(self, deg_per_pixel): cross = LineSegs() cross.setThickness(2.0) # cross hair is 1/2 degree visual angle, # so go 1/4 on each side dist_from_center = 0.25 / deg_per_pixel cross.moveTo(0 + dist_from_center, 55, 0) cross.drawTo(0 - dist_from_center, 55, 0) cross.moveTo(0, 55, 0 - dist_from_center) cross.drawTo(0, 55, 0 + dist_from_center) self.x_node = self.base.render.attachNewNode(cross.create(True)) self.x_node.hide() def write_to_file(self, event, photo=None): # print 'write to file', event self.logging.log_event(event) if photo: self.logging.log_event(photo) def close(self): self.base.taskMgr.removeTasksMatching('photo_*') with open(self.config['file_name'], 'a') as config_file: config_file.write('\nLAST_PHOTO_INDEX = ' + str(self.end_index)) def send_cleanup(self, task): self.stop_plot_eye_task() # print time() # print('after photo cleanup, start next loop') messenger.send('cleanup') return task.done
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 MenuFSM(FSM): def __init__(self): FSM.__init__(self, 'MenuFSM') self.frame = DirectFrame(frameColor = (255,255,255,1), frameSize = (-1.5,1.5,-1,1), pos = (0,0,0)) def enterMenu(self): self.mainBackground = OnscreenImage(image = 'images/titleScreen.png', scale = (1.3333333,1, 1)) self.createMenu(menus.mainMenu, startPos = (-0.7,-13,0), parent = self.mainBackground, increment = 0.2) # for button in self.buttons: # button.reparentTo(self.mainBackground) def exitMenu(self): self.mainBackground.destroy() def enterGame(self): self.loading = OnscreenImage(image = 'images/loading.png', scale = (1.3333333,0, 1)) taskMgr.doMethodLater(1, self.startGame, 'tickTask') def startGame(self, THING): # print "lol" self.world = World() self.world.accept("escape", self.request, ['Menu']) # print "abc" self.loading.destroy() self.frame.destroy() def exitGame(self): sys.exit() def enterInstructions(self): self.instructions = OnscreenImage(image = 'images/instructions.png', scale = (1.3333333,0, 1)) self.instructions.accept('escape', self.request, ['Menu']) def exitInstructions(self): self.instructions.destroy() # self.credits = OnscreenImage(image = 'images/credits.png', pos = (-0.5, 0, 0.02)) def enterCredits(self): self.credits = OnscreenImage(image = 'images/credits.png', scale = (1.3333333,0, 1)) self.credits.accept('escape', self.request, ['Menu']) def exitCredits(self): self.credits.destroy() def createMenu(self, menu, startPos=(0,-13,.9), parent = None, increment = 0.3): self.buttons = list() if parent is None: parent = self.frame font = loader.loadFont('fonts/beneg.ttf') scale = 0.10 x = startPos[0] y = startPos[1] z = startPos[2] for v in menu.values(): if 'args' in v: temp = DirectButton(text = v['text'], scale=scale, command=v['function'], extraArgs=v.get('args'), pos=(x,y,z), parent = parent, text_font = font, text_fg = (255,255,255,1), frameColor = (0,0,0,0) ) else: temp = DirectButton(text = v['text'], scale=scale, command=v['function'], pos=(x,y,z), parent = parent, text_font = font, text_fg = (255,255,255,1), frameColor = (0,0,0,0)) self.buttons.append(temp) z = z - increment
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 Minimap(): image = None texture = None map = None onscreen = None 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) def setTargets(self, planetTargets=None,starTargets=None): self.planetTargets = planetTargets if planetTargets is None: pass for i in range(len(self.planetTargets)): star = self.planetTargets[i].parent_star.point_path x = (self.planetTargets[i].point_path.getX() + star.getX())/self.constant y = (self.planetTargets[i].point_path.getY() + star.getY())/self.constant z = (self.planetTargets[i].point_path.getZ() + star.getZ())/self.constant self.dots.append(OnscreenImage(image = "models/gui/minimap/whiteDot.png", scale = 3,pos = (x,0,y), parent = self.map)) if starTargets is None: pass for i in range(len(starTargets)): x = starTargets[i].point_path.getX()/self.constant y = starTargets[i].point_path.getY()/self.constant z = starTargets[i].point_path.getZ()/self.constant self.dots.append(OnscreenImage(image = "models/gui/minimap/redDot.png", scale = 6,pos = (x,0,y), parent = self.map)) def step(self, task): self.dotPlayer.destroy() x = base.camera.getX() y = base.camera.getY() if (x < -3251): x = -3251 if (x > 3000): x= 3000 if (y < -6200): y = -6200 if (y > 6258): y = 6258 self.dotPlayer = OnscreenImage(image = "models/gui/minimap/Player.png", scale = 5,pos = (-1*x/self.constant,0,y/(-2*self.constant)), parent = self.map) self.dotPlayer.setTransparency(1) return Task.cont
class ScreenDecorationManager: def __init__(self): self.tex_judgements = {} for i in ["PERFECT", "GOOD", "OK", "BAD", "MISS"]: self.tex_judgements[i] = loader.loadTexture("image/j_%s.png" % i.lower()) ## Judgement message self.image_judgement = OnscreenImage( image=self.tex_judgements["OK"], pos=(0, 0, 0), scale=(256.0 / base.win.getXSize(), 1, 32.0 / base.win.getYSize()), parent=render2d) self.image_judgement.setTransparency(TransparencyAttrib.MAlpha) #self.image_judgement.setPos(-0.7, 1, 0.6) self.image_judgement.setAlphaScale(0) interval_pos = LerpPosInterval(self.image_judgement, duration=0.1, startPos=VBase3(-1.2, 1, 0.5), pos=VBase3(-0.7, 1, 0.5), blendType='easeOut') interval_alpha = LerpFunc(self.image_judgement.setAlphaScale, duration=0.1, blendType='easeOut') interval_fade = LerpFunc(self.image_judgement.setAlphaScale, fromData=1, toData=0, duration=1.0, blendType='easeOut') self.judgement_enters = Sequence( Parallel(interval_pos, interval_alpha), Wait(1.0), interval_fade) ## Chain message text_node = TextNode('chain_msg') text_node.setAlign(TextNode.ACenter) text_node.setFont(babelfish_font) text_node.setTextColor(1, 1, 0.16, .9) text_node.setShadow(0.05, 0.05) text_node.setShadowColor(0.05, 0, 0.43, .9) self.chain_msg = aspect2d.attachNewNode(text_node) self.chain_msg.setPos(-.9, 1, 0.35) self.chain_msg.setScale(0.11) def judgement_msg(self, msg, chain): if self.judgement_enters.isPlaying(): self.judgement_enters.clearToInitial() self.image_judgement.setTexture(self.tex_judgements[msg]) self.judgement_enters.start() if chain > 1: self.chain_msg.node().setText("%d CHAIN" % chain) taskMgr.add(self.task_ClearJudgementTask, "clear-judgement") def task_ClearJudgementTask(self, task): if task.time < 1.5: return Task.cont self.chain_msg.node().clearText() def __del__(self): self.judgement_enters.finish() self.image_judgement.destroy() self.chain_msg.removeNode()
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 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 SplashScreen(object): #class SplashScreen, which loads a splash screen def __init__(self): #initialization of a splash screen - nothing happens #must request type of splash screen pass def loading(self): #splash screen for loading self.image = OnscreenImage( image = "/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/splashScreens/loading.png", pos = (0, 0, 0), parent=render2d) self.renderFrame() self.image.destroy() def introduction(self): #splash screen for an introduction self.image1 = OnscreenImage( image = "/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/splashScreens/welcome.png", pos = (0, 0, 0), parent=render2d) self.renderFrame() self.image1.destroy() def mode(self): #splash screen for asking for mode self.image3 = OnscreenImage( image="/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/splashScreens/mode.png", pos = (0, 0, 0), parent=render2d) for i in range(2): self.renderFrame() self.image3.destroy() def lose(self): #splash screen for if time runs out self.image4 = OnscreenImage( image="/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/splashScreens/lose.png", pos = (0, 0, 0), parent=render2d) for i in range(2): self.renderFrame() self.image4.destroy() def win(self): #splash screen for a win self.image2 = OnscreenImage( image="/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/splashScreens/winning.png", pos = (0, 0, 0), parent=render2d) for i in range(2): self.renderFrame() self.image2.destroy() def renderFrame(self): #renders the frame for a bit reps = 50 for i in range(reps): base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame()
class Login: def __init__(self, game, statusText="Press 'Enter' to login"): self.game = game self.background = OnscreenImage(image="media/gui/login/bg.png", parent=render2d) base.setBackgroundColor(0, 0, 0) # sets the background color to black because the # default grey color bugs me for some reason self.loginScreen(statusText) # draws the login screen self.usernameBox["focus"] = 1 # sets the cursor to the username field by default game.accept("tab", self.cycleLoginBox) # enables the user to cycle through the text fields with the tab key # this is a standard feature on most login forms game.accept("enter", self.attemptLogin) # submits the login form, or you can just click the Login button def loginScreen(self, statusText): # creates a basic login screen that asks for a username/password boxloc = Vec3(0.0, 0.0, 0.0) # all items in the login form will have a position relative to this # this makes it easier to shift the entire form around once we have # some graphics to display with it without having to change the # positioning of every form element # p is the position of the form element relative to the boxloc # coordinates set above it is changed for every form element p = boxloc + Vec3(-0.22, 0.090, 0.0) self.usernameText = OnscreenText( text="Username:"******"Username: "******""), pos=p, scale=0.04, initialText="hunter", numLines=1 ) # My testing name :P # Username textbox where you type in your username p = boxloc + Vec3(-0.22, 0.0, 0.0) self.passwordText = OnscreenText( text="Password:"******"Password: "******"", pos=p, scale=0.04, initialText="hunter", numLines=1, obscured=1 ) # Testing password. # Password textbox where you type in your password # Note - obscured = 1 denotes that all text entered will be replaced # with a * like a standard password box p = boxloc + Vec3(0, 0, -0.090) self.loginButton = DirectButton(text="Login", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.attemptLogin) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0.95, 0, -0.9) self.createAccButton = DirectButton( text="Create Account", scale=0.050, pos=p, relief=DGG.GROOVE, command=self.attemptCreateAccount ) # Made a quick button for adding accounts. Its fugly p = boxloc + Vec3(1.20, 0, -0.9) self.quitButton = DirectButton(text="Exit", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.game.quit) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0, -0.4, 0) self.statusText = OnscreenText(text=statusText, pos=p, scale=0.043, fg=(1, 0.5, 0, 1), align=TextNode.ACenter) # A simple text object that you can display an error/status messages # to the user def updateStatus(self, statustext): self.statusText.setText(statustext) # all this does is change the status text. def attemptLogin(self): # checks to make sure the user inputed a username and password: # if they didn't it will spit out an error message # if they did, it will try to connect to the login server # (under construction) self.updateStatus("") if self.usernameBox.get() == "": if self.passwordBox.get() == "": self.updateStatus("You must enter a username and password before logging in.") else: self.updateStatus("You must specify a username") self.passwordBox["focus"] = 0 self.usernameBox["focus"] = 1 elif self.passwordBox.get() == "": self.updateStatus("You must enter a password") self.usernameBox["focus"] = 0 self.passwordBox["focus"] = 1 elif self.usernameBox.get() != "" and self.passwordBox.get() != "": self.updateStatus("Attempting to login...") # If user and pass is filled in, send it to the login manager. return self.game.attempt_login(self.usernameBox.get(), self.passwordBox.get()) # why is this returning? does it need to be or does it just need to call the function? # because it will return after calling the function anyway # was thinking could self.updateStatus() and pass a string back from the attempt_login function to say if couldn't connect or if attempting login def attemptCreateAccount(self): # This checks and creates a new account with the username and password. if self.usernameBox.get() == "": if self.passwordBox.get() == "": self.updateStatus("You must enter a username and password before creating.") else: self.updateStatus("") self.updateStatus("You must specify a username") self.passwordBox["focus"] = 0 self.usernameBox["focus"] = 1 elif self.passwordBox.get() == "": self.updateStatus("") self.updateStatus("You must enter a password") self.usernameBox["focus"] = 0 self.passwordBox["focus"] = 1 elif self.usernameBox.get() != "" and self.passwordBox.get() != "": self.updateStatus("") # If user and pass is filled in we send the data once again. but this time to createAccount :P return self.game.create_account(self.usernameBox.get(), self.passwordBox.get()) def cycleLoginBox(self): # function is triggered by the tab key so you can cycle between # the two input fields like on most login screens # IMPORTANT: When you change the focus to one of the text boxes, # you have to unset the focus on the other textbox. If you do not # do this Panda seems to get confused. if self.passwordBox["focus"] == 1: self.passwordBox["focus"] = 0 self.usernameBox["focus"] = 1 elif self.usernameBox["focus"] == 1: self.usernameBox["focus"] = 0 self.passwordBox["focus"] = 1 def destroy(self): self.background.destroy() self.usernameText.destroy() self.passwordText.destroy() self.usernameBox.destroy() self.passwordBox.destroy() self.loginButton.destroy() self.quitButton.destroy() self.createAccButton.destroy() self.statusText.destroy() self.game.ignore("tab") self.game.ignore("enter")
class MainMenu(DirectObject): def __init__(self, skipIntro=False): render.show() engine.Mouse.showCursor() # In case we just got back from the tutorial, which hides everything # sometimes. engine.renderLit.show() self.backgroundSound = audio.FlatSound("menu/background.ogg", volume=0.3) self.backgroundSound.setVolume(0) self.backgroundSound.setLoop(True) self.clickSound = audio.FlatSound("menu/click.ogg", volume=0.3) self.active = True self.accept("escape", self.escape) self.accept("mouse1", self.click) self.cameraDistance = 20 self.globe = engine.loadModel("menu/Globe") self.globe.reparentTo(render) self.globe.setTransparency(TransparencyAttrib.MAlpha) self.globe.setColor(Vec4(1, 1, 1, 0.6)) self.globe.setTwoSided(True) self.globe.setRenderModeWireframe() self.overlay = camera.attachNewNode("overlay") self.overlay.setTransparency(TransparencyAttrib.MAlpha) self.overlay.setColor(Vec4(1, 1, 1, 0)) self.overlay.setPos(0, 0, 0) self.overlay.setPos(0, self.cameraDistance, 0) self.overlay1 = engine.loadModel("menu/overlay1") self.overlay1.setScale(4) self.overlay1.setTwoSided(True) self.overlay1.setRenderModeWireframe() self.overlay1.reparentTo(self.overlay) self.overlay2 = engine.loadModel("menu/overlay2") self.overlay2.setScale(4) self.overlay2.setTwoSided(True) self.overlay2.setRenderModeWireframe() self.overlay2.reparentTo(self.overlay) self.overlay3 = engine.loadModel("menu/overlay3") self.overlay3.setScale(4) self.overlay3.setTwoSided(True) self.overlay3.setRenderModeWireframe() self.overlay3.setR(uniform(0, 360)) self.overlay3.setP(uniform(0, 360)) self.overlay3.setH(uniform(0, 360)) self.overlay3.reparentTo(self.overlay) self.overlay4 = engine.loadModel("menu/overlay3") self.overlay4.setScale(4) self.overlay4.setTwoSided(True) self.overlay4.setRenderModeWireframe() self.overlay4.setH(uniform(0, 360)) self.overlay4.setR(uniform(0, 360)) self.overlay4.setP(uniform(0, 360)) self.overlay4.reparentTo(self.overlay) self.text = engine.loadModel("menu/text") self.text.setScale(4) self.text.setTwoSided(True) self.text.reparentTo(self.overlay) self.selector = engine.loadModel("menu/selector") self.selector.setScale(4) self.selector.setTwoSided(True) self.selector.reparentTo(self.overlay) self.selectedItem = 0 self.skyBox = engine.loadModel("menu/skybox") self.skyBox.setScale(self.cameraDistance * 5) self.skyBox.setRenderModeWireframe() self.skyBox.setTwoSided(True) self.skyBox.reparentTo(render) self.skyBox.setTransparency(TransparencyAttrib.MAlpha) self.skyBox.setColor(Vec4(1, 1, 1, 0)) cmbg = CardMaker("background") size = 10 cmbg.setFrame(-size * engine.aspectRatio, size * engine.aspectRatio, -size, size) self.background = camera.attachNewNode(cmbg.generate()) self.background.setTexture(loader.loadTexture("menu/background.jpg"), 1) self.background.setPos(0, size * 1.25, 0) self.background.setDepthWrite(False) self.belt = JunkBelt(5) self.angle = uniform(0, 360) self.period = 60 self.uiAngle = 0 self.logo = OnscreenImage(image="menu/logo.png", pos=(0, 0, 0), scale=((512.0 / 175.0) * 0.075, 0, 0.075)) self.logo.setTransparency(TransparencyAttrib.MAlpha) self.logo.setColor(1, 1, 1, 0) self.logo.setBin("transparent", 0) self.loadingScreen = OnscreenImage(image="menu/loading.jpg", pos=(0, 0, 0)) self.loadingScreen.setScale(render2d, VBase3(1)) self.loadingScreen.setSx(2) self.loadingScreen.hide() self.skipToEndOfTutorial = skipIntro global firstBoot firstBoot = False self.introTime = 2 if firstBoot and not skipIntro: self.introTime = 4 self.showLogin = firstBoot self.hostList = ui.HostList(self.startClient) self.mapList = ui.MapList(self.startServer) self.loginDialog = ui.LoginDialog(self.setUsername) self.loginDialogShown = False self.introSound = audio.FlatSound("menu/intro.ogg", volume=0.15) self.introSound.play() self.clientConnectAddress = None self.serverMapName = None self.serverMode = 0 # 0 for normal, 1 for tutorial self.serverGameType = 0 # 0 for deathmatch, 1 for survival self.username = "******" self.startTime = -1 self.goTime = -1 if base.appRunner is not None: token = base.appRunner.getToken("username") if token != "" and token != "Unnamed": self.setUsername(token) self.loginDialogShown = True def escape(self): if self.hostList.visible: self.hostList.hide() elif self.mapList.visible: self.mapList.hide() def startClient(self, host): self.clickSound.play() self.hostList.hide() self.loadingScreen.show() self.clientConnectAddress = host self.goTime = engine.clock.time def startServer(self, map, gametype): # Tutorial works on Point Control maps. if not (self.serverMode == 1 and gametype == 1): self.clickSound.play() self.mapList.hide() self.loadingScreen.show() self.serverMapName = map self.serverGameType = gametype self.goTime = engine.clock.time def setUsername(self, username): self.clickSound.play() self.username = username engine.savedUsername = self.username engine.saveConfigFile() self.loginDialog.hide() def update(self): if not self.active: return net.context.readTick() if self.startTime == -1: self.startTime = engine.clock.time elapsedTime = engine.clock.time - self.startTime if elapsedTime < self.introTime: blend = elapsedTime / self.introTime self.angle += engine.clock.timeStep * (1 - blend) self.cameraDistance = 20 + (1 - blend)**2 * 200 elif elapsedTime < self.introTime + 2: self.cameraDistance = 20 blend = (elapsedTime - self.introTime) / 2 self.overlay.setColor(Vec4(1, 1, 1, blend)) self.logo.setColor(1, 1, 1, blend) self.skyBox.setColor(Vec4(1, 1, 1, blend)) if not self.backgroundSound.isPlaying(): self.backgroundSound.play() self.backgroundSound.setVolume(blend * 0.5) else: self.cameraDistance = 20 self.overlay.setColor(Vec4(1, 1, 1, 1)) self.logo.setColor(1, 1, 1, 1) self.skyBox.setColor(Vec4(1, 1, 1, 1)) self.backgroundSound.setVolume(0.5) if elapsedTime > self.introTime: if not self.loginDialogShown and self.showLogin: self.loginDialog.show() self.loginDialogShown = True self.uiAngle -= engine.clock.timeStep * 2 self.text.setR(self.uiAngle) self.hostList.update() self.mapList.update() self.loginDialog.update() mouse = base.win.getPointer(0) props = base.win.getProperties() vector = Vec3((mouse.getX() / float(props.getXSize())) - 0.5, (mouse.getY() / float(props.getYSize())) - 0.5, 0) vector.normalize() angle = math.degrees(math.atan2(-vector.getX(), vector.getY())) + 180 angle -= self.uiAngle if not self.hostList.visible and not self.mapList.visible and not self.loginDialog.visible: self.selectedItem = int(round(angle / 90.0)) while self.selectedItem > 3: self.selectedItem -= 4 while self.selectedItem < 0: self.selectedItem += 4 self.selector.setR(self.uiAngle + self.selectedItem * 90) self.overlay1.setR(self.overlay1.getR() - engine.clock.timeStep * 2) self.overlay2.setR(self.overlay2.getR() + engine.clock.timeStep * 2) self.overlay3.setH(self.overlay3.getH() + engine.clock.timeStep * 10) self.overlay4.setP(self.overlay4.getP() - engine.clock.timeStep * 10) self.belt.update() self.angle += engine.clock.timeStep * 0.025 camera.setPos( math.cos(self.angle) * self.cameraDistance, math.sin(self.angle) * self.cameraDistance, math.cos(elapsedTime / 45 + 2) * 2) camera.lookAt(Point3(0, 0, 0)) backend = None game = None if self.goTime != -1 and engine.clock.time - self.goTime > 0.25: if self.clientConnectAddress is not None: self.delete() online.connectTo(self.clientConnectAddress) backend = ClientBackend(self.clientConnectAddress, self.username) game = Game(backend) elif self.serverMapName is not None: if self.serverMode == 0: # Normal server mode self.delete() if self.serverGameType == 0: backend = PointControlBackend( True, self.username) # Deathmatch else: backend = SurvivalBackend(True, self.username) # Survival game = Game(backend) game.localStart(self.serverMapName) elif self.serverMode == 1: # Tutorial mode self.delete() backend = PointControlBackend(False, self.username) game = Tutorial(backend, 2 if self.skipToEndOfTutorial else 0) game.localStart(self.serverMapName) net.context.writeTick() return backend, game def click(self): if self.mapList.visible or self.hostList.visible or self.loginDialog.visible or engine.clock.time - \ self.startTime < self.introTime + 0.5: return self.clickSound.play() if self.selectedItem == 0: # Join self.hostList.show() elif self.selectedItem == 1: # Tutorial self.mapList.show() self.serverMode = 1 elif self.selectedItem == 2: # Exit engine.exit() elif self.selectedItem == 3: # Host self.mapList.show() self.serverMode = 0 def delete(self): self.loadingScreen.destroy() self.hostList.delete() self.mapList.delete() self.loginDialog.delete() self.active = False self.overlay.removeNode() self.belt.delete() self.background.removeNode() self.globe.removeNode() self.skyBox.removeNode() self.ignoreAll() self.logo.destroy() self.introSound.stop() self.backgroundSound.stop()
class Pregame(DirectObject): def __init__(self): self.posit = 0 self.accept('mouse1', self.positionMove) self.accept('1', self.selectOne) self.accept('2', self.selectTwo) self.accept("escape", sys.exit) self.a = OnscreenImage(parent=render2d, image=os.path.join("image files", "Title-Screen.png")) self.sound_title = loader.loadSfx(os.path.join("sound files", "Title Theme.mp3")) self.sound_main = loader.loadSfx(os.path.join("sound files", "Main Theme.mp3")) self.music = True if self.music: self.sound_title.play() self.sound_title.setLoop(True) self.dog_selection=0 self.music_type = 0 self.accept("m", self.muteMusic) def muteMusic(self): if self.music: self.music = False if self.music_type == 0: self.sound_title.stop() else: self.sound_main.stop() else: self.music = True if self.music_type == 0: self.sound_title.play() self.sound_title.setLoop(True) else: self.sound_main.play() self.sound_main.setLoop(True) def selectOne(self): self.dog_selection=1 self.positionMove() def selectTwo(self): self.dog_selection=2 self.positionMove() def positionMove(self): self.posit += 1 if self.posit == 1: self.a.destroy() self.b = OnscreenImage(parent=render2d, image=os.path.join("image files", "Intro-Screen.png")) elif self.posit == 2: self.b.destroy() self.c = OnscreenImage(parent=render2d, image=os.path.join("image files", "Instruction-Screen.png")) elif self.posit == 3: self.c.destroy() self.d = OnscreenImage(parent=render2d, image=os.path.join("image files", "Selection-Screen.png")) elif self.posit == 4: if not self.dog_selection==0: self.music_type = 1 if self.music: self.sound_title.stop() self.sound_main.play() self.sound_main.setLoop(True) self.d.destroy() w = world.World(self.dog_selection) else: self.posit = 3
class Login(): def __init__(self, game, statusText = "Press 'Enter' to login"): self.game=game self.background = OnscreenImage( image = 'media/gui/login/bg.png', parent = render2d ) base.setBackgroundColor( 0, 0, 0 ) # sets the background color to black because the # default grey color bugs me for some reason self.loginScreen(statusText) # draws the login screen self.usernameBox['focus'] = 1 # sets the cursor to the username field by default game.accept('tab', self.cycleLoginBox) # enables the user to cycle through the text fields with the tab key # this is a standard feature on most login forms game.accept('enter', self.attemptLogin) # submits the login form, or you can just click the Login button def loginScreen(self,statusText): # creates a basic login screen that asks for a username/password boxloc = Vec3(0.0, 0.0, 0.0) # all items in the login form will have a position relative to this # this makes it easier to shift the entire form around once we have # some graphics to display with it without having to change the # positioning of every form element # p is the position of the form element relative to the boxloc # coordinates set above it is changed for every form element p = boxloc + Vec3(-0.22, 0.090, 0.0) self.usernameText = OnscreenText(text = "Username:"******"Username: "******"") , pos = p, scale=.04, initialText="hunter", numLines = 1) # My testing name :P # Username textbox where you type in your username p = boxloc + Vec3(-0.22, 0.0, 0.0) self.passwordText = OnscreenText(text = "Password:"******"Password: "******"" , pos = p, scale=.04, initialText="hunter", numLines = 1, obscured = 1) # Testing password. # Password textbox where you type in your password # Note - obscured = 1 denotes that all text entered will be replaced # with a * like a standard password box p = boxloc + Vec3( 0, 0, -0.090) self.loginButton = DirectButton(text="Login", pos = p, scale = 0.048, relief=DGG.GROOVE, command=self.attemptLogin) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0.95, 0, -0.9) self.createAccButton = DirectButton(text= "Create Account", scale=0.050, pos = p, relief=DGG.GROOVE, command=self.attemptCreateAccount) # Made a quick button for adding accounts. Its fugly p = boxloc + Vec3(1.20, 0, -0.9) self.quitButton = DirectButton(text="Exit", pos = p, scale = 0.048, relief=DGG.GROOVE, command=self.game.quit) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0, -0.4, 0) self.statusText = OnscreenText(text = statusText, pos = p, scale = 0.043, fg = (1, 0.5, 0, 1), align=TextNode.ACenter) # A simple text object that you can display an error/status messages # to the user def updateStatus(self, statustext): self.statusText.setText(statustext) # all this does is change the status text. def attemptLogin(self): # checks to make sure the user inputed a username and password: # if they didn't it will spit out an error message # if they did, it will try to connect to the login server # (under construction) self.updateStatus("") if(self.usernameBox.get() == ""): if(self.passwordBox.get() == ""): self.updateStatus("You must enter a username and password before logging in.") else: self.updateStatus("You must specify a username") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif(self.passwordBox.get() == ""): self.updateStatus("You must enter a password") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 elif self.usernameBox.get() != "" and self.passwordBox.get() != "": self.updateStatus("Attempting to login...") # If user and pass is filled in, send it to the login manager. return self.game.attempt_login(self.usernameBox.get(), self.passwordBox.get()) # why is this returning? does it need to be or does it just need to call the function? # because it will return after calling the function anyway # was thinking could self.updateStatus() and pass a string back from the attempt_login function to say if couldn't connect or if attempting login def attemptCreateAccount(self): # This checks and creates a new account with the username and password. if(self.usernameBox.get() == ""): if(self.passwordBox.get() == ""): self.updateStatus("You must enter a username and password before creating.") else: self.updateStatus("") self.updateStatus("You must specify a username") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif(self.passwordBox.get() == ""): self.updateStatus("") self.updateStatus("You must enter a password") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 elif self.usernameBox.get() != "" and self.passwordBox.get() != "": self.updateStatus("") # If user and pass is filled in we send the data once again. but this time to createAccount :P return self.game.create_account(self.usernameBox.get(), self.passwordBox.get()) def cycleLoginBox(self): # function is triggered by the tab key so you can cycle between # the two input fields like on most login screens # IMPORTANT: When you change the focus to one of the text boxes, # you have to unset the focus on the other textbox. If you do not # do this Panda seems to get confused. if(self.passwordBox['focus'] == 1): self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif(self.usernameBox['focus'] == 1): self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 def destroy(self): self.background.destroy() self.usernameText.destroy() self.passwordText.destroy() self.usernameBox.destroy() self.passwordBox.destroy() self.loginButton.destroy() self.quitButton.destroy() self.createAccButton.destroy() self.statusText.destroy() self.game.ignore('tab') self.game.ignore('enter')
class Lvl03(DirectObject): def start(self): base.disableMouse() #turn off mouse camera control base.enableParticles() self.music = loader.loadMusic("models/gamedev/DEC.mp3") self.music.play() camera.setPosHpr(Vec3(98,-390,90), Vec3(0,-5,0)) self.ballNum = 10 self.setupStage() self.loadModels() self.setupLighting() self.setupCollisions() self.setupIntervals() taskMgr.add(self.ballMovementTask,'ballMoveTask') self.gameLen = 30 self.player1Weapon = "" self.player2Weapon = "" #hud = OnscreenImage(image = 'models/gamedev/lvl2hud.jpg', pos = (0,1,20),scale=5.0) #hud.reparentTo(render) globalClock.reset() self.timer = OnscreenText("%d" % (self.gameLen-globalClock.getRealTime(),), pos = (98,145), scale = 18.0) self.timer.setColor(1,1,1) taskMgr.add(self.clockTask,"clockTask") self.player1Score = 0 self.player2Score = 0 self.nodeCount1 = 0 self.nodeCount2 = 0 self.player1Invincible = 0 self.player2Invincible = 0 self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2") self.jNP2 = self.playerModel2.exposeJoint(None,"modelRoot","ikHandle2") self.climbing1 = 0 self.climbing2 = 0 self.speed1 = 3.0 self.speed2 = 3.0 self.ignoreColl= 0 self.player1IsColliding = 0 self.player2IsColliding = 0 taskMgr.doMethodLater(self.gameLen, self.endGame,'gameFinished') #taskMgr.doMethodLater(self.gameLen/2.0,self.changeMusic,'musicSwitch') #setup key controls self.accept("escape",sys.exit) #self.acceptOnce("space",self.drop) # Player 1 movement self.acceptOnce("a",self.left) self.acceptOnce("d",self.right) self.accept("a-up",self.stopLeft) self.accept("d-up",self.stopRight) self.acceptOnce("w", self.jump) #Player 2 movement keys #self.accept("l",self.fall2) self.acceptOnce("k",self.left2) self.acceptOnce(";",self.right2) self.accept("k-up",self.stopLeft2) self.accept(";-up",self.stopRight2) self.acceptOnce("o", self.jumpT2) def setupStage(self): self.ball = [] self.movement = [] for i in range(self.ballNum+1): z=random.randint(1,2) if z ==1: z=-1 else: z=1 weapBalls.define(self.ball,i,render) self.movement.append(Vec3(random.random()*z,0,random.random()*z)) #self.movement[i].Vec3(random.randint(1,3),0,random.randint(1,3)) self.background2 = OnscreenImage(image = 'models/gamedev/frozenbg.JPG', pos = (98,10,0),scale=500) self.background2.detachNode() self.background = OnscreenImage(image = 'models/gamedev/moltenbg.JPG', pos = (98,10,0),scale=500) self.background.reparentTo(render) self.lava = loader.loadModel("models/gamedev/lava") self.lava.setPosHpr(Vec3(98,0,-18),Vec3(0,5,0)) self.lava.setScale(50) self.lava.reparentTo(render) x1= 196 x2 = 0 m1 = 98 m2 = 107.8 len = 9.8 h = 0 a = 0 p = 0 for j in range(4): if j > 0: x1Old = x1 x2Old = x2 x1 = 196-(random.randint(0,3)*9.8) x2 = 0+random.randint(0,3)*9.8 m1=98-(random.randint(0,3)*9.8) m2= 107.8+random.randint(0,3)*9.8 for count in range(1): l = random.randint(2,5) r = random.randint(2,5) c1 = random.randint(2,5) c2 = random.randint(2,5) if l+r < 4: count = 0 else: l = 4 r = 4 c1 = 2 c2 = 2 ''' if j ==1 or j == 3: self.ladder = loader.loadModel("models/gamedev/ladder") self.ladder.reparentTo(render) self.ladder.setScale(1.5) self.ladder.setPos(x2+4.9,0,h-20) self.ladder2 = loader.loadModel("models/gamedev/ladder") self.ladder2.reparentTo(render) self.ladder2.setScale(1.5) self.ladder2.setPos(x1-4.9,0,h-20) if j == 2: self.ladder = loader.loadModel("models/gamedev/ladder") self.ladder.reparentTo(render) self.ladder.setScale(1.5) self.ladder.setPos(m1-4.9,0,h-20) self.ladder2 = loader.loadModel("models/gamedev/ladder") self.ladder2.reparentTo(render) self.ladder2.setScale(1.5) self.ladder2.setPos(m2+4.9,0,h-20) ''' self.first = 1 for i in range(r): '''Right half of stage''' self.environment = loader.loadModel("models/gamedev/platform") self.environment.reparentTo(render) self.environment.setScale(5) self.environment.setPos(x1,0,h) if self.first == 1: self.first = 0 bounds = self.environment.getChild(0).getBounds() center = bounds.getCenter() poly1 = Point3(center.getX()+1, center.getY()-.5, center.getZ()+.2) poly2 = Point3(center.getX()-(2*r-1), center.getY()-.5, center.getZ()+.2) poly3 = Point3(center.getX()+1, center.getY()+.5, center.getZ()+.2) poly4 = Point3(center.getX()-(2*r-1), center.getY()+.5, center.getZ()+.2) cPoly = CollisionPolygon(poly4, poly2, poly1, poly3) cNode = CollisionNode("platform") cNode.addSolid(cPoly) cNodePath = self.environment.attachNewNode(cNode) cNodePath.show() x1 = x1 - len self.first = 1 for i in range(l): '''Left Half of stage''' self.environment = loader.loadModel("models/gamedev/platform") self.environment.reparentTo(render) self.environment.setScale(5) self.environment.setPos(x2,0,h) if self.first == 1: self.first = 0 bounds = self.environment.getChild(0).getBounds() center = bounds.getCenter() poly1 = Point3(center.getX()+(2*l-1), center.getY()-.5, center.getZ()+.2) poly2 = Point3(center.getX()-1, center.getY()-.5, center.getZ()+.2) poly3 = Point3(center.getX()+(2*l-1), center.getY()+.5, center.getZ()+.2) poly4 = Point3(center.getX()-1, center.getY()+.5, center.getZ()+.2) cPoly = CollisionPolygon(poly4, poly2, poly1, poly3) cNode = CollisionNode("platform") cNode.addSolid(cPoly) cNodePath = self.environment.attachNewNode(cNode) cNodePath.show() x2 = x2 + len self.first = 1 for i in range(c1): '''Right half of stage''' self.environment = loader.loadModel("models/gamedev/platform") self.environment.reparentTo(render) self.environment.setScale(5) self.environment.setPos(m1,0,h) if self.first == 1: self.first = 0 bounds = self.environment.getChild(0).getBounds() center = bounds.getCenter() poly1 = Point3(center.getX()+1, center.getY()-.5, center.getZ()+.2) poly2 = Point3(center.getX()-(2*c1-1), center.getY()-.5, center.getZ()+.2) poly3 = Point3(center.getX()+1, center.getY()+.5, center.getZ()+.2) poly4 = Point3(center.getX()-(2*c1-1), center.getY()+.5, center.getZ()+.2) cPoly = CollisionPolygon(poly4, poly2, poly1, poly3) cNode = CollisionNode("platform") cNode.addSolid(cPoly) cNodePath = self.environment.attachNewNode(cNode) cNodePath.show() m1 = m1 - len self.first = 1 for i in range(c2): '''Left Half of stage''' self.environment = loader.loadModel("models/gamedev/platform") self.environment.reparentTo(render) self.environment.setScale(5) self.environment.setPos(m2,0,h) if self.first == 1: self.first = 0 bounds = self.environment.getChild(0).getBounds() center = bounds.getCenter() poly1 = Point3(center.getX()+(2*c2-1), center.getY()-.5, center.getZ()+.2) poly2 = Point3(center.getX()-1, center.getY()-.5, center.getZ()+.2) poly3 = Point3(center.getX()+(2*c2-1), center.getY()+.5, center.getZ()+.2) poly4 = Point3(center.getX()-1, center.getY()+.5, center.getZ()+.2) cPoly = CollisionPolygon(poly4, poly2, poly1, poly3) cNode = CollisionNode("platform") cNode.addSolid(cPoly) cNodePath = self.environment.attachNewNode(cNode) cNodePath.show() m2 = m2 + len h = h+40 a = 0 def loadModels(self): # ** Load female character that will represent first player** # self.playerModel = Actor("models/gamedev/redguy-model",{"walk":"models/gamedev/redguy-run"}) self.playerModel.reparentTo(render) self.playerModel.setScale(.6) self.playerModel.setH(90) # ** Position player at center of the field with it lying directly above the field. ** # self.playerModel.setPos(0,0,1.76) # ** Load female character that will represent second player** # self.playerModel2 = Actor("models/gamedev/bluegirl-model",{"walk2":"models/gamedev/bluegirl-run"}) self.playerModel2.reparentTo(render) self.playerModel2.setScale(.6) self.playerModel2.setH(0) # ** Position player at center of the field with it lying directly above the field. ** # self.playerModel2.setPos(196,0,2.0) def reset(self): self.an1.getPhysicsObject().setVelocity(Vec3(0,0,0)) self.an2.getPhysicsObject().setVelocity(Vec3(0,0,0)) self.an1.getPhysicsObject().setPosition(Point3(0,0,11.76)) self.an2.getPhysicsObject().setPosition(Point3(196,0,22.0)) self.playerModel.setH(90) self.playerModel.detachNode() self.playerModel.setPos(0,0,1.76) self.anp.setFluidPos(Point3(0,0,1.76)) self.playerModel.reparentTo(self.anp) self.playerModel2.setH(0) self.playerModel2.detachNode() self.playerModel2.setPos(196,0,22.0) self.anp2.setFluidPos(Point3(196,0,22.0)) self.playerModel2.reparentTo(self.anp2) def setupLighting(self): ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.55,0.55,0.55,1.0)) ambientLightNP = render.attachNewNode(ambientLight) render.setLight(ambientLightNP) dirLight = DirectionalLight('dirLight') dirLight.setColor(Vec4(0.6,0.6,0.6,1)) dirLightNP = render.attachNewNode(dirLight) dirLightNP.setHpr(Vec3(0.0,-26.0,0.0)) render.setLight(dirLightNP) def setupIntervals(self): self.charWalk1l = self.playerModel.actorInterval("walk") self.charWalk1l.loop( ) self.charWalk1l.pause( ) self.charWalk1r = self.playerModel.actorInterval("walk") self.charWalk1r.loop( ) self.charWalk1r.pause( ) self.charWalk2l = self.playerModel2.actorInterval("walk2") self.charWalk2l.loop( ) self.charWalk2l.pause( ) self.charWalk2r = self.playerModel2.actorInterval("walk2") self.charWalk2r.loop( ) self.charWalk2r.pause( ) self.jump1 = self.playerModel.actorInterval("jump") self.jump1.loop() self.jump1.pause() self.jump2 = self.playerModel2.actorInterval("jump2") self.jump2.loop() self.jump2.pause() self.climb1 = self.playerModel.actorInterval("climb") self.climb1.loop() self.climb1.pause() self.climb2 = self.playerModel2.actorInterval("climb2") self.climb2.loop() self.climb2.pause() # end setupIntervals # ############################ # Actual Working movement code # ############################ def rise(self): dist = 40 self.playerModel.setH(0) playerJump = self.playerModel.posInterval(1.0,Vec3(self.playerModel.getX(), self.playerModel.getY(),self.playerModel.getZ()+dist)) playerJump.start() def rise2(self): dist = 40 self.playerModel2.setH(90) playerJump2 = self.playerModel2.posInterval(1.0,Vec3(self.playerModel2.getX(), self.playerModel2.getY(),self.playerModel2.getZ()+dist)) playerJump2.start() # PLAYER ONE # def left(self): taskMgr.add(self.leftTask,'leftTask') self.charWalk1l.loop() #end left def leftTask(self,task): if self.climbing1 == 0: self.playerModel.setH(270) self.playerModel.setPos(Vec3(self.playerModel.getX()-self.speed1, self.playerModel.getY(), self.playerModel.getZ())) return Task.cont def right(self): taskMgr.add(self.rightTask,'rightTask') self.charWalk1r.loop() #end right def rightTask(self,task): if self.climbing1 == 0: self.playerModel.setH(90) self.playerModel.setPos(Vec3(self.playerModel.getX()+self.speed1, self.playerModel.getY(), self.playerModel.getZ())) return Task.cont def climbable(self,cEntry): self.nodeCount1+=1 print self.nodeCount1 self.ignore("w") self.ignore("w-up") self.ignore("s") self.ignore("s-up") self.acceptOnce("w",self.climb,[1]) self.accept("w-up",self.noClimb) self.acceptOnce("s",self.climb,[-1]) self.accept("s-up",self.noClimb) def climb(self,dir): self.dir1 = dir self.climbing1 = 1 self.climbSpeed1 = 1 self.ignore("a") self.ignore("a-up") self.ignore("d") self.ignore("d-up") taskMgr.add(self.climbTask,'climbTask') self.climb1.loop() def noClimb(self): taskMgr.remove('climbTask') self.climb1.pause() if self.nodeCount1 == 0: self.climbing = 0 self.climbSpeed1 = 0 self.acceptOnce("w",self.climb,[1]) self.acceptOnce("s",self.climb,[-1]) def jumpable(self,cEntry): self.nodeCount1+=-1 print self.nodeCount1 if self.nodeCount1 == 0: taskMgr.remove('climbTask') self.ignore("w") self.ignore("w-up") self.ignore("s") self.ignore("s-up") self.acceptOnce("w",self.jump) self.acceptOnce("a",self.left) self.acceptOnce("d",self.right) self.accept("a-up",self.stopLeft) self.accept("d-up",self.stopRight) self.climbing1 = 0 self.climbSpeed1 = 0 self.climb1.pause() def walkable(self,cEntry): self.ignore("w") self.ignore("w-up") self.ignore("s") self.ignore("s-up") self.acceptOnce("w",self.climb,[1]) self.accept("w-up",self.noClimb) self.acceptOnce("s",self.climb,[-1]) self.accept("s-up",self.noClimb) self.acceptOnce("a",self.left) self.acceptOnce("d",self.right) self.accept("a-up",self.stopLeft) self.accept("d-up",self.stopRight) self.climbing1 = 0 self.climbSpeed1 = 0 self.climb1.pause() def climbTask(self,task): if self.playerModel.getZ() >=0: self.playerModel.setH(0) self.playerModel.setPos(Vec3(self.playerModel.getX(), self.playerModel.getY(), self.playerModel.getZ()+self.climbSpeed1*self.dir1)) return Task.cont def jump(self): if self.nodeCount1 == 0: self.ignore("w") self.ignore("w-up") z = self.playerModel.getZ() j = ProjectileInterval(self.playerModel, startPos = self.playerModel.getPos(), startVel = Point3(5,0,30), duration = 2.0) j.start() taskMgr.doMethodLater(2,self.jumpTask,"jumpTask") else: self.acceptOnce("w",self.climb,[1]) def jumpTask(self, task): if self.climbing1 == 0: self.jump1.pause() self.acceptOnce("w",self.jump) #return task.cont def allowRight(self): self.acceptOnce("d",self.right) def noRight(self): taskMgr.remove('rightTask') self.charWalk1r.pause() self.acceptOnce("d",self.right) def stopRight(self): self.noRight() #self.allowRight() def rightWall(self,cEntry): self.ignore("d") self.noRight() def rightEdge(self,cEntry): self.ignore("d") self.noRight() def rightOK(self,cEntry): self.allowRight() def allowLeft(self): self.acceptOnce("a",self.left) def noLeft(self): taskMgr.remove('leftTask') self.charWalk1l.pause() self.acceptOnce("a",self.left) def stopLeft(self): self.noLeft() #self.allowLeft() def leftWall(self,cEntry): self.ignore("a") self.noLeft() def leftEdge(self,cEntry): self.ignore("a") self.noLeft() def leftOK(self,cEntry): self.allowLeft() # PLAYERTWO # def left2(self): taskMgr.add(self.leftTask2,'leftTask2') self.charWalk2l.loop() #end left def leftTask2(self,task): if self.climbing2 == 0: self.playerModel2.setH(0) self.playerModel2.setPos(Vec3(self.playerModel2.getX()-self.speed2, self.playerModel2.getY(), self.playerModel2.getZ())) return Task.cont def right2(self): taskMgr.add(self.rightTask2,'rightTask2') self.charWalk2r.loop() #end right def rightTask2(self,task): if self.climbing2 == 0: self.playerModel2.setH(180) self.playerModel2.setPos(Vec3(self.playerModel2.getX()+self.speed2, self.playerModel2.getY(), self.playerModel2.getZ())) return Task.cont def climbable2(self,cEntry): self.nodeCount2+=1 #print self.nodeCount1 self.ignore("o") self.ignore("o-up") self.ignore("l") self.ignore("l-up") self.acceptOnce("o",self.climbT2,[1]) self.accept("o-up",self.noClimb2) self.acceptOnce("l",self.climbT2,[-1]) self.accept("l-up",self.noClimb2) def climbT2(self,dir): self.dir2 = dir self.climbing2 = 1 self.climbSpeed2 = 1 self.ignore("k") self.ignore("k-up") self.ignore(";") self.ignore(";-up") taskMgr.add(self.climbTask2,'climbTask2') self.climb2.loop() def noClimb2(self): taskMgr.remove('climbTask2') self.climb2.pause() if self.nodeCount2 == 0: self.climbing2 = 0 self.climbSpeed2 = 0 self.acceptOnce("o",self.climbT2,[1]) self.acceptOnce("l",self.climbT2,[-1]) def jumpable2(self,cEntry): self.nodeCount2+=-1 #print self.nodeCount2 if self.nodeCount2 == 0: taskMgr.remove('climbTask2') self.ignore("o") self.ignore("o-up") self.ignore("l") self.ignore("l-up") self.acceptOnce("o",self.jumpT2) self.acceptOnce("k",self.left2) self.acceptOnce(";",self.right2) self.accept("k-up",self.stopLeft2) self.accept(";-up",self.stopRight2) self.climbing2 = 0 self.climbSpeed2 = 0 self.climb2.pause() def walkable2(self,cEntry): self.ignore("o") self.ignore("o-up") self.ignore("l") self.ignore("l-up") self.acceptOnce("o",self.climbT2,[1]) self.accept("o-up",self.noClimb2) self.acceptOnce("l",self.climbT2,[-1]) self.accept("l-up",self.noClimb2) self.acceptOnce("k",self.left2) self.acceptOnce(";",self.right2) self.accept("k-up",self.stopLeft) self.accept(";-up",self.stopRight) self.climbing2 = 0 self.climbSpeed2 = 0 self.climb2.pause() def climbTask2(self,task): if self.playerModel2.getZ() >=0: self.playerModel2.setH(90) self.playerModel2.setPos(Vec3(self.playerModel2.getX(), self.playerModel2.getY(), self.playerModel2.getZ()+self.climbSpeed2*self.dir2)) return Task.cont def jumpT2(self): if self.nodeCount2 == 0: self.ignore("o") self.ignore("o-up") z = self.playerModel2.getZ() j = ProjectileInterval(self.playerModel2, startPos = self.playerModel2.getPos(), startVel = Point3(3,0,30), duration = 2.0) j.start() taskMgr.doMethodLater(3,self.jumpTask2,"jumpTask2") else: self.acceptOnce("w",self.climb,[1]) def jumpTask2(self, task): if self.climbing2 == 0: self.jump2.pause() self.acceptOnce("o",self.jumpT2) #return task.cont def allowRight2(self): self.acceptOnce(";",self.right2) def noRight2(self): taskMgr.remove('rightTask2') self.charWalk2r.pause() self.acceptOnce(";",self.right2) def stopRight2(self): self.noRight2() #self.allowRight() def rightWall2(self,cEntry): self.ignore(";") self.noRight2() def rightEdge2(self,cEntry): self.ignore(";") self.noRight2() def rightOK2(self,cEntry): self.allowRight2() def allowLeft2(self): self.acceptOnce("k",self.left2) def noLeft2(self): taskMgr.remove('leftTask2') self.charWalk2l.pause() self.acceptOnce("k",self.left2) def stopLeft2(self): self.noLeft2() #self.allowLeft() def leftWall2(self,cEntry): self.ignore("k") self.noLeft2() def leftEdge2(self,cEntry): self.ignore("k") self.noLeft2() def leftOK2(self,cEntry): self.allowLeft2() def setupCollisions(self): self.cHandler = PhysicsCollisionHandler() #self.cHandler.setInPattern("ate-%in") self.cHandler.addInPattern('%fn-into-%in') #self.cHandler2.addInPattern('%fn-into-%in') self.cHandler.setAgainPattern('%fn-again-%in') self.cHandler.setOutPattern('%fn-outof-%in') self.cTrav = CollisionTraverser() #self.cTrav2 = CollisionTraverser() base.cTrav = self.cTrav #Player 1 collision solid bounds = self.playerModel.getChild(0).getBounds() center = bounds.getCenter()-Vec3(0,0,12) radius = bounds.getRadius()-18 boundsB = self.playerModel.getChild(0).getBounds() centerB = bounds.getCenter()-Vec3(0,0,-4) radiusB = bounds.getRadius()-20 cSphere = CollisionSphere(center,radius) cSphereB = CollisionSphere(centerB,radiusB) cNode = CollisionNode("player1") #print radius, radiusB cNode.addSolid(cSphere) cNode.addSolid(cSphereB) cNodePath = self.playerModel.attachNewNode(cNode) cNodePath.show() Node=NodePath(PandaNode("PhysicsNode")) Node.reparentTo(render) self.an1=ActorNode("player1-physics") self.anp=Node.attachNewNode(self.an1) base.physicsMgr.attachPhysicalNode(self.an1) self.playerModel.reparentTo(self.anp) #self.anp.reparentTo(self.playerModel) #Player 2 collision solid bounds2 = self.playerModel2.getChild(0).getBounds() center2 = bounds2.getCenter()-Vec3(0,0,-4) radius2 = bounds2.getRadius()-20 cSphere2 = CollisionSphere(center2,radius2) bounds2B = self.playerModel2.getChild(0).getBounds() center2B = bounds2B.getCenter()-Vec3(0,0,12) radius2B = bounds2B.getRadius()-18 cSphere2B = CollisionSphere(center2B,radius2B) cNode2 = CollisionNode("player2") #print radius2, radius2B cNode2.addSolid(cSphere2) cNode2.addSolid(cSphere2B) cNodePath2 = self.playerModel2.attachNewNode(cNode2) cNodePath2.show() Node2=NodePath(PandaNode("PhysicsNode")) Node2.reparentTo(render) self.an2=ActorNode("player2-physics") self.anp2=Node2.attachNewNode(self.an2) base.physicsMgr.attachPhysicalNode(self.an2) self.playerModel2.reparentTo(self.anp2) #self.anp2.reparentTo(self.playerModel2) gravityFN=ForceNode('world-forces') gravityFNP=render.attachNewNode(gravityFN) gravityForce=LinearVectorForce(0,0,-9.8) #gravity acceleration gravityFN.addForce(gravityForce) base.physicsMgr.addLinearForce(gravityForce) self.an1.getPhysicsObject().setMass(15) self.an2.getPhysicsObject().setMass(15) gravityForce.setMassDependent(1) self.cHandler.addCollider(cNodePath, self.anp) self.cHandler.addCollider(cNodePath2, self.anp2) self.cTrav.addCollider(cNodePath,self.cHandler) self.cTrav.addCollider(cNodePath2,self.cHandler) self.cTrav.addCollider(cNodePath,self.cHandler) self.cTrav.addCollider(cNodePath2,self.cHandler) #self.cTrav.addCollider(cNodePath,self.cHandler2) #self.cTrav.addCollider(cNodePath2,self.cHandler2) #self.cTrav2.addCollider(cNodePath,self.cHandler2) #self.cTrav2.addCollider(cNodePath2,self.cHandler2) #cHandler2 = CollisionHandlerEvent() #cHandler2.addInPattern('%fn-into-%in') #self.cTrav.addCollider(cNodePath1,cHandler2) #self.cTrav.addCollider(cNodePath2,cHandler2) for i in range(self.ballNum+1): boundsB = self.ball[i].getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*0.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("ball") cNodeB.addSolid(cSphereB) cNodePathB = self.ball[i].attachNewNode(cNodeB) #self.cTrav.addCollider(cNodePathB,self.cHandler) #cNodePathB.show() self.accept("player1-into-ball",self.acquire1) #self.accept("ball-into-player1",self.acquire1) self.accept("player2-into-ball",self.acquire2) #self.accept("ball-into-player2",self.acquire2) #self.accept( 'player1-into2-platform', self.wall1) #self.accept( 'player2-into2-platform', self.wall2) def wall1(self,cEntry): self.an1.getPhysicsObject().setVelocity(Vec3(0,0,0)) def wall2(self,cEntry): self.an2.getPhysicsObject().setVelocity(Vec3(0,0,0)) def player1Wins(self,cEntry): if self.player2Invincible == 0: self.player1Score+=10 self.reset() def player2Wins(self,cEntry): if self.player1Invincible == 0: self.player2Score+=10 self.reset() def acquire1(self,cEntry): self.playerModel.setY(0) if str(cEntry.getIntoNodePath().getParent()) == "render/sawball": self.player1Weapon = "saw" saw = loader.loadModel("models/gamedev/saw") saw.setScale(2.5) self.jNP.getChildren().detach() saw.reparentTo(self.jNP) self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/moltovball": self.player1Weapon = "molotov" molo = loader.loadModel("models/gamedev/moltov") molo.setScale(2.5) #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2") self.jNP.getChildren().detach() molo.reparentTo(self.jNP) self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/grenadeball": self.player1Weapon = "grenade" gren = loader.loadModel("models/gamedev/grenade") gren.setScale(2.5) #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2") self.jNP.getChildren().detach() gren.reparentTo(self.jNP) self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/pogo": #done self.jNP.getChildren().detach() self.player1Weapon = "jump" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/golden": #done self.jNP.getChildren().detach() self.player1Weapon = "speedUp" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/crystalball": self.jNP.getChildren().detach() self.player1Weapon = "icestage" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/fireball": #done self.jNP.getChildren().detach() self.player1Weapon = "meteo" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/blackball": #done self.jNP.getChildren().detach() self.player1Weapon = "blind" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/translucent": self.jNP.getChildren().detach() self.player1Weapon = "invis" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/superball": #done self.jNP.getChildren().detach() self.player1Weapon = "invincible" self.acceptOnce("e",self.useWeapon1) self.acceptOnce("q",self.useWeapon1) elif str(cEntry.getIntoNodePath().getParent()) == "render/death": #done self.jNP.getChildren().detach() if self.player1Invincible == 0: self.player2Deaths+= 1 self.reset() cEntry.getIntoNodePath().getParent().removeNode() #Drop a New Ball self.ballNum+=1 z=random.randint(1,2) if z ==1: z=-1 else: z=1 self.movement.append(Vec3(random.random()*z,0,random.random()*z)) weapBalls.define(self.ball,self.ballNum,render) boundsB = self.ball[self.ballNum].getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("ball") cNodeB.addSolid(cSphereB) cNodePathB = self.ball[self.ballNum].attachNewNode(cNodeB) def acquire2(self,cEntry): if str(cEntry.getIntoNodePath().getParent()) == "render/sawball": self.player2Weapon = "saw" saw = loader.loadModel("models/gamedev/saw") saw.setScale(2.5) self.jNP2.getChildren().detach() saw.reparentTo(self.jNP2) self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/moltovball": self.player2Weapon = "molotov" molo = loader.loadModel("models/gamedev/moltov") molo.setScale(2.5) #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2") self.jNP.getChildren().detach() molo.reparentTo(self.jNP) self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/grenadeball": self.player2Weapon = "grenade" gren = loader.loadModel("models/gamedev/grenade") gren.setScale(2.5) #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2") self.jNP.getChildren().detach() gren.reparentTo(self.jNP) self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/pogo": #done self.jNP.getChildren().detach() self.player2Weapon = "jump" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/golden": #done self.jNP.getChildren().detach() self.player2Weapon = "speedUp" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/crystalball": self.jNP.getChildren().detach() self.player2Weapon = "icestage" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/fireball": #done self.jNP.getChildren().detach() self.player2Weapon = "meteo" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/blackball": #done self.jNP.getChildren().detach() self.player2Weapon = "blind" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/translucent": self.jNP.getChildren().detach() self.player2Weapon = "invis" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/superball": #done self.jNP.getChildren().detach() self.player2Weapon = "invincible" self.acceptOnce("e",self.useWeapon2) self.acceptOnce("q",self.useWeapon2) elif str(cEntry.getIntoNodePath().getParent()) == "render/death": #done self.jNP.getChildren().detach() if self.player2Invincible == 0: self.player1Score+=3 self.reset() cEntry.getIntoNodePath().getParent().removeNode() #Drop a New Ball self.ballNum+=1 z=random.randint(1,2) if z ==1: z=-1 else: z=1 self.movement.append(Vec3(random.random()*z,0,random.random()*z)) weapBalls.define(self.ball,self.ballNum,render) boundsB = self.ball[self.ballNum].getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("ball") cNodeB.addSolid(cSphereB) cNodePathB = self.ball[self.ballNum].attachNewNode(cNodeB) def useWeapon1(self): if self.player1Weapon == "meteo": fireRain = Sequence(Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain)) fireRain.start() elif self.player1Weapon == "jump": self.playerModel.detachNode() self.playerModel.reparentTo(render) angle = (self.playerModel.getH())*math.pi/180.0 ProjectileInterval(self.playerModel, startPos = Point3(self.playerModel.getPos()),startVel = Point3(math.sin(angle)*30,0,100), duration= 4.0).start() elif self.player1Weapon == "speedUp": self.speed1 = 6 taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff") elif self.player1Weapon == "blind": camera.setPos(Vec3(-50,0,0)) taskMgr.doMethodLater(5,self.restoreCamera,"restoreCamera") elif self.player1Weapon == "invincible": self.player1Invincible = 1 taskMgr.doMethodLater(5,self.notInvince1,"mortal1") elif self.player1Weapon == "grenade": self.jNP.getChildren().detach() gren = loader.loadModel("models/gamedev/grenade") gren.setScale(2.5) gren.reparentTo(render) angle = (self.playerModel.getH())*math.pi/180.0 ProjectileInterval(gren, startPos = Point3(self.playerModel.getPos()),startVel = Point3(math.sin(angle)*30,0,10), endZ = -50).start() if gren.getZ() == -50: gren.removeNode() cHandler = CollisionHandlerEvent() cHandler.addInPattern('%fn-into-%in') boundsB = gren.getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*0.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("grenade") cNodeB.addSolid(cSphereB) cNodePathB = gren.attachNewNode(cNodeB) self.cTrav.addCollider(cNodePathB,cHandler) self.acceptOnce("grenade-into-platform",self.explode) elif self.player1Weapon == "molotov": self.jNP.getChildren().detach() elif self.player1Weapon == "saw": self.jNP.getChildren().detach() elif self.player1Weapon == "invis": self.jNP.getChildren().detach() self.playerModel2.hide() taskMgr.doMethodLater(4.0,self.showPlayer,"showPlayer") elif self.player1Weapon == "icestage": self.jNP.getChildren().detach() self.speed1 = 6 self.speed2 = 6 self.background.detachNode() self.background2.reparentTo(render) taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff") def restoreSpeedBG(self,task): self.speed1 = 3 self.speed2 = 3 self.background2.detachNode() self.background.reparentTo(render) def showPlayer(self,task): self.playerModel.show() self.playerModel2.show() def useWeapon2(self): if self.player2Weapon == "meteo": fireRain = Sequence(Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain)) fireRain.start() elif self.player2Weapon == "jump": angle = self.playerModel2.getH()/90 ProjectileInterval(self.playerModel2, startPos = Point3(self.playerModel2.getPos()),startVel = Point3(angle*30,0,100), endZ = self.playerModel2.getZ()).start() elif self.player2Weapon == "speedUp": self.speed2 = 6 elif self.player2Weapon == "blind": camera.setPos(Vec3(-50,0,0)) taskMgr.doMethodLater(5,self.restoreCamera,"restoreCamera") elif self.player2Weapon == "invincible": self.player2Invincible = 1 taskMgr.doMethodLater(5,self.notInvince2,"mortal2") elif self.player2Weapon == "grenade": self.jNP2.getChildren().detach() gren = loader.loadModel("models/gamedev/grenade") gren.setScale(2.5) gren.reparentTo(render) angle = (self.playerModel2.getH())*math.pi/180.0 ProjectileInterval(gren, startPos = Point3(self.playerModel2.getPos()),startVel = Point3(math.sin(angle)*30,0,10), endZ = -50).start() if gren.getZ() == -50: gren.removeNode() cHandler = CollisionHandlerEvent() cHandler.addInPattern('%fn-into-%in') boundsB = gren.getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*0.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("grenade") cNodeB.addSolid(cSphereB) cNodePathB = gren.attachNewNode(cNodeB) self.cTrav.addCollider(cNodePathB,cHandler) self.acceptOnce("grenade-into-platform",self.explode) elif self.player2Weapon == "molotov": self.jNP.getChildren().detach() elif self.player2Weapon == "saw": self.jNP.getChildren().detach() elif self.player2Weapon == "invis": self.jNP.getChildren().detach() self.playerModel1.hide() taskMgr.doMethodLater(4.0,self.showPlayer,"showPlayer") elif self.player2Weapon == "icestage": self.jNP2.getChildren().detach() self.speed1 = 6 self.speed2 = 6 self.background.detachNode() self.background2.reparentTo(render) taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff") def rain(self): meteoBall = Actor("models/gamedev/fireball") meteoBall.reparentTo(render) meteoBall.setScale(2) meteoBall.setH(-15) boundsB = meteoBall.getChild(0).getBounds() centerB = boundsB.getCenter() radiusB = boundsB.getRadius()*0.65 cSphereB = CollisionSphere(centerB,radiusB) cNodeB = CollisionNode("meteor") cNodeB.addSolid(cSphereB) cNodePathB = meteoBall.attachNewNode(cNodeB) #cNodePathB.show() ProjectileInterval(meteoBall, startPos = Point3(random.randint(15,211),0,170),startVel = Point3(-12,0,0), endZ = -50).start() cHandler = CollisionHandlerEvent() cHandler.addInPattern('%fn-into-%in') self.cTrav.addCollider(cNodePathB,cHandler) self.accept("meteor-into-player1",self.player2Wins) self.accept("meteor-into-player2",self.player1Wins) def showBalls(self,task): for i in self.ball: i.show() def notInvince1(self,task): self.player1Invincible = 0 def notInvince2(self,task): self.player2Invincible = 0 def restoreCamera(self,task): camera.setPosHpr(Vec3(98,-390,90), Vec3(0,-5,0)) def switch(self,task): self.environment.setColor(0,1,0.3) def colliding1( self, collEntry ): # accept a collision entry argument if self.ignoreColl == 0: self.player1IsColliding = 1 # we are colliding self.stopWalk( ) # pause all walking animation and movement disp = ( collEntry.getSurfacePoint( render ) - collEntry.getInteriorPoint( render ) ) newPos = self.playerModel2.getPos( ) + disp # get new position self.playerModel2.setPos( newPos ) # and set it to tiny's position # end colliding def notColliding1( self, collEntry ): self.player1IsColliding = 0 def colliding2( self, collEntry ): # accept a collision entry argument if self.ignoreColl == 0: self.player2IsColliding = 1 # we are colliding self.stopWalk2( ) # pause all walking animation and movement disp = ( collEntry.getSurfacePoint( render ) - collEntry.getInteriorPoint( render ) ) newPos = self.playerModel2B.getPos( ) + disp # get new position self.playerModel2B.setPos( newPos ) # and set it to tiny's position # end colliding def notColliding2( self, collEntry ): self.player2IsColliding = 0 def returnSpeeds(self,task): self.speed1 = 8.0 self.speed2 = 8.0 self.turnSpeed1 = 80.0 self.turnSpeed2 = 80.0 def returnSpeeds2(self,task): self.acceptOnce("w",self.walk) self.acceptOnce("o",self.walk2) self.speed1 = 8.0 self.speed2 = 8.0 self.turnSpeed1 = 80.0 self.turnSpeed2 = 80.0 def returnSpeeds3(self,task): self.speed1 = 8.0 self.speed2 = 8.0 self.turnSpeed1 = 80.0 self.turnSpeed2 = 80.0 def changeMusic(self,task): self.music.stop() self.music2 = loader.loadMusic("models/gamedev/ADRENALINE.mp3") self.music2.play() def clockTask(self,task): self.timer.detachNode() self.timer = OnscreenText("%d" % (self.gameLen-globalClock.getRealTime(),), pos = (98,145), scale = 18.0) self.timer.setColor(1,1,1) self.timer.reparentTo(render) return Task.cont def ballMovementTask(self,task): self.anp.setY(0) self.anp2.setY(0) for i in range(self.ballNum+1): if i < len(self.ball): if self.ball[i].getX() > 234 or self.ball[i].getX() < -38 or self.ball[i].getZ() < -10 or self.ball[i].getZ() > 132: self.ball[i].setPos(self.ball[i].getPos()/1.005) z=random.randint(1,2) if z ==1: z=-1 else: z=1 self.movement[i]=Vec3(random.random()*z,0,random.random()*z) else: self.ball[i].setPos(self.ball[i].getPos()+self.movement[i]) return Task.cont def fire(self): self.fire = ParticleEffect() self.fire.reset() self.fire.setPos(0.000, 0.000, 0.000) self.fire.setHpr(0.000, 0.000, 0.000) self.fire.setScale(10.000, 10.000, 10.000) p0 = Particles('particles-1') # Particles parameters p0.setFactory("PointParticleFactory") p0.setRenderer("SpriteParticleRenderer") p0.setEmitter("DiscEmitter") p0.setPoolSize(1024) p0.setBirthRate(0.0200) p0.setLitterSize(10) p0.setLitterSpread(0) p0.setSystemLifespan(1200.0000) p0.setLocalVelocityFlag(1) p0.setSystemGrowsOlderFlag(0) # Factory parameters p0.factory.setLifespanBase(2.0000) p0.factory.setLifespanSpread(0.0000) p0.factory.setMassBase(1.0000) p0.factory.setMassSpread(0.0000) p0.factory.setTerminalVelocityBase(400.0000) p0.factory.setTerminalVelocitySpread(0.0000) # Point factory parameters # Renderer parameters p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAOUT) p0.renderer.setUserAlpha(0.22) # Sprite parameters p0.renderer.addTextureFromFile('models/gamedev/sparkle.png') p0.renderer.setColor(Vec4(1.00, 1.00, 1.00, 1.00)) p0.renderer.setXScaleFlag(1) p0.renderer.setYScaleFlag(1) p0.renderer.setAnimAngleFlag(0) p0.renderer.setInitialXScale(0.5000) p0.renderer.setFinalXScale(2.0000) p0.renderer.setInitialYScale(1.0000) p0.renderer.setFinalYScale(2.0000) p0.renderer.setNonanimatedTheta(0.0000) p0.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPNOBLEND) p0.renderer.setAlphaDisable(0) # Emitter parameters p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE) p0.emitter.setAmplitude(1.0000) p0.emitter.setAmplitudeSpread(0.0000) p0.emitter.setOffsetForce(Vec3(0.0000, 0.0000, 3.0000)) p0.emitter.setExplicitLaunchVector(Vec3(1.0000, 0.0000, 0.0000)) p0.emitter.setRadiateOrigin(Point3(0.0000, 0.0000, 0.0000)) # Disc parameters p0.emitter.setRadius(0.5000) self.fire.addParticles(p0) self.fire.setPos(self.playerModel2.getPos()) t = Sequence(Func(self.fire.start, render, render),Wait(20),Func(self.cleanFire)) t.start() def cleanFire(self): self.fire.cleanup() def explode(self,cEntry): self.explosion = ParticleEffect() self.explosion.reset() self.explosion.setPos(cEntry.getIntoNodePath().getParent().getPos()) self.explosion.setHpr(0.000, 0.000, 0.000) self.explosion.setScale(10.000, 10.000, 10.000) p0 = Particles('particles-1') # Particles parameters p0.setFactory("PointParticleFactory") p0.setRenderer("LineParticleRenderer") p0.setEmitter("SphereVolumeEmitter") p0.setPoolSize(10000) p0.setBirthRate(0.0500) p0.setLitterSize(10000) p0.setLitterSpread(0) p0.setSystemLifespan(2.0000) p0.setLocalVelocityFlag(1) p0.setSystemGrowsOlderFlag(1) # Factory parameters p0.factory.setLifespanBase(2.0000) p0.factory.setLifespanSpread(0.0000) p0.factory.setMassBase(.5000) p0.factory.setMassSpread(0.0500) p0.factory.setTerminalVelocityBase(400.0000) p0.factory.setTerminalVelocitySpread(0.0000) # Point factory parameters # Renderer parameters p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAOUT) p0.renderer.setUserAlpha(1.00) # Line parameters p0.renderer.setHeadColor(Vec4(1.00, 0.00, 0.00, 1.00)) p0.renderer.setTailColor(Vec4(1.00, 1.00, 0.00, 1.00)) p0.renderer.setLineScaleFactor(3.00) # Emitter parameters p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE) p0.emitter.setAmplitude(10.0000) p0.emitter.setAmplitudeSpread(0.0000) p0.emitter.setOffsetForce(Vec3(0.0000, 0.0000, -0.4930)) p0.emitter.setExplicitLaunchVector(Vec3(1.0000, 0.0000, 0.0000)) p0.emitter.setRadiateOrigin(Point3(0.0000, 0.0000, 0.0000)) # Sphere Volume parameters p0.emitter.setRadius(0.5000) self.explosion.addParticles(p0) f0 = ForceGroup('gravity') # Force parameters self.explosion.addForceGroup(f0) cHandler = CollisionHandlerEvent() cHandler.addInPattern('%fn-into-%in') cSphereB = CollisionSphere(cEntry.getIntoNodePath().getParent().getPos(),1) cNodeB = CollisionNode("explosion") cNodeB.addSolid(cSphereB) cNodePathB = self.explosion.attachNewNode(cNodeB) self.cTrav.addCollider(cNodePathB,cHandler) cNodePathB.show() self.accept("player1-into-explosion",self.player2Wins) self.accept("player2-into-explosion",self.player1Wins) #f.reparentTo(self.playerModel) #self.explosion.setPos(self.playerModel.getPos()) t = Sequence(Func(self.explosion.start, render, render),Wait(2),Func(self.cleanExplo)) t.start() cEntry.getFromNodePath().getParent().removeNode() def cleanExplo(self): self.explosion.cleanup() def endGame(self,task): taskMgr.removeTasksMatching('returnSpeedsToNormal') taskMgr.removeTasksMatching('restoreCamera') taskMgr.removeTasksMatching('clockTask') taskMgr.removeTasksMatching('ballMoveTask') self.music.stop() self.music3 = loader.loadMusic("models/gamedev/CSTAR.mp3") self.music3.play() self.speed1 = 0 self.speed2 = 0 def getScores(self): return (self.player1Score, self.player2Score) def getGameLen(self): return self.gameLen def stopMusic(self): self.music3.stop() def destroy(self): self.playerModel.detachNode() self.playerModel2.detachNode() self.background.destroy() self.lava.detachNode() self.ladder.detachNode() self.ladder2.detachNode() for i in range(self.ballNum+1): self.ball[i].detachNode() def stopMusic(self): self.music3.stop() #world = Lvl03() #world.start() #run()
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) #Background sound (does not play infinitely) self.backgroundSound = base.loader.loadSfx("sounds/DireDireDocks.mp3") taskMgr.add(self.update, "moveTask") #Disable the mouse so that we may use it for our control scheme. self.props = WindowProperties() self.props.setSize(1920, 1080) self.props.setFullscreen(True) self.props.setCursorHidden(True) base.win.requestProperties(self.props) base.disableMouse() self.buildKeyMap() self.inMenu = True self.menuScreen = OnscreenImage("titlescreen.png", (0, .01, 0)) self.menu() def initialize(self): self.timer = 0 base.enableParticles() #base.setFrameRateMeter(True) ########## # # SETUP COLLISION HANDLERS AND FLAMIE'S MODEL # ########## #Create the collision handlers in order to build the level. WALL_MASK = BitMask32.bit(2) FLOOR_MASK = BitMask32.bit(1) #Start up the collision system self.cTrav = CollisionTraverser() #Determine how collisions with walls will be handled self.wallHandler = CollisionHandlerPusher() self.bobbing = False #Setup flamie's model self.flamieNP = base.render.attachNewNode(ActorNode('flamieNP')) self.flamieNP.reparentTo(base.render) self.flamie = loader.loadModel('models/Flame/body') self.flamie.setScale(.5) self.flamie.setTransparency(TransparencyAttrib.MAlpha) self.flamie.setAlphaScale(0) self.flamie.reparentTo(self.flamieNP) self.flamie.setCollideMask(BitMask32.allOff()) flameLight = DirectionalLight("flameLight") fl = self.flamie.attachNewNode(flameLight) fl.setColor(255, 255, 255, 1) flameLight.setDirection((-5, -5, -5)) self.flamie.setLight(fl) self.flamie2 = loader.loadModel("models/p.obj") self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f7.png")) self.flamie2.reparentTo(self.flamieNP) self.flamie2.setScale(4) self.flamie2OriZ = 2 self.flamie2.setPos(-6.5, 0, self.flamie2OriZ) #(length, depth, height) self.flamie2.setLight(fl) self.flamie2.setTransparency(TransparencyAttrib.MAlpha) self.flamieFire = PointLight('fire') self.flamieFire.setColor(VBase4(1,1,1,1)) self.flamieFire.setAttenuation((1,0,1)) plnp = render.attachNewNode(self.flamieFire) plnp.setPos(self.flamieNP.getPos()) self.flamielight = AmbientLight('light') self.flamielight.setColor(VBase4(1, 0.5, 0.6, 1)) self.flamielight = self.flamie2.attachNewNode(self.flamielight) self.flamie2.setLight(self.flamielight) self.flamie2.setLight(plnp) self.mayFlamieBob = True #self.flamie2.setAlphaScale(0.5) '''self.tree = loader.loadModel("models/p2.obj") self.tree.setTexture(loader.loadTexture("deadTree.png")) self.tree.reparentTo(render) self.tree.setScale(4) self.tree.setPos(25,25,0) #(length, depth, height) self.tree.setLight(fl) self.tree.setTransparency(TransparencyAttrib.MAlpha) self.treelight = AmbientLight('light') self.treelight.setColor(VBase4(0.9, 0.9, 0.6, 1)) self.treelight = self.tree.attachNewNode(self.treelight) self.tree.setLight(self.treelight)''' x = 150 y = 20 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(7)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 4 y = 90 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(6)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 3 y = 120 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(4)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) x = 200 y = 20 offset1 = 0 treeList2 = [loader.loadModel("models/p2.obj") for i in range(4)] for j in treeList2: k = random.randint(1, 100) if k%5 is 1 or k%5 is 2: j.setTexture(loader.loadTexture("deadTree.png")) else: j.setTexture(loader.loadTexture("tree.png")) j.reparentTo(render) j.setScale(random.randint(4,7)) j.setTransparency(TransparencyAttrib.MAlpha) j.setPos(x + 3*offset1, y + 4*offset1, 0) treelight = AmbientLight('light') treelight = j.attachNewNode(treelight) j.setLight(treelight) offset1 = offset1 + random.randint(4, 10) ### Something that should look like water ### w = loader.loadModel("models/flatP.obj") w.setTexture(loader.loadTexture("ice.png")) w.reparentTo(render) w.setScale(75) w.setTransparency(TransparencyAttrib.MAlpha) w.setAlphaScale(.7) w.setLight(treelight) w.setPos(-200, 0, -10) self.waterOrigiZ = -10 self.waterSecZ = -95 self.waterThirdZ = -120 self.water = w ### Reskying the sky ### w = loader.loadModel("models/biggerFlatP.obj") w.setTexture(loader.loadTexture("models/n2.jpg")) w.reparentTo(self.flamie2) w.setScale(15) w.setLight(treelight) w.setPos(-200, 450, -200) #(length, depth, height) #Give flamie gravity self.floorHandler = CollisionHandlerGravity() self.floorHandler.setGravity(9.81+100) self.floorHandler.setMaxVelocity(100) ########## # # GENERATING LEVEL PARTS # ########## self.ice_reset = () self.start = PlatformSeg(LVector3(0,0,0)) self.start.generateAllParts(render) self.checkpointCreator(70, 90, self.start.pos.z, 10) self.floater = False for p in self.start.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.lostWood = LostWood(LVector3(self.start.pos.x + 750, self.start.parts[0].pos.y + self.start.parts[0].wid, self.start.pos.z)) self.lostWood.generateAllParts(render) self.checkpointCreator(self.lostWood.pos.x+120, self.lostWood.pos.y+150, self.lostWood.pos.z,20) self.checkpointCreator(self.lostWood.parts[6].pos.x + self.lostWood.parts[6].len/2, self.lostWood.parts[6].pos.y + self.lostWood.parts[6].wid/2, self.lostWood.pos.z, 40) for p in self.lostWood.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.cave = Cave(LVector3(self.lostWood.pos.x + 1100, self.lostWood.pos.y + 2000, self.lostWood.pos.z - 50)) self.cave.generateAllParts(render) self.checkpointCreator(self.cave.thirdRoomParts[5].pos.x + self.cave.thirdRoomParts[5].len/2, self.cave.thirdRoomParts[5].pos.y + self.cave.thirdRoomParts[5].wid/2, self.cave.thirdRoomParts[5].pos.z, 30) for p in self.cave.parts: if isinstance(p, Prism): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, p.dep, 'terraincollision', 'wallcollision') if isinstance(p, Square): self.collisionBoxCreator(p.pos.x, p.pos.y, p.pos.z, p.len, p.wid, 3, 'terraincollision', 'wallcollision') if isinstance(p, IceCube): p.model.setCollideMask(BitMask32.allOff()) self.ice_reset += (p,) iceCubefloor= p.model.find("**/iceFloor") iceCubewall = p.model.find("**/iceWall") iceCubefloor.node().setIntoCollideMask(FLOOR_MASK) iceCubewall.node().setIntoCollideMask(WALL_MASK) self.end = End(LVector3(self.cave.thirdRoomParts[8].pos.x - 200, self.cave.thirdRoomParts[8].pos.y + self.cave.thirdRoomParts[8].wid, self.cave.thirdRoomParts[8].pos.z)) self.end.generate(render) self.collisionBoxCreator(self.end.floor.pos.x, self.end.floor.pos.y, self.end.floor.pos.z, self.end.floor.len, self.end.floor.wid, self.end.floor.dep, 'terraincollision', 'wallcollision') ######### # DRAWING THE CABIN AND FINAL CAMPFIRE ######### self.checkpointCreator(self.end.floor.pos.x + self.end.floor.len/2, self.end.floor.pos.y + self.end.floor.wid/2, self.end.floor.pos.z, 30) self.cabin = loader.loadModel("models/p2.obj") self.cabin.setTexture(loader.loadTexture("models/cabin.png")) self.cabin.setScale(50) self.cabin.reparentTo(render) self.cabin.setPos(self.end.floor.pos.x + self.end.floor.len/2, self.end.floor.pos.y + self.end.floor.wid/1.1, self.end.floor.pos.z) self.cabin.setTransparency(TransparencyAttrib.MAlpha) #Manually creating starting position. Copy and paste the first three parameters of the checkpoint you want to start at. self.startPos = LVector3(70, 90, self.start.pos.z) self.flamieNP.setPos(self.startPos) '''#Testing the tree model self.tree = loader.loadModel('models/Tree/log') self.tree.reparentTo(render) self.tree.setPos(-50,0,100) self.tree.setScale(2)''' '''#Add sky background self.sky = loader.loadModel('models/sphere.obj') self.sky.reparentTo(self.camera) self.sky.set_two_sided(True) self.skyTexture = loader.loadTexture("models/n2.jpg") self.sky.setTexture(self.skyTexture) self.sky.set_bin('background', 0) self.sky.set_depth_write(False) self.sky.set_compass()''' ########## # # CREATE FLAMIE'S COLLISION GEOMETRY # ########## #Give flamie a collision sphere in order to collide with walls flamieCollider = self.flamie.attachNewNode(CollisionNode('flamiecnode')) flamieCollider.node().addSolid(CollisionSphere(0,0,0,5)) flamieCollider.node().setFromCollideMask(WALL_MASK) flamieCollider.node().setIntoCollideMask(BitMask32.allOff()) self.wallHandler.addCollider(flamieCollider, self.flamieNP) self.cTrav.addCollider(flamieCollider, self.wallHandler) #Give flamie a collision ray to collide with the floor flamieRay = self.flamie.attachNewNode(CollisionNode('flamieRay')) flamieRay.node().addSolid(CollisionRay(0,0,8,0,0,-1)) flamieRay.node().setFromCollideMask(FLOOR_MASK) flamieRay.node().setIntoCollideMask(BitMask32.allOff()) self.floorHandler.addCollider(flamieRay, self.flamieNP) self.cTrav.addCollider(flamieRay, self.floorHandler) #Add a sensor that lets us melt ice cubes without standing on the cube. meltSensor = self.flamie.attachNewNode(CollisionNode('meltSensor')) cs = CollisionSphere(-2,0,10, 50) meltSensor.node().addSolid(cs) meltSensor.node().setFromCollideMask(WALL_MASK) meltSensor.node().setIntoCollideMask(BitMask32.allOff()) cs.setTangible(0) self.wallHandler.addCollider(meltSensor, self.flamieNP) self.cTrav.addCollider(meltSensor, self.wallHandler) self.wallHandler.addInPattern('%fn-into-%in') self.wallHandler.addAgainPattern('%fn-again-%in') self.accept('meltSensor-into-iceWall', self.melt) self.accept('meltSensor-again-iceWall', self.melt) self.accept('meltSensor-into-checkpointCol', self.newstart) #Add in an event handle to prevent the jumping glitch found on the bobbing ice cubes. self.floorHandler.addInPattern('%fn-into-%in') self.floorHandler.addAgainPattern('%fn-again-%in') self.floorHandler.addOutPattern('%fn-out-%in') self.accept('flamieRay-into-iceFloor', self.jittercancel) self.accept('flamieRay-again-iceFloor', self.jittercancel) self.accept('flamieRay-out-iceFloor', self.jittercanceloff) #Uncomment these lines to see flamie's collision geometry #flamieCollider.show() #flamieRay.show() #meltSensor.show() #Uncomment this line to see the actual collisions. #self.cTrav.showCollisions(render) #This plane is found at the very bottom of the level and adds global gravity. killfloor = CollisionPlane(Plane(Vec3(0,0,1), Point3(0,0,-1000))) killfloorCol = CollisionNode('kfcollision') killfloorCol.addSolid(killfloor) killfloorCol.setIntoCollideMask(BitMask32.bit(1)) killfloorColNp = self.render.attachNewNode(killfloorCol) #################### # # Setting light so that we could see the definition in the walls # #################### render.setShaderAuto() self.dlight = DirectionalLight('dlight') self.dlight.setColor(LVector4(0.3, 0.1, 0.7, 1)) dlnp = render.attachNewNode(self.dlight) dlnp.setHpr(90, 20, 0) render.setLight(dlnp) self.alight = render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(LVector4(0.5, 0.5, 1, .1)) render.setLight(self.alight) self.snow = loader.loadTexture("models/ground.jpg") #Create a floater object and have it float 2 units above fireball. #And use this as a target for the camera to focus on. #This idea is taken from the roaming ralph sample that came with the #Panda3D SDK. self.camFocus = NodePath(PandaNode("floater")) self.camFocus.reparentTo(render) self.camFocusCurrZ = self.flamie.getZ() + 10 #The camera is locked to the avatar so it always follows regardless of movement. self.camera.reparentTo(render) self.cameraTargetHeight = 8.0 self.cameraDistance = 100 self.cameraHeightModes = (self.start.parts[0].pos.z + 45, self.start.parts[0].pos.z + 125, self.camFocus.getZ() + 10, self.camFocus.getZ() + 150, self.end.floor.pos.z + 10) self.cameraHeight = self.cameraHeightModes[0] ################# # Changes Camera orientation depending on where the player is in the stage to compensate for the fact that # the player has no direct control of the camera. # Checks using the arrays from the level parts. ################## def cameraModes(self, delta): #Is the fireball within the platforming section between the starting area and the lost woods? #Is the fireball near the simple platforming sections of the LostWoods? #Is the fireball near the drop off point into the cave? #Is the fireball near the entrance to the second room in the cave? #If yes to any of these, bring the camera up to give a bird's eye view of the platforming if ((self.flamieNP.getX() > self.start.parts[1].pos.x and self.flamieNP.getY() > self.start.parts[1].pos.y - self.start.parts[1].wid and self.flamieNP.getX() < self.lostWood.parts[0].pos.x) or (self.flamieNP.getX() > self.lostWood.parts[0].pos.x + self.lostWood.parts[0].len/1.1 and self.flamieNP.getX() < self.lostWood.parts[2].pos.x + self.lostWood.parts[0].len/11 and self.flamieNP.getY() < self.lostWood.parts[0].pos.y + self.lostWood.parts[0].wid) or (self.flamieNP.getY() > self.cave.parts[0].pos.y - 20 and self.flamieNP.getY() <= self.cave.parts[0].pos.y + self.cave.parts[0].wid/2) or (self.flamieNP.getX() < self.cave.parts[1].pos.x + self.cave.parts[1].wid/10 and self.flamieNP.getY() >= self.cave.parts[1].pos.x)): camMode = 1 #Is the fireball in the beginning of the cave area? #If yes, bring the camera closer elif self.flamieNP.getY() > self.cave.parts[1].pos.y - self.cave.parts[0].wid/2 and self.flamieNP.getY() < self.cave.thirdRoomParts[5].pos.y: camMode = 2 else: camMode = 0 if self.flamieNP.getY() >= self.cave.thirdRoomParts[6].pos.y: self.cave.thirdRoomParts[0].hide() camMode = 3 if self.flamieNP.getY() >= self.cave.thirdRoomParts[8].pos.y + self.cave.thirdRoomParts[8].wid/1.5: camMode = 4 self.lerpCam(camMode, delta) def lerpCam(self, camMode, delta): CAMLERPSPEED = 25 if camMode == 0: if not self.cameraHeight == self.cameraHeightModes[camMode]: if self.cameraHeight - CAMLERPSPEED * delta <= self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeightModes[camMode] else: self.cameraHeight = self.cameraHeight - CAMLERPSPEED * delta elif camMode == 1: if not self.cameraHeight == self.cameraHeightModes[camMode]: if self.cameraHeight - CAMLERPSPEED * delta >= self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeightModes[camMode] else: if self.cameraHeight < self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeight + CAMLERPSPEED * delta else: self.cameraHeight = self.cameraHeight - CAMLERPSPEED * delta elif camMode == 2: if not self.cameraHeight == self.cameraHeightModes[camMode]: if self.cameraHeight - CAMLERPSPEED * delta <= self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeightModes[camMode] self.camFocusCurrZ = self.flamieNP.getZ() + 10 else: self.cameraHeight = self.cameraHeight - CAMLERPSPEED * delta self.camFocusCurrZ = self.flamieNP.getZ() + 10 elif camMode == 3: if not self.cameraHeight == self.cameraHeightModes[camMode]: if self.cameraHeight + CAMLERPSPEED * 3 * delta >= self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeightModes[camMode] else: self.cameraHeight = self.cameraHeight + CAMLERPSPEED * 3 * delta elif camMode == 4: if not self.cameraHeight == self.cameraHeightModes[camMode]: if self.cameraHeight - CAMLERPSPEED * 3 * delta <= self.cameraHeightModes[camMode]: self.cameraHeight = self.cameraHeightModes[camMode] else: self.cameraHeight = self.cameraHeight - CAMLERPSPEED * 3 * delta def waterControl(self, delta): WATERLERPSPEED = .75 if self.flamieNP.getY() <= self.lostWood.parts[6].pos.y + self.lostWood.parts[6].wid/2: if not self.water.getZ() == self.waterOrigiZ: if self.water.getZ() - WATERLERPSPEED * delta < self.waterOrigiZ and self.water.getZ() > self.waterOrigiZ: self.water.setZ(self.waterOrigiZ) elif self.water.getZ() + WATERLERPSPEED * delta > self.waterOrigiZ and self.water.getZ() < self.waterOrigiZ: self.water.setZ(self.waterOrigiZ) else: if self.water.getZ() > self.waterOrigiZ: self.water.setZ(self.water, - WATERLERPSPEED * delta) if self.water.getZ() < self.waterOrigiZ: self.water.setZ(self.waterOrigiZ) else: self.water.setZ(self.water, + WATERLERPSPEED * delta) if self.water.getZ() > self.waterOrigiZ: self.water.setZ(self.waterOrigiZ) elif self.flamieNP.getY() <= self.cave.parts[1].pos.y: if not self.water.getZ() == self.waterSecZ: if self.water.getZ() - WATERLERPSPEED * delta < self.waterSecZ: self.water.setZ(self.waterSecZ) else: self.water.setZ(self.water, - WATERLERPSPEED * delta) else: if not self.water.getZ() == self.waterThirdZ: if self.water.getZ() - WATERLERPSPEED * delta < self.waterThirdZ: self.water.setZ(self.waterThirdZ) else: self.water.setZ(self.water, - WATERLERPSPEED * delta) def reset(self): self.flamieNP.setPos(self.startPos) self.camFocusCurrZ = self.flamieNP.getZ() + 10 for p in self.ice_reset: p.model.setScale(p.original_scale) def jump(self, dt): if self.bobbing: if self.floorHandler.getAirborneHeight() < 0.15: self.floorHandler.addVelocity(60) elif self.floorHandler.isOnGround(): self.floorHandler.addVelocity(60) def jittercancel(self, collEntry): model = collEntry.getIntoNodePath().getParent() modelRef = model.getPythonTag("iceRef") if model.getScale()[0] > 1.2: model.setScale(model.getScale()- modelRef.meltspeed) self.bobbing = True def jittercanceloff(self, collEntry): self.bobbing = False def melt(self, collEntry): model = collEntry.getIntoNodePath().getParent() modelRef = model.getPythonTag("iceRef") if model.getScale()[0] > 1.2 and self.bobbing != True: model.setScale(model.getScale()- modelRef.meltspeed) def newstart(self, collEntry): entry = collEntry.getInto().getCenter() self.startPos = (entry[0]+10, entry[1]+10, entry[2] +10) cp = loader.loadModel('models/Campfire/fire') cp.setPos(entry[0],entry[1], entry[2]) cp.reparentTo(render) def buildKeyMap(self): self.keyMap = {"left": 0, "right": 0, "forward": 0, "back": 0, "down": 0, "up": 0, "lookUp": 0, "lookDown": 0, "lookLeft": 0, "lookRight": 0} #I changed the control scheme let me know if you would like me to try something else. #WASD for movement, space for jump self.accept("escape", sys.exit) self.accept("a", self.setKey, ["left", True]) self.accept("a-up", self.setKey, ["left", False]) self.accept("d", self.setKey, ["right", True]) self.accept("d-up", self.setKey, ["right", False]) self.accept("w", self.setKey, ["forward", True]) self.accept("w-up", self.setKey, ["forward", False]) self.accept("s", self.setKey, ["back", True]) self.accept("s-up", self.setKey, ["back", False]) self.accept("space", self.setKey, ["down", True]) self.accept("space-up", self.setKey, ["down", False]) self.accept("shift", self.setKey, ["up", True]) self.accept("shift-up", self.setKey, ["up", False]) def setKey(self, key, value): self.keyMap[key] = value def update(self, task): delta = globalClock.getDt() if not self.inMenu: SPEED = 125 #Variable that holds what direction the player is inputting fblr = 0 self.timer += delta * 25 self.killPlane = self.water.getZ() - 25 if self.flamieNP.getZ() < self.killPlane: self.reset() if self.keyMap["left"]: fblr = 1 old_fblr = fblr self.flamieNP.setX(self.flamie, - SPEED * delta) if self.keyMap["right"]: fblr = 2 old_fblr = fblr self.flamieNP.setX(self.flamie, + SPEED * delta) if self.keyMap["forward"]: fblr = 3 old_fblr = fblr self.flamieNP.setY(self.flamie, + SPEED * delta) if self.keyMap["back"]: fblr = 4 old_fblr = fblr self.flamieNP.setY(self.flamie, - SPEED * delta) if self.keyMap["up"]: #self.flamieNP.setZ(self.flamie, - SPEED * dt) self.reset() #self.cameraDistance = 20+self.cameraDistance if self.keyMap["down"] and self.timer > 1: #self.flamieNP.setZ(self.flamie, + SPEED * dt) self.timer = 0 self.jump(delta) if fblr == 1: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f8.png")) elif fblr == 2: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f6.png")) elif fblr == 3: if old_fblr == 1: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f1.png")) elif old_fblr == 2: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f4.png")) else: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f3.png")) else: self.flamie2.setTexture(loader.loadTexture("models/flamie2D/f7.png")) if self.floorHandler.isOnGround: self.flamieBob(delta) #The camera control is borrowed from Kristina's Tech Demo #This is also a demo found at: http://www.panda3d.org/forums/viewtopic.php?t=8452 '''# mouse-controlled camera begins # Use mouse input to turn both the Character and the Camera if base.mouseWatcherNode.hasMouse(): md = base.win.getPointer(0) x = md.getX() y = md.getY() deltaX = md.getX() - 200 deltaY = md.getY() - 200 # reset mouse cursor position base.win.movePointer(0, 200, 200) # alter flamie's yaw by an amount proportionate to deltaX self.flamie.setH(self.flamie.getH() - 0.3* deltaX) # find the new camera pitch and clamp it to a reasonable range self.cameraPitch = self.cameraPitch + 0.1 * deltaY if (self.cameraPitch < -60): self.cameraPitch = -60 if (self.cameraPitch > 80): self.cameraPitch = 80 base.camera.setHpr(0,self.cameraPitch,0) # set the camera at around ralph's middle # We should pivot around here instead of the view target which is noticebly higher base.camera.setPos(0,0,self.cameraTargetHeight/2) # back the camera out to its proper distance base.camera.setY(base.camera,self.cameraDistance) # point the camera at the view target viewTarget = Point3(0,0,self.cameraTargetHeight) base.camera.lookAt(viewTarget) # reposition the end of the camera's obstruction ray trace #self.cameraRay.setPointB(base.camera.getPos()) # mouse-controlled camera ends''' self.waterControl(delta) self.water.setX(self.flamieNP.getX() - 250) self.water.setY(self.flamieNP.getY() - 250) self.cameraModes(delta) base.camera.setPos(self.flamieNP.getX(), self.flamieNP.getY() - self.cameraDistance, self.cameraHeight) self.camFocus.setPos(self.flamieNP.getX(), self.flamieNP.getY(), self.camFocusCurrZ) base.camera.lookAt(self.camFocus) ''' ###################### # # SIMPLE OCCLUSION FOR START AREA # ###################### for p in self.start.parts: if p.type == 'IceCube': if math.fabs((math.sqrt((p.model.getX() * p.model.getX()) + (p.model.getY() * p.model.getY())) - math.sqrt((self.camFocus.getX() * self.camFocus.getX()) + (self.camFocus.getY() * self.camFocus.getY())))) <= 400: p.show() #Ice cube movement p.bob(delta) else: p.hide() if p.type == 'Prism': if p.type == 'Prism': if math.fabs((math.sqrt((p.pos.x * p.pos.x) + (p.pos.y * p.pos.y)) - math.sqrt((self.camFocus.getX() * self.camFocus.getX()) + (self.camFocus.getY() * self.camFocus.getY())))) <= 1000: p.show() else: p.hide() ###################### # # SIMPLE OCCLUSION FOR CAVE PARTS # ###################### for p in self.cave.parts: if p.type == 'Prism': if math.fabs((math.sqrt((p.pos.x * p.pos.x) + (p.pos.y * p.pos.y)) - math.sqrt((self.flamieNP.getX() * self.flamieNP.getX()) + (self.flamieNP.getY() * self.flamieNP.getY())))) <= 2500: p.show() else: p.hide() if p.type == 'IceCube': if math.fabs((math.sqrt((p.model.getX() * p.model.getX()) + (p.model.getY() * p.model.getY())) - math.sqrt((self.flamieNP.getX() * self.flamieNP.getX()) + (self.flamieNP.getY() * self.flamieNP.getY())))) <= 2000: p.show() #Ice cube movement self.cave.moveIceCubes(delta/25) for p in self.cave.iceCubesThirdRoom: p.bob(delta/25) for p in self.cave.iceCubesSecondRoom: p.bob(delta/25) self.cave.bigCube.bob(delta/25) for p in self.start.iceCubes: p.bob(delta) else: p.hide() ''' #Ice cube movement self.cave.moveIceCubes(delta) for p in self.cave.iceCubesThirdRoom: p.bob(delta) for p in self.cave.iceCubesSecondRoom: p.bob(delta) self.cave.bigCube.bob(delta) for p in self.start.iceCubes: p.bob(delta) elif self.inMenu: self.menu() if self.backgroundSound.status() is not self.backgroundSound.PLAYING: self.backgroundSound.play() return task.cont def menu(self): if self.keyMap["down"]: self.inMenu = False self.menuScreen.destroy() self.initialize() def flamieBob(self, delta): if self.mayFlamieBob: self.flamie2.setZ(self.flamie2.getZ() + .5*delta) if self.flamie2.getZ() - self.flamie2OriZ > 1: self.mayFlamieBob = False else: self.flamie2.setZ(self.flamie2.getZ() - .5*delta) if self.flamie2.getZ() - self.flamie2OriZ < -2: self.mayFlamieBob = True #Function to create a box collision using six polygon. The top face is created as terrain and thus provides gravity. #While the rest of the faces only act as wall pushers. def collisionBoxCreator(self, posx, posy, posz, length, width, height, floorname, wallname): ret = () #Create top face terrain = CollisionPolygon(Point3(posx, posy+width, posz), Point3(posx, posy, posz), Point3(posx+length, posy, posz), Point3(posx+length, posy+width, posz)) terrainCol = CollisionNode(floorname) terrainCol.addSolid(terrain) terrainCol.setIntoCollideMask(BitMask32.bit(1)) terrainColNp = self.render.attachNewNode(terrainCol) self.cTrav.addCollider(terrainColNp, self.floorHandler) ret += (terrainColNp,) #Create left face sideLeft = CollisionPolygon(Point3(posx, posy+width, posz-height), Point3(posx, posy, posz-height), Point3(posx, posy, posz), Point3(posx, posy+width, posz)) sideLeftCol = CollisionNode(wallname) sideLeftCol.addSolid(sideLeft) sideLeftCol.setIntoCollideMask(BitMask32.bit(2)) sideLeftColNp = self.render.attachNewNode(sideLeftCol) self.cTrav.addCollider(sideLeftColNp, self.wallHandler) ret += (sideLeftColNp,) #Create right face sideRight = CollisionPolygon(Point3(posx+length, posy+width, posz), Point3(posx+length, posy, posz), Point3(posx+length, posy, posz-height), Point3(posx+length, posy+width, posz-height)) sideRightCol = CollisionNode(wallname) sideRightCol.addSolid(sideRight) sideRightCol.setIntoCollideMask(BitMask32.bit(2)) sideRightColNp = self.render.attachNewNode(sideRightCol) self.cTrav.addCollider(sideRightColNp, self.wallHandler) ret += (sideRightColNp,) #Create front face sideFront = CollisionPolygon(Point3(posx, posy+width, posz-height), Point3(posx, posy+width, posz), Point3(posx+length, posy+width, posz), Point3(posx+length, posy+width, posz-height)) sideFrontCol = CollisionNode(wallname) sideFrontCol.addSolid(sideFront) sideFrontCol.setIntoCollideMask(BitMask32.bit(2)) sideFrontColNp = self.render.attachNewNode(sideFrontCol) self.cTrav.addCollider(sideFrontColNp, self.wallHandler) ret += (sideFrontColNp,) #Create back face sideBack = CollisionPolygon(Point3(posx, posy, posz), Point3(posx, posy, posz-height), Point3(posx+length, posy, posz-height), Point3(posx+length, posy, posz)) sideBackCol = CollisionNode(wallname) sideBackCol.addSolid(sideBack) sideBackCol.setIntoCollideMask(BitMask32.bit(2)) sideBackColNp = self.render.attachNewNode(sideBackCol) self.cTrav.addCollider(sideBackColNp, self.wallHandler) ret += (sideBackColNp,) #Create bottom face sideBot = CollisionPolygon(Point3(posx, posy, posz-height), Point3(posx, posy+width, posz-height), Point3(posx+length, posy+width, posz-height), Point3(posx+length, posy, posz-height)) sideBotCol = CollisionNode(wallname) sideBotCol.addSolid(sideBot) sideBotCol.setIntoCollideMask(BitMask32.bit(2)) sideBotColNp = self.render.attachNewNode(sideBotCol) self.cTrav.addCollider(sideBotColNp, self.wallHandler) ret += (sideBotColNp,) #Uncomment these lines to see the collision polygons. '''terrainColNp.show() sideLeftColNp.show() sideRightColNp.show() sideFrontColNp.show() sideBackColNp.show() sideBotColNp.show()''' return ret #Old way of creating box collisions (left here for reference) '''box = CollisionBox((posx+(length/2), posy+(width/2),-(posz+height/2)), length/2, width/2, height/2) boxCol = CollisionNode('testcollision') boxCol.addSolid(box) boxCol.setIntoCollideMask(BitMask32.bit(2)) boxColNp = self.render.attachNewNode(boxCol) boxHandler = CollisionHandlerQueue() self.cTrav.addCollider(boxColNp, self.wallHandler) #Uncomment this line to see the collision solids. #boxColNp.show()''' def checkpointCreator(self, posx, posy, posz, radius): cp = loader.loadModel('models/Campfire/logs') cp.setPos(posx,posy, posz) cp.reparentTo(render) checkpoint = CollisionSphere(cp.getX(),cp.getY(),cp.getZ(),radius) checkpoint.setTangible(0) checkpointCol = CollisionNode('checkpointCol') checkpointCol.addSolid(checkpoint) checkpointCol.setIntoCollideMask(BitMask32.bit(2)) checkpointColNp = self.render.attachNewNode(checkpointCol) self.cTrav.addCollider(checkpointColNp, self.wallHandler)
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 Login(ShowBase): def __init__(self, World): self.appRunner = None self.World = World self.taskMgr = World.taskMgr self.createLoginWindow() self.hasClickedRegister = False def createLoginWindow(self): self.myImage = OnscreenImage(image='IMAGES/login.png', pos=(0, 0, 0), scale=(2, 1, 1)) self.enter_btn = DirectButton(image='IMAGES/enter.png', pos=(-1.4, 0, -.5), scale=(.15, 1, .04), command=self.auth, relief=None) self.register_btn = DirectButton(image='IMAGES/register.png', pos=(-1, 0, -.5), command=self.clickedRegister, scale=(.15, 1, .04), relief=None) self.userTextbox = DirectEntry(text="" , scale=.05, pos=(-1.4, 0, 0.1), command=self.setUserText, initialText="", numLines=1, focus=1, focusInCommand=doPass, focusOutCommand=self.getUserText) self.passTextbox = DirectEntry(text="" , scale=.05, pos=(-1.4, 0, -.2), command=self.setPassText, initialText="", numLines=1, focus=0, focusInCommand=doPass, obscured=1, focusOutCommand=self.getPassText) self.enter_btn['state'] = DGG.NORMAL self.ignore('tab') self.ignore('enter') self.accept('tab', self.cycleLoginBox) self.accept('enter', self.auth) self.status = OnscreenText(text="", pos=(-0.5, -0.7, 0), scale=0.075, fg=(1, 1, 0, 1), align=TextNode.ACenter) def createRegisterWindow(self): self.myImage = OnscreenImage(image='IMAGES/register_w.png', pos=(0, 0, 0), scale=(2, 1, 1)) self.cancel_btn = DirectButton(image='IMAGES/cancel.png', pos=(-1, 0, -.5), command=self.clickedRegCancel, scale=(.15, 1, .04), relief=None) self.register_btn = DirectButton(image='IMAGES/register.png', pos=(-1.4, 0, -.5), command=self.reg, scale=(.15, 1, .04), relief=None) self.regInputUser = DirectEntry(text="" , scale=.05, pos=(-1.4, 0, 0.1), command=self.setUserText, initialText="", numLines=1, focus=1, focusInCommand=doPass, focusOutCommand=self.getRegUserText) self.regInputPass = DirectEntry(text="" , scale=.05, pos=(-1.4, 0, -0.1), command=self.setPassText, initialText="", numLines=1, focus=0, focusInCommand=doPass, obscured=1, focusOutCommand=self.getRegPassText) self.regInputCPass = DirectEntry(text="" , scale=.05, pos=(-1.4, 0, -.3), command=self.setPassText, initialText="", numLines=1, focus=0, focusInCommand=doPass, obscured=1, focusOutCommand=self.testRegPassText) self.hasClickedRegister = True self.ignore('tab') self.ignore('enter') self.accept('tab', self.cycleRegisterBox) self.accept('enter', self.reg) self.status = OnscreenText(text=self.status['text'], pos=(-0.5, -0.7, 0), scale=0.075, fg=(1, 1, 0, 1), align=TextNode.ACenter) def setUserText(self, textEntered): print "username: "******"password: "******""): if(self.passwordInput == ""): self.setStatusText("ERROR: You must enter a username and password before logging in.") else: self.setStatusText("ERROR: You must specify a username") self.passTextbox['focus'] = 0 self.userTextbox['focus'] = 1 elif(self.passwordInput == ""): self.setStatusText("ERROR: You must enter a password") self.userTextbox['focus'] = 0 self.passTextbox['focus'] = 1 else: self.setStatusText("Attempting to log in...") self.enter_btn['state'] = DGG.DISABLED self.register_btn['state'] = DGG.DISABLED self.World.username = self.usernameInput self.World.authConnection.sendLoginRequest(self.usernameInput, self.passwordInput) def reg(self): if(self.getRegUserText() == ""): if(self.getRegPassText() == ""): self.setStatusText("ERROR: You must enter a username and password before logging in.") else: self.setStatusText("ERROR: You must specify a username") self.regInputPass['focus'] = 0 self.regInputCPass['focus'] = 0 self.regInputUser['focus'] = 1 elif(self.getRegPassText() == ""): self.setStatusText("ERROR: You must enter a password") self.regInputUser['focus'] = 0 self.regInputCPass['focus'] = 0 self.regInputPass['focus'] = 1 elif(not self.testRegPassText()): self.setStatusText("ERROR: Your passwords must match") self.regInputPass.enterText("") self.regInputCPass.enterText("") self.regInputUser['focus'] = 0 self.regInputCPass['focus'] = 0 self.regInputPass['focus'] = 1 else: self.setStatusText("Attempting to sign up...") self.cancel_btn['state'] = DGG.DISABLED self.register_btn['state'] = DGG.DISABLED self.World.username = self.getRegUserText() self.World.authConnection.sendRegisterRequest(self.getRegUserText(), self.getRegPassText()) def cycleLoginBox(self): # function is triggered by the tab key so you can cycle between # the two input fields like on most login screens # IMPORTANT: When you change the focus to one of the text boxes, # you have to unset the focus on the other textbox. If you do not # do this Panda seems to get confused. if(self.passTextbox['focus'] == 1): self.passTextbox['focus'] = 0 self.userTextbox['focus'] = 1 elif(self.userTextbox['focus'] == 1): self.userTextbox['focus'] = 0 self.passTextbox['focus'] = 1 def cycleRegisterBox(self): if(self.regInputUser['focus'] == 1): self.regInputUser['focus'] = 0 self.regInputCPass['focus'] = 0 self.regInputPass['focus'] = 1 elif(self.regInputPass['focus'] == 1): self.regInputUser['focus'] = 0 self.regInputPass['focus'] = 0 self.regInputCPass['focus'] = 1 elif(self.regInputCPass['focus'] == 1): self.regInputPass['focus'] = 0 self.regInputCPass['focus'] = 0 self.regInputUser['focus'] = 1 def clickedCancel(self): exit() def clickedRegister(self): self.destroyLoginWindow() self.createRegisterWindow() def clickedRegCancel(self): self.destroyRegisterWindow() self.createLoginWindow() def destroyLoginWindow(self): self.userTextbox.destroy() self.passTextbox.destroy() self.enter_btn.destroy() self.register_btn.destroy() self.myImage.destroy() def destroyRegisterWindow(self): self.regInputUser.destroy() self.regInputPass.destroy() self.regInputCPass.destroy() self.cancel_btn.destroy() self.register_btn.destroy() self.myImage.destroy() def parseAuthResponse(self, data): if data == 1: print("unloading") self.unloadScreen() self.World.doMenu() else: if data == 2: self.status["text"] = ("Already logged in") else: self.setStatusText("Invalid username/password") self.enter_btn['state'] = DGG.NORMAL self.register_btn['state'] = DGG.NORMAL def setStatusText(self, s): self.status["text"] = s def parseRegResponse(self, data): if data == 1: print("unloading") self.unloadScreen() self.World.doMenu() else: self.setStatusText("User already exists") self.cancel_btn['state'] = DGG.NORMAL self.register_btn['state'] = DGG.NORMAL
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()
class world(ShowBase): def __init__(self): try: ShowBase.__init__(self) except: sys.exit("something went wrong: error while loading OpenGL") # ------------------------------- Begin of parameter variables (pretty messy actually) ------------------------------------ #debug self.debug = False #REMEMBER TO TURN THIS OFF WHEN COMMITTING THIS TO GITHUB YOU GODDAM MORRON !!! #debug self.dir = Filename.fromOsSpecific(os.getcwd()) self.timescale = 5 self.worldscale = 0.1 # currently unused self.camera_delta = 0.5 # camera delta displacement self.sensitivity_x, self.sensitivity_y = 20, 20 self.watched = None # watched object (object focused by the cursor) self.state = [ 'paused', 'free', None ] # state of things: [simulation paused/running,camera following object/free,followed object/None] print('free mode on') self.iteration = 0 #iteration for the menu to be drawn once self.collision_status = False # Keep this on False, that's definitely not a setting # currently unused self.u_constant = 6.67408 * 10**(-11) #just a quick reminder self.u_radius = 5.25 #just what I said earlier self.u_radius_margin = 0.1 #a margin added to the generic radius as a safety feature (mountains and stuff, atmosphere) # ------------------------------- End of parameter variables (sry for the mess) -------------------------------------------- # Mouse parameters self.hidden_mouse = True wp = WindowProperties() wp.setCursorHidden(self.hidden_mouse) self.win.requestProperties(wp) # preparing the menu text list: self.menu_text = [] self.menu_text.append( self.showsimpletext('The PyOS project V0.10', (0, 0.4), (0.07, 0.07), None, (1, 1, 1, True))) self.menu_text.append( self.showsimpletext('Resume', (0, 0.3), (0.06, 0.06), None, (1, 1, 1, True))) self.menu_text.append( self.showsimpletext('Quit', (0, 0.2), (0.06, 0.06), None, (1, 1, 1, True))) # btw I found something about energy transmition through thermal radiation. I think it uses some Boltzmann formula stuff. Link here: # https://fr.wikibooks.org/wiki/Plan%C3%A9tologie/La_temp%C3%A9rature_de_surface_des_plan%C3%A8tes#Puissance_re%C3%A7ue_par_la_Terre # Defining important data lists self.sounds = [ self.loader.loadSfx(self.dir + "/Sound/001.mp3"), self.loader.loadSfx(self.dir + "/Sound/002.mp3"), self.loader.loadSfx(self.dir + "/Sound/003.mp3"), self.loader.loadSfx(self.dir + "/Sound/004.mp3"), self.loader.loadSfx(self.dir + "/Sound/005.mp3") ] #buggy self.collision_solids = [ ] #collision related stuff - comments are useless - just RTFM self.light_Mngr = [] self.data = [ [ 0, 0, 0, 0, 0.003, 0, 0.15, 0.15, 0.15, 100000.00, True, [ self.loader.loadModel(self.dir + "/Engine/lp_planet_0.egg"), (0.1, 0, 0), self.loader.loadModel(self.dir + "/Engine/lp_planet_1.egg"), (0.14, 0, 0) ], "lp_planet", False, 0.1 ], [ 40, 0, 0, 0, 0.003, 0, 0.05, 0.05, 0.05, 20.00, True, [ self.loader.loadModel(self.dir + "/Engine/Icy.egg"), (0.05, 0, 0) ], "Ottilia", False, 0.1 ], [ 0, 70, 10, 0, 0.005, 0, 0.1, 0.1, 0.1, 40.00, True, [ self.loader.loadModel(self.dir + "/Engine/asteroid_1.egg"), (0, 0, 0.2) ], "Selena", False, 1 ], [ 100, 0, 10, 0, 0, 0, 5, 5, 5, 1000000, True, [ self.loader.loadModel(self.dir + "/Engine/sun1.egg"), (0.01, 0, 0), self.loader.loadModel(self.dir + "/Engine/sun1_atm.egg"), (0.01, 0, 0) ], "Sun", True, 0.1 ], [ -100, 50, 70, 0, 0, 0.002, 0.15, 0.15, 0.15, 1000.00, True, [ self.loader.loadModel(self.dir + "/Engine/Earth2.egg"), (-0.1, 0, 0), self.loader.loadModel(self.dir + "/Engine/Earth2_atm.egg"), (-0.15, 0, 0) ], "Julius_planet", False, 0.1 ] # insert your 3d models here, following the syntax ] # the correct reading syntax is [x,y,z,l,m,n,scale1,scale2,scale3,mass,static,[file,(H,p,r),file,(H,p,r)...],id,lightsource,brakeforce] for each body - x,y,z: position - l,m,n: speed - scale1,scale2,scale3: obvious (x,y,z) - mass: kg - static: boolean - [files]: panda3d readfiles list - id: str - lightsource: boolean - #if you want the hitbox to be correctly scaled, and your body to have reasonable proportions, your 3d model must be a 5*5 sphere, or at least have these proportions # create the real data list, the one used by the program self.bodies = [] for c in self.data: temp = body() temp.fill_entries(c) self.bodies.append(temp) temp = None #self.bodies.reverse() # Quick presetting self.setBackgroundColor(0, 0, 0, True) # non-body type structures loading if SKYBOX == 'sky': self.isphere = self.loader.loadModel( self.dir + "/Engine/InvertedSphere.egg") #loading skybox structure self.tex = loader.loadCubeMap(self.dir + '/Engine/Skybox4/skybox_#.png') elif SKYBOX == 'arena': self.box = self.loader.loadModel(self.dir + "/Engine/arena.egg") #load shaders (optionnal) ''' sun_shader=Shader.load(Shader.SLGLSL,self.dir+'/Engine/Shaders/flare_v.glsl',self.dir+'/Engine/Shaders/flare_f.glsl') ''' self.orbit_lines = [] #under developement # see https://www.panda3d.org/manual/?title=Collision_Solids for further collision interaction informations base.graphicsEngine.openWindows() try: # filters predefining self.filters = CommonFilters(base.win, base.cam) ''' self.filters.setBlurSharpen(amount=0) # just messing around ''' if not self.debug: self.filters.set_gamma_adjust(1.0) # can be usefull self.filters.set_bloom(intensity=1, size="medium") render.setAntialias(AntialiasAttrib.MAuto) for c in self.bodies: # loading and displaying the preloaded planets and bodies if c.is_lightSource and not self.debug: # VM filtering self.filters.setVolumetricLighting(c.filelist[u], numsamples=50, density=0.5, decay=0.95, exposure=0.035) #c.filelist[u].set_shader(sun_shader) if BLUR: self.filters.setCartoonInk() for u in range(0, len(c.filelist), 2): # loading each sub-file c.filelist[u].reparentTo(self.render) c.filelist[u].setScale(tuple(c.scale)) c.filelist[u].setPos(tuple(c.position)) #setting the collision solid up temp = hitbox() temp.Volume = CollisionSphere(0, 0, 0, self.u_radius) temp.NodePath = c.filelist[0].attachNewNode(CollisionNode( c.id)) temp.CollisionNode = temp.NodePath.node() self.collision_solids.append( temp ) #the radius is calculated by using the average scale + the u_radius # the structure of the collision_solids list will be: [temp1,temp2,...] # asteroids and irregular shapes must be slightly bigger than their hitbox in order to avoid visual glitches self.collision_solids[ len(self.collision_solids) - 1].CollisionNode.addSolid( self.collision_solids[ len(self.collision_solids) - 1].Volume) #I am definitely not explaining that temp = None if self.debug: loadPrcFileData('', 'show-frame-rate-meter true') self.collision_solids[ len(self.collision_solids) - 1].NodePath.show() # debugging purposes only print("collision: ok") print("placing body: done") if c.is_lightSource: self.light_Mngr.append([PointLight(c.id + "_other")]) self.light_Mngr[len(self.light_Mngr) - 1].append( render.attachNewNode( self.light_Mngr[len(self.light_Mngr) - 1][0])) self.light_Mngr[len(self.light_Mngr) - 1][1].setPos( tuple(c.position)) render.setLight(self.light_Mngr[len(self.light_Mngr) - 1][1]) self.light_Mngr.append([AmbientLight(c.id + "_self")]) self.light_Mngr[len(self.light_Mngr) - 1][0].setColorTemperature(3000) self.light_Mngr[len(self.light_Mngr) - 1].append( render.attachNewNode( self.light_Mngr[len(self.light_Mngr) - 1][0])) for u in range(0, len(c.filelist), 2): c.filelist[u].setLight( self.light_Mngr[len(self.light_Mngr) - 1][1]) print("lights: done") print("loaded new body, out: done") if SKYBOX == 'sky': self.isphere.setTexGen( TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap ) # *takes a deep breath* cubemap stuff ! self.isphere.setTexProjector(TextureStage.getDefault(), render, self.isphere) self.isphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.isphere.setTexScale(TextureStage.getDefault(), .5) # that's a thing... self.isphere.setTexture( self.tex ) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. self.isphere.setLightOff() self.isphere.setScale(10000) #hope this is enough self.isphere.reparentTo(self.render) elif SKYBOX == 'arena': self.box.setPos(0, 0, 0) self.box.setScale(100) self.box.reparentTo(self.render) # collision traverser and other collision stuff # that's super important, and super tricky to explain so just check the wiki self.ctrav = CollisionTraverser() self.queue = CollisionHandlerQueue() for n in self.collision_solids: self.ctrav.add_collider(n.NodePath, self.queue) # the traverser will be automatically updated, no need to repeat this every frame # debugging only if self.debug: self.ctrav.showCollisions(render) # play a random music self.current_playing = random.randint(0, len(self.sounds) - 1) self.sounds[self.current_playing].play() # task manager stuff comes here self.taskMgr.add(self.intro_loop, 'showIntroPic') except: sys.exit(":( something went wrong: files could not be loaded") ''' self.showsimpletext("All modules loaded, simulation running",(-1.42,0.95),(0.04,0.04),None,(1,1,1,True)) self.showsimpletext("PyOS build V0.10",(-1.5,0.90),(0.04,0.04),None,(1,1,1,True)) self.showsimpletext("By l3alr0g",(-1.68,0.85),(0.04,0.04),None,(1,1,1,True)) ''' # key bindings self.accept('backspace', self.system_break) self.accept('escape', self.toggle_pause) self.accept('mouse1', self.handle_select, [True]) self.accept('wheel_up', self.handle_scrolling, [True]) # center button (just a quick test) self.accept('wheel_down', self.handle_scrolling, [False]) self.accept('z', self.move_camera, [0, True]) self.accept('q', self.move_camera, [1, True]) self.accept('s', self.move_camera, [2, True]) self.accept('d', self.move_camera, [3, True]) self.accept('a', self.move_camera, [4, True]) self.accept('e', self.move_camera, [5, True]) self.accept('z-up', self.move_camera, [0, False]) self.accept('q-up', self.move_camera, [1, False]) self.accept('s-up', self.move_camera, [2, False]) self.accept('d-up', self.move_camera, [3, False]) self.accept('a-up', self.move_camera, [4, False]) self.accept('e-up', self.move_camera, [5, False]) self.keymap = [ 'z', 0, 'q', 0, 's', 0, 'd', 0, 'a', 0, 'e', 0, 'mouse1', 0 ] self.disable_mouse() if self.debug: # draw axis coord = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] axis = [] for c in range(3): axis.append(LineSegs()) axis[c].moveTo(0, 0, 0) axis[c].drawTo(coord[c]) axis[c].setThickness(3) axis[c].setColor( tuple([coord[c][u] * 255 for u in range(len(coord[c]))] + [True])) NodePath(axis[c].create()).reparent_to(render) # camera positionning ------- self.focus_point = [ 0, 0, 0 ] # point focused: can become a body's coordinates if the user tells the program to do so self.zoom_distance = 30 # distance to the focus point in common 3D units (can be modified by scrolling) self.cam_Hpr = [0, 0, 0] # phi, alpha, theta - aka yaw, pitch, roll self.cam_Hpr = [ self.cam_Hpr[n] * pi / 180 for n in range(len(self.cam_Hpr)) ] # convert to rad phi, alpha, theta, zoom, object = self.cam_Hpr[ 0] * pi / 180, self.cam_Hpr[1] * pi / 180, self.cam_Hpr[ 2] * pi / 180, self.zoom_distance, self.state[ 2] # temporary vars if self.state[1] == 'free': self.camera_pos = [0, 0, 0] self.camera.setPos(tuple(self.camera_pos)) elif self.state[1] == 'linked': # find the object (self.state[2]) in the data list list_pos = [ self.bodies[n].filelist[0] for n in range(len(self.bodies)) ].index(object.getParent()) self.focus_point = self.bodies[ list_pos].position # take the focused object's coordinates self.camera_pos = [ self.focus_point[0] + sin(phi) * cos(-alpha) * zoom, self.focus_point[1] - cos(phi) * cos(-alpha) * zoom, self.focus_point[2] + sin(-alpha) * zoom ] #keep it up to date so that it's not hard to find whend switching modes self.camera.setPos(tuple(self.camera_pos)) self.camera.setHpr(self.cam_Hpr) # cursor self.cursor = self.showsimpletext('.', (0, 0), (0.08, 0.08), None, ( 1, 1, 1, True)) # yeah, you can laugh, but this still works so I don't care self.pointerNode = CollisionNode('cursor') self.pointerNP = camera.attachNewNode(self.pointerNode) self.pointerNode.setFromCollideMask( BitMask32.bit(1) ) # separate collisions (in order to avoid mistakes during physical calculations) self.cursor_ray = CollisionRay() # create the mouse control ray self.pointerNode.addSolid(self.cursor_ray) self.ctrav.add_collider(self.pointerNP, self.queue) return None def showsimpletext( self, content, pos, scale, bg, fg ): #shows a predefined, basic text on the screen (variable output only) return OnscreenText(text=content, pos=pos, scale=scale, bg=bg, fg=fg) def intro_loop(self, task): if not (task.time): self.screen_fill = OnscreenImage(image=str(self.dir) + "/Engine/main_page.png", pos=(0, 0, 0), scale=(1.77777778, 1, 1)) elif task.time > 3: self.screen_fill.destroy() self.taskMgr.add(self.mouse_check, 'mousePositionTask') self.taskMgr.add(self.placement_Mngr, 'frameUpdateTask') self.taskMgr.add(self.Sound_Mngr, 'MusicHandle') self.taskMgr.add(self.camera_update, 'cameraPosition') self.taskMgr.remove('showIntroPic') return None return task.cont def placement_Mngr( self, task ): # main game mechanics, frame updating function (kinda, all pausing and menu functions must be applied here if self.state[0] == 'running' or not task.time: self.ctrav.traverse(render) #self.queue = CollisionHandlerQueue() # update the collision queue brakeforce = [0 for n in range(len(self.bodies)) ] # create an empty brakeforce list if self.queue.getNumEntries(): if self.debug: print(self.queue.getNumEntries()) # debug # now we have to create a temp list containing only the Entries that refer to collisions between bodies, # not cursor-type collisions: temp1, temp2 = [], [] for count in range(len(self.queue.getEntries())): if self.queue.getEntries()[count].getFromNodePath( ) != self.pointerNP: temp1.append(self.queue.getEntries()[count]) else: temp2.append(self.queue.getEntries()[count]) # the temp1 and temp2 lists have been created # run the check for the body-with-body collisions for c in range(0, len(temp1), 2): entry = temp1[c] brakeforce = self.collision_log(entry, brakeforce) # run the check for the cursor-with-body collisions for c in range(len(temp2)): entry = temp2[c] self.watched = entry.getIntoNodePath() # print "out" # update the collider list self.ctrav.clear_colliders() self.queue = CollisionHandlerQueue() for n in self.collision_solids: self.ctrav.add_collider(n.NodePath, self.queue) self.ctrav.add_collider(self.pointerNP, self.queue) # add the cursor ray again else: self.watched = None # collision events are now under constant surveillance acceleration = [] for c in range(len(self.bodies)): #selects the analysed body var = self.bodies[c] Bdf = [ 0, 0, 0 ] #Bdf stands for 'bilan des forces' in french, it's the resulting acceleration for d in self.bodies[0:c] + self.bodies[c + 1:len( self.bodies ) - 1]: #selects the body which action on the analysed body we're studying...not sure about that english sentence though S, M = [d.mass] + d.position, [var.mass] + var.position temp = self.dual_a(S, M) Bdf = [Bdf[x] + temp[x] for x in range(3)] # list sum # add the result to the global save list acceleration.append(Bdf) #update the bodies' position self.speed_update(acceleration, brakeforce) self.pos_update() self.apply_update() elif self.state[0] == 'paused': self.handle_menu(self.iteration) self.iteration += 1 return task.cont def speed_update(self, a, brakeforce): for c in range(len(self.bodies) ): #the function updates the speed tuple accordingly self.bodies[c].speed[0] += self.timescale * a[c][0] #self.bodies[c].speed[0]/=brakeforce[c]+1 # aero/lytho braking has to be applied to the colliding object # actually, speed isn't applied that way self.bodies[c].speed[1] += self.timescale * a[c][1] #self.bodies[c].speed[1]/=brakeforce[c]+1 self.bodies[c].speed[2] += self.timescale * a[c][2] #self.bodies[c].speed[2]/=brakeforce[c]+1 return 0 def pos_update(self): #updates the positional coordinates for c in range(len(self.bodies)): self.bodies[c].position[ 0] += self.timescale * self.bodies[c].speed[0] self.bodies[c].position[ 1] += self.timescale * self.bodies[c].speed[1] self.bodies[c].position[ 2] += self.timescale * self.bodies[c].speed[2] return 0 def apply_update(self): #actually moves the hole 3d stuff around count = 0 #local counter for c in self.bodies: for u in range(len(c.filelist)): if u % 2 != 0: c.filelist[u - 1].setHpr(c.filelist[u - 1], c.filelist[u]) else: c.filelist[u].setPos(tuple(c.position)) if c.is_lightSource: self.light_Mngr[count][1].setPos(tuple(c.position)) count += 2 #we have to change the position of the pointlight, not the ambientlight return 0 def camera_update(self, task): phi, alpha, theta, zoom, object = self.cam_Hpr[ 0] * pi / 180, self.cam_Hpr[1] * pi / 180, self.cam_Hpr[ 2] * pi / 180, self.zoom_distance, self.state[2] if self.state[1] == 'free': self.camera.setPos(tuple(self.camera_pos)) elif self.state[1] == 'linked': # find the object (self.state[2]) in the data list list_pos = [ self.bodies[n].filelist[0] for n in range(len(self.bodies)) ].index(object.getParent()) self.focus_point = self.bodies[ list_pos].position # take the focused object's coordinates self.camera_pos = [ self.focus_point[0] + sin(phi) * cos(-alpha) * zoom, self.focus_point[1] - cos(phi) * cos(-alpha) * zoom, self.focus_point[2] + sin(-alpha) * zoom ] self.camera.setPos(tuple(self.camera_pos)) self.camera.setHpr(tuple(self.cam_Hpr)) ''' # not finished yet self.camera.setPos(self.focus_point[0]+cos(self.cam_Hpr[0])*self.zoom_distance,self.focus_point[1]+sin(self.cam_Hpr[0])*self.zoom_distance,self.focus_point[2]+sin(self.cam_Hpr[1])*self.zoom_distance) self.camera.lookAt(self.focus_point[0],self.focus_point[1],self.focus_point[2]) ''' # collision cursor stuff goes here: self.cursor_ray.setFromLens(self.camNode, 0, 0) # relatively to the camera, the cursor position will always be 0,0 which is the position of the # white point on the screen if self.keymap != ['z', 0, 'q', 0, 's', 0, 'd', 0]: for x in range(1, len(self.keymap), 2): if self.keymap[x]: self.move_camera( int((x - 1) / 2), True ) # why (x-1)/2 ? because we have to make the tow readable as a key number, like 0,1,2,3 return task.cont def dual_a( self, S, M ): #S is the "static object", the one that applies the force to the "moving" object M O = [] #This will be the list with the accelerations for an object d = sqrt((S[1] - M[1])**2 + (S[2] - M[2])**2 + (S[3] - M[3])**2) x = (self.u_constant * S[0] * (S[1] - M[1])) / d**2 y = (self.u_constant * S[0] * (S[2] - M[2])) / d**2 z = (self.u_constant * S[0] * (S[3] - M[3])) / d**2 O.append(x) O.append(y) O.append(z) return O def collision_log(self, entry, brakeforce): from_pos = [ self.bodies[n].filelist[0] for n in range(len(self.bodies)) ].index(entry.getFromNodePath().getParent()) into_pos = [ self.bodies[n].filelist[0] for n in range(len(self.bodies)) ].index(entry.getIntoNodePath().getParent() ) #find the nodepath in the list f_radius = sum(self.bodies[from_pos].scale) * self.u_radius / 3 i_radius = sum(self.bodies[into_pos].scale) * self.u_radius / 3 if max(f_radius, i_radius) == f_radius: inverted = True into_pos, from_pos = from_pos, into_pos else: inverted = False # currently unused brakeforce[from_pos] = self.bodies[ from_pos].brakeforce # get the force given in the data list # those are the two positions of the nodepaths, now we need to know which one is bigger, in order to obtain the fusion effect # from_pos is the smaller body, into_pos is the bigger one self.collision_gfx( self.momentum_transfer(from_pos, into_pos, entry, inverted), f_radius, i_radius) return brakeforce def momentum_transfer(self, f_pos, i_pos, entry, inverted): if self.debug: print("colliding") # debug, makes the game laggy interior = entry.getInteriorPoint(entry.getIntoNodePath()) # default surface = entry.getSurfacePoint(entry.getIntoNodePath()) print((interior - surface).length()) # debug if (interior - surface).length() >= 2 * sum( self.bodies[f_pos].scale) * self.u_radius / 3: if self.state[2] == self.collision_solids[f_pos].NodePath: self.state[1] = 'free' self.state[2] = None self.ctrav.remove_collider(self.collision_solids[f_pos].NodePath) self.bodies[f_pos].delete_body() self.bodies[i_pos].scale[0] *= ( self.bodies[i_pos].mass + self.bodies[f_pos].mass) / self.bodies[i_pos].mass self.bodies[i_pos].scale[1] *= ( self.bodies[i_pos].mass + self.bodies[f_pos].mass) / self.bodies[i_pos].mass self.bodies[i_pos].scale[2] *= ( self.bodies[i_pos].mass + self.bodies[f_pos].mass) / self.bodies[i_pos].mass self.bodies[i_pos].mass += self.bodies[f_pos].mass # scale updating () ''' temporarly removed for c in range(0,len(self.bodies[i_pos].filelist),2): self.bodies[i_pos].filelist[c].setScale(tuple(self.bodies[i_pos].scale)) ''' # deleting the destroyed planet's data self.bodies = self.bodies[:f_pos] + self.bodies[f_pos + 1:len(self.bodies)] self.collision_solids = self.collision_solids[:f_pos] + self.collision_solids[ f_pos + 1:len(self.collision_solids)] # just a quick test if self.debug: self.ctrav.showCollisions(render) if self.debug: print("planet destroyed") return interior, surface # used for the collision gfx calculations def printScene(self): #debug file = open("scenegraph.txt", "a") ls = LineStream() render.ls(ls) while ls.isTextAvailable(): file.write(ls.getLine()) file.write("\n") file.write("\n") file.write("END\n") file.write("\n") file.close() def Sound_Mngr(self, task): if self.sounds[self.current_playing].length() - self.sounds[ self.current_playing].getTime( ) == 0: #could have just used not() self.current_playing = random.choice( list(range(0, self.current_playing)) + list(range(self.current_playing + 1, len(self.sounds)))) self.sounds[self.current_playing].play() return task.cont def collision_gfx(self, points, Rf, Ri): # collision animation calculations # section size calculation # we know the depth of penetration (no silly jokes please), which allows us, knowing the radius of each body, # to calculate the radius of the section (I've got no idea how to say that in correct english) # the display of the particles all over this circle will be a piece of cake (at least I hope so) # see documents in the screenshot folder for more informations about the maths interior, surface = points[0], points[1] p = (interior - surface).length() p2 = (p**2 - 2 * Ri * p) / (2 * Ri - 2 * p - 2 * Rf) p1 = p - p2 # now we know everything about our impact section (the circle that defines the contact between the two bodies) # we just have to find the coord of the circle's center return 0 def create_crater(self): # see project for more informations return None def toggle_pause(self): temp = ['paused', 'running'] self.state[0] = temp[self.state[0] == temp[0]] # switches between paused and running self.iteration = 0 if self.state[0] == 'paused': self.handle_menu(self.iteration) else: self.filters.del_blur_sharpen() # make the mouse invisible self.hidden_mouse = True wp = WindowProperties() wp.setCursorHidden(self.hidden_mouse) # set the mouse pos to 0 self.center_mouse() self.win.requestProperties(wp) for u in self.menu_text: u.hide() return None def handle_menu(self, iteration): if not iteration: self.accept('escape', self.toggle_pause) self.draw_menu() # make the mouse visible self.hidden_mouse = False wp = WindowProperties() wp.setCursorHidden(self.hidden_mouse) self.win.requestProperties(wp) else: a = 1 # indentation (temporary) #put your mouse detection stuff here return None def draw_menu(self): self.filters.setBlurSharpen(amount=0) for u in self.menu_text: u.show() return None def show_credits(self): print( "created by l3alr0g (at least this part, I'll do something better at the end)" ) return None def system_break(self): # place your data saving routines here print("system exit successful, data saved") print("executing sys.exit()") print("out: done") sys.exit(0) return None def handle_scrolling( self, up): # up is a boolean: up=True means up, up=False means down if up and self.state[0] == 'running': if self.state[1] == 'linked': self.zoom_distance *= 0.95 else: self.camera_delta *= 1.1 elif not up and self.state[0] == 'running': if self.state[1] == 'linked': self.zoom_distance /= 0.95 else: self.camera_delta /= 1.1 return None def rotate_camera(self): self.camera.setHpr(tuple(self.cam_Hpr)) return None def move_camera( self, tow, pressed ): # tow stands for towards, pressed is a boolean which indicates the state of the key if pressed: self.keymap[2 * tow + 1] = 1 self.state[1] = 'free' #print('free mode on') self.state[2] = None else: self.keymap[2 * tow + 1] = 0 if self.keymap[2 * tow + 1]: phi, alpha, theta, delta, zoom = self.cam_Hpr[ 0] * pi / 180, self.cam_Hpr[1] * pi / 180, self.cam_Hpr[ 2] * pi / 180, self.camera_delta, self.zoom_distance if self.keymap[2 * tow] == 'q': if self.state[1] == 'free': self.camera_pos = [ self.camera_pos[0] - cos(phi) * cos(theta) * delta, self.camera_pos[1] - sin(phi) * cos(theta) * delta, self.camera_pos[2] + sin(theta) * delta ] # moving the camera if self.keymap[2 * tow] == 'z': if self.state[1] == 'free': self.camera_pos = [ self.camera_pos[0] - sin(phi) * cos(alpha) * delta, self.camera_pos[1] + cos(phi) * cos(alpha) * delta, self.camera_pos[2] + sin(alpha) * delta ] if self.keymap[2 * tow] == 's': if self.state[1] == 'free': self.camera_pos = [ self.camera_pos[0] + sin(phi) * cos(alpha) * delta, self.camera_pos[1] - cos(phi) * cos(alpha) * delta, self.camera_pos[2] - sin(alpha) * delta ] if self.keymap[2 * tow] == 'd': if self.state[1] == 'free': self.camera_pos = [ self.camera_pos[0] + cos(phi) * cos(theta) * delta, self.camera_pos[1] + sin(phi) * cos(theta) * delta, self.camera_pos[2] - sin(theta) * delta ] if self.keymap[2 * tow] == 'a': self.cam_Hpr[2] -= 1 if self.keymap[2 * tow] == 'e': self.cam_Hpr[2] += 1 return None def mouse_check(self, task): # gets the mouse's coordinates mwn = self.mouseWatcherNode if mwn.hasMouse(): x, y = mwn.getMouseX(), mwn.getMouseY() #print(x,y) # debug # focus_point coordinates modifier code here: if self.state == ['running', 'free', None]: self.cam_Hpr[ 0] -= x * self.sensitivity_x # the - fixes a bug I can't solve self.cam_Hpr[ 1] += y * self.sensitivity_y # those formulas do not work when theta (self.cam_Hpr[2]) changes self.rotate_camera() self.center_mouse() elif self.state[0] == 'running' and self.state[1] == 'linked': self.cam_Hpr[0] -= x * self.sensitivity_x self.cam_Hpr[1] -= y * self.sensitivity_y self.rotate_camera() self.center_mouse() ''' if self.debug: print(self.cam_Hpr,self.camera_pos) # debug ''' return task.cont def center_mouse(self): self.win.movePointer( 0, int(self.win.getProperties().getXSize() / 2), int(self.win.getProperties().getYSize() / 2) ) # move mouse back to center --> careful ! this makes the delta calculation code buggy def handle_select(self, is_clicked): if is_clicked and self.watched != None: self.state[1] = 'linked' # toggle following mode self.state[2] = self.watched print('linked mode on, focusing: ', self.watched) #else: # do nothing actually return None def easter_egg(self): return "please be patient, our hens are working on it"
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 MainScreen(object): """ Controls the main menu screen. This is not the actual main menu, this object controls movement between the main menu forms""" def __init__(self, gcli): """ Create the menu forms and draw the background image. The main menu also handles changing the current active form.""" LOG.notice("Creating Main Menu") # Create handle to game client self.gcli = gcli # self.menusize = MENUSIZE # self.MENUPAD = MENUPAD # self.menupos = MENUPOS # self.gameList = [] # Background image self.background = OnscreenImage( image="data/images/menubackground2.png", pos=(0.6, 0, -1.1333), scale=(1.6, 1, 2.1333), parent=render2d ) # Create menu forms self.main = MainPane(self, gcli) gui.add(self.main) self.multi = MultiPane(self, gcli) gui.add(self.multi) self.multi.visable = False self.option = OptionPane(self, gcli) gui.add(self.option) self.option.visable = False self.player = PlayerPane(self, gcli) gui.add(self.player) self.player.visable = False self.credit = CreditsPane(self, gcli) gui.add(self.credit) self.credit.visable = False # Setup menu state self._currentmenu = self.main def showMain(self): self._currentmenu.toggle() self._currentmenu = self.main self.main.toggle() def showMulti(self): self._currentmenu.toggle() self._currentmenu = self.multi self.multi.toggle() def showPlayer(self): self._currentmenu.toggle() self._currentmenu = self.player self.player.toggle() def showOptions(self): self._currentmenu.toggle() self._currentmenu = self.option self.option.toggle() def showCredits(self): self._currentmenu.toggle() self._currentmenu = self.credit self.credit.toggle() def exit(self): Event.Dispatcher().broadcast(Event.Event("E_ExitProgram", src=self)) def startGame(self, mapMD5): """ Clean up all the menus and then tell dispatcher to start the game""" self.background.destroy() Event.Dispatcher().broadcast(Event.Event("E_StartGame", src=self, data=mapMD5))
class IntroScene(Scene): ''' A subclass of the Scene class to handle the main menu and all of it's required tasks + events ''' def __init__(self, app): ''' Initialise and run any events BEFORE loading the scene ''' self.app = app self.isPlayerControlled = False self.models = {} self.loader = app.loader self.renderTree = deepcopy(app.emptyRenderTree) # Add the ground model self.addObject("ground.bam", scale=(3.6,3.6,2), key="ground") # Add the barn barnModel = self.addObject("barn.bam", scale=(1, 1, 1)) # Create a corn model and add it in the bottom corner self.addObject("corn.egg", pos=(-62, -62, 0), scale=(1, 1, 1.3), key="corn") # Iterate a 25x25 square for the corn for x in range(25): for z in range(25): # Use basic maths to create a 'lollypop' shape cutout if (x-12)**2+(z-12)**2 > 25 and (abs(x-12) > 1 or z > 12): # Add a corn instance to the scene self.addObject("corn.egg", (x*5, z*5, 0), instanceTo="corn") # Add the AI World self.AIworld = AIWorld(self.renderTree) # Add generic linear fog on super-low quality mode if app.quality == 'super-low': fog = Fog("corn_fog") # Set the fog colour fog.setColor(0.8,0.8, 0.8) # Set the density of the fog fog.setExpDensity(0.005) # Add the fog to the scene self.renderTree.setFog(fog) # Set the scene's background colour base.setBackgroundColor(0.635, 0.454, 0.494) # Create an empty ambient light alight = AmbientLight('alight') # Set the colour alight.setColor(VBase4(0.2, 0.2, 0.2, 0.2)) # Attach the node to the render tree alnp = render.attachNewNode(alight) # Set the light to illuminate the scene render.setLight(alnp) # Add the two chickens and set the maximum velocity (force) on them self.chickenOne = Chicken(self, (20, -50, 0)) self.chickenOne.aiChar.setMaxForce(70) self.chickenTwo = Chicken(self, (-20, -40, 0)) self.chickenTwo.aiChar.setMaxForce(70) # Add them to the AI World self.AIworld.addAiChar(self.chickenOne.aiChar) self.AIworld.addAiChar(self.chickenTwo.aiChar) # Enable the pursue behaviour self.chickenOne.aiBehaviour.pursue(self.app.camera) self.chickenTwo.aiBehaviour.pursue(self.app.camera) def eventRun(self, task): ''' Run any constant events for the scene ''' # If the movement controller has finished its path then if self.app.controller and self.app.controller.clock_obj.get_frame_time() > self.app.controller.curve_time_end: # delete the motion controller self.app.controller = None # Load the first scene of the gameplay self.app.sceneMgr.loadScene(SceneOne(self.app)) # Update the AI world self.AIworld.update() return Task.cont def initScene(self): ''' Set up the movement controller and begin the motion path. ''' # Make the motion path motionPath = ( (Vec3(0, -63, 4), Vec3(0, 0, 0)), (Vec3(0, -63, 4), Vec3(0, 0, 0)), (Vec3(0, -63, 4), Vec3(0, 0, 0)), (Vec3(0, -56, 4), Vec3(-90, -10, 0)), (Vec3(0, -52, 4), Vec3(0, -70, 0)), (Vec3(0, -46, 4), Vec3(90, 0, 20)), (Vec3(0, -40, 4), Vec3(0, 0, 0)), (Vec3(0, -30, 4), Vec3(0, 0, 0)), (Vec3(0, -20, 4), Vec3(0, 0, 0)), (Vec3(5, -10, 4), Vec3(-40, 0, -5)), (Vec3(5, -9, 4), Vec3(-190, 0, 0)), (Vec3(5, -4, 4), Vec3(-190, 0, -5)), (Vec3(4, 0, 0.5), Vec3(-190, 80, 0)) ) # Create the controller for movement self.app.controller = MovementController(self.app) # Set the initial position self.app.controller.set_initial_position(Vec3(0, -63, 4), Vec3(0, 0, 0)) # Run the setup on the movement controller self.app.controller.update_task = self.app.addTask(nullTask, 'meh') # Play the pre-defined motion path self.app.controller.play_motion_path(motionPath, 0.8) # Remove the player movement controls self.app.taskMgr.remove(self.app.controller.update_task) # Unhide the 2d overlay. self.app.aspect2d.show() self.app.render2d.show() # set up the black image self.fadeQuad = OnscreenImage(image='resources/generic/fade.png',pos=(-0.5, 0, 0), scale=(2, 1, 1)) self.fadeQuad.setTransparency(TransparencyAttrib.MAlpha) # Add the fadein transition self.app.taskMgr.add(self.fadeIn, 'fade-task') def fadeIn(self, task): ''' Fade in the scene by fading a black rectangle ''' # If more than 4 seconds have passed then finish the task if task.time > 4: self.fadeQuad.destroy() return # Get the alpha of the square alpha = task.time / 4 # set the alpha level on the rectangle self.fadeQuad.setAlphaScale(1-alpha) return Task.cont
class MyApp(ShowBase): def __init__(self, fStartDirect=True): #ConfigVariableBool("fullscreen",0).setValue(1) ShowBase.__init__(self) self.loadInitialCamPos()#initialize camera positioning self.assocs=dict() self.loadBooleans() self.loadLists() self.shuffleCards() self.loadValues() #creates a random sequence of cards we will memorize self.setInputs() #set up keyboard and mouse inputs self.setUpCollision() #sets up collision detection self.setUpScene() #sets up geometry in the 3D Enviroments self.loadSFX() self.light=self.setUpPointLight() taskMgr.add(self.setUpChest, 'setUpChest') #sets up rotating graphic of chest def loadValues(self): self.counter,self.lightCounter,self.fade,self.numFireflies=0,0,0,15 self.numCards=13 self.numCardsCopy=copy.copy(self.numCards) self.shuffledCardFacesCopy=copy.copy(self.shuffledCardFaces) def loadLists(self): self.cardsPos,self.imageList,self.visitedItems=[],[],[] self.buttonList,self.lastCoord,self.fireFlyList=[],[],[] self.previousCard,self.nextCard=[],[] def loadBooleans(self): self.toggleChest=False self.fadeToggle=False self.togglePreviousCard=False self.toggleNextCard=False self.toggleBar=True self.titleText=None self.userLocation=None def loadInitialCamPos(self): #we disable our mouse because we be using a different method #that will set up our mouse controls base.disableMouse() self.camPosx,self.camPosz=15,28 self.camera.setH(90) self.camera.setP(-25) self.heading=0 base.camera.setPos(self.camPosx,0,self.camPosz) def loadSFX(self): self.soundSteps = loader.loadMusic("footsteps.wav") #circus in the Sky is a piece written by Uzman Riaz (credit) #self.circusInTheSky=loader.loadMusic("circusInTheSky.wav") def setUpCollision(self): #pusher and queue are handlers from when a collision occurs self.cTrav = CollisionTraverser() self.queue = CollisionHandlerQueue() self.pusher = CollisionHandlerPusher() #set up scene geometrys self.setUpCollisionRay() self.setUpCollisionNode() def setUpPointLight(self): taskMgr.doMethodLater(.1, self.createTitleText, 'textFadeInOut') #we create multiple point lights to make it appear as if there are #'firefly' entities within the chest for n in xrange(self.numFireflies): self.generateLights("%fFirefly"%n) #sets up a soft ambient light so that our 3D enviroment appears #more realistic self.alight = AmbientLight('ambientLight') self.alight.setColor(VBase4(.6, .6, .6, 1)) alnp = render.attachNewNode(self.alight) render.setLight(alnp) self.treasureChest.setLight(alnp) def createTitleText(self,task): #task allows up to fade text in and out self.updateFade() if self.titleText!=None: self.titleText.remove() self.titleText=OnscreenText(text="[Click on the chest to begin]", style=Plain,pos=(0,0),fg=(1,1,1,self.fade)) if self.toggleChest==True: self.titleText.remove() return task.done return task.again def generateLights(self,name): #generate pointlights and reparenting them to the chest name=PointLight("Light") name=render.attachNewNode(name) name.setPos(0,0,22) name.hide() self.modelLight = loader.loadModel("misc/Pointlight.egg.pz") self.modelLight.reparentTo(name) self.treasureChest.setLight(name) self.fireFlyList.append(name) def setUpChest(self,task): if self.toggleChest==True: #chest rotates backwards if clicked on self.speed=-1.5 else: self.speed=.5 #chest rotates forward slowly self.lightCounter+=1 angle,radius= radians(self.heading),1.2 x,y,z =(cos(angle)*radius,sin(angle)*radius,sin(angle)*radius) self.heading+=self.speed self.heading%=360 self.treasureChest.setH(self.heading) if self.lightCounter%7==0: for n in xrange(self.numFireflies): self.generateFireFlies(x,y,n) if abs(self.treasureChest.getH()-360)<2 and self.toggleChest==True: #if chest is activated and the chest if facing the camera taskMgr.add(self.moveChest, 'moveChest') return task.done else: return Task.cont def moveChest(self,task): #units are calculated so that camera and chest move simultaneously #to create smooth transition between frames self.alight.setColor(VBase4(.8, .8, .8, 1)) self.shiftChestUnits,self.intervals=.1,52.0 x,y,z=self.treasureChest.getPos() newx=x+self.shiftChestUnits self.treasureChest.setPos(newx,y,z) self.moveCamera() if int(x)==self.camPosx-10: #if we get within a range of acceptable values # we set up our homepage self.homePage() return task.done else: return task.cont def moveCamera(self): self.originalZ,self.targetZ=28.0,22.0 self.shiftCameraZ=(self.originalZ-self.targetZ)/self.intervals self.pitchChange=25.0/self.intervals newPitch=self.camera.getP()+self.pitchChange newHeight=self.camera.getPos()[2]-self.shiftCameraZ camerax,cameray=self.camera.getPos()[0],self.camera.getPos()[1] self.camera.setPos(camerax,cameray,newHeight) self.camera.setP(newPitch) def generateFireFlies(self,x,y,n): zLowerLimit=21.0 zHigherLimit=22.0 light=self.fireFlyList[n] self.xFirefly=random.uniform(-x,x) self.yFirefly=random.uniform(-y,y) self.zFirefly=random.uniform(zLowerLimit,zHigherLimit) light.setPos(self.xFirefly,self.yFirefly,self.zFirefly) def setUpFog(self): self.fogDensity=.03 myFog = Fog("fog") myFog.setColor(1,1,1) myFog.setExpDensity(self.fogDensity) render.setFog(myFog) def displayHelpPanel(self): self.dummyNode1=self.createDummyNode("self.dummyNode1") self.dummyNode2=self.createDummyNode("self.dummyNode2") self.dummyNode3=self.createDummyNode("self.dummyNode3") self.floorPlan=OnscreenImage( image="floorplan.png", scale=(.4,.25,.55), pos=(.7,0,.3)) self.floorPlan.setTransparency(TransparencyAttrib.MAlpha) self.floorPlan.reparentTo(self.dummyNode1) self.displayToggleBar() self.displayAdjacencies() taskMgr.doMethodLater(.1, self.createSubTitle, 'textFadeInOut') def createSubTitle(self,task): self.previousTitlePos=(-1.205,.89) self.nextTitlePos=(-1.195,-.43) try: self.titlePrevious.destroy() self.titlePrevious=OnscreenText( text="[Previous]",pos=self.previousTitlePos, scale=.045,fg=(1,1,1,self.fade)) except: self.titlePrevious=OnscreenText( text="[Previous]",pos=self.previousTitlePos, scale=.045,fg=(1,1,1,self.fade)) try : self.titleNext.destroy() self.titleNext=OnscreenText( text="[Next]",pos=self.nextTitlePos,scale=.045,fg=(1,1,1,self.fade)) except: self.titleNext=OnscreenText( text="[Next]",pos=self.nextTitlePos, scale=.045,fg=(1,1,1,self.fade)) return task.again def createDummyNode(self,name): name=render.attachNewNode("2d") name.reparentTo(aspect2d) return name def displayToggleBar(self): self.toggleBarImage=DirectButton( image = "hidebar.png",scale=(.07,0.1,.55),pos=(1.17,0,.3), relief=None,command=lambda: self.switchDisplays( self.toggleBar,self.dummyNode1,self.toggleBarImage, "hidebar.png","showbar.png", (.07,0.1,.55),(1.17,0,.3))) self.togglePreviousBar() self.toggleNextBar() def togglePreviousBar(self): self.previousBarPos=(-1.2,0,.57) self.togglePreviousBarImage=(DirectButton( image = "hidebarshort.png", scale=(.07,0.1,.195),pos=self.previousBarPos,relief=None, command= lambda: self.switchDisplays( self.togglePreviousCard, self.dummyNode2,self.togglePreviousBarImage, "hidebarshort.png","showbarshort.png", (.07,0.1,.195),self.previousBarPos))) def toggleNextBar(self): self.nextBarPos=(-1.2,0,-.7) self.toggleNextBarImage=(DirectButton( image = "hidebarshort.png", scale=(.07,0.1,.195),pos=self.nextBarPos,relief=None, command= lambda: self.switchDisplays( self.toggleNextCard,self.dummyNode3,self.toggleNextBarImage, "hidebarshort.png","showbarshort.png", (.07,0.1,.195),self.nextBarPos))) def switchPreviousCardDisplay(self): self.toggleBarPrevious=not(self.toggleBarPrevious) def displayAdjacencies(self): if self.previousCard: self.displayPreviousCard() if self.nextCard: self.displayNextCard() def displayPreviousCard(self): self.previousCardPos=(-1,0,.58) self.previousCardTextPos=(-.9,.57) prevCard=self.previousCard.split(".")[0] self.previousCard=OnscreenImage( image=self.previousCard,pos=self.previousCardPos, scale=(0.07,0.82,0.12)) self.previousCard.reparentTo(self.dummyNode2) try: self.assocPrevText.destroy() self.assocPrevText=OnscreenText( text="(%s)"%self.inputs[prevCard], pos=self.previousCardTextPos, scale=.06,fg=(1,1,1,1),align=TextNode.ALeft) self.assocPrevText.reparentTo(self.dummyNode2) except: self.assocPrevText=OnscreenText( text="(%s)"%self.inputs[prevCard], pos=self.previousCardTextPos, scale=.06,fg=(1,1,1,1),align=TextNode.ALeft) self.assocPrevText.reparentTo(self.dummyNode2) def displayNextCard(self): self.nextCardPos=(-1,0,-.685) self.nextCardTextPos=(-.9,-.69) nextCard=self.nextCard.split(".")[0] self.nextCard=OnscreenImage( image=self.nextCard,pos=self.nextCardPos,scale=(0.07,0.82,0.12)) self.nextCard.reparentTo(self.dummyNode3) try: self.assocNextText.destroy() self.assocNextText=OnscreenText( text="(%s)"%self.inputs[nextCard], pos=self.nextCardTextPos, scale=.06,fg=(1,1,1,1),align=TextNode.ALeft) self.assocNextText.reparentTo(self.dummyNode3) except: self.assocNextText=OnscreenText( text="(%s)"%self.inputs[nextCard], pos=self.nextCardTextPos,scale=.06, fg=(1,1,1,1),align=TextNode.ALeft) self.assocNextText.reparentTo(self.dummyNode3) def switchDisplays(self,toggleBar,dummyNode,imageNode,hideImage, showImage,scale,pos): toggleBar=not(toggleBar) if toggleBar==True: dummyNode.show() imageNode.destroy() imageNode=(DirectButton(image = hideImage,scale=scale,pos=pos, relief=None, command=lambda: self.switchDisplays( toggleBar,dummyNode, imageNode,hideImage, showImage,scale,pos))) else: dummyNode.hide() imageNode.destroy() imageNode=(DirectButton(image = showImage,scale=scale,pos=pos, relief=None, command= lambda: self.switchDisplays( toggleBar,dummyNode, imageNode,hideImage, showImage,scale,pos))) def shuffleCards(self): self.shuffledCardNames=[] self.shuffledCardFaces=copy.copy(cardFaces) random.shuffle(self.shuffledCardFaces) for face in self.shuffledCardFaces: self.shuffledCardNames.append(face.split(".")[0]) def setUpCollisionRay(self): #Make a collision node for ours selection ray #Repurposed from Panda3D Documentation self.selectionNode = CollisionNode('mouseRay') self.selectionNP = camera.attachNewNode(self.selectionNode) self.selectionNode.setFromCollideMask( GeomNode.getDefaultCollideMask()) self.selectionNode.setFromCollideMask(1) self.selectionNode.setIntoCollideMask(0) self.selectionRay = CollisionRay() #Make our ray self.selectionNode.addSolid(self.selectionRay) #Add it to the collision node #Register the ray as something that can cause collisions self.cTrav.addCollider(self.selectionNP,self.queue) def setUpCollisionNode(self): #add a collision node to our camera self.fromObject = base.camera.attachNewNode( CollisionNode('colNode')) self.fromObject.setPos(0,0,3) self.fromObject.node().addSolid(CollisionSphere(0, 0, 0, .5)) self.fromObject.node().setIntoCollideMask(0) self.cTrav.addCollider(self.fromObject,self.pusher) self.pusher.addCollider( self.fromObject, base.camera, base.drive.node()) def setInputs(self): self.accept("mouse1",self.mouse1Tasks) self.accept('escape', sys.exit) def playFootSteps(self): self.soundSteps.play() def mouse1Tasks(self): self.mouseTask() def setUpScene(self): #self.setUpControls() self.setUpBackground() #set up the items where we can store information self.setUpItems() def mouseTask(self): self.scale=53 self.loadItemList() if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.selectionRay.setFromLens( base.camNode, mpos.getX(), mpos.getY()) #self.cTrav.showCollisions(render) if self.queue.getNumEntries() > 0: self.mouseEntry() def mouseEntry(self): #if we've clicked on something self.queue.sortEntries() #we get closest item pickedObj = self.queue.getEntry(0).getIntoNodePath().getTag("items") #check if what we clicked is what we want (has proper tag) if len(pickedObj)>0 and (pickedObj not in self.visitedItems): self.mouseTaskSupport(pickedObj) if self.queue.getEntry(0).getIntoNodePath().getTag("openChest"): self.toggleChest=True def mouseTaskSupport(self,pickedObj): self.assocs[ self.shuffledCardNames[self.counter]]=self.items[int(pickedObj)] self.counter+=1 self.visitedItems.append(pickedObj) #self.queue.getEntry(0).getIntoNodePath().clearTag("items") #if len(self.visitedItems)==len(self.items): if len(self.visitedItems)==5: self.testMemory() self.drawMiniCards(-self.camera.getPos()[1]/self.scale+.40, self.camera.getPos()[0]/self.scale-.2) self.updateDisplayCards() self.displayAdjacencies() def loadItemList(self): self.items=["painting","post","tv","bed","carpet","table","tree", "shelf","loveSeat1","loveSeat2","longSofa", "dinnerTable","dinnerChair1","dinnerChair2"] def testMemory(self): self.nextButton=DirectButton(image = 'arrow.png', scale=.15,pos=(0.8,0,-0.6), relief=None, command=self.recallMemory) self.nextButton.setTransparency(TransparencyAttrib.MAlpha) def displayPriorityArrow(self): self.arrow=OnscreenImage(image="arrow2.png", scale=(.05,.1,.05),pos=(-.51,0,-.6), color=(1,0,0,0)) self.arrow.setTransparency(TransparencyAttrib.MAlpha) taskMgr.doMethodLater(.1, self.fadeArrow, 'arrowFadeInOut') def displayUserLocation(self,task,scale=(.05,1,.05)): self.updateFade() if self.userLocation!=None: self.userLocation.destroy(),self.userAngle.destroy() x=-self.camera.getPos()[1]/self.scale+.40 y=self.camera.getPos()[0]/self.scale-.2 self.userLocation=OnscreenImage( image="dot.png",pos=(x,0,y),scale=scale, color=(1,1,1,self.fade)) self.userAngle=OnscreenImage( image="rotating.png",pos=(x,0,y),scale=scale, color=(1,1,1,self.fade)) self.userAngle.setR(-self.camera.getHpr()[0]) self.userLocation.setTransparency(TransparencyAttrib.MAlpha) self.userAngle.setTransparency(TransparencyAttrib.MAlpha) self.userLocation.reparentTo(self.dummyNode1) self.userAngle.reparentTo(self.dummyNode1) return Task.again def updateFade(self): if self.fadeToggle==True: self.fade+=.05 if self.fade>1: self.fadeToggle=False elif self.fadeToggle==False: self.fade-=.05 if self.fade<0: self.fadeToggle=True def drawMiniCards(self,x,y): self.lastCoord+=([[x,0,y]]) self._draw_line_segs(self.dummyNode1,self.lastCoord) for i in xrange(len(self.lastCoord)): self.miniCards=OnscreenImage( image=self.shuffledCardFaces[i], pos=(self.lastCoord[i][0],0,self.lastCoord[i][2]), scale=(0.03,0.82,0.050)) self.miniCards.reparentTo(self.dummyNode1) def _draw_line_segs(self, parent, points, thickness=1.5): segs = LineSegs() segs.setThickness(thickness) segs.setColor( Vec4(1,0,0,.35) ) if points: segs.moveTo(points[0][0], points[0][1], points[0][2]) for p in points[1:]: segs.drawTo(p[0], p[1], p[2]) lines = NodePath(segs.create()) lines.reparentTo(parent) def recallMemory(self): self.checkList=[] self.checkListFaces=[] self.startCard=0 self.endCard=13 self.cardSet=0 self.bk=OnscreenImage(image="bk.png",scale=(2,1,1)) self.recallCards(self.startCard,self.endCard, self.cardSet,0) self.scaleCards=(0.1,0.1,0.13) scaleCards2=(0.07,0.05,0.10) self.recallMemoryPrompt=OnscreenText( text="List the cards in the sequence as you recall", pos=(0,.45),scale=.045,fg=(0,0,0,.75)) def recallCards(self,startCard,endCard,cardSet,createEntries=1): for i in xrange(startCard,endCard): x=2*(i+1)/(self.numCards+1.0)-1-cardSet*1.75 self.cardsPos.append(x) self.createButtons(i,x) if createEntries==1: self.createEntries(x, cardSet) for image in self.buttonList: image.setTransparency(TransparencyAttrib.MAlpha) def createButtons(self,i,x): self.buttonList.append(DirectButton( image = cardFaces[i],scale=(0.06,0.1,0.095),pos=(x,0,.3), relief=None, command=lambda: self.createCheckButtons(i))) def createCheckButtons(self,i): self.correctCount=0 self.checkList.append(i) self.checkListFaces.append(cardFaces[i]) for i in xrange(len(self.checkList)): x=2*(i+1)/(self.numCards+1.0)-1 self.cards=OnscreenImage(image=self.checkListFaces[i], pos=(x,0,-.2),scale=(0.06,0.1,0.095)) if len(self.checkList)==13: correct=self.testResults() self.results=OnscreenText( text="You recalled %d out of %d correctly"%( correct,self.numCards),pos=(0,-0.85),scale=.1) def testResults(self): for i in xrange(len(self.shuffledCardFaces)): if self.shuffledCardFaces[i]==self.checkListFaces[i]: self.correctCount+=1 return self.correctCount def updateDisplayCards(self): self.numCardsCopy-=1 self.previousCard=self.shuffledCardFacesCopy.pop(0) if len(self.shuffledCardFacesCopy)!=0: self.nextCard=self.shuffledCardFacesCopy[0] else: self.nextCard=False for image in self.imageList: image.destroy() self.displayCards() def displayCards(self): for i in xrange(self.numCardsCopy): x=2*(i+1)/(self.numCards+1.0)-.65 self.cardsPos.append(x) self.imageList.append(OnscreenImage( image="%s"%(self.shuffledCardFacesCopy[i]), pos=(x,0,-.8),scale=(0.05,0.05,0.08))) #we use middle numbers as coordinates def fadeArrow(self,task): self.arrow.setColor(1,0,0,self.fade) return task.cont def setUpBackground(self): self.scale=10 #load grass and set position, scale, and texture self.walls=loader.loadModel("Walls") self.walls.setPos(0,0,0) self.walls.setScale(self.scale,self.scale,self.scale) walltex1 = loader.loadTexture('walltex1.png') self.walls.setTexture(walltex1) #render our object self.walls.reparentTo(render) self.loadColGeomsSet1() self.loadColGeomsSet2() self.setUpBackgroundSupport() def setUpBackgroundSupport(self): for geom in self.colGeoms: self.createCollisionGeom(*geom) cFloorNode=CollisionNode('floorCollision') floorQuad=CollisionPolygon(Point3(5, 0, 0), Point3(-1.5,0,0), Point3(-1.5, -4, 0),Point3(5, -4, 0)) cFloorNode.addSolid(floorQuad) def loadColGeomsSet1(self): self.colGeoms=[ (11,(2.4,-1.80,1),(2.4,-1.80,0),(.55,-1.80,0), (.55,-1.80,1)),#Interior 2b (firsthalf), (1,(5,-.05,0),(5,-.05,1),(-1.5,-.05,1), (-1.5,-.05,0)),#West Wall (2,(-1.5,0,0),(-1.5,0,1),(-1.5,-4,1), (-1.5,-4,0)),#South Edge (5,(0.52,0,0),(0.52,0,1),(0.52,-1.2,1), (0.52,-1.2,0)), #South Wall_1_Interior (3,(0.38,0,1),(0.38,0,0),(0.38,-1.2,0), (0.38,-1.2,1)), #South Wall_1_Exterior (4,(0.38,-1.7,1),(0.38,-1.7,0),(0.38,-4,0),(0.38,-4,1)), #South Wall_2_Exterior (6,(0.52,-1.7,0),(0.52,-1.7,1),(0.52,-4,1),(0.52,-4,0)), #South Wall_2 Interior (7,(1.8,0,1),(1.8,0,0),(1.8,-1.45,0),(1.8,-1.45,1)), #Interior 1 (TV) (8,(1.9,0,0),(1.9,0,1),(1.9,-1.45,1),(1.9,-1.45,0)), #Interior 1b (TV) (9,(2.4,-1.95,0),(2.4,-1.95,1),(.55,-1.95,1), (.55,-1.95,0)), #Interior 2 (firsthalf) (10,(3.95,-1.95,0),(3.95,-1.95,1), (2.7,-1.95,1),(2.7,-1.95,0))] #Interior 2 (secondhalf) def loadColGeomsSet2(self): self.colGeoms+=[ (12,(3.95,-1.80,1),(3.95,-1.80,0), (2.7,-1.80,0), (2.7,-1.80,1)), #Interior 2b (secondhalf) (13,(2.95,-1.9,0),(2.95,-1.9,1),(2.95,-2.1,1), (2.95,-2.1,0)),#North Wall 1 Exterior (firsthalf)E (14,(2.95,-2.48,0),(2.95,-2.48,1),(2.95,-4,1), (2.95,-4,0)),#North Wall 1 Exterior (secondhalf)E (15,(2.7,-1.9,1),(2.7,-1.9,0),(2.7,-2.1,0), (2.7,-2.1,1)), #North Wall 1b Interior (firsthalf) E (16,(2.7,-2.48,1),(2.7,-2.48,0),(2.7,-4,0), (2.7,-4,1)), #North Wall 1b Interior (secondhalf) E (17,(3.82,0,1),(3.82,0,0),(3.82,-.35,0), Point3(3.82,-.35,1)),#North Wall 2 Interior (firsthalf) W (18,(3.82,-1.1,1),(3.82,-1.1,0),(3.82,-1.9,0), Point3(3.82,-1.9,1)),#North Wall 2 Interior (secondhalf) W (19,(4,0,0),(4,0,1),(4,-.35,1), Point3(4,-.35,0)),#North Wall 2 Exterior (firsthalf) W (20,(4,-1.1,0),(4,-1.1,1),(4,-1.9,1), Point3(4,-1.9,0))#North Wall 2 Exterior (secondhalf) W ] def createCollisionGeom(self,n,firstPts,secondPts,thirdPts,fourthPts): collisionNode="wallCollision%d"%n collisionNodeName="cWallNode%d"%n collisionNodeName=CollisionNode(collisionNode) quadName="wallQuad%d"%n quadName=CollisionPolygon(Point3(firstPts),Point3(secondPts), Point3(thirdPts),Point3(fourthPts)) collisionNodeName.addSolid(quadName) self.wallC=self.walls.attachNewNode(collisionNodeName) self.roof=self.loadItems("Roof","rooftex.png",scaleX=6,scaleY=6) self.walls2=self.loadItems("Walls2","walltex2.png") self.grass=self.loadItems("grass",'8CYNDAC0.png') self.floor=self.loadItems("floor","floor.png") self.exterior=self.loadItems("exterior",'brick.png') def setUpItems(self): self.itemList=[] self.scale=10 self.tv=self.loadItems("tv",'tv.png') self.carpet=self.loadItems("carpet","carpet.png") self.white=self.loadItems("white","walltex2.png",8,4) self.painting=self.loadItems("painting","kosbie.png") self.wood=self.loadItems("wood","wood.png",8,4) self.tree=self.loadItems("GroomedTree",None,1,1,.9,(52,-5,0)) self.shelf=self.loadItems("shelf","darkwood.png") self.couches=self.loadItems("couch","leather.png",5,5) self.dining=self.loadItems("chairs","wood.png") self.treasureChest=self.loadItems( "treasurechest","woodpanel.png",1,1,None,(0,0,20)) self.sky=self.loadItems("sky","sky.png",1,1) self.selectionItems = render.attachNewNode("selectionRoot") self.setUpCollisionGeom() def setUpCollisionGeom(self): self.paintingNode=self.loadCollisionPolygon( "painting",self.painting,(3.35,-.07,.45),(3.35,-.07,.8), (2.9,-.07,.8),(2.9,-.07,.45)) self.postNode=self.loadCollisionTube( "post",self.wood,.25,-2,0,.25,-2,.55,.03) self.tvNode=self.loadCollisionPolygon( "tv",self.tv,(1.75,-.35,.78),(1.75,-.35,.5),(1.75,-1.1,.5), (1.75,-1.1,.78)) self.bedNode=self.loadCollisionPolygon( "bed",self.white,(1,-2.7,.17),(.5,-2.7,.17),(.5,-1.9,.17), (1,-1.9,.17)) self.carpetNode=self.loadCollisionPolygon( "carpet",self.carpet,(1.95,-3.15,.05),(2.4,-3.15,.05), (2.4,-2.55,.05),(1.95,-2.55,.05)) self.tableNode=self.loadCollisionPolygon( "table",self.wood,(1,-3.5,.26),(1.45,-3.5,.26), (1.45,-3.1,.26),(1,-3.1,.26)) self.supportSetUpCollisionGeom() def supportSetUpCollisionGeom(self): self.treeNode=self.loadCollisionTube( "tree",self.tree,0,0,0,0,0,7,2) self.shelfNode=self.loadCollisionPolygon( "shelf",self.shelf,(.6,-0.05,.78),(.6,-0.05,0), (.6,-.43,0),(.6,-.43,.78)) self.couchNode1=self.loadCollisionTube( "couch1",self.couches,1.05,-.96,0,1.05,-.96,.2,.2) self.couchNode2=self.loadCollisionTube( "couch2",self.couches,1.45,-.96,0,1.45,-.96,.2,.2) self.couchNode3=self.loadCollisionTube( "couch3",self.couches,1.00,-.16,.1,1.5,-.16,.1,.2) self.dinnerTable=self.loadCollisionPolygon( "dinnerTable",self.dining,(3.6,-.89,.26),(3.6,-.61,.26), (3.1,-.61,.26),(3.1,-.89,.26)) self.dinnerChairNode1=self.loadCollisionTube( "dinnerChair1",self.dining,2.9,-.75,0,2.9,-.75,.2,.1) self.dinnerChairNode2=self.loadCollisionTube( "dinnerChair1",self.dining,3.7,-.75,0,3.7,-.75,.2,.1) self.chestNode=self.loadCollisionTube( "chest",self.treasureChest,.02,.02,.25,.07,.07,.25,.25) self.chestNode.setTag( "openChest","1") self.itemList+=(self.paintingNode,self.postNode,self.tvNode, self.bedNode,self.carpetNode,self.tableNode, self.treeNode,self.shelfNode,self.couchNode1, self.couchNode2,self.couchNode3,self.dinnerTable, self.dinnerChairNode1,self.dinnerChairNode2) self.setTag(self.itemList,"items") def setTag(self): self.itemList+=(self.paintingNode,self.postNode,self.tvNode, self.bedNode,self.carpetNode,self.tableNode, self.treeNode,self.shelfNode, self.couchNode1,self.couchNode2,self.couchNode3, self.dinnerTable,self.dinnerChairNode1, self.dinnerChairNode2) self.setTag(self.itemList,"items") def setTag(self,node,tagKey): for i in xrange(len(node)): node[i].setTag(tagKey,str(i)) def loadItems(self,modelName,texture=None,scaleX=1,scaleY=1, scale=None,pos=(0,0,0)): if scale==None: scale=self.scale modelName=loader.loadModel(modelName) modelName.setPos(pos) modelName.setScale(scale,scale,scale) ts=TextureStage("ts") if texture!=None: modelTex=loader.loadTexture(texture) modelName.setTexture(ts,modelTex) modelName.setTexScale(ts,scaleX,scaleY) modelName.reparentTo(render) return modelName def loadCollisionPolygon(self,modelName,attachGeom,firstPts, secondPts,thirdPts,fourthPts): modelName=CollisionNode(modelName) quadName=CollisionPolygon(Point3(firstPts),Point3(secondPts), Point3(thirdPts),Point3(fourthPts)) modelName.addSolid(quadName) modelName=attachGeom.attachNewNode(modelName) return modelName def loadCollisionTube(self,modelName,attachGeom,x0,y0,z0,x1,y1,z1, radius): modelName=CollisionNode(modelName) cylinder=CollisionTube(x0,y0,z0,x1,y1,z1,radius) modelName.addSolid(cylinder) modelName=attachGeom.attachNewNode(modelName) return modelName def homePage(self): self.introduction=False #self.setUphomePageSFX() self.introButton=DirectButton( image=("introduction.png"),scale=.5,pos=(-0.8,0,-0.65), relief=None,command=self.startIntro) self.introButton.setTransparency(TransparencyAttrib.MAlpha) self.startButton=DirectButton( image=("beginJourney.png"),scale=.5,pos=(+0.8,0,-0.65), relief=None, command=self.startJourney) self.startButton.setTransparency(TransparencyAttrib.MAlpha) self.cylinder=self.loadItems( "cylinder","wood.png",1,1,2,(9,-1.3,20.8)) self.hexagon=self.loadItems( "hexagon","wood.png",1,1,2.5,(9,1.4,20.8)) taskMgr.add(self.rotateMenuItems, 'rotateMenuItems') #def setUphomePageSFX(self): #self.volume=0 #self.circusInTheSky.setVolume(0) #self.circusInTheSky.setLoop(1) #self.circusInTheSky.play() #taskMgr.doMethodLater(.5, self.playCircusInTheSky, # 'Fade in Music', extraArgs = [self]) #def playCircusInTheSky(self,task): #self.volume+=.00125 #self.circusInTheSky.setVolume(self.volume) #return Task.cont def rotateMenuItems(self,task): self.speed=1.5 radius=.5 angle = radians(self.heading) x = cos(angle) * radius y = sin(angle) * radius z = sin(angle) * radius self.heading+=self.speed self.heading%=360 self.cylinder.setH(self.heading) self.hexagon.setH(self.heading) if self.introduction==True: self.cylinder.remove() self.hexagon.remove() return task.done return Task.cont def startJourney(self): #self.circusInTheSky.stop() self.introButton.destroy() self.startButton.destroy() self.initSetUpAssoc() #self.setUp3DEnvironmentIntro() ###########change here def setUp3DEnvironmentIntro(self): self.camera.setP(25) self.Enviro3DDummy=self.createDummyNode("3DEnviroDummy") self.textBlocks,self.color,self.keyBrightenComplete=[],0.01,False self.displayCards() self.displayHelpPanel() taskMgr.doMethodLater(.05,self.displayUserLocation, 'Track User', extraArgs = [self]) self.setUpDirectionalLight() self.displayPriorityArrow() self.accept("arrow_down",self.playFootSteps) self.accept("arrow_up",self.playFootSteps) self.enviroTextBlocks() self.Enviro3DSupportText() def enviroTextBlocks(self): self.enviroTextBlock1=( "1. Here is the priority queue for the shuffled cards") self.enviroTextBlock2=( "2. Toggle displays to show/hide windows") self.enviroTextBlock3=( "3. See your location in the plan") self.textBlocks+=(self.enviroTextBlock1,self.enviroTextBlock2, self.enviroTextBlock3) self.textPos=[(0,-.6),(-.6,.6),(.7,-.4)] def Enviro3DSupportText(self): for i in xrange(len(self.textBlocks)): self.titleText=OnscreenText(text=self.textBlocks[i], pos=self.textPos[i],scale=.058,fg=(1,1,1,1)) self.titleText.reparentTo(self.Enviro3DDummy) taskMgr.doMethodLater(.1, self.init3DActiveEnviro,'3DEnviroEntry') taskMgr.doMethodLater(.15,self.brightenKey,"brightenKey") def init3DActiveEnviro(self,task): self.keyButton=DirectButton( image = 'key.png',scale=(.5,.2,.15),color=(0,0,0,0),pos=(-.5,0,0), relief=None, command=self.setUp3DEnvironmentActive) self.keyButton.setTransparency(TransparencyAttrib.MAlpha) self.keyButton.reparentTo(self.Enviro3DDummy) self.keyButton['state'] = DGG.DISABLED return task.done def brightenKey(self,task): if self.keyBrightenComplete==False: self.brightenSpeed=0.025 if self.color<1: self.color+=self.brightenSpeed self.keyButton.setColor(0,0,0,self.color) return task.again else: self.entryText=OnscreenText(text="[Click the key to begin]", pos=(-.7,.13),scale=.058,fg=(1,1,1,1)) self.entryText.reparentTo(self.Enviro3DDummy) self.keyButton['state'] = DGG.NORMAL task.done else: task.done def setUp3DEnvironmentActive(self): base.useDrive() self.keyBrightenComplete=True self.Enviro3DDummy.removeNode() def setUpDirectionalLight(self): dlight = DirectionalLight('dlight') dlight.setColor(VBase4(0.8, 0.8, 0.5, 1)) dlnp = render.attachNewNode(dlight) dlnp.setHpr(0, -60, 0) render.setLight(dlnp) render.setShaderAuto() def startIntro(self): self.introduction=True self.introButton.destroy() self.startButton.destroy() self.setUpHelp() def setUpHelp(self): self.titleText=OnscreenText(text="Introduction", pos=(-0.85,0.85),scale=.1) self.text = TextNode('helpText') self.textBlocks() self.text.setText(self.textBlock1) textNodePath = aspect2d.attachNewNode(self.text) textNodePath.setScale(0.07) textNodePath.setPos(-1,0,0) self.text.setWordwrap(30.0) self.nextButton=DirectButton( image = 'arrow.png',scale=.15,pos=(0.8,0,-0.6),relief=None, command=self.nextPage ) self.nextButton.setTransparency(TransparencyAttrib.MAlpha) def textBlocks(self): self.textBlock1=("This project tests the effectiveness" +" of along established 'Method of loci', which is a" +" mnemonic device used for memory enhancement which uses" +" visualization to organize and recall information." +" We will be using this technique to memory a set of 13" +" cards (one suit)") self.textBlock2=( "STEP 1 \n\n We create rooms which are connected " + "and unique. These are provided for you." +"\n\n STEP 2 \n\n Associate each card with visual " +"objects (eg. 2 ---> Swan)" +"\n\n STEP 3 \n\n We 'place' the cards at specific " +"locations in sequence so relationship between " +"the location and item are made." +"\n\n STEP 4 \n\n Test the associations we've made") def nextPage(self): textNodePath = aspect2d.attachNewNode(self.text) textNodePath.setPos(-1,0,.5) self.nextButton.destroy() self.text.setText(self.textBlock2) self.nextButton=DirectButton( image = 'arrow.png',scale=.15,pos=(0.8,0,-0.6),relief=None, command=(self.clear)) self.nextButton.setTransparency(TransparencyAttrib.MAlpha) def clear(self): self.text.clearText() self.titleText.clearText() self.nextButton.destroy() self.homePage() def initSetUpAssoc(self): self.bk=OnscreenImage(image="bk.png",scale=(2,1,1)) self.inputs=dict() self.cardsPositions=[] self.imageListFaces,self.textObjs,self.entries=[],[],[] self.numCardsPage1=7 self.startCard=0 self.endCard=7 self.cardSet=0 self.callCards(self.startCard,self.endCard, self.cardSet) self.goAhead=[] self.button1=loader.loadMusic("button1.wav") self.assocTextBlocks() taskMgr.doMethodLater(.1, lambda task: self.createAssocHelperText( task,self.assocTextBlock1),'assocHelperText') def assocTextBlocks(self): self.assocTextBlock1=( "[Enter a word you strongly associated with each card]" +"\n Helpful Hint: Use less abstract and more descriptive words") self.assocTextBlock2=( "[That's great! Finish up the rest!]") def createAssocHelperText(self,task,text): self.updateFade() try: self.assocText.destroy() self.assocText=OnscreenText( text=text, pos=(0,-.2),scale=.05,fg=(0,0,0,self.fade)) except: self.assocText=OnscreenText( text=text, pos=(0,-.2),scale=.05,fg=(0,0,0,self.fade)) return task.again def callCards(self,startCard,endCard,cardSet,createEntries=1, scaleCards=(0.1,0.1,0.13)): for i in xrange(startCard,endCard): x=2*(i+1)/(self.numCardsPage1+1.0)-1-cardSet*1.75 self.cardsPositions.append(x) self.imageListFaces.append( OnscreenImage(image="%s"%(cardFaces[i]), pos=(x,0,.3),scale=scaleCards)) self.textObjs.append(OnscreenText(text=str(i),pos=(x,0))) #we use middle numbers as coordinates self.cardName=cardNames[i] if createEntries==1: self.createEntries(x, cardSet) def createEntries(self,x, cardSet): self.entries.append( DirectEntry(text = "" ,scale=.02,pos=(x-0.1,0.1,0.1), command=(lambda textEntered: self.storeAssoc (textEntered, x, cardSet)), numLines = 2)) def clearPage(self): for image in self.imageListFaces: image.destroy() for textObj in self.textObjs: textObj.destroy() for entry in self.entries: entry.destroy() for image in self.goAhead: image.destroy() self.assocText.destroy() self.clearBK() def clearBK(self): self.bk.destroy() def storeAssoc(self,textEntered, x, cardSet): index=int((x+cardSet*1.75+.75)/0.25) self.inputs[cardNames[index]]=textEntered self.greenDot=OnscreenImage( image="greenDot.png",pos=(x,0,.55),scale=(.25,1,.25)) self.greenDot.setTransparency(TransparencyAttrib.MAlpha) self.goAhead.append(self.greenDot) self.button1.play() if len(self.inputs)>6 and cardSet==0: taskMgr.remove('assocHelperText') taskMgr.doMethodLater(.1, lambda task: self.createAssocHelperText( task,self.assocTextBlock2),'assocHelperText') self.startCard=7 self.endCard=13 self.clearBK() self.cardSet=1 self.bk=OnscreenImage(image="bk.png",scale=(2,1,1)) self.callCards(self.startCard,self.endCard, self.cardSet) if len(self.inputs)>12 and cardSet==1: taskMgr.remove('assocHelperText') self.clearPage() self.setUp3DEnvironmentIntro() def startGame(self): self.bk.destroy()
class MainMenu: 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 mouseOverStart(self, frame, mousePos): self.startImage.setImage('Models/menu/Start2.png') self.startImage.setTransparency(TransparencyAttrib.MMultisampleMask) def mouseOutStart(self, frame, mousePos): self.startImage.setImage('Models/menu/Start.png') self.startImage.setTransparency(TransparencyAttrib.MMultisampleMask) def mouseOverExit(self, frame, mousePos): self.exitImage.setImage('Models/menu/Exit2.png') self.exitImage.setTransparency(TransparencyAttrib.MMultisampleMask) def mouseOutExit(self, frame, mousePos): self.exitImage.setImage('Models/menu/Exit.png') self.exitImage.setTransparency(TransparencyAttrib.MMultisampleMask) def hide(self): self.mainFrame.hide() self.menuFrame.hide() def show(self): self.mainFrame.show() self.menuFrame.show() def start(self): self.hide() self.startImage.destroy() self.exitImage.destroy() self.main.startGame() def __del__(self): self.start.destroy() self.exit.destroy() self.mainFrame.destroy()