Пример #1
0
 def acceder(self, Invitado=""):
     fetch = []
     if Invitado == "":
         repeticion = True
         while repeticion == True:
             acceso = input("Introduce tu usuario\n")
             acc = input("Introduce tu contrasenia\n")
             acc_pass = self.encriptar(acc)
             string_acceso = "SELECT nombre,pk_id_jugador FROM Jugador WHERE nombre='" + acceso + "' AND password='******'"
             self.cursor.execute(string_acceso)
             fetch = self.cursor.fetchall()
             self.connection.commit()
             #print(fetch)
             if fetch == []:
                 valor = input(
                     "El usuario no existe, estas registrado(n)? Si se equivoco en contrasenia o usuario, ingrese lo que sea e intente de nuevo\n"
                 ).lower()
                 if valor == "n":
                     self.registrar()
             else:
                 jugador = Jugador(self.cursor, self.connection,
                                   fetch[0][0], fetch[0][1])
                 repeticion = False
     else:
         string_invitado = "SELECT pk_id_jugador FROM Jugador WHERE nombre='invitado'"
         self.cursor.execute(string_invitado)
         fetch = self.cursor.fetchall()
         self.connection.commit()
         jugador = Jugador(self.cursor, self.connection, "invitado",
                           fetch[0][0])
     #print(jugador.getNombre())
     return jugador
Пример #2
0
def test_expectancia():
    Jugador1 = Jugador(1500)
    Jugador2 = Jugador(1800)
    var1 = Jugador1.getExpectancia(Jugador2.elo)

    assert (var1 > 0.150979557
            and var1 < 0.150979558), "Fallo en calculo expectancia"
    assert Jugador1.getExpectancia(
        Jugador1.elo) == 0.5, "Fallo en calculo expectancia"
Пример #3
0
def test_percentil():
    Jugador1 = Jugador(2000)
    Jugador2 = Jugador(2800)
    Jugador3 = Jugador(2700)

    var1 = Jugador1.getPercentil()
    var2 = Jugador2.getPercentil()
    var3 = Jugador3.getPercentil()

    assert var1 == 0.9462 and var2 == 1 and var3 == 0.9998, "Fallo en calculo de percentil"

    return 0
Пример #4
0
def crea_jugador(data):
    """
		Función para generar una instancia de un jugador dada la información de un diccionario
	"""
    return Jugador.Jugador(data["nombre"], data["nivel"], data["goles"],
                           data["sueldo"], data["bono"],
                           data["sueldo_completo"], data["equipo"])
Пример #5
0
    def __init__(self, pantalla, screen_resolution):
        ''' Juego '''
        self.mediafuente = pygame.font.SysFont(None, 30)
        self.vida = 100
        self.puntuacion1 = 0
        self.puntuacion2 = 0
        self.resultado1 = 0
        self.resultado2 = 0

        self.game_over = False
        self.game_exit = False
        self.pause = False
        self.screen_resolution = screen_resolution  # clase pantalla
        self.pantalla = pantalla  # clase de pygame
        self.vx = 0
        self.vy = 0
        self.velocidad = 2
        self.t = 0
        ''' Sprite '''
        self.player1 = Jugador(screen_resolution)
        self.fruta1 = Fruta()
        self.fruta2 = Fruta()
        self.fruta3 = Fruta()
        self.chatarra1 = Chatarra()
        self.chatarra2 = Chatarra()
        self.chatarra3 = Chatarra()
        self.quemada = Quemada()
        self.fondo1 = Fondo()
        ''' Sonidos '''
        self.crunch_sonido = pygame.mixer.Sound("imagenes/Crunch_I.ogg")
def main():
    pygame.init()
    pantalla = pygame.display.set_mode([ANCHO, ALTO])
    fondo = pygame.image.load('fondoPsico.gif')  # cargamos la imagen con su extension
    sprite = pygame.image.load('animals.png')  # cargamos la imagen con su extension
    reloj = pygame.time.Clock()  # tiempo utilizado para la velocidad de animacion
    # objetos
    jugadores = pygame.sprite.Group()  # sprite del tipo group
    matriz = []  # matriz para almacenar las animaciones de 3 x 4
    m = recortar(matriz,sprite)
    j = Jugador(m)  # instanciamos un objeto de la clase Jugador
    jugadores.add(j)  # agregamos a jugadores
    disparo = Disparo()

    fin = False
    while not fin:  # bucle infinito
        for event in pygame.event.get():  # para cualquier evento de entrada
            if event.type == pygame.QUIT:
                fin = True
        # actualizacion grafica
        pantalla.blit(fondo,(0,0))  # refrescamos la pantalla
        j.movimiento()
        disparo.update(j)
        jugadores.draw(pantalla)  # dibujamos en pantalla
        pantalla.blit(disparo.image, disparo.rect)
        pygame.display.flip()
        reloj.tick(j.velocidad)  # tiempo ajustado en 100 ms
    return 0
