Exemplo n.º 1
0
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((735, 800))
        pygame.display.set_caption("Pac-man")
        self.settings = Settings()

        self.radius = 1
        self.start = 2
        self.end = 10
        self.begin = pygame.time.get_ticks()
        self.wait = 800

        self.stats = Stats(self.settings)

        self.pb = Button(self.screen)

        self.maze = Maze(self.screen, 'images/maze.txt', 'images/cube0.png',
                         'images/gate0.png', 'images/dot0.png')

        self.sb = Scoreboard(self.settings, self.screen, self.stats, self.maze,
                             self.pb)

        self.player = Player(self.settings, self.screen, self.stats, self.sb,
                             self.maze)
        self.red = Red(self.screen, self.stats, self.player, self.sb,
                       self.maze)
        self.blue = Blue(self.screen, self.stats, self.player)
        self.orange = Orange(self.screen, self.stats, self.player)
        self.pink = Pink(self.screen, self.stats, self.player)

        self.menu = Menu(self.screen, self.stats, self.sb, self.pb, self.maze)
Exemplo n.º 2
0
    def create_ghost(self):
        self.red = Red(self.screen, self.stats, self.pacman, self.sb,
                       self.maze)

        self.red.centerx = self.screen_rect.left - 100
        self.red.rect.centery = self.screen_rect.centery

        self.red.index = 4

        self.blue = Blue(self.screen, self.stats, self.pacman)

        self.blue.centerx = self.screen_rect.left - 125
        self.blue.rect.centery = self.screen_rect.centery

        self.blue.index = 4

        self.orange = Orange(self.screen, self.stats, self.pacman)

        self.orange.centerx = self.screen_rect.left - 150
        self.orange.rect.centery = self.screen_rect.centery

        self.orange.index = 4

        self.pink = Pink(self.screen, self.stats, self.pacman)

        self.pink.centerx = self.screen_rect.left - 175
        self.pink.rect.centery = self.screen_rect.centery

        self.pink.index = 4
