def __init__(self, taille=None, fichierIn=None, fichierOut=None, etape=0): if not taille and not fichierIn: print "besoin de taille ou fichier" return general.filtresRoute = None self.fichierIn=fichierIn self.fichierOut=fichierOut self.routes=[] self.batiments = [] self.points=[] self.sol=Sol() if fichierIn==None: self.sol.genereSol(*taille) A=self.ajouteCentre() B=self.ajouteCentre() C=self.ajouteCentre() self.ajouteRoute(A,B,cptBatiments=False) self.ajouteRoute(B,C,cptBatiments=False) else: self.charge(fichierIn) if etape==0 or etape==1: self.ping = self.pingCreation elif etape==2: self.ping = self.pingChargement elif etape==3: self.ping = self.pingModeleRoutes elif etape==4: self.ping = self.pingModeleBatiments elif etape==5: self.ping = self.pingModeleSol else: print "etape inconue", etape
def _cargar_terreno(self): # terreno self.terreno = Terreno(self.base, self.bullet_world) self.terreno.iniciar() self.terreno.nodo.reparentTo(self.nodo) self.terreno.update() # cielo self.cielo = Cielo(self.base, Sistema.TopoAltitudOceano - 20.0) self.cielo.nodo.reparentTo(self.nodo) # agua self.agua = Agua(self.base, Sistema.TopoAltitudOceano) self.agua.nodo.reparentTo(self.nodo) # estaba self.base.render self.agua.generar() # self.agua.mostrar_camaras() # sol self.sol = Sol(self.base, Sistema.TopoAltitudOceano - 20.0) self.sol.pivot.reparentTo(self.nodo) # self.cielo.nodo # self.sol.mostrar_camaras() self.nodo.setLight(self.sol.luz) # objetos # self.objetos=Objetos(self.base) # self.objetos.iniciar() # self.objetos.nodo.reparentTo(self.nodo) # self.objetos.update() # # self.cielo.nodo.setBin("background", 0) # self.agua.nodo.setBin("background", 1) # self.sol.nodo.setBin("background", 2) # self.terreno.nodo.setBin("opaque", 0) # self.objetos.nodo.setBin("transparent", 0) # self.controlador_camara.altitud_agua = Sistema.TopoAltitudOceano
def __init__(self): self.ecran = pygame.display.set_mode((1100, 600)) pygame.display.set_caption('Jeu De Combat') self.jeu_encours = True self.joueur_x, self.joueur_y = 600, 100 self.taille = [32, 64] self.joueur_vitesse_x = 0 self.joueur = Joueur(self.joueur_x, self.joueur_y, self.taille) self.enemie_x, self.enemie_y = 100, 400 self.enemie_taille = [88, 60] self.image_enemie = pygame.image.load('knight.png') self.enemie = Enemie(self.enemie_x, self.enemie_y, self.enemie_taille) self.image_arriere_plan = pygame.image.load( 'PC Computer - RPG Maker VX Ace - Battle Background Overlays 33.png' ) self.arriere_plan_rect = [34, 34, 574, 214] self.image_ciel_bleu = self.image_arriere_plan.subsurface( self.arriere_plan_rect) self.image_ciel_bleu = pygame.transform.scale(self.image_ciel_bleu, (1100, 600)) self.image_sol_plat = pygame.image.load( 'Game Boy Advance - Sonic Advance - Background Elements 1.gif') self.image_sol_rect = [542, 3693, 373, 117] self.image_sol = self.image_sol_plat.subsurface(self.image_sol_rect) self.image_sol = pygame.transform.scale(self.image_sol, (1100, 170)) self.image_plat_rect = [535, 3689, 379, 123] self.image_plat = self.image_sol_plat.subsurface(self.image_plat_rect) self.image_plat = pygame.transform.scale(self.image_plat, (300, 50)) self.sol = Sol(self.image_sol) self.gravite = (0, 10) self.resistance = (0, 0) self.rect = pygame.Rect(0, 0, 1100, 600) self.collision_sol = False self.horloge = pygame.time.Clock() self.fps = 30 self.projectile_groupe = Group() self.t1, self.t2 = 0, 0 self.delta_temps = 0 self.image_joueur = pygame.image.load( 'WonderSwan WSC - RockmanEXE WS - MegaManEXE Heat Style.png') self.image_joueur_rect = pygame.Rect(124, 453, 8, 8) self.image_boule_de_feu = self.image_joueur.subsurface( self.image_joueur_rect) self.plateforme_groupe = Group() self.plateforme_liste_rect = [ pygame.Rect(0, 300, 300, 50), pygame.Rect(800, 300, 300, 50), pygame.Rect(400, 150, 300, 50) ] self.slash_groupe = Group() self.slash_image_rect = pygame.Rect(108, 232, 24, 43) self.image_slash = self.image_enemie.subsurface(self.slash_image_rect) self.image_slash = pygame.transform.scale(self.image_slash, (30, 30))
def __init__(self): self.ecran = pygame.display.set_mode((1100, 600)) pygame.display.set_caption('Jeu Combat') self.jeu_encours = True self.joueur_x, self.joueur_y = 700, 200 self.joueur_vitesse_x = 0 self.joueur_taille = [32, 64] self.joueur = Joueur(self.joueur_x, self.joueur_y, self.joueur_taille) self.sol = Sol() self.gravite = (0, 10) self.resistance = (0, 0) self.clock = pygame.time.Clock() self.fps = 30 self.rect = pygame.Rect(0, 0, 1100, 600) self.collision_sol = False
def __init__(self, shotlabel=None, mode=None): sys.dont_write_bytecode = True # Create shotlabel as an attribute of plasma class self.shotlabel = shotlabel self.inp = ReadInfile(self.shotlabel) self.core = Core(self.inp) if mode == 'coreonly': pass if mode == 'coreandsol': self.sol = Sol(self.inp, self.core) elif mode == 'thermaliol': self.iol = IOL(self.inp, self.core) elif mode == 'fulliol': self.iol = IOL(self.inp, self.core) elif mode == 'imp': self.imp = ImpRad(core=self.core) elif mode == 'ntrls': self.ntrl = Neutrals(self.inp, self.core) elif mode == 'ntrlsandiol': self.nbi = BeamDeposition(self.inp, self.core) self.iol = IOL(self.inp, self.core) self.ntrl = Neutrals(self.inp, self.core) elif mode == 'nbi': self.nbi = BeamDeposition(self.inp, self.core) elif mode == 'marfe_denlim': self.nbi = BeamDeposition(self.inp, self.core) self.ntrl = Neutrals(self.inp, self.core) self.imp = ImpRad(core=self.core) self.dl = DensityLimit(self.core, self.nbi) self.mar = Marfe(core=self.core) elif mode == 'marfe': self.nbi = BeamDeposition(self.inp, self.core) self.ntrl = Neutrals(self.inp, self.core) self.imp = ImpRad(core=self.core) self.mar = Marfe(core=self.core) elif mode == 'allthethings': self.nbi = BeamDeposition(self.inp, self.core) self.iol = IOL(self.inp, self.core) self.ntrl = Neutrals(self.inp, self.core) self.imp = ImpRad(core=self.core) self.dl = DensityLimit(self.inp, self.core, self.nbi, self.imp, self.ntrl) self.mar = Marfe(self.inp, self.core, self.imp) elif mode == 'radialtrans': self.iol = IOL(self.inp, self.core) self.nbi = BeamDeposition(self.inp, self.core) self.ntrl = Neutrals(self.inp, self.core) # self.imp = ImpRad(z=None, core=self.core) self.rtrans = RadialTransport(self.inp, self.core, self.iol, self.nbi)
def __init__(self, planetas, dia=0): """ Parametros ---------- planetas: arreglo de 3 planetas (planeta1, planeta2, planeta3) dia: dia actual """ self._clima = Clima() self._sol = Sol() self._dia = dia if len(planetas) != SistemaSolar.CANT_PLANETAS: raise ValueError("El sistema debe tener %s planetas") self._planetas = planetas
def __init__(self, player): self.races = {} self.races["Elders"] = Race("Elders", None, "E", colorama.Fore.LIGHTWHITE_EX) self.races["Humans"] = Race("Human", None, "H", colorama.Fore.WHITE) self.races["Rindhalu"] = Race("Rindhalu", None, "R", colorama.Fore.GREEN) self.races["Jeraptha"] = Race("Jeraptha", self.races["Rindhalu"], "J", colorama.Fore.BLUE) self.races["Ruhar"] = Race("Ruhar", self.races["Jeraptha"], "R", colorama.Fore.LIGHTCYAN_EX) self.races["Maxolhx"] = Race("Maxolhx", None, "M", colorama.Fore.LIGHTMAGENTA_EX) self.races["Thuranin"] = Race("Thuranin", self.races["Maxolhx"], "T", colorama.Fore.MAGENTA) self.races["Kristang"] = Race("Kristang", self.races["Thuranin"], "K", colorama.Fore.YELLOW) self.races["Bosphuraq"] = Race("Bosphuraq", self.races["Maxolhx"], "B", colorama.Fore.RED) self.races["Wurgalan"] = Race("Wurgalan", self.races["Bosphuraq"], "W", colorama.Fore.LIGHTYELLOW_EX) self.news = {} self.news["global"] = [] self._star_names = StarNamesStack() self.stars = [] for n in range(len(self._star_names.names)): star = Star(random.randrange(config.world_width), random.randrange(config.world_height), self._star_names.pop(), self.get_random_owner_race()) self.stars.append(star) self.news[star.name] = [] self._scatter_stars() self._scatter_stars() sol = Sol(self, player.world_x, player.world_y) self.stars.append(sol) player.star = sol for b in sol.bodies: if b.name == 'Planet Earth (Medium Terran)': player.system_x = b.body_x player.system_y = b.body_y player.body = b break self.fleets = [] self.spawn_fleets() self.spawn_investigator_fleet()
def __init__(self): #chargement joueur self.player = Player() #chargement enemy self.enemy = Enemy() #chargement sol self.sol = Sol() #chargement effects self.effects = Effects() #chargement plateforme self.plateforme = Plateforme() #chargement sonore self.sonore = Sonore() #définir pressed self.pressed = {} #touches actionnées par le joueur #création gravité self.gravite = 3 self.resistance = 0
class Jeu: def __init__(self): self.ecran = pygame.display.set_mode((1100, 600)) pygame.display.set_caption('Jeu De Combat') self.jeu_encours = True self.joueur_x, self.joueur_y = 600, 100 self.taille = [32, 64] self.joueur_vitesse_x = 0 self.joueur = Joueur(self.joueur_x, self.joueur_y, self.taille) self.enemie_x, self.enemie_y = 100, 400 self.enemie_taille = [88, 60] self.image_enemie = pygame.image.load('knight.png') self.enemie = Enemie(self.enemie_x, self.enemie_y, self.enemie_taille) self.image_arriere_plan = pygame.image.load('PC Computer - RPG Maker VX Ace - Battle Background Overlays 33.png') self.arriere_plan_rect = [34, 34, 574, 214] self.image_ciel_bleu = self.image_arriere_plan.subsurface(self.arriere_plan_rect) self.image_ciel_bleu = pygame.transform.scale(self.image_ciel_bleu, (1100, 600)) self.image_sol_plat = pygame.image.load('Game Boy Advance - Sonic Advance - Background Elements 1.gif') self.image_sol_rect = [542, 3693, 373, 117] self.image_sol = self.image_sol_plat.subsurface(self.image_sol_rect) self.image_sol = pygame.transform.scale(self.image_sol, (1100, 170)) self.image_plat_rect = [535, 3689, 379, 123] self.image_plat = self.image_sol_plat.subsurface(self.image_plat_rect) self.image_plat = pygame.transform.scale(self.image_plat, (300, 50)) self.sol = Sol(self.image_sol) self.gravite = (0, 10) self.resistance = (0, 0) self.rect = pygame.Rect(0, 0, 1100, 600) self.collision_sol = False self.horloge = pygame.time.Clock() self.fps = 30 self.projectile_groupe = Group() self.t1, self.t2 = 0, 0 self.delta_temps = 0 self.image_joueur = pygame.image.load('WonderSwan WSC - RockmanEXE WS - MegaManEXE Heat Style.png') self.image_joueur_rect = pygame.Rect(124, 453, 8, 8) self.image_boule_de_feu = self.image_joueur.subsurface(self.image_joueur_rect) self.plateforme_groupe = Group() self.plateforme_liste_rect = [ pygame.Rect(0, 300, 300, 50), pygame.Rect(800, 300, 300, 50), pygame.Rect(400, 150, 300, 50) ] self.slash_groupe = Group() self.slash_image_rect = pygame.Rect(108, 232, 24, 43) self.image_slash = self.image_enemie.subsurface(self.slash_image_rect) self.image_slash = pygame.transform.scale(self.image_slash, (30, 30)) self.image_vie_joueur = pygame.image.load('life.png') self.image_vie_rect = pygame.Rect(38, 9, 55, 13) self.image_vie_joueur = self.image_vie_joueur.subsurface(self.image_vie_rect) self.image_barre_de_vie = pygame.transform.scale(self.image_vie_joueur, (285, 40)) self.rect_tete = pygame.Rect(82, 0, 12, 10) self.image_tete = self.image_joueur.subsurface(self.rect_tete) self.image_tete = pygame.transform.scale(self.image_tete, (50, 50)) self.debut_timer = 90000 self.bouton = pygame.image.load('button.png') self.replay_bouton = pygame.image.load('replay.png') self.bouton_rect = pygame.Rect(542, 501, 84, 82) self.image_bouton = self.bouton.subsurface(self.bouton_rect) self.image_bouton = pygame.transform.scale(self.image_bouton, (50, 50)) self.x_souris, self.y_souris = 0, 0 self.etat_1 = False self.but_du_jeu = False def boucle_principale(self): """ Boucle principale du jeu """ dictionnaire_vide_joueur = {} dictionnaire_images_joueur = self.joueur.convertir_rect_surface(self.image_joueur, dictionnaire_vide_joueur) dictionnaire_vide_enemie = {} dictionnaire_images_enemie = self.enemie.image_liste(self.image_enemie, dictionnaire_vide_enemie) while self.jeu_encours: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: self.x_souris, self.y_souris = pygame.mouse.get_pos() print(self.x_souris, self.y_souris) if (self.x_souris < 575 and self.x_souris > 525 and self.y_souris < 70 and self.y_souris > 20): self.etat_1 = True if (self.x_souris < 59 and self.x_souris > 29 and self.y_souris < 480 and self.y_souris > 450) and self.etat_1: self.but_du_jeu = True if (self.x_souris < 901 and self.x_souris > 851 and self.y_souris < 572 and self.y_souris > 533) and self.etat_1: self.recommencer() self.etat_1 = False if (self.x_souris < 884 and self.x_souris > 855 and self.y_souris < 477 and self.y_souris > 437) and self.etat_1: self.etat_1 = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 10 self.joueur.direction = 1 self.joueur.etat = 'bouger' if event.key == pygame.K_LEFT: self.joueur_vitesse_x = -10 self.joueur.direction = -1 self.joueur.etat = 'bouger' if event.key == pygame.K_UP: self.joueur.a_sauter = True self.joueur.nombre_de_saut += 1 if event.key == pygame.K_p: self.t1 = time.time() self.joueur.etat = 'attaque' if event.key == pygame.K_e: self.enemie.a_attaque = True self.enemie.etat = 'attaque' if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 0 self.joueur.etat = 'debout' if event.key == pygame.K_LEFT: self.joueur_vitesse_x = 0 self.joueur.etat = 'debout' if event.key == pygame.K_p: self.t2 = time.time() self.joueur.a_tire = True self.joueur.etat = 'debout' if event.key == pygame.K_e: self.enemie.etat = 'vivant' if self.sol.rect.colliderect(self.joueur.rect): self.resistance = (0, -10) self.collision_sol = True self.joueur.nombre_de_saut = 0 else: self.resistance = (0, 0) if self.joueur.a_sauter and self.collision_sol: if self.joueur.nombre_de_saut < 2: self.joueur.sauter() if self.joueur.a_tire: if len(self.projectile_groupe) < self.joueur.tir_autorise and self.delta_temps > 0.05: projectile = Projectile(self.joueur.rect.x + 20, self.joueur.rect.y + 10, [10, 10], self.joueur.direction, self.image_boule_de_feu) self.projectile_groupe.add(projectile) self.joueur.a_tire = False if self.enemie.a_attaque: if len(self.slash_groupe) < self.enemie.tir_autorise: slash = Slash(self.enemie.rect.x + 20, self.enemie.rect.y - 5, [30, 30], self.image_slash) self.slash_groupe.add(slash) self.enemie.a_attaque = False secondes = (self.debut_timer - pygame.time.get_ticks()) // 1000 if secondes == 0: break for projectile in self.projectile_groupe: projectile.mouvement(50) if projectile.rect.right >= self.rect.right or projectile.rect.left <= self.rect.left: self.projectile_groupe.remove(projectile) if self.enemie.rect.colliderect(projectile.rect): self.projectile_groupe.remove(projectile) self.enemie.degats_recus = 10 if self.delta_temps > 2: self.enemie.degats_recus = 30 self.enemie.vie -= self.enemie.degats_recus self.enemie.degats_recus = 0 for slash in self.slash_groupe: slash.mouvement(50) if slash.rect.right >= self.rect.right or slash.rect.left <= self.rect.left: self.slash_groupe.remove(slash) if self.joueur.rect.colliderect(slash.rect): self.slash_groupe.remove(slash) self.joueur.rect.x += 3 self.joueur.degats_recus = 10 self.joueur.vie -= self.joueur.degats_recus self.joueur.degats_recus = 0 if self.joueur.vie <= 0: self.joueur.etat = 'mort' if self.enemie.vie <= 0: self.enemie.etat = 'mort' for rectangle in self.plateforme_liste_rect: plateforme = Plateforme(rectangle, self.image_plat) self.plateforme_groupe.add(plateforme) if self.joueur.rect.midbottom[1] // 10 * 10 == plateforme.rect.top \ and self.joueur.rect.colliderect(rectangle): self.resistance = (0, -10) self.joueur.nombre_de_saut = 0 self.delta_temps = self.t2 - self.t1 self.joueur.mouvement(self.joueur_vitesse_x) self.gravite_jeu() self.joueur.rect.clamp_ip(self.rect) self.ecran.fill((255, 255, 255)) self.ecran.blit(self.image_ciel_bleu, self.rect) self.sol.afficher(self.ecran) self.ecran.blit(self.image_barre_de_vie, (26, 500, 285, 40)) self.ecran.blit(self.image_tete, (10, 490, 50, 50)) self.joueur.afficher(self.ecran, dictionnaire_images_joueur) self.enemie.afficher(self.ecran, dictionnaire_images_enemie) self.ecran.blit(self.image_bouton, (525, 20, 50, 50)) self.creer_message('grande','{}'.format(secondes), [535, 70, 20, 20], (255, 255, 255)) for plateforme in self.plateforme_groupe: plateforme.afficher(self.ecran) for slash in self.slash_groupe: slash.afficher(self.ecran) for projectile in self.projectile_groupe: projectile.afficher(self.ecran, self.delta_temps) if self.etat_1: pygame.draw.rect(self.ecran, (255, 255, 255), (0, 500, 1100, 100), 2) pygame.draw.rect(self.ecran, (0, 0, 0), (0, 400, 1100, 200)) self.ecran_menu() if self.but_du_jeu: self.creer_message('petite', f" Le dernier en vie Gagne !!! ", (100, 450, 80, 80), (255, 255, 255)) pygame.draw.rect(self.ecran, (255, 0, 0), self.rect, 1) self.horloge.tick(self.fps) pygame.display.flip() def gravite_jeu(self): """ Gére la gravité pour chaque élément """ self.joueur.rect.y += self.gravite[1] + self.resistance[1] def creer_message(self, font, message, message_rectangle, couleur): if font == 'petite': font = pygame.font.SysFont('lato', 20, False) elif font == 'moyenne': font = pygame.font.SysFont('lato', 30, False) elif font == 'grande': font = pygame.font.SysFont('lato', 40, True) message = font.render(message, True, couleur) self.ecran.blit(message, message_rectangle) def ecran_menu(self): """ Afficher les boutons """ image_rect = pygame.Rect(11, 7, 69, 67) image_restart = self.replay_bouton.subsurface(image_rect) image_restart = pygame.transform.scale(image_restart, (50, 50)) image_continuer_rect = pygame.Rect(546, 274, 96, 92) image_continuer = self.bouton.subsurface(image_continuer_rect) image_continuer = pygame.transform.scale(image_continuer, (50, 50)) imgae_info_rect = pygame.Rect(924, 432, 58, 60) image_info = self.bouton.subsurface(imgae_info_rect) image_info = pygame.transform.scale(image_info, (50, 50)) self.ecran.blit(image_restart, (850, 530, 50, 50)) self.ecran.blit(image_continuer, (850, 430, 50, 50)) self.ecran.blit(image_info, (20, 440, 50, 50)) def recommencer(self): self.joueur.vie = 100 self.enemie.vie = 100 self.joueur.rect.x = 400 self.joueur.rect.y = 100 self.joueur.etat = 'debout' self.enemie.etat = 'vivant'
class Mundo: def __init__(self, base): # referencias: self.base = base self.sistema = None # componentes: self.nodo = self.base.render.attachNewNode("mundo") self.input_mapper = None self.controlador_camara = None self.terreno = None self.cielo = None self.sol = None self.agua = None self.objetos = None self.hombre = None self.nave = None # variables internas: self._counter = 50 # forzar terreno.update antes de hombre.update self._personajes = [] self._periodo_dia_actual = 0 def iniciar(self): log.info("iniciar") # sistema: self.sistema = Sistema() self.sistema.iniciar() self.sistema.cargar_parametros_iniciales() self.sistema.update(0.0, self.sistema.posicion_cursor) Sistema.establecer_instancia(self.sistema) # fisica: self._configurar_fisica() # mundo: self._establecer_material() # quitarlo, optimizacion? no, al reves! self._establecer_shader() # componentes: self.input_mapper = InputMapperTecladoMouse(self.base) self.controlador_camara = ControladorCamara(self.base) self.controlador_camara.iniciar() # self._cargar_terreno() # self._cargar_personajes() # self._cargar_objetos() # #self._cargar_obj_voxel() # gui: self._cargar_debug_info() self._cargar_gui() # ShowBase self.base.cam.node().setCameraMask(DrawMask(1)) self.base.render.node().adjustDrawMask(DrawMask(5), DrawMask(0), DrawMask(0)) # self.base.accept("l-up", self._hacer, [0]) self.base.accept("m-up", self._hacer, [1]) self.base.accept("v-up", self._hacer, [2]) # self.base.taskMgr.add(self._update, "mundo_update") # def terminar(self): log.info("terminar") # self.base.ignore("l-up") self.base.ignore("m-up") self.base.ignore("v-up") # self.controlador_camara.terminar() # for _personaje in self._personajes: _personaje.terminar() if self.objetos: self.objetos.terminar() if self.agua: self.agua.terminar() if self.sol: self.sol.terminar() if self.cielo: self.cielo.terminar() if self.terreno: self.terreno.terminar() # self.sistema = None Sistema.remover_instancia() def _hacer(self, que): if que == 0: log.debug(self.sistema.obtener_info()) elif que == 1: self.nodo.analyze() elif que == 2: self.base.bufferViewer.toggleEnable() elif que == 3: if not self.nave: return if not self.hombre.conduciendo: self.nave.setPos(self.sistema.posicion_cursor) self.hombre.cuerpo.reparentTo(self.nave.cuerpo) self.hombre.setPos(Vec3(0, 0, -0.5)) self.hombre.conduciendo = True self.controlador_camara.seguir(self.nave.cuerpo) else: self.hombre.cuerpo.reparentTo(self.nodo) self.hombre.setPos(self.sistema.posicion_cursor) self.hombre.conduciendo = False self.controlador_camara.seguir(self.hombre.cuerpo) def _establecer_material(self): log.info("_establecer_material") intensidades = (0.20, 0.35, 0.0) # (a,d,s) material = Material("material_mundo") material.setAmbient( (intensidades[0], intensidades[0], intensidades[0], 1.0)) material.setDiffuse( (intensidades[1], intensidades[1], intensidades[1], 1.0)) material.setSpecular( (intensidades[2], intensidades[2], intensidades[2], 1.0)) material.setShininess(0) self.nodo.setMaterial(material, 1) def _establecer_shader(self): log.info("_establecer_shader") GestorShader.iniciar(self.base, Sistema.TopoAltitudOceano, Vec4(0, 0, 1, Sistema.TopoAltitudOceano)) # # ¿esto habra solucionado el problema del clipping caprichoso? self.nodo.setShaderInput("altitud_agua", Sistema.TopoAltitudOceano, 0.0, 0.0, 0.0, priority=1) # #GestorShader.aplicar(self.nodo, GestorShader.ClaseGenerico, 1) # quitarlo, optimizacion? #GestorShader.aplicar(self, GestorShader.ClaseDebug, 1000) def _cargar_obj_voxel(self): hm = HeightMap(id=66) N = 64 self.obj = voxels.Objeto("volumen", N, N, N, 0) for x in range(N - 2): for y in range(N - 2): h = int(hm.getHeight(x, y) * N) print("%s,%s->%i" % (str(x), str(y), h)) for z in range(h): self.obj.establecer_valor(x + 1, y + 1, z + 1, 255) model_root = ModelRoot("volumen") self.objN = self.nodo.attachNewNode(model_root) self.objN.attachNewNode(self.obj.iniciar_smooth()) self.objN.setColor(0.4, 0.4, 0.4, 1) self.objN.setTwoSided(True, 1) self.objN.setShaderAuto() self.objN.setScale(1) self.objN.setPos(-N / 2, -N / 2, -9.5) def _configurar_fisica(self): self.bullet_world = BulletWorld() #return # debug_fisica = BulletDebugNode("debug_fisica") debug_fisica.showNormals(True) self.debug_fisicaN = self.nodo.attachNewNode(debug_fisica) self.debug_fisicaN.hide() self.base.accept("f3", self._toggle_debug_fisica) # self.bullet_world.setGravity(Vec3(0.0, 0.0, -9.81)) self.bullet_world.setDebugNode(debug_fisica) return # _shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) _cuerpo = BulletRigidBodyNode("caja_rigid_body") _cuerpo.setMass(1.0) _cuerpo.addShape(_shape) _cuerpoN = self.nodo.attachNewNode(_cuerpo) _cuerpoN.setPos(0.0, 0.0, 100.0) _cuerpoN.setCollideMask(BitMask32.bit(3)) self.bullet_world.attachRigidBody(_cuerpo) _cuerpoN.reparentTo(self.nodo) caja = self.base.loader.loadModel("box.egg") caja.reparentTo(_cuerpoN) def _cargar_debug_info(self): Negro = Vec4(0.0, 0.0, 0.0, 1.0) #Blanco=Vec4(1.0, 1.0, 1.0, 1.0) self.texto1 = OnscreenText(text="mundo", pos=(-1.2, 0.9), scale=0.045, align=TextNode.ALeft, fg=Negro, mayChange=True) def _cargar_gui(self): self.lblHora = DirectLabel(text="00:00", text_fg=(0.15, 0.15, 0.9, 1.0), text_bg=(1.0, 1.0, 1.0, 1.0), scale=0.1, pos=(1.2, 0.0, -0.8), color=(1, 1, 1, 1)) self.lblTemperatura = DirectLabel(text="0º", text_fg=(0.15, 0.15, 0.9, 1.0), text_bg=(1.0, 1.0, 1.0, 1.0), scale=0.1, pos=(1.2, 0.0, -0.93), color=(1, 1, 1, 1)) def _cargar_personajes(self): # personajes self.hombre = Hombre() self._personajes.append(self.hombre) # nave self.nave = Nave() self._personajes.append(self.nave) # for _personaje in self._personajes: _personaje.input_mapper = self.input_mapper _personaje.altitud_agua = Sistema.TopoAltitudOceano _personaje.iniciar(self.nodo, self.bullet_world) # posicionar self.hombre.setPos(self.sistema.posicion_cursor) pos = self.sistema.posicion_cursor + Vec3(-3, -3, 0) self.nave.setPos( Vec3(pos[0], pos[1], self.sistema.obtener_altitud_suelo(pos))) # self.controlador_camara.seguir(self.hombre.cuerpo) def _cargar_objetos(self): # self.palo = self.base.loader.loadModel("objetos/palof") self.palo.reparentTo(self.nodo) self.palo.setPos(self.sistema.obtener_posicion_3d(Vec3(12, 12, 0))) # luz_omni = self.nodo.attachNewNode(PointLight("luz_omni")) luz_omni.setPos(Vec3(0, -2, 152.5)) luz_omni.node().setColor(Vec4(1, 0, 0, 1)) luz_omni.node().setAttenuation(Vec3(0, 1.1, 0)) self.nodo.setShaderInput("luz_omni[0]", luz_omni, priority=4) # luz_omni.reparentTo(self.palo) # luz_omni.setPos(0, 0, 1) # self.spot_light = self.nodo.attachNewNode(Spotlight("spot_light")) self.spot_light.setPos(self.hombre.cuerpo.getPos() + Vec3(0, -5, 6)) self.spot_light.node().setColor((1, 1, 0.7, 1)) self.spot_light.node().setAttenuation(Vec3(0.04, 0.025, 0.01)) self.spot_light.node().setLens(PerspectiveLens()) #self.spot_light.node().setShadowCaster(True, 256, 256) self.spot_light.lookAt(self.hombre.cuerpo) self.nodo.setLight(self.spot_light) self.spot_light.reparentTo(self.palo) self.spot_light.setPos(0, 0, 1) self.spot_light.setHpr(0, 15, 0) # self.nubes = self.base.loader.loadModel("objetos/plano") self.nubes.reparentTo(self.nodo) #self.nubes.setTwoSided(True) self.nubes.setPos(self.hombre.cuerpo.getPos() + Vec3(0, -16, 2.5)) self.nubes.setP(-90) #noise=StackedPerlinNoise2(1, 1, 8, 2, 0.5, 256, 18) ts0 = TextureStage("ts_nubes") tamano = 512 imagen = PNMImage(tamano, tamano) #imagen.perlinNoiseFill(noise) for x in range(tamano): for y in range(tamano): #v=noise(x, y)*0.5+0.5 imagen.setXelA(x, y, 1, 0, 0, 0.5) tex0 = self.base.loader.loadTexture( "texturas/white_noise.png") #Texture("tex_nubes") # tex0.load(imagen) self.nubes.setTexture(ts0, tex0) # pelota = self.base.loader.loadModel("objetos/pelota.egg") pelota.reparentTo(self.nodo) pelota.setZ( self.sistema.obtener_altitud_suelo(self.sistema.posicion_cursor) + 3.0) material_pelota = Material("material_pelota") intensidades = (0.3, 0.2, 0.2) material_pelota.setAmbient( (intensidades[0], intensidades[0], intensidades[0], 1.0)) material_pelota.setDiffuse( (intensidades[1], intensidades[1], intensidades[1], 1.0)) material_pelota.setSpecular( (intensidades[2], intensidades[2], intensidades[2], 1.0)) material_pelota.setShininess(20) pelota.setMaterial(material_pelota, priority=2) GestorShader.aplicar(pelota, GestorShader.ClaseGenerico, 3) # plano_vertical = self.base.loader.loadModel( "objetos/plano_vertical.egg") plano_vertical.reparentTo(self.nodo) plano_vertical.setPos(0, -6, self.sistema.obtener_altitud_suelo((0, -6, 0))) #plano_vertical.setTwoSided(True) plano_vertical.setBillboardAxis() GestorShader.aplicar(plano_vertical, GestorShader.ClaseGenerico, 3) # nodo_flatten = self.nodo.attachNewNode("nodo_flatten") for x in range(4): p = self.base.loader.loadModel("objetos/pelota.egg") p.clearModelNodes() p.reparentTo(nodo_flatten) p.setPos(6, 0, 153 + x) p.setScale(0.2) nodo_flatten.flattenStrong() # cant = 3 prisma = self.base.loader.loadModel("objetos/prisma_tri.egg") prisma_geomnode = prisma.find("**/+GeomNode") for i_geom in range(prisma_geomnode.node().getNumGeoms()): prisma_geom = prisma_geomnode.node().getGeom(i_geom) ## prisma_vdata = prisma_geom.getVertexData() consolidado_prismas_vdata = GeomVertexData( "vertex_data", prisma_vdata.getFormat(), Geom.UHStatic) consolidado_prismas_vdata.setNumRows(cant * prisma_vdata.getNumRows()) offset = prisma_vdata.getNumRows() ## prisma_prims = list() consolidado_prismas_prims = list() for i_prim in range(prisma_geom.getNumPrimitives()): prim = prisma_geom.getPrimitive(i_prim).decompose() prisma_prims.append(prim) consolidado_prismas_prim = GeomTriangles(Geom.UHStatic) consolidado_prismas_prims.append(consolidado_prismas_prim) for i_cant in range(cant): vdata = GeomVertexData(prisma_vdata) vdata.transformVertices( LMatrix4f.translateMat(3 * i_cant, 0.0, 0.0)) for i_row in range(vdata.getNumRows()): consolidado_prismas_vdata.copyRowFrom( i_cant * offset + i_row, vdata, i_row, Thread.getCurrentThread()) for i_prim in range(len(prisma_prims)): consolidado_prismas_prim = consolidado_prismas_prims[ i_prim] prim_verts = prisma_prims[i_prim].getVertexList() for vert in prim_verts: consolidado_prismas_prim.addVertex(vert + i_cant * offset) consolidado_prismas_geom = Geom(consolidado_prismas_vdata) consolidado_prismas_geom.addPrimitive(consolidado_prismas_prim) # consolidado_prismas_geomnode = GeomNode("copia_geomnode") consolidado_prismas_geomnode.addGeom(consolidado_prismas_geom) self.nodo_prismas = self.nodo.attachNewNode("nodo_prismas") self.nodo_prismas.setPos( 20, 6, 2 + self.sistema.obtener_altitud_suelo((20, 6, 0))) self.nodo_prismas.attachNewNode(consolidado_prismas_geomnode) # def _cargar_terreno(self): # terreno self.terreno = Terreno(self.base, self.bullet_world) self.terreno.iniciar() self.terreno.nodo.reparentTo(self.nodo) self.terreno.update() # cielo self.cielo = Cielo(self.base, Sistema.TopoAltitudOceano - 20.0) self.cielo.nodo.reparentTo(self.nodo) # agua self.agua = Agua(self.base, Sistema.TopoAltitudOceano) self.agua.nodo.reparentTo(self.nodo) # estaba self.base.render self.agua.generar() # self.agua.mostrar_camaras() # sol self.sol = Sol(self.base, Sistema.TopoAltitudOceano - 20.0) self.sol.pivot.reparentTo(self.nodo) # self.cielo.nodo # self.sol.mostrar_camaras() self.nodo.setLight(self.sol.luz) # objetos # self.objetos=Objetos(self.base) # self.objetos.iniciar() # self.objetos.nodo.reparentTo(self.nodo) # self.objetos.update() # # self.cielo.nodo.setBin("background", 0) # self.agua.nodo.setBin("background", 1) # self.sol.nodo.setBin("background", 2) # self.terreno.nodo.setBin("opaque", 0) # self.objetos.nodo.setBin("transparent", 0) # self.controlador_camara.altitud_agua = Sistema.TopoAltitudOceano # def _update(self, task): if self._counter == 50: info = "" info += self.sistema.obtener_info() + "\n" #info+=self.terreno.obtener_info()+"\n" info += self.hombre.obtener_info() + "\n" #info+=self.agua.obtener_info()+"\n" #info+=self.objetos.obtener_info()+"\n" #info+=self.input_mapper.obtener_info()+"\n" #info+=self.cielo.obtener_info() #info+=self.sol.obtener_info()+"\n" self.texto1.setText(info) # tiempo dt = self.base.taskMgr.globalClock.getDt() # input self.input_mapper.update() # fisica self.bullet_world.doPhysics(dt) # controlador cámara self.controlador_camara.altitud_suelo = self.sistema.obtener_altitud_suelo( self.controlador_camara.pos_camara.getXy()) self.controlador_camara.update(dt) pos_pivot_camara = self.controlador_camara.pivot.getPos(self.nodo) self.nodo.setShaderInput("pos_pivot_camara", pos_pivot_camara, priority=10) # sistema self.sistema.update(dt, pos_pivot_camara) # cielo if self.cielo: offset_periodo = self.sistema.calcular_offset_periodo_dia() self.cielo.nodo.setX( self.controlador_camara.target_node_path.getPos().getX()) self.cielo.nodo.setY( self.controlador_camara.target_node_path.getPos().getY()) self.cielo.update(pos_pivot_camara, self.sistema.hora_normalizada, self.sistema.periodo_dia_actual, offset_periodo) self.nodo.setShaderInput("color_luz_ambiental", self.cielo.color_luz_ambiental, priority=10) self.nodo.setShaderInput("offset_periodo_cielo", self.cielo.offset_periodo, priority=10) self.nodo.setShaderInput("color_cielo_base_inicial", self.cielo.color_cielo_base_inicial, priority=10) self.nodo.setShaderInput("color_cielo_base_final", self.cielo.color_cielo_base_final, priority=10) self.nodo.setShaderInput("color_halo_sol_inicial", self.cielo.color_halo_sol_inicial, priority=10) self.nodo.setShaderInput("color_halo_sol_final", self.cielo.color_halo_sol_final, priority=10) # sol if self.sol: self.sol.update(pos_pivot_camara, self.sistema.hora_normalizada, self.sistema.periodo_dia_actual, offset_periodo) self.nodo.setShaderInput("posicion_sol", self.sol.nodo.getPos(self.nodo), priority=10) # personajes for _personaje in self._personajes: _personaje.update(dt) # contador 1/50 if self._counter == 50: self._counter = 0 # if self.terreno: self.terreno.update( ) #pos_pivot_camara)#self.controlador_camara.target_node_path.getPos()) ? if self.objetos: self.objetos.update() #pos_pivot_camara) # gui self.lblHora["text"] = self.sistema.obtener_hora() self.lblTemperatura[ "text"] = "%.0fº" % self.sistema.obtener_temperatura_actual_grados( ) # agua if self.agua: self.agua.nodo.setX( self.controlador_camara.target_node_path.getPos().getX()) self.agua.nodo.setY( self.controlador_camara.target_node_path.getPos().getY()) self.agua.update(dt, self.sol.luz.getPos(self.cielo.nodo), self.sol.luz.node().getColor()) # self._counter += 1 return task.cont def _toggle_debug_fisica(self): if self.debug_fisicaN.isHidden(): self.debug_fisicaN.show() else: self.debug_fisicaN.hide()
class Jeu: def __init__(self): self.ecran = pygame.display.set_mode((1100, 600)) pygame.display.set_caption('Jeu De Combat') self.jeu_encours = True self.joueur_x, self.joueur_y = 600, 100 self.taille = [32, 64] self.joueur_vitesse_x = 0 self.joueur = Joueur(self.joueur_x, self.joueur_y, self.taille) self.enemie_x, self.enemie_y = 100, 400 self.enemie_taille = [88, 60] self.image_enemie = pygame.image.load('knight.png') self.enemie = Enemie(self.enemie_x, self.enemie_y, self.enemie_taille) self.image_arriere_plan = pygame.image.load( 'PC Computer - RPG Maker VX Ace - Battle Background Overlays 33.png' ) self.arriere_plan_rect = [34, 34, 574, 214] self.image_ciel_bleu = self.image_arriere_plan.subsurface( self.arriere_plan_rect) self.image_ciel_bleu = pygame.transform.scale(self.image_ciel_bleu, (1100, 600)) self.image_sol_plat = pygame.image.load( 'Game Boy Advance - Sonic Advance - Background Elements 1.gif') self.image_sol_rect = [542, 3693, 373, 117] self.image_sol = self.image_sol_plat.subsurface(self.image_sol_rect) self.image_sol = pygame.transform.scale(self.image_sol, (1100, 170)) self.image_plat_rect = [535, 3689, 379, 123] self.image_plat = self.image_sol_plat.subsurface(self.image_plat_rect) self.image_plat = pygame.transform.scale(self.image_plat, (300, 50)) self.sol = Sol(self.image_sol) self.gravite = (0, 10) self.resistance = (0, 0) self.rect = pygame.Rect(0, 0, 1100, 600) self.collision_sol = False self.horloge = pygame.time.Clock() self.fps = 30 self.projectile_groupe = Group() self.t1, self.t2 = 0, 0 self.delta_temps = 0 self.image_joueur = pygame.image.load( 'WonderSwan WSC - RockmanEXE WS - MegaManEXE Heat Style.png') self.image_joueur_rect = pygame.Rect(124, 453, 8, 8) self.image_boule_de_feu = self.image_joueur.subsurface( self.image_joueur_rect) self.plateforme_groupe = Group() self.plateforme_liste_rect = [ pygame.Rect(0, 300, 300, 50), pygame.Rect(800, 300, 300, 50), pygame.Rect(400, 150, 300, 50) ] self.slash_groupe = Group() self.slash_image_rect = pygame.Rect(108, 232, 24, 43) self.image_slash = self.image_enemie.subsurface(self.slash_image_rect) self.image_slash = pygame.transform.scale(self.image_slash, (30, 30)) def boucle_principale(self): """ Boucle principale du jeu """ dictionnaire_vide_joueur = {} dictionnaire_images_joueur = self.joueur.convertir_rect_surface( self.image_joueur, dictionnaire_vide_joueur) dictionnaire_vide_enemie = {} dictionnaire_images_enemie = self.enemie.image_liste( self.image_enemie, dictionnaire_vide_enemie) while self.jeu_encours: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 10 self.joueur.direction = 1 self.joueur.etat = 'bouger' if event.key == pygame.K_LEFT: self.joueur_vitesse_x = -10 self.joueur.direction = -1 self.joueur.etat = 'bouger' if event.key == pygame.K_UP: self.joueur.a_sauter = True self.joueur.nombre_de_saut += 1 if event.key == pygame.K_p: self.t1 = time.time() self.joueur.etat = 'attaque' if event.key == pygame.K_e: self.enemie.a_attaque = True self.enemie.etat = 'attaque' if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 0 self.joueur.etat = 'debout' if event.key == pygame.K_LEFT: self.joueur_vitesse_x = 0 self.joueur.etat = 'debout' if event.key == pygame.K_p: self.t2 = time.time() self.joueur.a_tire = True self.joueur.etat = 'debout' if event.key == pygame.K_e: self.enemie.etat = 'vivant' if self.sol.rect.colliderect(self.joueur.rect): self.resistance = (0, -10) self.collision_sol = True self.joueur.nombre_de_saut = 0 else: self.resistance = (0, 0) if self.joueur.a_sauter and self.collision_sol: if self.joueur.nombre_de_saut < 2: self.joueur.sauter() if self.joueur.a_tire: if len( self.projectile_groupe ) < self.joueur.tir_autorise and self.delta_temps > 0.05: projectile = Projectile(self.joueur.rect.x + 20, self.joueur.rect.y - 5, [10, 10], self.joueur.direction, self.image_boule_de_feu) self.projectile_groupe.add(projectile) self.joueur.a_tire = False if self.enemie.a_attaque: if len(self.slash_groupe) < self.enemie.tir_autorise: slash = Slash(self.enemie.rect.x + 20, self.enemie.rect.y - 5, [30, 30], self.image_slash) self.slash_groupe.add(slash) self.enemie.a_attaque = False for projectile in self.projectile_groupe: projectile.mouvement(50) if projectile.rect.right >= self.rect.right or projectile.rect.left <= self.rect.left: self.projectile_groupe.remove(projectile) for slash in self.slash_groupe: slash.mouvement(50) if slash.rect.right >= self.rect.right or slash.rect.left <= self.rect.left: self.slash_groupe.remove(slash) for rectangle in self.plateforme_liste_rect: plateforme = Plateforme(rectangle, self.image_plat) self.plateforme_groupe.add(plateforme) if self.joueur.rect.midbottom[1] // 10 * 10 == plateforme.rect.top \ and self.joueur.rect.colliderect(rectangle): self.resistance = (0, -10) self.joueur.nombre_de_saut = 0 self.delta_temps = self.t2 - self.t1 self.joueur.mouvement(self.joueur_vitesse_x) self.gravite_jeu() self.joueur.rect.clamp_ip(self.rect) self.ecran.fill((255, 255, 255)) self.ecran.blit(self.image_ciel_bleu, self.rect) self.joueur.afficher(self.ecran, dictionnaire_images_joueur) self.enemie.afficher(self.ecran, dictionnaire_images_enemie) self.sol.afficher(self.ecran) for plateforme in self.plateforme_groupe: plateforme.afficher(self.ecran) for slash in self.slash_groupe: slash.afficher(self.ecran) for projectile in self.projectile_groupe: projectile.afficher(self.ecran, self.delta_temps) pygame.draw.rect(self.ecran, (255, 0, 0), self.rect, 1) self.horloge.tick(self.fps) pygame.display.flip() def gravite_jeu(self): """ Gére la gravité pour chaque élément """ self.joueur.rect.y += self.gravite[1] + self.resistance[1]
#charger images arriere plan background=pygame.image.load('assets/bg2.png').convert() bgOver=pygame.image.load('assets/bg1.png').convert_alpha() maison=pygame.image.load('assets/bg3.png').convert_alpha() #chargement classe Player(), etc... player = Player() #chargement jeu game = Game() #chargement sol sol = Sol() #Plateforme plateforme = Plateforme() #chargement enemy enemy = Enemy() #chargement effets effects = Effects() #chargement sonor sonore = Sonore() font=pygame.font.Font(None, 50) #PV Joueur PV = 10 music_1PV = False PV_im = pygame.image.load('assets/PV.png').convert_alpha()
class Ville: points = None routes = None batiments = None longueurSegment = 4.0 afficheModele = True fichierIn = None fichierOut = None def __init__(self, taille=None, fichierIn=None, fichierOut=None, etape=0): if not taille and not fichierIn: print "besoin de taille ou fichier" return general.filtresRoute = None self.fichierIn=fichierIn self.fichierOut=fichierOut self.routes=[] self.batiments = [] self.points=[] self.sol=Sol() if fichierIn==None: self.sol.genereSol(*taille) A=self.ajouteCentre() B=self.ajouteCentre() C=self.ajouteCentre() self.ajouteRoute(A,B,cptBatiments=False) self.ajouteRoute(B,C,cptBatiments=False) else: self.charge(fichierIn) if etape==0 or etape==1: self.ping = self.pingCreation elif etape==2: self.ping = self.pingChargement elif etape==3: self.ping = self.pingModeleRoutes elif etape==4: self.ping = self.pingModeleBatiments elif etape==5: self.ping = self.pingModeleSol else: print "etape inconue", etape def ajouteCentre(self): tr = len(self.routes) while len(self.routes)==tr: print "Ajout d'un nouveau centre" p1 = self.pointAlea(Vec3(random.randint(0, taille[0]-1),random.randint(0, taille[1]-1),0.0)) p2 = self.pointAlea(Vec3(random.randint(0, taille[0]-1),random.randint(0, taille[1]-1),0.0)) v=p2-p1 v.normalize() v=v*self.longueurSegment*2 p2=p1+v self.points = [] self.ajouteRoute(p1, p2) return self.routes[tr].pointB idAfficheRoute = 0 def afficheRoutes(self): if self.idAfficheRoute >= len(self.routes): return route = self.routes[self.idAfficheRoute] print "Creation de la route %i/%i\r" %(self.idAfficheRoute,len(self.routes)), route.hauteQualite(self) self.idAfficheRoute+=1 def flatten(self): import time deb = time.time() gr = SceneGraphReducer() print "Apply attribs" gr.applyAttribs(self.racineSol.node()) print time.time()-deb deb = time.time() print "Combine Radius" #gr.setCombineRadius(10.0) print time.time()-deb deb = time.time() print "Flatenning" gr.flatten(self.racineSol.node(), ~gr.CSOther) print time.time()-deb deb = time.time() print "Make compatible" gr.makeCompatibleState(self.racineSol.node()) print time.time()-deb deb = time.time() print "Collect" gr.collectVertexData(self.racineSol.node(), ~(gr.CVDFormat|gr.CVDName|gr.CVDAnimationType)) print time.time()-deb deb = time.time() #print "Unify" #gr.unify(self.racineSol.node(), False) print time.time()-deb def chercheQuartiers(self, route=None): if route == None: route = random.choice(self.routes) A,B = route.getCoord() dx=B[0]-A[0] dy=B[1]-A[1] n=Vec3(dy, -dx, 0.0) n.normalize() p1=(A+B)/2+n p2=(A+B)/2-n d_1 = (p1-p2).lengthSquared() d_2 = (p1-p2).lengthSquared() deb = p1 fin = p2 coll1 = None coll2 = None for obj in self.routes: C = obj.pointA D = obj.pointB r = self.intersection(p1, p2, C, D) if r!=None and obj!=route: Px=p1[0]+r*(p2[0]-p1[0]) Py=p1[1]+r*(p2[1]-p1[1]) Pz=self.sol.getAltitude(Vec3(Px,Py,0.0)) P = Px, Py, Pz d1 = (p1-P).lengthSquared() d2 = (p2-P).lengthSquared() if (coll1==None or d1<d_1) and d1<=d2: coll1=P d_1=d1 if (coll2==None or d2<d_2) and d2<d1: coll2=P d_2=d2 C=(A+B)/2 if coll1!=None and coll2!=None and coll1!=p1 and coll1!=p2 and coll2!=p1 and coll2!=p2 and coll1!=coll2 and coll1!=C and coll2!=C: p1=(C+coll1)/2 p2=(C+coll2)/2 p1[2]=0.0 p2[2]=0.0 print "test" contours1 = [] contours2 = [] points = self.cherchePointAutour(p1, self.longueurSegment)+self.cherchePointAutour(p2, self.longueurSegment) for point in points: print "test %i/%i\r" %(points.index(point), len(points)), i1 = self.intersectionne(p1, point) i2 = self.intersectionne(p2, point) if i1==None: contours1.append(point) if i2==None: contours2.append(point) q1=[] q2=[] for route in self.routes: if (route.pointA in contours1 and route.pointB in contours1): q1.append(route) if (route.pointA in contours2 and route.pointB in contours2): q2.append(route) if len(q1)>2: q1=Quartier(q1, 1.0) q1.rendOK(self) q1.affiche() if len(q2)>2: q2=Quartier(q2, 1.0) q2.rendOK(self) q2.affiche() def cherchePointAutour(self, point, dist): print "creation de la liste" points = [] dist=dist*dist for pt in self.points: if (pt-point).lengthSquared()<=dist: points.append(pt) print "fini" return points def charge(self, fichier): def getCoord(point): point = point.replace("[","(") point = point.replace("]",")") pts = point.split("(")[1].split(")")[0].split(",") objs = [] for pt in pts: objs.append(float(pt)) return Vec3(*objs) i=0 j=0 self.sol=Sol() fichier = open(fichier) for ligne in fichier: elements = ligne.strip().split(">") cptElements=0 for element in elements: cptElements+=1 if cptElements%100==0: print "Chargement %i/%i\r" %(cptElements, len(elements)), type = element.split("||")[0] parametres = element.split("||")[1:] if type.lower()=="s": self.sol.tailleX = int(parametres[0].split("$$")[0]) self.sol.tailleY = int(parametres[0].split("$$")[1]) elif type.lower()=="t": if j==0: self.sol.sol.append([]) self.sol.sol[-1].append(float(parametres[0])) j+=1 if j>=self.sol.tailleY: j=0 i+=1 elif type.lower()=="e": if j==0: self.sol.eau.append([]) self.sol.eau[-1].append(float(parametres[0])) j+=1 if j>=self.sol.tailleY: j=0 i+=1 elif type.lower()=="r": pointA, pointB, taille = parametres pointA=getCoord(pointA) pointB=getCoord(pointB) taille=float(taille) if taille==1: taille=2 pointA[2]=self.sol.getAltitude(pointA)+1.1 pointB[2]=self.sol.getAltitude(pointB)+1.1 if pointA not in self.points: self.points.append(pointA) if pointB not in self.points: self.points.append(pointB) self.routes.append(Route(pointA, pointB, taille, self)) self.routes[-1].fabrique() elif type.lower()=="b": position, orientation, taille, importance = parametres position = getCoord(position) orientation = getCoord(orientation) taille = float(taille) importance = float(importance) self.batiments.append(Batiment(position, orientation, taille, importance)) elif type.lower()=="": pass else: print "inconnu", type, parametres raw_input() print if self.sol.eau==None or len(self.sol.eau)==0: print "Recalcul de l'eau... " self.sol.eau=[] for i in range(0, self.sol.tailleX): self.sol.eau.append([]) for j in range(0, self.sol.tailleY): self.sol.eau[i].append(0.0) self.sol.calculEau() t = len(self.routes) cpt=0 for route in self.routes: cpt+=1 if cpt%5==1: print "Creation des routes... %i/%i \r" %(cpt, t), #route.hauteQualite(self) route.fabrique() print self.sol.fabriqueVectrices() def sauvegarde(self): fichier = open(self.fichierOut, "w") fichier.write("S||%i$$%i>" %(self.sol.tailleX, self.sol.tailleY)) for i in range(0, self.sol.tailleX): for j in range(0, self.sol.tailleY): fichier.write("T||%f>" %self.sol.sol[i][j]) for i in range(0, self.sol.tailleX): for j in range(0, self.sol.tailleY): fichier.write("E||%f>" %self.sol.eau[i][j]) for route in self.routes: fichier.write(route.sauvegarde()) for batiment in self.batiments: fichier.write(batiment.sauvegarde()) fichier.close() def pointAlea(self, pt, delta=None): import time deb=time.time() if delta==None: deltaX = self.sol.tailleX deltaY = self.sol.tailleY else: deltaX = delta deltaY = delta out = None x,y,z = pt autorise = self.sol.altitudeMax test=0 while out==None: test+=1 test = Vec3((random.random()*2-1)*deltaX+x, (random.random()*2-1)*deltaY+y, 0.0+z) test[2] = self.sol.getAltitude(test) if self.sol.pointValide(test): out = test if time.time()-deb>3: return Vec3(-10000,-10000,-10000) return out def intersection(self, A, B, C, D): Ax, Ay, Az = A Bx, By, Bz = B Cx, Cy, Cz = C Dx, Dy, Dz = D try: r=((Ay-Cy)*(Dx-Cx)-(Ax-Cx)*(Dy-Cy))/((Bx-Ax)*(Dy-Cy)-(By-Ay)*(Dx-Cx)) except: r=0.5 try: s=((Ay-Cy)*(Bx-Ax)-(Ax-Cx)*(By-Ay))/((Bx-Ax)*(Dy-Cy)-(By-Ay)*(Dx-Cx)) except: s=0.5 if 0<r and r<1 and 0<s and s<1: return r else: return None def intersectionne(self, A, B): d = (A-B).lengthSquared() deb = A fin = B coll = None for obj in self.routes: C = obj.pointA D = obj.pointB r = self.intersection(A, B, C, D) if r!=None: Px=A[0]+r*(B[0]-A[0]) Py=A[1]+r*(B[1]-A[1]) Pz=self.sol.getAltitude(Vec3(Px, Py, 0.0)) P = Vec3(Px, Py, Pz) d2 = (A-P).lengthSquared() if coll==None or d2<d: coll=P d=d2 if coll==A: return None if coll==B: return None return coll def collisionBatimentBatiment(self, position, rayon): for batiment in self.batiments: pos = Vec3(batiment.position[0], batiment.position[1], batiment.position[2]) taille = batiment.taille if (rayon+taille)*(rayon+taille)>(position-pos).lengthSquared(): return batiment return False def collisionLigneBatiment(self, pointA, pointB): for batiment in self.batiments: centre = batiment.position[0], batiment.position[1], batiment.position[2] rayon = batiment.taille if self.collisionLigneCercle(pointA, pointB, centre, rayon): return True return False def collisionBatimentLigne(self, position, rayon): for route in self.routes: pointA, pointB = route.getCoord() if self.collisionLigneCercle(pointA, pointB, position, rayon): return True return False def collisionLigneCercle(self, pointA, pointB, centre, rayon): ax,ay,az = pointA bx,by,bz = pointB cx,cy,cz = centre alpha = (bx-ax)*(bx-ax)+(by-ay)*(by-ay) beta = 2*((bx-ax)*(ax-cx)+(by-ay)*(ay-cy)) gamma = ax*ax+ay*ay+cx*cx+cy*cy-2*(ax*cx+ay*cy)-rayon*rayon if beta*beta-4*alpha*gamma>=0: u=((cx-ax)*(bx-ax)+(cy-ay)*(by-ay))/((bx-ax)*(bx-ax)+(by-ay)*(by-ay)) return 0<=u and u<=1 else: return False def ajouteBatiments(self, A, B, direction): i=0.0 rayon = 0.5 pas = 1.0/(B-A).length()*rayon Px=A[0]-5*(B[0]-A[0]) Py=A[1]-5*(B[1]-A[1]) Pz=self.sol.getAltitude(Vec3(Px,Py,0.0)) prev=Vec3(Px, Py, Pz) dx=B[0]-A[0] dy=B[1]-A[1] n=Vec3(direction*dy, -direction*dx, 0.0) n.normalize() cpt=0 dec = random.random()*rayon*30 batiments = [] while i<=1.0: i+=pas taille=random.random()*1.0+0.5 Cx = A[0]+i*(B[0]-A[0]) Cy = A[1]+i*(B[1]-A[1]) Cz = 0.0 Px=A[0]+i*(B[0]-A[0])+n[0]*taille Py=A[1]+i*(B[1]-A[1])+n[1]*taille point = Vec3(Px,Py,0.0) point[2]=self.sol.getAltitude(point) if (point-prev).length()>3*rayon+dec: if self.sol.pointValide(point): noeudColl = self.collisionBatimentBatiment(point, taille) if not noeudColl: if not self.collisionBatimentLigne(point, taille): if random.random()>0.4: cpt+=1 batiment = Batiment(point, Vec3(Cx,Cy,Cz), taille, 1.0) batiments.append(batiment) self.batiments.append(batiment) else: facteur = min(0.2 * 6.0 / float(len(self.batiments)), 0.8) facteur = max(0.0, facteur) importance = noeudColl.importance importance = importance + facteur noeudColl.setImportance(importance) prev=point return batiments def continueRoute(self, route, versFin): route = route.pointA, route.pointB vecteurRoute = route[1]-route[0] origine = route[1] if not versFin: vecteurRoute = -vecteurRoute origine = route[0] vecteurRoute[0] = vecteurRoute[0]+(random.random()-0.5)/2 vecteurRoute[1] = vecteurRoute[1]+(random.random()-0.5)/2 cible = self.pointAlea(origine+vecteurRoute, delta=None) return self.ajouteRoute(origine, cible) def intersectionEau(self, A, B): l=(B-A).length() if l>0: pas = 0.33/l r=0 prevR=0 while r<1.0: Px=A[0]+r*(B[0]-A[0]) Py=A[1]+r*(B[1]-A[1]) if self.sol.getAltitude(Vec3(Px,Py,0.0))<=0: Px=A[0]+prevR*(B[0]-A[0]) Py=A[1]+prevR*(B[1]-A[1]) return Vec3(Px, Py, self.sol.getAltitude(Vec3(Px,Py,0.0))) prevR=r r+=pas return None def ajouteRoute(self, depart, arrivee, couleur=(0.1, 0.1, 0.1), cptBatiments=True): depart[2]=0.0 arrivee[2]=0.0 coll = self.intersectionne(depart, arrivee) if coll: coll[2]=0.0 if coll and depart!=coll: arrivee = coll coll = self.intersectionEau(depart, arrivee) if coll: coll[2]=0.0 if (arrivee-depart).length() < self.longueurSegment*math.sqrt(len(self.batiments)): return False #else: # print "trav" if self.sol.estEau(depart): return False if self.sol.estEau(arrivee): return False if not self.sol.pointValide(depart, testeEau=False): return False if not self.sol.pointValide(arrivee, testeEau=False): return False if (arrivee-depart).length()==0: return False pt1, d1 = self.pointPlusProche(depart) pt2, d2 = self.pointPlusProche(arrivee) if d1<self.longueurSegment: depart=pt1 if d2<self.longueurSegment: arrivee=pt2 longueurMin = self.longueurSegment if (arrivee-depart).length()<longueurMin: return False for route in self.routes: lpos = route.pointA, route.pointB if (depart,arrivee)==lpos or (arrivee,depart)==lpos: return False if self.collisionLigneBatiment(depart, arrivee): return False position = depart points = [] routes = [] batiments = [] cptBat = 0 position[2]=0.0 arrivee[2]=0.0 longueurMarine = 0 postMarine=False drop=False longueurMarineMin = 20 longueurMarineMax = 30 while (position-arrivee).length()>0: direction = (arrivee-position) if direction.length()<self.longueurSegment: plus=arrivee else: direction.normalize()*self.longueurSegment plus=position+direction position[2]=self.sol.getAltitude(position) plus[2]=self.sol.getAltitude(plus) if position[2]<self.sol.altitudeMax: if self.sol.estEau(position): if postMarine: if longueurMarine<longueurMarineMin: drop = True if longueurMarine>longueurMarineMax: drop = True longueurMarine = 0 postMarine=False position[2]+=1.0#points[-1][2] plus[2]+=1.0#points[-1][2] longueurMarine+=1 else: batiments += self.ajouteBatiments(position, plus, 1) + self.ajouteBatiments(position, plus, -1) cptBat += len(batiments) if longueurMarine>0: postMarine=True points.append(Vec3(*position)) taille = 2.0 routes.append(Route(Vec3(*position), Vec3(*plus), taille)) position[2]=0.0 plus[2]=0.0 position = plus points.append(arrivee) if ((cptBatiments and cptBat<=0) or drop or (longueurMarine!=0 and (longueurMarine<longueurMarineMin or longueurMarine>longueurMarineMax))): for route in routes: route.supprime() for batiment in batiments: batiment.supprime() self.batiments.remove(batiment) return False else: self.points+=points self.routes+=routes for route in routes: #route.fabrique() route.hauteQualite(self) return True heurePing = None def ajouteRouteAlea(self): routeOrigine = random.choice(self.routes) choix = random.random() if self.continueRoute(routeOrigine, choix>=0.5): for i in range(0, max(10, len(self.routes)/50)): route = random.choice(self.routes) direction = 1 if random.random()>=0.5: direction=-1 self.ajouteBatiments(route.pointA, route.pointB, direction) if self.heurePing == None or time.time()-self.heurePing>5: self.heurePing = time.time() self.heurePing = time.time() + (time.time()-self.heurePing) print "Batiments : %i Routes : %i\r" %(len(self.batiments), len(self.routes)), sys.stdout.flush() def pointPlusProche(self, pt, egalOK=True): d=800000.0 ptProche=None for point in self.points: if egalOK or (point!=pt): dist = (point-pt).lengthSquared() if dist < d: ptProche = point d = dist return ptProche, math.sqrt(d) def distPointLigne(self, point, A, B): x1, y1, z1= A x2, y2, z2 = B x3, y3, z3 = point lAB = (B-A).length() u = ((x3-x1)*(x2-x1)+(y3-y1)*(y2-y1))/(lAB*lAB) x = x1 + u*(x2-x1) y = y1 + u*(y2-y1) return (Vec3(x, y, z3)-point).length(), u pings=0 def ping(self, task): return task.done def pingCreation(self, task): self.pings+=1 self.sol.affiche() self.ajouteRouteAlea() if len(self.batiments)>500: self.sauvegarde() return task.cont lastPing = None def pingChargement(self, task): self.pings+=1 self.sol.affiche() if self.lastPing==None: self.lastPing=time.time() if time.time()>self.lastPing: deb=time.time() self.concentreBatiments() self.lastPing=time.time()+(time.time()-deb) if self.pings%60==0: self.sauvegarde() #self.chercheQuartiers(random.choice(self.routes)) return task.cont def pingModeleRoutes(self, task): self.pings+=1 if self.pings==1: print "TODO : pingModeleRoutes" self.sol.affiche() self.afficheRoutes() random.choice(self.routes).hauteQualite(self) if self.pings%60==0: self.sauvegarde() return task.cont def pingModeleBatiments(self, task): self.pings+=1 if self.pings==1: print "TODO : pingModeleBatiments" self.sol.affiche() if self.pings%60==0: self.sauvegarde() return task.cont def pingModeleSol(self, task): self.pings+=1 if self.pings==1: print "TODO : pingModeleSol" self.sol.affiche() if self.pings%60==0: self.sauvegarde() return task.cont posBat = 0 passeBat = 0 ajoutBatPasse = 0 listeBatiments = None def concentreBatiments(self): if self.listeBatiments==None: self.listeBatiments = self.batiments[:] random.shuffle(self.listeBatiments) if self.posBat>=len(self.listeBatiments): self.posBat = 0 self.passeBat += 1 self.ajoutBatPasse = 0 self.listeBatiments = self.batiments[:] random.shuffle(self.listeBatiments) print "[%i-%i] Batiments, %i nouveaux batiments ajoutes pour un total de %i\r" %(self.passeBat, self.posBat+1, self.ajoutBatPasse, len(self.batiments)), batiment = self.batiments[self.posBat] position = batiment.position orientation = batiment.orientation importance = batiment.importance taille = batiment.taille tailleTeste = random.random()*1.0+0.5 nouvImportance = importance*0.95 if nouvImportance>=1.0: for angle in range(0,360): if random.random()>=0.33: tailleTeste = random.random()*1.0+0.5 direction = 1.0 if random.random()>=0.5: direction = -1.0 direction = Vec3((taille+tailleTeste+0.005)*math.cos(float(angle)/180*math.pi), (taille+tailleTeste+0.005)*math.sin(float(angle)/180*math.pi), 0.0) * direction newPos = position + direction newPos[2]=self.sol.getAltitude(newPos) if newPos[2]>0: if random.random()>0.90: if not self.collisionBatimentBatiment(newPos, tailleTeste): if not self.collisionBatimentLigne(newPos, tailleTeste): if self.pointPlusProche(newPos)[1]<=self.longueurSegment: batiment = Batiment(newPos, orientation, tailleTeste, nouvImportance) self.batiments.append(batiment) self.ajoutBatPasse +=1 self.posBat+=1
def charge(self, fichier): def getCoord(point): point = point.replace("[","(") point = point.replace("]",")") pts = point.split("(")[1].split(")")[0].split(",") objs = [] for pt in pts: objs.append(float(pt)) return Vec3(*objs) i=0 j=0 self.sol=Sol() fichier = open(fichier) for ligne in fichier: elements = ligne.strip().split(">") cptElements=0 for element in elements: cptElements+=1 if cptElements%100==0: print "Chargement %i/%i\r" %(cptElements, len(elements)), type = element.split("||")[0] parametres = element.split("||")[1:] if type.lower()=="s": self.sol.tailleX = int(parametres[0].split("$$")[0]) self.sol.tailleY = int(parametres[0].split("$$")[1]) elif type.lower()=="t": if j==0: self.sol.sol.append([]) self.sol.sol[-1].append(float(parametres[0])) j+=1 if j>=self.sol.tailleY: j=0 i+=1 elif type.lower()=="e": if j==0: self.sol.eau.append([]) self.sol.eau[-1].append(float(parametres[0])) j+=1 if j>=self.sol.tailleY: j=0 i+=1 elif type.lower()=="r": pointA, pointB, taille = parametres pointA=getCoord(pointA) pointB=getCoord(pointB) taille=float(taille) if taille==1: taille=2 pointA[2]=self.sol.getAltitude(pointA)+1.1 pointB[2]=self.sol.getAltitude(pointB)+1.1 if pointA not in self.points: self.points.append(pointA) if pointB not in self.points: self.points.append(pointB) self.routes.append(Route(pointA, pointB, taille, self)) self.routes[-1].fabrique() elif type.lower()=="b": position, orientation, taille, importance = parametres position = getCoord(position) orientation = getCoord(orientation) taille = float(taille) importance = float(importance) self.batiments.append(Batiment(position, orientation, taille, importance)) elif type.lower()=="": pass else: print "inconnu", type, parametres raw_input() print if self.sol.eau==None or len(self.sol.eau)==0: print "Recalcul de l'eau... " self.sol.eau=[] for i in range(0, self.sol.tailleX): self.sol.eau.append([]) for j in range(0, self.sol.tailleY): self.sol.eau[i].append(0.0) self.sol.calculEau() t = len(self.routes) cpt=0 for route in self.routes: cpt+=1 if cpt%5==1: print "Creation des routes... %i/%i \r" %(cpt, t), #route.hauteQualite(self) route.fabrique() print self.sol.fabriqueVectrices()
class Jeu: def __init__(self): self.ecran = pygame.display.set_mode((1100, 600)) pygame.display.set_caption('Jeu Combat') self.jeu_encours = True self.joueur_x, self.joueur_y = 700, 200 self.joueur_vitesse_x = 0 self.joueur_taille = [32, 64] self.joueur = Joueur(self.joueur_x, self.joueur_y, self.joueur_taille) self.sol = Sol() self.gravite = (0, 10) self.resistance = (0, 0) self.clock = pygame.time.Clock() self.fps = 30 self.rect = pygame.Rect(0, 0, 1100, 600) self.collision_sol = False def gravite_jeu(self, vecteur1, vecteur2): self.joueur.rect.y += vecteur1[1] + vecteur2[1] def boucle_principale(self): while self.jeu_encours: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 10 if event.key == pygame.K_LEFT: self.joueur_vitesse_x = -10 if event.key == pygame.K_UP: self.joueur.a_sauter = True self.joueur.nombre_de_saut += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: self.joueur_vitesse_x = 0 if event.key == pygame.K_LEFT: self.joueur_vitesse_x = 0 if self.sol.rect.colliderect(self.joueur.rect): self.resistance = (0, -10) self.collision_sol = True self.joueur.nombre_de_saut = 0 else: self.resistance = (0, 0) if self.collision_sol and self.joueur.a_sauter: if self.joueur.nombre_de_saut < 2: self.joueur.sauter() self.joueur.rect.clamp_ip(self.rect) self.gravite_jeu(self.gravite, self.resistance) self.joueur.mouvement(self.joueur_vitesse_x) self.ecran.fill((255, 255, 255)) self.joueur.afficher(self.ecran) self.sol.afficher(self.ecran) pygame.draw.rect(self.ecran, (0, 255, 0), self.rect, 2) self.clock.tick(self.fps) pygame.display.flip()