Пример #7
0
    def setup(self):
        # Sprite lists
        self.player_list = arcade.SpriteList()
        self.bullet_list = arcade.SpriteList()
        self.lista_balas_laser = arcade.SpriteList()
        self.lista_balas_gas = arcade.SpriteList()
        self.dama_list = arcade.SpriteList()
        self.lista_balas_boss = arcade.SpriteList()
        # Create the player
        self.jugador = Jugador.Jugador()  # OJO!
        self.jugador.center_x = 350
        self.jugador.center_y = 350
        self.player_list.append(self.jugador)
        # Creamos los sprites de la dama
        self.dama_fant_abajo = arcade.Sprite("sprites_master" + os.path.sep + "DAMA16.png")
        self.dama_fant_abajo.center_y = 725
        self.dama_fant_abajo.center_x = 450
        self.dama_fant_der = arcade.Sprite("sprites_master" + os.path.sep + "DAMA14.png")
        self.dama_fant_der.center_x = 50
        self.dama_fant_der.center_y = 450
        self.dama_abajo = arcade.Sprite("sprites_master" + os.path.sep + "DAMA7.png")
        self.dama_abajo.center_y = 700
        self.dama_abajo.center_x = 450
        # Ending
        self.contador_espera_mover_dama = 120  # 2s
        self.contador_espera_poner_artefacto = 120
        self.contador_espera_transformar_dama = 240
        self.contador_espera_pantalla_final = 240
        self.final_malo = False
        self.buffs_activos = [False, False, False, False,
                              False]  # True en la posicion 0: buff1 activo; True en la posicion 1: buff2 activo, etc
        # Los ponemos en el setup tambien para cuando hagamos el reinicio se inicien correctamente:
        self.recogido_buff1 = False
        self.recogido_buff2 = False
        self.recogido_buff3 = False
        self.recogido_buff4 = False
        self.recogido_buff5 = False
        self.velocidad_jugador = 4
        self.vida_jugador = 10
        self.carga_fantasmal_jugador = 100
        self.contador_quitar_mensaje = 600  # 10s
        # Musica
        self.contador_loop_musica = 18540  # 5,15 min (duracion musica)* 3600

        # Rooms
        self.cambiado = False
        self.rooms = Habitaciones.setup_habs()  # lista de todas las habitaciones
        self.current_room = 0  # habitacion inicial

        # Fisicas para la habitacion en la que estemos
        self.physics_engine = arcade.PhysicsEngineSimple(self.jugador, self.rooms[self.current_room].wall_list)
        for enemigos in self.rooms[self.current_room].enemigos_list:
            self.physics_engine_enemigos = arcade.PhysicsEngineSimple(enemigos, self.rooms[self.current_room].wall_list)
        if self.rooms[self.current_room].boss_list is not None:
            for boss in self.rooms[self.current_room].boss_list:
                self.physics_engine_boss = arcade.PhysicsEngineSimple(boss, self.rooms[self.current_room].wall_list)

        # Otros atributos
        self.controles_anulados_jugador = False
        self.ending_activado = False
Пример #8
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self._image_surf = None
     self._manzana_surf = None
     self.juego = Juego()
     self.jugador = Jugador(3)
     self.manzana = Manzana(5, 5)
Пример #9
0
 def obtenerJugadorpk(self, pk_jugador):
     string_obtener = "SELECT pk_id_jugador, nombre FROM Jugador WHERE pk_id_jugador = " + str(
         pk_jugador)
     self.cursor.execute(string_obtener)
     lista = self.cursor.fetchall()
     jugador = Jugador(self.cursor, self.connection, lista[0][1],
                       pk_jugador)
     return jugador
Пример #10
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self._image_surf = None
     self._covid_surf = None
     self.juego = Juego()
     self.jugador = Jugador(3)
     self.covid = Covid(5, 5)
     self.computadora = Computadora(3)