Exemplo n.º 3
0
    def __init__(self):
        pygame.init()
        pygame.mixer.pre_init(44100, 16, 2, 4096)
        self.settings = Settings()
        self.settings.start_intro_music()
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Pacman Portal")
        self.clock = pygame.time.Clock()
        self.radius = 1
        self.start = 1
        self.end = 10
        self.begin = pygame.time.get_ticks()
        self.wait = 800

        self.startup = Start(self.screen, self.settings)
        self.stats = Stats(self.settings)
        self.sb = Scoreboard(self.settings, self.screen, self.stats)

        self.maze = Maze(self.screen, mazefile='images/pacman_portal_maze.txt',
                         brickfile='square', orangeportalfile='portal_orange', blueportalfile='portal_blue',
                         shieldfile='shield', pointfile='point_pill', gatefile="gate")
        self.pacman = Pacman(self.screen, mazefile='images/pacman_portal_maze.txt')

        self.red = Red(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.blue = Blue(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.orange = Orange(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.pink = Pink(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.inc = 0
Exemplo n.º 4
0
    def __init__(self, manager):
        pygame.mixer.music.stop()
        pygame.mixer.music.load(os.getcwd() + "/sonidos/fondo_batalla.mp3")
        pygame.mixer.music.play(-1)
        self.net = Red()
        global personaje1, personaje2, fondo
        Pantalla.__init__(self, manager)
        self.agregar_sprite("fondo", Fondo(fondo))
        jugador = "jugador1" if self.net.id == "0" else "jugador2"
        self.jugador2 = "jugador2" if jugador == "jugador1" else "jugador1"
        self.jugador1 = Jugador(personaje1, jugador)

        self.id = 0
        self.ide = 0
        self.izquierda = False if self.net.id == "0" else True
        self.op_izquierda = True if self.izquierda == False else False
        personaje2 = self.jugador_data(
            self.net.send(
                str(self.net.id) + ":" + str(self.jugador1.image_rect.x) +
                "," + str(self.jugador1.image_rect.y)))
        if personaje2 != "":
            self.jugador2 = Jugador(personaje2, self.jugador2)
        else:
            self.jugador2 = None

        self.set_nombre_ventana("Jugando")
        self.handle_events()
        self.update()
Exemplo n.º 5
0
 def __init__(self, w, h):
     self.net = Red()
     self.width = w
     self.height = h
     self.player = Player(50, 50)
     self.player2 = Player(100, 100)
     self.canvas = Canvas(self.width, self.height, "Testing...")
Exemplo n.º 6
0
def run_red(G, S, H, genes):
    c = 100
    alpha = 0.1
    lambda_u = 1e-4
    lambda_v = lambda_u
    beta = alpha
    gene_red = Red(G, S, H, genes)
    gene_red.order(rank=c, lambda_u=lambda_u, lambda_v=lambda_v,
                               alpha=alpha, beta=beta,
                               verbose=False, callback=None)
    return gene_red
Exemplo n.º 7
0
 def __init__(self, red=None,cantidad = [6],activacion=["sigmoid"],dim_input=4,dim_output=1):
     self.cantidad = cantidad
     self.activacion = activacion
     self.dim_input = dim_input
     self.dim_output = dim_output
     if not(red):
         self.red = Red(cantidad=self.cantidad , activacion=self.activacion , dim_input=self.dim_input, dim_output=self.dim_output)
     else:
         self.red = red
     self.respuestas = 0
     self.distancia = 0
Exemplo n.º 8
0
 def test1(self):
     red = Red(cantidad=[1])
     red.capas[0][0].bias = 0.5
     red.capas[0][0].peso[0] = 0.4
     red.capas[0][0].peso[1] = 0.3
     red.capas[1][0].bias = 0.4
     red.capas[1][0].peso[0] = 0.3
     red.entrenar([[1, 1]], [[1]], [], [], epocas=1)
     self.assertEqual(0.502101508999489, red.capas[0][0].bias)
     self.assertEqual(0.40210150899948904, red.capas[0][0].peso[0])
     self.assertEqual(0.302101508999489, red.capas[0][0].peso[1])
     self.assertEqual(0.43937745312797394, red.capas[1][0].bias)
     self.assertEqual(0.33026254863991883, red.capas[1][0].peso[0])
Exemplo n.º 9
0
def analisisView(request):
	print 'hola'
	diccionario_autores = obtener_autores([open('busqueda.xml')])
	lista_autores = []
	lista_nombres = []
	for autor in diccionario_autores:
		lista_autores.append(diccionario_autores[autor])
		lista_nombres.append(autor)
	r=Red(lista_autores, 'autores3', lista_nombres)
	nodos, aristas = r.generar_json()
	nodos1=json.dumps(nodos)
	aristas1= json.dumps(aristas)
	#return render(request, "GestionAnalisis/Analisis.html", {"nodos":nodos, "aristas":aristas})
	return render(request, "GestionAnalisis/Analisis.html", {"nodos":nodos1, "aristas":aristas1})
Exemplo n.º 10
0
def run_red(G, S, H, genes):
    c = 100
    alpha = 0.1
    lambda_u = 1e-4
    lambda_v = lambda_u
    beta = alpha
    gene_red = Red(G, S, H, genes)
    gene_red.order(rank=c,
                   lambda_u=lambda_u,
                   lambda_v=lambda_v,
                   alpha=alpha,
                   beta=beta,
                   verbose=False,
                   callback=None)
    return gene_red
Exemplo n.º 11
0
def analisisView(request):
    print 'hola'
    diccionario_autores = obtener_autores([open('busqueda.xml')])
    lista_autores = []
    lista_nombres = []
    for autor in diccionario_autores:
        lista_autores.append(diccionario_autores[autor])
        lista_nombres.append(autor)
    r = Red(lista_autores, 'autores3', lista_nombres)
    nodos, aristas = r.generar_json()
    nodos1 = json.dumps(nodos)
    aristas1 = json.dumps(aristas)
    #return render(request, "GestionAnalisis/Analisis.html", {"nodos":nodos, "aristas":aristas})
    return render(request, "GestionAnalisis/Analisis.html", {
        "nodos": nodos1,
        "aristas": aristas1
    })
Exemplo n.º 12
0
    def main(self):
        run = True
        nt = Red(self.ip, self.puerto)
        avatar = nt.obtenerPK()
        clock = pygame.time.Clock()

        while run:
            clock.tick(60)
            avatares = nt.enviar(avatar)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                    pygame.quit()

            avatar.mover()
            time.sleep(0.02)
            self.repintarVentana(self.ventana, avatares)
Exemplo n.º 13
0
def main():
    run = True
    nt = Red("127.0.0.1", 5000)
    avatar = nt.obtenerPK()
    clock = pygame.time.Clock()

    while run:

        clock.tick(60)
        avatares = nt.enviar(avatar)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

        avatar.mover()
        repintarVentana(ventana, avatares)
Exemplo n.º 14
0
def generate_red(number_stations, name_stations, color_stations, conections):
    stations = np.array([])
    for i in range(number_stations):
        stations = np.append(stations,
                             Station(name_stations[i], color_stations[i]))
        for j in range(i):
            if conections[i][j] == "1":
                stations[i].append(stations[j])
                stations[j].append(stations[i])
    return Red(stations)
Exemplo n.º 15
0
    def get_color(self, color_name):
        if color_name == "blue":
            return Blue()
        if color_name == "red":
            return Red()
        if color_name == "green":
            return Green()

        print("Unknown color")

        return None
Exemplo n.º 16
0
class Player:
    def __init__(self, red=None,cantidad = [6],activacion=["sigmoid"],dim_input=4,dim_output=1):
        self.cantidad = cantidad
        self.activacion = activacion
        self.dim_input = dim_input
        self.dim_output = dim_output
        if not(red):
            self.red = Red(cantidad=self.cantidad , activacion=self.activacion , dim_input=self.dim_input, dim_output=self.dim_output)
        else:
            self.red = red
        self.respuestas = 0
        self.distancia = 0
    def generarHijo(self,padre,mutacion):
        punto = random.randint(0, self.red.total_neuronas)
        red_aux = Red(cantidad=self.cantidad, activacion=self.activacion, dim_input=self.dim_input, dim_output=self.dim_output)
        index_capa = 0
        cantidad_recorrida = 0
        for neuronas_capa_i in red_aux.capas:
            index_neurona = 0
            for neurona_capa_i in neuronas_capa_i:
                if not(random.randint(1, 100) <= mutacion):
                    if(cantidad_recorrida < punto):
                        neurona_capa_i.peso = self.red.capas[index_capa][index_neurona].peso
                        neurona_capa_i.bias = self.red.capas[index_capa][index_neurona].bias
                    else:
                        neurona_capa_i.peso = padre.red.capas[index_capa][index_neurona].peso
                        neurona_capa_i.bias = padre.red.capas[index_capa][index_neurona].bias
                index_neurona += 1
                cantidad_recorrida += 1
            index_capa += 1
        return Player(red=red_aux,
                      cantidad=self.cantidad, activacion=self.activacion, dim_input=self.dim_input, dim_output=self.dim_output)

    def movimiento(self,datos):
        resp = self.red.forward(datos)
        if(resp[0] > 0.5):
            return 1
        else:
            return 0

    def agregarDistancia(self,d):
        self.distancia += d

    def agregarRespuesta(self):
        self.respuestas += 1
Exemplo n.º 17
0
 def generarHijo(self,padre,mutacion):
     punto = random.randint(0, self.red.total_neuronas)
     red_aux = Red(cantidad=self.cantidad, activacion=self.activacion, dim_input=self.dim_input, dim_output=self.dim_output)
     index_capa = 0
     cantidad_recorrida = 0
     for neuronas_capa_i in red_aux.capas:
         index_neurona = 0
         for neurona_capa_i in neuronas_capa_i:
             if not(random.randint(1, 100) <= mutacion):
                 if(cantidad_recorrida < punto):
                     neurona_capa_i.peso = self.red.capas[index_capa][index_neurona].peso
                     neurona_capa_i.bias = self.red.capas[index_capa][index_neurona].bias
                 else:
                     neurona_capa_i.peso = padre.red.capas[index_capa][index_neurona].peso
                     neurona_capa_i.bias = padre.red.capas[index_capa][index_neurona].bias
             index_neurona += 1
             cantidad_recorrida += 1
         index_capa += 1
     return Player(red=red_aux,
                   cantidad=self.cantidad, activacion=self.activacion, dim_input=self.dim_input, dim_output=self.dim_output)
Exemplo n.º 18
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = 'dai'

import time
from movie import Movie
from red import Red
from model import MovieDB, session

while (True):
	print(time.strftime("%H:%M"))
	m = Movie("http://movie.douban.com/")
	m.dumpImg()
	r = Red(0)
	for i in m.arr:
		#如果存在记录,则更新评论人数和评级
		if(session.query(MovieDB).filter_by(title=i['title']).first() is not None):
			d = m.updateInfo(i['info'])
			try:
				s = session.query(MovieDB).filter_by(title=i['title']).first()
				s.average=d['average']
				s.votes=d['votes']
				session.add(s)
				session.commit()
			except Exception:
				continue
		else:
			d = m.getInfo(i['info'],i['title'])
			s = MovieDB(title = i['title'],
					director = d['director'],
Exemplo n.º 19
0
class Game:
    def __init__(self, w, h):
        self.net = Red()
        self.width = w
        self.height = h
        self.player = Player(50, 50)
        self.player2 = Player(100, 100)
        self.canvas = Canvas(self.width, self.height, "Testing...")

    def run(self):
        clock = pygame.time.Clock()
        run = True
        while run:
            clock.tick(60)

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

                if event.type == pygame.K_ESCAPE:
                    run = False

            keys = pygame.key.get_pressed()

            if keys[pygame.K_RIGHT]:
                if self.player.x <= self.width - self.player.velocity:
                    self.player.move(0)

            if keys[pygame.K_LEFT]:
                if self.player.x >= self.player.velocity:
                    self.player.move(1)

            if keys[pygame.K_UP]:
                if self.player.y >= self.player.velocity:
                    self.player.move(2)

            if keys[pygame.K_DOWN]:
                if self.player.y <= self.height - self.player.velocity:
                    self.player.move(3)

            # Envia a la libreria red
            self.player2.x, self.player2.y = self.parse_data(self.send_data())
            print(self.player2.x)
            print(self.player2.y)
            # Actualiza el Canvas
            self.canvas.draw_background()
            self.player.draw(self.canvas.get_canvas())
            self.player2.draw(self.canvas.get_canvas())
            self.canvas.update()

        pygame.quit()

    def send_data(self):
        """
        Send position to server
        :return: None
        """
        #Obtiene los datos y contruye el formato para enviarlo

        data = str(self.net.id) + ":" + str(self.player.x) + "," + str(
            self.player.y)
        reply = self.net.send(data)
        print(reply)
        print(data)
        return reply

    @staticmethod
    #Los une y lo hace por cada host
    def parse_data(data):
        try:
            d = data.split(":")[1].split(",")
            print(d)
            return int(d[0]), int(d[1])
        except:
            return 0, 0
Exemplo n.º 20
0
    print(
        "   test: En caso de ser el problema 0 la ruta del archivo de validacion"
    )
    print("         Si es el problema 1 el porcentaje de datos para entranar")
    sys.exit()

prueba = generar_df(leer_input(test_set))

capa = []
for i in range(int(capas)):
    capa += [
        int(
            input("Introduzca la cantidad de neuronas de la capa " +
                  str(i + 1) + ": "))
    ]
red = Red(capa, 2, float(eta))

epoca = 0
error = 0
errorAnt = 1000
while (epoca < 500 and abs(errorAnt - error) >= 0.000001):
    epoca += 1
    print(epoca)
    errorAnt = error
    error = 0
    for index, row in tabla.iterrows():
        estimulo = []
        for j in range(len(columnas) - 1):
            estimulo.append(row[columnas[j]])
        result = red.propagar(estimulo, row[columnas[-1]])
        error += (row[columnas[-1]] - max(result))**2
Exemplo n.º 21
0
total = [0,0,0,0,0]
for lineas in contents:
    dic = {3:0,4:0,5:1,6:2,7:3,8:4,9:4}
    x = lineas.split(";")
    if(primera):
        primera = False
    else:
        entradas.append([normalizar(float(x[0]),14.2,3.8),normalizar(float(x[1]),1.1,0.08),normalizar(float(x[2]),1.66,0),normalizar(float(x[3]),65.8,0.6),
                         normalizar(float(x[4]),0.346,.009),normalizar(float(x[5]),289.0,2.0),normalizar(float(x[6]),440.0,9.0),
                         normalizar(float(x[7]),1.04,0.99),normalizar(float(x[8]),3.82,2.72),normalizar(float(x[9]),1.08,0.22),normalizar(float(x[10]),14.2,8)])

        aux = [0,0,0,0,0,0,0]
        aux[dic[int(x[11])]] = 1
        total[dic[int(x[11])]] = total[dic[int(x[11])]] + 1
        salidas.append(aux)


entradas_train = entradas[:4500]
entradas_test = entradas[4500:]
salidas_train = salidas[:4500]
salidas_test = salidas[4500:]


neuronas = 5
epocas = 5000
red = Red(cantidad=[neuronas], activacion=["sigmoid"], dim_input=11, dim_output=5)
red.entrenar(entradas_train,salidas_train,entradas_test,salidas_test,epocas = epocas,guardar = True)



Exemplo n.º 22
0
    def construir_corpus(self, nombre, busqueda_inicial, conjunto_a, conjunto_s, conjunto_j, conjunto_o, clasificados, conjuntos_red = None, diccionario_todos_autores = None):
        '''Construye el corpus del modelo base a partir de la búsqueda incial y los conjuntos de atributos'''
        #Booleano que indica si estamos construyendo un corpus con redes
        corpus_red = conjuntos_red != None
        #Booleano que indica si estamos construyendo un corpus con redes recibiendo un diccionario
        corpus_red_diccionario = type(conjuntos_red) is dict
        corpus = open(nombre, 'w')
        ##corpus.write('nom,nom,nom,nom\n')
        #corpus.write('a'+'\n')
        if corpus_red:
            if self.EXP_BASE_WEIGHTS in nombre:
                corpus.write('nom,nom,nom,nom,num\n')
                corpus.write('A,S,J,O,AS,R\n')
            elif self.EXP_TODAS_MEDIDAS in nombre:
                corpus.write('nom,nom,nom,nom,num,num,num\n')
                corpus.write('A,S,J,O,AD,CC,APL,AS,R\n')
            elif self.EXP_ADCCAPLAS in nombre:
                corpus.write('num,num,num,num\n')
                corpus.write('AD,CC,APL,AS,R\n')
            elif self.EXP_CCAPLAS in nombre:
                corpus.write('num,num,num\n')
                corpus.write('CC,APL,AS,R\n')
            self.red = Red(dicci_to_list(conjuntos_red),'redCorpus', range(len(conjuntos_red)))

        else:
            corpus.write('nom,nom,nom,nom\n')
            corpus.write('A,S,J,O,R\n')


        lineaBI = 0

        for lineaBI, clasificacion in zip(busqueda_inicial,clasificados):
            print 'iteracion corpus'
            perteneceA = lineaBI in conjunto_a
            perteneceS = lineaBI in conjunto_s
            perteneceJ = lineaBI in conjunto_j
            perteneceO = lineaBI in conjunto_o

            #print (perteneceA)

            if corpus_red:

                #Autores qye trabajaron en el paper lineaBI
                autores_borrados= self.obtener_autores_borrados(lineaBI,diccionario_todos_autores)
                #Diccionario autores-eid sin los autores que se borran
                dicci_sin_autores = self.generar_dicci_sin_autores(autores_borrados, conjuntos_red)
                #Red sin autores
                redsita = Red(dicci_to_list(dicci_sin_autores), self.DIRECTORIO_REDES+str(lineaBI))
                ##print 'red retornada'
                average_path_lenght = redsita.average_path_lenght()
                ##print 'APL'
                average_degree = redsita.average_degree()
                ##print 'AD'
                clustering_coefficient = redsita.clustering_coefficient()
                ##print 'CC'
                ##print 'medidas basicas'
                average_strength = redsita.average_strength()
                ##print 'AS'
                ##print 'apl'
                '''corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                     str(int(perteneceO))+','+str(average_degree)+','+str(clustering_coefficient)+','+
                     str(average_path_lenght)+','+str(average_strength)+','+clasificacion.rstrip()+'\n')'''
                if self.EXP_BASE_WEIGHTS in nombre:
                    corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                         str(int(perteneceO))+','+str(redsita.weights())+','+clasificacion.rstrip()+'\n')
                elif self.EXP_TODAS_MEDIDAS in nombre:
                    corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                     str(int(perteneceO))+','+str(average_degree)+','+str(clustering_coefficient)+','+
                     str(average_path_lenght)+','+str(average_strength)+','+clasificacion.rstrip()+'\n')
                elif self.EXP_ADCCAPLAS in nombre:
                    corpus.write(str(average_degree)+','+str(clustering_coefficient)+','+
                     str(average_path_lenght)+','+str(average_strength)+','+clasificacion.rstrip()+'\n')
                elif self.EXP_CCAPLAS in nombre:
                    corpus.write(str(clustering_coefficient)+','+
                     str(average_path_lenght)+','+str(average_strength)+','+clasificacion.rstrip()+'\n')
            else:
                self.data.append([int(perteneceA), int(perteneceS), int(perteneceJ),
                                  int(perteneceO)])#, int(incide_red_sc)])
                corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                         str(int(perteneceO))+','+clasificacion.rstrip()+'\n')



            self.target.append(int(clasificacion.rstrip()))


        #return corpus
        corpus.close()
        print self.data
        print self.target
Exemplo n.º 23
0
class Game:
    BLACK = (0, 0, 0)

    def __init__(self):
        pygame.init()
        pygame.mixer.pre_init(44100, 16, 2, 4096)
        self.settings = Settings()
        self.settings.start_intro_music()
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Pacman Portal")
        self.clock = pygame.time.Clock()
        self.radius = 1
        self.start = 1
        self.end = 10
        self.begin = pygame.time.get_ticks()
        self.wait = 800

        self.startup = Start(self.screen, self.settings)
        self.stats = Stats(self.settings)
        self.sb = Scoreboard(self.settings, self.screen, self.stats)

        self.maze = Maze(self.screen, mazefile='images/pacman_portal_maze.txt',
                         brickfile='square', orangeportalfile='portal_orange', blueportalfile='portal_blue',
                         shieldfile='shield', pointfile='point_pill', gatefile="gate")
        self.pacman = Pacman(self.screen, mazefile='images/pacman_portal_maze.txt')

        self.red = Red(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.blue = Blue(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.orange = Orange(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.pink = Pink(self.screen, mazefile='images/pacman_portal_maze.txt')
        self.inc = 0

    def __str__(self): return 'Game(Pacman Portal), maze=' + str(self.maze) + ')'

    def open_portal(self, x, y, color):
        for r in range(self.start, self.end):
            pygame.gfxdraw.circle(self.screen, x, y, r, color)
        now = pygame.time.get_ticks()
        if now < self.begin + self.wait:
            self.inc = 1
        elif now < self.begin + 4 * self.wait:
            self.inc = 0
        else:
            self.inc = -1
        self.start += self.inc
        self.start = max(1, self.start)
        self.end += self.inc

    def play(self):
        clock = pygame.time.Clock()
        eloop = EventLoop(finished=False)
        while not eloop.finished:
            eloop.check_events(self.screen, self.pacman, self.startup)
            if self.startup.playing:
                pygame.mixer.music.stop()
                if not self.settings.flag_chomp:
                    self.settings.chomp_music()
                    self.settings.flag_chomp = True
                self.settings.chomp_music()
                self.pacman.update(self.maze, self.settings, self.stats, self.sb, self.red, self.blue, self.orange,
                                   self.pink)
                self.red.update(self.maze, self.settings, self.stats, self.pacman, self.startup, self.blue, self.pink,
                                self.orange, self.sb)
                self.blue.update(self.maze, self.settings, self.stats, self.pacman, self.startup, self.red, self.pink,
                                 self.orange, self.sb)
                self.orange.update(self.maze, self.settings, self.stats, self.pacman, self.startup, self.blue,
                                   self.pink, self.red, self.sb)
                self.pink.update(self.maze, self.settings, self.stats, self.pacman, self.startup, self.blue, self.red,
                                 self.orange, self.sb)

            self.update_screen()
            clock.tick(155)

    def update_screen(self):
        if not self.startup.playing:
            self.startup.draw_bg()
            self.startup.draw_button()
        else:
            self.screen.fill(Game.BLACK)
            self.maze.blitme()
            self.pacman.blitme()
            self.red.blitme()
            self.blue.blitme()
            self.orange.blitme()
            self.pink.blitme()
            self.open_portal(100, 100, (240, 100, 20))
            self.sb.show_score()
        pygame.display.flip()
Exemplo n.º 24
0
class Juego(Pantalla):
    def __init__(self, manager):
        pygame.mixer.music.stop()
        pygame.mixer.music.load(os.getcwd() + "/sonidos/fondo_batalla.mp3")
        pygame.mixer.music.play(-1)
        self.net = Red()
        global personaje1, personaje2, fondo
        Pantalla.__init__(self, manager)
        self.agregar_sprite("fondo", Fondo(fondo))
        jugador = "jugador1" if self.net.id == "0" else "jugador2"
        self.jugador2 = "jugador2" if jugador == "jugador1" else "jugador1"
        self.jugador1 = Jugador(personaje1, jugador)

        self.id = 0
        self.ide = 0
        self.izquierda = False if self.net.id == "0" else True
        self.op_izquierda = True if self.izquierda == False else False
        personaje2 = self.jugador_data(
            self.net.send(
                str(self.net.id) + ":" + str(self.jugador1.image_rect.x) +
                "," + str(self.jugador1.image_rect.y)))
        if personaje2 != "":
            self.jugador2 = Jugador(personaje2, self.jugador2)
        else:
            self.jugador2 = None

        self.set_nombre_ventana("Jugando")
        self.handle_events()
        self.update()
        #self.num = insertar(apodo,0)

    @staticmethod
    def jugador_data(data):
        try:
            return data.split(":")[1].split(",")[2]
        except:
            return ""

    @staticmethod
    def parse_data(data):
        try:
            d = data.split(":")[1].split(",")
            bol = True if d[3] == "si" else False
            return int(d[0]), int(d[1]), d[2], bol, int(d[4]), int(d[5])
        except:
            return 0, 0, "", True, 0, 100

    def handle_events(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_w] and self.jugador1.image_rect.y > (
                400 - self.jugador1.image_rect.height):
            self.id += 1
            if self.id > 2:
                self.id = 0
            self.jugador1.image_rect.y -= velocidad_v
        if keys[pygame.K_s] and self.jugador1.image_rect.y < (
                600 - self.jugador1.image_rect.height):
            self.id += 1
            if self.id > 2:
                self.id = 0
            self.jugador1.image_rect.y += velocidad_v
        if keys[pygame.K_a] and self.jugador1.image_rect.x > 0:
            self.id += 1
            if self.id > 2:
                self.id = 0
            self.izquierda = True
            self.jugador1.image_rect.x -= velocidad_h
        if keys[pygame.K_d] and self.jugador1.image_rect.x < (
                800 - self.jugador1.image_rect.width):
            self.id += 1
            if self.id > 2:
                self.id = 0
            self.izquierda = False
            self.jugador1.image_rect.x += velocidad_h

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_b:
                    if self.jugador2 != None:
                        if self.jugador1.image_rect.colliderect(
                                self.jugador2.image_rect
                        ) and self.jugador1.image_rect.y >= (
                                self.jugador2.image_rect.y -
                                10) and self.jugador1.image_rect.y <= (
                                    self.jugador2.image_rect.y + 10):
                            s = pygame.mixer.Sound(os.getcwd() +
                                                   "/sonidos/golpe.mp3")
                            pygame.mixer.Sound.play(s)
                            self.jugador2.bajar_vida()
                            self.jugador1.score += 5

    def determinar_fin(self):
        if self.jugador1.vida <= 0:
            time.sleep(10)
            fuente = pygame.font.SysFont("Verdana", 30)
            texto = fuente.render("PERDISTE, " + apodo, 0, (0, 0, 0))
            self.canvas.blit(texto, (350, 0))
            time.sleep(10)
            self.manager.cambiar_pantalla(Login(self.manager))
            #print(actualizar(self.num,apodo,self.jugador1.score))
        elif self.jugador2.vida <= 0:
            fuente = pygame.font.SysFont("Verdana", 30)
            texto = fuente.render("GANASTE, " + apodo, 0, (0, 0, 0))
            self.canvas.blit(texto, (350, 0))
            time.sleep(10)
            self.manager.cambiar_pantalla(Login(self.manager))
            #print(actualizar(self.num,apodo,self.jugador1.score))

    def update(self):
        global personaje2
        izq = "si" if self.izquierda == True else "no"
        vida = 100 if self.jugador2 == None else self.jugador2.vida
        x, y, personaje2, izquierda, self.ide, self.jugador1.vida = self.parse_data(
            self.net.send(
                str(self.net.id) + ":" + str(self.jugador1.image_rect.x) +
                "," + str(self.jugador1.image_rect.y) + "," + personaje1 +
                "," + izq + "," + str(self.id) + "," + str(vida)))
        if self.jugador2 == None and personaje2 != "":
            self.jugador2 = Jugador(personaje2, self.jugador2)
        elif personaje2 != "":
            self.jugador2.image_rect.x = x
            self.jugador2.image_rect.y = y
        self.op_izquierda = izquierda

    def render(self):
        surf = pygame.Surface(
            (self.sprites["fondo"].ancho, self.sprites["fondo"].alto))
        self.canvas.blit(
            self.sprites["fondo"].image,
            surf.get_rect(topleft=(self.sprites["fondo"].x,
                                   self.sprites["fondo"].y)))
        if self.izquierda == True:
            self.canvas.blit(
                pygame.transform.flip(self.jugador1.persona_viva[self.id],
                                      True, False), self.jugador1.image_rect)
        else:
            self.canvas.blit(self.jugador1.persona_viva[self.id],
                             self.jugador1.image_rect)
        if self.op_izquierda == True and self.jugador2 != None:
            self.canvas.blit(
                pygame.transform.flip(self.jugador2.persona_viva[self.ide],
                                      True, False), self.jugador2.image_rect)
        elif self.jugador2 != None:
            self.canvas.blit(self.jugador2.persona_viva[self.ide],
                             self.jugador2.image_rect)
        if self.jugador2 != None:
            self.determinar_fin()
        pygame.display.flip()
Exemplo n.º 25
0
    def construir_corpus(self, nombre, busqueda_inicial, conjunto_a, conjunto_s, conjunto_j, conjunto_o, clasificados, conjuntos_red = None, diccionario_todos_autores = None):
        '''Construye el corpus del modelo base a partir de la búsqueda incial y los conjuntos de atributos'''
        #Booleano que indica si estamos construyendo un corpus con redes
        corpus_red = conjuntos_red != None
        #Booleano que indica si estamos construyendo un corpus con redes recibiendo un diccionario
        corpus_red_diccionario = type(conjuntos_red) is dict

        corpus = open(nombre, 'w')
        ##corpus.write('nom,nom,nom,nom\n')
        #corpus.write('a'+'\n')
        if corpus_red:
            if corpus_red_diccionario:
                #corpus.write('A,S,J,O,AD,CC,APL,AS,R\n')
                corpus.write('nom,nom,nom,nom,num\n')
                corpus.write('A,S,J,O,AS,R\n')
                self.red = Red(dicci_to_list(conjuntos_red),'redCorpus')
            else:
                corpus.write('A,S,J,O,redS,redSC,R\n')
                average_strength_red_s = self.average_strength(self.obtener_grafo('s', 'EID'))
                average_strength_red_sc = self.average_strength(self.obtener_grafo('sc', 'EID'))
                #Medidas globales de las redes enteras.
        else:
            corpus.write('nom,nom,nom,nom\n')
            corpus.write('A,S,J,O,R\n')


        lineaBI = 0

        for lineaBI, clasificacion in zip(busqueda_inicial,clasificados):

            perteneceA = lineaBI in conjunto_a
            perteneceS = lineaBI in conjunto_s
            perteneceJ = lineaBI in conjunto_j
            perteneceO = lineaBI in conjunto_o

            #print (perteneceA)

            if corpus_red:
                if corpus_red_diccionario:
                    #Autores qye trabajaron en el paper lineaBI
                    autores_borrados= self.obtener_autores_borrados(lineaBI,diccionario_todos_autores)
                    #Diccionario autores-eid sin los autores que se borran
                    dicci_sin_autores = self.generar_dicci_sin_autores(autores_borrados, conjuntos_red)
                    #Red sin autores
                    redsita = Red(dicci_to_list(dicci_sin_autores), self.DIRECTORIO_REDES+str(lineaBI))
                    average_path_lenght = redsita.average_path_lenght()
                    average_degree = redsita.average_degree()
                    clustering_coefficient = redsita.clustering_coefficient()
                    average_strength = redsita.average_strength()
                    '''corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                         str(int(perteneceO))+','+str(average_degree)+','+str(clustering_coefficient)+','+
                         str(average_path_lenght)+','+str(average_strength)+','+clasificacion.rstrip()+'\n')'''
                    corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                         str(int(perteneceO))+','+str(redsita.weights())+','+clasificacion.rstrip()+'\n')
                else:
                    incide_red_s = self.obtener_atributo_existe_relacion('s', lineaBI, average_strength_red_s)
                    incide_red_sc = self.obtener_atributo_existe_relacion('sc', lineaBI, average_strength_red_sc)
                    self.data.append([int(perteneceA), int(perteneceS), int(perteneceJ),
                                  int(perteneceO), int(incide_red_sc)])
                    corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                             str(int(perteneceO))+','+incide_red_s+','+incide_red_sc+','+clasificacion.rstrip()+'\n')
            else:
                self.data.append([int(perteneceA), int(perteneceS), int(perteneceJ),
                                  int(perteneceO)])#, int(incide_red_sc)])
                corpus.write(str(int(perteneceA))+','+str(int(perteneceS))+','+str(int(perteneceJ))+','+
                         str(int(perteneceO))+','+clasificacion.rstrip()+'\n')



            self.target.append(int(clasificacion.rstrip()))



        corpus.close()
        print self.data
        print self.target
Exemplo n.º 26
0
class Menu:
    def __init__(self, screen, stats, sb, play_button, maze):
        self.settings = Settings()
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.button = play_button
        self.stats = stats
        self.sb = sb

        self.maze = maze

        self.menu_color = (0, 0, 0)
        self.text_color = (250, 250, 210)
        self.font = pygame.font.SysFont(None, 150)

        self.title = "Pac-man"

        self.prep_screen()

    def prep_screen(self):
        self.title_image = self.font.render(self.title, True, self.text_color,
                                            self.menu_color)
        self.title_image_rect = self.title_image.get_rect()
        self.title_image_rect.centerx = self.screen_rect.centerx
        self.title_image_rect.centery = self.screen_rect.top + 100

        self.create_pacman()
        self.create_ghost()

    def draw_menu(self):
        self.screen.fill((0, 0, 0))
        self.screen.blit(self.title_image, self.title_image_rect)
        self.button.draw_button()
        self.animate_pacman()
        self.animate_ghost()

    def create_pacman(self):
        self.pacman = Player(self.settings, self.screen, self.stats, self.sb,
                             self.maze)

        self.pacman.centerx = self.screen_rect.left
        self.pacman.rect.centery = self.screen_rect.centery

        self.pacman.index = 4

    def create_ghost(self):
        self.red = Red(self.screen, self.stats, self.pacman, self.sb,
                       self.maze)

        self.red.centerx = self.screen_rect.left - 100
        self.red.rect.centery = self.screen_rect.centery

        self.red.index = 4

        self.blue = Blue(self.screen, self.stats, self.pacman)

        self.blue.centerx = self.screen_rect.left - 125
        self.blue.rect.centery = self.screen_rect.centery

        self.blue.index = 4

        self.orange = Orange(self.screen, self.stats, self.pacman)

        self.orange.centerx = self.screen_rect.left - 150
        self.orange.rect.centery = self.screen_rect.centery

        self.orange.index = 4

        self.pink = Pink(self.screen, self.stats, self.pacman)

        self.pink.centerx = self.screen_rect.left - 175
        self.pink.rect.centery = self.screen_rect.centery

        self.pink.index = 4

    def animate_pacman(self):
        self.pacman.screen_animate()
        self.pacman.blitme()

    def animate_ghost(self):
        self.red.screen_animate()
        self.red.blitme()

        self.blue.screen_animate()
        self.blue.blitme()

        self.orange.screen_animate()
        self.orange.blitme()

        self.pink.screen_animate()
        self.pink.blitme()
Exemplo n.º 27
0
def sync(ran):
	r = Red(0)
	for i in range(0,ran):
		try:
			s = session.query(MovieDB).filter_by(id=i).first()
			if(s):
				r.add('全部',i)
				for t in str2list(s.types):
					r.add('type',t)
					r.add(t,i)
				for o in str2list(s.ontime):
					o = o.split('-')[0]
					r.add('ontimes',o)
					r.add(o,i)
				for x in s.country.split(' / '):
					r.add('country',x)
					r.add(x,i)
		except Exception:
			pass
Exemplo n.º 28
0
class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((735, 800))
        pygame.display.set_caption("Pac-man")
        self.settings = Settings()

        self.radius = 1
        self.start = 2
        self.end = 10
        self.begin = pygame.time.get_ticks()
        self.wait = 800

        self.stats = Stats(self.settings)

        self.pb = Button(self.screen)

        self.maze = Maze(self.screen, 'images/maze.txt', 'images/cube0.png',
                         'images/gate0.png', 'images/dot0.png')

        self.sb = Scoreboard(self.settings, self.screen, self.stats, self.maze,
                             self.pb)

        self.player = Player(self.settings, self.screen, self.stats, self.sb,
                             self.maze)
        self.red = Red(self.screen, self.stats, self.player, self.sb,
                       self.maze)
        self.blue = Blue(self.screen, self.stats, self.player)
        self.orange = Orange(self.screen, self.stats, self.player)
        self.pink = Pink(self.screen, self.stats, self.player)

        self.menu = Menu(self.screen, self.stats, self.sb, self.pb, self.maze)

    def open_portal(self, x, y, color):
        for r in range(self.start, self.end):
            pygame.gfxdraw.circle(self.screen, x, y, r, color)
        now = pygame.time.get_ticks()
        if now < self.begin + self.wait:
            self.inc = 1
        elif now < self.begin + 4 * self.wait:
            self.inc = 0
        else:
            self.inc = -1

        self.start += self.inc
        self.start = max(1, self.start)
        self.end += self.inc

    def play(self):
        clock = pygame.time.Clock()
        eloop = EventLoop(finished=False)

        self.menu.prep_screen()

        while not eloop.finished:
            eloop.check_events(self.settings, self.screen, self.stats, self.sb,
                               self.player, self.pb, self.maze)

            if self.stats.game_active:
                self.player.update(self.maze)
                self.red.update()
                self.blue.update()
                self.orange.update()
                self.pink.update()

            self.display_game()
            clock.tick(20)

    def display_game(self):
        self.screen.fill((0, 0, 0))
        self.maze.blitme()
        self.open_portal(365, 550, (240, 100, 20))
        self.player.blitme()
        self.red.blitme()
        self.blue.blitme()
        self.orange.blitme()
        self.pink.blitme()
        self.sb.show_score()

        if not self.stats.game_active:
            self.menu.draw_menu()
            if self.stats.HS_active:
                self.display_HS_menu()

        pygame.display.flip()

    def display_HS_menu(self):
        self.screen.fill((0, 0, 0))
        self.sb.prep_list()
        self.sb.display_list()