From f49eff21df9c4b65656e2abe6c54cee6c25089e4 Mon Sep 17 00:00:00 2001 From: Tipragot Date: Sun, 5 Nov 2023 08:52:03 +0100 Subject: [PATCH] Fix dialogs --- src/plugins/dialog.py | 60 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/src/plugins/dialog.py b/src/plugins/dialog.py index aa2d500..e099b19 100644 --- a/src/plugins/dialog.py +++ b/src/plugins/dialog.py @@ -5,29 +5,81 @@ Un plugin permettant de gérer l'affichage et l'audio des dialogues. import json import random +from typing import Callable import pygame -from engine.ecs import World +from engine.ecs import Entity, World from engine.math import Vec2 from plugins import render +from plugins.coroutine import wait # from plugins.assets import Assets from plugins.sound import Sound from plugins.text import Text -def spawn_dialog(world: World, name: str, index: int = -1, height: float = 100): +def __spawn_all_condition(entity: Entity) -> Callable[[World], bool]: + """ + Condition utilisé dans spawn_all_dialogs + """ + return lambda world: Text not in entity + + +def spawn_all_dialogs( + world: World, + name: str, + height: float = 100, + waiting_between: float = 1, + callback: Callable[[World], object] = lambda _w: None, +): + """ + Fais apparaitre tous les dialogues d'un info.json a la suite. + """ + texts: list[str] = json.load( + open(f"assets/dialogs/{name}/info.json", "r", encoding="utf-8") + ) + for i, text in enumerate(texts): + entity = world.new_entity() + entity.set( + Sound( + pygame.mixer.Sound(f"assets/dialogs/{name}/{i}.mp3"), + callback=lambda world, entity: entity.destroy(), + ), + Text(text, position=Vec2(render.WIDTH / 2, height), origin=Vec2(0.5)), + ) + yield __spawn_all_condition(entity) + yield wait(waiting_between) + callback(world) + + +def spawn_dialog( + world: World, + name: str, + index: int = -1, + height: float = 100, + callback: Callable[[World], object] = lambda _w: None, +): """ Fait apparaitre un dialogue dans le monde. """ texts: list[str] = json.load( open(f"assets/dialogs/{name}/info.json", "r", encoding="utf-8") ) - text = random.choice(texts) if index == -1 else texts[index] + if index == -1: + index = random.randint(0, len(texts) - 1) + text = texts[index] world.new_entity().set( Sound( pygame.mixer.Sound(f"assets/dialogs/{name}/{index}.mp3"), - callback=lambda world, entity: entity.destroy(), + callback=lambda world, entity: __sound_end(world, entity, callback), ), Text(text, position=Vec2(render.WIDTH / 2, height), origin=Vec2(0.5)), ) + + +def __sound_end(world: World, entity: Entity, callback: Callable[[World], object]): + """ + Fonction appelé a la fin d'un dialogue. + """ + entity.destroy() + callback(world)