Пример #11
0
    def CrearArchivo(self):  #Método para crear el archivo
        _ListJuegos = Juego.ListaJuegos()
        #Llama y llena la variable con la lista de juegos
        _EstadList = []  #Se crea una lista de tipo de list

        _root = os.path.join(
            os.path.join(os.environ['USERPROFILE']), 'Desktop'
        )  #Se llena la variable para obtener la ruta del escritorio del usuario actual del sistema operativo
        _path = _root + '\\DadosPokerFolder' + '\\DadosPokerFile.txt'  # Construye una ruta para el archivo

        if (os.path.isfile(_path) == False):  #Valida sí el archivo existe
            os.makedirs(_root + '\\DadosPokerFolder')
            #Construye un folder
            _path = _root + '\\DadosPokerFolder' + '\\DadosPokerFile.txt'  #Construye una ruta completa
            file = open(
                _path, 'w'
            )  #Construye un archivo con la ruta y la acción en este caso "W"

        file = open(_path, 'r')  #lee el archivo
        _cont = file.read()  #Almacena el contenido del archivo en una variable
        _count = 0  #Variable que funcionara como contador

        self.fecha = time.strftime(
            "%d/%m/%Y")  #Variable para almacenar la fecha
        self.hora = time.strftime("%I:%M:%S")  #Variable para almacenar la hora

        _EstadList.append(
            self)  #Alamacena en una variable de tipo list todos los jugadores

        if (
                len(_cont) > 1
        ):  #Validacion para sacar solo las lineas que contengan información
            for a in _cont.split('\n'):
                b = a.split('\t')
                if (len(b) > 1):
                    _EstadList.append(
                        Estadisticas(Juego(Jugador(b[1], None, 0), b[2]), b[3],
                                     b[4])
                    )  #Crea un objecto de tipo Estadistica para almacenarlos en un list con los datos del archivo
                else:
                    break

        if (
                len(_EstadList) == 11
        ):  #Valida que no existan mas de 10 jugadores, de lo contrario borrará el último
            del (_EstadList[10])

        file = open(_path, 'w')  # Escribe sobre el archivo
        for b in _ListJuegos:  #Estos for recorren los jugadores y la lista de juegos para ordenarlos.
            for c in _EstadList:
                if (b == c.TipoJuego):
                    _count = _count + 1
                    file.write(
                        str(_count) + '.' + '\t' + c.Nombre + '\t' +
                        c.TipoJuego + '\t' + c.fecha + '\t' + c.hora +
                        "\n")  #Estructura para guardar en el archivo
        file.close()  #Cierra el archivo
Пример #12
0
def _jugador_agregar():
    cadena = "JUGADOR AGREGAR\n"
    cadena += "--------------------\n"
    nombre = input("NOMBRE: ")
    posicion = int(input("POSICIÓN: "))
    cadena += "--------------------\n"
    jugador = j.Jugador()
    jugador.name = nombre
    jugador.position = posicion
    return jugador
Пример #13
0
def dibujarPersonaje(gen):
    """
    Dibuja los Personajes
    :param gen: generación del mapa con los elementos de este
    :param pantalla: pantalla donde puntar los elementos
    :return: el personaje
    """

    return Jugador((gen.salaInicial.x + gen.salaInicial.ancho / 2),
                   (gen.salaInicial.y + gen.salaInicial.alto / 2), 7, 7)
def main():
    ancho = 800
    alto = 600
    init(ancho, alto, "titulo")

    p = Jugador(Vector(180 + 12, 50 + 70))
    r = Reloj(Vector(50, 450))
    fondo = Fondo(Vector(0, 0))
    camara = Camara(p)
    piedra = PlataformaPiedra(Vector(200, 50))
    liana = PlataformaLiana(Vector(400, 150))
    madera = PlataformaMadera(Vector(650, 250))
    liana2 = PlataformaLiana(Vector(500, 400))
    piedra2 = PlataformaPiedra(Vector(200, 500))
    muro = Muros(Vector(0, 0))

    elementos = [fondo, piedra, liana, madera, liana2, piedra2, muro, p, r]
    plataformas = [piedra, liana, madera, liana2, piedra2]
    run = True

    while run:
        pygame.event.pump()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # cerrar ventana
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    pass
                if event.key == pygame.K_RIGHT:
                    p.pos += Vector(20, 0)
                if event.key == pygame.K_LEFT:
                    p.pos -= Vector(20, 0)
                if event.key == pygame.K_UP:
                    p.pos += Vector(0, 20)
                if event.key == pygame.K_DOWN:
                    p.pos -= Vector(0, 20)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)  # limpiar buffers

        # dibujar figuras

        p.update(plataformas, camara)
        r.update(fps)
        for elem in elementos:
            elem.dibujar()

        pygame.display.flip()  # actualizar pantalla
        clock.tick(fps)

    pygame.quit()
Пример #15
0
def preparaJuego(vista):
    global campo
    global jugador
    global ia
    global ia2
    campo = mdl.Campo()
    tipoIA = escogerTipoIA()
    campo.rellenar(tipoJugador, tipoIA)
    jugador = Jugador.Jugador(campo, tipoJugador)
    vista.setCampo(campo)
    vista.setJugador(jugador)
    ia2 = Greedy.IA(tipoIA.nombre, campo, 0.8)
    network = import_network("IA_50_50_50/IA_java_3550.txt")
    ia = IA(network, tipoIA.nombre, campo, 2)
