Exemplo n.º 1
0
def estado_estadisticas(vista):
    global campo
    lim = 2000
    carpeta = "IA_80"
    victorias = []
    for i in range(0, lim + 1, 50):
        print(str(i))
        network = import_network(carpeta + "/IA_java_" + str(i) + ".txt")

        contador_nn = 0
        for j in range(200):

            campo = mdl.Campo()
            campo.rellenar(mdl.training_2, mdl.training_1)
            ia_greedy = Greedy.IA("T2", campo, 0.5)
            ia_nn = IA(network, "T1", campo, 0.5)
            tiempo = 0
            while True:
                dt = 200
                tiempo += dt
                campo.actualizar(dt / 1000)
                if campo.revisarDerrota("T1"):
                    break
                elif campo.revisarDerrota("T2"):
                    contador_nn += 1
                    break

                if tiempo > 600000:
                    print("SE METIO EN UN LOOP")
                    break
                ia_greedy.jugar(dt)
                ia_nn.jugar(dt)
        victorias.append(contador_nn)
    print(str(victorias))
    return "menu"
Exemplo n.º 2
0
def jeu(longueur, hauteur, avance, profB, profN, alphaBeta):
    etat = s.State(longueur, hauteur)
    etat.create()
    etat.setCurrentPlayer("j1")
    etat.board[0][0] = "j1"
    etat.board[-1][-1] = "j2"
    tour = 0
    print("tour de jeu: ", tour)
    etat.affiche()
    nombreNoeudTotal = 0

    while (not (etat.isFinished())):
        if (avance > 0):
            avance = avance - 1
            etat.setCurrentPlayer("j1")
        p = etat.getCurrentPlayer()
        if (p == "j1"):
            iajoueur = ia.IA(p, profB, alphaBeta)
        else:
            iajoueur = ia.IA(p, profN, alphaBeta)
        l = etat.getMoves(p)
        #m=choice(l)
        m = iajoueur.decide(etat)
        etat = etat.play(m)
        tour += 1
        print("tour de jeu: ", tour)
        etat.affiche()

    print("nbPionts j1: ", etat.nbPionts("j1"))
    print("nbPionts j2: ", etat.nbPionts("j2"))
Exemplo n.º 3
0
def estadoEntrenamiento(vista):
    global campo
    clock = pygame.time.Clock()
    network = import_network("IA_50_50_50/IA_java_3550.txt")
    #network = Network(50, [300, 100, 20])
    seguir = True
    contador_greedy = 0
    contador_nn = 0
    while seguir:
        campo = mdl.Campo()
        campo.rellenar(mdl.training_2, mdl.training_1)
        ia_greedy = Greedy.IA("T2", campo, 0.5)
        ia_nn = IA(network, "T1", campo, 0.5)
        vista.setCampo(campo)
        vista.setJugador(jugador)
        termino = False
        while True:
            dt = 200
            #dt=clock.tick(60)
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        seguir = False

            campo.actualizar(dt / 1000)

            ver = False
            if ver:
                vista.dibujarCampoEntrenamiento()
                pygame.display.flip()

            if campo.revisarDerrota("T1"):
                #ia_greedy.escribir_jugadas("jugadas.txt")
                contador_greedy += 1
                termino = True
            elif campo.revisarDerrota("T2"):
                #ia_nn.escribir_jugadas("jugadas.txt")
                contador_nn += 1
                termino = True

            if termino:
                break

            ia_greedy.jugar(dt)
            ia_nn.jugar(dt)
        #jugadas=ia_greedy.get_jugadas()
        #ia_nn.entrenar_greedy(jugadas,10,0.0002)
        #ia_nn.entrenar_jugadas(10,0.0002)

    #network.export_network("IA_java2.txt")
    print("greedy: " + str(contador_greedy))
    print("nn: " + str(contador_nn))
    return "menu"
Exemplo n.º 4
0
    def __init__(self, mode = 1, dis = 0, showMove = True, showRecherche = False, showGUI = True, saveInfo = False):
                self.Plateau = PlateauEchecs()
                self.Player_Side = False
                self.GameMode = mode
                self.distribution = dis

                self.ai_0 = IA()
                self.ai_1 = IA()

                self.ShowMoveInfo = showMove
                self.ShowRechercheInfo = showRecherche
                self.ShowGraphUI = showGUI
                self.SaveInfo = saveInfo

                self.view = GraphEchecs(self)
Exemplo n.º 5
0
def playTurnIA(gui, node, game, condition):
    delete_node(gui.nodes, node.id_node)
    if (noMorePoisonedNodes(gui.nodes)):
        return loose(gui, game.turn)
    game.play()
    gui.canvas.delete("graph")
    gui.drawArrows()
    gui.drawNodes()
    gui.drawTurn(game)
    gui.hideTimer("hider")
    condition.timer1.pause()
    gui.canvas.update()
    time.sleep(0)  #We leave 1 second for the player to view his screen
    if (game.turn == 2):
        gui.canvas.delete("hider")
        delete_node(gui.nodes, IA.chooseNode(gui.nodes))  # IA delete
        if (noMorePoisonedNodes(
                gui.nodes)):  # if there are no more poisoned, loose
            return loose(gui, game.turn)
        game.play()
        gui.canvas.delete("graph")
        gui.drawArrows()
        gui.drawNodes()
        gui.drawTurn(game)
        gui.drawTimeRest(game.turn)
Exemplo n.º 6
0
    def __init__(self, IAcontador='0'):
        import IA
        if IAcontador == '1':
            self.jugadores = [Jugador(0), IA.Minimax(1)]
        elif IAcontador == '2':
            self.jugadores = [IA.Minimax(0), IA.Minimax(1)]
        else:
            self.jugadores = [Jugador(0), Jugador(1)]
        self.paredes = []
        self.casillas = [[], [], [], [], [], [], [], [], []]
        self.actual = 0
        self.actual = random.randint(0, 1)

        for i in range(0, 8):
            for j in range(0, 8):
                self.casillas[i].append(Casilla(i, j))
Exemplo n.º 7
0
 def loadGame(self, event):
     """
         Permet de charger la dernière partie sauvegardée pour initialiser le 2048 et conserver le score et les combos
     """
     #Si le fichier save.txt est vide on lance une nouvelle
     if (os.path.getsize("save.txt") == 0):
         mess = QMessageBox(self)
         mess.setText(
             "Aucune sauvegarde n'a été trouvé. Lancement d'une nouvelle partie !"
         )
         mess.setWindowTitle("Erreur")
         mess.setIcon(QMessageBox.Information)
         mess.setStandardButtons(QMessageBox.Ok)
         mess.exec_()
     save = open("save.txt", 'r')
     cpt = 0
     for i in save:
         if (cpt == 8):
             self.mode = i
         cpt += 1
     if (self.mode != "tetris"):
         self.game = Game(self, self.mode)
         self.setRenderArea()
         if (self.mode == "vsIa"):
             self.vsIa = IA(self.game.liste)
     else:
         self.game = GameTetris(self)
         self.setRenderArea()
     #On met à jour l'interface graphique avec les infos du fichier
     self.renderAreaGame.score = self.game.score
     self.renderAreaGame.liste = self.game.liste
     self.renderAreaGame.combo = self.game.combo
     self.renderAreaGame.comboSteps = self.game.comboSteps
     self.renderAreaGame.repaint()
Exemplo n.º 8
0
 def IATurn(self):
     sources = battle.selectUnitsSources(self.board, self.team)
     if self.isTurnPossible(len(sources),1):
         attackInformations = IA.play(self.board, self.team, sources)
         self.source = attackInformations[0]
         self.target = attackInformations[1]
         print("source : " + str(self.source) + "\target : " + str(self.target))
         self.root.update()
         time.sleep(self.timeToSleep*2)
         self.changeBgColorOfOneButton(self.source, "#FFFF00")
         self.root.update()
         time.sleep(self.timeToSleep)
         self.changeBgColorOfOneButton(self.target, "#FFFF00")
         self.root.update()
         time.sleep(self.timeToSleep)
         if self.source == self.target:
             self.isTurnPossible(0,2)
             if not self.isItFinish:
                 self.newTurn()
             else:
                 self.displayGameEnd()
         else:
             self.isTurnPossible(1,2)
             self.attack()
     else:
         if not self.isItFinish:
             self.newTurn()
         else:
             self.displayGameEnd()
Exemplo n.º 9
0
    def _nextmove(self, state):
        # Two possible situations:
        # - If the player is the first to play, it has to select his/her assassins
        #   The move is a dictionary with a key 'assassins' whose value is a list of villagers' names
        # - Otherwise, it has to choose a sequence of actions
        #   The possible actions are:
        #   ('move', x, y, dir): moves person at position (x,y) of one cell in direction dir
        #   ('arrest', x, y, dir): arrests the villager in direction dir with knight at position (x, y)
        #   ('kill', x, y, dir): kills the assassin/knight in direction dir with knight/assassin at position (x, y)
        #   ('attack', x, y, dir): attacks the king in direction dir with assassin at position (x, y)
        #   ('reveal', x, y): reveals villager at position (x,y) as an assassin
        state = state._state['visible']
        if state['card'] is None:
            return json.dumps({'assassins': IA.ChooseAssassins(state) }, separators=(',', ':'))
        else:
            #player 0 : on est l'assassin
            if self._playernb == 0:
                #if IA.CanKill(Xking,Yking,Xas,Yas,state) is True :

                #else:
                PAvillagers = state['card'][3]
                PAknight = state['card'][1]
                PAking = state['card'][0]
                Villagers = []
                for i in range(10):
                    for j in range(10):
                        if state['people'][i][j] not in {'knight','king',None}:
                            Villagers.append(state['people'][i][j])
                move = []
                while len(move) < PAvillagers:
                    directions = ['N','S','W','E']
                    name = random.choice(Villagers)
                    direct = random.choice(directions)
                    coordonnees = IA.coord(name,state)
                    z = IA.nextposfree(coordonnees[0],coordonnees[1],direct,state)
                    Newx = z[0]
                    Newy = z[1]
                    if state['people'][Newx][Newy] == None :
                        move.append(('move',coordonnees[0],coordonnees[1],direct))
                        state['people'][coordonnees[0]][coordonnees[1]] = None
                        state['people'][Newx][Newy]= name
                        if IA.OnRoof(coordonnees[1],coordonnees[0],Newx,Newy,state) is True:
                            PAvillagers-=1
                return json.dumps({'actions': move }, separators=(',', ':'))
            #player 1 : on est le roi
            else:
                return json.dumps({'actions': []}, separators=(',', ':'))
Exemplo n.º 10
0
def lancer(temps=125):
    t0 = time()
    # On récupère les données
    grille = capture.capturer()

    # On cherche dans le dictionnaire
    for mot in IA.donner_mot(grille, dico):
        cliquer(mot)
        if time() - t0 > temps: break  # On s'arrete si on dépasse le temps.
