Exemple #1
0
class Jeu(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller= controller
        self.data = None
        self.map = None
        self.canvas = Canvas(self, bg = 'dark gray', height = 600, width = 800)
        self.canvas.pack(padx = 10, pady = 10)
        self.liste_id_obstacle=[]
        self.taille = 25
        self.color_obstacle = "black"

        
    def initialisation(self):
        self.data = {self.controller.client.name:{"color":"red", "position":[(1,2)]}}
        self.map = Map(10,10)
        self.controller.client.get_map()
        
    def updateAffichage(self):
        self.afficherObstacle()
        '''
        for name in self.data:
            temp = self.data[name]
            pos = temp["position"]
            color = temp["color"]
            for n in pos:
                self.drawCarre(n, color, name)
                '''
    def set_map(self, dico):
        width = dico["width"]
        height = dico["height"]
        numbers = dico["numbers"]
        obstacles = dico["obstacles"]
        self.map = Map(width, height)
        for i in obstacles:
            self.map.set_obstacle(i[0], i[1], True)
        self.ajouterID_obstacles(numbers)

    def moveID(self, pos_x, pos_y, id, taille):
        x0 = pos_x * self.taille + self.taille/2.0 - taille/2.0
        y0 = pos_y * self.taille + self.taille/2.0 - taille/2.0
        x1 = pos_x * self.taille + taille + self.taille/2.0 - taille/2.0
        y1 = pos_y * self.taille + taille + self.taille/2.0 - taille/2.0
        self.canvas.coords(id, x0, y0, x1, y1)    

    def afficherObstacle(self):
        liste_pos = self.map.getPositionObstacles()
        for i in range (len(liste_pos)):
            pos = liste_pos[i]
            self.moveID(pos[0], pos[1], self.liste_id_obstacle[i], self.taille)

    def ajouterID_obstacles(self, nombre =1):
        for i in range (nombre):
            self.liste_id_obstacle.append(self.canvas.create_rectangle(0, 0, self.taille, self.taille, fill = self.color_obstacle))
        self.afficherObstacle()

    def drawCarre(self, n, color, name):
        print (n, color)
        print (name)
Exemple #2
0
class Controleur:

    def __init__(self):
        self.map = Map(31, 23)
        self.nourriture = Nourriture()
        self.serpent = Serpent()
        self.oriente = "Down"
        self.vie = True

    def initialize(self):
        self.serpent.setPosition(5,5, "Left")
        self.gui.ajouterID_corps(3)
        self.nouvellePositionNourriture()
        file = FileMap()
        matrice = file.loadFromFile("map.txt")
        valeur = self.map.loadMatrice(matrice)
        self.gui.ajouterID_obstacles(valeur)

    def getPositionBlock(self):
        return self.block.getPosition()

    def getLongueurMap(self):
        return self.map.getLongueur()

    def getHauteurMap(self):
        return self.map.getHauteur()

    def getPositionSerpent(self):
        return self.serpent.getPosition()

    def getPositionNourriture(self):
        return self.nourriture.getPosition()

    def checkEat(self):
        if self.nourriture.getPosition() == self.serpent.getPosition():
            self.serpent.agrandir(1)
            self.gui.ajouterID_corps()
            self.nouvellePositionNourriture()



    def getRandom(self, start, end):
        return randint(start, end)

    def getRandomFree(self):        #Trop aléatoire, DANGER !
        pos = (self.getRandom(0, self.getLongueurMap()-1), self.getRandom(0, self.getHauteurMap()-1))
        while self.checkCollision(pos[0], pos[1]):
            pos = (self.getRandom(0, self.getLongueurMap()), self.getRandom(0, self.getHauteurMap()))
        return pos

    def serpent_goLeft(self):
        self.serpent.move_left(self.getLongueurMap())

    def serpent_goRight(self):
        self.serpent.move_right(self.getLongueurMap())

    def serpent_goUp(self):
        self.serpent.move_up(self.getHauteurMap())

    def serpent_goDown(self):
        self.serpent.move_down(self.getHauteurMap())

    def nouvellePositionNourriture(self):
        pos = self.getRandomFree()
        self.nourriture.setPosition(pos[0], pos[1])
        self.gui.afficherNourriture()

    def link(self, gui):
        self.gui = gui
        self.initialize()



    def getListeCorpsSerpent(self):
        return self.serpent.getListeCorps()


    def move (self):
        if self.vie:
            if self.oriente == "Left":
                if self.possible_left():
                    self.serpent_goLeft()
                else:
                    self.serpentMort()
            elif self.oriente == "Right":
                if self.possible_right():
                    self.serpent_goRight()
                else :
                    self.serpentMort()
            elif self.oriente == "Up":
                if self.possible_up():
                    self.serpent_goUp()
                else :
                    self.serpentMort()
            elif self.oriente == "Down":
                if self.possible_down():
                    self.serpent_goDown()
                else :
                    self.serpentMort()
            self.gui.afficherSerpent()
            self.gui.afficherNourriture()
        else:
            print("Mort")

    def possible_left(self):
        pos = self.serpent.getPosition()
        pos = (pos[0]-1, pos[1])
        return not self.checkCollision(pos[0], pos[1])

    def possible_right(self):
        pos = self.serpent.getPosition()
        pos = ((pos[0]+1) %self.getLongueurMap(), pos[1])
        return not self.checkCollision(pos[0], pos[1])

    def possible_up(self):
        pos = self.serpent.getPosition()
        pos = (pos[0], pos[1]-1 )
        return not self.checkCollision(pos[0], pos[1])

    def possible_down(self):
        pos = self.serpent.getPosition()
        pos = (pos[0], (pos[1]+1)%self.getHauteurMap() )
        return not self.checkCollision(pos[0], pos[1])

    def oriente_serpent_left(self, event):
        if self.oriente != "Right":
            self.set_var("Left")

    def oriente_serpent_right(self, event):
        if self.oriente != "Left":
            self.set_var("Right")

    def oriente_serpent_up(self, event):
        if self.oriente != "Down":
            self.set_var("Up")

    def oriente_serpent_down(self, event):
        if self.oriente != "Up":
            self.set_var("Down")

    def set_var(self, var):
        self.oriente = var

    def checkCollision_corps(self, pos_x, pos_y):
        return self.serpent.contains(pos_x, pos_y)

    def switch(self, event):
        self.gui.switchToMenu()

    def getPositionObstacles(self):
        liste_pos = self.map.getPositionObstacles()
        return liste_pos

    def ajouterObstacles(self, x, y, valeur):
        self.map.set_obstacle(x, y, valeur)
        self.gui.ajouterID_obstacles()


    def checkCollision_obstacles(self, x, y):
        return self.map.obstacles_contains(x, y)

    def checkCollision(self, x, y):
        return self.checkCollision_corps(x, y) or self.checkCollision_obstacles(x, y)

    def serpentMort(self):
        self.vie = False
Exemple #3
0
class Serveur(threading.Thread):
    def __init__(self, interface):
        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sockets = {}
        self.interface = interface

        self.map = Map(1,1)
        file = FileMap()
        matrice = file.loadFromFile("map.txt")
        valeur = self.map.loadMatrice(matrice)
        self.running = True
        self.updateMovement()           #Faire classe thread

        #valeurs


    def run(self):
        try:
            self.socket.bind(('',33033))
            print("Serveur connecté, attente de player...")
            self.running = True
            while self.running:
                self.socket.listen(3)
                socket, adresse = self.socket.accept()
                print("Player connecté, adresse IP", adresse[0],", port",adresse[1])
                player = Player(socket, self, self.interface)
                pos = self.map.getRandomFree(3)
                player.setPosition(pos[0], pos[1])
                nom = player.getName()
                self.sockets[nom]=player
                player.start()
                self.interface.updatePlayers()                
                                                             
        except:
            print("La liaison du socket a été interrompue.")
            self.running = False
            self.socket.close()
            print ("Unexpected error:", sys.exc_info())

    def updateMovement(self):
        liste_pos = []
        for name in self.sockets:
            player = self.sockets[name]
            player.updateMovement()
            liste_pos.append(player.getPosition())

        self.send("all", "update players", liste_pos)
        if (self.running):
            self.interface.fenetre.after(200, self.updateMovement)
    
    def isrunning(self):
        return self.running

    def getSizeConnected(self):
        return len(self.sockets)

    def stop(self):
        self.running = False
        self.socket.close()

    def analyse(self, name, message):
        message = json.loads(message)
        if message["type"] == "load map":
            obstacles = self.map.getPositionObstacles()
            data = {"width" : self.map.getLongueur(), "height": self.map.getHauteur(), "numbers":len(obstacles), "obstacles":obstacles}
            self.send(name, "load map", data)
        else:
            print("Type inconnu", message["type"], message["data"])

    def send(self, name, types, data = ""):
        message = {}
        message["type"] = types
        message["data"] = data
        message = json.dumps(message)
        if name == "all":
            for name in self.sockets:
                self.sockets[name].socket.send(message.encode("Utf8"))
        else:
            self.sockets[name].socket.send(message.encode("Utf8"))

    def playerDeconnecte(self, name):
        self.sockets.pop(name)
        print ("Player", name,"déconnecté")
        self.interface.updatePlayers()