Пример #16
0
def main():
    pygame.init()
    pantalla = pygame.display.set_mode([ANCHO, ALTO])
    fondo = pygame.image.load(
        'fondoPsico.gif')  # cargamos la imagen con su extension
    spriteJugador = pygame.image.load(
        'animals.png')  # cargamos la imagen con su extension
    spriteZombie = pygame.image.load('zombie 3.png')
    reloj = pygame.time.Clock(
    )  # tiempo utilizado para la velocidad de animacion
    #listas
    jugadores = pygame.sprite.Group()  # sprite del tipo group
    zombies = pygame.sprite.Group()
    disparos = pygame.sprite.Group()
    # objetos
    matriz = []  # matriz para almacenar las animaciones de 3 x 4
    matrizZombie = []
    m = recortar(matriz, spriteJugador)
    mz = recortarZombie(matrizZombie, spriteZombie)
    jugador = Jugador(m)  # instanciamos un objeto de la clase Jugador
    zombie = EnemigoZombie(mz)  # instanciamos un objeto de la clase Jugador
    jugadores.add(jugador)  # agregamos a jugadores
    zombies.add(zombie)  # agregamos a jugadores

    fin = False
    while not fin:  # bucle infinito
        for event in pygame.event.get():  # para cualquier evento de entrada
            if event.type == pygame.QUIT:
                fin = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # Disparamos un proyectil si el usuario presiona el botón del ratón
                disparo = Disparo()
                # Configuramos el proyectil de forma que esté donde el protagonista
                disparo.rect.x = jugador.rect.x + 15
                disparo.rect.y = jugador.rect.y + 10
                disparos.add(disparo)

        # actualizacion grafica
        pantalla.blit(fondo, (0, 0))  # refrescamos la pantalla
        jugador.movimiento()
        disparos.update()
        zombie.movimiento()
        jugadores.draw(pantalla)  # dibujamos en pantalla
        zombies.draw(pantalla)
        disparos.draw(pantalla)
        pygame.display.flip()
        reloj.tick(10)  # tiempo ajustado en 100 ms = 20 fps
    return 0
Пример #17
0
 def __init__(self, pantalla, screen_resolution):
     ''' Juego '''
     self.sonido1 = pygame.mixer.Sound('Imagenes/mix.ogg')
     self.mediafuente = pygame.font.SysFont(None, 50)
     self.vida = 100
     self.puntuacion = 0
     self.game_over = False
     self.pause = False
     self.screen_resolution = screen_resolution  # clase pantalla
     self.pantalla = pantalla  # clase de pygame
     self.vx = 0
     self.vy = 0
     self.velocidad = 4
     self.t = 0
     ''' Sprite '''
     self.player1 = Jugador()
     self.fruta1 = Fruta()
     self.fruta2 = Fruta()
     self.fondo1 = Fondo()
     ''' Sonidos '''
def principal():
    alto = 500
    ancho = 700
    tema()
    consignas = AlmacenamientoConsignas()
    imgBoton = os.path.join('multimedia', 'cuadro.png')
    quijote = os.path.join('multimedia', 'quijoteLogo.png')

    ventana = sg.Window('Juego Cervantes: Inicio',
                        interfazInicial(imgBoton, quijote),
                        size=(ancho, alto),
                        element_justification='center')
    ventana.Finalize()

    while True:
        evento, value = ventana.read()
        if (evento == None or evento == 'salir' or evento == 'salir2'):
            break
        if (evento == 'docente'):
            clave = sg.popup_get_text('Ingrese la clave',
                                      password_char='*',
                                      font='MedievalSharp 10')
            if (clave == 'reshu'):
                inicioConsignas()
            else:
                sg.popup('clave incorrecta \n Intente nuevamente',
                         font='MedievalSharp 10')
        if (evento == 'jugar'):

            nombre = sg.popup_get_text('Ingrese su nombre',
                                       font='MedievalSharp 10')
            if (nombre != '') and (len(nombre) > 2) and (len(nombre) < 20):
                jugador = Jugador(nombre.upper())
                break
            else:
                sg.popup('El nombre debe tener entre 3 y 30 caracteres',
                         font='MedievalSharp 10')
        if (evento == 'puntos'):
            sg.popup('PUNTAJES en construcción', font='MedievalSharp 10')
    ventana.Close()
    return jugador, consignas
Пример #19
0
def insertarOrdenado(nombre, numeroCamisa):
    nuevo = Jugador()
    nuevo.set__info(nombre, numeroCamisa)
    global inicio
    global ultimo
    if (inicio == None):
        inicio = ultimo = nuevo
        return True

    if ((inicio.numeroCamisa == nuevo.numeroCamisa) |
        (ultimo.numeroCamisa == nuevo.numeroCamisa)):
        return False

    if (nuevo.numeroCamisa < inicio.numeroCamisa):
        nuevo.sig = inicio
        inicio.ant = nuevo
        inicio = nuevo
        return True

    if (nuevo.numeroCamisa > ultimo.numeroCamisa):
        ultimo.sig = nuevo
        nuevo.ant = ultimo
        ultimo = nuevo
        return True

    aux = inicio
    while (aux != None):
        if (nuevo.numeroCamisa == aux.numeroCamisa):
            return False

        if (nuevo.numeroCamisa < aux.numeroCamisa):
            aux.ant.sig = nuevo
            nuevo.ant = aux.ant
            nuevo.sig = aux
            aux.ant = nuevo
            return True

        aux = aux.sig

    return False
