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 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 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()
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) self.cfg = cfgdict("data/default_config.cfg") globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(int(self.cfg["general"]["framerate"])) #base.setFrameRateMeter(int(self.cfg["general"]["debug"])) self.props = WindowProperties() self.props.setSize(tuple(self.cfg["general"]["resolution"])) self.props.setFullscreen(int(self.cfg["general"]["fullscreen"])) self.props.setCursorHidden(True) self.fullscreen = int(self.cfg["general"]["fullscreen"]) #props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(self.props) base.disableMouse() base.win.setClearColor((0, 0, 0, 0)) self.inputs = Inputs(self.cfg["key"]) #cats=["mainmenu", "parts", "enemies", "items"] #for cat in cats: makeWireframe(cat) self.hud = HUD(self) self.transition = Transitions(loader) self.parts_models = getParts("data/models/egg/parts/parts") self.enemy_models = getParts("data/models/egg/enemies/enemies") self.item_models = getParts("data/models/egg/items/items") sounds = [ "break", "error", "explosion", "hit_a", "hit_b", "hit_c", "scare", "select_a", "select_b", "splurt_a", "splurt_b", "swallow", "step_enemy_a", "step_enemy_b", "step_enemy_c", "step_player", "turn", "projectile_a", "projectile_b", "projectile_c", ] self.sounds = {} for sound in sounds: self.sounds[sound] = loader.loadSfx("data/sound/" + sound + ".wav") self.sounds["step_player"].setVolume(0.3) self.act = False if self.cfg["general"]["fx"] == 1: render.setShaderAuto() aspect2d.setShaderAuto() filters = CommonFilters(base.win, base.cam) filters.setBloom(blend=(0.1, 0.1, 0.1, 0.0), mintrigger=0.0, maxtrigger=0.1, desat=0.0, intensity=0.6, size="small") #self.startGame() def startGame(self): self.hud.output.append("...") self.hud.output.append("You wake up, head on the keyboard.") self.hud.output.append("Where is everybody?") render.node().removeAllChildren() self.mode = "game" self.delay = 0 self.map = Map(self, 1) self.player = Player(self.map.start[0], self.map.start[1], 2) self.transition.setFadeColor(0, 0, 0) self.transition.fadeIn(2) d = DirectionalLight("d") dn = render.attachNewNode(d) self.actions = [] base.camera.setHpr(0, 0, 0) base.camera.setPos(0, 0, 0) drinks = ["red", "yellow", "orange", "green", "blue", "purple"] types = ["health", "cure", "poison", "blind", "improve", "warmth"] self.drinks = {} for drink in drinks: rt = choice(types) types.remove(rt) self.drinks[drink] = [rt, False] render.setLight(dn) def nextLevel(self): render.node().removeAllChildren() render.hide() self.transition.setFadeColor(0, 0, 0) self.transition.fadeOut(1) self.delay = 0 self.actions = [] self.map = Map(self, self.map.level + 1) self.hud.output.append("You reach the " + str(20 - self.map.level) + "th floor.") self.player.place = [self.map.start[0], self.map.start[1] - 1, 2] self.player.prev_place = self.player.place[:] self.player.pos = [self.map.start[0], self.map.start[1] - 1] render.show() self.player.camera.node.reparentTo(render) d = DirectionalLight("d") dn = render.attachNewNode(d) render.setLight(dn) self.transition.fadeIn(1) self.mode = "game" def mainMenu(self, task): if self.running: self.mcp[3] += 1 self.mcp[2] = 8 + (sin(self.mcp[3] / 50) * 7) base.camera.setPos(self.mcp[0], self.mcp[1], self.mcp[2]) self.buildingmodel["tower"][0].setHpr(self.mcp[3], 0, 0) self.buildingmodel["tower"][1].setHpr(self.mcp[3], 0, 0) if self.inputs.buttons["quit"]: self.running = False if self.inputs.buttons["stats"]: self.inputs.buttons["stats"] = False self.bgsong.stop() self.sounds["select_b"].play() base.camera.setPos(0, 0, 0) self.hud.loadGameHud() self.startGame() self.bgsong = loader.loadSfx("data/music/LEVEL1.ogg") self.bgsong.setVolume(0.3) self.bgsong.setLoop(True) self.bgsong.play() self.taskMgr.add(self.loop, "main_loop") return False return task.cont print("bye!") exit() def load(self): self.running = True self.actions = [] self.bgsong = loader.loadSfx("data/music/THEME.ogg") self.bgsong.setVolume(0.5) self.bgsong.setLoop(True) self.bgsong.play() self.buildingmodel = getParts("data/models/egg/mainmenu/mainmenu") self.buildingmodel["tower"][0].reparentTo(render) self.buildingmodel["tower"][1].reparentTo(render) d = DirectionalLight("d") dn = render.attachNewNode(d) render.setLight(dn) self.mcp = [0, -20, 8, 1200] self.taskMgr.add(self.mainMenu, "main_menu") def loop(self, task): if self.running: self.hud.update() if self.mode == "game": if self.inputs.buttons["quit"]: self.running = False if self.player.stats.status == "Dying": self.hud.output.append("You died.") self.mode = "gameover" self.sounds["explosion"].play() taskMgr.add(die()) else: self.delay -= 1 if self.delay <= 0: self.delay = 0 if len(self.actions) > 0: for action in self.actions: a = action[0](action[1]) if a == 1: self.actions.remove(action) else: self.input() self.update() elif self.mode == "gameover": base.camera.setH(base.camera.getH() + 2) base.camera.setZ(base.camera.getZ() - 0.001) # Hud input, choices, etc. elif self.mode == "inventory": close = False if self.inputs.buttons["return"]: close = True else: abc = "abcdefghijklmnopqrstuvwxyz0123456789" cc = 100 if not self.inputs.raw_key == None: if self.inputs.raw_key in abc: for l, letter in enumerate(abc): if self.inputs.raw_key == letter: cc = l if cc < len(self.hud.choices): item = self.hud.choices[cc] if self.hud.verb == "inventory": pass elif self.hud.verb == "drop": f = self.player.drop(item) if f: self.act = True elif self.hud.verb == "throw": self.player.throw(item) self.act = True else: f = self.hud.choices[cc].use(self.player) if f: self.act = True close = True if close: self.mode = "game" self.hud.inventory[0].setText("") self.hud.choices = [] self.inputs.buttons["return"] = False elif self.mode == "restart": self.startGame() self.inputs.raw_key = None return task.cont print("bye!") exit() def input(self): act = self.act tile = self.map.grid[self.player.pos[1]][self.player.pos[0]] if act == False: if self.inputs.buttons["turn_left"]: self.sounds["turn"].play() self.player.turn(1) self.actions.append((self.player.turn, 1)) elif self.inputs.buttons["turn_right"]: self.sounds["turn"].play() self.player.turn(-1) self.actions.append((self.player.turn, -1)) elif self.inputs.buttons["forward"]: en = self.player.move(-1) if not en == "cancel": if en == "melee": self.delay = 10 self.player.stats.attack(self.player.target.stats, True) self.player.target.switchFrame("hurt") self.transition.setFadeColor(0.1, 0.1, 0.1) self.transition.fadeOut(0.1) self.transition.fadeIn(0.01) self.hud.update() l = "_a", "_b", "_c" self.sounds["hit" + choice(l)].play() act = True else: self.actions.append((self.player.move, -1)) act = True elif self.inputs.buttons["backward"]: self.sounds["turn"].play() self.player.turn(1) self.actions.append((self.player.turn, 1)) self.player.turn(1) self.actions.append((self.player.turn, 1)) elif self.inputs.buttons["fire"]: f = self.player.fire() if f: act = True elif self.inputs.buttons["wait"]: act = True self.sounds["turn"].play() self.delay = 10 self.hud.output.append("You wait.") elif self.inputs.buttons["take"]: if not tile.item == None: abc = "abcdefghijklmnopqrstuvwxyz" if len(self.player.stats.inventory) < len(abc): self.sounds["select_b"].play() tile.item[0].removeNode() i = tile.item[1] self.player.stats.inventory.append(i) self.hud.output.append("You found a " + i.name) tile.item = None act = True else: self.hud.output.append("You can't carry any more.") self.delay = 10 elif self.inputs.buttons["stairs_down"]: if tile.c == "<": self.nextLevel() self.inputs.buttons["stairs_down"] = False elif self.inputs.buttons["fullscreen"]: if self.fullscreen: self.fullscreen = 0 else: self.fullscreen = 1 self.props.setFullscreen(int(self.fullscreen)) base.win.requestProperties(self.props) self.inputs.buttons["fullscreen"] = False else: verbs = "inventory", "drop", "throw", "eat", "quaff", "wield", "stats", "help" for i in self.inputs.buttons: if self.inputs.buttons[i]: if i in verbs: self.mode = "inventory" self.hud.inv(self.player, i) self.inputs.buttons[i] = False if act: self.act = False self.player.stats.turn() for e, enemy in enumerate(self.map.enemies): if self.player.stats.speedboost <= 0 or randint(0, 2) == 0: en = enemy.plan(self, e) if en: enemy.stats.turn() self.actions.append((enemy.move, self)) self.player.stats.updateStats() def update(self): self.player.update() for enemy in self.map.enemies: enemy.update(self)
class EffectsManager: """Manager to control the game visual effects.""" def __init__(self): base.enableParticles() # noqa: F821 render.setShaderAuto() # noqa: F821 self._explosion_lights = self._set_explosion_lights() self._transition = Transitions(loader) # noqa: F821 self._transition.setFadeColor(0, 0, 0) self.stench_effect = Stench() self.love_fog = LoveFog() filters = CommonFilters(base.win, base.cam) # noqa: F821 filters.setBloom(size="large", mintrigger=0.8, intensity=2.1) def _set_explosion_lights(self): """Prepare three explosion lights. Build a list-pool of light objects to be used in different explosions. Returns: list: List of lights to be used for explosions. """ lights = [] for num in range(3): light = PointLight("explosion_light_" + str(num)) light.setColor((1, 0.9, 0.55, 1)) light.setAttenuation((0, 0, 1)) light_np = render.attachNewNode(light) # noqa: F821 light_np.setPos(0, 0, -5) render.setLight(light_np) # noqa: F821 lights.append(light_np) return lights def bomb_explosion(self, parent): """Prepare a bomb explosion effect for the given object. Args: parent (object): Must include "model" property. Returns: BombExplosion: Hand bomb explosion effect object. """ return BombExplosion(parent) def burn_smoke(self, parent): """Prepare a burning object smoke effect. Args: parent (object): Must include "id" and "model" properties. Returns: BurnSmoke: Burning object smoke effect. """ return BurnSmoke(parent) def explosion(self, parent): """Prepare an explosion effect for the given object. Args: parent (object): Must include "id" and "model" properties. Returns: Explosion: Explosion effect object. """ return Explosion(self._explosion_lights, parent, "explode_fire", 0.9) def explosion_big(self, parent): """Prepare a big explosion effect for the given object. Args: parent (object): Must include "id" and "model" properties. Returns: Explosion: Explosion effect object. """ return Explosion(self._explosion_lights, parent, "explode_fire2", 1.9) def fade_in_screen(self, task): """Smoothly fill the screen with natural colors.""" self._transition.fadeIn(3) return task.done def fade_out_screen(self, task): """Smoothly fill the screen with black color.""" self._transition.fadeOut(3) return task.done
class InterfaceMenuNiveaux(ShowBase): def __init__(self): self.frames = [] self.dao = DAO_Oracle() # remplir les maps seulement si la connexion Oracle est fonctionnelle if self.dao.getConnexionState(): self.dao.fill_dto_with_db() else: self.afficherMessagesOracle() # Background image self.background = OnscreenImage(parent = render2d , image = '../asset/Menu/tank.jpg') #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) mapInfo = [] for i in range(len(DTO.maps)): mapInfo.append((DTO.maps[i].titre,DTO.maps[i].id)) self.controlTextScale = 0.10 self.controlBorderWidth = (0.005,0.005) self.scrollItemButtons = self.createAllItems(mapInfo) verticalOffsetControlButton = 0.225 verticalOffsetCenterControlButton = -0.02 self.myScrolledListLabel = DirectScrolledList( # bouton Haut et ses parametres decButton_pos = (0.0,0.0, verticalOffsetControlButton + verticalOffsetCenterControlButton), decButton_text = "Haut", decButton_text_scale = 0.08, decButton_borderWidth = (0.0025,0.0025), decButton_frameSize = (-0.35, 0.35, -0.0375, 0.075), decButton_text_fg = (0.15, 0.15, 0.75, 1.0), # decButton_clickSound = ("../asset/Menu/btn-Son.mp3"), # bouton bas et ses parametres incButton_pos = (0.0, 0.0, -0.625 - verticalOffsetControlButton + verticalOffsetCenterControlButton), incButton_text = "Bas", incButton_text_scale = 0.08, incButton_borderWidth = (0.0025, 0.0025), incButton_frameSize = (-0.35, 0.35, -0.0375, 0.075), incButton_text_fg = (0.15, 0.15, 0.75, 1.0), # incButton_clickSound = ("../asset/Menu/btn-Son.mp3"), pos = (0, 0, 0.5), items = self.scrollItemButtons, # nombre de map visible par 'Scroll' ici c'est 3 numItemsVisible = 5, forceHeight = 0.175, frameSize = (-1.05, 1.05, -0.95, 0.325), frameColor = (0.5, 0.5, 0.5, 0.75), itemFrame_pos = (0.0, 0.0, 0.0), itemFrame_frameSize = (-1.025, 1.025, -0.775, 0.15), itemFrame_frameColor = (0.35, 0.35, 0.35, 0.75), itemFrame_relief = 1, ) self.quitterButton = DirectButton( # les 4 parametres indiques les differents types d'état que le bouton px avoir #( lorsque tu survole lorsque tu clique etc) text = ("Quitter", "Etes-Vous Sur?","Au Revoir!!","disabled"), text_scale = self.controlTextScale, borderWidth = self.controlBorderWidth, relief = 2, pos = (0.0,0.0, -0.75), frameSize = (-0.5,0.5,-0.625, 0.105), command = lambda : sys.exit(), ) #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/loading.jpg") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/demarrage.mp3") # creation du bouton avec le nom de la map def createItemButton (self,nomMap,idMap): return DirectButton( text = nomMap, text_scale = self.controlTextScale, borderWidth = self.controlBorderWidth, relief = 2, frameSize = (-1.0,1.0,-0.0625,0.105), command = lambda: self.chargerJeu(idMap,nomMap) ) #Creation de la Map Aleatoire def createAllItems(self,mapsInfo): scrollItemButtons = [self.createItemButton(u'*-> Map au Hasard <-*',None)] for mapInfo in mapsInfo: pass scrollItemButtons.append(self.createItemButton(self.formatText(mapInfo[0]),mapInfo[1])) return scrollItemButtons # format du texte a mettre dans le bouton def formatText(self,text,maxLength = 30): return text if len(text) <= maxLength else text[0:maxLength] + '...' def chargerJeu(self,idMap, nomMap): #loader les données dans le DTO avec la bonne map DTO.idMap = idMap # pour éviter de refaire une requête juste pour connaître le nom de la map DTO.nomMap = nomMap #On démarre! if self.dao.getConnexionState(): transition = "DemarrerConnexion" else: transition = "DemarrerConnexion" Sequence(Func(lambda : self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda : messenger.send(transition)), Wait(0.2), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda : self.transition.irisIn(0.2)) ).start() def afficherMessagesOracle(self): height = 0.15 width = 0.30 textSize = 0.05 message = "Attention! La connexion au serveur Oracle n'est pas établie! Les choix de niveaux n'ont pas pu être chargés!" message = textwrap.fill(message, 25) positionDepart = Point3(-1.37,0,1.5) positionArrivee = Point3(-1.37,0,0.3) frameErreur = DirectFrame(text=message, pos = positionDepart, frameColor=(255,255,255,1), frameSize=(-width,width,-height,height)) frameErreur["text_scale"] = (textSize,textSize) frameErreur["text_fg"] = (255,0,0,1) frameErreur["text_pos"] = (0,0.1) intervalEntrer = frameErreur.posInterval(1.5, positionArrivee, startPos=positionDepart) sequence = Sequence( intervalEntrer ) sequence.start() self.frames.append(frameErreur) def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) #On cache les menus self.background.hide() for item in self.scrollItemButtons: item.hide() self.quitterButton.hide() self.myScrolledListLabel.hide() for item in self.frames: item.hide()
class InterfaceConnexion(): def __init__(self): #utilitaires self.analyse = AnalyseDTOJoueur() self.labels = [] self.drs = [] self.sequences = [] self.tankModels = [] # champs de textes #le frame du haut self.ajouterTopFrame() # Background image # on a commenté le background, pcq ca cachait les scènes pour les deux chars # self.background = OnscreenImage(parent = render2d , image = '../asset/Menu/menuLogin.png', ) #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) self.controlTextScale = 0.10 self.controlBorderWidth = (0.005, 0.005) #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/loading.jpg") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/demarrage.mp3") self.testerConnexion() def connexion(self, joueur): ordre = joueur + 1 # vérifier si le joueur n'est pas déjà connecté if (joueur == 0 and DTO.joueur1 != None) or (joueur == 1 and DTO.joueur2 != None): self.labelMessage.setText( "ATTENTION! Joueur %d est DÉJÀ connecté!" % (ordre)) return if joueur == 0: user = self.entryUser1.get() pw = self.entryMDP1.get() else: user = self.entryUser2.get() pw = self.entryMDP2.get() # vérifier que le joueur ne se connecte pas deux fois if (DTO.joueur1 != None and DTO.joueur1.nom == user) or (DTO.joueur2 != None and DTO.joueur2.nom == user): self.labelMessage.setText( "ATTENTION! L'usager %s est DÉJÀ connecté!" % (user)) return # faire une connexion à la bd self.dao = DAO_Oracle() connecte = self.dao.validerUsager(user, pw, joueur) # ajuster le message de l'état de connexion des joueurs if connecte: self.labelMessage.setText("Joueur %d est connecté!" % (ordre)) if joueur == 0: self.ajouterChar(joueur, DTO.joueur1.couleur) elif joueur == 1: self.ajouterChar(joueur, DTO.joueur2.couleur) self.afficherMessagesSanitizer(joueur) if DTO.joueur1 != None and DTO.joueur2 != None: self.labelMessage.setText("Les deux joueurs sont connectés!") self.ajouterMiddleFrame() self.ajouterBottomFrame() if len(DTO.joueurs) == 0: DTO.joueurs.append(DTO.joueur1) DTO.joueurs.append(DTO.joueur2) indexJoueur = joueur else: self.labelMessage.setText("Erreur de login pour Joueur %d " % (ordre)) def ajouterTopFrame(self): #le frame du top self.frameTop = DirectFrame(text="") self.frameTop.reparentTo(base.a2dTopLeft) #les 4 labels de joueurs et mot de passe labelJoueur1 = OnscreenText(text='Joueur 1', pos=(0.25, -0.10), scale=0.07, bg=(255, 255, 255, 1), frame=(0, 0, 0, 1)) labelMotDePasse1 = OnscreenText(text='Mot de passe 1', pos=(0.25, -0.30), scale=0.07, bg=(255, 255, 255, 1), frame=(0, 0, 0, 1)) labelJoueur2 = OnscreenText(text='Joueur 2', pos=(2.00, -0.10), scale=0.07, bg=(255, 255, 255, 1), frame=(0, 0, 0, 1)) labelMotDePasse2 = OnscreenText(text='Mot de passe 2', pos=(2.00, -0.30), scale=0.07, bg=(255, 255, 255, 1), frame=(0, 0, 0, 1)) labelJoueur1.reparentTo(self.frameTop) labelMotDePasse1.reparentTo(self.frameTop) labelJoueur2.reparentTo(self.frameTop) labelMotDePasse2.reparentTo(self.frameTop) #les quatre boîtes de saisie de texte #pour le joueur 1 self.entryUser1 = DirectEntry(text="", scale=.07, pos=(0.65, 0.0, -0.10), numLines=1, focus=1) self.entryUser1.reparentTo(self.frameTop) self.entryMDP1 = DirectEntry(text="", scale=.07, pos=(0.65, 0.0, -0.3), command=lambda x=1: self.connexion(0), numLines=1, focus=1, obscured=True) self.entryMDP1.reparentTo(self.frameTop) #pour le joueur 2 self.entryUser2 = DirectEntry(text="", scale=.07, pos=(2.4, 0.0, -0.10), numLines=1, focus=1) self.entryUser2.reparentTo(self.frameTop) self.entryMDP2 = DirectEntry(text="", scale=.07, pos=(2.4, 0.0, -0.3), command=lambda x=1: self.connexion(1), numLines=1, focus=1, obscured=True) self.entryMDP2.reparentTo(self.frameTop) self.frameConnecte = DirectFrame(text="") self.frameConnecte.reparentTo(self.frameTop) #label pour le message height = 0.10 self.frameMessage = DirectFrame(text="", frameColor=(255, 255, 255, 0.23), frameSize=(-1.2, 1.2, -height, height)) self.frameMessage.setPos(0, 0, 0.55) self.labelMessage = OnscreenText(text='Aucun message', pos=(0, 0), scale=0.07, align=TextNode.ACenter, mayChange=True) self.labelMessage.reparentTo(self.frameMessage) def ajouterChar(self, ordre, couleur): # https://www.panda3d.org/manual/index.php/File:DisplayRegion_1.jpg if ordre == 0: dr2 = base.win.makeDisplayRegion(0, 0.30, 0, 0.5) elif ordre == 1: dr2 = base.win.makeDisplayRegion(0.70, 1, 0, 0.5) dr2.setClearColor(VBase4(0.41, 0.41, 0.41, 0)) dr2.setClearColorActive(True) dr2.setClearDepthActive(True) render2 = NodePath('render') cam2 = render2.attachNewNode(Camera('cam2')) dr2.setCamera(cam2) cam2.setPos(-22.5, -387.3, 58.1999) env = loader.loadModel("box.egg") env.setTransparency(TransparencyAttrib.MAlpha) env.setDepthTest(False) env.setDepthWrite(False) env.reparentTo(render2) # ajouter le tank size = 50 tank = Actor("../asset/Tank/tank") tank.setScale(size, size, size) tank.setColorScale(couleur[0], couleur[1], couleur[2], 1) if ordre == 0: tank.setHpr(270.0, 0.0, 0.0) elif ordre == 1: tank.setHpr(90.0, 0.0, 0.0) tank.reparentTo(env) #faire avancer le tank if ordre == 0: intervalAvancer = tank.posInterval(2, Point3(-10, 4, 8), startPos=Point3(-200, 4, 8)) elif ordre == 1: intervalAvancer = tank.posInterval(2, Point3(-10, 4, 8), startPos=Point3(180, 4, 8)) # faire tourner le tank (interval) duree = 3.0 if ordre == 0: intervalTourner = tank.hprInterval(duree, Vec3(-90, 0, 0)) else: intervalTourner = tank.hprInterval(duree, Vec3(450, 0, 0)) sequenceAvancer = Sequence(intervalAvancer) sequenceTourner = Sequence(intervalTourner) sequence = Sequence(sequenceAvancer, Func(sequenceTourner.loop)) sequence.start() self.drs.append(dr2) self.sequences.append(sequenceTourner) self.tankModels.append([ordre, tank]) def ajouterMiddleFrame(self): height = 0.15 self.frameMiddle = DirectFrame(frameColor=(255, 255, 255, 0.23), frameSize=(-1.2, 1.2, -height, height)) self.frameMiddle.setPos(0, 0, 0.25) #calculer les noms des deux joueurs joueur1 = self.analyse.calculerNom(DTO.joueur1) joueur2 = self.analyse.calculerNom(DTO.joueur2) dist = 0.075 labelVS1 = OnscreenText(text=joueur1, pos=(0, 0.05), scale=0.07, align=TextNode.ACenter, mayChange=True) labelVS1.reparentTo(self.frameMiddle) labelVS = OnscreenText(text='VS', pos=(0, 0.05 - dist), scale=0.07, align=TextNode.ACenter, mayChange=True) labelVS.reparentTo(self.frameMiddle) labelVS2 = OnscreenText(text=joueur2, pos=(0, 0.05 - dist * 2), scale=0.07, align=TextNode.ACenter, mayChange=True) labelVS2.reparentTo(self.frameMiddle) def combattre(self): # freezer le bouton Combattre scaleBouton = self.b.getScale().getX() coordonnees = [] tankH1 = self.tankModels[0][1].getH() tankH2 = self.tankModels[1][1].getH() coordonnees.append(tankH1) coordonnees.append(tankH2) for sequence in self.sequences: sequence.finish() cpt = 0 sequenceTourner = None dureeTourner = 3.0 for listTank in self.tankModels: ordre = listTank[0] tank = listTank[1] tank.setH(coordonnees[cpt]) if ordre == 0: intervalTourner = tank.hprInterval(dureeTourner, Vec3(-90, 0, 0)) elif ordre == 1: intervalTourner = tank.hprInterval(dureeTourner, Vec3(450, 0, 0)) sequenceTourner = Sequence(intervalTourner) sequenceTourner.start() cpt = cpt + 1 self.b.setScale(scaleBouton) sequence = Sequence(Func(lambda: sequenceTourner.start()), Wait(dureeTourner), Func(lambda: self.ajouterTextVS()), Wait(5.5), Func(lambda: self.chargerJeu())) sequence.start() def analyserPositionChars(self): arrete = False arrete = self.tankModels[0][1].getH( ) == -90 and self.tankModels[1][1].getH() == 450 return arrete def ajouterTextVS(self): message = DTO.joueur1.nom + " VS " + DTO.joueur2.nom self.labelVS = OnscreenText(text=message, shadow=(0, 0, 0, 1), pos=(0, 0), frame=(0, 0, 0, 1), scale=0.14, align=TextNode.ACenter, mayChange=False, bg=(0, 255, 0, 0.5), fg=(255, 255, 255, 1)) #faire l'animation du texte scaleDebut = 1.0 scaleFin = 2.0 duree = 2.0 # #les deux intervals opposés (grandir vs rapetir) intervalRapetir = self.labelVS.scaleInterval( duree, Vec3(scaleDebut, scaleDebut, scaleDebut)) intervalGrossir = self.labelVS.scaleInterval( duree, Vec3(scaleFin, scaleFin, scaleFin)) # # # la loop qui dure toujours sequence = Sequence(intervalGrossir, intervalRapetir) sequence.loop() def afficherMessagesSanitizer(self, joueur): if joueur == 0: messagesErreurs = DTO.messagesErreurs1 elif joueur == 1: messagesErreurs = DTO.messagesErreurs2 for i in range(len(messagesErreurs)): height = 0.15 width = 0.4 textSize = 0.05 if joueur == 0: positionArrivee = Point3(-1.1, 0, -0.1) positionDepart = Point3(-2.5, 0, -0.1) elif joueur == 1: positionArrivee = Point3(1.1, 0, -0.1) positionDepart = Point3(2.5, 0, -0.1) message = messagesErreurs[i].retournerMessage() message = textwrap.fill(message, 33) self.frameErreur = DirectFrame(text=message, pos=positionDepart, frameColor=(255, 255, 255, 0.5), frameSize=(-width, width, -height, height)) self.frameErreur["text_scale"] = (textSize, textSize) self.frameErreur["text_fg"] = (255, 0, 0, 1) self.frameErreur["text_pos"] = (0, 0.1) scaleFin = 0 intervalEntrer = self.frameErreur.posInterval( 2, positionArrivee, startPos=positionDepart) intervalRapetisser = self.frameErreur.scaleInterval( 1, Vec3(1, 1, scaleFin)) tempsAttente = i * 8 sequence = Sequence(Wait(tempsAttente), intervalEntrer, Wait(5), intervalRapetisser) sequence.start() def ajouterBottomFrame(self): #variables de positionnement height = 0.15 width = 0.6 dist = 0.1 debut = 0.025 #frame combattre self.frameBottom = DirectFrame(text="", frameColor=(255, 255, 255, 0.23), frameSize=(-width, width, -height, height)) self.frameBottom.setPos(0, 0, -0.10) labelCombattre = OnscreenText(text='Combattrons dans', pos=(0, debut), scale=0.07, align=TextNode.ACenter, mayChange=True) labelCombattre.reparentTo(self.frameBottom) nomNiveau = DTO.nomMap if nomNiveau == None: nomNiveau = "" labelNiveau = OnscreenText(text=nomNiveau, pos=(0, debut - dist), scale=0.07, align=TextNode.ACenter, mayChange=True) # labelNiveau = OnscreenText(text = DTO.mapSelectionne.titre, pos = (0, debut-dist), scale = 0.07 , align=TextNode.ACenter, mayChange = True) labelNiveau.reparentTo(self.frameBottom) height = 0.10 width = 0.6 dist = 0.1 debut = -0.025 #frame joueur favorisé #déterminer le joueur favorisé if DTO.joueurs[0].level > DTO.joueurs[1].level: joueurFavorise = DTO.joueurs[0].nom DTO.joueurs[0].favori elif DTO.joueurs[1].level > DTO.joueurs[0].level: joueurFavorise = DTO.joueurs[1].nom DTO.joueurs[1].favori = True else: joueurFavorise = None if joueurFavorise == None: joueurFavorise = "Aucun joueur favorisé!" else: # joueurFavorise = self.analyse.calculerNom(DTO.joueurs[0]) joueurFavorise += " est favorisé!" self.frameFavori = DirectFrame(text="", frameColor=(24, 24, 0, 1), frameSize=(-width, width, -height, height)) self.frameFavori.setPos(0, 0, -0.40) labelFavori = OnscreenText(text=joueurFavorise, pos=(0, debut), scale=0.06, align=TextNode.ACenter, mayChange=True) labelFavori.reparentTo(self.frameFavori) # bouton combattre self.b = DirectButton(text=("COMBATTRE!"), scale=.07, frameSize=(-6, 6, -3, 3), pos=(0, 0, -0.65), command=self.combattre) self.b.reparentTo(self.frameBottom) # interval de "battements de coeur" pour le bouton Combattre # les paramètres de la séquence scaleDebut = 0.03 scaleFin = 0.05 self.b.setScale(scaleDebut, scaleDebut, scaleDebut) duree = 0.75 #les deux intervals opposés (grandir vs rapetir) intervalGrossir = self.b.scaleInterval( duree, Vec3(scaleDebut, scaleDebut, scaleDebut)) intervalRapetir = self.b.scaleInterval( duree, Vec3(scaleFin, scaleFin, scaleFin)) # la loop qui dure toujours sequence = Sequence(intervalRapetir, intervalGrossir) sequence.loop() self.sequences.append(sequence) def chargerJeu(self): #loader les données dans le DTO avec la bonne map self.dao = DAO_Oracle() self.dao.fillGame(DTO.idMap) #On démarre! Sequence( Func(lambda: self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda: messenger.send("DemarrerPartie")), Wait( 0.2 ), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda: self.transition.irisIn(0.2))).start() def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) # #On cache les menus # self.background.hide() self.frameTop.hide() self.frameBottom.hide() self.frameMiddle.hide() self.frameMessage.hide() self.frameFavori.hide() self.labelVS.hide() for dr in self.drs: base.win.removeDisplayRegion(dr) def testerConnexion(self): dao = DAO_Oracle() connecte = dao.connectDB() if not connecte: self.labelMessage.setText( "Aucune connexion avec la base de données...")
class Play(DirectObject): def __init__(self, parent): #Turn off default mouse control base.disableMouse() base.setFrameRateMeter(True) #globalClock = ClockObject.getGlobalClock() #globalClock.setMode(ClockObject.MLimited) #globalClock.setFrameRate(1000) #Set windows properties self.props = WindowProperties() self.props.setCursorHidden(True) #props.setFullscreen(1) #props.setSize(int(base.pipe.getDisplayWidth()), int(base.pipe.getDisplayHeight())) self.props.setMouseMode(WindowProperties.MRelative) base.win.requestProperties(self.props) self.transition = Transitions(loader) self.transition.setFadeColor(0,0,0) self.parent = parent base.accept("escape", self.togglePause) self.setupSounds() self.startLevel(0, True) self.task = taskMgr.add(self.update, "updateTask") def fadeOut(self): self.transition.fadeOut(1) def fadeIn(self): self.transition.irisIn(1) def togglePause(self): if self.parent.paused: self.props.setCursorHidden(True) base.win.requestProperties(self.props) base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2) taskMgr.add(self.task) self.parent.paused = False self.parent.continueImage.hide() self.parent.restartImage.hide() self.parent.exitImage.hide() self.parent.mainFrame.hide() self.playingBGM.setTime(self.bgmTime) self.playingBGM.play() else: self.props.setCursorHidden(False) base.win.requestProperties(self.props) taskMgr.remove(self.task) self.parent.paused = True self.parent.mainFrame.show() self.parent.continueImage.show() self.parent.restartImage.show() self.parent.exitImage.show() self.bgmTime = self.playingBGM.getTime() self.playingBGM.stop() def chaseBGM(self, chasing = False): if chasing and self.playingBGM != self.bgFast: self.playingBGM.stop() self.playingBGM = self.bgFast self.bgmTime = 0 self.playingBGM.play() elif not chasing and self.playingBGM != self.bgSlow: self.playingBGM.stop() self.playingBGM = self.bgSlow self.bgmTime = 0 self.playingBGM.play() def initModels(self): self.map = MapGen(self) # self.player = Player(self) # self.level = Level() self.enemies = [] def transitionFunc(self, level, next = False): tSequence = Sequence(Func(self.fadeOut), Wait(1), Func(self.startLevel, level, next), Func(self.fadeIn)) tSequence.start() #level number, next = true if next level (false = respawning) def startLevel(self, level, next = False): # per pixel lighting render.clearLight() render.setShaderAuto() try: self.level.initLight() except AttributeError: pass try: self.player.initHandLight() except AttributeError: pass # """ # render.clearLight() # render.setShaderAuto() # """ # self.map = MapGen(self) # self.player = Player(self) # self.level = Level() # self.enemies = [] if next: for node in render.getChildren(): node.removeNode() for node in base.camera.getChildren(): if node.getName() != 'cam': print node.getName() node.removeNode() else: #Clear render self.player.clearItems() #If next level, load level map #and initialize enemies if next: level += 1 for node in render.getChildren(): node.removeNode() self.player = Player(self) self.level = Level() self.enemies = [] self.player.level = level self.level.loadLevel(level) for enemy in self.level.enemies: enemySpawn = Enemy( self, enemy[0], enemy[1] ) self.enemies.append(enemySpawn) playerPos = self.level.playerPos #level.spawnPos walls = self.level.numWalls lights = self.level.numLights #Spawn player using spawn (spawn pos, max walls, max lights) self.player.spawn(playerPos,walls,lights) if not next: for enemy in self.enemies: enemy.respawn() self.playingBGM = self.bgSlow self.playingBGM.play() if next: self.setupCollisions() def die(self, level, next = False): self.transitionFunc(level, next) def setupCollisions(self): #Make a collision traverser, set it to default base.cTrav = CollisionTraverser() base.itemTrav = CollisionTraverser() base.pusher = CollisionHandlerPusher() base.cHandler = CollisionHandlerEvent() base.queue = CollisionHandlerQueue() base.eQueue = CollisionHandlerQueue() #Set the pattern for the event sent on collision base.cHandler.setAgainPattern("%fn-again-%in") base.cHandler.setInPattern("%fn-into-%in") base.cHandler.setOutPattern("%fn-out-%in") self.player.initCollisions() for enemy in self.enemies: enemy.initCollisions(self.player) #base.cTrav.showCollisions(render) #Set up BGM def setupSounds(self): ######################slow music########################## self.bgSlow = base.loadMusic("sounds/slow.ogg") self.bgSlow.setLoopCount(0) ######################fast music############################ self.bgFast = base.loadMusic("sounds/fast.ogg") self.bgFast.setLoopCount(0) self.playingBGM = self.bgSlow def update(self, task): dt = globalClock.getDt() self.player.update(globalClock.getDt()) if self.player.newLevel: return task.cont for enemy in self.enemies: enemy.update(globalClock.getDt(), self.player) return task.cont
class Engine(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() props = WindowProperties() props.setTitle('Test') self.win.requestProperties(props) # self.render.setAntiAlias(AntialiasAttrib.MAuto) self.transitions = Transitions(self.loader) self.transitions.setFadeColor(0, 0, 0) self.filters = CommonFilters(self.win, self.cam) # self.filters.setCartoonInk() self.filters.setBlurSharpen(1) # self.filters.setVolumetricLighting(self.render) # self.buffer = self.win.makeTextureBuffer("Post-processing buffer", self.win.getXSize(), self.win.getXSize()) # print self.buffer.getYSize() # self.texture = self.buffer.getTexture() # self.buffer.setSort(-100) # # self.originalCamera = self.camera # self.offScreenCamera = self.makeCamera(self.buffer) # self.camera = self.offScreenCamera # # self.img = OnscreenImage(image=self.texture, pos=(0, 0, 0.5)) self.scene = None self.channel = Channel() def set_scene(self, scene_module): # self.transitions.fadeOut(0.2) args = [] if self.scene: args.append(Parallel(Func(self.fade_out), LerpFunc(self.blur_out, duration=0.2))) args.append(Wait(0.2)) args.append(Func(self._set_scene, scene_module)) args.append(Parallel(Func(self.fade_in), LerpFunc(self.blur_in, duration=0.4))) Sequence(*args).start() def blur_out(self, t): # index = int(t) # self.filters.delBlurSharpen() self.filters.setBlurSharpen(1 - t) self.filters.setBloom(intensity=t) def blur_in(self, t): # index = int(t) # self.filters.delBlurSharpen() self.filters.setBlurSharpen(t) self.filters.setBloom(intensity=-t) def fade_out(self): self.transitions.fadeOut(0.2) def fade_in(self): self.transitions.fadeIn(0.2) def _set_scene(self, scene_module): group, class_ = scene_module.split('.') module = importlib.import_module('game.scenes.{}'.format(group)) scene_class = getattr(module, class_) if self.scene: self.scene.destroy() del self.scene self.scene = scene_class(self) # self.transitions.fadeIn(0.2) def start(self): self.channel = Channel() self.channel.connect() self.set_scene('auth.AuthScene') while True: self.taskMgr.step() if self.channel.can_read(): for packet in self.channel.read_packets(): self.scene.on_packet(packet)
class LevelChanger(DirectObject): #Use this to handle changing of levels #check the emeny list and if it is empty then change the level #Flag to tell if the level is complete levelComplete = False def __init__(self): #Level map self.level01 = "resources/theSouthBridge" self.level02 = "resources/theSocket" self.level03 = "resources/theDualChannel" self.level04 = "resources/theRoot" self.levelMap = {1:self.level01, 2:self.level02, 3:self.level03, 4:self.level04} self.currentLevel = 1 #Level music map self.level01M = base.loader.loadMusic("resources/sounds/level1.wav") self.level02M = base.loader.loadMusic("resources/sounds/level2.wav") self.level03M = base.loader.loadMusic("resources/sounds/level3.wav") self.level04M = base.loader.loadMusic("resources/sounds/bossMusic.wav") self.musicMap = {1:self.level01M, 2:self.level02M, 3:self.level03M, 4:self.level04M} self.currentMusic = self.musicMap[self.currentLevel] self.currentMusic.setLoop(True) self.currentMusic.play() #Open file to get player spawns self.pSpawnsFile = open("playerSpawns.txt") self.pSpawnsList = self.pSpawnsFile.readlines() self.pSpawnsFile.close() #Set players current spawn self.spawnIndex = 0 base.xPos = float(self.pSpawnsList[self.spawnIndex + 1].split("=")[1].translate(None,"\n")) base.yPos = float(self.pSpawnsList[self.spawnIndex + 2].split("=")[1].translate(None,"\n")) base.zPos = float(self.pSpawnsList[self.spawnIndex + 3].split("=")[1].translate(None,"\n")) base.player.playerNode.setPos(0, 0, 30) #resets height base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos) #resets position #checks the enemy list #if the list is empty, level is complete #set flag to true and change the level. def checkLevel (self, task): enemy = base.spawner.spawnId if(len(base.enemyList) == 0): if enemy > 0: self.levelComplete = True if self.currentLevel == len(self.levelMap): base.player.hide() base.player.canUseWeapons = False base.fsm.request('WinMenu', 1) return task.done else: self.changeLevel(task) return task.cont def changeLevel(self, task): if(self.levelComplete == True): self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.fadeOut = self.transition.fadeOut(2) #unload the current level and models self.unload(self.levelMap[self.currentLevel]) #load the next level and models self.load(self.levelMap[self.currentLevel + 1]) #self.fadeIn = self.transition.fadeIn(5) base.taskMgr.remove(task) return task.cont #Unloads current level objects def unload(self, level): for i in base.pickuplist: i.deletePickup = True for i in base.enemyList: i.delFlag = True i.deadFlag = True #stop the music self.currentMusic.stop() #detach playerNode base.player.playerNode.detachNode() #Remove enemies #base.taskMgr.remove("Spawn Enemies") base.taskMgr.remove("enemyCleanup") #unload the env and detach remove the node base.loader.unloadModel(level) base.environ.removeNode() #Load the next level def load(self, level): #Reset player health for the next level base.player.adjustHealth(base.player.maxEnergy) #load Environment - new level base.environ = base.loader.loadModel(level) base.environ.reparentTo(base.render) base.environ.setScale(7, 7, 3) #update the currentLevel. self.currentLevel += 1 #reattach player to render base.player.playerNode.reparentTo(render) #Set the next levels spawn coordinates self.spawnIndex += 4 base.xPos = float(self.pSpawnsList[self.spawnIndex + 1].split("=")[1].translate(None,"\n")) base.yPos = float(self.pSpawnsList[self.spawnIndex + 2].split("=")[1].translate(None,"\n")) base.zPos = float(self.pSpawnsList[self.spawnIndex + 3].split("=")[1].translate(None,"\n")) base.player.playerNode.setPos(0,0,30) #resets height base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos) #resets position #create new spawner on the env base.spawner = Spawner(base.environ, level.split("/")[1].translate(None,"\n")) #Reinit enemies base.spawner.spawn() base.taskMgr.add(self.checkLevel, "checkLevel") base.taskMgr.add(base.enemyCleanUp, "enemyCleanup", taskChain='GameTasks') self.fadeIn = self.transition.fadeIn(2) self.currentMusic = self.musicMap[self.currentLevel] self.currentMusic.setLoop(True) self.currentMusic.play() #Returns the current level def getCurrentLevel(self): return self.currentLevel #Goes direcctly to the boss level def goToBoss(self): self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.fadeOut = self.transition.fadeOut(2) self.unload(self.levelMap[1]) self.load(self.levelMap[4]) self.currentLevel = 4 #Resets enemies upon death def resetEnemy(self): base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos) base.player.playerNode.setPos(0,0,30) #resets height for i in base.enemyList: i.delFlag = True i.deadFlag = True for i in base.pickuplist: i.deletePickup = True #create new spawner on the current level base.spawner = Spawner(base.environ, self.levelMap[self.currentLevel].split("/")[1].translate(None,"\n")) #Reinit enemies base.spawner.spawn()
class ConfigRender: def __init__(self): render.setAntialias(AntialiasAttrib.MAuto) # render.setRenderModeWireframe() DGG.getDefaultFont().setPixelsPerUnit(100) self.setShaders() self.initLights() self.initTransitions() self.setFPS() self.setCam() def setCam(self): base.camLens.setNearFar(10, 500) # base.camLens.setFov(40) def setShaders(self): if not base.win.getGsg().getSupportsBasicShaders(): print( "Toon Shader: Video driver reports that Cg shaders are not supported." ) return tempnode = NodePath(PandaNode("temp node")) tempnode.setAttrib(LightRampAttrib.makeHdr0()) self.filters = CommonFilters(base.win, base.cam) # GLOW self.filters.setBloom(blend=(0.3, 0.4, 0.3, 0.0), mintrigger=0.6, maxtrigger=1.0, desat=0.6, intensity=1.0, size="medium") tempnode.setShaderAuto() base.cam.node().setInitialState(tempnode.getState()) def initLights(self): ambientLight = AmbientLight("ambient_light") ambientLight.setColor((0.2, 0.2, 0.2, 1)) self.alnp = render.attachNewNode(ambientLight) sunLens = PerspectiveLens() sunLens.setFilmSize(50) sun = DirectionalLight("sun") sun.setColor((1, 1, 1, 1)) # sun.setShadowCaster(True, 4096, 4096) # highest working value sun.setScene(render) # sun.showFrustum() sunLens.setFov(120, 40) sunLens.setNearFar(2, 100) sun.setLens(sunLens) self.sunNp = render.attachNewNode(sun) def setFPS(self): FPS = 30 globalClock = ClockObject.getGlobalClock() globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(FPS) def initTransitions(self): self.transitions = Transitions(loader) self.transitions.setFadeColor(0, 0, 0) self.transitionTime = 0.2 base.accept("fadeOut", self.transitions.fadeOut, [self.transitionTime]) base.accept("fadeIn", self.transitions.fadeIn, [self.transitionTime]) base.accept("noFade", self.transitions.noFade) def fadeInOutSequence(self, callback, callbackArgs=None): if callbackArgs: seq = Sequence( Func(base.messenger.send, 'fadeOut'), Wait(self.transitionTime), Func(callback, callbackArgs), Wait(self.transitionTime), Func(base.messenger.send, 'fadeIn'), ) else: seq = Sequence( Func(base.messenger.send, 'fadeOut'), Wait(self.transitionTime), Func(callback), Wait(self.transitionTime), Func(base.messenger.send, 'fadeIn'), ) seq.start()
class Engine(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() props = WindowProperties() props.setTitle('Test') self.win.requestProperties(props) # self.render.setAntiAlias(AntialiasAttrib.MAuto) self.transitions = Transitions(self.loader) self.transitions.setFadeColor(0, 0, 0) self.filters = CommonFilters(self.win, self.cam) # self.filters.setCartoonInk() self.filters.setBlurSharpen(1) # self.filters.setVolumetricLighting(self.render) # self.buffer = self.win.makeTextureBuffer("Post-processing buffer", self.win.getXSize(), self.win.getXSize()) # print self.buffer.getYSize() # self.texture = self.buffer.getTexture() # self.buffer.setSort(-100) # # self.originalCamera = self.camera # self.offScreenCamera = self.makeCamera(self.buffer) # self.camera = self.offScreenCamera # # self.img = OnscreenImage(image=self.texture, pos=(0, 0, 0.5)) self.scene = None self.channel = Channel() def set_scene(self, scene_module): # self.transitions.fadeOut(0.2) args = [] if self.scene: args.append( Parallel(Func(self.fade_out), LerpFunc(self.blur_out, duration=0.2))) args.append(Wait(0.2)) args.append(Func(self._set_scene, scene_module)) args.append( Parallel(Func(self.fade_in), LerpFunc(self.blur_in, duration=0.4))) Sequence(*args).start() def blur_out(self, t): # index = int(t) # self.filters.delBlurSharpen() self.filters.setBlurSharpen(1 - t) self.filters.setBloom(intensity=t) def blur_in(self, t): # index = int(t) # self.filters.delBlurSharpen() self.filters.setBlurSharpen(t) self.filters.setBloom(intensity=-t) def fade_out(self): self.transitions.fadeOut(0.2) def fade_in(self): self.transitions.fadeIn(0.2) def _set_scene(self, scene_module): group, class_ = scene_module.split('.') module = importlib.import_module('game.scenes.{}'.format(group)) scene_class = getattr(module, class_) if self.scene: self.scene.destroy() del self.scene self.scene = scene_class(self) # self.transitions.fadeIn(0.2) def start(self): self.channel = Channel() self.channel.connect() self.set_scene('auth.AuthScene') while True: self.taskMgr.step() if self.channel.can_read(): for packet in self.channel.read_packets(): self.scene.on_packet(packet)
class MenuPrincipal(ShowBase): def __init__(self, gameLogic): self.gameLogic = gameLogic #Image d'arrière plan self.background = OnscreenImage(parent=render2d, image="../asset/Menu/background.jpg") #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) #Titre du jeu self.textTitre = OnscreenText(text="Tank'em!", pos=(0, 0.6), scale=0.32, fg=(0.8, 0.9, 0.7, 1), align=TextNode.ACenter) #Boutons btnScale = (0.18, 0.18) text_scale = 0.12 borderW = (0.04, 0.04) couleurBack = (0.243, 0.325, 0.121, 1) separation = 1 hauteur = -0.6 numItemsVisible = 50 self.b1 = DirectButton(text=("Jouer", "Carnage!", "DESTRUCTION", "disabled"), text_scale=btnScale, borderWidth=borderW, text_bg=couleurBack, frameColor=couleurBack, relief=4, textMayChange=1, pad=(0.35, 0), command=self.chargeJeu, pos=(separation, 0, hauteur + 0.8)) self.b2 = DirectButton(text=("Quitter", "Cyka Bliat", "Bye!", "disabled"), text_scale=btnScale, borderWidth=borderW, text_bg=couleurBack, frameColor=couleurBack, relief=4, textMayChange=1, pad=(0.30, 0), command=lambda: sys.exit(), pos=(separation, 0, hauteur)) #Scroll list self.scrollList = DirectScrolledList( frameSize=(-0.4, 0.7, -0.8, 0.8), frameColor=(0, 0, 0, 0), pos=(-1, 1, 0), forceHeight=0.1, numItemsVisible=numItemsVisible, itemFrame_frameSize=(-0.4, 0.7, -0.5, 0.59), itemFrame_pos=(0, 0, 0), ) for map in DTOlistmap.getArrayMaps(): self.name = map.getName() self.i = map.getId() self.l = DirectButton( text=str(self.i) + " " + self.name, text_scale=0.08, scale=0.9, borderWidth=(0.005, 0.005), command=self.menuLogin, extraArgs=[self.gameLogic, self.i, self.name]) self.scrollList.addItem(self.l) #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/load.png") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/shotgun.mp3") def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) #On cache les menus self.background.hide() self.b1.hide() self.b2.hide() self.scrollList.hide() self.textTitre.hide() def menuLogin(self, gameLogic, mapID, mapName): self.cacher() self.menuPrincipal = MenuLogin(gameLogic, mapID, mapName) def chargeJeu(self): #On démarre! Sequence( Func(lambda: self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda: messenger.send("DemarrerPartie")), Wait( 0.2 ), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda: self.transition.irisIn(0.2))).start()
class InterfaceMenuPrincipal(ShowBase): def __init__(self): self.arriver1 = False self.arriver2 = False self.Parallel = Parallel(name="parallel") #Image d'arrière plan self.background=OnscreenImage(parent=render2d, image="../asset/Menu/menuPrincipal.jpg") #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(10) #Titre du jeu self.textTitre = OnscreenText(text = "Tankem!", pos = (0,0.6), scale = 0.32, fg=(0.8,0.9,0.7,1), align=TextNode.ACenter) #--------------------> #--------------------< #Boutons btnScale = (0.18,0.18) text_scale = 0.12 borderW = (0.04, 0.01) couleurBack = (0.243,0.325,0.121,1) separation = 0.5 hauteur = -0.6 self.b1 = DirectButton(text = ("Quick play", "!", "!", "disabled"), text_scale=btnScale, borderWidth = borderW, text_bg=couleurBack, frameColor=couleurBack, relief=2, command=self.chargeJeu, pos = (-1,0,hauteur)) self.b3 = DirectButton(text = ("Niveaux", "!", "!", "disabled"), text_scale=btnScale, borderWidth = borderW, text_bg=couleurBack, frameColor=couleurBack, relief=2, command=self.choisirNiveau, pos = (1,0,hauteur)) self.b2 = DirectButton(text = ("Quitter", "Bye!", ":-(", "disabled"), text_scale=btnScale, borderWidth = borderW, text_bg=couleurBack, frameColor=couleurBack, relief=2, command = lambda : sys.exit(), pos = (0,0,hauteur)) #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/loading.jpg") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/demarrage.mp3") self.etat = False #ici pour button les interfaces self.verticalOffsetControlButton = 0.225 self.verticalOffsetCenterControlButton = -0.02 def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) #On cache les menus self.background.hide() self.b1.hide() self.b2.hide() self.b3.hide() self.textTitre.hide() def cacherNiveau(self): #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) #On cache les menus self.background.hide() self.myScrolledListLabel.hide() def cacherAuthentification(self): #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) self.labelJ1.hide() self.labelmdp1.hide() self.entryJ1.hide() self.entrymdp1.hide() self.labelJ2.hide() self.labelmdp2.hide() self.entryJ2.hide() self.entrymdp2.hide() self.connectJ1.hide() self.connectJ2.hide() self.champMessage.hide() self.champCalcule1.hide() self.champVs.hide() self.champCalcule2.hide() self.champCombattre.hide() self.champNomNiv.hide() self.champFavori.hide() self.boutonCombattre.hide() self.labelVs.hide() self.background.hide() def chargeJeu(self): #On démarre! #if self.etat==True: # self.cacherNiveau() Sequence(Func(lambda : self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda : messenger.send("DemarrerPartie", ["quick"])), #Wait(0.2), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda : self.transition.irisIn(0.2)) ).start() def chargeJeuNiveau(self,niveau): self.tank1.removeNode() self.tank2.removeNode() Sequence(Func(lambda : self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacherAuthentification), Func(lambda : messenger.send("DemarrerPartie", [niveau])), #Wait(0.2), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda : self.transition.irisIn(0.2)) ).start() def choisirNiveau(self): ''' self.textObject = OnscreenText(text = "CHOISISSEZ VOTRE CHAMP DE BATAILLLE", pos =(0,0.9), scale = 0.1,fg=(1,1.5,0.5,0.3),bg=(1,1,1,0.4),align=TextNode.ACenter,mayChange=1) ''' self.cacher() self.etat=True self.background = OnscreenImage(parent = render2d, image="../asset/Menu/niveau.jpg") try: self.leDaoPhase2 = DAO_Oracle("e1529743","AAAaaa111","delta/decinfo.edu") self.niveaux = self.leDaoPhase2.accessNomsNiveaux() self.leDaoPhase2.deconnection() if(len(self.niveaux) > 0): mapsInfo = self.niveaux # ici pour cartes self.controlTextScale = 0.10 self.controlBorderWidth = (0.005, 0.005) self.scrollItemButtons = self.createAllItemsNiveau(mapsInfo) self.myScrolledListLabel = DirectScrolledList( decButton_pos = (0.5, 0.0,-0.625- self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), decButton_text = "Monter", decButton_text_scale = 0.08, decButton_borderWidth = (0.0025, 0.0025), decButton_frameSize = (-0.35, 0.35, -0.0375, 0.075), decButton_text_fg = (0.15, 0.15, 0.75, 1.0), incButton_pos = (-0.5, 0.0, -0.625 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), incButton_text = "Descendre", incButton_text_scale = 0.08, incButton_borderWidth = (0.0025, 0.0025), incButton_frameSize = (-0.35, 0.35, -0.0375, 0.075), incButton_text_fg = (0.15, 0.15, 0.75, 1.0), #position du frame x , z y pos = (0.1, 0, 0.5), items = self.scrollItemButtons, numItemsVisible = 5, forceHeight = 0.175, frameSize = (-1.05, 1.05, -0.95, 0.325), frameColor = (0.3254,0.3254, 0.12549, 0.75), # sur un item itemFrame_pos = (0.0, 0.0, 0.0), itemFrame_frameSize = (-1.025, 1.025, -0.775, 0.15), itemFrame_frameColor = (0.1098039215686275,0.1098039215686275, 0.0431372549019608, 0.75), itemFrame_relief = 1 ) else: ctypes.windll.user32.MessageBoxA(0, "Il n'y a aucun niveau actif dans la BD, on demarre le tankem avec un niveau au hasard", "Error de connection", 0) self.chargeJeu() except: ctypes.windll.user32.MessageBoxA(0, "erreur connexion pour les niveaux, on demarre le tankem avec un niveau au hasard", "Error de connection", 0) def AuthentificationJoueur(self, mapId): try: self.dao_joueur = DAO_Joueur("e1529743","AAAaaa111","delta/decinfo.edu") self.cacherNiveau() self.background = OnscreenImage(parent = render2d, image="../asset/Menu/background.jpg") base.cam.node().getDisplayRegion(0).setSort(20) self.isConnectedJ1 = False self.isConnectedJ2 = False self.labelJ1 = DirectLabel(text = "Joueur 1", text_scale=0.06, pos=(-1.5, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.labelmdp1 = DirectLabel(text = "Mot de passe", text_scale=0.06, pos=(-1.5, 0.0, 1.0 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.entryJ1 = DirectEntry(text_scale=0.06, pos=(-0.9, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.entrymdp1 = DirectEntry(text_scale=0.06, pos=(-0.9, 0.0, 1.0 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.labelJ2 = DirectLabel(text = "Joueur 2", text_scale=0.06, pos=(0.3, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.labelmdp2 = DirectLabel(text = "Mot de passe", text_scale=0.06, pos=(0.3, 0.0, 1.0 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.entryJ2 = DirectEntry(text_scale=0.06, pos=(0.9, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.entrymdp2 = DirectEntry(text_scale=0.06, pos=(0.9, 0.0, 1.0 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), color=(0,0,0,1), text_fg=(1,1,1,1)) self.connectJ1 = DirectButton(frameColor=(1,0.5,0.5,1), relief=1, text = "Connection",text_scale=0.06, pos=(-0.3, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), command = lambda: self.connect("J1", mapId)) self.connectJ2 = DirectButton(frameColor=(1,0.5,0.5,1), relief=1, text = "Connection", text_scale=0.06, pos=(1.5, 0.0, 1.1 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.25, 0.25, -0.035, 0.060), command = lambda: self.connect("J2", mapId)) self.champMessage = DirectLabel(text = "Veuillez vous-connectez !",text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), color=(0,0,0,1),text_fg=(1,0.1,0.1,1)) except: ctypes.windll.user32.MessageBoxA(0, "erreur connexion pour les login des joueurs, demmarage automatique", "Error de login", 0) self.cacherNiveau() self.chargeJeu() def connect(self, joueur, mapId): if(joueur == "J1"): self.dto_joueur1 = self.dao_joueur.lireJoueur(0, self.entryJ1.get(), self.entrymdp1.get()) if(self.dto_joueur1.id == 0): self.champMessage.hide() self.champMessage = DirectLabel(text = "Le joueur n'est pas reconnu !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) elif(self.isConnectedJ2): if(self.dto_joueur1.id == self.dto_joueur2.id): self.champMessage.hide() self.champMessage = DirectLabel(text = "Le joueur est déja connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) else: self.champMessage.hide() self.champMessage = DirectLabel(text = "Joueur1 est connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.isConnectedJ1 = True self.char1 = self.creerChar(6,6,0,Vec3(self.dto_joueur1.R,self.dto_joueur1.G,self.dto_joueur1.B)) else: self.champMessage.hide() self.champMessage = DirectLabel(text = "Joueur1 est connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.isConnectedJ1 = True self.char1 = self.creerChar(6,6,0,Vec3(self.dto_joueur1.R,self.dto_joueur1.G,self.dto_joueur1.B)) else: self.dto_joueur2 = self.dao_joueur.lireJoueur(1, self.entryJ2.get(), self.entrymdp2.get()) if(self.dto_joueur2.id == 0): self.champMessage.hide() self.champMessage = DirectLabel(text = "Le joueur n'est pas reconnu !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) elif(self.isConnectedJ1): if(self.dto_joueur1.id == self.dto_joueur2.id): self.champMessage.hide() self.champMessage = DirectLabel(text = "Le joueur est déja connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) else: self.champMessage.hide() self.champMessage = DirectLabel(text = "Joueur2 est connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1)) self.isConnectedJ2 = True self.char2 = self.creerChar(3,3,1,Vec3(self.dto_joueur2.R,self.dto_joueur2.G,self.dto_joueur2.B)) #Char gris-jaune else: self.champMessage.hide() self.champMessage = DirectLabel(text = "Joueur2 est connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.isConnectedJ2 = True self.char2 = self.creerChar(3,3,1,Vec3(self.dto_joueur2.R,self.dto_joueur2.G,self.dto_joueur2.B)) #Char gris-jaune if(self.isConnectedJ1 and self.isConnectedJ2): self.champMessage.hide() self.champMessage = DirectLabel(text = "Les deux joueurs sont connecté !", text_scale=0.06, pos=(0, 0.0, 0.8 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.createLastItem(mapId) def tournerJ1(self): self.arriver1 = True if(self.arriver2): self.Parallel.append(self.tankHprInterval1) self.Parallel.append(self.tankHprInterval2) self.Parallel.loop() else: self.Parallel.append(self.tankHprInterval1) self.Parallel.loop() def tournerJ2(self): self.arriver2 = True if(self.arriver1): self.Parallel.append(self.tankHprInterval2) self.Parallel.append(self.tankHprInterval1) self.Parallel.loop() else: self.Parallel.append(self.tankHprInterval2) self.Parallel.loop() def creerChar(self,positionX, positionY, identifiant, couleur): # On charge le modèles if(identifiant == 0): self.tank1 = loader.loadModel("../asset/Tank/tank") self.tank1.reparentTo(render) self.tank1.setColorScale(couleur.getX(),couleur.getY(),couleur.getZ(),1) self.tank1.setZ(-0.25) self.tank1.setHpr(-90,0,0) self.tankHprInterval1 = self.tank1.hprInterval(3.0,Point3(-450, 0, 0)) tankAvancerDroite = self.tank1.posInterval(3.0,Point3(-4,15,-3),startPos=Point3(-7,15,-3)) self.Sequence = Sequence(tankAvancerDroite, Func(self.tournerJ1)) self.Sequence.start() else: self.tank2 = loader.loadModel("../asset/Tank/tank") self.tank2.reparentTo(render) self.tank2.setColorScale(couleur.getX(),couleur.getY(),couleur.getZ(),1) self.tank2.setZ(-0.25) self.tank2.setHpr(90,0,0) self.tankHprInterval2 = self.tank2.hprInterval(3.0,Point3(450, 0, 0)) tankAvancerGauche = self.tank2.posInterval(3.0,Point3(4,15,-3),startPos=Point3(7,15,-3)) self.Sequence = Sequence(tankAvancerGauche, Func(self.tournerJ2)) self.Sequence.start() def createLastItem(self, mapId): #analyse pour le nom calcule analyse1 = AnalyseDTOJoueur(self.dto_joueur1) analyse2 = AnalyseDTOJoueur(self.dto_joueur2) self.nomCalcule1 = analyse1.nomCalcule() self.nomCalcule2 = analyse2.nomCalcule() self.champCalcule1 = DirectLabel(text = self.nomCalcule1, text_scale=0.06, pos=(0, 0.0, 0.65 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.035, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.champVs = DirectLabel(text = "VS", text_scale=0.06, pos=(0, 0.0, 0.55 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.035, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.champCalcule2 = DirectLabel(text = self.nomCalcule2 , text_scale=0.06, pos=(0, 0.0, 0.45 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) self.champCombattre = DirectLabel(text = "Combattrons dans", text_scale=0.06, pos=(0, 0.0, 0.30 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2,-0.035, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) pos = 0 for i in self.niveaux: if(i[1] == mapId): niveau = self.niveaux[pos][0] pos += 1 self.champNomNiv = DirectLabel(text = str(niveau), text_scale=0.06, pos=(0, 0.0, 0.20 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) #favori if(self.dto_joueur1.experience > self.dto_joueur2.experience): favori = self.nomCalcule1 + " est favori" self.dto_joueur1.favori = 0 elif(self.dto_joueur1.experience < self.dto_joueur2.experience): favori = self.nomCalcule2 + " est favori" self.dto_joueur2.favori = 0 else: favori = "Aucun favori" self.dto_joueur1.favori = 0 self.dto_joueur2.favori = 0 self.champFavori = DirectLabel(text = favori, text_scale=0.06, pos=(0, 0.0, 0.05 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.2,1.2, -0.020, 0.065), scale=(0,0,0),text_fg=(1,0.1,0.1,1), color=(0,0,0,1)) #animation des labels delai = Wait(0.3) scale1 = self.champCalcule1.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") scale2 = self.champVs.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") scale3 = self.champCalcule2.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") scale4 = self.champCombattre.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") scale5 = self.champNomNiv.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") scale6 = self.champFavori.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") sequence = Sequence(scale1, delai, scale2, delai,scale3, delai,scale4,scale5, delai,scale6, delai) sequence.start() #animation bouton combattre self.boutonCombattre = DirectButton(frameColor=(1,0,0,1), relief=2, text = "Combattre", text_scale=0.07, pos=(0, 0.0, - 0.5 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-0.40, 0.40, -0.080, 0.060), command = lambda: self.affichageCombat(mapId)) interval1 = self.boutonCombattre.scaleInterval(0.7, Point3(1.2, 1.2, 1.2), blendType="easeInOut") interval2 = self.boutonCombattre.scaleInterval(0.7, Point3(1, 1, 1), blendType="easeInOut") self.sequenceBouton = Sequence(interval1,interval2,name="sequenceBouton") self.sequenceBouton.loop() def affichageCombat(self, mapId): self.sequenceBouton.finish() self.boutonCombattre.hide() self.Parallel.start() self.labelVs = DirectLabel(text = self.nomCalcule1 + " VS " + self.nomCalcule2,frameColor=(1,0,0,1), text_scale=0.07, pos=(0, 0.0, - 0.7 - self.verticalOffsetControlButton + self.verticalOffsetCenterControlButton), frameSize = (-1.0,1.0, -0.020, 0.065), scale=(6,6,6)) rapetisseLabel = self.labelVs.scaleInterval(1, Point3(1, 1, 1), blendType="easeInOut") delai = Wait(3.5) self.sequenceNomVS = Sequence(rapetisseLabel, delai, Func(self.loadGame,mapId), name="sequenceNom") self.sequenceNomVS.start() def createItemButtonNiveau(self, mapName, mapId): return DirectButton( text = mapName, text_scale = self.controlTextScale, borderWidth = self.controlBorderWidth, relief = 1, frameSize = (-1.0, 1.0, -0.0425, 0.085), command = lambda: self.AuthentificationJoueur(mapId)) def createAllItemsNiveau(self, mapsInfo): scrollItemButtons = []#self.createItemButtonNiveau(u'-> Carte aléatoire <-', None)] for mapInfo in mapsInfo: scrollItemButtons.append(self.createItemButtonNiveau(self.formatText(mapInfo[0]), mapInfo[1])) return scrollItemButtons def formatText(self, text, maxLength = 20): return text if len(text) <= maxLength else text[0:maxLength] + '...' def loadGame(self, mapId): # À ajuster... évidemment... self.dao_joueur.deconnection() self.chargeJeuNiveau(mapId)
class InterfaceMenuPrincipal(ShowBase): def __init__(self): #Image d'arrière plan self.background = OnscreenImage( parent=render2d, image="../asset/Menu/menuPrincipal.jpg") #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) #Titre du jeu self.textTitre = OnscreenText(text="Tankem!", pos=(0, 0.6), scale=0.32, fg=(0.8, 0.9, 0.7, 1), align=TextNode.ACenter) #Boutons btnScale = (0.18, 0.18) text_scale = 0.12 borderW = (0.04, 0.04) couleurBack = (0.243, 0.325, 0.121, 1) separation = 0.5 hauteur = -0.6 self.b1 = DirectButton(text=("Jouer", "!", "!", "disabled"), text_scale=btnScale, borderWidth=borderW, text_bg=couleurBack, frameColor=couleurBack, relief=2, command=self.chargeJeu, pos=(-separation, 0, hauteur)) self.b2 = DirectButton(text=("Quitter", "Bye!", ":-(", "disabled"), text_scale=btnScale, borderWidth=borderW, text_bg=couleurBack, frameColor=couleurBack, relief=2, command=lambda: sys.exit(), pos=(separation, 0, hauteur)) #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/loading.jpg") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/demarrage.mp3") def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) #On cache les menus self.background.hide() self.b1.hide() self.b2.hide() self.textTitre.hide() def chargeJeu(self): #On démarre! Sequence( Func(lambda: self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda: messenger.send("DemarrerMenuNiveau")), Wait( 0.2 ), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda: self.transition.irisIn(0.2))).start()
class InterfaceMenuChoixNiveau(ShowBase): def __init__(self): self.accept("AllerChoixNiveau", self.ouvrirMenu) self.sound = loader.loadSfx("../asset/Menu/demarrage.mp3") curtain = loader.loadTexture("../asset/Menu/loading.jpg") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) def ouvrirMenu(self, unDTOUsers, unDTOMap, username1, username2, listeArmes): self.listeArmes = listeArmes self.username1 = username1 self.username2 = username2 self.unDTOUsers = unDTOUsers self.unDTOMap = unDTOMap numItemsVisible = 5 itemHeight = 0.11 self.myScrolledList = DirectScrolledList( decButton_pos=(0.29, 0, 0.53), decButton_text="Dec", decButton_text_scale=0.04, decButton_borderWidth=(0.005, 0.005), incButton_pos=(0.29, 0, -0.15), incButton_text="Inc", incButton_text_scale=0.04, incButton_borderWidth=(0.005, 0.005), frameSize=(-1.4, 1.7, -0.5, 0.75), frameColor=(1, 0, 0, 0.5), pos=(-0.12, 0, 0), numItemsVisible=numItemsVisible, forceHeight=itemHeight, itemFrame_frameSize=(-1.2, 1.2, -0.5, 0.11), itemFrame_pos=(0.27, 0, 0.4), ) btn = DirectButton(text=("Hasard", "click!", "roll", "disabled"), text_scale=0.075, borderWidth=(0.01, 0.01), relief=2, command=lambda: self.chargeJeu(000)) self.myScrolledList.addItem(btn) if Connexion().getCurseur() != None: self.dictInfoNiveaux = self.unDTOMap.getDictoNiveau() listeIdUsersEnOrdre = [] ######Met les niv en ordre de proprietaire tupleUser = self.unDTOUsers.getTousUser() for username in tupleUser: listeIdUsersEnOrdre.append(tupleUser.get(username)[0]) listeIdUsersEnOrdre.sort() listeDesUsersEnOrdre = [] for idJoueur in listeIdUsersEnOrdre: print idJoueur for username in tupleUser: if tupleUser.get(username)[0] == idJoueur: listeDesUsersEnOrdre.append(tupleUser.get(username)) for user1 in listeDesUsersEnOrdre: for key in self.dictInfoNiveaux: if self.dictInfoNiveaux.get(key)[8] == user1[0]: infosNiveau = [] infosNiveau = self.dictInfoNiveaux.get(key) nomProprio = user1[1] nbFoisFavori = self.unDTOMap.nbFoisNiveauFavori( infosNiveau[0]) nbFoisJouer = self.unDTOMap.obtenirNbFoisNiveauJoueTotal( infosNiveau[0]) if infosNiveau[5] != 4: textLabel = str( infosNiveau[1]) + " --> Propriétaire: " + str( nomProprio) + " -- Favoris: " + str( nbFoisFavori) + " -- Joué: " + str( nbFoisJouer) btn = DirectButton( text=(textLabel, "Bon choix!", self.stringHover(infosNiveau[5]), "disabled"), text_scale=0.075, borderWidth=(0.01, 0.01), relief=2, command=lambda idNiveau=infosNiveau[ 0]: self.chargeJeu(idNiveau)) self.myScrolledList.addItem(btn) def chargeJeu(self, idNiveau): listeInfo = [ idNiveau, self.unDTOMap, self.unDTOUsers, self.username1, self.username2, self.listeArmes ] #On démarre! Sequence( Func(lambda: self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(self.cacher), Func(lambda: messenger.send("DemarrerPartie", listeInfo)), Wait( 0.2 ), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda: self.transition.irisIn(0.2))).start() def cacher(self): #Est esssentiellement un code de "loading" #On remet la caméra comme avant base.cam.node().getDisplayRegion(0).setSort(self.baseSort) self.myScrolledList.hide() def setupMap(self): leDTOMap = DTOMap() leDAOMap = DAOOracleMap() leDTOMap = leDAOMap.read() return leDTOMap def stringHover(self, typeNiv): if typeNiv == 1: return "Public" if typeNiv == 2: return "Privé" if typeNiv == 3: return "Équipe" if typeNiv == 4: return "Inactif"
class MenuLogin(ShowBase): def __init__(self, gameLogic,mapID,mapName): self.gameLogic = gameLogic self.mapID = mapID self.mapName = mapName self.user = common.internal.UtilisateursDAODTO.DAOutilisateur.DAOutilisateur() self.wait = True #Image d'arrière plan self.background=OnscreenImage(parent=render2d, image="../asset/Menu/BackgroundLogin.jpg") #On dit à la caméra que le dernier modèle doit s'afficher toujours en arrière self.baseSort = base.cam.node().getDisplayRegion(0).getSort() base.cam.node().getDisplayRegion(0).setSort(20) #Variables utiles btnScale = (0.06,0.06) text_scale = 0.12 borderW = (0.02, 0.02) separation = 1 hauteur = -0.6 numItemsVisible = 50 self.couleurBack = (0.243,0.325,0.321,1) self.player1ready = False self.player2ready = False self.player1Infos = "" self.player2Infos = "" self.couleurDisabled = (0.343,0.325,0.321,1) self.couleurBGLabel = (255,255,255,0.3) self.couleurShadow = (200,200,200,0.8) self.couleurFG = (0,0,0,1) self.joueur1 = "" self.joueur2 = "" self.username1 = "" self.username2 = "" self.p1Logged = False self.p2Logged = False #Titre du jeu base.disableMouse() # fields dans lesquels on peut écrire self.fieldUsername1 = DirectEntry(text = "" ,scale=.05, initialText="", numLines = 1, focus=1, pos=(-4,0,0.82) ) self.fieldUsername2 = DirectEntry(text = "" ,scale=.05, initialText="", numLines = 1, focus=0, pos=(3.4,0,0.82) ) self.fieldPassword1 = DirectEntry(text = "" ,scale=.05, initialText="", numLines = 1, focus=0, pos=(-4,0,0.59), obscured=1 ) self.fieldPassword2 = DirectEntry(text = "" ,scale=.05, initialText="", numLines = 1, focus=0, pos=(3.4,0,0.59), obscured=1 ) self.messageBox = DirectEntry(text = "" ,scale=.05, width =55, initialText="Veuillez vous connecter à Tank'em", numLines = 1, focus=0, pos=(-10.35,0,0.3), focusInCommand=self.clearText ) # Labels et fields qui doivent subir des lerps # textnotes / notes aspect2d sont beaucoup plus sympatoches à travailler. self.textLabel1 = TextNode('testLabel1') self.textLabel1.setText("Player1") self.textLabel1.setTextColor(0,0,0,1) self.textLabel1.setShadow(0.05,0.05) self.textLabel1.setShadowColor(self.couleurShadow) self.textLabel1.setCardColor(self.couleurBGLabel) self.textLabel1.setCardAsMargin(0, 0, 0, 0) self.textLabel1.setCardDecal(True) self.textLabel1.setAlign(TextNode.ACenter) self.nodeLabel1 = aspect2d.attachNewNode(self.textLabel1) self.nodeLabel1.setScale(0.10) self.nodeLabel1.setPos(-3.75,0,0.9) self.textLabel2 = TextNode('textLabel2') self.textLabel2.setText("Player2") self.textLabel2.setTextColor(0,0,0,1) self.textLabel2.setShadow(0.05,0.05) self.textLabel2.setShadowColor(self.couleurShadow) self.textLabel2.setCardColor(self.couleurBGLabel) self.textLabel2.setCardAsMargin(0, 0, 0, 0) self.textLabel2.setCardDecal(True) self.textLabel2.setAlign(TextNode.ACenter) self.nodeLabel2 = aspect2d.attachNewNode(self.textLabel2) self.nodeLabel2.setScale(0.10) self.nodeLabel2.setPos(3.65,0,0.9) self.textPassword1 = TextNode('textPassword1') self.textPassword1.setText("Password") self.textPassword1.setTextColor(0,0,0,1) self.textPassword1.setShadow(0.05,0.05) self.textPassword1.setShadowColor(self.couleurShadow) self.textPassword1.setCardColor(self.couleurBGLabel) self.textPassword1.setCardAsMargin(0, 0, 0, 0) self.textPassword1.setCardDecal(True) self.textPassword1.setAlign(TextNode.ACenter) self.nodePassword1 = aspect2d.attachNewNode(self.textPassword1) self.nodePassword1.setScale(0.10) self.nodePassword1.setPos(-3.75,0,0.67) self.textPassword2 = TextNode('textPassword2') self.textPassword2.setText("Password") self.textPassword2.setTextColor(0,0,0,1) self.textPassword2.setShadow(0.05,0.05) self.textPassword2.setShadowColor(self.couleurShadow) self.textPassword2.setCardColor(self.couleurBGLabel) self.textPassword2.setCardAsMargin(0, 0, 0, 0) self.textPassword2.setCardDecal(True) self.textPassword2.setAlign(TextNode.ACenter) self.nodePassword2 = aspect2d.attachNewNode(self.textPassword2) self.nodePassword2.setScale(0.10) self.nodePassword2.setPos(3.65,0,0.67) self.textMessagebox = TextNode('textMessagebox') self.textMessagebox.setText("Message box") self.textMessagebox.setTextColor(0,0,0,1) self.textMessagebox.setShadow(0.05,0.05) self.textMessagebox.setShadowColor(self.couleurShadow) self.textMessagebox.setCardColor(self.couleurBGLabel) self.textMessagebox.setCardAsMargin(0, 0, 0, 0) self.textMessagebox.setCardDecal(True) self.textMessagebox.setAlign(TextNode.ACenter) self.nodeMessagebox = aspect2d.attachNewNode(self.textMessagebox) self.nodeMessagebox.setScale(0.10) self.nodeMessagebox.setPos(-3.05,0,0.4) self.textJoueur1 = TextNode('textJoueur1') self.textJoueur1.setText("") self.textJoueur1.setTextColor(0,0,0,1) self.textJoueur1.setShadow(0.05,0.05) self.textJoueur1.setShadowColor(self.couleurShadow) self.textJoueur1.setCardColor(self.couleurBGLabel) self.textJoueur1.setCardAsMargin(0, 0, 0, 0) self.textJoueur1.setCardDecal(True) self.textJoueur1.setAlign(TextNode.ACenter) self.nodeJoueur1 = aspect2d.attachNewNode(self.textJoueur1) self.nodeJoueur1.setScale(0) self.nodeJoueur1.setPos(0.014,0,0.1) self.textJoueur2 = TextNode('textJoueur2') self.textJoueur2.setText("") self.textJoueur2.setTextColor(0,0,0,1) self.textJoueur2.setShadow(0.05,0.05) self.textJoueur2.setShadowColor(self.couleurShadow) self.textJoueur2.setCardColor(self.couleurBGLabel) self.textJoueur2.setCardAsMargin(0, 0, 0, 0) self.textJoueur2.setCardDecal(True) self.textJoueur2.setAlign(TextNode.ACenter) self.nodeJoueur2 = aspect2d.attachNewNode(self.textJoueur2) self.nodeJoueur2.setScale(0) self.nodeJoueur2.setPos(0.014,0,-0.3) self.textVersus = TextNode('textVersus') self.textVersus.setText("VERSUS") self.textVersus.setTextColor(0,0,0,1) self.textVersus.setShadow(0.05,0.05) self.textVersus.setShadowColor(self.couleurShadow) self.textVersus.setCardColor(self.couleurBGLabel) self.textVersus.setCardAsMargin(0, 0, 0, 0) self.textVersus.setCardDecal(True) self.textVersus.setAlign(TextNode.ACenter) self.nodeVersus = aspect2d.attachNewNode(self.textVersus) self.nodeVersus.setScale(0) self.nodeVersus.setPos(0.014,0,-0.1) self.textCombattre = TextNode('textCombattre') self.textCombattre.setText("Combattrons dans l'arène :") self.textCombattre.setTextColor(0,0,0,1) self.textCombattre.setShadow(0.05,0.05) self.textCombattre.setShadowColor(self.couleurShadow) self.textCombattre.setCardColor(self.couleurBGLabel) self.textCombattre.setCardAsMargin(0, 0, 0, 0) self.textCombattre.setCardDecal(True) self.textCombattre.setAlign(TextNode.ACenter) self.nodeCombattre = aspect2d.attachNewNode(self.textCombattre) self.nodeCombattre.setScale(0) self.nodeCombattre.setPos(0.014,0,-0.5) self.textFavoris = TextNode('textFavoris') self.textFavoris.setText("") self.textFavoris.setTextColor(0,0,0,1) self.textFavoris.setShadow(0.05,0.05) self.textFavoris.setShadowColor(self.couleurShadow) self.textFavoris.setCardColor(self.couleurBGLabel) self.textFavoris.setCardAsMargin(0, 0, 0, 0) self.textFavoris.setCardDecal(True) self.textFavoris.setAlign(TextNode.ACenter) self.nodeFavoris = aspect2d.attachNewNode(self.textFavoris) self.nodeFavoris.setScale(0) self.nodeFavoris.setPos(0.014,0,-0.9) self.textNiveau = TextNode('textNiveau') self.textNiveau.setText("") self.textNiveau.setTextColor(0,0,0,1) self.textNiveau.setShadow(0.05,0.05) self.textNiveau.setShadowColor(self.couleurShadow) self.textNiveau.setCardColor(self.couleurBGLabel) self.textNiveau.setCardAsMargin(0, 0, 0, 0) self.textNiveau.setCardDecal(True) self.textNiveau.setAlign(TextNode.ACenter) self.nodeNiveau = aspect2d.attachNewNode(self.textNiveau) self.nodeNiveau.setScale(0) self.nodeNiveau.setPos(0.014,0,-0.7) # Bouttons nécéssaires. self.loginP1 = DirectButton(text = ("Login", "Login", "Login", "Login"), text_scale=btnScale, borderWidth = borderW, text_bg=self.couleurBack, frameColor=self.couleurBack, relief=2, textMayChange = 1, pad = (0,0), command = self.setPlayerReady, extraArgs = [True,1], pos = (-3.75,0,0.45)) self.loginP2 = DirectButton(text = ("Login", "Login", "Login", "Login"), text_scale=btnScale, borderWidth = borderW, text_bg=self.couleurBack, frameColor=self.couleurBack, relief=2, textMayChange = 1, pad = (0,0), command = self.setPlayerReady, extraArgs = [True,2], pos = (3.65,0,0.45)) self.buttonPlay = DirectButton(text = ("Play", "Play", "Play", "Play"), text_scale=btnScale, borderWidth = borderW, text_bg=self.couleurDisabled, frameColor=self.couleurDisabled, relief=2, textMayChange = 1, pad = (0,0), state = DGG.DISABLED, command = self.setNiveauChoisi, extraArgs = [self.mapID], pos = (-3.05,0.4,0.67)) self.buttonSite = DirectButton(text = ("Site internet de Tank'em", "Site internet de Tank'em", "Site internet de Tank'em", "Site internet de Tank'em"), text_scale=btnScale, borderWidth = borderW, text_bg=self.couleurBack, frameColor=self.couleurBack, relief=2, textMayChange = 1, pad = (0,0), command = self.openSite, pos = (1.25,-1.4,-0.9)) self.loginIntro() #Ici on call le modèle des tanks et commence l'interval pour les faire tourner en rond #Tank1 self.tankGauche = loader.loadModel("../asset/Tank/tank") self.tankGauche.reparentTo(render) self.tankGauche.setPos(-46.5,65,-10) self.tankGauche.setScale(6.005,6.005,6.005) self.tankGauche.setHpr(180, 0.0, 0.0) interval = self.tankGauche.hprInterval(4.0, Vec3(-180, 0, 0)) self.sequenceTourne = Sequence(interval) self.sequenceTourne.loop() #Tank2 self.tankDroite = loader.loadModel("../asset/Tank/tank") self.tankDroite.reparentTo(render) self.tankDroite.setPos(46.5,65,-10) self.tankDroite.setScale(6.005,6.005,6.005) self.tankDroite.setHpr(180, 0.0, 0.0) interval2 = self.tankDroite.hprInterval(4.0, Vec3(540, 0, 0)) self.sequenceTourne2 = Sequence(interval2) self.sequenceTourne2.loop() #Initialisation de l'effet de transition curtain = loader.loadTexture("../asset/Menu/load.png") self.transition = Transitions(loader) self.transition.setFadeColor(0, 0, 0) self.transition.setFadeModel(curtain) self.sound = loader.loadSfx("../asset/Menu/shotgun.mp3") #Pour ouvrir le site internet de Tank'Em def openSite(self): webbrowser.open_new("http://localhost/Tank'em%20Web/index.php") #Intro initial des labels quand on accède a la page de login def loginIntro(self): self.sequence = Sequence (LerpPosInterval(self.nodeLabel1,1,(-0.75,0,0.9),blendType="easeIn")) self.sequence2 = Sequence (LerpPosInterval(self.fieldUsername1,1,(-1,0,0.82),blendType="easeIn")) self.sequence3 = Sequence (LerpPosInterval(self.fieldUsername2,1,(0.4,0,0.82),blendType="easeIn")) self.sequence4 = Sequence (LerpPosInterval(self.nodeLabel2,1,(0.65,0,0.9),blendType="easeIn")) self.sequence5 = Sequence (LerpPosInterval(self.nodePassword1,1,(-0.75,0,0.67),blendType="easeIn")) self.sequence13 = Sequence (LerpPosInterval(self.nodeMessagebox,1,(-0.05,0,0.4),blendType="easeIn")) self.sequence6 = Sequence (LerpPosInterval(self.nodePassword2,1,(0.65,0,0.67),blendType="easeIn")) self.sequence7 = Sequence (LerpPosInterval(self.fieldPassword1,1,(-1,0,0.59),blendType="easeIn")) self.sequence8 = Sequence (LerpPosInterval(self.fieldPassword2,1,(0.4,0,0.59),blendType="easeIn")) self.sequence9 = Sequence (LerpPosInterval(self.messageBox,1,(-1.35,0,0.3),blendType="easeIn")) self.sequence10 = Sequence (LerpPosInterval(self.loginP1,1,(-0.75,0,0.45),blendType="easeIn")) self.sequence11 = Sequence (LerpPosInterval(self.loginP2,1,(0.65,0,0.45),blendType="easeIn")) self.sequence12 = Sequence (LerpPosInterval(self.buttonPlay,1,(-0.05,0.4,0.67),blendType="easeIn")) self.sequence.start() self.sequence4.start() self.sequence2.start() self.sequence3.start() self.sequence5.start() self.sequence6.start() self.sequence7.start() self.sequence8.start() self.sequence13.start() self.sequence9.start() self.sequence10.start() self.sequence11.start() self.sequence12.start() #Outro des logins def loginOutro(self): self.sequence = Sequence (LerpPosInterval(self.nodeLabel1,1,(-3.75,0,0.9),blendType="easeOut")) self.sequence2 = Sequence (LerpPosInterval(self.fieldUsername1,1,(-4,0,0.82),blendType="easeOut")) self.sequence3 = Sequence (LerpPosInterval(self.fieldUsername2,1,(3.4,0,0.82),blendType="easeOut")) self.sequence4 = Sequence (LerpPosInterval(self.nodeLabel2,1,(3.65,0,0.9),blendType="easeOut")) self.sequence5 = Sequence (LerpPosInterval(self.nodePassword1,1,(-3.75,0,0.67),blendType="easeOut")) self.sequence13 = Sequence (LerpPosInterval(self.nodeMessagebox,1,(-3.05,0,0.4),blendType="easeOut")) self.sequence6 = Sequence (LerpPosInterval(self.nodePassword2,1,(3.65,0,0.67),blendType="easeOut")) self.sequence7 = Sequence (LerpPosInterval(self.fieldPassword1,1,(-4,0,0.59),blendType="easeOut")) self.sequence8 = Sequence (LerpPosInterval(self.fieldPassword2,1,(3.4,0,0.59),blendType="easeOut")) self.sequence9 = Sequence (LerpPosInterval(self.messageBox,1,(-5.35,0,0.3),blendType="easeOut")) self.sequence10 = Sequence (LerpPosInterval(self.loginP1,1,(-3.75,0,0.45),blendType="easeOut")) self.sequence11 = Sequence (LerpPosInterval(self.loginP2,1,(3.65,0,0.45),blendType="easeOut")) self.sequence.start() self.sequence4.start() self.sequence2.start() self.sequence3.start() self.sequence5.start() self.sequence6.start() self.sequence7.start() self.sequence8.start() self.sequence13.start() self.sequence9.start() self.sequence10.start() self.sequence11.start() #Quand on se login, dépendant de la direction, le tank gauche ou droite apparait. (Gauche = P1, Droite = P2) def tankIntro(self,direction): if direction == "gauche" : self.sequence = Sequence (LerpPosInterval(self.tankGauche,2,(-17.5,65,-10))) self.color1 = self.hex_to_rgb(self.joueur1.couleurTank) self.tankGauche.setColorScale(self.color1[0]/255.0,self.color1[1]/255.0,self.color1[2]/255.0,1) if direction == "droite" : self.sequence = Sequence (LerpPosInterval(self.tankDroite,2,(17.5,65,-10))) self.color2 = self.hex_to_rgb(self.joueur2.couleurTank) self.tankDroite.setColorScale(self.color2[0]/255.0,self.color2[1]/255.0,self.color2[2]/255.0,1) self.sequence.start() #Faire apparaitre le text quand les eux players sont loggent in def lerpText(self) : self.sequence = Sequence (LerpScaleInterval(self.nodeJoueur1, 0.7, 0.08, 0), LerpScaleInterval(self.nodeVersus, 0.7, 0.08, 0), LerpScaleInterval(self.nodeJoueur2, 0.7, 0.08, 0), LerpScaleInterval(self.nodeCombattre, 0.7, 0.08, 0), LerpScaleInterval(self.nodeNiveau, 0.7, 0.08, 0), LerpScaleInterval(self.nodeFavoris,0.7, 0.08,0)) self.sequence.start() #Changer la valeur d'une couleur en quelque chose que Panda3d aime. def hex_to_rgb(self,value): value = value.lstrip('#') lv = len(value) if lv == 1: v = int(value, 16)*17 return v, v, v if lv == 3: return tuple(int(value[i:i+1], 16)*17 for i in range(0, 3)) return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3)) #Opérations à faire quand les joueurs sont loggés. def setPlayerReady(self,state,num): if num == 1 : self.username1 = self.fieldUsername1.get() self.password1 = self.fieldPassword1.get() if self.username1.lower() != self.username2.lower() : self.joueur1 = self.user.read(self.username1,self.password1) self.p1Logged = True if num == 2 : self.username2 = self.fieldUsername2.get() self.password2 = self.fieldPassword2.get() if self.username2.lower() != self.username1.lower() : self.joueur2 = self.user.read(self.username2,self.password2) self.p2Logged = True if self.joueur1 == 1 or self.joueur2 == 1 : self.setText("Mauvais nom d'utilisateur") elif self.joueur1 == 0 or self.joueur2 == 0 : self.setText("Mauvais mot de passe") else : if num == 1 : if self.p1Logged : self.player1ready = state self.player1Infos = self.joueur1 self.loginP1['state'] = DGG.DISABLED self.loginP1['frameColor'] = self.couleurDisabled self.loginP1['text_bg'] = self.couleurDisabled self.gameLogic.idJoueur1 = self.joueur1.idJoueur self.tankIntro("gauche") if num == 2 : if self.p2Logged : self.player2ready = state self.player2Infos = self.joueur2 self.loginP2['state'] = DGG.DISABLED self.loginP2['frameColor'] = self.couleurDisabled self.loginP2['text_bg'] = self.couleurDisabled self.gameLogic.idJoueur2 = self.joueur2.idJoueur self.tankIntro("droite") if self.player1ready == True and self.player2ready == True : self.setText("Welcome to Tank'em !") self.buttonPlay['state'] = DGG.NORMAL self.buttonPlay['frameColor'] = self.couleurBack self.buttonPlay['text_bg'] = self.couleurBack self.calcJoueur1 = self.calculateName(self.joueur1) self.calcJoueur2 = self.calculateName(self.joueur2) self.textJoueur1.setText(self.username1 + " " + self.calcJoueur1) self.textJoueur2.setText(self.username2 + " " + self.calcJoueur2) if self.joueur1.niveau > self.joueur2.niveau : self.favoris = self.username1 self.textFavoris.setText(self.favoris + " est le favoris !") elif self.joueur2.niveau > self.joueur1.niveau: self.favoris = self.username2 self.textFavoris.setText(self.favoris + " est le favoris !") else : self.favoris = "personne n'est le favoris !" self.textFavoris.setText(self.favoris) self.textNiveau.setText(self.mapName) self.lerpText() self.loginOutro() elif self.player1ready : if self.p1Logged and (self.username1.lower() == self.username2.lower()): self.setText("Cet utilisateur est déjà logged in") else : self.setText('Player 2 must also login') elif self.player2ready : if self.p2Logged and (self.username1.lower() == self.username2.lower()): self.setText("Cet utilisateur est déjà logged in") else : self.setText('Player 1 must also login') else : self.setText('Both players must login') #retourne le joueur 1 et le joueur 2. def getPlayer1(self): return self.joueur1 def getPlayer2(self): return self.joueur2 #pour set le text des labels def setText(self,textEntered): self.messageBox.enterText(textEntered) #clear le text des labels def clearText(self): self.messageBox.enterText('') #Sert à cacher le reste des bouttons et tanks lorsqu'on commence le jeu def cacher(self): self.tankGauche.removeNode() self.tankDroite.removeNode() loader.unloadModel( "../asset/Tank/tank" ) base.cam.node().getDisplayRegion(0).setSort(self.baseSort) self.background.hide() self.loginP1.hide() self.loginP2.hide() self.buttonPlay.hide() self.buttonSite.hide() self.fieldUsername1.hide() self.fieldUsername2.hide() self.fieldPassword1.hide() self.fieldPassword2.hide() self.messageBox.hide() self.nodeLabel1.hide() self.nodePassword1.hide() self.nodeLabel2.hide() self.nodePassword2.hide() self.nodeMessagebox.hide() self.nodeJoueur1.hide() self.nodeJoueur2.hide() self.nodeCombattre.hide() self.nodeNiveau.hide() self.nodeVersus.hide() # self.nodeFavoris.hide() #Ici, on set l'ID du niveau dans gameLogic ainsi que les joueurs qui participent. def setNiveauChoisi(self,idNiveau): self.gameLogic.setIdNiveau(idNiveau) self.gameLogic.setPlayers([self.player1Infos, self.player2Infos]) self.startGame() #Animation pré-partie des tanks ainsi que le début de la partie dans self.chargeJeu appelé dans intervalPos2. def startGame(self): #Tank1 self.sequenceTourne.finish() self.intervalPos = Sequence (self.tankGauche.hprInterval(0.75, Vec3(-90, 0, 0)), LerpPosInterval(self.tankGauche,0.35,(-5,65,-10)), LerpPosHprInterval(self.tankGauche, 0.75, (-50,65,20), Vec3(430,50,370))) self.intervalPos.start() #Tank2 self.sequenceTourne2.finish() self.intervalPos2 = Sequence (self.tankDroite.hprInterval(0.75,Vec3(450,0,0)), LerpPosInterval(self.tankDroite,0.35,(5,65,-10)), LerpPosHprInterval(self.tankDroite, 0.75,(50,65,20), Vec3(430,50,370)), Func(self.chargeJeu)) self.intervalPos2.start() #Séquence qui cache les éléments et fait la transition du login -> loading -> jeu. def chargeJeu(self): #On démarre! Sequence(Func(self.cacher), Func(lambda : self.transition.irisOut(0.2)), SoundInterval(self.sound), Func(lambda : messenger.send("DemarrerPartie")), Wait(0.2), #Bug étrange quand on met pas ça. L'effet de transition doit lagger Func(lambda : self.transition.irisIn(0.2)) ).start() #Sert à calculer le nom composé du joueur selon ses states def calculateName(self, joueur): self.statsJoueur = joueur.getStats() self.bestStat1 = [[0, -1]] #Un array d'arrays contenant deux infos: le nb de points et l'index number self.bestStat2 = [[0, -1]] self.qualificatifA = "" self.qualificatifB = "" self.maxStat = 30 #Le stat maximum #Si tous les stats sont au maximum if(self.statsJoueur[0] == self.maxStat and self.statsJoueur[1] == self.maxStat and self.statsJoueur[2] == self.maxStat and self.statsJoueur[3] == self.maxStat): return "dominateur" #Regarde chacun des stats du joueur et détermine ce qui est le plus grand for idx,stat in enumerate(self.statsJoueur): if(stat > self.bestStat1[0][0]): #S'il y a un stat plus grand que le bestStat, on restart le bestStats avec le nouveau stat self.bestStat1 = [] self.bestStat1.append([stat,idx]) elif(stat == self.bestStat1[0][0] and stat > 0): #S'il y a un stat égal au bestStat, on rajoute les infos dan's self.bestStat1.append([stat,idx]) self.bestStat1 = random.choice(self.bestStat1) for idx,stat in enumerate(self.statsJoueur): if(idx != self.bestStat1[1]): if(stat > self.bestStat2[0][0]): self.bestStat2 = [] self.bestStat2.append([stat,idx]) elif(stat == self.bestStat2[0][0] and stat > 0): self.bestStat2.append([stat,idx]) self.bestStat2 = random.choice(self.bestStat2) #Série de ifs pour déterminer le nom composé du joueur if(self.bestStat1[1] == 0): if(self.bestStat1[0] >= 1): self.qualificatifA = "le fougeux" if(self.bestStat1[0] >= 5): self.qualificatifA = "le pétulant" if(self.bestStat1[0] >= 10): self.qualificatifA = "l'immortel" elif(self.bestStat1[1] == 1): if(self.bestStat1[0] >= 1): self.qualificatifA = "le crossfiter" if(self.bestStat1[0] >= 5): self.qualificatifA = "le hulk" if(self.bestStat1[0] >= 10): self.qualificatifA = "le tout puissant" elif(self.bestStat1[1] == 2): if(self.bestStat1[0] >= 1): self.qualificatifA = "le prompt" if(self.bestStat1[0] >= 5): self.qualificatifA = "le lynx" if(self.bestStat1[0] >= 10): self.qualificatifA = "le foudroyant" elif(self.bestStat1[1] == 3): if(self.bestStat1[0] >= 1): self.qualificatifA = "le précis" if(self.bestStat1[0] >= 5): self.qualificatifA = "l'habile" if(self.bestStat1[0] >= 10): self.qualificatifA = "le chirurgien" if(self.bestStat2[1] == 0): if(self.bestStat2[0] >= 1): self.qualificatifB = "fougeux" if(self.bestStat2[0] >= 5): self.qualificatifB = "pétulant" if(self.bestStat2[0] >= 10): self.qualificatifB = "immortel" elif(self.bestStat2[1] == 1): if(self.bestStat2[0] >= 1): self.qualificatifB = "qui fait du crossfit" if(self.bestStat2[0] >= 5): self.qualificatifB = "brutal" if(self.bestStat2[0] >= 10): self.qualificatifB = "tout puissant" elif(self.bestStat2[1] == 2): if(self.bestStat2[0] >= 1): self.qualificatifB = "prompt" if(self.bestStat2[0] >= 5): self.qualificatifB = "lynx" if(self.bestStat2[0] >= 10): self.qualificatifB = "foudroyant" elif(self.bestStat2[1] == 3): if(self.bestStat2[0] >= 1): self.qualificatifB = "précis" if(self.bestStat2[0] >= 5): self.qualificatifB = "habile" if(self.bestStat2[0] >= 10): self.qualificatifB = "chirurgien" #on retourne le nom composé. return self.qualificatifA + " " + self.qualificatifB