Exemplo n.º 11
0
 def setVsIa(self, event):
     """
         Crée une game en mode contre l'IA
         :param event: événement
         :type event: event
     """
     self.mode = "vsIa"
     self.newGame(None)
     self.vsIa = IA(self.game.liste)
Exemplo n.º 12
0
	def __init__(self, number):
		self.partyInfos = PartyInformations(number)
		self.parser = Parser(self.partyInfos)
		while self.parser.tryRead() == False:
			continue
		while True:
			start = timer()
			self.parser.updateInfos()
			if number == 1:
				self.parser.getGhost()
			self.parser.parseTourInfos()
			if self.parser.readQuestion() == False:
				continue
			if self.parser.questionType == self.parser.tileQuestion:
				IA.compute(self.partyInfos)
				end = timer()
				print("time elapsed = " + str(end - start))
			self.parser.sendResponse()
Exemplo n.º 13
0
def test():
    etat = s.State(3, 3)
    etat.create()
    etat.setCurrentPlayer("j1")
    etat.board[0][0] = "j1"
    etat.board[-1][-1] = "j2"
    etat.affiche()
    iaj = ia.IA("j1", 3, False)
    iaj.decide(etat)
    print(iaj.nombreNoeud)
Exemplo n.º 14
0
 def mainLoop(self):
     turn = [IA.GHOST, IA.INSPECTOR, IA.INSPECTOR, IA.GHOST]
     taro = self.characters[4:]
     for i in range(len(taro)):
         result = IA.computeTaros(taro, self.rooms, turn[i])
         print "\t", turn[i], "MOVE::", result[
             "perso"].color, " from ", result[
                 "perso"].room.name, " to ", result["move"].name
         result["perso"].moveToRoom(result["move"])
         taro.remove(result["perso"])
     return