Пример #20
0
import Jugador
import Charmi
import Jugar

print("         !!!!BIENVENIDOS A JUGAR CON CHARMI!!!!      ")
print("Juguemos un torneo en el cual los dos tendremos un bote de 1000$")
inicio = input("¿Deseas Inscribirte? (si/no):")

while inicio != "si" and inicio != "no":
    inicio = input("Responde si o no porfavor. ¿Deseas Inscribirte? (si/no):")

if (inicio == "si"):
    os.system('clear')
    print("Introduzca su Nombre: ")
    nombre = input()
    usuario = Jugador.Jugador(nombre, 1000)
    charmi = Charmi.Charmi("charmi", 1000)
    print("Bienvenido ", usuario.name)

    while (usuario.bote != 0) and (charmi.bote != 0):
        partida = Jugar.Juego(charmi, usuario)
        #Ciegas minima y maxima
        partida.ciegas()

        #Primera Etapa Preeflop
        partida.preflop()
        retirar = partida.usuario.apuesta()

        if (retirar):

            #Segunda etapa
Пример #21
0
from time import sleep

import Tictactoe
import Tablero
import Jugador
import QLearning

ai = QLearning.QLearning()
ai2 = QLearning.QLearning()

jugador1 = Jugador.Jugador("player1", 'X', ai)
jugador2 = Jugador.Jugador("player2", 'O', None)

jugadores = []
jugadores.append(jugador1)
jugadores.append(jugador2)

tablero = Tablero.Tablero()
game = Tictactoe.tictactoe(tablero, jugadores)

game.encender()

#while True:
#    game.new_game()
#    if game.iterations == 3:
#        game.new_game(t="q")
#        break
#CopaLeche.nombre="Caquita"

#CopaLeche.updateCopa()

#MENUUU

opcion = int(
    input(
        "MENU\n 1-ORGANIZACIONES \n 2-COPAS \n 3-PAISES \n 4-LIGAS \n 5-EQUIPOS \n 6-JUGADOR \n 7- DTs \n 8- Salir \n OPCION: "
    ))
ORG = Organizacion()
COPA = Copa()
PAIS = Pais()
Ligue = Liga()
Team = Equipo()
Player = Jugador()
DeTe = DT()

while (opcion != 8):

    #opcion = int(input("\n MENU\n 1-ORGANIZACIONES \n 2-COPAS \n 3-PAISES \n 4-LIGAS \n 5-EQUIPOS \n 6-JUGADOR \n 7- DTs \n 8- Salir \n OPCION: "))

    if (opcion == 1):

        opcionOrg = int(
            input(
                "\n 1-CREAR ORGANIZACION \n 2-INSERTAR ORG EN BASE \n 3-VER ORGANIZACIONES DE LA BASE \n 4-MODIFICAR UNA ORGANIZACION \n 5-ELIMINAR UNA ORGANIZACION \n 6-VOLVER AL 1ER MENU \n OPCION: "
            ))

        if (opcionOrg == 1):
