diff options
author | flavio <fdanesse@gmail.com> | 2014-08-02 15:02:20 (GMT) |
---|---|---|
committer | flavio <fdanesse@gmail.com> | 2014-08-02 15:02:20 (GMT) |
commit | ec8313ead62cd5607b1e5a54c8a46c91ded58ded (patch) | |
tree | 5ce7dd837c187bdf8c08d6c1d26291d80e5df9ae | |
parent | 26123ea12af4eb9037c4ee05c64079e40627a50f (diff) |
-rw-r--r-- | JAMButton.py | 1202 | ||||
-rw-r--r-- | JAMGlobals.py | 746 | ||||
-rw-r--r-- | JAMLabel.py | 803 |
3 files changed, 1583 insertions, 1168 deletions
diff --git a/JAMButton.py b/JAMButton.py index bd5666e..7425537 100644 --- a/JAMButton.py +++ b/JAMButton.py @@ -3,555 +3,673 @@ import pygame import gc -import sys -from pygame.locals import * +#from pygame.locals import * gc.enable() import JAMGlobals as VG from JAMLabel import JAMLabel + class JAMButton(pygame.sprite.Sprite): - def __init__(self, texto, imagen, tipo="rectangulo"): - pygame.sprite.Sprite.__init__(self) - - self.image= None - self.rect= None - self.posicion= (0,0) - self.select= False - self.sonido_select= VG.get_sound_select() - self.callback= None - self.alineacion= "centro" - self.tipo = tipo - - COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR= VG.get_default_jambutton_values() - - self.base= {"tamanio":None, "colorbas":COLORBAS, "colorbor":COLORBOR, "grosorbor":GROSORBOR, "detalle":DETALLE, "espesor":ESPESOR} - self.cara= {"tamanio":None, "color":COLORCARA} - self.borde_label= {"grosor": 0, "color":VG.get_negro()} - - self.etiqueta_unselect= JAMLabel(texto) - self.etiqueta_unselect.set_contenedor(colorbas=self.cara["color"]) - self.etiqueta_select= JAMLabel(texto) - self.etiqueta_select.set_contenedor(colorbas=self.base["colorbor"]) - - self.JAMObjects = {"JAMLabelunselect": self.etiqueta_unselect, "JAMLabelselect": self.etiqueta_select, "Base": self.base, "Cara": self.cara, "Borde": self.borde_label} - - self.imagen_cara_unselect= None - self.imagen_cara_select= None - self.final_unselect= None - self.final_select= None - - self.Reconstruye_JAMButton(["texto"]) - - # ---------- SETEOS Y GET GENERALES ---------- # - def get_text(self): - ''' Devuelve la cadena de Texto en JAMLabel. ''' - return self.etiqueta_unselect.get_text() - - def set_tipo(self, tipo): - ''' Setea el tipo de botón "elipse" o "rectangulo". ''' - if tipo and tipo != self.tipo and (tipo== "elipse" or tipo== "rectangulo"): - self.tipo= tipo - self.Reconstruye_JAMButton(["texto"]) - - def get_posicion(self): - ''' Devuelve la posición actual. ''' - return self.posicion - - # ---------- SETEOS SOBRE LA ETIQUETA ---------- # - def set_text(self, tipo=None, tamanio=None, color=None, texto=None): - ''' Setea el Texto en JAMLabel. ''' - self.etiqueta_unselect.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=texto) - self.etiqueta_select.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=texto) - self.Reconstruye_JAMButton(["texto"]) - - def set_font_from_file(self, direccion_archivo, tamanio= None): - ''' Setea la fuente desde un archivo en JAMLabel. ''' - self.etiqueta_unselect.set_font_from_file(direccion_archivo, tamanio) - self.etiqueta_select.set_font_from_file(direccion_archivo, tamanio) - self.Reconstruye_JAMButton(["texto"]) - - def set_imagen(self, origen=None, tamanio=None): - ''' Setea el Imagen en JAMLabel. ''' - self.etiqueta_unselect.set_imagen(origen=origen, tamanio=tamanio) - self.etiqueta_select.set_imagen(origen=origen, tamanio=tamanio) - self.Reconstruye_JAMButton(["imagen"]) - # ---------- SETEOS SOBRE LA ETIQUETA ---------- # - - # ---------- SETEOS SOBRE LA BASE ---------- # - def set_tamanios(self, tamanio=None, grosorbor=None, detalle=None, espesor=None): - cambios= False - # desactivar tamaños - if tamanio == -1 and tamanio != None: - tamanio= None - self.base["tamanio"]= None - cambios= True - if grosorbor == -1 and grosorbor != None: - grosorbor= None - self.base["grosorbor"]= 1 - cambios= True - if detalle == -1 and detalle != None: - detalle= None - self.base["detalle"]= 1 - cambios= True - if espesor == -1 and espesor != None: - espesor= None - self.base["espesor"]= 1 - cambios= True - - # establecer tamaños - if tamanio and tamanio != self.base["tamanio"]: - self.base["tamanio"]= tamanio - cambios= True - if grosorbor and grosorbor != self.base["grosorbor"]: - self.base["grosorbor"]= grosorbor - cambios= True - if detalle and detalle != self.base["detalle"]: - self.base["detalle"]= detalle - cambios= True - if espesor and espesor != self.base["espesor"]: - self.base["espesor"]= espesor - cambios= True - - if cambios: - self.Reconstruye_JAMButton(["tamanio"]) - - def set_colores(self, colorbas=None, colorbor=None, colorcara=None): - ''' Setea los colores del botón y la etiqueta. ''' - cambios= False - if colorbas and colorbas != self.base["colorbas"]: - self.base["colorbas"]= colorbas - cambios= True - if colorbor and colorbor != self.base["colorbor"]: - self.base["colorbor"]= colorbor - cambios= True - if colorcara and colorcara != self.cara["color"]: - self.cara["color"]= colorcara - cambios= True - - if cambios: - self.etiqueta_unselect.set_contenedor(colorbas=self.cara["color"])#, grosor=None, colorbor=None) - self.etiqueta_select.set_contenedor(colorbas=self.base["colorbor"])#, grosor=None, colorbor=None) - self.Reconstruye_JAMButton(["colores"]) - - def set_borde_label(self, grosor=None, color=None): - ''' Agrega o quita un borde sobre la cara de JAMButton. ''' - cambios= False - if grosor < 1 and grosor != self.borde_label["grosor"]: - grosor= None - cambios= True - if grosor and grosor != self.borde_label["grosor"]: - self.borde_label["grosor"]= grosor - cambios= True - if color and color != self.borde_label["color"]: - self.borde_label["color"]= color - cambios= True - - if cambios: - self.Reconstruye_JAMButton(["borde"]) - - def set_alineacion_label(self, alineacion): - ''' Setea la alineacion de JAMLabel sobre la cara de JAMButton. ''' - if alineacion == "centro" or alineacion == "izquierda" or alineacion == "derecha": - self.alineacion= alineacion - self.Reconstruye_JAMButton(["alineacion"]) - # ---------- SETEOS SOBRE LA BASE ---------- # - - def connect(self, callback=None, sonido_select=None): - '''Conecta el botón a una función y un sonido para reproducir al hacer click sobre JAMButton. ''' - self.callback = callback - self.sonido_select = sonido_select # debes pasar una referencia al audio ya cargado para no cargarlo cada vez que creas un botón - - def set_posicion(self, punto=None): - ''' Setea la posición de JAMButton en la pantalla. ''' - try: - if punto: - self.rect.x, self.rect.y = (punto) - self.posicion = punto - except: - pass - - # ------------- GETS ------------------------ - def get_tamanio(self): - return (self.rect.w, self.rect.h) - - # ----------- CONSTRUCCION ------------------- - def Reconstruye_JAMButton(self, cambios): - ''' Cada vez que se setea algo, se reconstruye JAMButton con sus nuevos valores. ''' - if "tamanio" in cambios: - # reconstruye la cara en base a la etiqueta - self.cara["tamanio"]= None - self.imagen_cara_unselect, self.imagen_cara_select= self.construye_cara() - - # verifica tamaño minimo para la base según la cara reconstruida - anchominimo, altominimo= self.get_minimo_tamanio_base() - if not self.base["tamanio"]: self.base["tamanio"]= (anchominimo, altominimo) - ancho, alto= self.base["tamanio"] - if anchominimo > ancho: ancho= anchominimo - if altominimo > alto: alto= altominimo - - # Establece los nuevos tamaños - self.base["tamanio"]= (ancho, alto) - self.cara["tamanio"]= self.get_tamanio_cara_recalculado() - - self.imagen_cara_unselect, self.imagen_cara_select= self.construye_cara() # pegar la etiqueta sobre la cara (¿Alineaciones?) - self.final_unselect, self.final_select = self.construye_boton() # pegar la cara sobre la base - - self.image = self.final_unselect - self.rect = self.image.get_rect() - - self.set_posicion(self.posicion) # seteo automático de posición - - def get_minimo_tamanio_base(self): - ''' Devuelve el tamaño mínimo que puede tener la base del botón. ''' - x= self.base["grosorbor"] + int(self.base["espesor"]/3) - ancho= x + self.cara["tamanio"][0] + self.base["espesor"] + self.base["grosorbor"] - y= self.base["grosorbor"] + int(self.base["espesor"]/3) - alto= y + self.cara["tamanio"][1] + self.base["espesor"] + self.base["grosorbor"] - return (ancho, alto) - - def get_tamanio_cara_recalculado(self): - ''' Devuelve el tamaño que debe tener la cara luego de seteados los tamaños del JAMButton. ''' - tamanio= (0,0) - if self.tipo == "elipse": - (xx,yy,ss,zz)= self.etiqueta_unselect.rect - x= self.base["grosorbor"] + int(self.base["espesor"]/3)+zz/2 - ancho= x + self.base["espesor"] + self.base["grosorbor"]+zz/2 - y= self.base["grosorbor"] + int(self.base["espesor"]/3)+zz/2 - alto= y + self.base["espesor"] + self.base["grosorbor"]+zz/2 - a,h= self.base["tamanio"] - tamanio= (a- ancho, h -alto) - else: - x= self.base["grosorbor"] + int(self.base["espesor"]/3) - ancho= x + self.base["espesor"] + self.base["grosorbor"] - y= self.base["grosorbor"] + int(self.base["espesor"]/3) - alto= y + self.base["espesor"] + self.base["grosorbor"] - a,h= self.base["tamanio"] - tamanio= (a- ancho, h -alto) - return tamanio - - def construye_cara(self): - ''' Crea la cara del botón y pega centrado en ella el JAMLabel. ''' - unselect, select= (None, None) - if self.tipo == "elipse": - w, h= (0,0) - # toma tamaño de etiqueta como referencia - if not self.cara["tamanio"]: - w= self.etiqueta_unselect.rect.w+self.base["detalle"]+self.etiqueta_unselect.rect.h - h= self.etiqueta_unselect.rect.h+self.base["detalle"]+self.etiqueta_unselect.rect.h - self.cara["tamanio"] = (w, h) - # la cara nunca puede ser menor que la etiqueta pero si mayor - if self.cara["tamanio"] and self.cara["tamanio"][0]<self.etiqueta_unselect.rect.w+self.base["detalle"]+self.etiqueta_unselect.rect.h: - w= self.etiqueta_unselect.rect.w+self.base["detalle"]+self.etiqueta_unselect.rect.h - self.cara["tamanio"] = (w, h) - if self.cara["tamanio"] and self.cara["tamanio"][1]<self.etiqueta_unselect.rect.h+self.base["detalle"]+self.etiqueta_unselect.rect.h: - h= self.etiqueta_unselect.rect.h+self.base["detalle"]+self.etiqueta_unselect.rect.h - self.cara["tamanio"] = (w, h) - unselect= VG.get_Elipse(self.cara["color"], self.cara["tamanio"]) - select= VG.get_Elipse(self.base["colorbor"], self.cara["tamanio"]) - - # alineación desabilitada por bug - self.alineacion = "centro" - unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect) - select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select) - else: - w, h= (0,0) - # toma tamaño de etiqueta como referencia - if not self.cara["tamanio"]: - w= self.etiqueta_unselect.rect[2]+self.base["detalle"] - h= self.etiqueta_unselect.rect[3]+self.base["detalle"] - self.cara["tamanio"] = (w, h) - # la cara nunca puede ser menor que la etiqueta pero si mayor - if self.cara["tamanio"] and self.cara["tamanio"][0]<self.etiqueta_unselect.rect[2]+self.base["detalle"]: - w= self.etiqueta_unselect.rect[2]+self.base["detalle"] - self.cara["tamanio"] = (w, h) - if self.cara["tamanio"] and self.cara["tamanio"][1]<self.etiqueta_unselect.rect[3]+self.base["detalle"]: - h= self.etiqueta_unselect.rect[3]+self.base["detalle"] - self.cara["tamanio"] = (w, h) - unselect= VG.get_Rectangulo(self.cara["color"], self.cara["tamanio"]) - select= VG.get_Rectangulo(self.base["colorbor"], self.cara["tamanio"]) - - if self.alineacion == "centro": - unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect) - select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select) - elif self.alineacion == "izquierda": - unselect= VG.pegar_imagenes_alineado_izquierda(self.etiqueta_unselect.image, unselect) - select= VG.pegar_imagenes_alineado_izquierda(self.etiqueta_select.image, select) - elif self.alineacion == "derecha": - unselect= VG.pegar_imagenes_alineado_derecha(self.etiqueta_unselect.image, unselect) - select= VG.pegar_imagenes_alineado_derecha(self.etiqueta_select.image, select) - else: - self.alineacion = "centro" - unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect) - select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select) - - if self.borde_label["grosor"] > 1 and self.borde_label["grosor"] != None: - if not self.borde_label["color"]: self.borde_label["color"]= VG.get_negro() - if self.tipo == "elipse": - # desabilitado por bug - #unselect= VG.get_my_surface_whit_elipse_border(unselect, self.borde_label["color"], self.borde_label["grosor"]) - #select= VG.get_my_surface_whit_elipse_border(select, self.borde_label["color"], self.borde_label["grosor"]) - pass - else: - unselect= VG.get_my_surface_whit_border(unselect, self.borde_label["color"], self.borde_label["grosor"]) - select= VG.get_my_surface_whit_border(select, self.borde_label["color"], self.borde_label["grosor"]) - return unselect, select - - def construye_boton(self): - ''' Construye las imagenes finales del botón. ''' - unselect= None - select= None - if self.tipo == "elipse": - x= self.base["grosorbor"] + int(self.base["espesor"]/3) - ancho= x + self.cara["tamanio"][0] + self.base["espesor"] + self.base["grosorbor"] - y= self.base["grosorbor"] + int(self.base["espesor"]/3) - alto= y + self.cara["tamanio"][1] + self.base["espesor"] + self.base["grosorbor"] - self.base["tamanio"]= (ancho, alto) - unselect= VG.get_Elipse(self.base["colorbas"], self.base["tamanio"]) - unselect= VG.get_my_surface_whit_elipse_border(unselect, self.base["colorbor"], self.base["grosorbor"]) - select= VG.get_Elipse(self.base["colorbas"], self.base["tamanio"]) - select= VG.get_my_surface_whit_elipse_border(select, self.base["colorbor"], self.base["grosorbor"]) - else: - x= self.base["grosorbor"] + int(self.base["espesor"]/3) - ancho= x + self.cara["tamanio"][0] + self.base["espesor"] + self.base["grosorbor"] - y= self.base["grosorbor"] + int(self.base["espesor"]/3) - alto= y + self.cara["tamanio"][1] + self.base["espesor"] + self.base["grosorbor"] - self.base["tamanio"]= (ancho, alto) - unselect= VG.get_Rectangulo(self.base["colorbas"], self.base["tamanio"]) - unselect= VG.get_my_surface_whit_border(unselect, self.base["colorbor"], self.base["grosorbor"]) - select= VG.get_Rectangulo(self.base["colorbas"], self.base["tamanio"]) - select= VG.get_my_surface_whit_border(select, self.base["colorbor"], self.base["grosorbor"]) - - unselect.blit(self.imagen_cara_unselect, (x, y)) - select.blit(self.imagen_cara_select, (x, y)) - return unselect, select - # -------------------- FIN DE METODOS DE CONSTRUCCION -------------------- # - - # -------------------- INICIO DE METODOS INTERNOS AUTOMÁTICOS -------------------- # - def play_select(self): - # reproduce un sonido cuando pasas el mouse sobre el botón - if self.sonido_select: - self.sonido_select.play() - - def update(self): - # responde a los eventos del mouse sobre el sprite - ''' - posicion = pygame.mouse.get_pos() - # Selecciona el botón cuando el mouse pasa encima de él - if self.rect.collidepoint(posicion): - if self.select == False: - self.play_select() - self.image = self.final_select.copy() - self.select = True - - if pygame.event.get(pygame.MOUSEBUTTONDOWN): - if self.callback: - return self.callback(self) # modificación 29 de mayo el boton se pasa a si mismo. - else: - if self.select == True: - self.image = self.final_unselect.copy() - self.select = False''' - - ''' Reimplementación para Compatibilidad en Plug de gtk y mejora en rendimiento: - Los eventos se capturan por su tipo, se manejan y si es necesario se republican para habilitar la captura - de los mismos por parte de otros controles.''' - eventos_republicar= [] - eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN) - for event in eventos: - posicion = event.pos - if self.rect.collidepoint(posicion): - # Si el mouse está presionado sobre el botón. - if self.callback: - # y si además hay callback para esta acción. - pygame.event.clear() - return self.callback(self) - else: - # Si el mouse no está presionado sobre el botón. - if not event in eventos_republicar: eventos_republicar.append(event) - - eventos= pygame.event.get(pygame.MOUSEMOTION) - for event in eventos: - posicion = event.pos - if self.rect.collidepoint(posicion): - # Si el mouse está sobre el botón. - if self.select == False: - self.play_select() - self.image = self.final_select - self.select = True - else: - # Si el mouse no está sobre el botón. - if self.select == True: - self.image = self.final_unselect - self.select = False - if not event in eventos_republicar: eventos_republicar.append(event) - - for event in eventos_republicar: - # Se republican todos los eventos que este control no debe manejar. - pygame.event.post(event) - -# ----- FIN DE CLASE JAMButton - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- + + def __init__(self, texto, imagen, tipo="rectangulo"): + + pygame.sprite.Sprite.__init__(self) + + self.image = None + self.rect = None + self.posicion = (0, 0) + self.select = False + self.sonido_select = VG.get_sound_select() + self.callback = None + self.alineacion = "centro" + self.tipo = tipo + + vals = VG.get_default_jambutton_values() + COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR = vals + + self.base = { + "tamanio": None, "colorbas": COLORBAS, + "colorbor": COLORBOR, "grosorbor": GROSORBOR, + "detalle": DETALLE, "espesor": ESPESOR} + self.cara = {"tamanio": None, "color": COLORCARA} + self.borde_label = {"grosor": 0, "color": VG.get_negro()} + + self.etiqueta_unselect = JAMLabel(texto) + self.etiqueta_unselect.set_contenedor(colorbas=self.cara["color"]) + self.etiqueta_select = JAMLabel(texto) + self.etiqueta_select.set_contenedor(colorbas=self.base["colorbor"]) + + self.JAMObjects = { + "JAMLabelunselect": self.etiqueta_unselect, + "JAMLabelselect": self.etiqueta_select, + "Base": self.base, "Cara": self.cara, + "Borde": self.borde_label} + + self.imagen_cara_unselect = None + self.imagen_cara_select = None + self.final_unselect = None + self.final_select = None + + self.Reconstruye_JAMButton(["texto"]) + + # ---------- SETEOS Y GET GENERALES ---------- # + def get_text(self): + """ + Devuelve la cadena de Texto en JAMLabel. + """ + return self.etiqueta_unselect.get_text() + + def set_tipo(self, tipo): + """ + Setea el tipo de botón "elipse" o "rectangulo". + """ + if tipo and tipo != self.tipo and ( + tipo == "elipse" or tipo == "rectangulo"): + self.tipo = tipo + self.Reconstruye_JAMButton(["texto"]) + + def get_posicion(self): + """ + Devuelve la posición actual. + """ + return self.posicion + + # ---------- SETEOS SOBRE LA ETIQUETA ---------- # + def set_text(self, tipo=None, tamanio=None, color=None, texto=None): + """ + Setea el Texto en JAMLabel. + """ + self.etiqueta_unselect.set_text(tipo=tipo, + tamanio=tamanio, color=color, texto=texto) + self.etiqueta_select.set_text(tipo=tipo, + tamanio=tamanio, color=color, texto=texto) + self.Reconstruye_JAMButton(["texto"]) + + def set_font_from_file(self, direccion_archivo, tamanio=None): + """ + Setea la fuente desde un archivo en JAMLabel. + """ + self.etiqueta_unselect.set_font_from_file(direccion_archivo, tamanio) + self.etiqueta_select.set_font_from_file(direccion_archivo, tamanio) + self.Reconstruye_JAMButton(["texto"]) + + def set_imagen(self, origen=None, tamanio=None): + """ + Setea el Imagen en JAMLabel. + """ + self.etiqueta_unselect.set_imagen(origen=origen, tamanio=tamanio) + self.etiqueta_select.set_imagen(origen=origen, tamanio=tamanio) + self.Reconstruye_JAMButton(["imagen"]) + # ---------- SETEOS SOBRE LA ETIQUETA ---------- # + + # ---------- SETEOS SOBRE LA BASE ---------- # + def set_tamanios(self, tamanio=None, grosorbor=None, + detalle=None, espesor=None): + cambios = False + # desactivar tamaños + if tamanio == -1 and tamanio != None: + tamanio = None + self.base["tamanio"] = None + cambios = True + if grosorbor == -1 and grosorbor != None: + grosorbor = None + self.base["grosorbor"] = 1 + cambios = True + if detalle == -1 and detalle != None: + detalle = None + self.base["detalle"] = 1 + cambios = True + if espesor == -1 and espesor != None: + espesor = None + self.base["espesor"] = 1 + cambios = True + + # establecer tamaños + if tamanio and tamanio != self.base["tamanio"]: + self.base["tamanio"] = tamanio + cambios = True + if grosorbor and grosorbor != self.base["grosorbor"]: + self.base["grosorbor"] = grosorbor + cambios = True + if detalle and detalle != self.base["detalle"]: + self.base["detalle"] = detalle + cambios = True + if espesor and espesor != self.base["espesor"]: + self.base["espesor"] = espesor + cambios = True + + if cambios: + self.Reconstruye_JAMButton(["tamanio"]) + + def set_colores(self, colorbas=None, colorbor=None, colorcara=None): + """ + Setea los colores del botón y la etiqueta. + """ + cambios = False + if colorbas and colorbas != self.base["colorbas"]: + self.base["colorbas"] = colorbas + cambios = True + if colorbor and colorbor != self.base["colorbor"]: + self.base["colorbor"] = colorbor + cambios = True + if colorcara and colorcara != self.cara["color"]: + self.cara["color"] = colorcara + cambios = True + + if cambios: + self.etiqueta_unselect.set_contenedor( + colorbas=self.cara["color"]) + self.etiqueta_select.set_contenedor( + colorbas=self.base["colorbor"]) + self.Reconstruye_JAMButton(["colores"]) + + def set_borde_label(self, grosor=None, color=None): + """ + Agrega o quita un borde sobre la cara de JAMButton. + """ + cambios = False + if grosor < 1 and grosor != self.borde_label["grosor"]: + grosor = None + cambios = True + if grosor and grosor != self.borde_label["grosor"]: + self.borde_label["grosor"] = grosor + cambios = True + if color and color != self.borde_label["color"]: + self.borde_label["color"] = color + cambios = True + + if cambios: + self.Reconstruye_JAMButton(["borde"]) + + def set_alineacion_label(self, alineacion): + """ + Setea la alineacion de JAMLabel sobre la cara de JAMButton. + """ + if alineacion == "centro" or alineacion == "izquierda" or \ + alineacion == "derecha": + self.alineacion = alineacion + self.Reconstruye_JAMButton(["alineacion"]) + # ---------- SETEOS SOBRE LA BASE ---------- # + + def connect(self, callback=None, sonido_select=None): + """ + Conecta el botón a una función y un sonido para reproducir al + hacer click sobre JAMButton. + """ + self.callback = callback + self.sonido_select = sonido_select + # debes pasar una referencia al audio ya cargado para no cargarlo + # cada vez que creas un botón + + def set_posicion(self, punto=None): + """ + Setea la posición de JAMButton en la pantalla. + """ + try: + if punto: + self.rect.x, self.rect.y = (punto) + self.posicion = punto + except: + pass + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.rect.w, self.rect.h) + + # ----------- CONSTRUCCION ------------------- + def Reconstruye_JAMButton(self, cambios): + """ + Cada vez que se setea algo, se reconstruye JAMButton + con sus nuevos valores. + """ + if "tamanio" in cambios: + # reconstruye la cara en base a la etiqueta + self.cara["tamanio"] = None + dat = self.construye_cara() + self.imagen_cara_unselect, self.imagen_cara_select = dat + + # verifica tamaño minimo para la base según la cara reconstruida + anchominimo, altominimo = self.get_minimo_tamanio_base() + if not self.base["tamanio"]: + self.base["tamanio"] = (anchominimo, altominimo) + ancho, alto = self.base["tamanio"] + if anchominimo > ancho: + ancho = anchominimo + if altominimo > alto: + alto = altominimo + + # Establece los nuevos tamaños + self.base["tamanio"] = (ancho, alto) + self.cara["tamanio"] = self.get_tamanio_cara_recalculado() + + dat = self.construye_cara() + self.imagen_cara_unselect, self.imagen_cara_select = dat + self.final_unselect, self.final_select = self.construye_boton() + + self.image = self.final_unselect + self.rect = self.image.get_rect() + + self.set_posicion(self.posicion) + + def get_minimo_tamanio_base(self): + """ + Devuelve el tamaño mínimo que puede tener la base del botón. + """ + x = self.base["grosorbor"] + int(self.base["espesor"] / 3) + ancho = x + self.cara["tamanio"][0] + self.base[ + "espesor"] + self.base["grosorbor"] + y = self.base["grosorbor"] + int(self.base["espesor"] / 3) + alto = y + self.cara["tamanio"][1] + self.base[ + "espesor"] + self.base["grosorbor"] + return (ancho, alto) + + def get_tamanio_cara_recalculado(self): + """ + Devuelve el tamaño que debe tener la cara luego de seteados los + tamaños del JAMButton. + """ + tamanio = (0, 0) + if self.tipo == "elipse": + (xx, yy, ss, zz) = self.etiqueta_unselect.rect + x = self.base["grosorbor"] + int(self.base["espesor"] / 3) + zz / 2 + ancho = x + self.base["espesor"] + self.base["grosorbor"] + zz / 2 + y = self.base["grosorbor"] + int(self.base["espesor"] / 3) + zz / 2 + alto = y + self.base["espesor"] + self.base["grosorbor"] + zz / 2 + a, h = self.base["tamanio"] + tamanio = (a - ancho, h - alto) + else: + x = self.base["grosorbor"] + int(self.base["espesor"] / 3) + ancho = x + self.base["espesor"] + self.base["grosorbor"] + y = self.base["grosorbor"] + int(self.base["espesor"] / 3) + alto = y + self.base["espesor"] + self.base["grosorbor"] + a, h = self.base["tamanio"] + tamanio = (a - ancho, h - alto) + return tamanio + + def construye_cara(self): + """ + Crea la cara del botón y pega centrado en ella el JAMLabel. + """ + unselect, select = (None, None) + if self.tipo == "elipse": + w, h = (0, 0) + # toma tamaño de etiqueta como referencia + if not self.cara["tamanio"]: + w = self.etiqueta_unselect.rect.w + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h + h = self.etiqueta_unselect.rect.h + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h + self.cara["tamanio"] = (w, h) + # la cara nunca puede ser menor que la etiqueta pero si mayor + if self.cara["tamanio"] and self.cara[ + "tamanio"][0] < self.etiqueta_unselect.rect.w + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h: + w = self.etiqueta_unselect.rect.w + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h + self.cara["tamanio"] = (w, h) + if self.cara["tamanio"] and self.cara[ + "tamanio"][1] < self.etiqueta_unselect.rect.h + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h: + h = self.etiqueta_unselect.rect.h + self.base[ + "detalle"] + self.etiqueta_unselect.rect.h + self.cara["tamanio"] = (w, h) + unselect = VG.get_Elipse(self.cara["color"], self.cara["tamanio"]) + select = VG.get_Elipse(self.base["colorbor"], self.cara["tamanio"]) + + # alineación desabilitada por bug + self.alineacion = "centro" + unselect = VG.pegar_imagenes_centradas( + self.etiqueta_unselect.image, unselect) + select = VG.pegar_imagenes_centradas( + self.etiqueta_select.image, select) + else: + w, h = (0, 0) + # toma tamaño de etiqueta como referencia + if not self.cara["tamanio"]: + w = self.etiqueta_unselect.rect[2] + self.base["detalle"] + h = self.etiqueta_unselect.rect[3] + self.base["detalle"] + self.cara["tamanio"] = (w, h) + # la cara nunca puede ser menor que la etiqueta pero si mayor + if self.cara["tamanio"] and self.cara[ + "tamanio"][0] < self.etiqueta_unselect.rect[ + 2] + self.base["detalle"]: + w = self.etiqueta_unselect.rect[2] + self.base["detalle"] + self.cara["tamanio"] = (w, h) + if self.cara["tamanio"] and self.cara[ + "tamanio"][1] < self.etiqueta_unselect.rect[ + 3] + self.base["detalle"]: + h = self.etiqueta_unselect.rect[3] + self.base["detalle"] + self.cara["tamanio"] = (w, h) + unselect = VG.get_Rectangulo( + self.cara["color"], self.cara["tamanio"]) + select = VG.get_Rectangulo( + self.base["colorbor"], self.cara["tamanio"]) + + if self.alineacion == "centro": + unselect = VG.pegar_imagenes_centradas( + self.etiqueta_unselect.image, unselect) + select = VG.pegar_imagenes_centradas( + self.etiqueta_select.image, select) + elif self.alineacion == "izquierda": + unselect = VG.pegar_imagenes_alineado_izquierda( + self.etiqueta_unselect.image, unselect) + select = VG.pegar_imagenes_alineado_izquierda( + self.etiqueta_select.image, select) + elif self.alineacion == "derecha": + unselect = VG.pegar_imagenes_alineado_derecha( + self.etiqueta_unselect.image, unselect) + select = VG.pegar_imagenes_alineado_derecha( + self.etiqueta_select.image, select) + else: + self.alineacion = "centro" + unselect = VG.pegar_imagenes_centradas( + self.etiqueta_unselect.image, unselect) + select = VG.pegar_imagenes_centradas( + self.etiqueta_select.image, select) + + if self.borde_label["grosor"] > 1 and self.borde_label[ + "grosor"] != None: + if not self.borde_label["color"]: + self.borde_label["color"] = VG.get_negro() + if self.tipo == "elipse": + # desabilitado por bug + #unselect= VG.get_my_surface_whit_elipse_border( + # unselect, self.borde_label[ + # "color"], self.borde_label["grosor"]) + #select= VG.get_my_surface_whit_elipse_border( + # select, self.borde_label[ + # "color"], self.borde_label["grosor"]) + pass + else: + unselect = VG.get_my_surface_whit_border( + unselect, self.borde_label["color"], + self.borde_label["grosor"]) + select = VG.get_my_surface_whit_border( + select, self.borde_label["color"], + self.borde_label["grosor"]) + return unselect, select + + def construye_boton(self): + """ + Construye las imagenes finales del botón. + """ + unselect = None + select = None + if self.tipo == "elipse": + x = self.base["grosorbor"] + int(self.base["espesor"] / 3) + ancho = x + self.cara["tamanio"][0] + self.base[ + "espesor"] + self.base["grosorbor"] + y = self.base["grosorbor"] + int(self.base["espesor"] / 3) + alto = y + self.cara["tamanio"][1] + self.base[ + "espesor"] + self.base["grosorbor"] + self.base["tamanio"] = (ancho, alto) + unselect = VG.get_Elipse(self.base[ + "colorbas"], self.base["tamanio"]) + unselect = VG.get_my_surface_whit_elipse_border( + unselect, self.base["colorbor"], self.base["grosorbor"]) + select = VG.get_Elipse( + self.base["colorbas"], self.base["tamanio"]) + select = VG.get_my_surface_whit_elipse_border( + select, self.base["colorbor"], self.base["grosorbor"]) + else: + x = self.base["grosorbor"] + int(self.base["espesor"] / 3) + ancho = x + self.cara["tamanio"][0] + self.base[ + "espesor"] + self.base["grosorbor"] + y = self.base["grosorbor"] + int(self.base["espesor"] / 3) + alto = y + self.cara["tamanio"][1] + self.base[ + "espesor"] + self.base["grosorbor"] + self.base["tamanio"] = (ancho, alto) + unselect = VG.get_Rectangulo( + self.base["colorbas"], self.base["tamanio"]) + unselect = VG.get_my_surface_whit_border( + unselect, self.base["colorbor"], self.base["grosorbor"]) + select = VG.get_Rectangulo( + self.base["colorbas"], self.base["tamanio"]) + select = VG.get_my_surface_whit_border( + select, self.base["colorbor"], self.base["grosorbor"]) + + unselect.blit(self.imagen_cara_unselect, (x, y)) + select.blit(self.imagen_cara_select, (x, y)) + return unselect, select + # ------------------ FIN DE METODOS DE CONSTRUCCION -------------------- # + + # ---------- INICIO DE METODOS INTERNOS AUTOMÁTICOS -------------------- # + #def play_select(self): + # """ + # reproduce un sonido cuando pasas el mouse sobre el botón + # """ + # if self.sonido_select: + # self.sonido_select.play() + + def update(self): + """ + responde a los eventos del mouse sobre el sprite. + """ + eventos_republicar = [] + eventos = pygame.event.get(pygame.MOUSEBUTTONDOWN) + for event in eventos: + posicion = event.pos + if self.rect.collidepoint(posicion): + # Si el mouse está presionado sobre el botón. + if self.callback: + # y si además hay callback para esta acción. + pygame.event.clear() + return self.callback(self) + else: + # Si el mouse no está presionado sobre el botón. + if not event in eventos_republicar: + eventos_republicar.append(event) + + eventos = pygame.event.get(pygame.MOUSEMOTION) + for event in eventos: + posicion = event.pos + if self.rect.collidepoint(posicion): + # Si el mouse está sobre el botón. + if self.select == False: + #self.play_select() + self.image = self.final_select + self.select = True + else: + # Si el mouse no está sobre el botón. + if self.select == True: + self.image = self.final_unselect + self.select = False + if not event in eventos_republicar: + eventos_republicar.append(event) + + for event in eventos_republicar: + # Se republican todos los eventos que este control no debe manejar. + pygame.event.post(event) + + +''' class Ejemplo(object): - def __init__(self): - self.ventana = None - self.reloj = None - self.nivel = "menu_0" - - self.fondo = None - self.widgets = None - - self.resolucion = (800,800) - - self.setup() - self.Run() - - def Run(self): - self.ventana.blit(self.fondo, (0,0)) - self.widgets.draw(self.ventana) - pygame.display.update() - - #self.widgets.sprites()[0].set_text(tipo="Arial", tamanio=25, color=None, texto="Flavio Danesse") - #self.widgets.sprites()[0].set_imagen(origen=VG.URUGUAY, tamanio=None) - #self.widgets.sprites()[0].set_colores(colorbas=None, colorbor=color, colorcara=None) - #self.widgets.sprites()[0].set_tamanios(tamanio=tamanio, grosorbor=None, detalle=None, espesor=None) - #self.widgets.sprites()[0].set_posicion(punto=(25,25)) - #self.widgets.sprites()[0].set_borde_label(grosor=2, color=VG.get_negro()) - self.widgets.sprites()[0].connect(callback= self.salir, sonido_select= VG.get_sound_select()) - contador = 0 - while self.nivel == "menu_0": - self.reloj.tick(35) - - cambios=[] - self.widgets.clear(self.ventana, self.fondo) - - - if contador == 100: - # Activa la siguiente línea para provocar cambios de texto en JAMButton - contador= self.ejemplo_cambia_texto_en_button() - # Activa la siguiente línea para provocar cambios de imagen en JAMButton - contador= self.ejemplo_cambia_imagen_en_button() - # Activa la siguiente línea para provocar cambios de contenedor en JAMButton - contador= self.ejemplo_cambia_colores_en_button() - # Activa la siguiente línea para provocar cambios de posicion en JAMButton - contador= self.ejemplo_cambia_posicion_en_button() - # Activa la siguiente línea para provocar cambios de tamaño en JAMButton - contador= self.ejemplo_cambia_tamanios_en_button() - pass # y amor - - self.widgets.update() - self.handle_event() - pygame.event.clear() - cambios.extend ( self.widgets.draw(self.ventana) ) - pygame.display.update(cambios) - contador += 1 - - def ejemplo_cambia_texto_en_button(self): - import random - cambios = ["tipo", "tamanio", "color", "texto"] - modificar = random.choice(cambios) - if modificar == "tipo": - tipos= ["Arial", "Purisa", "Times New Roman", "Vardana", "Impact", pygame.font.get_default_font()] - tipo=random.choice(tipos) - self.widgets.sprites()[0].set_text(tipo=random.choice(tipos), tamanio=None, color=None, texto=None) - if modificar == "tamanio": - tamanios= [10,20,30,40,45] - tamanio=random.choice(tamanios) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=tamanio, color=None, texto=None) - if modificar == "color": - colores= [(0,0,0,255), (100,100,255,255), (110,25,255,255), (255,125,55,255)] - color = random.choice(colores) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=None, color=color, texto=None) - if modificar == "texto": - textos= ["JAMLabel", "Presiona escape cuando quieras salir", "Modificando Texto en JAMLabel", "CeibalJAM 2011"] - texto = random.choice(textos) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=None, color=None, texto=texto) - return 0 - - def ejemplo_cambia_imagen_en_button(self): - import random - cambios = ["origen", "tamanio"] - modificar = random.choice(cambios) - if modificar == "tamanio": - tamanios= [(10,20),(30,200),(250,100),None] - tamanio=random.choice(tamanios) - self.widgets.sprites()[0].set_imagen(origen=None, tamanio=tamanio) - if modificar == "origen": - origenes= [VG.get_jamimagenes()[0], VG.get_jamimagenes()[1], -1] - origen = random.choice(origenes) - self.widgets.sprites()[0].set_imagen(origen=origen, tamanio=None) - return 0 - - def ejemplo_cambia_colores_en_button(self): - import random - cambios = ["colorbas", "colorbor", "colorcara"] - modificar = random.choice(cambios) - - colores= [(10,20,100,255), (100,100,100,255), (255,255,255,255), (255,0,0,255)] - color=random.choice(colores) - - if modificar == "colorbas": - self.widgets.sprites()[0].set_colores(colorbas=color, colorbor=None, colorcara=None) - if modificar == "colorbor": - self.widgets.sprites()[0].set_colores(colorbas=None, colorbor=color, colorcara=None) - if modificar == "colorcara": - self.widgets.sprites()[0].set_colores(colorbas=None, colorbor=None, colorcara=color) - return 0 - - def ejemplo_cambia_tamanios_en_button(self): - import random - cambios = ["tamanio", "grosorbor", "detalle", "espesor"] - modificar = random.choice(cambios) - - #set_tamanios(tamanio=None, grosorbor=None, detalle=None, espesor=None) - if modificar == "tamanio": - tamanios= [(200,100), (100,50), (20,20), (300,150), (10,500), (300,50), -1] - tamanio = random.choice(tamanios) - self.widgets.sprites()[0].set_tamanios(tamanio=tamanio, grosorbor=None, detalle=None, espesor=None) - if modificar == "grosorbor": - tamanios= [1, 5, 8, 10] - tamanio = random.choice(tamanios) - self.widgets.sprites()[0].set_tamanios(tamanio=None, grosorbor=tamanio, detalle=None, espesor=None) - return 0 - - def ejemplo_cambia_posicion_en_button(self): - import random - posiciones= [(0,0), (25,25), (25,100), (25,150)] - posicion=random.choice(posiciones) - self.widgets.sprites()[0].set_posicion(punto=posicion) - return 0 - - def setup(self): - pygame.init() - pygame.display.set_mode(self.resolucion , 0, 0) - pygame.display.set_caption("Ejemplo") - - self.fondo = self.get_Fondo() - - self.widgets = pygame.sprite.OrderedUpdates() - self.widgets.add(JAMButton("JAMButton Prueba", None, tipo="elipse")) - - self.ventana = pygame.display.get_surface() - self.reloj = pygame.time.Clock() - - pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, - KEYUP, USEREVENT, QUIT, ACTIVEEVENT]) - pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, VIDEORESIZE, VIDEOEXPOSE]) - pygame.mouse.set_visible(True) - - def get_Fondo(self): - superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) - superficie.fill(VG.get_negro()) - return superficie - - def handle_event(self): - for event in pygame.event.get(): - if event.type == pygame.KEYDOWN: - self.salir() - pygame.event.clear() - - def salir(self, datos=None): - pygame.quit() - sys.exit() + + def __init__(self): + + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (800, 800) + + self.setup() + self.Run() + + def Run(self): + self.ventana.blit(self.fondo, (0, 0)) + self.widgets.draw(self.ventana) + pygame.display.update() + + #self.widgets.sprites()[0].set_text( + # tipo="Arial", tamanio=25, color=None, texto="Flavio Danesse") + #self.widgets.sprites()[0].set_imagen(origen=VG.URUGUAY, tamanio=None) + #self.widgets.sprites()[0].set_colores( + # colorbas=None, colorbor=color, colorcara=None) + #self.widgets.sprites()[0].set_tamanios( + # tamanio=tamanio, grosorbor=None, detalle=None, espesor=None) + #self.widgets.sprites()[0].set_posicion(punto=(25,25)) + #self.widgets.sprites()[0].set_borde_label( + # grosor=2, color=VG.get_negro()) + self.widgets.sprites()[0].connect( + callback=self.salir, sonido_select=VG.get_sound_select()) + contador = 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios = [] + self.widgets.clear(self.ventana, self.fondo) + + if contador == 100: + # Activa para provocar cambios de texto en JAMButton + contador = self.ejemplo_cambia_texto_en_button() + # Activa para provocar cambios de imagen en JAMButton + contador = self.ejemplo_cambia_imagen_en_button() + # Activa para provocar cambios de contenedor en JAMButton + contador = self.ejemplo_cambia_colores_en_button() + # Activa para provocar cambios de posicion en JAMButton + contador = self.ejemplo_cambia_posicion_en_button() + # Activa para provocar cambios de tamaño en JAMButton + contador = self.ejemplo_cambia_tamanios_en_button() + + self.widgets.update() + self.handle_event() + pygame.event.clear() + cambios.extend(self.widgets.draw(self.ventana)) + pygame.display.update(cambios) + contador += 1 + + def ejemplo_cambia_texto_en_button(self): + import random + cambios = ["tipo", "tamanio", "color", "texto"] + modificar = random.choice(cambios) + if modificar == "tipo": + tipos = ["Arial", "Purisa", "Times New Roman", + "Vardana", "Impact", pygame.font.get_default_font()] + self.widgets.sprites()[0].set_text( + tipo=random.choice(tipos), tamanio=None, + color=None, texto=None) + if modificar == "tamanio": + tamanios = [10, 20, 30, 40, 45] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_text( + tipo=None, tamanio=tamanio, color=None, texto=None) + if modificar == "color": + colores = [(0, 0, 0, 255), (100, 100, 255, 255), + (110, 25, 255, 255), (255, 125, 55, 255)] + color = random.choice(colores) + self.widgets.sprites()[0].set_text(tipo=None, + tamanio=None, color=color, texto=None) + if modificar == "texto": + textos = ["JAMLabel", "Presiona escape cuando quieras salir", + "Modificando Texto en JAMLabel", "CeibalJAM 2011"] + texto = random.choice(textos) + self.widgets.sprites()[0].set_text(tipo=None, tamanio=None, + color=None, texto=texto) + return 0 + + def ejemplo_cambia_imagen_en_button(self): + import random + cambios = ["origen", "tamanio"] + modificar = random.choice(cambios) + if modificar == "tamanio": + tamanios = [(10, 20), (30, 200), (250, 100), None] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_imagen(origen=None, tamanio=tamanio) + if modificar == "origen": + origenes = [VG.get_jamimagenes()[0], VG.get_jamimagenes()[1], -1] + origen = random.choice(origenes) + self.widgets.sprites()[0].set_imagen(origen=origen, tamanio=None) + return 0 + + def ejemplo_cambia_colores_en_button(self): + import random + cambios = ["colorbas", "colorbor", "colorcara"] + modificar = random.choice(cambios) + + colores = [(10, 20, 100, 255), (100, 100, 100, 255), + (255, 255, 255, 255), (255, 0, 0, 255)] + color = random.choice(colores) + + if modificar == "colorbas": + self.widgets.sprites()[0].set_colores( + colorbas=color, colorbor=None, colorcara=None) + if modificar == "colorbor": + self.widgets.sprites()[0].set_colores( + colorbas=None, colorbor=color, colorcara=None) + if modificar == "colorcara": + self.widgets.sprites()[0].set_colores( + colorbas=None, colorbor=None, colorcara=color) + return 0 + + def ejemplo_cambia_tamanios_en_button(self): + import random + cambios = ["tamanio", "grosorbor", "detalle", "espesor"] + modificar = random.choice(cambios) + + #set_tamanios(tamanio=None, grosorbor=None, detalle=None, espesor=None) + if modificar == "tamanio": + tamanios = [(200, 100), (100, 50), (20, 20), + (300, 150), (10, 500), (300, 50), -1] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_tamanios( + tamanio=tamanio, grosorbor=None, detalle=None, espesor=None) + if modificar == "grosorbor": + tamanios = [1, 5, 8, 10] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_tamanios( + tamanio=None, grosorbor=tamanio, detalle=None, espesor=None) + return 0 + + def ejemplo_cambia_posicion_en_button(self): + import random + posiciones = [(0, 0), (25, 25), (25, 100), (25, 150)] + posicion = random.choice(posiciones) + self.widgets.sprites()[0].set_posicion(punto=posicion) + return 0 + + def setup(self): + pygame.init() + pygame.display.set_mode(self.resolucion, 0, 0) + pygame.display.set_caption("Ejemplo") + + self.fondo = self.get_Fondo() + + self.widgets = pygame.sprite.OrderedUpdates() + self.widgets.add(JAMButton("JAMButton Prueba", None, tipo="elipse")) + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + + pygame.event.set_blocked([ + JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, + JOYBUTTONUP, JOYBUTTONDOWN, + KEYUP, USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([ + MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, + KEYDOWN, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def get_Fondo(self): + superficie = pygame.Surface(self.resolucion, flags=HWSURFACE) + superficie.fill(VG.get_negro()) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + self.salir() + pygame.event.clear() + + def salir(self, datos=None): + pygame.quit() + sys.exit() if __name__ == "__main__": - Ejemplo() + Ejemplo() +''' diff --git a/JAMGlobals.py b/JAMGlobals.py index eb3fd24..445873e 100644 --- a/JAMGlobals.py +++ b/JAMGlobals.py @@ -3,372 +3,594 @@ import pygame import gc -import sys import os -import platform +#import platform -from pygame.locals import * gc.enable() -''' -if "olpc" in platform.platform(): - os.environ['SDL_AUDIODRIVER'] = 'alsa' +#if "olpc" in platform.platform(): +# os.environ['SDL_AUDIODRIVER'] = 'alsa' + +#if not pygame.mixer.get_init(): +# pygame.mixer.pre_init(44100, -16, 2, 2048) +# pygame.mixer.init(44100, -16, 2, 2048) -if not pygame.mixer.get_init(): - pygame.mixer.pre_init(44100, -16, 2, 2048) - pygame.mixer.init(44100, -16, 2, 2048)''' -#pygame.init() +DIRECTORIO_BIBLIOJAM = os.path.dirname(__file__) -DIRECTORIO_BIBLIOJAM= os.path.dirname(__file__) # fuentes def get_Font_fawn(): - return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/fawn.ttf", 43) + return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/fawn.ttf", 43) + + def get_Font_KOMIKND(): - return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/KOMIKND.ttf", 43) + return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/KOMIKND.ttf", 43) + # COLORES def get_magenta(): - return (255, 0, 255, 255) + return (255, 0, 255, 255) + + def get_blanco(): - return (255,255,255,255) + return (255, 255, 255, 255) + + def get_negro(): - return (0,0,0,255) + return (0, 0, 0, 255) + + def get_gris1(): - return (128,128,128,255) + return (128, 128, 128, 255) + + def get_naranja1(): - return (240,150,0,255) + return (240, 150, 0, 255) + + def get_celeste1(): - return (0,240,240,255) + return (0, 240, 240, 255) + + def get_celeste_pastel_claro1(): - return (220,255,255,255) + return (220, 255, 255, 255) + + def get_celeste_cielo1(): - return (51,121,183,255) + return (51, 121, 183, 255) + + def get_celeste_cielo2(): - return (37,115,177,255) + return (37, 115, 177, 255) + + def get_celeste_cielo3(): - return (91,152,209,255) + return (91, 152, 209, 255) + + def get_celeste_cielo4(): - return (206,229,237,255) + return (206, 229, 237, 255) + + def get_rojo1(): - return (255,0,0,255) + return (255, 0, 0, 255) + + def get_amarillo1(): - return (255,255,0,255) + return (255, 255, 0, 255) + + def get_verde1(): - return (0,183,0,255) + return (0, 183, 0, 255) + + def get_bordo1(): - return (178,0,0,255) + return (178, 0, 0, 255) + + def get_azul1(): - return (55,93,237,255) -def get_rojo1(): - return (255,0,0,255) + return (55, 93, 237, 255) + # DE BiblioJAM def get_jamimagenes(): - ''' Devuelve las imágenes de BiblioJAM. ''' - return (DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/CeibalJAM.png", DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/bandera_uruguay.png", - DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/licencia.png") + """ + Devuelve las imágenes de BiblioJAM. + """ + return (DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/CeibalJAM.png", + DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/bandera_uruguay.png", + DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/licencia.png") + + def get_terron(): - ''' Devuelve Terron de CeibalJAM! ''' - return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/icono_jam.png" + """ + Devuelve Terron de CeibalJAM! + """ + return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/icono_jam.png" + def get_sound_select(): - ''' Carga y Devuelve el sonido "select" de BiblioJAM para JAMButton ''' - #pygame.mixer.init() - return pygame.mixer.Sound(DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/select.ogg") + """ + Carga y Devuelve el sonido "select" de BiblioJAM para JAMButton + """ + #pygame.mixer.init() + return pygame.mixer.Sound( + DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/select.ogg") + + def get_sound_clock_tick1(): - ''' Carga y Devuelve el sonido "clock1" de BiblioJAM. ''' - #pygame.mixer.init() - return pygame.mixer.Sound(DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/clock_tick1.ogg") + """ + Carga y Devuelve el sonido "clock1" de BiblioJAM. + """ + #pygame.mixer.init() + return pygame.mixer.Sound( + DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/clock_tick1.ogg") + + def get_alarma_reloj1(): - ''' Carga y Devuelve el sonido "alarma-reloj1" de BiblioJAM. ''' - #pygame.mixer.init() - return pygame.mixer.Sound(DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/alarma-reloj1.ogg") + """ + Carga y Devuelve el sonido "alarma-reloj1" de BiblioJAM. + """ + #pygame.mixer.init() + return pygame.mixer.Sound( + DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/alarma-reloj1.ogg") + + def get_alarma_reloj2(): - ''' Carga y Devuelve el sonido "alarma-reloj2" de BiblioJAM. ''' - #pygame.mixer.init() - return pygame.mixer.Sound(DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/alarma-reloj2.ogg") + """ + Carga y Devuelve el sonido "alarma-reloj2" de BiblioJAM. + """ + #pygame.mixer.init() + return pygame.mixer.Sound( + DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/alarma-reloj2.ogg") + # ICONOS def get_icon_back(): - ''' Devuelve las imágenes para botones atras, delante, play y salir. ''' - atras= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/anterior.png" - return atras + """ + Devuelve las imágenes para botones atras, delante, play y salir. + """ + atras = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/anterior.png" + return atras + + def get_icon_next(): - ''' Devuelve las imágenes para botones atras, delante, play y salir. ''' - delante= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/siguiente.png" - return delante + """ + Devuelve las imágenes para botones atras, delante, play y salir. + """ + delante = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/siguiente.png" + return delante + + def get_icon_play(): - ''' Devuelve las imágenes para botones atras, delante, play y salir. ''' - play= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/play.png" - return play + """ + Devuelve las imágenes para botones atras, delante, play y salir. + """ + play = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/play.png" + return play + + def get_icon_exit(): - ''' Devuelve las imágenes para botones atras, delante, play y salir. ''' - salir= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/cerrar.png" - return salir + """ + Devuelve las imágenes para botones atras, delante, play y salir. + """ + salir = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/cerrar.png" + return salir + + #def get_icon_stop(): # ''' Devuelve las imágenes para botones atras, delante, play y salir. ''' # stop= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/??.png" # return stop + + def get_icon_ok(): - ''' Devuelve las imágenes para botones ok y cancel. ''' - ok= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/tick_ok.png" - return ok + """ + Devuelve las imágenes para botones ok y cancel. + """ + ok = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos ick_ok.png" + return ok + + def get_icon_cancel(): - ''' Devuelve las imágenes para botones ok y cancel. ''' - cancel= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/tick_cancel.png" - return cancel + """ + Devuelve las imágenes para botones ok y cancel. + """ + cancel = DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos ick_cancel.png" + return cancel + # IMAGENES Y SUPERFICIES def get_Rectangulo(color, tamanio): - ''' Devuelve una superficie según color y tamaño. ''' - superficie = pygame.Surface( tamanio, flags=HWSURFACE ) - superficie.fill(color) - return superficie + """ + Devuelve una superficie según color y tamaño. + """ + from pygame.locals import HWSURFACE + superficie = pygame.Surface(tamanio, flags=HWSURFACE) + superficie.fill(color) + return superficie + + def get_Rectangulo_Transparente(tamanio): - ''' Devuelve una superficie según color y tamaño. ''' - superficie = pygame.Surface( tamanio, flags=HWSURFACE ) - superficie.fill(get_magenta()) - superficie.set_colorkey(get_magenta(), pygame.RLEACCEL) - return superficie + """ + Devuelve una superficie según color y tamaño. + """ + from pygame.locals import HWSURFACE + superficie = pygame.Surface(tamanio, flags=HWSURFACE) + superficie.fill(get_magenta()) + superficie.set_colorkey(get_magenta(), pygame.RLEACCEL) + return superficie + + def get_my_surface_whit_border(superficie, color, grosor): - ''' Pinta un Borde Rectangular sobre una superficie y devuelve el resultado. ''' - pygame.draw.rect(superficie, color, superficie.get_rect(), grosor) - return superficie + """ + Pinta un Borde Rectangular sobre una superficie y devuelve el resultado. + """ + pygame.draw.rect(superficie, color, superficie.get_rect(), grosor) + return superficie + + def get_Elipse(color, tamanio): - ''' Devuelve una Elipse según color y tamaño. ''' - superficie = pygame.Surface( tamanio, flags=HWSURFACE ) - superficie.fill(get_magenta()) - superficie.set_colorkey(get_magenta(), pygame.RLEACCEL) - rectangulo = (0, 0, tamanio[0], tamanio[1]) - pygame.draw.ellipse(superficie, color, rectangulo, 0) - return superficie + """ + Devuelve una Elipse según color y tamaño. + """ + from pygame.locals import HWSURFACE + superficie = pygame.Surface(tamanio, flags=HWSURFACE) + superficie.fill(get_magenta()) + superficie.set_colorkey(get_magenta(), pygame.RLEACCEL) + rectangulo = (0, 0, tamanio[0], tamanio[1]) + pygame.draw.ellipse(superficie, color, rectangulo, 0) + return superficie + + def get_my_surface_whit_elipse_border(superficie, color, grosor): - ''' Pinta un Borde Eliptico sobre una superficie y devuelve el resultado. ''' - try: - rectangulo= (0,0,superficie.get_size()[0],superficie.get_size()[1]) - pygame.draw.ellipse(superficie, color, rectangulo, int(grosor)) - return superficie - except: - print rectangulo, color, grosor + """ + Pinta un Borde Eliptico sobre una superficie y devuelve el resultado. + """ + try: + rectangulo = (0, 0, + superficie.get_size()[0], superficie.get_size()[1]) + pygame.draw.ellipse(superficie, color, rectangulo, int(grosor)) + return superficie + except: + print rectangulo, color, grosor + + def pegar_imagenes_centradas(superficie1, superficie2): - ''' Pega superficie1 sobre superficie2. ''' - w,h= superficie2.get_size() - w1,h1= superficie1.get_size() - superficie2.blit(superficie1, (w/2-w1/2, h/2-h1/2)) - return superficie2 + """ + Pega superficie1 sobre superficie2. + """ + w, h = superficie2.get_size() + w1, h1 = superficie1.get_size() + superficie2.blit(superficie1, (w / 2 - w1 / 2, h / 2 - h1 / 2)) + return superficie2 + + def pegar_imagenes_alineado_izquierda(superficie1, superficie2): - ''' Pega superficie1 sobre superficie2. ''' - w,h= superficie2.get_size() - w1,h1= superficie1.get_size() - superficie2.blit(superficie1, (0, h/2-h1/2)) - return superficie2 + """ + Pega superficie1 sobre superficie2. + """ + w, h = superficie2.get_size() + w1, h1 = superficie1.get_size() + superficie2.blit(superficie1, (0, h / 2 - h1 / 2)) + return superficie2 + + def pegar_imagenes_alineado_derecha(superficie1, superficie2): - ''' Pega superficie1 sobre superficie2. ''' - w,h= superficie2.get_size() - w1,h1= superficie1.get_size() - superficie2.blit(superficie1, (w-w1, h/2-h1/2)) - return superficie2 - -def get_grilla(superficie, columnas, filas): # Utilizado por JAMBoard - ''' Devuelve una lista de posiciones en una superficie, según columnas y filas. ''' - ancho, alto= superficie.get_size() - cuadros= ancho/columnas - posiciones= [] - for f in range(0, filas): - for x in range(0, columnas): - posiciones.append( (cuadros*x, cuadros*f) ) - return posiciones + """ + Pega superficie1 sobre superficie2. + """ + w, h = superficie2.get_size() + w1, h1 = superficie1.get_size() + superficie2.blit(superficie1, (w - w1, h / 2 - h1 / 2)) + return superficie2 + + +def get_grilla(superficie, columnas, filas): # Utilizado por JAMBoard + """ + Devuelve una lista de posiciones en una superficie, según columnas y filas. + """ + ancho, alto = superficie.get_size() + cuadros = ancho / columnas + posiciones = [] + for f in range(0, filas): + for x in range(0, columnas): + posiciones.append((cuadros * x, cuadros * f)) + return posiciones + def get_matriz_rect(lado, colum, filas): - ''' Devuelve una lista de columnas: - que contiene cuadrados iguales. ''' - x,y= (0,0) - columnas= [] - for col in range(colum): - # para todas las columnas - - fila= [] - for rect in range(filas): - # para todas las filas - rectangulo= pygame.rect.Rect(x,y,lado,lado) - fila.append(rectangulo) - y+= lado - - columnas.append(fila) - x+= lado - y= 0 - - return columnas - -def get_cuadricula(superficie, columnas, filas): # Utilizado por JAMClock - ''' Devuelve una lista de rectángulos en una superficie, según columnas y filas. ''' - ancho, alto= superficie.get_size() - cuadros= ancho/columnas - rectangulos= [] - for f in range(0, filas): - for x in range(0, columnas): - rectangulos.append( (cuadros*x, cuadros*f, ancho/columnas, alto/filas) ) - return rectangulos + """ + Devuelve una lista de columnas: + que contiene cuadrados iguales. + """ + x, y = (0, 0) + columnas = [] + for col in range(colum): + # para todas las columnas + + fila = [] + for rect in range(filas): + # para todas las filas + rectangulo = pygame.rect.Rect(x, y, lado, lado) + fila.append(rectangulo) + y += lado + + columnas.append(fila) + x += lado + y = 0 + + return columnas + + +def get_cuadricula(superficie, columnas, filas): # Utilizado por JAMClock + """ + Devuelve una lista de rectángulos en una superficie, + según columnas y filas. + """ + ancho, alto = superficie.get_size() + cuadros = ancho / columnas + rectangulos = [] + for f in range(0, filas): + for x in range(0, columnas): + rectangulos.append(( + cuadros * x, cuadros * f, ancho / columnas, alto / filas)) + return rectangulos # Devuelve las diferentes Simbologías para sprites necesarios en JAMBoard. def get_letras_up(): - return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] + return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] + + def get_tildes_up(): - return ['Á', 'É', 'Í', 'Ó', 'Ú'] + return ['Á', 'É', 'Í', 'Ó', 'Ú'] + + def get_letras_down(): - return ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] + return ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] + + def get_tildes_down(): - return ['á', 'é', 'í', 'ó', 'ú'] + return ['á', 'é', 'í', 'ó', 'ú'] + + def get_numeros(): - return ['1','2','3','4','5','6','7','8','9','0'] + return ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] + + def get_simbols(): - return ['^', '_', '~', '|', '\\', '#', '$', '€', '&', '@', '%', 'ª', 'º', '·', '¡', '!', '¿', '?', '\'', '\"', '(', ')', '{', '}', '[', ']'] + return ['^', '_', '~', '|', '\\', '#', '$', '€', '&', '@', '%', 'ª', 'º', + '·', '¡', '!', '¿', '?', '\'', '\"', '(', ')', '{', '}', '[', ']'] + + def get_otros(): - return [',', '.', ':', ';', '<', '>'] + return [',', '.', ':', ';', '<', '>'] + + def get_matematicas(): - return ['*', '+', '-', '/', '='] + return ['*', '+', '-', '/', '='] + + def get_especiales(): - return ['´', "Espacio", "Borrar", "Enter"] + return ['´', "Espacio", "Borrar", "Enter"] + # Seteos automáticos para JAMButton. def get_default_jambutton_values(): - ''' Devuelve los valores default para JAMButton. ''' - COLORCARA = (242,242,242,255) - COLORBAS= (128,128,128,255) - COLORBOR= (179,179,179,255) - GROSORBOR= 7 - DETALLE= 2 - ESPESOR= 8 - return COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR + """ + Devuelve los valores default para JAMButton. + """ + COLORCARA = (242, 242, 242, 255) + COLORBAS = (128, 128, 128, 255) + COLORBOR = (179, 179, 179, 255) + GROSORBOR = 7 + DETALLE = 2 + ESPESOR = 8 + return COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR + # Estilos de colores para JAMBoard. def get_estilo_naranja(): - return (200,100,0,255), (240,150,0,255), (255,220,0,255) + return (200, 100, 0, 255), (240, 150, 0, 255), (255, 220, 0, 255) + + def get_estilo_gris(): - return (128,128,128,255), (179,179,179,255), (242,242,242,255) + return (128, 128, 128, 255), (179, 179, 179, 255), (242, 242, 242, 255) + + def get_estilo_celeste(): - return (0,128,128,255),(0,180,180,255),(0,240,240,255) + return (0, 128, 128, 255), (0, 180, 180, 255), (0, 240, 240, 255) + + def get_estilo_papel_quemado(): - return (148,107,54), (197,155,101), (231,207,178) + return (148, 107, 54), (197, 155, 101), (231, 207, 178) + # CALENDARIO def get_calendar(mes, anio): - ''' Devuelve una lista que representa los renglones para un calendario según mes y año, (anio y mes deben ser enteros). ''' - import calendar - calendario= calendar.Calendar() - semanas= calendario.monthdayscalendar(anio, mes) - toodoelmes= [] - for i in (semanas): - todalasemana=[] - for fecha in i: - if int(fecha)!=0: - todalasemana.append(fecha) - toodoelmes.append(todalasemana) - #toodoelmes.insert(0, ["%s de %s" % (get_abrevia_mes(mes), anio)]) - toodoelmes.insert(0, "%s de %s" % (get_mes(mes), anio)) - toodoelmes.insert(1,["lu", "ma", "mie", "jue", "vie", "sa", "do"]) - return toodoelmes + """ + Devuelve una lista que representa los renglones para un calendario + según mes y año, (anio y mes deben ser enteros). + """ + import calendar + calendario = calendar.Calendar() + semanas = calendario.monthdayscalendar(anio, mes) + toodoelmes = [] + for i in (semanas): + todalasemana = [] + for fecha in i: + if int(fecha) != 0: + todalasemana.append(fecha) + toodoelmes.append(todalasemana) + #toodoelmes.insert(0, ["%s de %s" % (get_abrevia_mes(mes), anio)]) + toodoelmes.insert(0, "%s de %s" % (get_mes(mes), anio)) + toodoelmes.insert(1, ["lu", "ma", "mie", "jue", "vie", "sa", "do"]) + return toodoelmes + def get_abrevia_mes(numero): - ''' Recibe un entero de 1 a 12 y devuelve la abreviación del mes correspondiente.''' - numero= int(numero) - if numero== 1: return "ene" - if numero== 2: return "feb" - if numero== 3: return "mar" - if numero== 4: return "abr" - if numero== 5: return "may" - if numero== 6: return "jun" - if numero== 7: return "jul" - if numero== 8: return "ago" - if numero== 9: return "sep" - if numero== 10: return "oct" - if numero== 11: return "nov" - if numero== 12: return "dic" + """ + Recibe un entero de 1 a 12 y devuelve la abreviación del + mes correspondiente. + """ + numero = int(numero) + if numero == 1: + return "ene" + if numero == 2: + return "feb" + if numero == 3: + return "mar" + if numero == 4: + return "abr" + if numero == 5: + return "may" + if numero == 6: + return "jun" + if numero == 7: + return "jul" + if numero == 8: + return "ago" + if numero == 9: + return "sep" + if numero == 10: + return "oct" + if numero == 11: + return "nov" + if numero == 12: + return "dic" + def get_mes(numero): - ''' Recibe un entero de 1 a 12 y devuelve el nombre del mes correspondiente.''' - numero= int(numero) - if numero== 1: return "Enero" - if numero== 2: return "Febrero" - if numero== 3: return "Marzo" - if numero== 4: return "Abril" - if numero== 5: return "Mayo" - if numero== 6: return "Junio" - if numero== 7: return "Julio" - if numero== 8: return "Agosto" - if numero== 9: return "Setiembre" - if numero== 10: return "Octubre" - if numero== 11: return "Noviembre" - if numero== 12: return "Diciembre" + """ + Recibe un entero de 1 a 12 y devuelve el nombre del mes correspondiente. + """ + numero = int(numero) + if numero == 1: + return "Enero" + if numero == 2: + return "Febrero" + if numero == 3: + return "Marzo" + if numero == 4: + return "Abril" + if numero == 5: + return "Mayo" + if numero == 6: + return "Junio" + if numero == 7: + return "Julio" + if numero == 8: + return "Agosto" + if numero == 9: + return "Setiembre" + if numero == 10: + return "Octubre" + if numero == 11: + return "Noviembre" + if numero == 12: + return "Diciembre" + def get_dia(numero): - ''' Recibe un entero de 1 a 7 y devuelve el nombre del día correspondiente.''' - numero= int(numero) - if numero== 1: return "Lunes" - if numero== 2: return "Martes" - if numero== 3: return "Miercoles" - if numero== 4: return "Jueves" - if numero== 5: return "Viernes" - if numero== 6: return "Sabado" - if numero== 7: return "Domingo" + """ + Recibe un entero de 1 a 7 y devuelve el nombre del día correspondiente. + """ + numero = int(numero) + if numero == 1: + return "Lunes" + if numero == 2: + return "Martes" + if numero == 3: + return "Miercoles" + if numero == 4: + return "Jueves" + if numero == 5: + return "Viernes" + if numero == 6: + return "Sabado" + if numero == 7: + return "Domingo" + # Efectos def get_fire(): - ''' Imagenes de un fuego. ''' - imagenes_cargadas= [] - imagenes= os.listdir(DIRECTORIO_BIBLIOJAM + "/Recursos/Fuego/") - for imagen in imagenes: - im= pygame.image.load(DIRECTORIO_BIBLIOJAM + "/Recursos/Fuego/" + imagen) - imagenes_cargadas.append(im) - return imagenes_cargadas + """ + Imagenes de un fuego. + """ + imagenes_cargadas = [] + imagenes = os.listdir(DIRECTORIO_BIBLIOJAM + "/Recursos/Fuego/") + for imagen in imagenes: + im = pygame.image.load( + DIRECTORIO_BIBLIOJAM + "/Recursos/Fuego/" + imagen) + imagenes_cargadas.append(im) + return imagenes_cargadas + def get_nube(): - ''' Imagenes de nubes. ''' - imagen= pygame.image.load(DIRECTORIO_BIBLIOJAM + "/Recursos/Nubes/nube1.png") - #pygame.transform.scale(pygame.image.load(DIRECTORIO_BIBLIOJAM + "/Recursos/Nubes/001.png"), (125,125)) - return imagen + """ + Imagenes de nubes. + """ + imagen = pygame.image.load( + DIRECTORIO_BIBLIOJAM + "/Recursos/Nubes/nube1.png") + # pygame.transform.scale( + # pygame.image.load( + # DIRECTORIO_BIBLIOJAM + "/Recursos/Nubes/001.png"), (125, 125)) + return imagen + def get_sound_lluvia(): - ''' Carga y Devuelve el sonido de la lluvia para JAMNubes ''' - #pygame.mixer.init() - return pygame.mixer.Sound(DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/lluvia.ogg") + """ + Carga y Devuelve el sonido de la lluvia para JAMNubes + """ + #pygame.mixer.init() + return pygame.mixer.Sound( + DIRECTORIO_BIBLIOJAM + "/Recursos/Sonidos/lluvia.ogg") + ''' def get_libro(): - Libreta de lectura. - return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/libreta.png" - - def get_hoja(): - Devuelve la imagen para una hoja vacía. - imagen= pygame.image.load(VG.get_libro()) - ancho, alto= imagen.get_size() - fondo= VG.get_Rectangulo(VG.get_blanco(), (ancho, alto*19)) - - x, y= (0,0) - for n in range(19): - fondo.blit(imagen, (x, y)) - y+=alto - #fondo= pygame.transform.scale(fondo,(296,420)) - return fondo + Libreta de lectura. + return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/libreta.png" + + def get_hoja(): + Devuelve la imagen para una hoja vacía. + imagen= pygame.image.load(VG.get_libro()) + ancho, alto= imagen.get_size() + fondo= VG.get_Rectangulo(VG.get_blanco(), (ancho, alto*19)) + + x, y= (0,0) + for n in range(19): + fondo.blit(imagen, (x, y)) + y+=alto + #fondo= pygame.transform.scale(fondo,(296,420)) + return fondo ''' + def get_hoja(escala): - ''' Devuelve la imagen para una hoja vacía y un valor "margen" para el texto. ''' - imagen= pygame.image.load(DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/hoja.png") - if type(escala)== tuple and type(escala[0])== int and type(escala[1])== int: - imagen= pygame.transform.scale(imagen, escala) - w,h= imagen.get_size() - margen= w/10 - return imagen, margen + """ + Devuelve la imagen para una hoja vacía y un valor "margen" para el texto. + """ + imagen = pygame.image.load( + DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/hoja.png") + if type(escala) == tuple and type( + escala[0]) == int and type(escala[1]) == int: + imagen = pygame.transform.scale(imagen, escala) + w, h = imagen.get_size() + margen = w / 10 + return imagen, margen + def get_Sombra(tamanio, color, opacidad): - x= pygame.sprite.OrderedUpdates() - sombra= pygame.sprite.Sprite() - sombra.image= get_Rectangulo(color, tamanio) - sombra.image.set_alpha(opacidad, SRCALPHA) - sombra.rect= sombra.image.get_rect() - x.add(sombra) - return x + from pygame.locals import SRCALPHA + x = pygame.sprite.OrderedUpdates() + sombra = pygame.sprite.Sprite() + sombra.image = get_Rectangulo(color, tamanio) + sombra.image.set_alpha(opacidad, SRCALPHA) + sombra.rect = sombra.image.get_rect() + x.add(sombra) + return x diff --git a/JAMLabel.py b/JAMLabel.py index 1f7df3b..23baea8 100644 --- a/JAMLabel.py +++ b/JAMLabel.py @@ -3,379 +3,454 @@ import pygame import gc -import sys import os -from pygame.locals import * gc.enable() pygame.font.init() import JAMGlobals as VG + class JAMLabel(pygame.sprite.Sprite): - def __init__(self, texto): - pygame.sprite.Sprite.__init__(self) - ''' No se Puede Crear una Etiqueta sin Texto. ''' - self.separador = 5 - self.sprite_texto= None - self.image= None - self.rect= None - self.posicion = (0,0) - - self.imagen = {"origen": None, "tamanio": None} - self.texto = {"tipo": pygame.font.get_default_font(), "tamanio": 20, "color": VG.get_negro(), "texto": texto} - self.font_from_file= None # Agregado 15-06-2011 - Para cargar un tipo de letra desde un archivo.(os.getcwd()+"/Fuentes/fawn.ttf", 43) - self.base = {"tamanio": None, "color": None} - self.borde = {"grosor": None, "color": None} - self.contenedor = {"base": self.base, "borde": self.borde} - self.JAMObjects = {"Imagen": self.imagen, "Texto": self.texto, "Contenedor": self.contenedor} - - self.Reconstruye_JAMlabel(["texto"]) - - # ------------- GETS ------------------------ - def get_tamanio(self): - return (self.rect.w, self.rect.h) - - def get_posicion(self): - return (self.rect.x, self.rect.y) - - def get_text(self): - ''' Devuelve la cadena de Texto que contiene JAMLabel. ''' - return str(self.texto["texto"]) - - # ---------- SETEOS ------------------------- - def set_imagen(self, origen=None, tamanio=None): - ''' Setea la Imagen en JAMLabel. -1 para quitarla. ''' - if origen == -1: - self.imagen["origen"]= None - self.imagen["tamanio"]= None - self.Reconstruye_JAMlabel(["texto"]) - return - cambios= False - if origen and origen != self.imagen["origen"]: - self.imagen["origen"]= origen - cambios= True - if tamanio and tamanio != self.imagen["tamanio"]: - self.imagen["tamanio"]= tamanio - cambios= True - if cambios: - self.Reconstruye_JAMlabel(["imagen"]) - - def set_text(self, tipo=None, tamanio=None, color=None, texto=None): - ''' Setea el Texto en JAMLabel. "" para quitarlo. ''' - cambios= False - if tipo and tipo != self.texto["tipo"]: - self.texto["tipo"]= tipo - cambios= True - if tamanio and tamanio != self.texto["tamanio"]: - self.texto["tamanio"]= tamanio - cambios= True - if color and color != self.texto["color"]: - self.texto["color"]= color - cambios= True - if texto and texto != self.texto["texto"]: - self.texto["texto"]= texto - cambios= True - if cambios: - if self.texto["tipo"] and self.texto["tamanio"] and self.texto["color"] and self.texto["texto"]: - self.Reconstruye_JAMlabel(["texto"]) - - def set_contenedor(self, colorbas=None, grosor=None, colorbor=None): - ''' Setea los Colores del Contenedor de JAMLabel. ''' - cambios= False - if colorbas == -1: - # Deshabilita relleno - self.contenedor["base"]["color"] = None - colorbas=None - cambios= True - if colorbor == -1 or grosor < 1: - # Deshabilita borde - self.contenedor["borde"]["grosor"] = None - self.contenedor["borde"]["color"] = None - colorbor=None - grosor=None - cambios= True - if colorbas and colorbas != self.contenedor["base"]["color"]: - self.contenedor["base"]["color"] = colorbas - cambios= True - if grosor and grosor != self.contenedor["borde"]["grosor"]: - self.contenedor["borde"]["grosor"] = grosor - cambios= True - if colorbor and colorbor != self.contenedor["borde"]["color"]: - self.contenedor["borde"]["color"] = colorbor - cambios= True - if cambios: - self.Reconstruye_JAMlabel(["contenedor"]) - - def set_posicion(self, punto=None): - ''' Setea la posición de JAMLabel en la pantalla. ''' - if type(punto)== tuple and len(punto)== 2 and type(punto[0])== int and type(punto[1])== int: - self.rect.x, self.rect.y = (punto) - self.posicion = punto - - # ----------- CONSTRUCCION ------------------- - def Reconstruye_JAMlabel(self, cambios): - ''' Cada vez que se setea algo, se reconstruye JAMLabel con sus nuevos valores. ''' - if not self.sprite_texto: self.sprite_texto= self.construye_texto() - superficie= self.sprite_texto - if "texto" in cambios: - # si se modificó el texto - self.sprite_texto= self.construye_texto() - superficie= self.sprite_texto - - if self.imagen["origen"]: - # si hay una imagen - superficie= self.concatenar(superficie, self.construye_imagen()) - - if self.contenedor["base"]["color"] and self.contenedor["base"]["tamanio"] and not self.imagen["origen"]: - sprite_relleno= self.construye_relleno() - superficie= VG.pegar_imagenes_centradas(superficie, sprite_relleno) - - if self.contenedor["borde"]["grosor"]: - superficie= self.construye_borde(superficie) - - self.image = superficie - self.rect = self.image.get_rect() - self.set_posicion(self.posicion) # seteo automático de posición - - # ------ TEXTO - def construye_texto(self): - ''' Devuelve una Superficie con la Imagen del Texto. ''' - string_to_render= "" - fuente = pygame.font.Font(pygame.font.match_font(self.texto["tipo"], True, False), self.texto["tamanio"]) - if self.font_from_file: - fuente= pygame.font.Font(self.font_from_file, self.texto["tamanio"]) - string_to_render = unicode( str(self.texto["texto"]).decode("utf-8") ) - imagen_fuente = fuente.render(string_to_render, 1, (self.texto["color"])) - self.contenedor["base"]["tamanio"] = (imagen_fuente.get_size()[0]+self.separador*2, imagen_fuente.get_size()[1]+self.separador*2) - return imagen_fuente - - def set_font_from_file(self, direccion_archivo, tamanio= None): - ''' Setea la fuente desde un archivo. ''' - cambios= False - try: - if os.path.isfile(direccion_archivo): - self.font_from_file= direccion_archivo - cambios= True - except: - pass - if type(tamanio)== int: - self.texto["tamanio"]= tamanio - cambios= True - if cambios: self.Reconstruye_JAMlabel(["texto"]) - - # ------ IMAGEN - def construye_imagen(self): - ''' Carga una imagen. ''' - if self.imagen["tamanio"]: - w,h = self.imagen["tamanio"] - if w < 20: w = 20 - if h < 20: h = 20 - self.imagen["tamanio"]= (w,h) - else: - imagen = pygame.image.load(self.imagen["origen"]) - self.imagen["tamanio"]= imagen.get_size() - return pygame.transform.scale(pygame.image.load(self.imagen["origen"]), self.imagen["tamanio"]).convert_alpha() - - # ------- CONCATENAR IMAGEN-TEXTO SOBRE RELLENO - def concatenar(self, sprite_texto, sprite_imagen): - ''' Arma una imagen con Imagen+Texto Concatenados para Formar la Cara de JAMLabel. ''' - w,h = sprite_imagen.get_size() - w1,h1 = sprite_texto.get_size() - altura=h - if h > h1: - altura= h - else: - altura= h1 - self.contenedor["base"]["tamanio"] = (w+w1+self.separador*3, altura+self.separador*2) - superficie = self.construye_relleno() - superficie.blit(sprite_imagen, (self.separador, altura/2-h/2+self.separador)) - superficie.blit(sprite_texto, (w+self.separador*2, altura/2-h1/2+self.separador)) - return superficie - - # ------ RELLENO - def construye_relleno(self): - ''' Crea un Relleno de Color para JAMLabel. ''' - if not self.contenedor["base"]["color"]: self.contenedor["base"]["color"] = VG.get_blanco() - return VG.get_Rectangulo(self.contenedor["base"]["color"], self.contenedor["base"]["tamanio"]) - - # ------- Borde - def construye_borde(self, superficie): - ''' Crea un Borde de Color para JAMLabel. ''' - if not self.contenedor["borde"]["color"]: self.contenedor["borde"]["color"] = VG.get_negro() - if not self.contenedor["borde"]["grosor"]: self.contenedor["borde"]["grosor"] = 2 - return VG.get_my_surface_whit_border(superficie, self.contenedor["borde"]["color"], self.contenedor["borde"]["grosor"]) - - def Describe(self): - ''' Describe la Estructura de Este Control. ''' - estructura = ''' - Estructura JAMLabel: - JAMObjects: - Imagen - Texto - Contenedor - - Detalle Estructural: - Imagen: - origen - tamanio - Texto: - tipo - tamanio - color - texto - Contenedor: - Base: - tamanio - color - Borde: - grosor - color ''' - print estructura - print "Ejemplo, Configuración actual:\n" - print "\t", self.JAMObjects.keys(), "\n" - for k in self.JAMObjects.items(): - print k, "\n" - -# ----- FIN DE CLASE JAMLabel - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- + + def __init__(self, texto): + + pygame.sprite.Sprite.__init__(self) + + """ + No se Puede Crear una Etiqueta sin Texto. + """ + self.separador = 5 + self.sprite_texto = None + self.image = None + self.rect = None + self.posicion = (0, 0) + + self.imagen = {"origen": None, "tamanio": None} + self.texto = {"tipo": pygame.font.get_default_font(), + "tamanio": 20, "color": VG.get_negro(), "texto": texto} + self.font_from_file = None + self.base = {"tamanio": None, "color": None} + self.borde = {"grosor": None, "color": None} + self.contenedor = {"base": self.base, "borde": self.borde} + self.JAMObjects = {"Imagen": self.imagen, "Texto": self.texto, + "Contenedor": self.contenedor} + + self.Reconstruye_JAMlabel(["texto"]) + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.rect.w, self.rect.h) + + def get_posicion(self): + return (self.rect.x, self.rect.y) + + def get_text(self): + """ + Devuelve la cadena de Texto que contiene JAMLabel. + """ + return str(self.texto["texto"]) + + # ---------- SETEOS ------------------------- + def set_imagen(self, origen=None, tamanio=None): + """ + Setea la Imagen en JAMLabel. -1 para quitarla. + """ + if origen == -1: + self.imagen["origen"] = None + self.imagen["tamanio"] = None + self.Reconstruye_JAMlabel(["texto"]) + return + cambios = False + if origen and origen != self.imagen["origen"]: + self.imagen["origen"] = origen + cambios = True + if tamanio and tamanio != self.imagen["tamanio"]: + self.imagen["tamanio"] = tamanio + cambios = True + if cambios: + self.Reconstruye_JAMlabel(["imagen"]) + + def set_text(self, tipo=None, tamanio=None, color=None, texto=None): + """ + Setea el Texto en JAMLabel. "" para quitarlo. + """ + cambios = False + if tipo and tipo != self.texto["tipo"]: + self.texto["tipo"] = tipo + cambios = True + if tamanio and tamanio != self.texto["tamanio"]: + self.texto["tamanio"] = tamanio + cambios = True + if color and color != self.texto["color"]: + self.texto["color"] = color + cambios = True + if texto and texto != self.texto["texto"]: + self.texto["texto"] = texto + cambios = True + if cambios: + if self.texto["tipo"] and self.texto["tamanio"] and \ + self.texto["color"] and self.texto["texto"]: + self.Reconstruye_JAMlabel(["texto"]) + + def set_contenedor(self, colorbas=None, grosor=None, colorbor=None): + """ + Setea los Colores del Contenedor de JAMLabel. + """ + cambios = False + if colorbas == -1: + # Deshabilita relleno + self.contenedor["base"]["color"] = None + colorbas = None + cambios = True + if colorbor == -1 or grosor < 1: + # Deshabilita borde + self.contenedor["borde"]["grosor"] = None + self.contenedor["borde"]["color"] = None + colorbor = None + grosor = None + cambios = True + if colorbas and colorbas != self.contenedor["base"]["color"]: + self.contenedor["base"]["color"] = colorbas + cambios = True + if grosor and grosor != self.contenedor["borde"]["grosor"]: + self.contenedor["borde"]["grosor"] = grosor + cambios = True + if colorbor and colorbor != self.contenedor["borde"]["color"]: + self.contenedor["borde"]["color"] = colorbor + cambios = True + if cambios: + self.Reconstruye_JAMlabel(["contenedor"]) + + def set_posicion(self, punto=None): + """ + Setea la posición de JAMLabel en la pantalla. + """ + if type(punto) == tuple and len(punto) == 2 and \ + type(punto[0]) == int and type(punto[1]) == int: + self.rect.x, self.rect.y = (punto) + self.posicion = punto + + # ----------- CONSTRUCCION ------------------- + def Reconstruye_JAMlabel(self, cambios): + """ + Cada vez que se setea algo, se reconstruye JAMLabel + con sus nuevos valores. + """ + if not self.sprite_texto: + self.sprite_texto = self.construye_texto() + superficie = self.sprite_texto + if "texto" in cambios: + # si se modificó el texto + self.sprite_texto = self.construye_texto() + superficie = self.sprite_texto + + if self.imagen["origen"]: + # si hay una imagen + superficie = self.concatenar(superficie, self.construye_imagen()) + + if self.contenedor["base"]["color"] and \ + self.contenedor["base"]["tamanio"] and not self.imagen["origen"]: + sprite_relleno = self.construye_relleno() + superficie = VG.pegar_imagenes_centradas( + superficie, sprite_relleno) + + if self.contenedor["borde"]["grosor"]: + superficie = self.construye_borde(superficie) + + self.image = superficie + self.rect = self.image.get_rect() + self.set_posicion(self.posicion) # seteo automático de posición + + # ------ TEXTO + def construye_texto(self): + """ + Devuelve una Superficie con la Imagen del Texto. + """ + string_to_render = "" + fuente = pygame.font.Font( + pygame.font.match_font(self.texto["tipo"], + True, False), self.texto["tamanio"]) + if self.font_from_file: + fuente = pygame.font.Font( + self.font_from_file, self.texto["tamanio"]) + string_to_render = unicode(str(self.texto["texto"]).decode("utf-8")) + imagen_fuente = fuente.render( + string_to_render, 1, (self.texto["color"])) + self.contenedor["base"]["tamanio"] = ( + imagen_fuente.get_size()[0] + self.separador * 2, + imagen_fuente.get_size()[1] + self.separador * 2) + return imagen_fuente + + def set_font_from_file(self, direccion_archivo, tamanio=None): + """ + Setea la fuente desde un archivo. + """ + cambios = False + try: + if os.path.isfile(direccion_archivo): + self.font_from_file = direccion_archivo + cambios = True + except: + pass + if type(tamanio) == int: + self.texto["tamanio"] = tamanio + cambios = True + if cambios: + self.Reconstruye_JAMlabel(["texto"]) + + # ------ IMAGEN + def construye_imagen(self): + """ + Carga una imagen. + """ + if self.imagen["tamanio"]: + w, h = self.imagen["tamanio"] + if w < 20: + w = 20 + if h < 20: + h = 20 + self.imagen["tamanio"] = (w, h) + else: + imagen = pygame.image.load(self.imagen["origen"]) + self.imagen["tamanio"] = imagen.get_size() + return pygame.transform.scale( + pygame.image.load(self.imagen["origen"]), + self.imagen["tamanio"]).convert_alpha() + + # ------- CONCATENAR IMAGEN-TEXTO SOBRE RELLENO + def concatenar(self, sprite_texto, sprite_imagen): + """ + Arma una imagen con Imagen+Texto Concatenados para Formar + la Cara de JAMLabel. + """ + w, h = sprite_imagen.get_size() + w1, h1 = sprite_texto.get_size() + altura = h + if h > h1: + altura = h + else: + altura = h1 + self.contenedor["base"]["tamanio"] = (w + w1 + self.separador * 3, + altura + self.separador * 2) + superficie = self.construye_relleno() + superficie.blit(sprite_imagen, (self.separador, + altura / 2 - h / 2 + self.separador)) + superficie.blit(sprite_texto, (w + self.separador * 2, + altura / 2 - h1 / 2 + self.separador)) + return superficie + + # ------ RELLENO + def construye_relleno(self): + """ + Crea un Relleno de Color para JAMLabel. + """ + if not self.contenedor["base"]["color"]: + self.contenedor["base"]["color"] = VG.get_blanco() + return VG.get_Rectangulo(self.contenedor["base"]["color"], + self.contenedor["base"]["tamanio"]) + + # ------- Borde + def construye_borde(self, superficie): + """ + Crea un Borde de Color para JAMLabel. + """ + if not self.contenedor["borde"]["color"]: + self.contenedor["borde"]["color"] = VG.get_negro() + if not self.contenedor["borde"]["grosor"]: + self.contenedor["borde"]["grosor"] = 2 + return VG.get_my_surface_whit_border(superficie, + self.contenedor["borde"]["color"], + self.contenedor["borde"]["grosor"]) + + def Describe(self): + """ + Describe la Estructura de Este Control. + """ + estructura = ''' + Estructura JAMLabel: + JAMObjects: + Imagen + Texto + Contenedor + + Detalle Estructural: + Imagen: + origen + tamanio + Texto: + tipo + tamanio + color + texto + Contenedor: + Base: + tamanio + color + Borde: + grosor + color ''' + print estructura + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + + +''' class Ejemplo(object): - def __init__(self): - self.ventana = None - self.reloj = None - self.nivel = "menu_0" - - self.fondo = None - self.widgets = None - - self.resolucion = (800,300) - - self.setup() - self.Run() - - def Run(self): - self.ventana.blit(self.fondo, (0,0)) - self.widgets.draw(self.ventana) - pygame.display.update() - contador = 0 - while self.nivel == "menu_0": - self.reloj.tick(35) - - cambios=[] - self.widgets.clear(self.ventana, self.fondo) - if contador == 50: - # Activa la siguiente línea para provocar cambios de texto en JAMLabel - contador= self.ejemplo_cambia_texto_en_Label() - # Activa la siguiente línea para provocar cambios de imagen en JAMLabel - contador= self.ejemplo_cambia_imagen_en_Label() - # Activa la siguiente línea para provocar cambios de contenedor en JAMLabel - contador= self.ejemplo_cambia_contenedor_en_Label() - # Activa la siguiente línea para provocar cambios de posicion en JAMLabel - contador= self.ejemplo_cambia_posicion_en_Label() - - self.widgets.update() - self.handle_event() - pygame.event.clear() - cambios.extend ( self.widgets.draw(self.ventana) ) - pygame.display.update(cambios) - contador += 1 - - def ejemplo_cambia_texto_en_Label(self): - import random - cambios = ["tipo", "tamanio", "color", "texto"] - modificar = random.choice(cambios) - if modificar == "tipo": - tipos= ["Arial", "Purisa", "Times New Roman", "Vardana", "Impact", pygame.font.get_default_font()] - tipo=random.choice(tipos) - self.widgets.sprites()[0].set_text(tipo=random.choice(tipos), tamanio=None, color=None, texto=None) - if modificar == "tamanio": - tamanios= [10,20,30,40,45] - tamanio=random.choice(tamanios) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=tamanio, color=None, texto=None) - if modificar == "color": - colores= [(0,0,0,255), (100,100,255,255), (110,25,255,255), (255,125,55,255)] - color = random.choice(colores) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=None, color=color, texto=None) - if modificar == "texto": - textos= ["JAMLabel", "Presiona escape cuando quieras salir", "Modificando Texto en JAMLabel", "CeibalJAM 2011"] - texto = random.choice(textos) - self.widgets.sprites()[0].set_text(tipo=None, tamanio=None, color=None, texto=texto) - return 0 - - def ejemplo_cambia_imagen_en_Label(self): - import random - cambios = ["origen", "tamanio"] - modificar = random.choice(cambios) - if modificar == "tamanio": - tamanios= [(10,20),(30,200),(250,100)] - tamanio=random.choice(tamanios) - self.widgets.sprites()[0].set_imagen(origen=None, tamanio=tamanio) - if modificar == "origen": - origenes= [VG.get_jamimagenes()[0], VG.get_jamimagenes()[1], -1] - origen = random.choice(origenes) - self.widgets.sprites()[0].set_imagen(origen=origen, tamanio=None) - return 0 - - def ejemplo_cambia_contenedor_en_Label(self): - import random - cambios = ["colorbas", "grosor", "colorbor"] - modificar = random.choice(cambios) - - colores= [(10,20,100,255), -1,(255,255,255,255)] - color=random.choice(colores) - grosores= [1, -1, 0, 5, 10] - grosor=random.choice(grosores) - - if modificar == "colorbor": - self.widgets.sprites()[0].set_contenedor(colorbas=None, grosor=None, colorbor=color) - if modificar == "colorbas": - self.widgets.sprites()[0].set_contenedor(colorbas=color, grosor=None, colorbor=None) - if modificar == "grosor": - self.widgets.sprites()[0].set_contenedor(colorbas=None, grosor=grosor, colorbor=None) - return 0 - - def ejemplo_cambia_posicion_en_Label(self): - import random - posiciones= [(0,0), (25,25), (25,100), (25,150)] - posicion=random.choice(posiciones) - self.widgets.sprites()[0].set_posicion(punto=posicion) - return 0 - - def setup(self): - pygame.init() - pygame.display.set_mode(self.resolucion , 0, 0) - pygame.display.set_caption("Ejemplo") - - self.fondo = self.get_Fondo() - - self.widgets = pygame.sprite.OrderedUpdates() - self.widgets.add(JAMLabel("JAMLabel Prueba")) - - self.ventana = pygame.display.get_surface() - self.reloj = pygame.time.Clock() - - pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, - KEYUP, USEREVENT, QUIT, ACTIVEEVENT]) - pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, VIDEORESIZE, VIDEOEXPOSE]) - pygame.mouse.set_visible(True) - - def get_Fondo(self): - superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) - superficie.fill((128,128,128,255)) - return superficie - - def handle_event(self): - for event in pygame.event.get(): - if event.type == pygame.KEYDOWN: - self.salir() - pygame.event.clear() - - def salir(self): - print "\n" - self.widgets.sprites()[0].Describe() - pygame.quit() - sys.exit() + def __init__(self): + + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (800,300) + + self.setup() + self.Run() + + def Run(self): + self.ventana.blit(self.fondo, (0,0)) + self.widgets.draw(self.ventana) + pygame.display.update() + contador = 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios = [] + self.widgets.clear(self.ventana, self.fondo) + if contador == 50: + # Activa provocar cambios de texto en JAMLabel + contador = self.ejemplo_cambia_texto_en_Label() + # Activa provocar cambios de imagen en JAMLabel + contador = self.ejemplo_cambia_imagen_en_Label() + # Activa para provocar cambios de contenedor en JAMLabel + contador = self.ejemplo_cambia_contenedor_en_Label() + # Activa para provocar cambios de posicion en JAMLabel + contador = self.ejemplo_cambia_posicion_en_Label() + + self.widgets.update() + self.handle_event() + pygame.event.clear() + cambios.extend(self.widgets.draw(self.ventana)) + pygame.display.update(cambios) + contador += 1 + + def ejemplo_cambia_texto_en_Label(self): + import random + cambios = ["tipo", "tamanio", "color", "texto"] + modificar = random.choice(cambios) + if modificar == "tipo": + tipos = ["Arial", "Purisa", "Times New Roman", + "Vardana", "Impact", pygame.font.get_default_font()] + tipo =random.choice(tipos) + self.widgets.sprites()[0].set_text( + tipo=random.choice(tipos), tamanio=None, + color=None, texto=None) + if modificar == "tamanio": + tamanios = [10, 20, 30, 40, 45] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_text( + tipo=None, tamanio=tamanio, color=None, texto=None) + if modificar == "color": + colores = [(0, 0, 0, 255), (100, 100, 255, 255), + (110, 25, 255, 255), (255, 125, 55, 255)] + color = random.choice(colores) + self.widgets.sprites()[0].set_text( + tipo=None, tamanio=None, color=color, texto=None) + if modificar == "texto": + textos = ["JAMLabel", + "Presiona escape cuando quieras salir", + "Modificando Texto en JAMLabel", "CeibalJAM 2011"] + texto = random.choice(textos) + self.widgets.sprites()[0].set_text( + tipo=None, tamanio=None, color=None, texto=texto) + return 0 + + def ejemplo_cambia_imagen_en_Label(self): + import random + cambios = ["origen", "tamanio"] + modificar = random.choice(cambios) + if modificar == "tamanio": + tamanios = [(10, 20),(30, 200),(250, 100)] + tamanio = random.choice(tamanios) + self.widgets.sprites()[0].set_imagen(origen=None, tamanio=tamanio) + if modificar == "origen": + origenes = [VG.get_jamimagenes()[0], VG.get_jamimagenes()[1], -1] + origen = random.choice(origenes) + self.widgets.sprites()[0].set_imagen(origen=origen, tamanio=None) + return 0 + + def ejemplo_cambia_contenedor_en_Label(self): + import random + cambios = ["colorbas", "grosor", "colorbor"] + modificar = random.choice(cambios) + + colores = [(10, 20, 100, 255), -1, (255, 255, 255, 255)] + color = random.choice(colores) + grosores = [1, -1, 0, 5, 10] + grosor = random.choice(grosores) + + if modificar == "colorbor": + self.widgets.sprites()[0].set_contenedor( + colorbas=None, grosor=None, colorbor=color) + if modificar == "colorbas": + self.widgets.sprites()[0].set_contenedor( + colorbas=color, grosor=None, colorbor=None) + if modificar == "grosor": + self.widgets.sprites()[0].set_contenedor( + colorbas=None, grosor=grosor, colorbor=None) + return 0 + + def ejemplo_cambia_posicion_en_Label(self): + import random + posiciones = [(0, 0), (25, 25), (25, 100), (25, 150)] + posicion = random.choice(posiciones) + self.widgets.sprites()[0].set_posicion(punto=posicion) + return 0 + + def setup(self): + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + pygame.display.set_caption("Ejemplo") + + self.fondo = self.get_Fondo() + + self.widgets = pygame.sprite.OrderedUpdates() + self.widgets.add(JAMLabel("JAMLabel Prueba")) + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, + JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + KEYUP, USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, + MOUSEBUTTONDOWN, KEYDOWN, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def get_Fondo(self): + superficie = pygame.Surface(self.resolucion, flags=HWSURFACE) + superficie.fill((128, 128, 128, 255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + self.salir() + pygame.event.clear() + + def salir(self): + print "\n" + self.widgets.sprites()[0].Describe() + pygame.quit() + sys.exit() if __name__ == "__main__": - Ejemplo() - + Ejemplo() +''' |