<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

from Batiments import Batiment
from Commands import Command
import GraphicsManagement
from LoadingScreen import ResourceLoader, LoadingScreen
from Model import Model
from NetworkModule import NetworkController, ClientConnectionError, Client
import NetworkModule
from TitleScreen import TitleScreen
from Units import Unit
from Units import Noeud
from View import GameView, FrameSide
from GameWindow import GameWindow
from SimpleTimer import Timer
import MenuDebut


SKIP_MENU = True  # Permet de skipper les menus
LOAD_RESSOURCE_ON_START = False  # Si on load les ressources au démarrage du jeu ou non



class Controller:
    """ Responsable des communications entre le module réseau, la Vue et le Modèle
        de sorte à ce qu'ils n'aient pas accès entre eux directement.
    """


    def __init__(self):
        self.model = Model(self)
        self.network = NetworkController()
        self.eventListener = EventListener(self)
        self.window = GameWindow()

        self.view = None


        self.currentFrame = -1
        self.nbFramesPerSecond = 15
        self.refreshRate = int(1000 / self.nbFramesPerSecond)

        self.displayTimer = Timer(1000 / 60)  # Pour limiter nombre de rafraichissement du GUI (60 FPS ~ 16ms)
        self.loadingThread = None

        self.gameStarted = False


    def mainLoop(self):
        if self.network.client is not None:
            try:
                print(self.currentFrame)
                cmd = self.network.synchronizeClient(self.currentFrame)
            except ClientConnectionError:
                self.shutdown()
            # TODO Faire quelque chose de plus approprié (afficher message? retour au menu principal?)
            for c in cmd:
                if c['TYPE'] == Command.START_GAME:
                    self.startGame()

        if not self.gameStarted:
            self.titleScreenLoop()
        else:
            self.gameLoop(cmd)

        self.window.after(self.refreshRate, self.mainLoop)

    def gameLoop(self, cmd):
        self.doLogic(cmd)
        self.renderGraphics()


    def startGame(self):

        self.view.destroy()
        print(self.window.root)
        self.view = GameView(self.window, self.eventListener)

        cmd = Command(self.network.getClientId(), Command.CIVILISATION_CREATE)
        cmd.addData('ID', self.network.getClientId())
        self.sendCommand(cmd)
        self.model.creerJoueur(self.network.getClientId())
        self.model.civNumber = self.network.getClientId()

        self.gameStarted = True



        #self.view = GameView(self.window, self.eventListener)
        #self.view.drawMinimap(self.model.carte.matrice)
        #self.view.drawRectMiniMap()
        #self.view.drawMap(self.model.carte.matrice)






    def doLogic(self, commands):
        """ Une itération sur cette fonction constitue une FRAME
        :return:
        """
        doUpdate = True
        for command in commands:
            if command['TYPE'] == Command.WAIT:
                doUpdate = False
            elif command['TYPE'] == Command.DESYNC:
                Client.outputDebug("Votre clent est DÉSYNCHRONISÉ")
                self.shutdown()  # TODO Afficher message
            else:
                self.model.executeCommand(command)

        if doUpdate:
            self.model.update()
            # print("Finnished %s" % self.currentFrame)
            self.currentFrame += 1

    def renderGraphics(self):
        """ Méthode principale d'affichage des Graphics
        :return:
        """
        joueur = self.model.joueurs[self.model.civNumber]
        if self.displayTimer.isDone():

            if self.view.needUpdateCarte():
                self.view.update(self.model.getUnits(), self.model.getBuildings(), self.model.carte.matrice, joueur=joueur)
            else:
                self.view.update(self.model.getUnits(), self.model.getBuildings(), joueur=joueur)
            self.displayTimer.reset()

    def start(self):
        """ Starts the controller
        """

        # TIMERS
        self.displayTimer.start()

        # FRAMES
        self.currentFrame = 0


        if SKIP_MENU:
           # INITIALISATION RÉSEAU
            self.network.startServer(port=33333)
            self.network.connectClient(ipAddress='10.57.100.193', port=33333, playerName='Batman')

            # INITIALISATION MODEL
            self.gameStarted = True
            cmd = Command(self.network.getClientId(), Command.CIVILISATION_CREATE)
            cmd.addData('ID', self.network.getClientId())
            self.sendCommand(cmd)

            self.model.creerJoueur(self.network.getClientId())
            self.model.joueur = self.model.joueurs[self.network.getClientId()]
            self.model.civNumber = self.network.getClientId()


            self.model.creerAI(7)
            self.model.creerbaseAI(7)

            # INITIALISATION AFFICHAGE
            self.view = GameView(self.window, self.eventListener)
            self.view.drawMinimap(self.model.carte.matrice)
            self.view.drawRectMiniMap()
            self.view.drawMap(self.model.carte.matrice)
        else:
            if LOAD_RESSOURCE_ON_START:
                print("YAA")
                self.view = LoadingScreen(self.window, self)
                self.graphicsLoader = ResourceLoader(GraphicsManagement.detectGraphics(), self.view)
            else:
                self.graphicsLoader = ResourceLoader(GraphicsManagement.detectGraphics(), self.view)
                self.graphicsLoader.isDone = True
                self.view = TitleScreen(self.window, self)
                self.catchMenuEvent(MenuDebut.TitleEvent.VOIR_MENU_PRINCIPAL)


        self.mainLoop()
        self.window.show()







    def catchMenuEvent(self, event, additionalData=None):
        """ Événement actionné par l'usager durant l'écran titre
        :param event: L'évenement à gérer
        :param additionalData: paramètre additionnel accompagnant l'action
        """
        # Affichage Menus
        if event == MenuDebut.TitleEvent.VOIR_MENU_PRINCIPAL:<commit_msg>Lancement Partie réseau à partir du menu<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from tkinter import ALL