Пример #23
0
def nivel2():
    #pygame.quit()
    screen = pygame.display.set_mode((1200, 1000))
    Cinematica2()
    pygame.display.set_caption("sprite")
    reloj = pygame.time.Clock()
    game_over = False
    jugador = Jugador([600, 300])
    desplazamientoX = 0  #-100
    desplazamientoY = 0  #-1400
    jugador.gemas = 0
    #inicializamos pygame
    pygame.init()
    #imagen = pygame.image.load("fondo.png")
    #screen.blit(imagen ,(0,0))
    pygame.display.set_caption("Mapa")
    clock = pygame.time.Clock()
    img = pygame.image.load("juego.png")
    uploadMap("mapa2")
    hoja = arrayTileset(img)

    #Cargar las imagenes de los Sprites
    Bloque1 = img.subsurface(0, 0, 64, 64)
    Bloque2 = img.subsurface(64, 0, 64, 64)
    Bloque3 = img.subsurface(128, 0, 64, 64)
    #BloqueL = img.subsurface(384,448,64,64)
    Caja = img.subsurface(384, 0, 64, 64)
    Escalera1 = img.subsurface(256, 320, 64, 64)
    Escalera2 = img.subsurface(320, 320, 64, 64)
    imgGema = img.subsurface(128, 384, 64, 64)
    Bloque4 = img.subsurface(256, 0, 64, 64)

    #Cargamos la musica
    pygame.mixer.music.load("Musica.mp3")
    pygame.mixer.music.play(-1)

    #Cargamos los sonidos
    #sonidoGema = pygame.mixer.Sound("Gema.mp3")
    #sonidoMuerte = pygame.mixer.Sound("Muerte.mp3")

    #Creamos los grupos de sprites
    jugadores = pygame.sprite.Group()
    gemas = pygame.sprite.Group()
    escaleras = pygame.sprite.Group()
    bloques = pygame.sprite.Group()
    enemigos = pygame.sprite.Group()

    #Creamos los sprites
    jugadores.add(jugador)

    for i in range(mapHeight):
        for j in range(mapWidth):
            minum = matrizMap[i][j]
            if minum == 1:
                b = Bloque([j * 64, i * 64], Bloque1)
                bloques.add(b)
            elif minum == 2:
                b = Bloque([j * 64, i * 64], Bloque2)
                bloques.add(b)
            #elif minum == 63:
            #    b = Bloque([j*64,i*64],BloqueL)
            #    bloques.add(b)
            elif minum == 3:
                b = Bloque([j * 64, i * 64], Bloque3)
                bloques.add(b)
            elif minum == 7:
                b = Bloque([j * 64, i * 64], Caja)
                bloques.add(b)
            elif minum == 45:
                e = Escalera([j * 64, i * 64], Escalera1, True)
                escaleras.add(e)
            elif minum == 46:
                e = Escalera([j * 64, i * 64], Escalera2, True)
                escaleras.add(e)
            elif minum == 51:
                g = Gema([j * 64, i * 64], imgGema)
                gemas.add(g)
            elif minum == 5:
                b = Bloque([j * 64, i * 64], Bloque4)
                bloques.add(b)

    while not game_over:

        screen.fill((112, 145, 241))
        clock.tick(10)
        for event in pygame.event.get():
            if event.type == QUIT:
                game_over = True
                sys.exit()

        jugador.bajar = False
        jugador.escalar = False
        jugador.escalando = False
        jugador.bajando = False

        ls = pygame.sprite.spritecollide(jugador, escaleras, False)
        if len(ls) > 0:
            jugador.escalar = True
        for e in ls:
            if e.bajar:
                jugador.bajar = True

        temp = jugador.evento(event)
        bloques.update(temp)
        escaleras.update(temp)
        gemas.update(temp)

        ls = pygame.sprite.spritecollide(jugador, escaleras, False)
        if len(ls) > 0:
            jugador.escalar = True

        ls = pygame.sprite.spritecollide(jugador, bloques, False)
        for e in ls:
            if jugador.rect.top < e.rect.bottom and temp[
                    1] < 0 and not jugador.escalando:
                temp = [0, (e.rect.bottom - jugador.rect.top)]
                bloques.update(temp)
                escaleras.update(temp)
                gemas.update(temp)
                jugador.contGravedad = 0
                break
            elif jugador.rect.bottom > e.rect.top and temp[
                    1] > 0 and not jugador.bajando:
                temp = [0, (e.rect.top - jugador.rect.bottom)]
                jugador.contGravedad = 0
                bloques.update(temp)
                escaleras.update(temp)
                gemas.update(temp)
                break

        ls = pygame.sprite.spritecollide(jugador, bloques, False)
        for e in ls:
            if jugador.rect.right > e.rect.left and temp[0] > 0:
                temp = [(e.rect.left - jugador.rect.right), 0]
                bloques.update(temp)
                escaleras.update(temp)
                gemas.update(temp)
                break
            elif jugador.rect.left < e.rect.right and temp[0] < 0:
                temp = [(e.rect.right - jugador.rect.left), 0]
                bloques.update(temp)
                escaleras.update(temp)
                gemas.update(temp)
                break

        ls = pygame.sprite.spritecollide(jugador, gemas, True)
        for e in ls:
            jugador.gemas += 1
            print(jugador.gemas)

        for b in bloques:
            screen.blit(b.image, b.rect)
        for e in escaleras:
            screen.blit(e.image, e.rect)
        for g in gemas:
            screen.blit(g.image, g.rect)
        screen.blit(jugador.imagen, jugador.rect)
        pygame.display.flip()
Пример #24
0
            print mensaje
            print "Jugador %s Gana" % jugador2.nombre
        else:
            print "Empate"
    
    print
    print
    print jugador1
    print jugador2
    print 
    print
    


print "Bienvenido a piedra papel tijeras lagarto spock!"
yo = Jugador(raw_input("\nIngrese su nombre\n>>"))
pc = JugadorCPU()


# MainLoop
   
while True:
 
    print "Instrucciones: Ingresar los siguientes numeros para jugar"
    print "1 - Piedra"
    print "2 - Papel"
    print "3 - Tijeras"
    print "4 - Lagarto"
    print "5 - Spock!"
    print "0 - Salir"
    
Пример #25
0
import pygame, sys
from pygame.locals import*
from Jugador import*
from Barril import*
from BarrilSaltarin import*
from random import randint
from BarrilEnLlamas import *
from BarrelManager import*
booleano = True
ventana = pygame.display.set_mode( (1280,720) )
pygame.display.set_caption("DK PreAlpha")
jugador = Jugador()
manager = BarrelManager()
barriles = []
#barril=BarrilSaltarin()
#barriles.append(barril)
contador = 900
def spawn(contador):
    spawnNum=randint(0,2)
    if contador == 0:
        if spawnNum == 1:
            barriles.append(manager.clonarSaltarin())
            contador=2000
        elif spawnNum == 2:
            barriles.append(manager.clonarLlamas())
            contador = 2000
        elif spawnNum == 0:
            barriles.append(manager.clonarBarril())
            contador = 2000
    else:
        contador-=1
