def invasao(): pygame.init() tela = pygame.display.set_mode((LARGURA, ALTURA)) #criando a tela pygame.display.set_caption("Invasão") #titulo da tela jogador = Nave() #instancia do objeto nave ImagemFundo = pygame.image.load( 'image/espaço.jpg') #criando tela com a imagem do arquivo (instancia) jogando = True #jogador()nave comeca com true bomba = Disparo(LARGURA / 2, ALTURA - 70) #instancia a bomba grupo_inimigos = pygame.sprite.Group() #blocos amarelos todos_inimigos = pygame.sprite.Group() #todos blocos for i in range(20): x = random.randrange(LARGURA) y = random.randrange(ALTURA / 2) inimigo = Inimigo(AMARELO, 40, 20, x, y) grupo_inimigos.add(inimigo) todos_inimigos.add(grupo_inimigos) while True: jogador.movimento() bomba.trajetoria() for evento in pygame.event.get( ): #verifica se tem algum evento acontecendo if evento.type == QUIT: #se o evento for sair pygame.quit() #comando sair sys.exit() #garante que toda a aplicacao finalize if evento.type == pygame.KEYDOWN: #verifica se o evento foi feito a partir do teclado if evento.key == K_LEFT: #verifica se é o botaao esquerda que foi precionado jogador.rect.left -= jogador.velocidade #muda a posicao da nave para esquerda if evento.key == K_RIGHT: #verifica se o botao precionado foi a seta para direita jogador.rect.right += jogador.velocidade #muda a posicao para a direita if evento.key == K_SPACE: #verfica se a tecla precionada é o espaco x, y = jogador.rect.center # variaveis que recebe a posicao do jogador jogador.disparar( x, y ) #chama a funcao disparar epassa a mesma posicao do jogador if bomba.rect.colliderect(inimigo.rect): if todos_inimigos > 0: todos_inimigos.remove() tela.blit(ImagemFundo, (0, 0)) #coloca a imagem de fundo na tela bomba.colocar(tela) #coloca a bomba na tela jogador.colocar(tela) #coloca a nave na tela todos_inimigos.draw(tela) if len(jogador.listaDisparo ) > 0: #verifica se a lista de disparo é maior que 0 for x in jogador.listaDisparo: #variavel que percorre a lista x.colocar(tela) #coloca a bala na tela x.trajetoria() #faz percorrer a trajetoria if x.rect.top < -10: #verifica a bala ja passou da tela para remover jogador.listaDisparo.remove(x) #remove a bala da tela pygame.display.update() #atualiza a tela
def iniciarPartida(self): if (self.partidaIniciada == True): raise ExcecaoJogo("Uma partida ja foi iniciada") if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") self.partidaIniciada = True self.nave = Nave(self.tamX, self.tamY)
def RunJuego(self): pygame.mixer.music.fadeout(1200) time.sleep(1.2) self.set_musica("juego") self.nave = Nave(self.sprites, self) self.barra_de_estado = Barra_de_estado(self.nave) self.sprites.add(self.nave) self.sprites.add(self.barra_de_estado) self.sprites.clear(self.ventana, self.fondo) self.sprites.draw(self.ventana) self.fondo = self.get_fondo("en_juego") self.ventana.blit(self.fondo, (0,0)) self.estado = "en_juego" pygame.mouse.set_visible(False) pygame.display.update() self.tiempo = 0 self.pos_fondo = 0 while self.estado == "en_juego": self.reloj.tick(32) self.actualizar()
def jugar(self): self._oleada = Oleada() self._oleada.crearMeteoritos() self._personaje = Nave() self._oleada.crearMeteoritos() while ((self._personaje.gameOver()) == False): if (self.getEstadoJuego()): self.graficar() opcion = input() if (self.getEstadoJuego() == True): if (opcion == "a" or opcion == "d"): self._personaje.setDireccion(opcion) self.refrescar() elif (opcion == "w"): for i in range(self._personaje.getVelocidad()): self._personaje.avanzar() self.colision() self.refrescar() elif (opcion == "f"): if (len(Nave.disparos) < self._personaje.getNumDisparos()): self._personaje.crearDisparo() self.refrescar() elif (opcion == "p"): self.setEstadoJuego() else: self.refrescar() else: if (opcion == "p"): self.setEstadoJuego() else: if (self.getEstadoJuego() == True): self.refrescar() print(Mensajes.mensajes.get("GameOver")) if (input() == "1"): print(Mensajes.mensajes.get("IngreseSuNombre"), "Score ", Oleada.score) Juego.AgregarPuntaje() self._personaje = Nave() self._oleada.meteoros = [] Nave.disparos = []
def refrescar(self): if (len(self._oleada.meteoros) > 0): vel_m = int(self._oleada.meteoros[0].getVelocidad()) self._oleada.setCantidadDeTurnos( self._oleada.getCantidadDeTurnos() + 1) for j in range(vel_m): for i in range(len(self._oleada.meteoros)): self._oleada.meteoros[i].avanzar() self.colision() if (len(Nave.disparos) > 0): vel_d = Nave.disparos[0].getVelocidad() for j in range(vel_d): for i in range(len(Nave.disparos)): Nave.disparos[i].avanzar() self.colision() Nave.reducir_vu() if (self._personaje.getVida() == 0): return 0 else: if (self._personaje.getVida() == 0): return 0 opcion = 4 print( "Oleada Completada, Desea visitar la tienda?\n 1)Si 2)No 3)Finalizar" ) while (opcion != "1" and opcion != "2" and opcion != "3"): opcion = input() if (opcion == "1" or opcion == "2"): Nave.disparos = [] if (opcion == "1"): self._personaje = Tienda.comprar(self._personaje) self._personaje.setPosicionX(int(Resolution.resx / 2)) self._personaje.setPosicionY(int(Resolution.resy / 2)) self._oleada.setNumOleada(self._oleada.getNumOleada() + 1) self._oleada.crearMeteoritos() elif (opcion == "3"): self._personaje.setVida(0) return 0
def test_destruir_SinDano(self): invasor = Invasor(100, 0) nave = Nave(100, 60) invasor.destruir(nave) print("TEST - destruir nave sin daño ") self.assertTrue(nave.vida == 100)
from Zona import Zona from Nave import Nave # listas para registrar coordenadas que los robots han recorrido, de los obstaculos y de los recursos zonas_conocidas1 = [] zonas_conocidas2 = [] zonas_conocidas3 = [] zonas_conocidas4 = [] zonas_conocidas_general = [] obstaculos = [] recursos = [] # inicializamos compoenntes planeta = turtle.Screen() objetoNave = turtle.Turtle() nave = Nave(-200, 200, objetoNave) robot1 = turtle.Turtle() robot1.speed(0) robot1.shape("square") robot1.color("white") robot1.penup() robot1.goto(-200, 200) robot1.pendown() r1 = Agente(robot1, "explorando") robot2 = turtle.Turtle() robot2.speed(0) robot2.shape("square") robot2.color("orange") robot2.penup() robot2.goto(-200, 200) robot2.pendown()
def test_destruir(self): invasor = Invasor(100, 50) nave = Nave(100, 60) invasor.destruir(nave) print("TEST - destruir nave ") self.assertTrue(nave.vida == 40)
class Zeus(): def __init__(self): self.nave = None self.fondo = None self.menu = None self.ventana = None self.reloj = None self.estado = None self.pausa = False self.joystick = None self.actualizacion_de_joysticks_tiempo = 0 self.tiempo = 0 self.sprites = pygame.sprite.OrderedUpdates() def Run(self): pygame.mouse.set_visible(False) self.fondo = self.fondo self.ventana.blit(self.fondo, (0,0)) pygame.display.update() self.tiempo = 0 while self.estado == "presentacion": self.reloj.tick(32) self.actualizar() def RunMenu(self): pygame.mixer.music.fadeout(1200) time.sleep(1.2) self.menu = Menu(self) self.sprites.add(self.menu) self.set_musica("menu") self.fondo = self.get_fondo("menu") self.ventana.blit(self.fondo, (0,0)) pygame.display.update() self.tiempo = 0 while self.estado == "menu": self.reloj.tick(32) self.actualizar() def RunJuego(self): pygame.mixer.music.fadeout(1200) time.sleep(1.2) self.set_musica("juego") self.nave = Nave(self.sprites, self) self.barra_de_estado = Barra_de_estado(self.nave) self.sprites.add(self.nave) self.sprites.add(self.barra_de_estado) self.sprites.clear(self.ventana, self.fondo) self.sprites.draw(self.ventana) self.fondo = self.get_fondo("en_juego") self.ventana.blit(self.fondo, (0,0)) self.estado = "en_juego" pygame.mouse.set_visible(False) pygame.display.update() self.tiempo = 0 self.pos_fondo = 0 while self.estado == "en_juego": self.reloj.tick(32) self.actualizar() def RunFinJuego(self): self.nave.borrar_todo() self.sprites.clear(self.ventana, self.fondo) self.sprites.draw(self.ventana) self.fondo = self.get_fondo("fin_del_juego") self.ventana.blit(self.fondo, (0,0)) pygame.display.update() self.tiempo = 0 while self.estado == "fin_del_juego": self.reloj.tick(10) self.actualizar() def setup(self): pygame.init() pygame.font.init() pygame.mixer.init() self.actualizar_joysticks() self.segoepr = pygame.font.Font(SEGOE_PRINT, 30) pygame.display.set_mode(RESOLUCION, 0,0) pygame.display.set_caption(".: Zeus :.") pygame.display.set_icon(ICONO) #pygame.display.toggle_fullscreen() self.set_musica("inicio") self.ventana = pygame.display.get_surface() self.reloj = pygame.time.Clock() self.estado = "presentacion" self.fondo = self.get_fondo("inicio") self.sprites.draw(self.ventana) pygame.display.update() def get_fondo(self, tipo="inicio"): fondo = pygame.surface.Surface(RESOLUCION, flags=HWSURFACE) if tipo == "inicio": imagen = pygame.image.load(WALLPAPER) fondo.blit(imagen, POS_IMG) fondo.blit(self.segoepr.render(".: Presiona espacio para continuar :.", 1, AZUL), (350, 700)) elif tipo == "en_juego": imagen = pygame.image.load(NIVELES[self.get_configuracion("nivel")]) fondo.blit(imagen, (0,0)) elif tipo == "menu": imagen = pygame.image.load(WALLPAPER_2) fondo.blit(imagen, POS_IMG) elif tipo == "fin_del_juego": imagen = pygame.image.load(FIN_JUEGO) fondo.blit(imagen, POS_IMG) else: print "Ese fondo no existe, igual se retorna una superficie en negro" return fondo def set_musica(self, tipo="incio y menu"): if tipo == "inicio": pygame.mixer.music.load(MUSICA1) pygame.mixer.music.play(-1, 0.0) elif tipo == "menu": pygame.mixer.music.load(MUSICA2) pygame.mixer.music.play(-1, 0.0) elif tipo == "juego": pygame.mixer.music.load(MUSICA3) pygame.mixer.music.play(-1, 0.0) def handle_event(self): for event in pygame.event.get(): if event.type == QUIT: exit() elif event.type == KEYDOWN: if event.key == K_q: exit() elif event.key == K_ESCAPE and self.estado == "en_juego": self.set_pausa() if self.estado == "presentacion" and event.key == K_SPACE: self.estado = "menu" self.RunMenu() elif event.type == JOYBUTTONDOWN: if event.button == 8 and self.estado == "en_juego": self.set_pausa() if self.estado == "presentacion" and event.button == 0: self.estado = "menu" self.RunMenu() try: self.nave.evento(event) except: pass try: self.dialogo_pausa.actualizar_eventos(event) except: pass try: self.menu.actualizar_eventos(event) except: pass pygame.event.clear() def get_configuracion(self, tipo): # abrir archivo: config = open(CONFIGURACION, "r") configuracion = {"vol_FX": 0.7, "vol_musica": 0.5, "vol_musica_menu": 1.0, "nivel": 1} for cfg in config.readlines(): variable = cfg.split(" = ") nombre = variable[0] info = variable[1] if nombre == "vol_fx": configuracion["vol_FX"] = float(info) elif nombre == "vol_musica": configuracion["vol_musica"] = float(info) elif nombre == "vol_musica_menu": configuracion["vol_musica_menu"] = float(info) elif nombre == "nivel": configuracion["nivel"] = int(info) if tipo == "vol_FX": configuracion = configuracion["vol_FX"] elif tipo == "vol_musica": configuracion = configuracion["vol_musica"] elif tipo == "vol_musica_menu": configuracion = configuracion["vol_musica_menu"] elif tipo == "nivel": configuracion = configuracion["nivel"] return configuracion def get_tiempo(self): return int(self.tiempo) def set_pausa(self): if not self.pausa: self.pausa = True self.dialogo_pausa = Pausa(self) self.sprites.add(self.dialogo_pausa) elif self.pausa: self.dialogo_pausa.escape() def actualizar(self): self.tiempo += 0.032 self.actualizar_graficos() if self.actualizacion_de_joysticks_tiempo + TIEMPO_ACTUALIZACION_DE_JOYSTICKS <= self.get_tiempo(): self.actualizar_joysticks() self.actualizacion_de_joysticks_tiempo = self.get_tiempo() def actualizar_graficos(self, sprites=True): cambios=[] if self.estado == "en_juego": self.pos_fondo += 1 self.fondo = self.get_fondo(tipo = "en_juego") self.sprites.clear(self.ventana, self.fondo) if not self.pausa: self.sprites.update() elif self.pausa: self.dialogo_pausa.update() cambios.extend ( self.sprites.draw(self.ventana) ) self.handle_event() if sprites: pygame.display.update(cambios) elif not sprites: pygame.display.update() def actualizar_joysticks(self): if pygame.joystick.get_init(): pygame.joystick.quit() elif not pygame.joystick.get_init(): self.joystick = None pygame.joystick.init() if pygame.joystick.get_count(): self.joystick = pygame.joystick.Joystick(0) self.joystick.init() if self.joystick != None: "Joystick conectado" elif self.joystick == None: "Joystick desconectado"
def test_destruir_Nave(self): invasorGhost = InvasorGhost(100, 50) nave = Nave(100, 60) nave.destruirGhost(invasorGhost) print("TEST - destruir invasorGhost ") self.assertTrue(invasorGhost.vida == 100)
class Gerenciador(object): def __init__(self): self.jogoIniciado = False self.partidaIniciada = False self.salvouNoRanking = False self.tamX =800 self.tamY = 600 self.persistencia = Persistencia() self.ranking = self.persistencia.lerArquivo() def iniciarJogo (self): if (self.jogoIniciado == True): raise ExcecaoJogo("Um jogo ja foi iniciado") self.jogoIniciado = True self.nave = None self.listaTiros = [] self.listaNaves = [] # self.ranking = self.persistencia.lerArquivo() self.salvouNoRanking = False def moverNavesInimigas(self): for naveInimiga in self.listaNaves: naveInimiga.moverAleatorio() def moverTiros (self): for tiro in self.listaTiros: tiro.mover() if tiro.posY < 0: #neste caso o tamnho da nave self.listaTiros.remove(tiro) def iniciarPartida(self): if (self.partidaIniciada == True): raise ExcecaoJogo("Uma partida ja foi iniciada") if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") self.partidaIniciada = True self.nave = Nave(self.tamX, self.tamY) def jogoComecou(self): return self.jogoIniciado def getTamanhoTela(self): return (self.tamX, self.tamY) def getPosNave (self): return self.nave.getPos() def moverNave(self, deslocamentoX, deslocamentoY): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") self.nave.moverNave(deslocamentoX, deslocamentoY) def atacarInimigo(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") posNave = self.getPosNave() self.listaTiros.append(Tiro(posNave[0],posNave[1])) def adicionarNomeNoRanking(self, Nome): pontuacaoEnome = (Nome, self.getPontuacao()) self.adicionarNoRanking(pontuacaoEnome) self.ranking.sort(self.funcaoOrdenacaoRanking) self.ranking.reverse() def funcaoOrdenacaoRanking(self,a,b): if (a[1] == b[1]): return (-1) * cmp(a[0], b[0]) return cmp(a[1], b[1]) def getRanking(self): return self.ranking def adicionarNoRanking(self, pontuacaoENome): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == True): raise ExcecaoJogo("Partida em andamento") if(pontuacaoENome[1] == 0): raise ExcecaoJogo("Você precisa ter pontuação maior que zero") if (not(pontuacaoENome in self.ranking)): self.ranking.append(pontuacaoENome) self.ranking.sort() self.ranking.reverse() if (len(self.ranking )> 10): self.ranking.remove(self.ranking[10]) #salvar em arquivo self.persistencia.gravarArquivo( self.ranking ) def sairDaPartida(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") self.partidaIniciada = False tamanhoRanking = len(self.ranking) #retorna true se for para adicionar no ranking if ((tamanhoRanking == 0)): return True elif (self.nave.pontuacao >= (self.ranking[tamanhoRanking-1])[1]): return True elif (tamanhoRanking < 10): return True return False def sairDoJogo(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == True): raise ExcecaoJogo("Voce precisa terminar a partida antes de sair") self.jogoIniciado = False def getNivel(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") return self.nave.getNivel() def ganharVida(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") self.nave.ganharVida() nivel = self.nave.getNivel() if (nivel >= 6): tamanhoRanking = len(self.ranking) #retorna true se for para adicionar no ranking if (tamanhoRanking == 0): self.partidaIniciada = False return True elif (self.nave.pontuacao >= (self.ranking[tamanhoRanking-1])[1]): self.partidaIniciada = False return True elif (tamanhoRanking < 10): self.partidaIniciada = False return True else: return False return False def perderVida(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") vidasAcabaram = self.nave.perderVida() if (vidasAcabaram == True): return self.sairDaPartida() return False def partidaFoiIniciada(self): return self.partidaIniciada def criarNaveInimiga(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") escolhaPosX = random.choice listaPosicoes = range(0, self.tamX) naveInimiga = NaveInimigaComum(escolhaPosX(listaPosicoes), 50 , self.tamX, self.tamY) self.listaNaves.append(naveInimiga) def destruirNaveInimiga(self, nave): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") if (self.partidaIniciada == False): raise ExcecaoJogo("Partida não iniciada") if (nave in self.listaNaves): self.listaNaves.remove(nave) self.nave.pontuar() def getListaNaves(self): return self.listaNaves def getPontuacao(self): if (self.jogoIniciado == False): raise ExcecaoJogo("Jogo não iniciado") return self.nave.getPontuacao() def getListaTiros(self): return self.listaTiros def getVida(self): return self.nave.getVida()
def test_chocar_SinVel(self): invasor = InvasorGhost(100, 100) nave = Nave(100, 0) invasor.chocar(nave) print("TEST - chocar nave sin velocidad") self.assertTrue(nave.vida == 100)
def __init__(self, estado_juego=True, oleada=Oleada(), personaje=Nave()): self._estado_juego = estado_juego self._oleada = oleada self._personaje = personaje
def test_destruir_TodoDano(self): invasor = Invasor(100, 100) nave = Nave(100, 60) invasor.destruir(nave) print("TEST - destruir nave con todo el daño") self.assertLessEqual(nave.vida, 0)
def test_destruir(self): invasor = Invasor(100, 30) nave = Nave(100, 50) nave.destruir(invasor) print("TEST - destruir invasor") self.assertTrue(invasor.vida == 85)
def test_destruir_Invasor_SinDano(self): invasor = Invasor(100, 0) nave = Nave(100, 0) nave.destruir(invasor) print("TEST - destruir invasor sin daño ") self.assertTrue(invasor.vida == 100)
def test_destruir_TodoDano(self): invasor = Invasor(100, 100) nave = Nave(100, 100) nave.destruir(invasor) print("TEST - destruir invasor con todo el daño") self.assertTrue(invasor.vida == 0)
def test_chocar(self): invasor = Invasor(100, 30) nave = Nave(100, 100) invasor.chocar(nave) print("TEST - chocar nave ") self.assertTrue(nave.vida == 0)
def test_chocar_Nave_SinDano(self): nave = Nave(100, 50) asteroide = Asteroide(0) asteroide.chocarNave(nave) print("TEST - chocar nave sin daño ") self.assertTrue(nave.vida == 100)
def test_chocar_Nave_TodaVel(self): nave = Nave(100, 100) asteroide = Asteroide(100) asteroide.chocarNave(nave) print("TEST - chocar nave con toda velocidad ") self.assertTrue(nave.vida == 50)
def test_chocar_Nave(self): nave = Nave(100, 50) asteroide = Asteroide(40) asteroide.chocarNave(nave) print("TEST - chocar nave ") self.assertTrue(nave.vida == 90)
class Juego: def __init__(self, estado_juego=True, oleada=Oleada(), personaje=Nave()): self._estado_juego = estado_juego self._oleada = oleada self._personaje = personaje def idioma(): print("IDIOMA:\n1. ESPAÑOL\n2. INGLES") idioma = input("Por favor seleccion un idioma: ") if idioma == "1": Mensajes.mensajes = Mensajes.español else: Mensajes.mensajes = Mensajes.ingles def setEstadoJuego(self): if (self.getEstadoJuego() == True): self._estado_juego = False else: self._estado_juego = True def jugar(self): self._oleada = Oleada() self._oleada.crearMeteoritos() self._personaje = Nave() self._oleada.crearMeteoritos() while ((self._personaje.gameOver()) == False): if (self.getEstadoJuego()): self.graficar() opcion = input() if (self.getEstadoJuego() == True): if (opcion == "a" or opcion == "d"): self._personaje.setDireccion(opcion) self.refrescar() elif (opcion == "w"): for i in range(self._personaje.getVelocidad()): self._personaje.avanzar() self.colision() self.refrescar() elif (opcion == "f"): if (len(Nave.disparos) < self._personaje.getNumDisparos()): self._personaje.crearDisparo() self.refrescar() elif (opcion == "p"): self.setEstadoJuego() else: self.refrescar() else: if (opcion == "p"): self.setEstadoJuego() else: if (self.getEstadoJuego() == True): self.refrescar() print(Mensajes.mensajes.get("GameOver")) if (input() == "1"): print(Mensajes.mensajes.get("IngreseSuNombre"), "Score ", Oleada.score) Juego.AgregarPuntaje() self._personaje = Nave() self._oleada.meteoros = [] Nave.disparos = [] def getEstadoJuego(self): return self._estado_juego def colision(self): pila_m = [] pila_d = [] for i in range(len(self._oleada.meteoros)): for j in range(i + 1, len(self._oleada.meteoros)): if (self.verificar(self._oleada.meteoros[i], self._oleada.meteoros[j]) == True): self._oleada.meteoros[i].setVida( self._oleada.meteoros[i].getVida() - self._oleada.meteoros[j].getDamage()) self._oleada.meteoros[j].setVida( self._oleada.meteoros[j].getVida() - self._oleada.meteoros[i].getDamage()) if (not i in pila_m and self._oleada.meteoros[i].getVida() <= 0): pila_m.append(i) if (not j in pila_m and self._oleada.meteoros[j].getVida() <= 0): pila_m.append(j) for i in range(len(Nave.disparos)): for j in range(len(self._oleada.meteoros)): if (self.verificar(Nave.disparos[i], self._oleada.meteoros[j]) == True): self._oleada.meteoros[j].setVida( self._oleada.meteoros[j].getVida() - Nave.disparos[i].getDamage()) if (not i in pila_d): pila_d.append(i) if (not j in pila_m and self._oleada.meteoros[j].getVida() <= 0): pila_m.append(j) for i in range(len(self._oleada.meteoros)): if (self.verificar(self._personaje, self._oleada.meteoros[i])): self._personaje.setVida(self._personaje.getVida() - self._oleada.meteoros[i].getDamage()) if (not i in pila_m): pila_m.append(i) self._oleada.setMeteorosDestruidos( self._oleada.getMeteorosDestruidos() + 1) while (len(pila_m) > 0): self._oleada.meteoros.remove(self._oleada.meteoros[pila_m.pop()]) while (len(pila_d) > 0): Nave.disparos.remove(Nave.disparos[pila_d.pop()]) Oleada.score += 10 def verificar(self, first, second): arreglo_first = first.getHitBox() arreglo_second = second.getHitBox() for i in range(len(arreglo_second)): if (arreglo_second[i] in arreglo_first): return True return False def refrescar(self): if (len(self._oleada.meteoros) > 0): vel_m = int(self._oleada.meteoros[0].getVelocidad()) self._oleada.setCantidadDeTurnos( self._oleada.getCantidadDeTurnos() + 1) for j in range(vel_m): for i in range(len(self._oleada.meteoros)): self._oleada.meteoros[i].avanzar() self.colision() if (len(Nave.disparos) > 0): vel_d = Nave.disparos[0].getVelocidad() for j in range(vel_d): for i in range(len(Nave.disparos)): Nave.disparos[i].avanzar() self.colision() Nave.reducir_vu() if (self._personaje.getVida() == 0): return 0 else: if (self._personaje.getVida() == 0): return 0 opcion = 4 print( "Oleada Completada, Desea visitar la tienda?\n 1)Si 2)No 3)Finalizar" ) while (opcion != "1" and opcion != "2" and opcion != "3"): opcion = input() if (opcion == "1" or opcion == "2"): Nave.disparos = [] if (opcion == "1"): self._personaje = Tienda.comprar(self._personaje) self._personaje.setPosicionX(int(Resolution.resx / 2)) self._personaje.setPosicionY(int(Resolution.resy / 2)) self._oleada.setNumOleada(self._oleada.getNumOleada() + 1) self._oleada.crearMeteoritos() elif (opcion == "3"): self._personaje.setVida(0) return 0 def graficar(self): print("Oleada Numero: ", self._oleada.getNumOleada(), " Vidas: ", self._personaje.getVida(), "Score: ", Oleada.score, "Meteoros Restantes: ", len(self._oleada.meteoros), " EstadoJuego: ", self.getEstadoJuego(), " cantidad de turnos ", self._oleada.getCantidadDeTurnos()) for i in range(Resolution.resx): print("-", end="") print("\n") matriz = self.imprimirRadios(self._oleada.meteoros, Nave.disparos) matriz[self._personaje.getPosicionX()][ self._personaje.getPosicionY()] = self._personaje.getImagen() for i in range(len(self._oleada.meteoros)): matriz[self._oleada.meteoros[i].getPosicionX()][ self._oleada.meteoros[i].getPosicionY()] = "O" for i in range(len(Nave.disparos)): matriz[Nave.disparos[i].getPosicionX()][ Nave.disparos[i].getPosicionY()] = "*" for i in range(Resolution.resy + 1): print("|", end="") for j in range(Resolution.resx + 1): if matriz[j][i] == 0: print(".", end="") else: print(matriz[j][i], end="") print("|", end="") print("\n") for i in range(Resolution.resx): print("-", end="") print("\n") def imprimirRadios(self, listam, listad): matriz = [] for i in range(Resolution.resx + 1): matriz.append([0] * (Resolution.resy + 1)) for k in range(len(listam)): posx_aux = listam[k].getPosicionX() - listam[k].getMedidaHitBox() posy_aux = listam[k].getPosicionY() - listam[k].getMedidaHitBox() for i in range(2 * listam[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "O" posx_aux += 1 for i in range(2 * listam[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "O" posy_aux += 1 for i in range(2 * listam[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "O" posx_aux -= 1 for i in range(2 * listam[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "O" posy_aux -= 1 for k in range(len(listad)): posx_aux = listad[k].getPosicionX() - listad[k].getMedidaHitBox() posy_aux = listad[k].getPosicionY() - listad[k].getMedidaHitBox() for i in range(2 * listad[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "*" posx_aux += 1 for i in range(2 * listad[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "*" posy_aux += 1 for i in range(2 * listad[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "*" posx_aux -= 1 for i in range(2 * listad[k].getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = "*" posy_aux -= 1 posx_aux = self._personaje.getPosicionX( ) - self._personaje.getMedidaHitBox() posy_aux = self._personaje.getPosicionY( ) - self._personaje.getMedidaHitBox() for i in range(2 * self._personaje.getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = self._personaje.getImagen() posx_aux += 1 for i in range(2 * self._personaje.getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = self._personaje.getImagen() posy_aux += 1 for i in range(2 * self._personaje.getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = self._personaje.getImagen() posx_aux -= 1 for i in range(2 * self._personaje.getMedidaHitBox()): if (posy_aux >= 0 and posy_aux <= Resolution.resy and posx_aux >= 0 and posx_aux <= Resolution.resx): matriz[posx_aux][posy_aux] = self._personaje.getImagen() posy_aux -= 1 return matriz @staticmethod def AgregarPuntaje(): puntajes = open("MejoresPuntajes.txt", "a") datos = input()[0:5] datos += " " datos += str(Oleada.score) puntajes.write(datos + "\n") puntajes.close()
def nivel1(): # --- Creamos la ventana # Iniciamos Pygame pygame.init() auxc = 0 crono = 0 # Establecemos las dimensiones de la pantalla largo_pantalla = 750 alto_pantalla = 600 pantalla = pygame.display.set_mode([largo_pantalla, alto_pantalla]) # --- Lista de sprites # Esta es una lista de cada sprite, asi como de todos los bloques y del protagonista. lista_de_todos_los_sprites = pygame.sprite.Group() #Lista de impactos para los proyectiles que impacten lista_Impactos = pygame.sprite.Group() # Lista de cada proyectil lista_proyectiles = pygame.sprite.Group() lista_proyectilesE = pygame.sprite.Group() #Lista de explosiones lista_Explosiones = pygame.sprite.Group() lista_lifeBar_Damage = pygame.sprite.Group() #Inicando el vector de imagenes para la imagen del Miselanio listImg = [ "sp/exp/explotion1.png", "sp/exp/explotion2.png", "sp/exp/explotion3.png", "sp/exp/explotion4.png", "sp/exp/explotion5.png", "sp/exp/explotion6.png", "sp/exp/explotion7.png", "sp/exp/explotion8.png", "sp/exp/explotion9.png", "sp/exp/explotion9.png", "sp/exp/explotion10.png", "sp/exp/explotion11.png", "sp/exp/explotion12.png", "sp/exp/explotion13.png", "sp/exp/explotion14.png" ] aux = 0 for i in range(0, len(listImg)): aux = listImg[i] listImg[i] = pygame.image.load(aux).convert_alpha() # --- Creamos los sprites # Creamos el fondo fondoMovil = fondo("galaxy.jpg") # Creamos un bloque protagonista ROJO nave1 = Nave(30) lista_de_todos_los_sprites.add(nave1) #Creamos la barra de vida para el protagonista #lifebar1=life_Bar() #Creando naves enemigas lista_NavesE = pygame.sprite.Group() lista_NavesE2 = pygame.sprite.Group() lista_proyectilesBoss = pygame.sprite.Group() #trayectoriaTop=generarRutas(True) for i in range(1, 30): naveE = NaveE(["sp/nav1.png", "sp/nav1D.png"], 3) naveE.cambiovelocidad(-5, 0) naveE.setRect(600 + i * 300, 0) lista_NavesE.add(naveE) lista_de_todos_los_sprites.add(naveE) for i in range(1, 30): naveE = NaveE(["sp/nav1D3.png", "sp/nav1D.png"], 3) naveE.cambiovelocidad(-5, 0) naveE.setRect(600 + i * 300, 400) lista_NavesE2.add(naveE) lista_de_todos_los_sprites.add(naveE) jefe1 = NaveE(["sp/jefe1.png", "sp/jefe12.png"], 40) jefe1.setRect(800, 0) lista_de_todos_los_sprites.add(jefe1) # Iteramos hasta que el usuario presione el boton de salir. hecho = False # Para controlar la tasa de refresco de la pantalla reloj = pygame.time.Clock() nave1.setRect(0, 200) sonido = pygame.mixer.Sound("sounds/blaster.wav") sonido2 = pygame.mixer.Sound("sounds/blasterE.wav") sonidoExp = pygame.mixer.Sound("sounds/exp.wav") sonido.set_volume(0.3) sonido2.set_volume(0.3) sonidoExp.set_volume(1.0) cont = 1 barra1 = StatusBar(nave1.getLife(), True, 0, 0, "YOU") barra2 = StatusBar(jefe1.getLife(), False, 0, -100, "BOSS") crono1 = Cronometro(20) cronoGeneral = Cronometro(20) #fuente1=pygame.font.Font(None,48) bossDefeat = False pygame.mixer.music.load("OST/OST1.mp3") pygame.mixer.music.play(4) # -------- Bucle Principal ----------- while not hecho: # --- Procesamiento de Eventos if bossDefeat == False: hecho = activarControles(nave1, lista_proyectiles, lista_de_todos_los_sprites, sonido) else: for evento in pygame.event.get(): if evento.type == pygame.QUIT: hecho = True """for evento in pygame.event.get(): if evento.type == pygame.QUIT: hecho = True elif evento.type == pygame.KEYDOWN: if evento.key == pygame.K_LEFT: nave1.cambiovelocidad(-10,0) elif evento.key == pygame.K_RIGHT: nave1.cambiovelocidad(10,0) elif evento.key == pygame.K_UP: nave1.cambiovelocidad(0,-10) elif evento.key == pygame.K_DOWN: nave1.cambiovelocidad(0,10) # Reseteamos la velocidad cuando la tecla es hacia arriba elif evento.type == pygame.KEYUP: if evento.key == pygame.K_LEFT: nave1.cambiovelocidad(10,0) elif evento.key == pygame.K_RIGHT: nave1.cambiovelocidad(-10,0) elif evento.key == pygame.K_UP: nave1.cambiovelocidad(0,10) elif evento.key == pygame.K_DOWN: nave1.cambiovelocidad(0,-10) if evento.type==pygame.KEYDOWN: if evento.key == pygame.K_x: # Disparamos un proyectil si el usuario presiona la tecla x proyectil = Proyectil("sp/proyectil.png",60) # Configuramos el proyectil de forma que este donde el protagonista proyectil.rect.x = nave1.getRectX()+nave1.getWidth()-10 proyectil.rect.y = nave1.getRectY()+nave1.getHeight()/2-5 sonido.play() # Agregamos el proyectil a la lista lista_de_todos_los_sprites.add(proyectil) lista_proyectiles.add(proyectil)""" # --- Logica del Juego #texto1=fuente1.render("SCORE: "+str(nave1.getScore()),0,(255,230,245)) if jefe1.getRectY() % 5 == 0: jefe1.setImage(0) #print "\n Posicion del Fondo: "+str(fondoMovil.rect.x) if fondoMovil.rect.x == -1800: if jefe1.getRectY() == 0: jefe1.setRect(600, jefe1.getRectY()) jefe1.setCrono() jefe1.setCrono() jefe1.rect.y = 200 """if jefe1.getRectY()<150: jefe1.cambiovelocidad(0,1) elif jefe1.getRectY()>150: jefe1.cambiovelocidad(0,-1) if jefe1.getRectY()>=75 and jefe1.getRectY()<150: jefe1.cambiovelocidad(-1,0) print "\n Posicion jefe: "+str(jefe1.getRectX())+","+str(jefe1.getRectY())""" if jefe1.getRectX() < 400: jefe1.cambiovelocidad(1, 0) if jefe1.getRectX() > 400: jefe1.cambiovelocidad(-1, 0) #if jefe1.getRectY()%20==0: """proyectilJefe = Proyectil("sp/proyectil2.png",-80) sonido2.play() proyectilJefe.rect.x = jefe1.getRectX() proyectilJefe.rect.y = jefe1.getRectY()+jefe1.getHeight()/2 lista_proyectilesBoss.add(proyectilJefe) lista_de_todos_los_sprites.add(proyectilJefe)""" if jefe1.getCrono() == 2: multipleProyectil(jefe1, lista_proyectilesBoss, lista_de_todos_los_sprites, 30, False) multipleProyectil(jefe1, lista_proyectilesBoss, lista_de_todos_los_sprites, 30, False, 30, 0) sonido2.play() jefe1.setCrono(False) # Llamamos al metodo update() en todos los sprites lista_de_todos_los_sprites.update() #Se define el comportamiento de las naves enemigas for naveE in lista_NavesE2: if naveE.getRectX() == 0: lista_NavesE2.remove(naveE) lista_de_todos_los_sprites.remove(naveE) if naveE.getRectX() % -10 == 0: naveE.setImage(0) if naveE.getRectX() == 200 or naveE.getRectX() == 600: proyectilE = Proyectil("sp/proyectil2.png", -60) sonido2.play() proyectilE.rect.x = naveE.getRectX() - 10 if naveE.getRectX() == 500: proyectilE.rect.y = naveE.getRectY() + naveE.getHeight() else: proyectilE.rect.y = naveE.getRectY( ) + naveE.getHeight() / 2 # Agregamos el proyectil a la lista lista_de_todos_los_sprites.add(proyectilE) lista_proyectilesE.add(proyectilE) if naveE.getRectX() <= 370: naveE.setRect(naveE.getRectX(), 300) for naveE in lista_NavesE: if naveE.getRectX() == 0: lista_NavesE.remove(naveE) lista_de_todos_los_sprites.remove(naveE) naveE.setRect(naveE.getRectX(), 100) if naveE.getRectX() % -10 == 0: naveE.setImage(0) if naveE.getRectX() == 400 or naveE.getRectX() == 500: proyectilE = Proyectil("sp/proyectil2.png", -60) sonido2.play() proyectilE.rect.x = naveE.getRectX() - 10 if naveE.getRectX() == 500: proyectilE.rect.y = naveE.getRectY() + naveE.getHeight() else: proyectilE.rect.y = naveE.getRectY( ) + naveE.getHeight() / 2 # Agregamos el proyectil a la lista lista_de_todos_los_sprites.add(proyectilE) lista_proyectilesE.add(proyectilE) if naveE.getRectX() > 400: naveE.setRect(naveE.getRectX(), 150) if naveE.getRectX() <= 370: naveE.setRect(naveE.getRectX(), 200) for proyectilBoss in lista_proyectilesBoss: if pygame.sprite.collide_rect(proyectilBoss, nave1): nave1.setLife(-1) lista_proyectilesBoss.remove(proyectilBoss) lista_de_todos_los_sprites.remove(proyectilBoss) barra1.setLife(nave1.getLife()) if proyectilBoss.rect.x < 0: lista_proyectilesE.remove(proyectilBoss) lista_de_todos_los_sprites.remove(proyectilBoss) if proyectilBoss.rect.x > largo_pantalla: lista_proyectilesBoss.remove(proyectilBoss) lista_de_todos_los_sprites.remove(proyectilBoss) for proyectilE in lista_proyectilesE: if pygame.sprite.collide_rect(proyectilE, nave1): nave1.setLife(-1) lista_proyectilesE.remove(proyectilE) lista_de_todos_los_sprites.remove(proyectilE) barra1.setLife(nave1.getLife()) if proyectilE.rect.x < 0: lista_proyectilesE.remove(proyectilE) lista_de_todos_los_sprites.remove(proyectilE) if proyectilE.rect.x > largo_pantalla: lista_proyectilesE.remove(proyectilE) lista_de_todos_los_sprites.remove(proyectilE) # Calculamos la mecanica para cada proyectil for proyectil in lista_proyectiles: lista_naves_alcanzadas = pygame.sprite.spritecollide( proyectil, lista_NavesE, False) if jefe1.getLife() >= 1: if pygame.sprite.collide_rect(proyectil, jefe1): jefe1.setLife(-1) jefe1.setImage(1) nave1.setScore(20) barra1.setScore(nave1.getScore()) lista_proyectiles.remove(proyectil) lista_de_todos_los_sprites.remove(proyectil) barra2.setLife(jefe1.getLife()) if jefe1.getLife() == 0: nave1.setScore(500) bossDefeat = True barra1.setScore(nave1.getScore()) lista_de_todos_los_sprites.remove(jefe1) explotionBoss = Miselanio(listImg) explotionBoss.rect.x = jefe1.rect.x explotionBoss.rect.y = jefe1.rect.y lista_Explosiones.add(explotionBoss) lista_de_todos_los_sprites.add(explotionBoss) sonidoExp.play() removerProyectiles(lista_proyectilesBoss, lista_de_todos_los_sprites) colisionProyectiles(lista_proyectiles, lista_NavesE, naveE, nave1, barra1, lista_de_todos_los_sprites, listImg, sonidoExp, largo_pantalla, lista_Explosiones) colisionProyectiles(lista_proyectiles, lista_NavesE2, naveE, nave1, barra1, lista_de_todos_los_sprites, listImg, sonidoExp, largo_pantalla, lista_Explosiones) """ for naveE in lista_naves_alcanzadas: nave1.setScore(10) barra1.setScore(nave1.getScore()) naveE.setLife(-1) naveE.setImage(1) lista_proyectiles.remove(proyectil) lista_de_todos_los_sprites.remove(proyectil) if naveE.getLife()==0: lista_de_todos_los_sprites.remove(naveE) lista_NavesE.remove(naveE) explotion=Miselanio(listImg) explotion.rect.x=naveE.rect.x explotion.rect.y=naveE.rect.y lista_Explosiones.add(explotion) lista_de_todos_los_sprites.add(explotion) sonidoExp.play() #naveE.image=pygame.image.load("sp/nav1.png").convert_alpha() # Eliminamos el proyectil si vuela fuera de la pantalla if proyectil.rect.x > largo_pantalla: lista_proyectiles.remove(proyectil) lista_de_todos_los_sprites.remove(proyectil)""" for explosion in lista_Explosiones: if explosion.crono >= 2: lista_Explosiones.remove(explosion) lista_de_todos_los_sprites.remove(explosion) # --- Dibujamos un marco # Limpiamos la pantalla #pantalla.blit(fondo,(0,0)) #---actualizamos los efectos de estrellas fondoMovil.update(pantalla) # Dibujamos todos los sprites lista_de_todos_los_sprites.draw(pantalla) #nave1.show_life_bar(pantalla) impacto = False # Avanzamos y actualizamos la pantalla con todo lo que hemos dibujado. if bossDefeat and crono1.getTime() <= 2: crono1.Empezar(True) removerProyectiles(lista_proyectiles, lista_de_todos_los_sprites) removerProyectiles(lista_proyectilesBoss, lista_de_todos_los_sprites) movNave(nave1, crono1, 1) if fondoMovil.rect.x <= -1800: barra2.setPos(largo_pantalla - barra2.bannerRect.width, alto_pantalla - barra2.bannerRect.height) barra2.setLife(jefe1.getLife()) barra2.DrawStatusBar(pantalla) barra1.DrawStatusBar(pantalla) #pantalla.blit(texto1,(350,0)) pygame.display.flip() # --- Limitamos a 20 fps reloj.tick(20) pygame.quit()