def __init__(self): """Aquí se inicializan los atributos del tablero y de la pantalla de pygame que lo contiene""" self.jugador = Jugador() self.SCREEN_WIDTH = 640 self.widthtab = 640 self.SCREEN_HEIGHT = 640 self.heighttab = 640 self.xposition = 0 self.yposition = 0 self.tableros = [ 'tableros/tablero-azul-notacion.png', 'tableros/tablero-gris-notacion.png', 'tableros/tablero-marron-notacion.png', 'tableros/tablero-naranja-notacion.png', 'tableros/tablero-negro-notacion.png', 'tableros/tablero-rojo-notacion.png', 'tableros/tablero-verde-notacion.png', 'tableros/tablero-violeta-notacion.png' ] #pygame.init() self.opciones = { "1": 0, #self.tableros[0], "2": 1, #self.tableros[1], "3": 2, #self.tableros[2], "4": 3, #self.tableros[3], "5": 4, #self.tableros[4], "6": 5, #self.tableros[5], "7": 6, #self.tableros[6], "8": 7 #self.tableros[7] }
def buscarPartidaPendiente(): if connection_string == "": raise Exception("Inicializar Connection String") conn = pyodbc.connect(connection_string) cursor = conn.cursor() cursor.execute( "Select top 1 * From Partidas Where FechaFinalizacion Is Null Order by 1 Desc" ) dbPartida = cursor.fetchone() if dbPartida == None: return None partida = Partida() partida.idPartida = dbPartida[0] if dbPartida[3] != "" and dbPartida[3] != None: partida.cartas = json.loads(dbPartida[3]) if dbPartida[4] != "" and dbPartida[4] != None: partida.manoBanca = json.loads(dbPartida[4]) #Busco los jugadores y las manos #cursor2 = conn.cursor() cursor.execute("exec ObtenerDetallePartida ?", str(partida.idPartida)) for row in cursor: if row[3] in partida.jugadores: jugador = partida.jugadores[row[3]] else: jugador = Jugador(None) #jugador.usuario.nombre = row[3] jugador.apuestaInicial = row[2] return partida
def iniciarJugadores(self, jugadoresTotales): numJugadores=Utilidades.preguntarNumero("Número de jugadores humanos: [0,"+str(jugadoresTotales)+"]",0,jugadoresTotales) for i in range(numJugadores): nombre =input("Nombre del jugador "+str(i+1)+": ") self.jugadores.append(Jugador(nombre,False)) for i in range(jugadoresTotales-numJugadores): self.jugadores.append(Jugador("BOT_"+str(i+1),True))
def comprobar_fin_jugador(jugador): if jugador.vida() <= 0: print(f'¡El jugador {jugador.nombre()} queda descalificado!') Jugador.borrar_jugador(jugador) if len(jugador.jugadores()) <= 1: comprobar_fin_juego() input('Pulsa una tecla para continuar.')
def __init__(self): self.bolsa = Bolsa() self.jugador = Jugador(self.bolsa) self.jugador.set_nombre("sinNombre") # solo para realizar el test self.maquina = Jugador(self.bolsa) self.maquina.set_nombre("Rinfo") # solo para realizar el test self.palabra = Palabra()
def finalizar(): """El repartidor pregunta al jugador si quiere volver a jugar.""" Jugador.limpiar_jugadores() print('\nRepartidor.- Bueno, esto ha sido todo por ahora.') decision = repetir() if decision == True: sietemedia() else: print('(El repartidor se desvanece en la oscuridad.)')
def __init__(self, imatge, x, y): Jugador.__init__(self, imatge, x, y) self.angle = 0 self.v_angular = 250 self.original_image = self.image self.a = 400 self.dispara = False self.rellotge_refredament = pygame.time.Clock() self.temps_ultim_tret = 0 self.temps_refredament = 0.5
def agregar_final(self, user, punt): if self.vacia(): self.primero = self.ultimo = Jugador(user, punt) else: aux = self.ultimo self.ultimo = aux.siguiente = Jugador(user, punt) self.ultimo.anterior = aux self.primero.anterior = self.ultimo self.ultimo.siguiente = self.primero self.size += 1
def jugar(): """Gestiona la partida.""" while Jugador.jugadores() != []: Naipe.barajar() repartir_mesa(1) for jugador in list(Jugador.jugadores()): turno(jugador) comprobar_fin_jugador(jugador) comprobar_fin_ronda() recoger_mesa() comprobar_fin_juego()
def sietemedia(): global tuto global _inicio print('\n¡Bienvenido de nuevo al juego de las siete y media!') tutorial() if _inicio is False: Naipe.generar_baraja() _inicio = True num_humanos = int(input('¿Cuántos vamos a jugar?: ')) Jugador.asignar_humanos(num_humanos) jugar()
def principal(): Naipe.generar_baraja() Jugador.asignar_bots(4) Naipe.barajar() repartir_mesa(3) mostrar_mesa() print(f'Baraja descubierta:\n{Naipe.mostrar_baraja()}') repartir_mesa(3) mostrar_mesa() print(f'Naipes restantes:\n{Naipe.mostrar_baraja()}')
def comprobar_fin_ronda(): if Jugador.jugadores() == []: # Si no queda ningún jugador con vida finalizar() ganador = Jugador.get_jugador(0) for jugador in Jugador.jugadores(): if Naipe.sm_valores(jugador.mano()) > 7.5: continue if Naipe.sm_valores(ganador.mano()) > 7.5 or \ Naipe.sm_valores(ganador.mano()) < Naipe.sm_valores(jugador.mano()): ganador = jugador ganador.set_vida(ganador.vida() + 1) print(f'¡{ganador.nombre()} gana esta ronda, con '\ f'{Naipe.sm_valores(ganador.mano())} puntos!') input('Pulsa una tecla para comenzar una nueva ronda.')
def iniciarJuego(self, newGame, multijugador): self.crearFichas() self.barajarFichas() i = 0 inicio = 0 equipo = 1 if newGame: while (i < 4): if (multijugador): if (i % 2 == 0): equipo = 1 else: equipo = 2 print("\nEquipo {} !!".format(str(equipo))) correcto = False while (not correcto): correcto = True nombrePlayer = input( "Digite el nombre del Jugador no. {}: ".format( str(i + 1))) for player in self.jugadores: if player._nombre == nombrePlayer: print( "\nEl jugador ya ha sido registrado. Digite de nuevo" ) correcto = False break i += 1 self.jugadores.append(Jugador(nombrePlayer, i, equipo)) else: correcto = False while (not correcto): correcto = True nombrePlayer = input( "Digite el nombre del Jugador no. {}: ".format( str(i + 1))) for player in self.jugadores: if player._nombre == nombrePlayer: print( "\nEl jugador ya ha sido registrado. Digite de nuevo" ) correcto = False break i += 1 self.jugadores.append(Jugador(nombrePlayer, i, None)) for x in self.jugadores: x._fichas = self.asignarFichas(inicio) inicio += 7
def __init__(self, nombrePrimerJugador, primerElementoPrimerJugador, segundoElementoPrimerJugador, nombreSegundoJugador, primerElementoSegundoJugador, segundoElementoSegundoJugador): self.elementos = [ Elemento.FUEGO, Elemento.TIERRA, Elemento.AIRE, Elemento.AGUA ] self.__jugador_atacante__ = Jugador(nombrePrimerJugador, primerElementoPrimerJugador, segundoElementoPrimerJugador) self.__jugador_defensor__ = Jugador(nombreSegundoJugador, primerElementoSegundoJugador, segundoElementoSegundoJugador) if (nombrePrimerJugador == nombreSegundoJugador): raise ValueError("Nombres de monstruo idénticos")
def agregarJugador(self, usuario): jug = self.obtenerJugadorTotal(usuario.nombre) if jug == None: self.interrumpirTimer = True nuevoJugador = Jugador(usuario, self.diccionario) nuevoJugador.enviarMensaje(self.diccionario[usuario.idioma]["bienvenido"] + usuario.nombre + "") self.jugadoresTotales.append(nuevoJugador) for d in self.diccionario: jugadoresLenguaje = self.obtenerJugadoresIdioma(self.jugadoresTotales, d) self.notificarJugadores(jugadoresLenguaje, self.diccionario[d]["jugadorSeUnio"].replace("{0}", usuario.nombre)) self.decidirUsuario(nuevoJugador) else: for d in self.diccionario: jugadoresLenguaje = self.obtenerJugadoresIdioma(self.jugadoresTotales, d) self.notificarJugadores(jugadoresLenguaje, self.diccionario[d]["jugadorFondeo"].replace("{0}", usuario.nombre))
def __init__(self, color, nombre): Jugador.__init__(self, color, nombre) self.ronda = 0 self.orden_ronda = [] # Caracteristicas de personalidad self.proba_aceptada = 0 self.caracter = PER_NEUTRAL # Inventario self.tarjetas = {} self.cantidad_canjes = 0 # Tablero self.mis_continentes = []
def get(self): try: name = self.request.GET['name'] print(str.format("esto es el atrib {0}",name)) except: name = None if name == None: self.redirect("/main") return else: jugador=Jugador.query(ndb.AND(Jugador.name==name,Jugador.user_id==users.get_current_user().user_id())) teams=Equipo.query(ndb.AND(ndb.OR(Equipo.nameJug1==name,Equipo.nameJug2==name),Equipo.user_id==users.get_current_user().user_id())) names=[] for eq in teams: names.append(eq.name) eq.key.delete() games=Partida.query(Partida.user_id==users.get_current_user().user_id()) for ga in games: for name in names: if ga.nameEquipoA== name: ga.key.delete() if ga.nameEquipoB== name: ga.key.delete() for jug in jugador: jug.key.delete() time.sleep(1) self.redirect("/main")
def main(): url = "https://api-escapamet.vercel.app/" response = requests.get(url).json() inventario = {"Carnet": "No disponible", "Llave": "Disponible", "Cable HDMI": "No disponible", "Libro de matemáticas": "Disponible", "Título universitario": "No disponible", "Martillo": "Disponible", "Contraseña": "No Disponible", "Mensaje": "No disponible", "Disco duro": "No disponible", "Libro de física": "No disponible"} jugador = Jugador("Carlos","25","1234","Pepa"," "," ",inventario,3, 4, 3,3,"2",False,False,False,False,0) juego(jugador,response) #main()
def __init__(self, jugadores): if len(jugadores) < 2: raise AttributeError( 'No se puede crear un parques con menos de 2 jugadores') self.jugadores = [] self.tablero = [] self.escalera = [] # Las fichas que van al cielo self.fichas = [] self.carcel = set() self.cielo = set() # Las fichas que ya ganaron self.esperando_movimiento = False self.jugador_actual = None self.dados = Dados() self.ganador = None for datos in jugadores: jugador = Jugador(*datos) self.jugadores.append(jugador) if datos[2] == 1: self.jugador_actual = jugador for jugador in self.jugadores: for ficha in jugador.fichas: self.fichas.append(ficha) for ficha in self.fichas: self.carcel.add(ficha) self.construir_tablero()
def get(self): try: name = self.request.GET['name'] print(str.format("esto es el atrib {0}", name)) except: name = None if name == None: self.redirect("/main") return else: jugador = Jugador.query( ndb.AND(Jugador.name == name, Jugador.user_id == users.get_current_user().user_id())) teams = Equipo.query( ndb.AND( ndb.OR(Equipo.nameJug1 == name, Equipo.nameJug2 == name), Equipo.user_id == users.get_current_user().user_id())) names = [] for eq in teams: names.append(eq.name) eq.key.delete() games = Partida.query( Partida.user_id == users.get_current_user().user_id()) for ga in games: for name in names: if ga.nameEquipoA == name: ga.key.delete() if ga.nameEquipoB == name: ga.key.delete() for jug in jugador: jug.key.delete() time.sleep(1) self.redirect("/main")
def ver_jugadores_existentes(): """ Esta función muestra la información de todos los jugadores previamente almacenada en la base de datos de jugadores. Argumentos => n/a Retorna => \tSi hay jugadores registrados: imprime los jugadores numerados por orden de registro. \tSi el archivo .txt no existe (o sea, no hay nadie registrado): notifica que no existen jugadores registrados. """ jugadores = [] try: with open("/home/catato/proyecto-carrasquero/Database_Players.txt") as dbp: datos = dbp.readlines() if len(datos) == 0: print("\nTodavía no hay ningún jugador registrado.\n") else: for dato in datos: player = dato[:-1].split("//") jugadores.append(Jugador(player[0],player[1],player[2],player[3],player[4],player[5],player[6],player[7],player[8],player[9],player[10],player[11],player[12],player[13],player[14],player[15],player[16])) print("\n\t\JUGADORES REGISTRADOS (por orden de registro)\n") for i,jug in enumerate(jugadores): print("-"*2,str(i+1),"-"*18) print(jug.mostrar_jugador()) return True except FileNotFoundError: print("\nTodavía no hay ningún jugador registrado.\n") return False
def setUp(self): self.jugador = Jugador('ivan', n=8) self.tablero = self.jugador.tablero self.barco = BuquedeGuerra() self.puerto = Puerto() self.lancha = Lancha() self.avion = Kamikaze()
def get(self): try: name = self.request.GET['name'] print(str.format("esto es el atrib {0}",name)) except: name = None if name == None: self.redirect("/player") return else: jugadores=Jugador.query(Jugador.user_id==users.get_current_user().user_id()) partidas=Partida.query(Partida.user_id==users.get_current_user().user_id()) equipos=Equipo.query(Equipo.user_id==users.get_current_user().user_id()) for jugador in jugadores: if jugador.name==name: toret =jugador eq=[] for equipo in equipos: if equipo.nameJug1==name : flag=True for e in eq: if e.name==equipo.name:flag=False if flag==True:eq.append(equipoEnt(equipo.name,equipo.nameJug1,equipo.nameJug2,users.get_current_user().user_id())) if equipo.nameJug2==name : flag=True for e in eq: if e.name==equipo.name:flag=False if flag==True:eq.append(equipoEnt(equipo.name,equipo.nameJug1,equipo.nameJug2,users.get_current_user().user_id())) ga=[] for partida in partidas: for e in eq: if partida.nameEquipoA==e.name : flag=True for g in ga: if g.name==partida.name:flag=False if flag==True:ga.append(partidaEnt(partida.name,partida.nameEquipoA,partida.nameEquipoB,partida.estado,users.get_current_user().user_id())) if partida.nameEquipoB==e.name : flag=True for g in ga: if g.name==partida.name:flag=False if flag==True:ga.append(partidaEnt(partida.name,partida.nameEquipoA,partida.nameEquipoB,partida.estado,users.get_current_user().user_id())) template_values = { "name":toret.name, "posicion":toret.posicion, "equipos":eq, "partidas":ga } template = JINJA_ENVIRONMENT.get_template( "player.html" ) self.response.write(template.render(template_values));
def main(): albert = Mascota(1, 'Albert Rivera', 8, 7, 10) pablo_i = Mascota(2, 'Pablo Iglesias', 7, 9, 10) pedro = Mascota(3, 'Pedro Sánchez', 6, 4, 10) pablo_c = Mascota(4, 'Pablo Casado', 8, 3, 10) santiago = Mascota(5, 'Santiago Abascal', 9, 5, 10) mascotas_maquina = { '1': albert, '2': pablo_i, '3': pedro, '4': pablo_c, '5': santiago, } maquina = Jugador(mascotas_maquina) maquina.elegir_mascota_random() print(f'Ha aparecido {maquina.luchador.nombre} y te va a atacar') quim = Mascota(6, 'Quim Torra', 8, 5, 10) oriol = Mascota(7, 'Oriol Junqueras', 4, 6, 10) gabriel = Mascota(8, 'Gabriel Rufián', 5, 3, 10) jordi = Mascota(9, 'Jordi Sánchez', 3, 5, 10) carles = Mascota(10, 'Carles Puigdemont', 2, 4, 10) mascotas_jugador = { '6': quim, '7': oriol, '8': gabriel, '9': jordi, '10': carles, } jugador = Jugador(mascotas_jugador) try: jugador.elegir_mascota_por_teclado() except: print('Has seleccionado un indice de mascota incorrecto') turno = 0 while (maquina.luchador.esta_vivo() and jugador.luchador.esta_vivo()): if (turno % 2 == 0): accion(maquina.luchador, jugador.luchador) else: accion(jugador.luchador, maquina.luchador) turno += 1 if (maquina.luchador.vida > 0): print('Ha ganado la maquina') else: print('Ha ganado el jugador')
def __init__(self): """Aquí se inicializan los atributos del tablero y de la pantalla de pygame que lo contiene""" self.jugador = Jugador() self.pieza = Pieza() self.clock = pygame.time.Clock() self.SCREEN_WIDTH = 640 self.widthtab = 640 self.SCREEN_HEIGHT = 640 self.heighttab = 640 self.xposition = 0 self.yposition = 0 self.tableros = [ 'tableros/tablero-azul-notacion.png', 'tableros/tablero-gris-notacion.png', 'tableros/tablero-marron-notacion.png', 'tableros/tablero-naranja-notacion.png', 'tableros/tablero-negro-notacion.png', 'tableros/tablero-rojo-notacion.png', 'tableros/tablero-verde-notacion.png', 'tableros/tablero-violeta-notacion.png' ] #pygame.init() self.opciones = { "1": 0, #self.tableros[0], "2": 1, #self.tableros[1], "3": 2, #self.tableros[2], "4": 3, #self.tableros[3], "5": 4, #self.tableros[4], "6": 5, #self.tableros[5], "7": 6, #self.tableros[6], "8": 7 #self.tableros[7] } self.mascara_piezas = [ Rook, Knight, Bishop, King, Queen, Bishop, Knight, Rook ] + 8 * [Pawn] self.pos_blancas = list( zip(list(range(8)) + list(range(8)), [0] * 8 + [1] * 8)) self.pos_negras = list( zip(list(range(8)) + list(range(8)), [6] * 8 + [7] * 8)) self.pixel_blancas = self.pieza.cuadro_pixel(self.pos_blancas) self.pixel_negras = self.pieza.cuadro_pixel(self.pos_negras) self.seq_surfaces = list( zip(self.pieza.W + self.pieza.B, self.pixel_blancas + self.pixel_negras)) self.click_pos = ()
class Juego: def __init__(self): self.mazo=Mazo() self.mazo.barajar() self.jugador1=Jugador(self.reparto()) self.repartidor=Repartidor(self.reparto()) def jugar(self): print(self.jugador1.valormano()) while(self.jugador1.plantarse(self.jugador1.valormano())!=0): self.jugador1.recibir(self.mazo.dar_carta(0)) self.mazo.cartas.pop(0) while(self.repartidor.pedir(self.jugador1.valormano(),self.repartidor.valormano())!=0): self.repartidor.recibir(self.mazo.dar_carta(0)) self.mazo.cartas.pop(0) print(self.ganador(self.jugador1.valormano(),self.repartidor.valormano())) def ganador(self,vjuga,vrepa): if(vrepa>21 and vjuga<21): return "ganojugador" if (vjuga==vrepa or vrepa>vjuga): return "ganorepartidor" def reparto(self): listajugador = [] listajugador.append(self.mazo.dar_carta(0)) listajugador.append(self.mazo.dar_carta(1)) manojugador = Mano(listajugador) self.mazo.cartas.pop(0) self.mazo.cartas.pop(1) return manojugador
def __init__(self,name,nameJug1,nameJug2,user_id): self.__name=name jugadores=Jugador.query() for jugador in jugadores: if jugador.name==nameJug1: self.__jugador1=jugador if jugador.name==nameJug2: self.__jugador2=jugador self.__user_id=user_id
def getJugador(self,idf): if idf == "c": self.jugador = Jugador() elif idf == "n": self.jugador = Jugador_adapter() self.jugador.set_sprites(self.__builder.get_sprites()) return self.jugador
def consultar_jugadores( self, nombre): #Se consulta si el jugador esta en la base de datos if f'{nombre}' in self.datos: #Si el jugador esta en la base de datos, se crea un nuevo objeto jugador con los datos existentes jugador = Jugador(self.datos[f'{nombre}']['nombre'], self.datos[f'{nombre}']['vencedor'], self.datos[f'{nombre}']['puesto_reciente']) return jugador else: return self.nuevo_jugador(nombre)
def jugador_existente(tiempo_vida_pistas): """Esta función revisa la base de datos y verifica si existen jugadores que coincidan con el usuario y clave ingresados por el jugador. Args: tiempo_vida_pistas (diccionario): Este diccionario consolida la información de dificultad de acuerdo a la preferencia indicada por el usuario. Se necesita porque una vez identificado el usuario hay que inicializarlo nuevamente. Returns: Bool: Retorna falso si el usuario no existe o si no hay usuarios registrados hasta el momento. Objeto: Si encuentra un jugador que coincide con la combinación nombre + contraseña retorna un objeto de tipo jugador inicializado en cero con nombre, contraseña... asociados a lo ingresado por el usuario. """ jugadores = [] try: with open("/home/catato/proyecto-carrasquero/Database_Players.txt") as dbp: datos = dbp.readlines() if len(datos) == 0: print("\nTodavía no hay ningún jugador registrado.\n") return False else: for dato in datos: player = dato[:-1].split("//") jugadores.append(Jugador(player[0],player[1],player[2],player[3],player[4],player[5],player[6],player[7],player[8],player[9],player[10],player[11],player[12],player[13],player[14],player[15],player[16])) nombre_jugador = input('Ingrese el nombre del jugador: ') while not nombre_jugador.isalpha(): print('Error') nombre_jugador = input('> ') while True: for i in jugadores: if nombre_jugador == i.nombre: clave = input('Ingrese la contraseña: ') while True: if clave == i.clave: print('Autenticación exitosa') print(f'Bienvenido de vuelva {i.nombre} // {i.avatar}') i.nivel_dificultad = tiempo_vida_pistas["Nivel de dificultad"] i.tiempo = tiempo_vida_pistas["Tiempo"] i.pistas = tiempo_vida_pistas["Pistas"] i.vida = tiempo_vida_pistas["Vida"] i.vida_inicial = tiempo_vida_pistas["Vida"] i.saman = False i.biblioteca = False i.laboratorio = False i.puerta_laboratorio = False i.tiempo_realizado = " " i.ubicacion = 0 i.inventario = {"Carnet": "No disponible", "Llave": "No disponible", "Cable HDMI": "No disponible", "Libro de matemáticas": "No disponible", "Título universitario": "No disponible", "Martillo": "No disponible", "Contraseña": "No Disponible"} return i else: print('Clave inválida. Intente nuevamente.\nSi olvidó su clave ingrese "x".') clave = input('> ') if clave == "x": return False print('El nombre de usuario no existe') nombre_jugador = input('Intente nuevamente: ') except FileNotFoundError: print("\nTodavía no hay ningún jugador registrado.\n") return False
def login(self): print('Bienvendido a Bummer UC ') print('[0]: 1 Jugador') print('[1]: 2 Jugadores') choice = loop(ask_number, [2], (IndexError, ValueError), '', '') if choice == 1: print('Dimension del tablero: ') n = loop(ask_number, [12], (IndexError, ValueError), '', '') self.jugador1 = Jugador(input('Nombre Jugador 1: \n'), n) self.jugador2 = Jugador(input('Nombre Jugador 2: \n'), n) else: self.jugador1 = Jugador(input('Nombre Jugador 1: \n'), 8) self.jugador2 = Computador('Computador 1', 8) self.jugador1.oponente = self.jugador2 self.jugador2.oponente = self.jugador1
def get(self): pla=Jugador.query(Jugador.user_id==users.get_current_user().user_id()) players=[] for p in pla:players.append(p) template_values = { "jugadores":players } template = JINJA_ENVIRONMENT.get_template( "addPlayer.html" ) self.response.write(template.render(template_values));
class Juego(object): def __init__(self, _gestor_estados): self.fondo = cargar_img("fondos/fondo") self.jugador = Jugador() self.pelota = Pelota() self.escenario = Escenario() def dibujar(self, _pantalla): _pantalla.blit(self.fondo, (20, 0)) self.jugador.render(_pantalla) self.pelota.dibujar(_pantalla) self.escenario.dibujar(_pantalla) def actualizar(self, _dt): self.jugador.actualizar(_dt) self.pelota.actualizar(_dt, self.jugador) self.escenario.actualizar(_dt, self.pelota)
def rastrea(self): for fila in self.html( "table.sdata_table>tbody>tr[itemprop='employee']"): info = PyQuery(fila) nombre = info('.sdata_player_name').text() url = info('.sdata_player_name>a').attr('href') """ hay jugadores que no tienen dorsal, peso o altura (muy pocos) si no tienen se quedan con este valor """ dorsal = 0 altura = 0 peso = 0 print("Rastreando", nombre, "......") if info('td').eq(0).text().strip() != '': dorsal = int(info('td').eq(0).text()) if info('td.dat').eq(0).text() != '-': altura = int(info('td.dat').eq(0).text()) if info('td.dat').eq(1).text() != '-': peso = int(info('td.dat').eq(1).text()) imagen = info('.sdata_player_img>a>img').attr('src') id_rf = Util.get_id_jugador(imagen, url) # print(, info('.sdata_player_name>a').attr('href')) jugador = Jugador("https://www.resultados-futbol.com" + url) jugador.rastrea() self.modelo['data'].append({ 'id_resultados_futbol': int(id_rf), 'nombre': nombre, 'nombre_completo': jugador.nombre_completo, 'fecha_nacimiento': jugador.fecha_nacimiento, 'pais': jugador.pais_nacimiento, 'nacionalidad': jugador.nacionalidad, 'dorsal': dorsal, 'altura': altura, 'peso': peso, 'posicion': jugador.posicion, 'imagen': imagen[:imagen.find('?')] })
def iniciar_testeo_jugador(): dbacceso.activar_testeo() dbacceso.insert_db('delete from jugador') #cliente.Jugador.crear_ejemplos() nombres = ["juan", "pepe", "pedro", "samuel", "diego", "cristian", "marcos", "lionel", "victor"] clubes = ["independiente", "boca", "racing", "colon", "lanus"] posiciones = ["defensor", "delantero", "volante", "arquero"] ln = len(nombres) lc = len(clubes) lp = len(posiciones) for x in range(24): Jugador( Jugador.ultimo_codigo()+1, nombres[x%ln], clubes[x%lc], posiciones[x%lp], random.randint(1000, 1000000) ).guardar_bd() Jugador( Jugador.ultimo_codigo()+1, "ricardito", "river", "defensor", 2345235 ).guardar_bd() Jugador( Jugador.ultimo_codigo()+1, "rubencito", "central", "defensor", 4234231 ).guardar_bd()
def get(self): pla=Jugador.query(Jugador.user_id==users.get_current_user().user_id()) equ=Equipo.query(Equipo.user_id==users.get_current_user().user_id()) players=[] equipos=[] for p in pla:players.append(p) for p in equ:equipos.append(p) template_values = { "jugadores":players, "equipos":equipos } template = JINJA_ENVIRONMENT.get_template( "addTeam.html" ) self.response.write(template.render(template_values));
def get(self): try: name = self.request.GET['name'] print(str.format("esto es el atrib {0}",name)) except: name = None if name == None: self.redirect("/game") return else: partidas=Partida.query(Partida.user_id==users.get_current_user().user_id()) for partida in partidas: if partida.name==name: toret =partida equipos=Equipo.query(Equipo.user_id==users.get_current_user().user_id()) for equipo in equipos: if equipo.id==toret.idEquipoA: e1 =equipo for equipo in equipos: if equipo.id==toret.idEquipoB: e2 =equipo jugadores=Jugador.query(Jugador.user_id==users.get_current_user().user_id()) for jugador in jugadores: if jugador.id==e1.idJug1: j1 =jugador for jugador in jugadores: if jugador.id==e1.idJug2: j2 =jugador for jugador in jugadores: if jugador.id==e2.idJug1: j3 =jugador for jugador in jugadores: if jugador.id==e2.idJug2: j4 =jugador template_values = { "partida":toret, "e1":e1, "e2":e2, "j1":j1, "j2":j2, "j3":j3, "j4":j4 } template = JINJA_ENVIRONMENT.get_template( "game.html" ) self.response.write(template.render(template_values));
def get(self): def montaEquipos(self): toret=[] for equipo in Equipo.query(Equipo.user_id==users.get_current_user().user_id()): toret.append(equipoEnt(equipo.name,equipo.nameJug1,equipo.nameJug2,users.get_current_user().user_id())) return toret def montaPartidas(self): toret=[] for partida in Partida.query(Partida.user_id==users.get_current_user().user_id()): toret.append(partidaEnt(partida.name,partida.nameEquipoA,partida.nameEquipoB,partida.estado,users.get_current_user().user_id())) return toret user = users.get_current_user() user_name = user.email() print("llegoaki") access_link = users.create_logout_url("/") juga = Jugador.query(Jugador.user_id==users.get_current_user().user_id()) jugadores=[] for j in juga: jugadores.append(j) equipos = montaEquipos(self) partidas = montaPartidas(self) template_values = { "user_name": user_name, "access_link": access_link, "partidas":partidas, "jugadores":jugadores, "equipos":equipos } template = JINJA_ENVIRONMENT.get_template( "mainMenu.html" ) self.response.write(template.render(template_values));
def logeo(Cliente, username, password): mensaje = {"Status": 2, "Action": 1, "Username": username, "Password": password} recibido = Cliente.responder_tps(mensaje) if recibido["Status"] == True: from jugador import Jugador player = recibido["Answer"] Jugador = Jugador() Jugador.establecer_Id(player["ID"]) Jugador.establecer_nombre("username") Jugador.establecer_nivel("nivel") Jugador.establecer_experiencia("experiencia") Jugador.establecer_gold("gold") Jugador.establecer_silver("silver") Jugador.establecer_deck("deck") Jugador.establecer_coleccion("coleccion") Jugador.establecer_rank("rank") return (True, Jugador) else: error = recibido["Answer"] return (False, error)
def jugar(surface, fps_clock): #------------------Fondo imagen_fondo = pygame.image.load("imagenes/imagen_fondo.jpg") #------------------Jugadores jugador1 = Jugador([500, ALTO_SCREEN-39]) jugador1.direccion = 'derecha' jugador2 = Jugador([600, ALTO_SCREEN-39]) jugador2.direccion = 'izquierda' #------------------Tiles y disparos # piedra = pygame.image.load("imagenes/tile_piedra.png") lista_disparos_j1 = pygame.sprite.Group() # Se almacenan los disparos del jugador 1 lista_disparos_j2 = pygame.sprite.Group() # Se almacenan los disparos del jugador 2 #========================BUCLE========================== while True: # main game loop for event in pygame.event.get(): if event.type == pygame.locals.QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: #------------------Movimiento y ataque jugador 1 if event.key == K_a: jugador1.moverse = True jugador1.direccion = 'izquierda' elif event.key == K_d: jugador1.moverse = True jugador1.direccion = 'derecha' elif event.key == K_w: jugador1.salto = 25 # La fuerza irá bajando gracias a la gravedad que se aplicará en cada vuelta elif event.key == K_SPACE: jugador1.disparar = True elif event.key == K_1: jugador1.tipo_disparo = jugador1.tipos_disparos[0] # Cambiar el tipo de disparo a manzana elif event.key == K_2: jugador1.tipo_disparo = jugador1.tipos_disparos[1] # Cambiar el tipo de disparo a plátano elif event.key == K_3: jugador1.tipo_disparo = jugador1.tipos_disparos[2] # Cambiar el tipo de disparo a melón #------------------Movimiento y ataque jugador 2 if event.key == K_LEFT: jugador2.moverse = True jugador2.direccion = 'izquierda' elif event.key == K_RIGHT: jugador2.moverse = True jugador2.direccion = 'derecha' elif event.key == K_UP: jugador2.salto = 25 # La fuerza irá bajando gracias a la gravedad que se aplicará en cada vuelta elif event.key == K_KP_ENTER: jugador2.disparar = True elif event.key == K_KP1: jugador2.tipo_disparo = jugador2.tipos_disparos[0] # Cambiar el tipo de disparo a manzana elif event.key == K_KP2: jugador2.tipo_disparo = jugador2.tipos_disparos[1] # Cambiar el tipo de disparo a plátano elif event.key == K_KP3: jugador2.tipo_disparo = jugador2.tipos_disparos[2] # Cambiar el tipo de disparo a melón elif event.type == KEYUP: tecla_pulsada = pygame.key.get_pressed() # Para que siga moviéndose si mantienes dos teclas pulsadas al mismo tiempo y sueltas una #------------------Movimiento y ataque jugador 1 if event.key == K_a: jugador1.moverse = False if tecla_pulsada[K_d]: jugador1.moverse = True jugador1.direccion = 'derecha' elif event.key == K_d: jugador1.moverse = False if tecla_pulsada[K_a]: jugador1.moverse = True jugador1.direccion = 'izquierda' elif event.key == K_SPACE: jugador1.disparar = False #------------------Movimiento y ataque jugador 2 if event.key == K_LEFT: jugador2.moverse = False if tecla_pulsada[K_RIGHT]: jugador2.moverse = True jugador2.direccion = 'derecha' elif event.key == K_RIGHT: jugador2.moverse = False if tecla_pulsada[K_LEFT]: jugador2.moverse = True jugador2.direccion = 'izquierda' elif event.key == K_KP_ENTER: jugador2.disparar = False #------------------Actualizar disparos jugador 1 jugador1.actualizar_frecuencia_disparos() # Esperar un rato para poder lanzar el siguiente disparo if jugador1.disparar == True: jugador1.atacar(lista_disparos_j1) #------------------Actualizar disparos jugador 2 jugador2.actualizar_frecuencia_disparos() # Esperar un rato para poder lanzar el siguiente disparo if jugador2.disparar == True: jugador2.atacar(lista_disparos_j2) #========================UPDATE========================== #------------------Surface surface.blit(imagen_fondo, (0, 0)) #------------------Jugadores movimiento_jugador(jugador1, jugador1.images) # Cambiamos la imagen según su movimiento jugador1.ajustar_posicion() # Si se sale de la pantalla surface.blit(jugador1.image, (jugador1.rect.x, jugador1.rect.y)) movimiento_jugador(jugador2, jugador2.images) # Cambiamos la imagen según su movimiento jugador2.ajustar_posicion() # Si se sale de la pantalla surface.blit(jugador2.image, (jugador2.rect.x, jugador2.rect.y)) #------------------Frutas/disparos #--Jugador 1 for disparo in lista_disparos_j1: disparo.ajustar_posicion() colision = pygame.sprite.spritecollide(jugador2, lista_disparos_j1, True, pygame.sprite.collide_mask) if colision != []: # Si hay una colisión jugador2.life -= disparo.daño disparo.kill() # Eliminamos el disparo else: surface.blit(disparo.image, (disparo.rect.x, disparo.rect.y)) #--Jugador 2 for disparo in lista_disparos_j2: disparo.ajustar_posicion() colision = pygame.sprite.spritecollide(jugador1, lista_disparos_j2, True, pygame.sprite.collide_mask) if colision != []: # Si hay una colisión jugador1.life -= disparo.daño disparo.kill() # Eliminamos el disparo else: surface.blit(disparo.image, (disparo.rect.x, disparo.rect.y)) #------------------Dibujar, FPS pygame.display.update() fps_clock.tick(FPS)
def jugar(pygame, constantes, pantalla,jugador): """ Clase principal en el que se debe ejecutar el juego. """ tiempo_comienzo = time() + 150 # Creamos al jugador con la imagen p1_walk.png jugador_principal = Jugador(jugador) letraParaPuntos = pygame.font.Font(None, 50) letraParaVidas = pygame.font.Font(None, 50) letraParaGameOver = pygame.font.Font(None, 45) relojmarcador = pygame.image.load("imagenes/relojmarcador.png") puntosmarcador = pygame.image.load("imagenes/llave.png") vidasmarcador = pygame.image.load("imagenes/vidas.png") gameovertime = pygame.image.load("imagenes/gameovertime.png") gameover = pygame.image.load("imagenes/gameover.png") # Creamos todos los niveles del juego lista_niveles = [] lista_niveles.append(Habitacion_1(jugador_principal)) lista_niveles.append(Habitacion_2(jugador_principal)) lista_niveles.append(Habitacion_3(jugador_principal)) lista_niveles.append(Habitacion_4(jugador_principal)) lista_niveles.append(Habitacion_5(jugador_principal)) lista_niveles.append(Habitacion_6(jugador_principal)) # Seteamos cual es el primer nivel. numero_del_nivel_actual = 0 nivel_actual = lista_niveles[numero_del_nivel_actual] lista_sprites_activos = pygame.sprite.Group() jugador_principal.nivel = nivel_actual jugador_principal.rect.x = 380 jugador_principal.rect.y = 140 lista_sprites_activos.add(jugador_principal) #Variable booleano que nos avisa cuando el usuario aprieta el boton salir. salir = False clock = pygame.time.Clock() # -------- Loop Princiapl ----------- while not salir: for evento in pygame.event.get(): if evento.type == pygame.QUIT: salir = True if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_UP: jugador_principal.arriba() elif (evento.key == pygame.K_DOWN): jugador_principal.abajo() elif evento.key == pygame.K_LEFT: jugador_principal.izquierda() elif evento.key == pygame.K_RIGHT: jugador_principal.derecha() elif evento.key == pygame.K_ESCAPE: salir = True elif evento.type == pygame.KEYUP: if evento.key == pygame.K_LEFT and jugador_principal.mover_x < 0: jugador_principal.parar() elif evento.key == pygame.K_RIGHT and jugador_principal.mover_x > 0: jugador_principal.parar() elif evento.key == pygame.K_UP and jugador_principal.mover_y < 0: jugador_principal.parar() elif evento.key == pygame.K_DOWN and jugador_principal.mover_y > 0: jugador_principal.parar() #elif evento.type==VIDEORESIZE: #pantalla=pygame.display.set_mode(evento.dict['size'],HWSURFACE|DOUBLEBUF|RESIZABLE) #fondo_escala = pygame.transform.scale(nivel_actual.fondo,evento.dict['size']) #nivel_actual.fondo = fondo_escala #pantalla.blit(fondo_escala,(0,0)) #pygame.display.flip() # Actualiza todo el jugador lista_sprites_activos.update() # Actualiza los elementos del nivel nivel_actual.update() if (jugador_principal.llave and jugador_principal.puntos_por_nivel == len(jugador_principal.nivel.lista_puntos)): if (numero_del_nivel_actual < len(lista_niveles) - 1): numero_del_nivel_actual += 1 nivel_actual = lista_niveles[numero_del_nivel_actual] jugador_principal.nivel = nivel_actual jugador_principal.llave = False if numero_del_nivel_actual == 1 : jugador_principal.rect.x = 400 jugador_principal.rect.y = 600 if numero_del_nivel_actual == 2 : jugador_principal.rect.x = 620 jugador_principal.rect.y = 400 if numero_del_nivel_actual == 3 : jugador_principal.rect.x = 419 jugador_principal.rect.y = 677 if numero_del_nivel_actual == 4 : jugador_principal.rect.x = 710 jugador_principal.rect.y = 400 if numero_del_nivel_actual == 5 : jugador_principal.rect.x = 436 jugador_principal.rect.y = 100 print "Posicion x", jugador_principal.rect.x, "Posicion y", jugador_principal.rect.y # TODO EL CODIGO PARA DIBUJAR DEBE IR DEBAJO DE ESTE COMENTARIO. nivel_actual.draw(pantalla) lista_sprites_activos.draw(pantalla) textoPuntos = letraParaPuntos.render("" + str(jugador_principal.puntos), 1, constantes.NEGRO) pantalla.blit(puntosmarcador, (70, 810)) pantalla.blit(textoPuntos, (110, 820)) textoVidas = letraParaVidas.render("" + str(jugador_principal.vidas), 1, constantes.ROJO) pantalla.blit(vidasmarcador, (280, 810)) pantalla.blit(textoVidas, (325, 820)) tiempo_transcurrido = int(tiempo_comienzo - time()) textotiempo =letraParaPuntos.render("" + str(tiempo_transcurrido), 1, constantes.NEGRO) pantalla.blit(relojmarcador, (160, 820)) pantalla.blit(textotiempo, (210, 820)) # TODO EL CODIGO PARA DIBUJAR DEBE IR POR ARRIBA DE ESTE COMENTARIO. if jugador_principal.vidas == 0: pantalla.fill(constantes.NEGRO) pantalla.blit(gameover, [0,0]) pygame.display.flip() pygame.event.wait() salir = True menuPrincipal(pygame, constantes, pantalla) if tiempo_transcurrido == 0: pantalla.fill(constantes.NEGRO) pantalla.blit(gameovertime,[0,0] ) pygame.display.flip() pygame.event.wait() salir = True menuPrincipal(pygame, constantes, pantalla) clock.tick(60) pygame.display.flip() #salgo del juego return True