Пример #26
0
                           ((screenX * 3 / 4) + (screenX / 16)), screenY / 16,
                           buttonW, buttonH, "Jugar")
button_Retirar = button((186, 190, 195), ((screenX * 3 / 4) + (screenX / 8)),
                        (screenY / 4 - screenY / 16), buttonW, buttonH,
                        "Retirar")
botones = [button_Mover, button_Habilidad, button_Cancelar]
botonesRetirar = [
    button_Mover, button_Habilidad, button_Cancelar, button_Retirar
]
botonesMano = [button_JugarCarta, button_Cancelar]
cartaSeleccionada = False
tokenSeleccionado = False
#Loop de juego
UnidadesEnJuego = []
running = True
jugador1 = Jugador(mazoSelva)


#Metodos
def paint_button(button):
    if button == button_JugarCarta:
        button_JugarCarta.draw(main.screen, (255, 244, 0))
        pygame.display.update()
    if button == button_Cancelar:
        button_Cancelar.draw(main.screen, (255, 244, 0))
        pygame.display.update()
    if button == button_Mover:
        button_Mover.draw(main.screen, (255, 244, 0))
        pygame.display.update()
    if button == button_Habilidad:
        button_Habilidad.draw(main.screen, (255, 244, 0))
Пример #27
0
            resp = 0

        if resp in jugador.disparos:
            print("Ya has disparado en esta posicion")
            resp = None

        return resp
    except:
        return None


es_maquina = False

salir = False

jugador_1 = Jugador()

jugador_2 = Jugador()

print("Bienvenido al juego HUNDIR LA FLOTA")