Exemplo n.º 15
0
    def place_hands(self):
        '''Cette méthode prend en argument le jeu donc la classe qui gère les cartes etc...,
        donc qui possède en attribut les mains des joueurs à la fois sous forme de tableau de classes
        héritant de Playing_Card_GUI'''

        #On initialise la position des points stratégiques EST,SUD,NORD et OUEST

        nord = (self.__width // 2 - 3 * 50, 50)
        sud = (self.__width // 2 - 18 * 50 * 0.35 // 2, self.__height - 100)
        est = (20, self.__height // 2)
        ouest = (self.__width - 50 * 7, self.__height // 2)

        side = [sud, est, nord, ouest]
        pos = ["SOUTH", "EAST", "NORTH", "WEST"]

        #On initialise les joueurs
        for i in range(4):
            if i == 0:
                p = Human(0, "Joueur {}".format(i))
            else:
                p = IA(0, "Joueur {}".format(i))
            p.set_instance(i)
            cards = []
            for j in range(18):
                r = randint(0, len(self.__deck) - 1)
                self.__deck[r].set_in_hand(True)
                cards.append(self.__deck[r])
                self.__deck.pop(r)
            #On donne une main au joueur aléatoirement
            #print(Hand(cards,side[i]))
            h = Hand(cards, side[i], pos[i])
            for c in cards:
                c.set_hand(h)
            p.set_hand(h)

            self.__players.append(p)

        for i in range(len(self.__deck)):
            self.__dog.add_card(self.__deck[i])

        h1 = self.__players[0].get_hand()
        h2 = self.__players[1].get_hand()
        h3 = self.__players[2].get_hand()
        h4 = self.__players[3].get_hand()

        #        h1.set_position(sud)
        #        h2.set_position(ouest)
        #        h3.set_position(nord)
        #        h4.set_position(est)
        h1.show()
        h2.show()
        h3.show()
        h4.show()
        self.__dog.show_dog(self)
Exemplo n.º 16
0
    def __init__(self, *args, **kwargs):

        super().__init__()

        self.p = profile.Profile()
        self.p.enable()

        self.estilo = int(sys.argv[1])

        #Aqui basicamente se instancia e inicia todas as partes da interface
        self.iniciaComponentes()

        self.jogo = Jogo()

        self.playerAtual = self.jogo.turno

        self.alteraContexto()
        self.alteraContexto()

        self.ia1 = IA(self.jogo)
        self.ia2 = IA(self.jogo)
Exemplo n.º 17
0
 def setIA(self, event):
     """
         Active l'IA
         :param event: événement
         :type event: event
     """
     if (self.canPlay):  #Verifie si l'utilisateur n'est plus dans le menu
         #Initialise l'IA
         self.ia = IA(self.game.liste)
         #Tant que le bot n'a pas perdu ou gagné et qu'il est toujours activé
         while not (self.game.isWin()
                    or self.game.isLose()) and self.iaRunning:
             QCoreApplication.processEvents()
             self.ia.liste = self.game.liste
             moves = self.ia.play()
             if (self.game.move(moves[0])):
                 self.game.spawnRandom()
             if (self.game.move(moves[1])):
                 self.game.spawnRandom()
             if (self.game.move(moves[2])):
                 self.game.spawnRandom()
Exemplo n.º 18
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.º 19
0
def lancer():
    t0 = time.time()
    # On récupère les données
    grille = capture.capturer(x0, y0, x1, y1)
    t1 = time.time()
    print("Capture effectuée en {} s".format(round(t1 - t0, 1)))
    print("Recherche de la solution")
    # On détermine la solution
    solution = IA.donner_solution(grille)
    print("Solution trouvée en {} s".format(round(time.time() - t1, 1)))
    # On remplit la grille sur l'emulateur
    for i in range(9):
        for j in range(9):
            if grille[i][
                    j] == 0:  # Si la case etait vide au début, on la remplit
                cliquer(i, j, solution[i][j])
 def _nextmove(self, state):
     # Two possible situations:
     # - If the player is the first to play, it has to select his/her assassins
     #   The move is a dictionary with a key 'assassins' whose value is a list of villagers' names
     # - Otherwise, it has to choose a sequence of actions
     #   The possible actions are:
     #   ('move', x, y, dir): moves person at position (x,y) of one cell in direction dir
     #   ('arrest', x, y, dir): arrests the villager in direction dir with knight at position (x, y)
     #   ('kill', x, y, dir): kills the assassin/knight in direction dir with knight/assassin at position (x, y)
     #   ('attack', x, y, dir): attacks the king in direction dir with assassin at position (x, y)
     #   ('reveal', x, y): reveals villager at position (x,y) as an assassin
     state = state._state['visible']
     ass_list = IA.random_assassins(POPULATION)
     if state['card'] is None:
         return json.dumps({'assassins': ass_list }, separators=(',', ':'))
     else:
         #Fais tes actions
         if self._playernb == 0: #Actions Assassin
             return json.dumps({'actions': IA.AssassinAI(state, ass_list)}, separators=(',', ':'))
         else: #Actions Roi
             return json.dumps({'actions': IA.KingAI(state)}, separators=(',', ':'))
Exemplo n.º 21
0
def gestionTour(partie, isIAPresente):
    """
    Va cherche la direction auprès du joueur (en demandant aux humains et en appelant
    choixDirectionIA pour l'IA). Puis modifie l'état de la partie.
    :param partie: (Game) Partie sur laquelle on travaille.
    :param isIAPresente: (bool) True s'il y a une IA dans la partie.
    :return: Rien.
    """

    # S'il y a une IA, et que c'est à elle de jouer, on appelle la choixDirectionIA.
    if isIAPresente and partie.joueurCourant == 1:
        print("{} refléchit...".format(partie.listeJoueurs[1].getNom()))
        direction = IA.choixDirectionIA(partie)
    else:
        direction = partie.demandeDirection()
        # On demande la direction tant que celle-ci n'est pas valide.
        while partie.isDirectionNonValide(direction):
            direction = partie.demandeDirection()

    # Une fois qu'on a la direction on modifie l'état.
    partie.modifieEtat(direction)

    return None
Exemplo n.º 22
0
 def __init__(self, host, port, step, serialized_ia):
     self.selected = False
     self.serialized_ia = serialized_ia
     self.step_by_step = step
     self.nextstep = True
     self.internal_error = False
     self.factory = Factory.Factory()
     self.ia = IA.IA(self, serialized_ia)
     self.host = host
     self.port = port
     self.sockets = {}
     self.sockets_input_buffer = {}
     self.sockets_output_buffer = {}
     self.tcp_request = {}
     self.udp_request = {}
     self.sockets["tcp"] = self.__connect("tcp", host, port)
     self.sockets["udp"] = self.__connect("udp", host, port)
     self.__process_send(_p895o_Q28)
     self.sockets_input_buffer["tcp"] = []
     self.sockets_input_buffer["udp"] = []
     self.sockets_output_buffer["tcp"] = []
     self.sockets_output_buffer["udp"] = []
     self.is_connected = False
     self.buff = ""
     self.tcp_request["map"] = Request.map
     self.tcp_request["start"] = Request.start
     self.tcp_request["player"] = Request.player
     self.tcp_request["all_player"] = Request.all_player
     self.tcp_request["tile"] = Request.tile
     self.tcp_request["die"] = Request.die
     self.tcp_request["alive"] = Request.alive
     self.tcp_request["start"] = Request.game_start
     self.tcp_request["stop"] = Request.game_stop
     self.tcp_request["move"] = Request.move
     self.tcp_request["connexion"] = Request.id_network
     self.tcp_request["id_player"] = Request.id_player
     self.tcp_request["nextstep"] = Request.nextstep
Exemplo n.º 23
0
    def launch(self, diff):
        print('Launching game ...')

        self.screen = pygame.display.set_mode(
            [self.screen_width, self.screen_height])
        pygame.display.set_caption("Road to Mordor")
        self.clock = pygame.time.Clock()

        self.joueur = joueur_classe.Joueur("Player 1", "humain", 1)
        self.joueurIA = joueur_classe.Joueur("Computer", "orc", 0)
        self.hud = HUD.UserInterface(self.screen, self.joueur, self.joueurIA)
        self.grille = grille_classe.Grille(
            16, 20, diff, self.screen.subsurface((205, 50, 1000, 800)),
            self.hud, self.joueurIA, self.joueur)
        self.IA = IA.IA(self.grille, self.joueurIA)
        self.ig_menu = ig_menu_classe.InGameMenu(self.screen)
        self.rules = regles_classe.Regles(self.screen)
        self.game_over = fin_jeu.Fin(self.screen)

        pygame.mixer.music.load('Musique/Musiquedefond.mp3')
        pygame.mixer.music.play(-1)

        turn = 0
        done = False
        show_regles = False
        show_gameOver = False
        # -------- Main Program Loop -----------
        keys_pressed = dict()
        pygame.event.Event(pygame.USEREVENT, {'key': 0, 'unicode': ''})
        while not done:
            turn += 1
            # --- Main event loop
            for event in pygame.event.get():
                #print('EVENT ', pygame.event.event_name(event.type))
                if event.type == pygame.QUIT:
                    print('Ending game ... and QUIT !')
                    return False
                elif event.type == pygame.KEYDOWN:
                    #keys_pressed[event.key] = {'key': event.key, 'unicode': event.unicode} # Create KEYPRESS events
                    if len(keys_pressed) > 0:
                        pygame.time.set_timer(pygame.USEREVENT, 150)
                    if self.paused:
                        if show_regles:
                            show_regles = False
                        else:
                            if event.key == pygame.K_RETURN:
                                res_m = self.ig_menu.getSelected()
                                if res_m == 0:
                                    pygame.mixer.music.unpause()
                                    self.paused = False
                                elif res_m == 1:
                                    show_regles = True
                                elif res_m == 2:
                                    self.paused = False
                                    print('Ending game ...')
                                    return True
                            elif event.key == pygame.K_ESCAPE:
                                self.paused = False
                                pygame.mixer.music.unpause()
                            elif event.key == pygame.K_LEFT:
                                self.ig_menu.selectPrev()
                            else:
                                self.ig_menu.switchSelected()
                    elif show_gameOver:
                        print('Ending game ...')
                        self.game_over.stop()
                        return True
                    else:
                        # Handle KEYDOWN
                        if event.unicode == 'd':
                            self.hud.selectNext()
                        elif event.unicode == 'q':  # Q sur un Azerty
                            self.hud.selectPrev()
                        elif event.unicode == 'a':  # A sur un Azerty
                            self.hud.switchMode()
                        elif event.unicode == '-':
                            print('- HEY !')
                        elif event.unicode == '.':
                            self.joueurIA.setVieChateau(0)
                        elif event.key == pygame.K_ESCAPE:
                            self.paused = True
                            pygame.mixer.music.pause()
                        elif event.key == pygame.K_UP:
                            self.grille.selectUp()
                        elif event.key == pygame.K_DOWN:
                            self.grille.selectDown()
                        elif event.key == pygame.K_LEFT:
                            self.grille.selectLeft()
                        elif event.key == pygame.K_RIGHT:
                            self.grille.selectRight()
                        elif event.key == pygame.K_RETURN:
                            if self.hud.canUse():
                                if self.hud.getMode() == 'towers':
                                    if self.grille.canBuild(
                                            self.grille.getSelected(),
                                            self.joueur.getEquipe()):
                                        tour = self.joueur.createBuild(
                                            self.hud.getSelected(),
                                            self.grille,
                                            self.grille.getSelected())
                                        if tour == False:
                                            self.hud.showMessage(
                                                "Argent insufisant ...", 70)
                                            print('Argent insufisant')
                                        else:
                                            self.grille.place(tour)
                                            self.hud.use()
                                    else:
                                        self.hud.showMessage(
                                            "Placement impossible !", 70)
                                        print('Placement impossible')
                                else:
                                    if self.grille.canSpawn(
                                            self.grille.getRoute(),
                                            self.joueur.getEquipe()):
                                        unit = self.joueur.createUnit(
                                            self.hud.getSelected(),
                                            self.grille,
                                            self.grille.getRoute())
                                        if unit == False:
                                            self.hud.showMessage(
                                                "Argent insufisant ...", 70)
                                            print('Argent insufisant')
                                        else:
                                            self.grille.place(unit)
                                            self.hud.use()
                                    else:
                                        self.hud.showMessage(
                                            "Placement impossible !", 70)
                                        print('Placement impossible')
                            else:
                                self.hud.showMessage("Cooldown en cours.", 70)
                                print('Cooldown en cours')
                """
				elif event.type == pygame.KEYUP:
					keys_pressed.pop(event.key) # Create KEYPRESS events
					if len(keys_pressed)<=0:
						pygame.time.set_timer(pygame.USEREVENT,0) # Remove timer
				elif event.type == pygame.USEREVENT:
					for key,item in keys_pressed.iteritems():
						if key == pygame.K_UP:
							self.grille.selectUp()
						elif key == pygame.K_DOWN:
							self.grille.selectDown()
						elif key == pygame.K_LEFT:
							self.grille.selectLeft()
						elif key == pygame.K_RIGHT:
							self.grille.selectRight()
				"""
            # --- Game logic should go here
            #pygame.display.update()
            self.screen.fill((75, 75, 75))
            if self.paused:
                if show_regles:
                    self.rules.draw()
                else:
                    self.ig_menu.draw()
            elif show_gameOver:
                self.game_over.draw()
            else:
                self.grille.draw()
                self.hud.draw()
                if turn % 300 == 0:
                    self.joueur.recevoirArgent(100)
                    self.joueurIA.recevoirArgent(100)
                if turn % 5 == 0:
                    self.IA.play()
                if turn % 10 == 0:
                    self.grille.play()
            # --- Check if the game is over
            if self.joueur.getVieChateau() == 0 and not show_gameOver:
                show_gameOver = True
                pygame.mixer.music.stop()
                self.game_over.start(False)
            elif self.joueurIA.getVieChateau() == 0 and not show_gameOver:
                show_gameOver = True
                pygame.mixer.music.stop()
                self.game_over.start(True)

            # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

            # --- Limit to 60 frames per second
            self.clock.tick(60)

        # Close the window and quit.

        print('Ending game ...')

        return True
Exemplo n.º 24
0
 def fin_juego(self):
     return IA.hay_linea_3(self)
Exemplo n.º 25
0
def main():
    """
	Programme principal...
	"""
    pygame.init()
    os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(
        50, 200)  #position la fenetre a un endroit precis pour l'ouverture
    ecran = pygame.display.set_mode(
        [setting["l_ecran"],
         int((setting["l_ecran"] * 448) / 1242)])  #cree l'ecran
    pygame.display.set_caption(
        setting["titre"])  #change le titre de la fenetre

    #---------------------------------------------- instanciation onjets ----------------------------------------------------------------------------------------

    interface = Interface.Interface(ecran)

    #-------------------------------------------------- boucle du jeu --------------------------------------------------------------------------------------------

    continuer = True
    menu_principal = True
    menu_choix_mode = False
    selecteur_perso = False
    init_player = False
    mode = False
    menu_pause = False
    menu_fin_partie = False

    while continuer:
        while menu_principal:
            for event in pygame.event.get():  #recupere les evenements
                if event.type == pygame.QUIT:
                    continuer = False
                    menu_principal = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_play.collidepoint(event.pos):
                                menu_principal = False
                                menu_choix_mode = True
                            elif interface.rect_quit.collidepoint(event.pos):
                                menu_principal = False
                                continuer = False
                        except Exception as e:
                            print(e)

            interface.menu_principal()
            pygame.display.flip()

        while menu_choix_mode:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    menu_choix_mode = False
                    continuer = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        menu_choix_mode = False
                        menu_principal = True

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_1v1.collidepoint(event.pos):
                                menu_choix_mode = False
                                selecteur_perso = True
                                mode = "1v1"
                            elif interface.rect_1vsIA.collidepoint(event.pos):
                                menu_choix_mode = False
                                selecteur_perso = True
                                mode = "1vsIA"
                        except Exception as e:
                            print(e)

            interface.menu_choix_mode()
            pygame.display.flip()

        while selecteur_perso:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    selecteur_perso = False
                    continuer = False
                    mode = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        selecteur_perso = False
                        menu_choix_mode = True
                        mode = False
                        interface = Interface.Interface(ecran)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_joueur1.collidepoint(event.pos):
                                interface.choix_actif = "joueur1"
                            elif interface.rect_joueur2.collidepoint(
                                    event.pos):
                                interface.choix_actif = "joueur2"
                            elif interface.rect_valider1.collidepoint(
                                    event.pos
                            ) and interface.choix_perso_joueur[0]:
                                interface.validation[0] = True
                                interface.choix_actif = "joueur2"
                            elif interface.rect_valider2.collidepoint(
                                    event.pos
                            ) and interface.choix_perso_joueur[1]:
                                interface.validation[1] = True
                                interface.choix_actif = "joueur1"
                            if interface.choix_actif:
                                for perso in interface.rect_logo.keys():
                                    if interface.rect_logo[perso].collidepoint(
                                            event.pos
                                    ) and interface.choix_actif == "joueur1":
                                        interface.choix_perso_joueur[0] = perso
                                        if interface.validation[0]:
                                            interface.validation[0] = False
                                    elif interface.rect_logo[perso].collidepoint(
                                            event.pos
                                    ) and interface.choix_actif == "joueur2":
                                        interface.choix_perso_joueur[1] = perso
                                        if interface.validation[1]:
                                            interface.validation[1] = False
                        except Exception as e:
                            pass
                        try:
                            if interface.validation_finale.collidepoint(
                                    event.pos):
                                selecteur_perso = False
                                init_player = True
                        except:
                            pass

            interface.selecteur_perso()
            interface.bouton_selecteur()
            interface.perso_selected()
            interface.bouton_validation()
            interface.check_validation()

            if not interface.init_ia and mode == "1vsIA":
                interface.choix_perso_IA()
                interface.init_ia = True
            pygame.display.flip()

        if init_player:
            if mode == "1v1":
                joueur1 = Player.Player(ecran, interface.choix_perso_joueur[0],
                                        1, setting["speed"], (0, 0, 255))
                joueur2 = Player.Player(ecran, interface.choix_perso_joueur[1],
                                        2, setting["speed"], (255, 0, 0))
                init_player = False
            elif mode == "1vsIA":
                joueur1 = Player.Player(ecran, interface.choix_perso_joueur[0],
                                        1, setting["speed"], (0, 0, 255))
                joueur2 = IA.IA(ecran, interface.choix_perso_joueur[1], 2,
                                setting["speed"], (255, 0, 0))
            interface = Interface.Interface(ecran)
            interface.transition((255, 255, 255))
            init_player = False
            interface.timer_debut_partie(joueur1, joueur2)
            pygame.event.clear()

        while mode:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    continuer = False
                    mode = False

                elif event.type == pygame.KEYDOWN:
                    if event.key in [
                            setting["touche_joueur1"]["pause"],
                            setting["touche_joueur2"]["pause"]
                    ]:
                        menu_pause = True
                        mode = False

                joueur1.input_player(event)
                joueur2.input_player(event)

            joueur1.recup_action_active()
            joueur2.recup_action_active()

            joueur1.update_hit_box(joueur2)
            joueur2.update_hit_box(joueur1)
            joueur1.gerer_degat(joueur2)
            joueur2.gerer_degat(joueur1)
            joueur1.reset_combo()
            joueur2.reset_combo()

            #joueur1.afficher()
            #joueur2.afficher()

            interface.draw_bg()
            interface.barre_de_vie(joueur1, joueur2)
            joueur1.draw()
            joueur2.draw()
            interface.afficher_combo(joueur1, 50, 75)
            interface.afficher_combo(joueur2, 900, 75)
            quitter = interface.temps()
            pygame.display.flip()
            pygame.time.Clock().tick(setting["fps"])

            if joueur1.vie <= 0 or joueur2.vie <= 0 or quitter:
                menu_fin_partie = True
                mode = False
                interface.afficher_fin_de_partie(joueur1, joueur2)
                if joueur1.vie > joueur2.vie:
                    interface.transition(joueur1.couleur)
                else:
                    interface.transition(joueur2.couleur)

        while menu_pause:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    continuer = False
                    menu_pause = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if interface.rect_continuer.collidepoint(event.pos):
                            mode = True
                            menu_pause = False

                        elif interface.rect_quitter.collidepoint(event.pos):
                            menu_pause = False
                            menu_principal = True

            interface.menu_pause()
            pygame.display.flip()

        while menu_fin_partie:
            for event in pygame.event.get():  #recupere les evenements
                if event.type == pygame.QUIT:
                    menu_fin_partie = False
                    continuer = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        menu_fin_partie = False
                        menu_principal = True
                        interface.transition((0, 0, 0))

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_menu.collidepoint(event.pos):
                                menu_choix_mode = True
                                menu_fin_partie = False
                                interface.transition((255, 255, 255))

                            elif interface.rect_quit.collidepoint(event.pos):
                                menu_fin_partie = False
                                continuer = False
                        except Exception as e:
                            print(e)

            interface.fin_de_partie(joueur1, joueur2)
            pygame.display.flip()
Exemplo n.º 26
0
	def __init__(self):
		self.tabule = tabule.Tabuleiro() # Tabuleiro
		self.ia = ia.IA(self.tabule) # IA para executar o MiniMax
		self.iniciarJogo()
Exemplo n.º 27
0
class Window(QMainWindow):
    def __init__(self):
        """
            Constructeur de la class
        """
        super().__init__()
        self.highscoreF = Highscores(self)  #Initialise le Hightscore
        self.mode = ""
        self.initUI()

    def initUI(self):
        """
            Initialise la fenêtre de jeu avec la taille initial, le titre et les differentes implémentation dans la fenêtre
        """

        #Met en place la musique de fond
        self.playerMusic = QMediaPlayer(self)
        content = QMediaContent(
            QUrl.fromLocalFile("sound/ambiantSoundKevinMacLeod.wav"))
        #On met la musique de fond en boucle
        playlist = QMediaPlaylist(self)
        playlist.setPlaybackMode(QMediaPlaylist.Loop)
        playlist.addMedia(content)

        self.playerMusic.setPlaylist(playlist)
        self.playerMusic.setVolume(100)
        self.playerMusic.play()

        self.setGeometry(10, 10, 580, 580)
        self.setFixedSize(580, 580)
        p = self.palette()
        p.setBrush(QPalette.Window, QBrush(QImage("draw/background.png")))
        self.setPalette(p)
        self.setWindowTitle('2048')
        self.statusBar().showMessage("")
        self.setMenuBar()
        self.setCenter()
        self.home(None)
        self.show()

    def keyPressEvent(self, event):
        """
            Initialise la fonction
            :param event: événement touche du clavier appuyée
            :type event: QKeyEvent
        """
        pass

    def home(self, event):
        """
            Mise en place du menu avec les differents boutons
            :param event: événement
            :type event: event
        """
        #Initialise l'écran du menu principal avec le logo
        ecran = RenderAreaHome()
        self.canPlay = False  #Interdit l'utilisateur de jouer tant qu'il est dans le menu
        #On reset tout si l'utilisateur était en train de jouer
        if self.mode == "tetris":
            self.game.timer.stop()
            self.mode = ""
        else:
            self.mode = ""
        self.iaRunning = False
        self.statusBar().showMessage("")

        #Si la variable game existe et le type de la varible est Game alors on sauvegarde la partie en cours
        if (hasattr(self, 'game') and type(self.game) is Game):
            self.game.sauvegarder()

        playGif = ButtonHome("home/jouer.gif",
                             self.width() / 2,
                             self.width() / 3,
                             ecran)  #Creation du bouton "Jouer"
        playGif.mouseReleaseEvent = self.subHomePlay  #On ajoute une action au bouton "Jouer"

        loadGif = ButtonHome("home/charger.gif",
                             self.width() / 2,
                             self.width() / 3 + (80 * 1), ecran)
        loadGif.mouseReleaseEvent = self.loadGame

        highscoreGif = ButtonHome("home/highscore.gif",
                                  self.width() / 2,
                                  self.width() / 3 + (80 * 2), ecran)
        highscoreGif.mouseReleaseEvent = self.highscores

        quitGif = ButtonHome("home/quitter.gif",
                             self.width() / 2,
                             self.width() / 3 + (80 * 3), ecran)
        quitGif.mouseReleaseEvent = self.quit

        self.setCentralWidget(ecran)

    def subHomePlay(self, event):
        """
            Mise en place du menu avec les differents boutons
            :param event: événement
            :type event: event
        """
        ecran = RenderAreaHome()

        classiqueGif = ButtonHome("home/classique.gif",
                                  self.width() / 2,
                                  self.width() / 3,
                                  ecran)  #Creation du bouton "Jouer"
        classiqueGif.mouseReleaseEvent = self.newGame  #On ajoute une action au bouton "Jouer"

        miroirGif = ButtonHome("home/miroir.gif",
                               self.width() / 2,
                               self.width() / 3 + (70 * 1), ecran)
        miroirGif.mouseReleaseEvent = self.miroir

        popGif = ButtonHome("home/vsPop.gif",
                            self.width() / 2,
                            self.width() / 3 + (70 * 2), ecran)
        popGif.mouseReleaseEvent = self.setVsIa

        tetrisGif = ButtonHome("home/tetris.gif",
                               self.width() / 2,
                               self.width() / 3 + (70 * 3), ecran)
        tetrisGif.mouseReleaseEvent = self.tetris

        backGif = ButtonHome("home/retour.gif",
                             self.width() / 2,
                             self.width() / 3 + (70 * 4), ecran)
        backGif.mouseReleaseEvent = self.home

        self.setCentralWidget(ecran)

    def setMenuBar(self):
        """
            Crée la bar de menu avec les differents onglets et les actions de chaque
        """
        mainMenu = self.menuBar()
        systemeMenu = mainMenu.addMenu('Système')
        jeuMenu = mainMenu.addMenu('Jeu')
        helpMenu = mainMenu.addMenu('Aide')

        newAction = QAction("&Nouvelle partie",
                            self,
                            icon=QIcon("icon/new_game.png"),
                            shortcut="Ctrl+N",
                            statusTip="Commencer une nouvelle partie",
                            triggered=self.newGame)
        systemeMenu.addAction(newAction)

        highscoreAction = QAction("&Highscores",
                                  self,
                                  icon=QIcon("icon/leaderboard.png"),
                                  shortcut="Ctrl+H",
                                  statusTip="Voir les meilleurs scores !",
                                  triggered=self.highscores)
        systemeMenu.addAction(highscoreAction)

        backHome = QAction("&Menu principal",
                           self,
                           icon=QIcon("icon/home.png"),
                           shortcut="Ctrl+M",
                           statusTip="Retour au menu principal",
                           triggered=self.home)
        systemeMenu.addAction(backHome)

        exitAction = QAction("&Quitter",
                             self,
                             icon=QIcon('icon/exit.svg'),
                             shortcut="Ctrl+Q",
                             statusTip="Quitter l'application",
                             triggered=self.quit)
        systemeMenu.addAction(exitAction)

        aboutAction = QAction("&A propos de",
                              self,
                              icon=QIcon('icon/about.png'),
                              shortcut="Ctrl+?",
                              statusTip="A propos de",
                              triggered=self.about)
        helpMenu.addAction(aboutAction)

        resetAction = QAction("&Retour en arrière",
                              self,
                              icon=QIcon('icon/reset.png'),
                              shortcut="Ctrl+R",
                              statusTip="Dernier coup joué",
                              triggered=self.resetButton)
        jeuMenu.addAction(resetAction)

        sonAction = QAction("&Son",
                            self,
                            icon=QIcon('icon/sound.png'),
                            shortcut="Ctrl+S",
                            statusTip="Ajuster le son",
                            triggered=lambda: Son(self, self.playerMusic))
        jeuMenu.addAction(sonAction)

    def closeEvent(self, event):
        """
            Evenement si l'utilisateur ferme la fenêtre principale
            :param event: événement
            :type event: event
        """
        #Si la variable game existe et le type de la varible est Game alors on sauvegarde la partie en cours
        if (hasattr(self, 'game') and type(self.game) is Game):
            self.game.sauvegarder()

    def setCenter(self):
        """
            Centre la fenêtre de jeu
        """
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def newGame(self, event):
        """
            Crée une varibale de la class Game pour initiliser le 2048 et met en place l'affichage
        """
        #On vide le fichier save.txt
        reset = open("save.txt", 'w')
        reset.write("")
        reset.close()
        if (self.mode != "tetris"):
            self.iaRunning = False
            self.game = Game(self, self.mode)
            self.setRenderArea()
        else:
            #Si la variable game existe et le type de la varible est diffèrent de Game alors on reset la partie sinon on crée une variable game avec comme type GameTetris
            if (hasattr(self, 'game') and type(self.game) is not Game):
                self.game.resetGame()
            else:
                self.game = GameTetris(self)
            self.setRenderArea()

    def loadGame(self, event):
        """
            Permet de charger la dernière partie sauvegardée pour initialiser le 2048 et conserver le score et les combos
        """
        #Si le fichier save.txt est vide on lance une nouvelle
        if (os.path.getsize("save.txt") == 0):
            mess = QMessageBox(self)
            mess.setText(
                "Aucune sauvegarde n'a été trouvé. Lancement d'une nouvelle partie !"
            )
            mess.setWindowTitle("Erreur")
            mess.setIcon(QMessageBox.Information)
            mess.setStandardButtons(QMessageBox.Ok)
            mess.exec_()
        save = open("save.txt", 'r')
        cpt = 0
        for i in save:
            if (cpt == 8):
                self.mode = i
            cpt += 1
        if (self.mode != "tetris"):
            self.game = Game(self, self.mode)
            self.setRenderArea()
            if (self.mode == "vsIa"):
                self.vsIa = IA(self.game.liste)
        else:
            self.game = GameTetris(self)
            self.setRenderArea()
        #On met à jour l'interface graphique avec les infos du fichier
        self.renderAreaGame.score = self.game.score
        self.renderAreaGame.liste = self.game.liste
        self.renderAreaGame.combo = self.game.combo
        self.renderAreaGame.comboSteps = self.game.comboSteps
        self.renderAreaGame.repaint()

    def about(self):
        """
            Fait apparaitre une fenêtre pour les differentes information du logiciel
        """
        dialog = QMessageBox(self)
        dialog.setText(
            "Cette application a été créée par Justin MOTTIER, Sacha FOLCKE, Pierre COSSART et Romain DUBUC, étudiants en DUT1 Informatique, groupe B-1, IUT DE LENS. \nMusique de fond : Clean Soul - Kevin MacLeod\nLangage : Python 3 et PyQt5"
        )
        dialog.setWindowTitle("A propos de")
        dialog.setIcon(QMessageBox.Information)
        dialog.setStandardButtons(QMessageBox.Ok)
        dialog.exec_()

    def quit(self, event):
        """
            Fait apparaitre une fenêtre pour savoir si l'utilisateur veut quitter le logiciel
        """
        dialog = QMessageBox(self)
        dialog.setText("Souhaitez-vous quitter l'application ?")
        dialog.setWindowTitle("Quitter")
        dialog.setIcon(QMessageBox.Question)
        button_yes = dialog.addButton("Oui", QMessageBox.YesRole)
        dialog.addButton("Non", QMessageBox.NoRole)
        dialog.setDefaultButton(button_yes)
        dialog.exec_()
        if (button_yes == dialog.clickedButton()):
            #Si la variable game existe et que son type est Game alors tu sauvegarde la partie en cours
            if (hasattr(self, 'game') and type(self.game) is Game):
                self.game.sauvegarder()
            QCoreApplication.instance().quit()

    def setRenderArea(self):
        """
            Initialise l'affichage du jeu
        """
        self.renderAreaGame = RenderAreaGame(self)
        self.canPlay = True
        self.setCentralWidget(self.renderAreaGame)

    def resetButton(self, event):
        """
            Reset du coup joué et changement de l'état du bouton
        """
        if (self.canPlay and self.mode !=
                "tetris"):  #Verifie si l'utilisateur n'est plus dans le menu
            self.game.backupMove()
            self.checkButtonState()

    def highscores(self, event):
        """
            Ouvre la fenêtre des meilleurs scores
        """
        self.highscoreF = Highscores(self)
        self.highscoreF.show()

    def setIA(self, event):
        """
            Active l'IA
            :param event: événement
            :type event: event
        """
        if (self.canPlay):  #Verifie si l'utilisateur n'est plus dans le menu
            #Initialise l'IA
            self.ia = IA(self.game.liste)
            #Tant que le bot n'a pas perdu ou gagné et qu'il est toujours activé
            while not (self.game.isWin()
                       or self.game.isLose()) and self.iaRunning:
                QCoreApplication.processEvents()
                self.ia.liste = self.game.liste
                moves = self.ia.play()
                if (self.game.move(moves[0])):
                    self.game.spawnRandom()
                if (self.game.move(moves[1])):
                    self.game.spawnRandom()
                if (self.game.move(moves[2])):
                    self.game.spawnRandom()

    def setVsIa(self, event):
        """
            Crée une game en mode contre l'IA
            :param event: événement
            :type event: event
        """
        self.mode = "vsIa"
        self.newGame(None)
        self.vsIa = IA(self.game.liste)

    def miroir(self, event):
        """
            Crée une game en mode miroir
            :param event: événement
            :type event: event
        """
        self.mode = "miroir"
        self.newGame(None)

    def tetris(self, event):
        """
            Crée une game en mode tetris
            :param event: événement
            :type event: event
        """
        self.mode = "tetris"
        self.newGame(None)
Exemplo n.º 28
0
 def _nextmove(self, state):
     input()
     state = state._state['visible']
     if state['card'] is None:
         self.MyKillers=IA.choicekillers(state)
         return json.dumps({'assassins': self.MyKillers}, separators=(',', ':'))
     else:
         if self._playernb == 0:
                     #   ----------------------
                     #         ASSASSINS
                     #   ----------------------
             MyVillagers,king=IA.findtroops(state,POPULATION)
             paV=state['card'][3]
             MyActions=[]
             #   Time to reveal and kill the KING ?
             hitmen,king=IA.findtroops(state,self.MyKillers)
             maybekiller=IA.able2kill(hitmen,paV,king,MyActions)
             if len(maybekiller)>0:
                 actions,Cost=IA.time2kill(maybekiller,king,state,paV)
                 if actions!=-1:
                     for action in actions:
                         MyActions.append(action)
                     paV+=-Cost
             #   déplacement aléatoire des villageois
             state,MyActions=IA.randommove(MyVillagers,paV,king,state,MyActions,{None},50)
             
             return json.dumps({'actions': MyActions}, separators=(',', ':'))
             
         
         else:
                     #   ----------------------
                     #            KING
                     #   ----------------------
             MyArmies,king=IA.findtroops(state,{'knight'})
             paC=state['card'][1]
             MyActions=[]
             #   déplacement aléatoire des chevaliers
             state,MyActions=IA.randommove(MyArmies,paC,['coinHG',1,1,'R'],state,MyActions,{None},50)
             money=state['card'][0]
             #   déplacement aléatoire du roi
             it=0
             while money>0 and it<5:
                 guy=king                    
                 if guy[2]>1 and state['people'][guy[1]][guy[2]-1] ==None and state['board'][guy[1]][guy[2]-1]=='G':
                     MyActions.append(('move',guy[1],guy[2],'W'))
                     guy[2]+=-1
                     money+=-1
                 elif guy[1]>1 and state['people'][guy[1]-1][guy[2]]==None and state['board'][guy[1]-1][guy[2]]=='G':
                     MyActions.append(('move',guy[1],guy[2],'N'))
                     guy[1]+=-1
                     money+=-1
                 elif guy[1]<1 and state['people'][guy[1]+1][guy[2]]==None and state['board'][guy[1]+1][guy[2]]=='G':
                     MyActions.append(('move',guy[1],guy[2],'S'))
                     guy[1]+=1
                     money+=-1
                 elif guy[2]<1 and state['people'][guy[1]][guy[2]+1]==None and state['board'][guy[1]][guy[2]+1]=='G':
                     MyActions.append(('move',guy[1],guy[2],'E'))
                     guy[2]+=1
                     money+=-1
                 it+=1
             return json.dumps({'actions': MyActions}, separators=(',', ':'))
Exemplo n.º 29
0
    def envoyer(self, chaine):
        """Envoie sur le socket la chaîne de caractères passée en paramètre."""
        self.connexion_serveur.send(bytes(chaine + '\n', 'utf_8'))

    def tout_fermer(self):
        """Ferme le socket."""
        self.connexion_serveur.close()


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print('Usage : ' + sys.argv[0] + ' <adresse> <port> <nom_équipe>')
        sys.exit(1)

    mon_client = Client(sys.argv[1], int(sys.argv[2]), sys.argv[3])
    mon_IA = IA()

    # Première réponse du serveur, notre numéro d'équipe
    reponse_1 = mon_client.recevoir()
    print('Réponse du serveur : ' + reponse_1)

    mon_IA.num_equipe = int(reponse_1)

    # Deuxième réponse, cette fois avec le terrain et toutes les infos
    reponse_1 = mon_client.recevoir()
    print('Réponse du serveur : ' + reponse_1)

    # On peut donc créer le terrain
    mon_IA.set_taille(reponse_1)
    mon_IA.creer_terrain(reponse_1)
    mon_IA.set_position(reponse_1)
Exemplo n.º 30
0
import numpy as np
import IA
from keras.datasets import mnist

(feed, lambels), (feed_test, lambels_test) = mnist.load_data()

print("Treinando {} images com {}/{} de tamanho".format(
    feed.shape[0], feed.shape[1], feed.shape[2]))

size = feed.shape[1] * feed.shape[2]

neural_network = IA.Perceptron(
    (size, int(size / 2), int(size / 3), int(size / 6), 1))
feed = feed.reshape(feed.shape[0], size)

neural_network.train(feed, lambels)

print("Terminado")
Exemplo n.º 31
0
class jeu:
    IA1 = IA.IA(0)  # Nous dirons quelle stratégie va utiliser chaque IA
    IA2 = IA.IA(
        0)  # Par exemple si IA1 = 1 on utilisera la stratégie agressive etc.
    nb_cases = 0  # nombre de case dans le jeu
    nb_pierres = 0  # nombre de pierre
    grille = []  # grille
    chateau1 = chateau.chateau(0, "Chateau 1")  # chateau1
    chateau2 = chateau.chateau(0, "Chateau 2")  # chateau 2
    troll = troll.troll(0)  # troll

    # def __init__(self, cases, pierres):         #constructeur
    # Grille et initialisation de la grille
    # _________________________________________________________________________________________________________________________

    def reinitialise_pierre(self):  #Reinitialise le nb de pierre envoyer a 0
        self.chateau1.nb_pierre_envoyee = 0
        self.chateau2.nb_pierre_envoyee = 0

    def init(self, cases, pierres):
        self.nb_cases = cases
        self.nb_pierres = pierres
        self.init_grille()
        self.troll.emplacement = self.place_troll() - 1  # tableau commence à 0
        self.chateau1.pierre = self.nb_pierres
        self.chateau2.pierre = self.nb_pierres
        print(self.affiche_grille())
        print("Init fini")
        # print("TROLL : ",self.grille.index("troll"))
        # print("Chateau 2",self.grille.index("Chateau 2"))
        # difference=self.grille.index("Chateau 2")-self.grille.index("troll")
        # print(difference)
    def initIA(self):
        print("Stratégie IA 1 ? Choisissez une des stratégie suivantes : ")
        print("a. Aggresive")
        print("b. Prudente ")
        print("c. Aléatoire ")
        print("d. Contre-Attaque ")
        nb = input("Votre choix ?")
        while nb != 'a' and nb != 'b' and nb != 'c' and nb != 'd':
            nb = input("Votre choix ?")
        if nb == 'a':
            self.IA1.strategie = 1
        elif nb == 'b':
            self.IA1.strategie = 2
        elif nb == 'c':
            self.IA1.strategie = 3
        elif nb == 'd':
            self.IA1.strategie = 4
        print("Stratégie IA 2 ? Choisissez une des stratégie suivantes : ")
        print("a. Aggresive")
        print("b. Prudente ")
        print("c. Aléatoire ")
        print("d. Contre-Attaque ")
        nb = input("Votre choix ?")
        while nb != 'a' and nb != 'b' and nb != 'c' and nb != 'd':
            nb = input("Votre choix ?")
        if nb == 'a':
            self.IA2.strategie = 1
        elif nb == 'b':
            self.IA2.strategie = 2
        elif nb == 'c':
            self.IA2.strategie = 3
        elif nb == 'd':
            self.IA2.strategie = 4

            # def init_grille(self,grille):                       #on initialise la grille avec le chateau troll et des 0 quand c'est vide

    #     i=1
    #     i=self.init_grille1(i,grille)
    #     i=self.init_troll(i,grille)
    #     self.init_grille2(i,grille)
    #
    #
    # def init_grille1(self,i, grille):                   #La première partie de la grille jusqu'au troll
    #     grille.append("Chateau 1")
    #     i=i+1
    #     while i < self.place_troll():
    #         grille.append(0)
    #         i = i+1
    #     return i
    #
    # def init_grille2(self,i,grille):                    #Du troll jusqu'a la fin de la grille
    #     while i < self.nb_cases:
    #         grille.append(0)
    #         i = i+1
    #     grille.append("Chateau 2")

    def init_grille(
        self
    ):  # on initialise la grille avec le chateau troll et des 0 quand c'est vide
        print("Rentrer")
        self.grille.append("Chateau 1")
        i = 2
        while i < self.nb_cases:
            if i == self.place_troll():
                self.grille.append("troll")
                i = i + 1
            else:
                self.grille.append(0)
                i = i + 1
        self.grille.append("Chateau 2")

        # def init_troll(self,i,grille):                      #Positionnement du troll

    #     grille.append("troll")
    #     i = i+1
    #     return i

    def affiche_grille(self):  # Affichage de la grille
        print(self.grille)

    def place_troll(self):
        return int((self.nb_cases / 2) +
                   0.5)  # L'indice ou est posé le troll au début

    # Le jeu
    # _______________________________________________________________________________________________________________________

    def compare_pierre(self):
        if self.chateau1.nb_pierre_envoyee < self.chateau2.nb_pierre_envoyee:
            return 1
        elif self.chateau1.nb_pierre_envoyee > self.chateau2.nb_pierre_envoyee:
            return 2
        else:
            return 3

    def lancer_pierre(self):  # La fonction pour le lancer de pierre
        print("| Attaque du Chateau 1 |")
        print("Nombre de pierres restantes : ", self.chateau1.pierre)
        self.chateau1.nb_pierre_envoyee = int(
            input(" Nombre de pierre à envoyer ?")
        )  # Si on entre plus de pierres qu'on en a on refait
        while self.chateau1.nb_pierre_envoyee > self.chateau1.pierre or self.chateau1.nb_pierre_envoyee < 1:
            self.chateau1.nb_pierre_envoyee = int(
                input(" Nombre de pierre à envoyer ?"))
        self.chateau1.pierre = self.chateau1.pierre - self.chateau1.nb_pierre_envoyee
        #cls()
        print("| Attaque du Chateau 2 |")
        print("Nombre de pierres restantes : ", self.chateau2.pierre)
        self.chateau2.nb_pierre_envoyee = int(
            input(" Nombre de pierre à envoyer ?")
        )  # Si on entre plus de pierres qu'on en a on refait
        while self.chateau2.nb_pierre_envoyee > self.chateau2.pierre or self.chateau2.nb_pierre_envoyee < 1:
            self.chateau2.nb_pierre_envoyee = int(
                input(" Nombre de pierre à envoyer ?"))
        self.chateau2.pierre = self.chateau2.pierre - self.chateau2.nb_pierre_envoyee

    # cls()

    def lancer_pierre_ia(self):
        print("| Attaque du Chateau 1 |")
        print("Nombre de pierres restantes : ", self.chateau1.pierre)
        self.chateau1.nb_pierre_envoyee = self.IA1.choixStrategie(
            self,
            self.chateau1)  # Si on entre plus de pierres qu'on en a on refait

        print("| Attaque du Chateau 2 |")
        print("Nombre de pierres restantes : ", self.chateau2.pierre)
        self.chateau2.nb_pierre_envoyee = self.IA2.choixStrategie(
            self,
            self.chateau2)  # Si on entre plus de pierres qu'on en a on refait
        self.chateau1.pierre = self.chateau1.pierre - self.chateau1.nb_pierre_envoyee
        self.chateau2.pierre = self.chateau2.pierre - self.chateau2.nb_pierre_envoyee

    def deplace_troll(
            self):  # La fonction de déplacement du troll sur la grille

        if self.compare_pierre(
        ) == 3:  # Si les 2 balancent le même nombre de pierre..
            self.reinitialise_pierre()
            self.affiche_grille()
            print("3 vOILA")

        elif self.compare_pierre() == 1:
            self.grille[
                self.troll.emplacement] = 0  # On met un 0 la ou était le troll
            self.troll.emplacement = self.troll.emplacement - 1  # On change l'emplacement du troll
            self.grille[
                self.troll.
                emplacement] = "troll"  # On met au nouvel emplacement sur la grille le troll
            self.reinitialise_pierre()
            self.affiche_grille()
            print("1 vOILA")

        elif self.compare_pierre() == 2:  # Pareil mais dans l'autre sens
            self.grille[self.troll.emplacement] = 0
            self.troll.emplacement = self.troll.emplacement + 1
            self.grille[self.troll.emplacement] = "troll"
            self.reinitialise_pierre()
            self.affiche_grille()
            print("2 vOILA")

    def testnb_pierre(
            self):  # Le test pour le nombre de pierres de chaque chateau
        if self.chateau1.pierre == 0 and self.chateau2.pierre != 0:
            self.jetpierre1par1(self.chateau2)
        if self.chateau2.pierre == 0 and self.chateau1.pierre != 0:
            self.jetpierre1par1(self.chateau1)
        return 0

    def jetpierre1par1(
        self, chateau
    ):  # Si l'un des chateaux tombe à court de pierre on les envoie 1 par 1
        while chateau.pierre != 0 and self.victoire2() != 1:
            chateau.nb_pierre_envoyee = 1
            chateau.pierre = chateau.pierre - 1
            print("Nombre de PIERRE ENVOYER : ", chateau.nb_pierre_envoyee)
            self.deplace_troll()
        #  print(self.grille)

    def plusdepierres(self):
        if self.troll.emplacement + 1 < self.place_troll():
            print("Victoire chateau 2")
            return 2
        if self.troll.emplacement + 1 > self.place_troll():
            print("Victoire chateau 1")
            return 1
        if self.troll.emplacement + 1 == self.place_troll():
            print("Match Nul")
            return 0

    def victoire2(self):  # Les conditions de victoire pour le jet 1 par 1
        if self.grille[
                0] == "troll":  # Solution la plus simple pour ne pas afficher 2 fois
            return 1
        if self.grille[-1] == "troll":
            return 1
        if self.chateau1.pierre == 0 and self.chateau2.pierre == 0:  # Si les 2 n'ont plus de pierre
            return 1

    def victoire(self):  # Les conditions de victoire
        if self.grille[0] == "troll":
            print("Victoire chateau 2")
            return 2
        elif self.grille[-1] == "troll":  # Le premier à partir de la fin
            print("Victoire chateau 1")
            return 1
        elif self.chateau1.pierre == 0 and self.chateau2.pierre == 0:  # Si les 2 n'ont plus de pierre
            return self.plusdepierres()
        else:
            return -1
            #return 1

    # Le Menu
    # _________________________________________________________________________________________________________________________
    def menu(self):
        print("Choisissez votre mode de Jeu:")
        print("1.Mode 1 vs 1")
        print("2.Mode IA")
        print("3.Test IA x100")
        print("4.Quitter")

        nb = int(input("Votre choix ?"))
        while nb != 1 and nb != 2 and nb != 3 and nb != 4:
            nb = int(input("Votre choix ?"))
        return nb

    def menuConfig(self):
        self.nb_cases = self.menuCases()
        self.nb_pierres = self.menuPierres()

    def menuCases(self):
        print("1. Nombre de cases ?")
        print("a.7 cases")
        print("b.15 cases")
        nb = input("Votre choix ?")
        while nb != 'a' and nb != 'b':
            nb = input("Votre choix ?")
        if nb == 'a':
            nb = 7
        else:
            nb = 15
        return nb

    def menuPierres(self):
        print("1.Nombre de pierres ?")
        print("a.15 pierres")
        print("b.30 pierres")
        nb = input("Votre choix ?")
        while nb != 'a' and nb != 'b':
            nb = input("Votre choix ?")
        if nb == 'a':
            nb = 15
        else:
            nb = 30
        return nb

    def jeu(self):

        nb = self.menu()
        print(self.grille)
        if nb == 1:
            self.menuConfig()
            cls()
            self.jeuHumain()
        elif nb == 2:
            self.menuConfig()
            cls()
            self.jeuIA()
        elif nb == 3:  #IA 100 fois
            self.menuConfig()
            cls()
            self.jeuIA100()
        else:
            sys.exit(0)

    #Fonction Globales de jeu IA humain et 100x IA_______________________________________________

    def jeuHumain(self):  # La fonction de jeu
        self.init(self.nb_cases, self.nb_pierres)
        while (self.victoire() == -1):
            self.lancer_pierre()
            self.deplace_troll()
            print("JEU")
            self.testnb_pierre()
        return self.victoire()

    def jeuIA(self):
        self.init(self.nb_cases, self.nb_pierres)
        print("Pierre IA1 :", self.IA1.choixStrategie(self, self.chateau1))
        print("Pierre IA2 :", self.IA2.choixStrategie(self, self.chateau2))
        self.initIA()
        while (self.victoire() == -1):
            self.lancer_pierre_ia()
            self.deplace_troll()
            self.testnb_pierre()

    # self.IA1.StrategiePrudente(self) Idée pour strategie prudente

    def jeuIA100(self):
        i = 0
        victoiresJ1 = 0
        victoiresJ2 = 0
        MatchsNuls = 0
        print("Pierre IA1 :", self.IA1.choixStrategie(self, self.chateau1))
        print("Pierre IA2 :", self.IA2.choixStrategie(self, self.chateau2))
        self.initIA()
        while i < 100:  #Changer victoire 1 et victoire 2
            self.grille = []
            self.init(self.nb_cases, self.nb_pierres)
            while (self.victoire() == -1):
                self.lancer_pierre_ia()
                self.deplace_troll()
                self.testnb_pierre()
            resultat = self.victoire()
            if resultat == 1:
                victoiresJ1 = victoiresJ1 + 1
            elif resultat == 2:
                victoiresJ2 = victoiresJ2 + 1
            elif resultat == 0:
                MatchsNuls = MatchsNuls + 1
            i = i + 1
        cls()
        print("Victoires J1", victoiresJ1)
        print("Victoires J2", victoiresJ2)
        print("Match Nuls", MatchsNuls)

        return 0
Exemplo n.º 32
0
 def aiPick(self):
     ia.pick(self)
     pass
Exemplo n.º 33
0
def main():
    pygame.init()
    os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(
        50, 200)  #position la fenetre a un endroit precis pour l'ouverture
    ecran = pygame.display.set_mode(
        [setting["l_ecran"],
         int((setting["l_ecran"] * 448) / 1242)])  #cree l'ecran
    pygame.display.set_caption(
        setting["titre"])  #change le titre de la fenetre

    #---------------------------------------------- instanciation onjets ----------------------------------------------------------------------------------------

    interface = Interface.Interface(ecran)
    replay = Replay.Replay()
    pygame.mixer.music.set_volume(son.son["volume"]["volume"])

    #-------------------------------------------------- boucle du jeu --------------------------------------------------------------------------------------------

    continuer = True
    menu_principal = True
    menu_choix_mode = False
    selecteur_perso = False
    choix_map = False
    init_player = False
    init_timer_debut = False
    mode = False
    menu_replay = False
    choix_replay = False
    menu_pause = False
    menu_fin_partie = False
    tutoriel = False
    entrainement = False

    while continuer:
        if menu_principal or menu_choix_mode:
            pygame.mixer.music.load(son.son["background"]["opening_theme"])
            pygame.mixer.music.play(-1)
        while menu_principal:
            for event in pygame.event.get():  #recupere les evenements
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_play.collidepoint(event.pos):
                                menu_principal = False
                                menu_choix_mode = True
                            elif interface.rect_quit.collidepoint(event.pos):
                                menu_principal = False
                                continuer = False
                        except Exception as e:
                            print(e)

            interface.menu_principal()
            pygame.display.flip()

        while menu_choix_mode:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        menu_choix_mode = False
                        menu_principal = True

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_1v1.collidepoint(event.pos):
                                menu_choix_mode = False
                                selecteur_perso = True
                                mode = "1v1"
                            elif interface.rect_1vsIA.collidepoint(event.pos):
                                menu_choix_mode = False
                                selecteur_perso = True
                                mode = "1vsIA"
                            elif interface.rect_replay.collidepoint(event.pos):
                                menu_choix_mode = False
                                choix_replay = True
                            elif interface.rect_tuto.collidepoint(event.pos):
                                menu_choix_mode = False
                                tutoriel = True
                        except Exception as e:
                            print(e)

            interface.menu_choix_mode()
            pygame.display.flip()

        if selecteur_perso:
            pygame.mixer.music.load(son.son["background"]["character_select"])
            pygame.mixer.music.play(-1)
        while selecteur_perso:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        selecteur_perso = False
                        menu_choix_mode = True
                        mode = False
                        interface = Interface.Interface(ecran)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_joueur1.collidepoint(event.pos):
                                interface.choix_actif = "joueur1"
                            elif interface.rect_joueur2.collidepoint(
                                    event.pos):
                                interface.choix_actif = "joueur2"
                            elif interface.rect_valider1.collidepoint(
                                    event.pos
                            ) and interface.choix_perso_joueur[0]:
                                interface.validation[0] = True
                                interface.choix_actif = "joueur2"
                            elif interface.rect_valider2.collidepoint(
                                    event.pos
                            ) and interface.choix_perso_joueur[1]:
                                interface.validation[1] = True
                                interface.choix_actif = "joueur1"
                            if interface.choix_actif:
                                for perso in interface.rect_logo.keys():
                                    if interface.rect_logo[perso].collidepoint(
                                            event.pos
                                    ) and interface.choix_actif == "joueur1":
                                        interface.choix_perso_joueur[0] = perso
                                        if interface.validation[0]:
                                            interface.validation[0] = False
                                    elif interface.rect_logo[perso].collidepoint(
                                            event.pos
                                    ) and interface.choix_actif == "joueur2":
                                        interface.choix_perso_joueur[1] = perso
                                        if interface.validation[1]:
                                            interface.validation[1] = False
                        except Exception as e:
                            print(e)
                        try:
                            if interface.validation_finale.collidepoint(
                                    event.pos):
                                selecteur_perso = False
                                init_player = True
                                choix_map = True
                        except:
                            pass

            interface.selecteur_perso()
            interface.bouton_selecteur()
            interface.perso_selected()
            interface.bouton_validation()
            interface.check_validation()

            if not interface.init_ia and mode == "1vsIA":
                interface.choix_perso_IA()
                interface.init_ia = True
            pygame.display.flip()

        if init_player:
            if mode == "1v1":
                joueur1 = Player.Player(ecran, interface.choix_perso_joueur[0],
                                        1, setting["speed"], (0, 0, 255))
                joueur2 = Player.Player(ecran, interface.choix_perso_joueur[1],
                                        2, setting["speed"], (255, 0, 0))
                init_player = False
            elif mode == "1vsIA":
                joueur1 = Player.Player(ecran, interface.choix_perso_joueur[0],
                                        1, setting["speed"], (0, 0, 255))
                joueur2 = IA.IA(ecran, interface.choix_perso_joueur[1], 2,
                                setting["speed"], (255, 0, 0))
            interface = Interface.Interface(ecran)
            replay.reset_data()
            interface.transition((255, 255, 255))
            init_player = False

        if choix_map:
            interface.icone_map()
        while choix_map:
            for event in pygame.event.get():  #recupere les evenements
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        choix_map = False
                        selecteur_perso = True
                        mode = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            for i in range(
                                    len(interface.rect_map) - 1, -1, -1):
                                if interface.rect_map[i].collidepoint(
                                        event.pos):
                                    interface.num_map = i + 1

                            if interface.num_map and interface.validation_finale_map.collidepoint(
                                    event.pos):
                                choix_map = False
                                init_timer_debut = True
                        except Exception as e:
                            print(e)

            ecran.fill((0, 0, 0))
            interface.choix_map()
            interface.afficher_choix_map()
            interface.afficher_icone_map_choisie()
            interface.validation_map()
            pygame.display.flip()

        if init_timer_debut:
            interface.transition((255, 255, 255))
            pygame.mixer.music.fadeout(250)
            interface.timer_debut_partie(joueur1, joueur2)
            pygame.event.clear()

            musique = son.son["map"][random.choice(list(
                son.son["map"].keys()))]
            init_timer_debut = False

        if mode:
            try:
                pygame.mixer.music.fadeout(250)
                pygame.mixer.music.load(musique)
                pygame.mixer.music.set_volume(son.son["volume"]["volume"])
                pygame.mixer.music.play(-1)
            except Exception as e:
                print(e)
        while mode:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key in [
                            setting["touche_joueur1"]["pause"],
                            setting["touche_joueur2"]["pause"]
                    ]:
                        menu_pause = True
                        mode = False
                    if event.key == pygame.K_ESCAPE:
                        mode = False
                        menu_choix_mode = True

                joueur1.input_player(event, joueur2)
                joueur2.input_player(event, joueur1)

            joueur1.recup_action_active()
            joueur2.recup_action_active()

            joueur1.update_hit_box(joueur2)
            joueur2.update_hit_box(joueur1)

            joueur1.gerer_degat(joueur2)
            joueur2.gerer_degat(joueur1)
            joueur1.reset_combo()
            joueur2.reset_combo()

            replay.add_data(joueur1, joueur2)
            #joueur1.afficher()
            #joueur2.afficher()

            interface.draw_bg()
            interface.barre_de_vie(joueur1, joueur2)
            joueur1.draw()
            joueur2.draw()

            interface.afficher_combo(joueur1, 50, 75)
            interface.afficher_combo(joueur2, 900, 75)
            quitter = interface.temps()
            pygame.display.flip()
            pygame.time.Clock().tick(setting["fps"])

            if joueur1.vie <= 0 or joueur2.vie <= 0 or quitter:
                menu_fin_partie = True
                mode = False

                interface.afficher_fin_de_partie(joueur1, joueur2)
                if joueur1.vie > joueur2.vie:
                    interface.transition(joueur1.couleur)
                else:
                    interface.transition(joueur2.couleur)
        pygame.mixer.music.fadeout(250)

        if menu_pause:
            pygame.mixer.music.load(son.son["background"]["character_select"])
            pygame.mixer.music.play(-1)
        while menu_pause:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if interface.rect_continuer.collidepoint(event.pos):
                            mode = True
                            menu_pause = False

                        elif interface.rect_quitter.collidepoint(event.pos):
                            menu_pause = False
                            menu_principal = True

            interface.menu_pause()
            pygame.display.flip()

        if menu_replay:
            try:
                replay.load_replay("replay" + str(replay.replay_selected),
                                   interface, joueur1, joueur2)
            except Exception as e:
                print(e)
                joueur1 = Player.Player(ecran, "ken", 1, setting["speed"],
                                        (0, 0, 255))
                joueur2 = Player.Player(ecran, "ken", 2, setting["speed"],
                                        (255, 0, 0))
                replay.load_replay("replay" + str(replay.replay_selected),
                                   interface, joueur1, joueur2)
            interface.transition((255, 255, 255))
            pygame.mixer.music.fadeout(250)
            interface.timer_debut_partie(joueur1, joueur2)
            pygame.event.clear()

            try:
                pygame.mixer.music.load(son.son["map"][random.choice(
                    list(son.son["map"].keys()))])
                pygame.mixer.music.set_volume(son.son["volume"]["volume"])
                pygame.mixer.music.play()
            except Exception as e:
                print(e)
        while menu_replay:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        menu_replay = False
                        choix_replay = True

            replay.load_data(joueur1, joueur2)
            joueur1.recup_action_active()
            joueur2.recup_action_active()

            interface.draw_bg()
            interface.barre_de_vie(joueur1, joueur2)
            interface.afficher_replay()
            joueur1.draw()
            joueur2.draw()

            pygame.display.flip()

            if len(replay.data_player1["posX"]) > 80:
                pygame.time.Clock().tick(setting["fps"])
            else:
                pygame.time.Clock().tick(setting["slow_fps"])

            if joueur1.vie <= 0 or joueur2.vie <= 0:
                menu_fin_partie = True
                menu_replay = False
                replay.replay_selected = None

                interface.afficher_fin_de_partie(joueur1, joueur2)
                if joueur1.vie > joueur2.vie:
                    interface.transition(joueur1.couleur)
                else:
                    interface.transition(joueur2.couleur)
        pygame.mixer.music.fadeout(250)

        if menu_fin_partie:
            pygame.mixer.music.load(son.son["background"]["ending_theme"])
            pygame.mixer.music.play(-1)
            if len(replay.data_player1["posX"]):
                couleur_save = (255, 255, 255)
            elif not (replay.data_player1["posX"]):
                couleur_save = (255, 0, 0)
        while menu_fin_partie:
            for event in pygame.event.get():  #recupere les evenements
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        menu_fin_partie = False
                        menu_principal = True
                        interface.transition((0, 0, 0))

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.rect_menu.collidepoint(event.pos):
                                menu_choix_mode = True
                                menu_fin_partie = False
                                interface.transition((255, 255, 255))

                            elif interface.rect_quit.collidepoint(event.pos):
                                menu_fin_partie = False
                                continuer = False

                            elif interface.rect_save.collidepoint(event.pos):
                                if len(replay.data_player1["posX"]):
                                    menu_fin_partie = False
                                    choix_replay = "save"

                        except Exception as e:
                            print(e)

            interface.fin_de_partie(joueur1, joueur2, couleur_save)
            pygame.display.flip()

        if choix_replay:
            pygame.mixer.music.load(son.son["background"]["ending_theme"])
            pygame.mixer.music.play(-1)
        while choix_replay:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        if choix_replay == "save":
                            choix_replay = False
                            menu_fin_partie = True
                        else:
                            choix_replay = False
                            menu_choix_mode = True
                            replay.replay_selected = None

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.r_replay1.collidepoint(event.pos):
                                replay.replay_selected = 1
                            elif interface.r_replay2.collidepoint(event.pos):
                                replay.replay_selected = 2
                            elif interface.r_replay3.collidepoint(event.pos):
                                replay.replay_selected = 3
                            elif interface.bouton_ok.collidepoint(
                                    event.pos) and replay.replay_selected:
                                if choix_replay == "save":
                                    replay.save_replay(
                                        "replay" + str(replay.replay_selected),
                                        interface.num_map, joueur1.nom,
                                        joueur2.nom)
                                    choix_replay = False
                                    menu_principal = True
                                    replay.replay_selected = None
                                else:
                                    choix_replay = False
                                    menu_replay = True
                        except Exception as e:
                            print(e)

            interface.choix_replay(replay)
            pygame.display.flip()

        if tutoriel:
            pygame.mixer.music.load(son.son["background"]["ending_theme"])
            pygame.mixer.music.play(-1)
        while tutoriel:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        tutoriel = False
                        menu_choix_mode = True

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        try:
                            if interface.r_retour.collidepoint(event.pos):
                                tutoriel = False
                                menu_choix_mode = True
                            elif interface.r_entrainement.collidepoint(
                                    event.pos):
                                tutoriel = False
                                entrainement = True
                        except Exception as e:
                            print(e)

            ecran.fill((255, 255, 255))
            interface.aide()
            interface.bouton_aide()
            pygame.display.flip()

        if entrainement:
            interface.create_box(15)
            perso = random.choice(["ken", "ryu", "cammy"])
            joueur1 = Player.Player(ecran, perso, 1, setting["speed"],
                                    (0, 0, 255))
            interface.num_map = random.randrange(1, 7)
            interface.load_record()
            interface.transition((255, 255, 255))
            musique = son.son["map"][random.choice(list(
                son.son["map"].keys()))]
            try:
                pygame.mixer.music.fadeout(250)
                pygame.mixer.music.load(musique)
                pygame.mixer.music.set_volume(son.son["volume"]["volume"])
                pygame.mixer.music.play(-1)
            except Exception as e:
                print(e)

            interface.debut_entrainement = time.time()
        while entrainement:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == son.son["volume"]["volume_up"]:
                        son.modif_volume(0.1)
                    elif event.key == son.son["volume"]["volume_down"]:
                        son.modif_volume(-0.1)
                    if event.key == pygame.K_ESCAPE:
                        entrainement = False
                        tutoriel = True

                joueur1.input_player(event)

            joueur1.recup_action_active()
            joueur1.update_hit_box(joueur1)

            interface.draw_bg()
            joueur1.draw()
            interface.tutoriel()

            pygame.draw.rect(ecran, (0, 255, 0), interface.box_tuto[0])
            interface.gerer_box_tuto(joueur1)
            interface.nbr_box_restantes()

            pygame.display.flip()
            pygame.time.Clock().tick(setting["fps"])

            if not len(interface.box_tuto):
                interface.temps_entrainement = time.time(
                ) - interface.debut_entrainement
                interface.save_record()
                entrainement = False
                tutoriel = True
                time.sleep(1)
                interface.transition((255, 255, 255))
        pygame.mixer.music.fadeout(250)
Exemplo n.º 34
0
class Echecs:

    Distribution_Info = ["Lancement classique", "Single Tour Kill", "Pion mange Pion "]     #afficher le mode de lancement sur le terminal
    Game_Mode_Info = ["Humain vs Humain", "Humain vs IA", "IA vs IA"]

    def __init__(self, mode = 1, dis = 0, showMove = True, showRecherche = False, showGUI = True, saveInfo = False):
                self.Plateau = PlateauEchecs()
                self.Player_Side = False
                self.GameMode = mode
                self.distribution = dis

                self.ai_0 = IA()
                self.ai_1 = IA()

                self.ShowMoveInfo = showMove
                self.ShowRechercheInfo = showRecherche
                self.ShowGraphUI = showGUI
                self.SaveInfo = saveInfo

                self.view = GraphEchecs(self)

    def Set(self, mode = 1, dis = 0, showMove = True, showRecherche = False, showGUI = True,
                saveInfo = False, saveChemin = r".\Records",
                ai_name_0 = "MinMaxRecherche", use_pos_0 = False, profondeur_0 = 3,
                ai_name_1 = "MinMaxRecherche", profondeur_1 = 3, use_pos_1 = False):
        self.GameMode = mode
        self.distribution = dis
        self.ShowMoveInfo = showMove
        self.ShowRechercheInfo = showRecherche
        self.ShowGraphUI = showGUI
        self.SaveInfo = saveInfo
        self.SaveChemin = saveChemin
        self.SaveFileName = ""
        if ai_name_0 == "MinMaxRecherche":
            ai_0 = MinMaxRechercheIA(profondeur_0, True, use_pos_0)
        else:
            ai_0 = RandomMoveIA()
        if ai_name_1 == "MinMaxRecherche":
            ai_1 = MinMaxRechercheIA(profondeur_1, True, use_pos_1)
        else:
            ai_1 = RandomMoveIA()
        self.SetIA(ai_0, ai_1)

    def SetGame(self, mode = 1, dis = 0):
        self.GameMode = mode
        self.distribution = dis

    def SetInfo(self, showMove = True, showRecherche = False, showGUI = True, saveInfo = False):
            self.ShowMoveInfo = showMove
            self.ShowRechercheInfo = showRecherche
            self.ShowGraphUI = showGUI
            self.SaveInfo = saveInfo

    def SetIA(self, ai_0, ai_1):
        self.ai_0 = ai_0
        self.ai_1 = ai_1

    def start(self):

        timeInfo = time.strftime('%Y-%m-%d %H:%M:%S')   #Temps passe
        timeLabel = time.strftime('%Y-%m-%d-%H-%M-%S')

        self.SaveFileName = timeLabel + ".txt"  #Sauvegarder une partie avec la date et l'heure a laquelle la personne a joue

        Msg = timeInfo + " " \
              + Echecs.Game_Mode_Info[self.GameMode] + " " \
              + Echecs.Distribution_Info[self.distribution] + "\n"
        Msg_IA = ""
        if self.GameMode == 1:
            Msg_IA += str(self.ai_0) + "\n"
        elif self.GameMode == 2:
            Msg_IA += str(self.ai_0) + "\n"
            Msg_IA += str(self.ai_1) + "\n"

        print Msg + Msg_IA,
        if self.SaveInfo:
            self.SaveData(Msg + Msg_IA)

        self.Plateau.Plateau_Init(self.distribution)

        if self.GameMode == 2:
            if not self.ShowGraphUI:
                self.Game_IAvIA_Auto(self.ai_0, self.ai_1)

        self.view.showMsg("Jeu D'Echecs")
        self.view.draw_Plateau(self.Plateau)
        self.view.start()

    def callback(self, event):
        rx, ry = real_coord(event.x), real_coord(800 - event.y)
        self.Game(rx, ry, self.GameMode)

    def Move_Info(self, move_info):
        game_info = {0:"", 1:" #", 2:" #", 3:" Impasse", 4:" Egalite", 5:" Perpetual check"}
        return "(" + str(self.Plateau.Round) + "):" + move_info \
        + game_info[self.Plateau.Statut] \
        + ("; " if self.Player_Side else ";\n")

    def SaveData(self, info):
        fileName = self.SaveChemin + r'\chess-' + self.SaveFileName
        with open(fileName, 'a') as data:
            data.write(info)

    def Game(self, x, y, mode = 0):
        if mode == 0:
            self.Game_PvP(x, y)
        elif mode == 1:
            self.Game_PvIA(x, y)
        elif mode == 2:
            self.Game_IAvIA(self.ai_0, self.ai_1)
        else:
            raise Exception("Mode de jeu invalide: " + str(mode))

    
    def Game_PvIA(self, rx, ry):  #Fonction qui fait le jeu entre un joueur et l'IA
        if self.Plateau.Statut != 0:
            return
        move_info = self.Plateau.select(rx, ry, self.Player_Side)
        self.view.draw_Plateau(self.Plateau)
        if move_info != "":
            self.view.showMsg("Tour Blanc" if self.Player_Side else "Tour Noir")    #On affiche en titre de fenetre si c'est aux blancs ou aux noirs de jouer
            self.Player_Side = not self.Player_Side
            self.Plateau.Round += 1
            self.Plateau.UpdateStatu()
            if self.ShowMoveInfo:
                print self.Move_Info(move_info),
                if self.SaveInfo:
                    self.SaveData(self.Move_Info(move_info))
            self.view.draw_Plateau(self.Plateau)

            if self.Plateau.Statut != 0:
                return

            move, msg = self.ai_0.Play(self.Plateau, self.Player_Side)
            self.Plateau.select(move[0][0], move[0][1], self.Player_Side)
            move_info = self.Plateau.select(move[1][0], move[1][1], self.Player_Side)
            self.view.showMsg("Tour Blanc" if self.Player_Side else "Tour Noir")
            self.Player_Side = not self.Player_Side
            self.Plateau.Round += 1
            self.Plateau.UpdateStatu()
            if self.ShowRechercheInfo:
                print msg,
                if self.SaveInfo:
                    self.SaveData(msg + " ")
            if self.ShowMoveInfo:
                print self.Move_Info(move_info),
                if self.SaveInfo:
                    self.SaveData(self.Move_Info(move_info))
            self.view.draw_Plateau(self.Plateau)

    def Game_IAvIA_Auto(self, ai_0, ai_1):
        while self.Plateau.Statut == 0:
            ai_0.Clear()
            move, msg = ai_0.Play(self.Plateau, self.Player_Side)
            self.Plateau.select(move[0][0], move[0][1], self.Player_Side)
            move_info = self.Plateau.select(move[1][0], move[1][1], self.Player_Side)
            self.view.showMsg("Tour Blanc" if self.Player_Side else "Tour Noir")
            self.Player_Side = not self.Player_Side
            self.Plateau.Round += 1
            self.Plateau.UpdateStatu()
            if self.ShowRechercheInfo:
                print msg,
                if self.SaveInfo:
                    self.SaveData(msg + " "),
            if self.ShowMoveInfo:
                print self.Move_Info(move_info),
                if self.SaveInfo:
                    self.SaveData(self.Move_Info(move_info))

            if self.Plateau.Statut != 0:
                self.SaveData("\n")
                print ""
                break

            ai_1.Clear()
            move, msg = ai_1.Play(self.Plateau, self.Player_Side)
            self.Plateau.select(move[0][0], move[0][1], self.Player_Side)
            move_info = self.Plateau.select(move[1][0], move[1][1], self.Player_Side)
            self.view.showMsg("Tour Blanc" if self.Player_Side else "Tour Noir")
            self.Player_Side = not self.Player_Side
            self.Plateau.Round += 1
            self.Plateau.UpdateStatu()
            if self.ShowRechercheInfo:
                print msg,
                if self.SaveInfo:
                    self.SaveData(msg + " ")
            if self.ShowMoveInfo:
                print self.Move_Info(move_info),
                if self.SaveInfo:
                    self.SaveData(self.Move_Info(move_info))

        print self.Plateau
        print self.Plateau.Statut
        if self.SaveInfo:
            self.SaveData(str(self.Plateau)+"\n")
            self.SaveData(str(self.Plateau.Statut) + "\n")