from Batiments import Batiment
from Commands import Command
import GraphicsManagement
from LoadingScreen import ResourceLoader, LoadingScreen
from Model import Model
from NetworkModule import NetworkController, ClientConnectionError, Client
import NetworkModule
from TitleScreen import TitleScreen
from Units import Unit
from Units import Noeud
from View import GameView, FrameSide
from GameWindow import GameWindow
from SimpleTimer import Timer
import MenuDebut


SKIP_MENU = False  # Permet de skipper les menus
LOAD_RESSOURCE_ON_START = True  # Si on load les ressources au démarrage du jeu ou non



class Controller:
    """ Responsable des communications entre le module réseau, la Vue et le Modèle
        de sorte à ce qu'ils n'aient pas accès entre eux directement.
    """


    def __init__(self):
        self.model = Model(self)
        self.network = NetworkController()
        self.eventListener = EventListener(self)
        self.window = GameWindow()

        self.view = None


        self.currentFrame = -1
        self.nbFramesPerSecond = 15
        self.refreshRate = int(1000 / self.nbFramesPerSecond)

        self.displayTimer = Timer(1000 / 60)  # Pour limiter nombre de rafraichissement du GUI (60 FPS ~ 16ms)
        self.loadingThread = None

        self.gameStarted = False


    def mainLoop(self):
        if self.network.client is not None:
            try:
                print(self.currentFrame)
                cmd = self.network.synchronizeClient(self.currentFrame)
            except ClientConnectionError:
                self.shutdown()
            # TODO Faire quelque chose de plus approprié (afficher message? retour au menu principal?)
            for c in cmd:
                if c['TYPE'] == Command.START_GAME:
                    self.startGame()

        if not self.gameStarted:
            self.titleScreenLoop()
        else:
            self.gameLoop(cmd)

        self.window.after(self.refreshRate, self.mainLoop)

    def gameLoop(self, cmd):
        self.doLogic(cmd)
        self.renderGraphics()


    def startGame(self):

        self.window.canvas.delete(ALL)
        print(self.window.root.update())
        self.view = GameView(self.window, self.eventListener)

        cmd = Command(self.network.getClientId(), Command.CIVILISATION_CREATE)
        cmd.addData('ID', self.network.getClientId())
        self.sendCommand(cmd)
        self.model.creerJoueur(self.network.getClientId())
        self.model.joueur = self.model.joueurs[self.network.getClientId()]
        self.model.civNumber = self.network.getClientId()

        self.gameStarted = True



        self.view = GameView(self.window, self.eventListener)
        self.view.drawMinimap(self.model.carte.matrice)
        self.view.drawRectMiniMap()
        self.view.drawMap(self.model.carte.matrice)






    def doLogic(self, commands):
        """ Une itération sur cette fonction constitue une FRAME
        :return:
        """
        doUpdate = True
        for command in commands:
            if command['TYPE'] == Command.WAIT:
                doUpdate = False
            elif command['TYPE'] == Command.DESYNC:
                Client.outputDebug("Votre clent est DÉSYNCHRONISÉ")
                self.shutdown()  # TODO Afficher message
            else:
                self.model.executeCommand(command)

        if doUpdate:
            self.model.update()
            # print("Finnished %s" % self.currentFrame)
            self.currentFrame += 1

    def renderGraphics(self):
        """ Méthode principale d'affichage des Graphics
        :return:
        """
        joueur = self.model.joueurs[self.model.civNumber]
        if self.displayTimer.isDone():

            if self.view.needUpdateCarte():
                self.view.update(self.model.getUnits(), self.model.getBuildings(), self.model.carte.matrice, joueur=joueur)
            else:
                self.view.update(self.model.getUnits(), self.model.getBuildings(), joueur=joueur)
            self.displayTimer.reset()

    def start(self):
        """ Starts the controller
        """

        # TIMERS
        self.displayTimer.start()

        # FRAMES
        self.currentFrame = 0

        if LOAD_RESSOURCE_ON_START:
            print("YAA")
            self.view = LoadingScreen(self.window, self)
            self.graphicsLoader = ResourceLoader(GraphicsManagement.detectGraphics(), self.view)
        else:
            if SKIP_MENU:
               # INITIALISATION RÉSEAU
                self.network.startServer(port=33333)
                self.network.connectClient(ipAddress='10.57.100.193', port=33333, playerName='Batman')

                # INITIALISATION MODEL
                self.gameStarted = True
                cmd = Command(self.network.getClientId(), Command.CIVILISATION_CREATE)
                cmd.addData('ID', self.network.getClientId())
                self.sendCommand(cmd)

                self.model.creerJoueur(self.network.getClientId())
                self.model.joueur = self.model.joueurs[self.network.getClientId()]
                self.model.civNumber = self.network.getClientId()


                self.model.creerAI(7)
                self.model.creerbaseAI(7)

                # INITIALISATION AFFICHAGE
                self.view = GameView(self.window, self.eventListener)
                self.view.drawMinimap(self.model.carte.matrice)
                self.view.drawRectMiniMap()
                self.view.drawMap(self.model.carte.matrice)
            else:
                self.graphicsLoader = ResourceLoader(GraphicsManagement.detectGraphics(), self.view)
                self.graphicsLoader.isDone = True
                self.view = TitleScreen(self.window, self)
                self.catchMenuEvent(MenuDebut.TitleEvent.VOIR_MENU_PRINCIPAL)


        self.mainLoop()
        self.window.show()







    def catchMenuEvent(self, event, additionalData=None):
        """ Événement actionné par l'usager durant l'écran titre
        :param event: L'évenement à gérer
        :param additionalData: paramètre additionnel accompagnant l'action
        """
        # Affichage Menus
        if event == MenuDebut.TitleEvent.VOIR_MENU_PRINCIPAL:
{'fraction_non_alphanumeric': 0.09105495387083835, 'fraction_numerical': 0.006738868832731649, 'mean_word_length': 2.2087516087516086, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6135563', 'n_tokens_mistral': 3721, 'n_tokens_neox': 3478, 'n_words': 755}