def display(self) -> None: """Procédure d'affichage de la cellule""" Display.drawCircle(pos=self.pos, color=self.color, radius=self.radius, base_pos=Camera.pos)
def __init__(self): self.layout = Layout(Const.WORLD) Display.initGraphics(self.layout) self.model = Model(self.layout) self.carChanges = {} self.errorCounter = Counter() self.consecutiveLate = 0
def run(self): self.render() self.userThread = UserThread(self.model.junior, self.model) self.userThread.start() self.iteration = 0 while not self.isGameOver(): self.resetTimes() startTime = time.time() self.printStats() self.otherCarUpdate() self.calculateError() duration = time.time() - startTime timeToSleep = Const.SECONDS_PER_HEARTBEAT - duration # self.checkLate(timeToSleep) timeToSleep = max(0.01, timeToSleep) Display.graphicsSleep(timeToSleep) self.iteration += 1 if not self.userThread.quit and not self.isLearning: self.outputGameResult() self.userThread.stop() Display.graphicsSleep(0.1) self.userThread.join() return self.userThread.quit
def init(cls) -> None: """Initialisation de la caméra""" Display.execWhenResized(cls.whenResized) cls.pos = Vect2d(0, 0) cls.window_center = Vect2d(0, 0)
def updateBeliefs(self): if self.isLearning: return beliefs = [] for car in self.model.getOtherCars(): belief = car.getInference().getBelief() color = car.getColor() Display.updateBelief(color, belief) beliefs.append(belief) self.model.setProbCar(beliefs)
def render(self): Display.drawBelief(self.model) Display.drawBlocks(self.model.getBlocks()) if Const.SHOW_CARS: for car in self.model.getCars(): Display.drawCar(car) else: Display.drawCar(self.model.getJunior()) Display.drawFinish(self.model.getFinish()) view.graphicsUtils.refresh()
def outputGameResult(self): collided = self.userThread.hasCollided() for car in self.model.getCars(): Display.drawCar(car) print '*********************************' print '* GAME OVER *' if collided: print '* CAR CRASH!!!!!' else: print '* You Win!' print '*********************************'
def infer(self): start = time.time() try: self.elapseTime() self.observe() except Exception, e: print 'caught' traceback.print_exc() Display.raiseEndGraphics() Display.graphicsSleep(0.01) self.userThread.quit = True
def display(cls) -> None: """Affichage du menu""" hand_cursor = False for i in range(len(cls.buttons)): hand_cursor = cls.buttons[i].display(cls.mouse_pos) or hand_cursor if hand_cursor: # Change le curseur selon le bouton sur lequel il est Display.setCursorHand() else: Display.setCursorArrow()
def buttonWin_Display( button: Button, mouse_pos: Vect2d, ) -> None: """Affichage du texte de fin""" min_size = max(button.size.x, button.size.y) font_size = min_size * 50 / 400 Display.drawRect(Vect2d(0, 0), Display.size, (0, 0, 0, button.alpha)) if button.alpha < 127: button.alpha += 1 elif button.alpha < 255 and Map.game_finished: button.alpha += 1 score = Map.player_infos.get("score", 0) tps = Map.player_infos.get("time", 0) Display.drawText(button.text, button.pos + button.size / 2, color=button.color, size=font_size) Display.drawText("Score : " + str(score), button.pos + button.size / 2 + Vect2d(0, button.size.y), color=button.color, size=font_size) Display.drawText("Temps : " + str(tps) + " secondes", button.pos + button.size / 2 + Vect2d(0, button.size.y * 2), color=button.color, size=font_size)
def handleKeys(cls) -> None: """Méthode permettant de traiter les entrées clavier""" keys = pygame.key.get_pressed() if keys[pygame.K_RETURN]: for k in Map.creatures.keys(): if k == Map.player_id: for creature in Map.creatures[k]: creature.score += 100 #! à retirer if keys[pygame.K_ESCAPE]: # Si la touche ESC est pressée if cls.keytime.get(pygame.K_ESCAPE, 0) > cls.ESC_MAX_FRAMECOUNT: # Si l'on est au dessus de la valeur maximale pour quitter cls.finished = True else: cls.keytime[pygame.K_ESCAPE] = cls.keytime.get( pygame.K_ESCAPE, 0) + 1 # Sinon on incrémente le nombre d'images écoulées else: cls.keytime[pygame.K_ESCAPE] = 0 # Si elle est relachée on remet le compteur à 0 for event in pygame.event.get(): if event.type == pygame.VIDEORESIZE: # Quand la fenêtre est redimensionnée Display.resize(event.w, event.h) if event.type == pygame.QUIT: # Détection de la fermeture de la fenêtre cls.finished = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_F11: # Quand F11 on se met en plein écran Display.toggleFullscreen() if event.key == pygame.K_SPACE: if Map.isPlayerAlive(): Map.splitPlayer()
def heartbeat(self): oldDir = Vec2d(self.junior.dir.x, self.junior.dir.y) oldPos = Vec2d(self.junior.pos.x, self.junior.pos.y) quitAction = self.junior.action() carProb = self.model.getProbCar() if carProb and Const.AUTO: agentGraph = self.model.getJuniorGraph() self.junior.autonomousAction(carProb, agentGraph) if quitAction: self.quit = True return self.junior.update() self.collision = self.model.checkCollision(self.junior) self.victory = self.model.checkVictory() newPos = self.junior.getPos() newDir = self.junior.getDir() deltaPos = newPos - oldPos deltaAngle = oldDir.get_angle_between(newDir) Display.move(self.junior, deltaPos) Display.rotate(self.junior, deltaAngle)
def isGameOver(self): if self.isLearning: keys = Display.getKeys() if 'q' in keys: self.userThread.quit = True return True return self.iteration > Const.TRAIN_ITERATIONS if self.userThread.quit: return True if self.userThread.victory: return True return self.userThread.hasCollided()
def buttonEnd_Display(button: Button, mouse_pos: Vect2d) -> None: """Affichage du texte de fin""" min_size = max(button.size.x, button.size.y) font_size = min_size * 50 / 400 # Taille de la police Display.drawRect(Vect2d(0, 0), Display.size, (0, 0, 0, button.alpha)) # Fondu transparent if button.alpha < 127: # Si le jeu est en cours on a un fondu jusqu'à 50% button.alpha += 1 elif button.alpha < 255 and Map.game_finished: # Sinon le fondu se fait jusqu'à 100% button.alpha += 1 Display.drawText(button.text, button.pos + button.size / 2, color=button.color, size=font_size)
def buttonStart_Display(button: Button, mouse_pos: Vect2d) -> bool: """Affichage du bouton Start Args: button (Button): bouton start mouse_pos (Vect2d): position de la souris Returns: hand_cursor (bool): si la souris doit être affichée comme une main ou un curseur """ if button.isMouseOver(mouse_pos): # Arc-en-ciel hand_cursor = True button.color_sat = (button.color_sat - 3 + 100) % 100 else: # Flash épileptique hand_cursor = False button.color_sat = 100 button.color_hue = (button.color_hue + 1) % 360 button_color = Color.HSVToRGB(button.color_hue, button.color_sat, 100) min_size = max(button.size.x, button.size.y) # Taille minimale entre la largeur et la hauteur font_size = min_size * 50 / 400 Display.drawRect(button.pos, button.size, color=button_color, fill=True) # Rectangle du bouton Display.drawText(button.text, button.pos + button.size / 2, color=Color.BLACK, size=font_size) # Texte du bouton return hand_cursor
def buttonEndChoice_Display(button: Button, mouse_pos: Vect2d) -> bool: """Affichage du bouton rejouer""" min_size = max(button.size.x, button.size.y) font_size = min_size * 50 / 400 if button.isMouseOver(mouse_pos): hand_cursor = True c = Color.BLACK f = True else: hand_cursor = False c = button.color f = False Display.drawRect(button.pos, button.size, color=button.color, fill=f) Display.drawText(button.text, button.pos + button.size / 2, color=c, size=font_size) return hand_cursor
def display(self) -> None: """Affichage du buisson""" c = Color.linearGradient(Color.BUSH_COLOR_FULL, Color.BUSH_COLOR_DEAD, 1-(self.health-1)/(Bush.BASE_HEALTH-1)) for i in range(self.health): # Les pics du buisson angle = i/self.health*2*math.pi + self.angle offset = Vect2d(math.cos(angle), math.sin(angle))*Bush.RADIUS*(1+Bush.SHARPNESS/3) Display.drawTriangle(pos=self.pos + offset, color=c, radius=Bush.RADIUS*Bush.SHARPNESS, angle=2*math.pi/self.health*i + self.angle, base_pos=Camera.pos) # Le cercle du buisson Display.drawCircle(pos=self.pos, color=c, radius=Bush.RADIUS, base_pos=Camera.pos)
def display(self) -> None: """Permet d'afficher la créature""" if Creature.ALLOW_SKINS: Display.drawImg(img=self.img, pos=self.pos, radius=self.radius, base_pos=Camera.pos) else: Display.drawCircle(pos=self.pos, color=self.color, radius=self.radius, base_pos=Camera.pos) Display.drawText(text=self.name, size=self.radius*0.75, color=self.opposite_color, pos=self.pos, base_pos=Camera.pos)
# Fenêtre from view.camera import Camera # Caméra from view.skins import Skins # Skins pygame.init() # Initialisation de pygame Camera.init() # Initialisation de la caméra Display.init(width=config.WINDOW_WIDTH, height=config.WINDOW_HEIGHT, framerate=config.FRAMERATE) # Initialisation de la fenêtre Menu.init() # Initialisation du menu Skins.init() # Initialisation et chargement des skins Map.init(width=config.MAP_WIDTH, height=config.MAP_HEIGHT) # Initialisation du terrain de jeu Game.run() # Lancement du jeu
def run(cls) -> None: """Méthode principale permettant de faire tourner le jeu""" cls.finished = False cls.keytime = {} cls.state = GameState.MENU while not cls.finished: cls.ESC_MAX_FRAMECOUNT = Display.real_framerate * 0.25 # On veut quitter après 0.25 secondes cls.handleKeys() mx, my = pygame.mouse.get_pos() mouse_pos = Vect2d(mx, my) # Position de la souris mouse_pressed = pygame.mouse.get_pressed()[0] # Clic ou non Menu.state = GameState.MENU if cls.state == GameState.MENU: # Affichage du menu Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: # Si l'on veut rejouer cls.state = GameState.GAME if Menu.can_quit: # Si l'on veut quitter cls.finished = True Menu.display() if Menu.can_play: # Si l'on veut rejouer on remet le curseur normal Display.setCursorArrow() elif cls.state == GameState.END: # Partie perdue Menu.update(mouse_pos, mouse_pressed) if not Map.game_finished: # On update la map tant que la partie n'est pas terminée pour de bon # afin de faire jouer les IA Map.update() if Menu.can_play: cls.state = GameState.GAME if Menu.can_quit: cls.finished = True Map.display() Menu.display() # Affichage du menu et de l'effet de transparence au dessus de la map if Menu.can_play: Display.setCursorArrow() elif cls.state == GameState.WIN: # Victoire Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: cls.state = GameState.GAME if Menu.can_quit: cls.finished = True Menu.display() if Menu.can_play: Display.setCursorArrow() elif cls.state == GameState.GAME: # Jeu en cours Map.setMousePos(mouse_pos / Display.zoom_factor) # On envoie la position de la souris à la map Map.update() Map.display() if Map.isPlayerAlive(): if Map.game_finished: cls.state = GameState.WIN Menu.applyState(GameState.WIN) else: cls.state = GameState.END Menu.applyState(GameState.END) else: raise ValueError("État inconnu") alpha = cls.keytime.get(pygame.K_ESCAPE, 0) / cls.ESC_MAX_FRAMECOUNT * 255 Display.drawText("Quitter...", Vect2d(50, 25), color=(255, 0, 0, alpha), size=16, base_pos=Vect2d(0, 0)) # Affichage du "Quitter" rouge en haut à gauche proportionnellement au temps d'appui de la touche ESC Display.updateFrame()
def freezeFrame(self): while True: keys = Display.getKeys() if 'q' in keys: return Display.graphicsSleep(0.1)
def display(cls): """Affichage de la map""" w = cls.size.x h = cls.size.y for x in range(1, cls.grid_size.x): # Lignes entre la grille Display.drawLine(Vect2d(x * w / cls.grid_size.x, 0), Vect2d(x * w / cls.grid_size.x, h), color=Color.DARK_GRAY, base_pos=Camera.pos) for y in range(1, cls.grid_size.y): Display.drawLine(Vect2d(0, y * h / cls.grid_size.y), Vect2d(w, y * h / cls.grid_size.y), color=Color.DARK_GRAY, base_pos=Camera.pos) Display.drawLine(Vect2d(0, 0), Vect2d(w, 0), color=Color.RED, base_pos=Camera.pos) Display.drawLine(Vect2d(w, 0), Vect2d(w, h), color=Color.RED, base_pos=Camera.pos) Display.drawLine(Vect2d(w, h), Vect2d(0, h), color=Color.RED, base_pos=Camera.pos) Display.drawLine(Vect2d(0, h), Vect2d(0, 0), color=Color.RED, base_pos=Camera.pos) cls.displayCell() for k in cls.creatures.keys(): enemy_list = cls.creatures[k] if k != cls.player_id: for enemy in enemy_list: enemy.display() if cls.isPlayerAlive(): for player in cls.creatures[cls.player_id]: player.display() for i in range(len(cls.bushes)): cls.bushes[i].display() x = Display.size.x / 2 y = Display.size.y / 2 r = min(x, y) / 50 Display.drawLine(Vect2d(x - r, y - r), Vect2d(x + r, y + r), color=Color.RED) Display.drawLine(Vect2d(x - r, y + r), Vect2d(x + r, y - r), color=Color.RED) Camera.setPos(cls.getFocusedPos()) r = cls.getFocusedRadius() - Creature.BASE_RADIUS r = abs(r) r = r**0.1 z = math.exp(-r + 1) Display.zoom(z)
def init(cls) -> None: """Initialisation""" cls.applyState(GameState.MENU) Display.execWhenResized(cls.createButtons)
def moveCarDisplay(self, car, deltaPos, deltaAngle): start = time.time() Display.move(car, deltaPos) Display.rotate(car, deltaAngle) self.drawTime += time.time() - start
def play(cls) -> None: """Lorsqu'un bouton pour rejouer est cliqué""" Display.setCursorArrow() Map.reset() cls.can_play = True