def shot(self, file): """ shot(file) -> None Salva o último frame renderizado no disco. O argumento "file" é o nome do arquivo onde os dados serão despejados. A extensão de arquivo precisa estar presente. As extensões válidas são: ".bmp", ".tga", ".png" e ".jpeg". """ if not mindu.loop._running: raise mindu.Error( 'shot(): método chamado com o loop interno do Mindu parado') if not isinstance(file, str): raise TypeError('shot(): o argumento "file" precisa ser string') ext = os.path.splitext(file)[1] if ext.upper() not in ('.BMP', '.TGA', '.PNG', '.JPEG'): raise ValueError( 'shot(): extensão de arquivo inválida: "{}"'.format(ext)) try: pygame.image.save(self._last_surf, file) except: raise mindu.Error( 'shot(): impossível despejar dados em "{}"'.format(file))
def __init__(self, file): if not isinstance(file, str): raise TypeError('Sound(): o argumento "file" precisa ser string') if not os.path.exists(file): raise mindu.Error( 'Sound(): impossível carregar o arquivo "{}"'.format(file)) if not os.path.isfile(file): raise mindu.Error( 'Sound(): impossível carregar o arquivo "{}"'.format(file)) if os.path.splitext(file)[1].upper() not in ('.OGG', '.WAV'): raise mindu.Error( 'Sound(): o formato do arquivo de som precisa ser OGG ou WAV') try: self._pygame_sound = PygameSound(file) except: raise mindu.Error( 'Sound(): impossível carregar o arquivo "{}"'.format(file)) self._pygame_sound._mindu_sound = self
def set_font(self, font): """ set_font(font) -> None Define a fonte do rótulo. O argumento "font" é uma string representando o nome do arquivo de fonte a ser carregado. O único formato de arquivo de fonte suportado é o TTF. Este argumento também pode ser None, para que a fonte padrão seja utilizada. """ if (font is not None) and (not isinstance(font, str)): raise TypeError( 'set_font(): o argumento "font" precisa ser string ou None') try: pygame_font = pygame.font.Font(font, self._size) except: raise mindu.Error( 'set_font(): impossível carregar o arquivo "{}"'.format(font)) self._font = font self._pygame_font = pygame_font self._pygame_font.set_italic(self._italic) self._pygame_font.set_bold(self._bold) self._pygame_font.set_underline(self._underline) self._render()
def stop(self): """ stop() -> None Interrompe o loop. """ if not self._running: raise mindu.Error('stop(): método chamado com o loop já parado') raise Stop()
def play(self, sound, loops = 0, maxtime = 0, fadein = 0): """ play(sound, loops = 0, maxtime = 0, fadein = 0) -> None Inicia a reprodução de som no canal. O argumento "sound" é um objeto Sound, representando o som a ser reproduzido. O argumento "loops" é um inteiro representando quantas vezes o som deve se repetir automaticamente depois de tocar a primeira vez. Por exemplo, 1 fará com que o som seja reproduzido 2 vezes ao todo. Para que o som se repita indefinidamente, use -1. O argumento "maxtime" é um inteiro indicando após quantos milissegundos o som deve ser interrompido automaticamente. Se for 0, o som será reproduzido até o fim. O argumento "fadein" é um inteiro representando quantos milissegundos deve levar para o volume total ser atingido na reprodução do som, iniciando em mudo. Se for 0, por exemplo, a reprodução já inicia no volume total; se for 1000, a reprodução começa no mudo e o volume é aumentado automaticamente e de forma gradual, de modo que em 1000 milissegundos o volume total é atingido. """ if not mindu.loop._running: raise mindu.Error('play(): método chamado com o loop interno do Mindu parado') if not isinstance(sound, mindu.Sound): raise TypeError('play(): o argumento "sound" precisa ser um objeto Sound') if not isinstance(loops, int): raise TypeError('play(): o argumento "loops" precisa ser inteiro') if loops < -1: raise ValueError('play(): o argumento "loops" precisa ser maior ou igual a -1') if not isinstance(maxtime, int): raise TypeError('play(): o argumento "maxtime" precisa ser inteiro') if maxtime < 0: raise ValueError('play(): o argumento "maxtime" precisa ser maior ou igual a 0') if not isinstance(fadein, int): raise TypeError('play(): o argumento "fadein" precisa ser inteiro') if fadein < 0: raise ValueError('play(): o argumento "fadein" precisa ser maior ou igual a 0') self._pygame_channel.play(sound._pygame_sound, loops, maxtime, fadein)
def get_replay(self): """ get_replay() -> Animation Obtém os últimos N quadros renderizados como uma animação de replay. Use os métodos get_replay_length() e set_replay_length() para consultar e definir o comprimento do replay. """ if not mindu.loop._running: raise mindu.Error( 'get_replay(): método chamado com o loop interno do Mindu parado' ) if not self._replay: raise mindu.Error('get_replay(): nenhum frame no histórico') animation = object.__new__(mindu.Animation) animation._surfs = self._replay[:] animation._rects = [surf.get_rect() for surf in animation._surfs] animation._redraw = 1 animation._anchor = 'midbottom' animation._repeat = True animation._running = True animation._osd = False animation._redraw_count = 0 animation._index = 0 animation._limit = len(animation._surfs) animation._surf = animation._surfs[animation._index] animation._rect = animation._rects[animation._index] return animation
def draw(self): """ draw() -> None Desenha o sprite na tela. """ if not mindu.loop._running: raise mindu.Error( 'draw(): método chamado com o loop interno do Mindu parado') if self._osd: mindu.screen._osd.append((self._surf, self._rect)) else: mindu.screen._surf.blit(self._surf, self._rect)
def get_last_frame(self): """ get_last_frame() -> Image Obtém o último quadro renderizado como uma imagem. """ if not mindu.loop._running: raise mindu.Error( 'get_last_frame(): método chamado com o loop interno do Mindu parado' ) image = object.__new__(mindu.Image) image._surf = self._last_surf image._rect = image._surf.get_rect() image._osd = False return image
def queue(self, sound): """ queue(sound) -> None Coloca um som na fila de reprodução do canal. O som será reproduzido automaticamente assim que a reprodução atual chegar ao fim. O argumento "sound" é um objeto Sound representando o som a ser enfileirado. """ if not mindu.loop._running: raise mindu.Error('queue(): método chamado com o loop interno do Mindu parado') if not isinstance(sound, mindu.Sound): raise TypeError('queue(): o argumento "sound" precisa ser um objeto Sound') self._pygame_channel.queue(sound._pygame_sound)
def start(self): """ start() -> None Inicia o loop. """ if self._running: raise mindu.Error('start(): método chamado com o loop já rodando') self._running = True tick = pygame.time.Clock().tick mindu.screen._create() try: while True: mindu.keyboard._update() mindu.mouse._update() pygame.event.get(pygame.JOYAXISMOTION) pygame.event.get(pygame.JOYHATMOTION) pygame.event.get(pygame.JOYBUTTONUP) pygame.event.get(pygame.JOYBUTTONDOWN) for joystick in mindu.joysticks: joystick._update() if self._on_iterate is not None: self._on_iterate(*self._on_iterate_pargs, **self._on_iterate_kwargs) mindu.screen._update() tick(self._ips) except Stop: pass finally: mindu.screen._destroy() pygame.mixer.stop() self._running = False
def __init__(self, file, alpha = True, osd = False, **position): if not isinstance(file, str): raise TypeError('Image(): o argumento "file" precisa ser string') try: surface = pygame.image.load(file) except: raise mindu.Error('Image(): impossível carregar o arquivo "{}"'.format(file)) if not isinstance(alpha, bool): raise TypeError('Image(): o argumento "alpha" precisa ser True ou False') if not isinstance(osd, bool): raise TypeError('Image(): o argumento "osd" precisa ser True ou False') if alpha: surf = pygame.Surface(surface.get_size(), pygame.SRCALPHA) else: surf = pygame.Surface(surface.get_size()) surf.blit(surface, (0, 0)) self._surf = surf self._rect = surf.get_rect() self._osd = osd for (key, value) in position.items(): if key not in ('top', 'left', 'bottom', 'right', 'topleft', 'bottomleft', 'topright', 'bottomright', 'midtop', 'midleft', 'midbottom', 'midright', 'center', 'centerx', 'centery'): raise KeyError('Image(): argumento de palavra-chave inválido: "{}"'.format(key)) setattr(self, key, value)
def __init__(self, text, font=None, size=30, color=(1.0, 1.0, 1.0, 1.0), alignment='left', italic=False, bold=False, underline=False, osd=False, **position): if not isinstance(text, str): raise TypeError('Label(): o argumento "text" precisa ser string') if not isinstance(size, int): raise TypeError('Label(): o argumento "size" precisa ser inteiro') if size <= 0: raise ValueError( 'Label(): o argumento "size" precisa ser maior que 0') if (font is not None) and (not isinstance(font, str)): raise TypeError( 'Label(): o argumento "font" precisa ser string ou None') try: pygame_font = pygame.font.Font(font, size) except: raise mindu.Error( 'Label(): impossível carregar o arquivo "{}"'.format(font)) if not isinstance(color, (list, tuple)): raise TypeError( 'Label(): o argumento "color" precisa ser lista ou tupla') if len(color) != 4: raise ValueError( 'Label(): o argumento "color" precisa ter comprimento 4') (r, g, b, a) = color if not isinstance(r, float): raise TypeError( 'Label(): o primeiro item do argumento "color" precisa ser float' ) if not isinstance(g, float): raise TypeError( 'Label(): o segundo item do argumento "color" precisa ser float' ) if not isinstance(b, float): raise TypeError( 'Label(): o terceiro item do argumento "color" precisa ser float' ) if not isinstance(a, float): raise TypeError( 'Label(): o quarto item do argumento "color" precisa ser float' ) if r > 1.0: r = 1.0 elif r < 0.0: r = 0.0 if g > 1.0: g = 1.0 elif g < 0.0: g = 0.0 if b > 1.0: b = 1.0 elif b < 0.0: b = 0.0 if a > 1.0: a = 1.0 elif a < 0.0: a = 0.0 color = (r, g, b, a) r = int(r * 255) g = int(g * 255) b = int(b * 255) a = int(a * 255) ints_color = (r, g, b, a) if not isinstance(alignment, str): raise TypeError( 'Label(): o argumento "alignment" precisa ser string') if alignment not in ('left', 'center', 'right'): raise ValueError( 'Label(): o argumento "alignment" precisa ser "left", "center" ou "right"' ) if not isinstance(italic, bool): raise TypeError( 'Label(): o argumento "italic" precisa ser True ou False') if not isinstance(bold, bool): raise TypeError( 'Label(): o argumento "bold" precisa ser True ou False') if not isinstance(underline, bool): raise TypeError( 'Label(): o argumento "underline" precisa ser True ou False') if not isinstance(osd, bool): raise TypeError( 'Label(): o argumento "osd" precisa ser True ou False') self._text = text self._font = font self._pygame_font = pygame_font self._size = size self._color = color self._ints_color = ints_color self._alignment = alignment self._italic = italic self._bold = bold self._underline = underline self._osd = osd self._pygame_font.set_italic(self._italic) self._pygame_font.set_bold(self._bold) self._pygame_font.set_underline(self._underline) self._surf = None self._rect = None self._render() for (key, value) in position.items(): if key not in ('top', 'left', 'bottom', 'right', 'topleft', 'bottomleft', 'topright', 'bottomright', 'midtop', 'midleft', 'midbottom', 'midright', 'center', 'centerx', 'centery'): raise KeyError( 'Label(): argumento de palavra-chave inválido: "{}"'. format(key)) setattr(self, key, value)
def set_size(self, size): """ set_size(size) -> None Define as dimensões da tela. O argumento "size" é um par de inteiros (w, h) representando a largura e a altura da tela. """ if mindu.loop._running: raise mindu.Error( 'set_size(): método chamado com o loop interno do Mindu rodando' ) if not isinstance(size, (list, tuple)): raise TypeError( 'set_size(): o argumento "size" precisa ser lista ou tupla') if len(size) != 2: raise ValueError( 'set_size(): o argumento "size" precisa ter comprimento 2') (w, h) = size if not isinstance(w, int): raise TypeError( 'set_size(): o primeiro item do argumento "size" precisa ser inteiro' ) if not isinstance(h, int): raise TypeError( 'set_size(): o segundo item do argumento "size" precisa ser inteiro' ) if w <= 0: raise ValueError( 'set_size(): o primeiro item do argumento "size" precis ser maior que 0' ) if h <= 0: raise ValueError( 'set_size(): o segundo item do argumento "size" precis ser maior que 0' ) self._size = tuple(size) self._rect = pygame.Rect(0, 0, self._size[0], self._size[1]) self._zoom_rect = self._rect.copy() zoom = 1.0 - self._zoom width = int(zoom * self._rect.width) or 1 height = int(zoom * self._rect.height) or 1 center = self._zoom_rect.center self._zoom_rect = pygame.Rect(0, 0, width, height) self._zoom_rect.center = center self._bright_surf = pygame.Surface(self._size) bright = 255 - int(self._bright * 255) self._bright_surf.set_alpha(bright, pygame.RLEACCEL) self._subtraction_surf = pygame.Surface(self._size) red = 255 - int(self._red * 255) green = 255 - int(self._green * 255) blue = 255 - int(self._blue * 255) self._subtraction_surf.fill((red, green, blue))
def __init__(self, directory, alpha=True, redraw=1, anchor="midbottom", repeat=True, running=True, osd=False, **position): if not isinstance(alpha, bool): raise TypeError( 'Animation(): o argumento "alpha" precisa ser True ou False') if not isinstance(directory, str): raise TypeError( 'Animation(): o argumento "directory" precisa ser string') if not os.path.exists(directory): raise mindu.Error( 'Animation(): o diretório "{}" não existe'.format(directory)) if not os.path.isdir(directory): raise mindu.Error( 'Animation(): "{}" não é um diretório'.format(directory)) files = [ os.path.join(directory, file) for file in os.listdir(directory) ] if not files: raise mindu.Error( 'Animation(): o diretório "{}" está vazio'.format(directory)) files.sort() self._surfs = [] for file in files: try: surface = pygame.image.load(file) except: raise mindu.Error( 'Animation(): impossível carregar o arquivo "{}"'.format( file)) if alpha: surf = pygame.Surface(surface.get_size(), pygame.SRCALPHA) else: surf = pygame.Surface(surface.get_size()) surf.blit(surface, (0, 0)) self._surfs.append(surf) if not isinstance(redraw, int): raise TypeError( 'Animation(): o argumento "redraw" precisa ser inteiro') if redraw <= 0: raise ValueError( 'Animation(): o argumento "redraw" precisa ser maior que 0') if not isinstance(anchor, str): raise TypeError( 'Animation(): o argumento "anchor" precisa ser string') if anchor not in ('top', 'left', 'bottom', 'right', 'centerx', 'centery', 'topleft', 'bottomleft', 'topright', 'bottomright', 'midtop', 'midleft', 'midbottom', 'midright', 'center'): raise ValueError( 'Animation(): valor inválido para o argumento "anchor": "{}"'. format(anchor)) if not isinstance(repeat, bool): raise TypeError( 'Animation(): o argumento "repeat" precisa ser True ou False') if not isinstance(running, bool): raise TypeError( 'Animation(): o argumento "running" precisa ser True ou False') if not isinstance(osd, bool): raise TypeError( 'Animation(): o argumento "osd" precisa ser True ou False') self._rects = [surf.get_rect() for surf in self._surfs] self._redraw = redraw self._anchor = anchor self._repeat = repeat self._running = running self._osd = osd self._redraw_count = 0 self._index = 0 self._limit = len(self._surfs) self._surf = self._surfs[self._index] self._rect = self._rects[self._index] for (key, value) in position.items(): if key not in ('top', 'left', 'bottom', 'right', 'topleft', 'bottomleft', 'topright', 'bottomright', 'midtop', 'midleft', 'midbottom', 'midright', 'center', 'centerx', 'centery'): raise KeyError( 'Animation(): argumento de palavra-chave inválido: "{}"'. format(key)) setattr(self, key, value)