Exemplo n.º 1
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
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
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"
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()
Exemplo n.º 8
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
Exemplo n.º 9
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
Exemplo n.º 10
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"])
Exemplo n.º 11
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
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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
Exemplo n.º 15
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)
Exemplo n.º 16
0
	def __init__(self,*args): #constructor		
		Escenario.__init__(self,*args)
		self.mover=True
		color=QColor(0,0,155)		
		self.jugador=Jugador(0,Escenario.dimension_y-self.nivel_piso_y-50,color,10)#posicion inicial del jugador
		self.jugador.setRadio(50)
		self.jugador.setNivel(2)
		self.setWindowTitle("Escenario Dos")
		self.thread_pintarPasadizo=Hilo(self,Accion.pasadizo)
		self.estadoEscenario=EstadoEscenario.pasadizoOff
Exemplo n.º 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 '''
Exemplo n.º 18
0
	def __init__(self,*args):
		Escenario.__init__(self,*args)
		self.mover=True #sirve para saber si el jugador se puede mover
		self.todoTerreno=False
		self._iniPendiente=500
		self._finPendiente=755
		self.hiloCaida=None
		self.hiloSalto=None
		self.piso1=430
		self.piso2=290
		self.Duelo=None
		self.jugador=Jugador(20,430,Qt.white,5)
		self.setWindowTitle("Escenario Tres")
Exemplo n.º 19
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)
Exemplo n.º 20
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
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
Exemplo n.º 22
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
Exemplo n.º 23
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"
    
Exemplo n.º 24
0
class EscenarioDos(Escenario):
	pisoUno=None
	pisoDos=None
	pisoTres=None
	nivel_piso_x=200 #separacion horizontal entre pisos
	nivel_piso_y=300 # altura de los pisos
	valor=0
	tam=0

	def __init__(self,*args): #constructor		
		Escenario.__init__(self,*args)
		self.mover=True
		color=QColor(0,0,155)		
		self.jugador=Jugador(0,Escenario.dimension_y-self.nivel_piso_y-50,color,10)#posicion inicial del jugador
		self.jugador.setRadio(50)
		self.jugador.setNivel(2)
		self.setWindowTitle("Escenario Dos")
		self.thread_pintarPasadizo=Hilo(self,Accion.pasadizo)
		self.estadoEscenario=EstadoEscenario.pasadizoOff

	def paintEvent(self, event):
		paint = QPainter()
		paint.begin(self)
		paint.setRenderHint(QPainter.Antialiasing)
		fondoEscenario=QImage("Fondo_Escenario_Dos","png")
		center=QPoint(0,0)
		paint.drawImage(center,fondoEscenario)
		self.dibujarPisos(paint)
		paint.setBrush(self.jugador.getColor())
		paint.drawEllipse(self.jugador.getPosX(),self.jugador.getPosY(),self.jugador.getRadio(),self.jugador.getRadio())
		paint.setBrush(Qt.green)
		paint.drawRect(self.tam,Escenario.dimension_y-self.nivel_piso_y,self.thread_pintarPasadizo.valor_X,10)#rectangulo que se mueve
		paint.end()

	def dibujarPisos(self,painter):
		self.tam=125 #ancho del piso
		valor_X=0 
		valor_Y=0
		pisoUno=QRect(0,Escenario.dimension_y-self.nivel_piso_y,self.tam,self.nivel_piso_y)
		pisoDos=QRect(self.tam,Escenario.dimension_y-20,self.nivel_piso_x,20)
		pisoTres=QRect(self.tam+self.nivel_piso_x,Escenario.dimension_y-self.nivel_piso_y,2*self.tam,self.nivel_piso_y)#piso tres es dos veces mas grande que piso Uno
		pisoCuatro=QRect(3*self.tam+self.nivel_piso_x+self.nivel_piso_x,Escenario.dimension_y-self.nivel_piso_y,2*self.tam,self.nivel_piso_y)#piso cuatro es dos veces mas grande que piso Uno
		painter.setBrush(Qt.green)
		painter.drawRect(pisoUno)
		painter.drawRect(pisoDos)
		painter.drawRect(pisoTres)
		painter.drawRect(pisoCuatro)
		#cajas de habilidad
		painter.setBrush(Qt.red)
		painter.drawRect(self.tam,Escenario.dimension_y-20-20,30,20)
		painter.drawRect(self.tam+self.nivel_piso_x+2*self.tam-30,Escenario.dimension_y-self.nivel_piso_y-20,30,20)

	def keyPressEvent(self,e):
		if self.mover==True and e.key()==QtCore.Qt.Key_Right:
			self.jugador.avanzar()
			self.repaint()# se vuelve a pintar el circulo con las nuevas coordenadas
			if self.estadoEscenario==EstadoEscenario.pasadizoOff and self.jugador.getPosX()>self.tam-self.jugador.getRadio()/2: #si el pasadizo esta cerrado jugador se cae al piso dos
					self.my_thread=Hilo(self,Accion.caida)
					self.mover=False #Bloquea el movimiento
					self.my_thread.start()

		if self.mover==True and e.key()==QtCore.Qt.Key_Left:
			self.jugador.retroceder()
			self.repaint()	

		if self.jugador.getPosY()>Escenario.dimension_y-self.nivel_piso_y and self.jugador.getPosX()< self.tam+30 and e.key()==QtCore.Qt.Key_X:
			self.mover=False #bloquea el movimiento
			self.hilo=Hilo(self,Accion.teletransportacion)
			self.hilo.start()

		if self.jugador.getPosX()== self.tam+self.nivel_piso_x+2*self.tam-30 and e.key()==QtCore.Qt.Key_Y:
			self.mover=False #bloquea el movimiento
			self.hilo=Hilo(self,Accion.salto)
			self.hilo.start()
		if self.jugador.getPosX()>3*self.tam+self.nivel_piso_x+self.nivel_piso_x:
			self.duelo=Duelo(self.jugador)


	def  activarPasadizo(self):
		self.mover==False #bloquea el movimiento
		self.thread_pintarPasadizo.start()
Exemplo n.º 25
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\
Exemplo n.º 26
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)
Exemplo n.º 27
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
Exemplo n.º 28
0
def main():

    # variables
    tipo_control = 0
    mute = False
    irect = (0, 0)
    frect = (0, 0)
    seleccion = False
    grupo_seleccionados = grupo_enemigos


    # Inicialización del programa
    num_enemigos = int(raw_input("Por favor di un numero: "))


    # Creando la ventana
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Pro-proyecto1")


    # Carga la imagen del fondo
    background_image = pygame.transform.smoothscale(load_image("imagenes/fondo.jpg"), (WIDTH, HEIGHT))

    
    # Crea el jugador   
    jugador = Jugador([WIDTH /2 ,HEIGHT /2], [70,70], "imagenes/narval_azul1.png", [grupo_todos, grupo_personajes, grupo_dibujables, grupo_colisionables], "Jugador")
    
    objetivo = jugador


    # Crea el target (mouse)
    target_mouse = Personaje(pygame.mouse.get_pos(), [50,50], "imagenes/target.png", [grupo_todos, grupo_dibujables], "Mouse")
    pygame.mouse.set_visible(False)


    # Crea los enemigos
    for num in range(0, num_enemigos):
        Enemigo(jugador, [100*num,100], [30,30], "imagenes/aliado.png", [grupo_todos, grupo_personajes, grupo_enemigos, grupo_dibujables, grupo_colisionables],"E" + str(num)).add(grupo_enemigos)


    obstaculo1 = Personaje( [500,400], [80,80], "imagenes/obstaculo2.png", [grupo_todos, grupo_dibujables, grupo_personajes, grupo_colisionables, grupo_obstaculos], "Obstaculo1")
    pygame.mouse.set_visible(False)



    # Crea el reloj del juego
    clock = pygame.time.Clock()


    # Arreglo que contiene las teclas apretadas antes de comenzar
    keysanteriores = pygame.key.get_pressed()
    mouse_anterior = pygame.mouse.get_pressed()
    target = jugador

    # inicia la fastidiosa y repetitiva musica
    sonar_musica("sonido/483578_Can-Of-Infinite-Min.mp3", -1) 

    #sonar_sonido("sonido/Bottle Rocket-SoundBible.com-332895117.mp3")

    # loop principal del juego
    while True:       
        time = clock.tick(60)
        keys = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()


        # Maneja los eventos en general
        for eventos in pygame.event.get():
            if eventos.type == QUIT:
                sys.exit(0)
        

        # Maneja el tipo de control del jugador
        if not keysanteriores[K_t] and keys[K_t]:
            tipo_control = (tipo_control + 1) % 3


        if not keysanteriores[K_m] and keys[K_m]:
            if not mute:
                pygame.mixer.music.pause()
                mute = True
            else:
                pygame.mixer.music.unpause()
                mute = False

        if not keysanteriores[K_0] and keys[K_0]:
            Enemigo(jugador, [100*num_enemigos,100], [30,30], "imagenes/aliado.png", [grupo_todos, grupo_personajes, grupo_enemigos, grupo_dibujables,  grupo_colisionables],"E" + str(num_enemigos)).add(grupo_enemigos)
            num_enemigos += 1
            
        if not keysanteriores[K_9] and keys[K_9]:
            Enemigo(jugador, [100*num_enemigos,100], [80,120], "imagenes/jefe2.png", [grupo_todos, grupo_personajes, grupo_enemigos, grupo_dibujables, grupo_colisionables],"T" + str(num_enemigos)).add(grupo_enemigos)
            num_enemigos += 1
            
        if not keysanteriores[K_p] and keys[K_p]:
            Enemigo(jugador, [100*num_enemigos,100], [70,70], "imagenes/char.png", [grupo_todos, grupo_personajes, grupo_enemigos, grupo_dibujables, grupo_colisionables],"P" + str(num_enemigos)).add(grupo_enemigos)
            num_enemigos += 1 
            
            
        
# ------- Manejo de los personajes y objetos

        # Texto que muestra el comportamiento actual en pantalla
        ##advertencia, advertencia_rect = texto("comportamiento: " + comportamiento.comportamiento_actual(), [WIDTH/2, 50], (244, 244, 244))
        control, control_rect = texto("control: " + str(tipo_control + 1), [WIDTH/8, 50], (244, 244, 244))
        objetivo_tx, objetivo_rect = texto("objetivo: " + objetivo.nombre, [(WIDTH * 4) / 5, 80], (244, 244, 244))

        # Maneja el jugador
        if tipo_control == 0:
            jugador.moverse_general(keys)
        elif tipo_control == 1:
            jugador.moverse_relativo(keys)
        elif tipo_control == 2:
            jugador.moverse_personal(keys)

        
        # Maneja el target (mouse)
        target_mouse.posi = [pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1], 0]
        target_mouse.angulo = jugador.angulo
        target_mouse.rect.center = [target_mouse.posi[0], target_mouse.posi[1]]
        target_mouse.actualizar(time)
        
        selector = None
        if mouse[0]:
            if seleccion:
                frect = target_mouse.rect.topleft
                rectselect = pygame.Rect(min(irect[0], frect[0]), min(irect[1],frect[1]),\
                 math.fabs(frect[0]-irect[0]), math.fabs(frect[1]-irect[1]))
                 
                selector = Personaje([rectselect.centerx, rectselect.centery], \
                [rectselect.width + 1, rectselect.height+ 1], "imagenes/selector.png", [grupo_todos, grupo_dibujables], "selector")
                grupo_seleccionados = pygame.sprite.spritecollide(selector, grupo_enemigos, False)
                if grupo_seleccionados == []:
                    grupo_seleccionados = grupo_enemigos
                #print grupo_seleccionados
                
            else:
                seleccion = True
                irect = target_mouse.rect.topleft
        else:
            seleccion = False
        
                

        if mouse[2]:
            grupo_colisionables.add(target_mouse)
            colisiones = target_mouse.colisionar()
            if len(colisiones) == 1:
                target = colisiones[0]
                objetivo = colisiones[0]
                grupo_personajes.remove(target_mouse)
            elif len(colisiones) == 0:
                target = target_mouse
                objetivo = target_mouse
            grupo_colisionables.remove(target_mouse)
            
            
        
        
        # Maneja los enemigos
        
        for e in grupo_seleccionados:
            # Maneja el cambio en el comportamiento de los enemigos
            if not keysanteriores[K_LSHIFT] and keys[K_LSHIFT]:
                e.siguiente_comportamiento()
            #print grupo_seleccionados
            e.target = target
            
        for e in grupo_enemigos:
            e.moverse()
                    
                    

       
            
        # Actualiza el estado de los personajes
        for p in grupo_personajes:
            p.actualizar(time)
            


# -------  Se dibujan los elementos en la pantalla
        # Dibuja el fondo
        screen.blit(background_image, (0, 0))

        # Dibuja los objetos dibujables
        for d in grupo_dibujables:       
            screen.blit(d.image, d.rect)
        screen.blit(jugador.image, jugador.rect)
        ##screen.blit(advertencia, advertencia_rect)
        screen.blit(control, control_rect)
        screen.blit(objetivo_tx, objetivo_rect)
        pygame.display.flip()
        
        if selector != None:
            selector.kill()
            del selector
            
        keysanteriores = keys
        mouse_anterior = mouse
        
    return 0
Exemplo n.º 29
0
class EscenarioTres(Escenario):

	def __init__(self,*args):
		Escenario.__init__(self,*args)
		self.mover=True #sirve para saber si el jugador se puede mover
		self.todoTerreno=False
		self._iniPendiente=500
		self._finPendiente=755
		self.hiloCaida=None
		self.hiloSalto=None
		self.piso1=430
		self.piso2=290
		self.Duelo=None
		self.jugador=Jugador(20,430,Qt.white,5)
		self.setWindowTitle("Escenario Tres")

	def dibujarCofres(self,paint):
		paint.setBrush(Qt.red)
		paint.drawRect(40,413,35,35)
		paint.drawRect(370,413,35,35)
		
	def paintEvent(self, event):       
		paint = QPainter()
		paint.begin(self)
		paint.setRenderHint(QPainter.Antialiasing)
		paint.setBrush(Qt.white) # cambiar el color
		paint.drawRect(event.rect())
		imagen=QImage("fondo3","jpg")
		center=QPoint(0,0)
		paint.drawImage(center,imagen)
		self.dibujarCofres(paint)
		paint.setBrush(self.jugador.getColor())
		center = QPoint(self.jugador.getPosX(), self.jugador.getPosY())
		paint.drawEllipse(center,self.jugador.getRadio(),self.jugador.getRadio())
		paint.end()
		
	
		
		
	#se define el movimiento de el jugador
	def keyPressEvent(self,e):
		if self.mover and e.key()==QtCore.Qt.Key_Right:
			x=self.jugador.getPosX()
			if (x>= 850) :
				self.mover = False
				self.Duelo=Duelo(self.jugador)
			elif(self.todoTerreno and x>self._iniPendiente and x<self._finPendiente):
				self.jugador.avanzar()
				self.jugador.acender(2.65)
			elif x<=self._iniPendiente or x>=self._finPendiente:
				self.jugador.avanzar()
			
			if x>=100 and x<=200:
				self.hiloCaida=HiloCaida(self,1)
				self.hiloCaida.start()
			else:
				self.repaint()
		if self.mover and e.key()==QtCore.Qt.Key_Left:
			x=self.jugador.getPosX()
			if(x>self._iniPendiente and x<self._finPendiente):
				self.jugador.retroceder()
				self.jugador.descender(2.65)
			elif x<=self._iniPendiente or x>=self._finPendiente:
				self.jugador.retroceder()
			if x>=200 and x<=300:
				self.hiloCaida=HiloCaida(self,-1)
				self.hiloCaida.start()
			else:
				self.repaint()
		if self.mover and e.key()==QtCore.Qt.Key_X:
			if(self.jugador.getPosX()>=40 and self.jugador.getPosX()<=75):
				self.hiloSalto=HiloSalto(self)
				self.hiloSalto.start()
			if(self.jugador.getPosX()>=370 and self.jugador.getPosX()<=420):
				self.todoTerreno=True
				self.jugador.setColor(Qt.black)
				self.repaint()
Exemplo n.º 30
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
import math
import random
import sys
import playsound

from Jugador import *
from Policia import *

from Carretera import *
from Obstaculos import *
from Vehiculos import *

from Interfaz import *

#Jugador
jugador = Jugador()

#Policia
policia = Policia()

#Carretera
tramo = Tramo(0.0, 0.0)
tramoAux = Tramo(0.0, 2.0)
calleTrans = CalleTrans()
caminoTrans = CaminoTrans()

#Obstaculos
cono = Cono()
barril = Barril()
ponLlan = PonLlan()
barrera = Barrera()
Exemplo n.º 32
0
class Aplicacion:
    windowWidth = 800
    windowHeight = 600
    jugador = 0
    manzana = 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)
        self.computadora = Computer(3)

    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode(
            (self.windowWidth, self.windowHeight), pygame.HWSURFACE)

        pygame.display.set_caption('Ejemplo de juego Snake aprenderPython.net')
        self._running = True
        #original-------------------------------------------------------------------------------------------------------------------------
        self._image_surf = pygame.image.load("block.jpg").convert()
        self._manzana_surf = pygame.image.load("manzana.jpg").convert()
        #correcion------------------------------------------------------------------------------------------------------------------------
        #self._image_surf = pygame.image.load('C:/Users/JJ Chalot/Documents/Escuela/Guereca - Taller inteligencia artificial/pygame/block.jpg').convert()
        #self._manzana_surf = pygame.image.load('C:/Users/JJ Chalot/Documents/Escuela/Guereca - Taller inteligencia artificial/pygame/manzana.jpg').convert()

    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def on_loop(self):
        self.jugador.update()
        self.computadora.update()
        self.computadora.target(self.manzana.x, self.manzana.y)

        # does snake eat manzana?
        for i in range(0, self.jugador.longitud):
            if self.juego.isCollision(self.manzana.x, self.manzana.y,
                                      self.jugador.x[i], self.jugador.y[i],
                                      44):
                self.manzana.x = randint(2, 9) * 44
                self.manzana.y = randint(2, 9) * 44
                self.jugador.longitud = self.jugador.longitud + 1

        # does computer's snake eat manzana?
        for i in range(0, self.computadora.longitud):
            if self.juego.isCollision(self.manzana.x, self.manzana.y,
                                      self.computadora.x[i],
                                      self.computadora.y[i], 44):
                self.manzana.x = randint(2, 9) * 44
                self.manzana.y = randint(2, 9) * 44
                self.computadora.longitud = self.computadora.longitud + 1

        # does snake collide with itself?
        for i in range(2, self.jugador.longitud):
            if self.juego.isCollision(self.jugador.x[0], self.jugador.y[0],
                                      self.jugador.x[i], self.jugador.y[i],
                                      40):
                print("You lose! Collision: ")
                print("x[0] (" + str(self.jugador.x[0]) + "," +
                      str(self.jugador.y[0]) + ")")
                print("x[" + str(i) + "] (" + str(self.jugador.x[i]) + "," +
                      str(self.jugador.y[i]) + ")")
                exit(0)

        pass

    def on_render(self):
        self._display_surf.fill((0, 0, 0))
        self.jugador.draw(self._display_surf, self._image_surf)
        self.manzana.draw(self._display_surf, self._manzana_surf)
        self.computadora.draw(self._display_surf, self._image_surf)
        pygame.display.flip()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while (self._running):
            pygame.event.pump()
            keys = pygame.key.get_pressed()

            if (keys[K_RIGHT]):
                self.jugador.moveRight()

            if (keys[K_LEFT]):
                self.jugador.moveLeft()

            if (keys[K_UP]):
                self.jugador.moveUp()

            if (keys[K_DOWN]):
                self.jugador.moveDown()

            if (keys[K_ESCAPE]):
                self._running = False

            self.on_loop()
            self.on_render()

            time.sleep(50.0 / 1000.0)
        self.on_cleanup()
#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):
Exemplo n.º 34
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()
Exemplo n.º 35
0
	def __init__(self,duel):
		Thread.__init__(self)
		self.duelo=duel
		self.stop=False
		
	def run(self):
		while True:
			if self.duelo.anchopintado<=0:
				self.duelo.anchopintado=498
				self.duelo.jugador.disminuirVidas()
				self.duelo.repaint()
				if self.duelo.jugador.vidas==0:	
					self.duelo.anchopintado=0
					self.duelo.repaint()
					break
			else:
				self.duelo.anchopintado-=5
				self.duelo.repaint()
			sleep(0.1)
			
			if self.stop:
				break
		
				
if __name__=="__main__":
	app=QApplication(sys.argv)
	jugador=Jugador(40,500,Qt.white,5)
	jugador.setNivel(2)
	Ventana_Duelo=Duelo(jugador)
	sys.exit(app.exec_())
Exemplo n.º 36
0
        for i in range(0,55):
            self.hi_there = tk.Button(self)
            self.hi_there["text"] = "Hello World\n(click me)"
            self.hi_there["command"] = self.say_hi
            self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = cGame(master=root)
app.mainloop()

listafichas=generaFichas.cGenera()

j1=Jugador.cJugador("jugador1",listafichas.listas[0:10])
j2=Jugador.cJugador("jugador2",listafichas.listas[10:20])
j3=Jugador.cJugador("jugador3",listafichas.listas[20:30])
j4=Jugador.cJugador("jugador4",listafichas.listas[30:40])

print(j1.fichas)
print(j2.fichas)
print(j3.fichas)
print(j4.fichas)


Exemplo n.º 37
0
def dibujarNuevoJuego(pantalla,X_Screen,Y_Screen):	
	pygame.display.set_caption("PUBLO DE KIBRA")	
	#creo un objeto de tipo fondo
	fondito=fondo()
	#creo un buffer  que va contener mi mapa 
	buffe=pygame.Surface((4000,4000))
	#creo una lista imagenes que va contener mis sprites
	sprites=fondito.cargarSprites("final3.png")	
	
	# dibujo mi buffer
	fondito.DrawPantalla(buffe,sprites)
	pantalla.blit(buffe.subsurface(X_Screen,Y_Screen,ANCHO,ALTO),(0,0))
	pygame.display.flip()
	#creo un objeto jugador
	jugadorP=Jugador()

	jug=jugadorP.cargarSprites();
	jugadorP.image = jug[0]

	
	while True:	
		tecla = pygame.key.get_pressed()
		tecla = pygame.key.get_pressed()
		pantalla.blit(buffe.subsurface(X_Screen,Y_Screen,ANCHO,ALTO),(0,0))
		pantalla.blit(jugadorP.image,(jugadorP.x,jugadorP.y))
		pygame.display.flip()
			
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			if tecla[K_RIGHT]:
				jugadorP.moverDerecha(jug)				
				if X_Screen == 3000:
					print "fdgdsfh"
				else:
					X_Screen = X_Screen+V
						
				print "holaaa"
			if tecla[K_DOWN]:
				jugadorP.moverAbajo(jug)				
				if Y_Screen == 3000:
					print "fdgdsfh"
				else:
					Y_Screen = Y_Screen+V
						
				print "holaaa"
			if tecla[K_UP]:
				jugadorP.moverArriba(jug)
				if Y_Screen == 0:
					print "fdgdsfh"
				else:
					Y_Screen = Y_Screen-V
			if tecla[K_LEFT]:
				jugadorP.moverIzquierda(jug)
				if X_Screen == 0:
					print "fdgdsfh"
				else:
					X_Screen = X_Screen-V
			#obtener la posicion del mouse cuando se da click en la pantalla
				
			if event.type== pygame.MOUSEBUTTONDOWN:	
				print "posicion X e Y "+str(pygame.mouse.get_pos())