print("                  __--___\n\
                 >_--__ \n\
                _________!__________\n\
               /   /   /   /   /   /\n\
              /   /   /   /   /   /\n\
             |   |   |   |   |   |\n\
        __^  |   |   |   |   |   |\n\
      _/@  \  \   \   \   \   \   \n\
     S__   |   \   \   \   \   \   \         __\n\
    (   |  |    \___\___\___\___\___\       /  \n\
Пример #28
0
import pygame
from Jugador import *
from Zonaprotegida import *
from Boton import *
from Grilla import *
from Amenaza import *
from Texto import *
from ImagenConTextoCentrado import *
from Timer import *
from configuracion import *
from imagenes import *

nivel2 = Grilla(8, 5)

# Jugador (xinicial, yinicial)
supertabletnivel2 = Jugador(3, 2)

# Amenaza (xinicial, yinicial)
amenaza1nivel2 = Amenaza(3, 3)
amenaza2nivel2 = Amenaza(4, 3)
amenaza3nivel2 = Amenaza(5, 3)
amenaza4nivel2 = Amenaza(6, 3)
amenaza5nivel2 = Amenaza(5, 4)

# ZonaProtegida (xinicial, yinicial)
zonaprotegida1nivel2 = Zonaprotegida(2, 2)
zonaprotegida2nivel2 = Zonaprotegida(2, 4)
zonaprotegida3nivel2 = Zonaprotegida(4, 4)
zonaprotegida4nivel2 = Zonaprotegida(7, 2)
zonaprotegida5nivel2 = Zonaprotegida(7, 4)
Пример #29
0
def OpcionesJuego():
    opcion = input('Por favor, digite una opcion: ')  #Menú a mostrar
    ValidacionMenu(opcion)

    if (opcion == '1'):  #Opciones del menú

        MostrarTitulo()  #Mostrar un titulo

        _numeroJugadores = ValidacionNumeroJugadores(
            input('Por favor ingresar el numero de jugadores: '))
        _numeroJugadoresVirtuales = ValidacionNumeroJugadoresVirtuales(
            input("De estos jugadores, cuantos son virtuales: "),
            _numeroJugadores)

        # _numeroJugadoresVirtuales = int(input("De estos jugadores, cuantos son virtuales: ")) #Jugadores virtuales
        _numeroJugadoresHumanos = _numeroJugadores - _numeroJugadoresVirtuales  #Cálculo para los jugadores humanos.

        MostrarTitulo()
        print('Definir el nombre para los jugadores')

        _JugadoresList = []  #Arrays para crear la lista de jugadores

        i = 1

        while i <= _numeroJugadoresHumanos:  #Muestra el nombre de los jugadores humanos, se construye un objecto solo con
            #el nombre.
            _JugadoresList.append(
                Jugador(input('Nombre del jugador ' + str(i) + ': '), 'Prueba',
                        1))
            i += 1

        i = 1
        while i <= _numeroJugadoresVirtuales:  #Muestra el nombre de los jugadores virtuales, se construye un objecto solo con
            #el nombre.
            _JugadoresList.append(Jugador('Virtual_' + str(i), 'Prueba', 0))
            i += 1

        os.system('cls')  #Comando para limpiar en consola
        CrearJuego(
            _JugadoresList
        )  #Se ejecuta el metodo CrearJuego y que por parametro lleva la lista de
        #jugadores

        Jugar(_JugadoresList)
        if (RelanzarDados(_JugadoresList) != False
            ):  #Se ejecuta sí los jugadores lanzan de nuevo algún dado
            Jugar(_JugadoresList)  #Se juega ya con los dados lanzados
        _Ganador = Juego.DefinirGanador(
            _ListJuegos
        )  #Metodo para definir un ganador del juego, utilizando la clase de tipo Juego

        if (_Ganador != None):
            if (len(_Ganador.Jugador.Nombre.split(' ')) == 1):
                print('Ganador : ' + _Ganador.Jugador.Nombre + ' con ' +
                      _Ganador.Descripcion)  #Muestra el ganador del juego
            elif (len(_Ganador.Jugador.Nombre.split(' ')) > 1):
                print('Juego empate : ' + _Ganador.Jugador.Nombre + ' con ' +
                      _Ganador.Descripcion)  #Muestra el ganador del juego
            Estadisticas(_Ganador, None, None).CrearArchivo(
            )  #Llama la clase Estadisticas, al método Crear Archivo donde mete a lista de                                                      #jugadores
        else:
            print('No hay ganadores')
        RetornoMenu()  #Regresa al juego.

    if (opcion == '2'):  #Opcion para mostrar en estadisticas
        MostrarTitulo()  #Muestra el titulo
        print(Estadisticas.MostrarEstadisticas()
              )  #Inprime en consola las estadisticas de los estudiantes
        RetornoMenu()  #Regresa al menu

    if (opcion == '3'):  #Opcion para salir del programa
        os.system('exit()')  #Comando para salir del programa
Пример #30
0
class Partida:

    print
    print " ------------"
    print "| 4 EN LINEA |"
    print " ------------"
    print

    while True:
        print "1. Nueva partida"
        print "2. Cargar partida"
        print "================="
        print

        modoDeJuego = input("Modo de juego: ")
        print

        if modoDeJuego == 1:
            nombre1 = raw_input("Nombre del jugador 1: ")
            nombre2 = raw_input("Nombre del jugador 2: ")

            jugador1 = Jugador.Jugador(nombre1, 21, "rojo")
            jugador2 = Jugador.Jugador(nombre2, 21, "amarillo")

            jugador1.crearFichas()
            jugador2.crearFichas()

            tablero = Tablero.Tablero()
            turno = 1

            break

        elif modoDeJuego == 2:
            with open('partidaGuardada.pkl', 'rb') as binario:
                jugador1 = pickle.load(binario)
                jugador2 = pickle.load(binario)
                tablero = pickle.load(binario)
                turno = pickle.load(binario)

                binario.close()
                print "Partida cargada!"
                print
            break

        else:
            print "ERROR: Elige un modo de juego valido!"

    print
    tablero.pintarse()

    while jugador1.getNumFichas() > 0 or jugador2.getNumFichas() > 0:

        if turno == 1:
            jugadorActual = jugador1
        else:
            jugadorActual = jugador2

        print
        print "Turno del jugador %i (%s)" % (turno, jugadorActual.getNombre())
        print "Color de ficha %s (%c)" % (jugadorActual.getFicha().getColor(),
                                          jugadorActual.getFicha().pintarse())

        numColumna = input("Numero de columna (0 para guardar partida): ")
        print

        if numColumna == 0:
            with open('partidaGuardada.pkl', 'wb') as binario:
                pickle.dump(jugador1, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(jugador2, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(tablero, binario, pickle.HIGHEST_PROTOCOL)
                pickle.dump(turno, binario, pickle.HIGHEST_PROTOCOL)

                binario.close()
                print
                print "Partida guardada!"
                print

            break

        elif 0 < numColumna <= tablero.getNumColumnas():
            if tablero.ponerFicha(numColumna,
                                  jugadorActual.sacarFicha().getNumero()):
                print
                print "VICTORIA DEL JUGADOR %i (%s: %i puntos)!!" % (
                    turno, jugadorActual.getNombre(),
                    jugadorActual.getPuntos())
                break

            jugadorActual.setNumFichas(jugadorActual.getNumFichas() - 1)
            if turno == 1:
                turno = 2
            else:
                turno = 1

        else:
            print
            print "ERROR: Introducir numeros del 1 al %i o 0 para guardar." % tablero.getNumColumnas(
            )

    if jugador1.getNumFichas() == jugador2.getNumFichas() == 0:
        print
        print "EMPATE!!"