From 9d57ae40095b2928672b2f4b23a87b8d5927753e Mon Sep 17 00:00:00 2001 From: flavio Date: Wed, 07 Dec 2011 23:10:50 +0000 Subject: CucaraSims Base --- (limited to 'BiblioJAM') diff --git a/BiblioJAM/JAMBoard.py b/BiblioJAM/JAMBoard.py new file mode 100644 index 0000000..e15fc68 --- /dev/null +++ b/BiblioJAM/JAMBoard.py @@ -0,0 +1,541 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 21/04/2011 - CeibalJAM! - Uruguay +# JAMBoard.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG +from JAMBoardTypes import JAMBoardTypes + +class JAMBoard(pygame.sprite.OrderedUpdates): + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + + self.tipo_buttons= "rectangulo" + self.posicion= (0,0) + self.text_buffer= "" + + self.grosor_borde1= 7 + self.separador1= 4 + self.grosor_borde2= 1 + self.separador2= 2 + + # Colores de la base + self.colores= {"base":VG.get_blanco(), "bordes":VG.get_negro()} + + self.xysimbolos= (0,0) + self.xyletras= (0,0) + self.xynumeros= (0,0) + self.xymatematicas= (0,0) + self.xyotros= (0,0) + self.xyespeciales= (0,0) + + self.board_simbolos= None + self.board_letras= None + self.board_numeros= None + self.board_matematicas= None + self.board_otros= None + self.board_especiales= None + + self.frame= pygame.sprite.Sprite() + + self.Reconstruye_JAMBoard(["todo"]) + + self.JAMObjects= {"Buffer": self.text_buffer, "Frame": self.frame, "Simbolos": self.board_simbolos, + "Letras": self.board_letras, "Numeros": self.board_numeros, "Matematicas": self.board_matematicas, + "Otros": self.board_otros, "Especiales": self.board_especiales} + + # ------------ SETEOS ----------------------- + def set_estilo(self, board, colorbase, colorborde, colorcara): + ''' Setea una gama de Colores para la base y los botones de cada JAMBoardType según indique el usuario.''' + for color in [colorbase, colorborde, colorcara]: + if type(color) != tuple or len(color) != 4: return + for valor in color: + if type(valor) != int: return + if board == "simbolos": + self.board_simbolos.set_color_base(colorborde) + self.board_simbolos.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + if board == "letras": + self.board_letras.set_color_base(colorborde) + self.board_letras.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + if board == "numeros": + self.board_numeros.set_color_base(colorborde) + self.board_numeros.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + if board == "matematicas": + self.board_matematicas.set_color_base(colorborde) + self.board_matematicas.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + if board == "otros": + self.board_otros.set_color_base(colorborde) + self.board_otros.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + if board == "especiales": + self.board_especiales.set_color_base(colorborde) + self.board_especiales.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + elif board == "todos": + self.set_color_base(colorborde, colorbase) + self.set_colors_buttons(base=colorbase, bordes=colorborde, cara=colorcara) + + def set_colors_buttons(self, base=None, bordes=None, cara=None): + ''' Setea los Colores de los botones.''' + self.board_simbolos.set_colors_buttons(base=base, bordes=bordes, cara=cara) + self.board_letras.set_colors_buttons(base=base, bordes=bordes, cara=cara) + self.board_numeros.set_colors_buttons(base=base, bordes=bordes, cara=cara) + self.board_matematicas.set_colors_buttons(base=base, bordes=bordes, cara=cara) + self.board_otros.set_colors_buttons(base=base, bordes=bordes, cara=cara) + self.board_especiales.set_colors_buttons(base=base, bordes=bordes, cara=cara) + + def set_color_base(self, colorbase, colorborde): + ''' Setea el color de la base de JAMBoard. ''' + cambios= False + if colorbase and type(colorbase) == tuple and colorbase != self.colores["base"]: + self.colores["base"]= colorbase + cambios= True + if colorborde and type(colorborde) == tuple and colorborde != self.colores["bordes"]: + self.colores["bordes"]= colorborde + cambios= True + if cambios: + self.Reconstruye_JAMBoard(["colors"]) + + def set_text(self, tipo=None, tamanio=None, color=None): + ''' Setea el tipo, tamaño y color de las letras en los botones.''' + cambios= False + if type(tipo) == str: + cambios= True + if type(tamanio) == int: + cambios= True + if type(color) == tuple: + cambios= True + if cambios: + self.board_simbolos.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.board_letras.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.board_numeros.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.board_matematicas.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.board_otros.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.board_especiales.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + self.Reconstruye_JAMBoard(["texto"]) + + def set_font_from_file(self, direccion_archivo, tamanio= None): + ''' Setea la fuente desde un archivo. ''' + self.board_simbolos.set_font_from_file(direccion_archivo, tamanio) + self.board_letras.set_font_from_file(direccion_archivo, tamanio) + self.board_numeros.set_font_from_file(direccion_archivo, tamanio) + self.board_matematicas.set_font_from_file(direccion_archivo, tamanio) + self.board_otros.set_font_from_file(direccion_archivo, tamanio) + self.board_especiales.set_font_from_file(direccion_archivo, tamanio) + self.Reconstruye_JAMBoard(["texto"]) + + def set_reconnect_sound(self, sonido): + ''' Reconecta un sonido para "select" sobre el botón. ''' + self.board_simbolos.set_reconnect_sound(sonido) + self.board_letras.set_reconnect_sound(sonido) + self.board_numeros.set_reconnect_sound(sonido) + self.board_matematicas.set_reconnect_sound(sonido) + self.board_otros.set_reconnect_sound(sonido) + self.board_especiales.set_reconnect_sound(sonido) + + def set_center(self, punto= None): + ''' Centra JAMBoard en el punto indicado. ''' + w,h= (0,0) + if not punto or type(punto) != tuple or type(punto[0]) != int or type(punto[1]) != int: + w,h= (pygame.display.Info().current_w, pygame.display.Info().current_h) + posicion= (w/2-self.frame.rect.w/2, h/2-self.frame.rect.h/2) + self.set_posicion(punto=posicion) + elif type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + posicion= (punto[0]-self.frame.rect.w/2, punto[1]-self.frame.rect.h/2) + self.set_posicion(punto=posicion) + + def set_posicion(self, punto=(0,0)): + ''' Setea la posición de cada sprite según la posición proporcionada por el usuario para todo el control. ''' + if type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + self.posicion= punto + self.frame.rect.x,self.frame.rect.y= self.posicion + posicion= (self.xysimbolos[0]+self.posicion[0], self.xysimbolos[1]+self.posicion[1]) + self.board_simbolos.set_posicion(punto=posicion) + posicion= (self.xyletras[0]+self.posicion[0], self.xyletras[1]+self.posicion[1]) + self.board_letras.set_posicion(punto=posicion) + posicion= (self.xynumeros[0]+self.posicion[0], self.xynumeros[1]+self.posicion[1]) + self.board_numeros.set_posicion(punto=posicion) + posicion= (self.xymatematicas[0]+self.posicion[0], self.xymatematicas[1]+self.posicion[1]) + self.board_matematicas.set_posicion(punto=posicion) + posicion= (self.xyotros[0]+self.posicion[0], self.xyotros[1]+self.posicion[1]) + self.board_otros.set_posicion(punto=posicion) + posicion= (self.xyespeciales[0]+self.posicion[0], self.xyespeciales[1]+self.posicion[1]) + self.board_especiales.set_posicion(punto=posicion) + + def set_tipo_button(self, tipo): + ''' Cambia el tipo de los botones. (puede ser "rectangulo" o "elipse"). ''' + if tipo == "rectangulo" or tipo == "elipse" and tipo != self.tipo_buttons: + self.tipo_buttons= tipo + self.board_simbolos.set_tipo_button(self.tipo_buttons) + self.board_letras.set_tipo_button(self.tipo_buttons) + self.board_numeros.set_tipo_button(self.tipo_buttons) + self.board_matematicas.set_tipo_button(self.tipo_buttons) + self.board_otros.set_tipo_button(self.tipo_buttons) + self.board_especiales.set_tipo_button(self.tipo_buttons) + self.Reconstruye_JAMBoard(["tipo"]) + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.frame.rect.w, self.frame.rect.h) + + # ------------ CONSTRUCCIÓN ----------------------- + def Reconstruye_JAMBoard(self, cambios): + '''Reconstruye JAMBoard cuando se setean valores en él. ''' + if "todo" in cambios: + self.board_simbolos= JAMBoardTypes("simbolos") + self.board_letras= JAMBoardTypes("letras") + self.board_numeros= JAMBoardTypes("numeros") + self.board_matematicas= JAMBoardTypes("matematicas") + self.board_otros= JAMBoardTypes("otros") + self.board_especiales= JAMBoardTypes("especiales") + + self.get_frame() + + self.add(self.frame) + self.add(self.board_simbolos) + self.add(self.board_letras) + self.add(self.board_numeros) + self.add(self.board_matematicas) + self.add(self.board_otros) + self.add(self.board_especiales) + + # Reconectando Click sobre los botones de los JAMBoardTypes + self.board_simbolos.set_callback(self.handle_click) + self.board_letras.set_callback(self.handle_click) + self.board_numeros.set_callback(self.handle_click) + self.board_matematicas.set_callback(self.handle_click) + self.board_otros.set_callback(self.handle_click) + self.board_especiales.set_callback(self.handle_click) + + self.set_posicion(punto=self.posicion) + + if "tipo" in cambios or "texto" in cambios: + self.get_frame() + self.set_posicion(punto=self.posicion) + if "colors" in cambios: + self.get_frame() + self.board_simbolos.set_color_base(self.colores["base"]) + self.board_letras.set_color_base(self.colores["base"]) + self.board_numeros.set_color_base(self.colores["base"]) + self.board_matematicas.set_color_base(self.colores["base"]) + self.board_otros.set_color_base(self.colores["base"]) + self.board_especiales.set_color_base(self.colores["base"]) + self.set_posicion(punto=self.posicion) + + def get_frame(self): + # recuadro interior + sep= self.grosor_borde1 + self.separador1 + self.grosor_borde2 + self.separador2 + + espacio1, espacio2=(0,0) + if self.board_letras.frame.rect.w > self.board_simbolos.frame.rect.w: + espacio1= self.board_letras.frame.rect.w + else: + espacio1= self.board_simbolos.frame.rect.w + + if self.board_especiales.frame.rect.w > self.board_otros.frame.rect.w: + espacio2= self.board_especiales.frame.rect.w + else: + espacio2= self.board_otros.frame.rect.w + + w= (self.grosor_borde2 + self.separador2)*2 + espacio1 + self.separador1 + espacio2 + h= self.board_simbolos.frame.rect.h + (self.grosor_borde2 + self.separador2)*2 + self.separador1 + self.board_letras.frame.rect.h + + # posicion para board letras + self.xysimbolos= (sep,sep) + self.xynumeros= (self.xysimbolos[0] + self.board_simbolos.frame.rect.w + self.separador1, self.xysimbolos[1]) + self.xymatematicas= (self.xynumeros[0], self.xynumeros[1] + self.board_numeros.frame.rect.h + self.separador1) + + self.xyletras= (self.xysimbolos[0], self.xysimbolos[1] + self.board_simbolos.frame.rect.h + self.separador1) + + self.xyotros= (self.xyletras[0] + self.board_letras.frame.rect.w + self.separador1, self.xyletras[1] + self.board_letras.frame.rect.h - self.board_otros.frame.rect.h) + + self.xyespeciales= (self.xyletras[0] + self.board_letras.frame.rect.w + self.separador1, self.xyotros[1] - self.separador1 - self.board_especiales.frame.rect.h) + + tamanio= (w,h) + superficie= VG.get_Rectangulo(self.colores["base"], tamanio) + superficie= VG.get_my_surface_whit_border(superficie, self.colores["bordes"], self.grosor_borde2) + + # recuadro exterior + tamanio= (w + (self.grosor_borde1 + self.separador1)*2, h + (self.grosor_borde1 + self.separador1)*2) + superficie1= VG.get_Rectangulo(self.colores["base"], tamanio) + superficie1= VG.get_my_surface_whit_border(superficie1, self.colores["bordes"], self.grosor_borde1) + + # armado final de la base + self.frame.image= VG.pegar_imagenes_centradas(superficie, superficie1) + self.frame.rect= self.frame.image.get_rect() + # ------------ CONSTRUCCIÓN ----------------------- + + # ----------- DETECTOR DE EVENTOS ---------------- + def handle_click(self, boton=None): + ''' Detecta los click sobre los botones devolviendo la letra o simbolo que el mismo contiene. ''' + ''' Modificaciones del 29 de Mayo tras modificar callback de JAMButton para pasarse a si mismo. ''' + ''' + posicion = pygame.mouse.get_pos() + for boton in self.board_letras.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + for boton in self.board_numeros.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + + for boton in self.board_simbolos.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + + for boton in self.board_otros.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + + for boton in self.board_matematicas.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + + for boton in self.board_especiales.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return ''' + + if boton in self.board_letras.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + elif boton in self.board_numeros.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + elif boton in self.board_simbolos.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + elif boton in self.board_otros.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + elif boton in self.board_matematicas.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + elif boton in self.board_especiales.botones: + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + print self.text_buffer + return + + + def Describe(self): + ''' Describe la Estructura de Este Control. ''' + estructura = ''' + Estructura JAMBoard: + + JAMObject: + Frame + Text_Buffer + JAMBoardTypes simbolos + JAMBoardTypes letras + JAMBoardTypes numeros + JAMBoardTypes matematicas + JAMBoardTypes otros + JAMBoardTypes especiales''' + + print estructura, "\n" + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + +# ----- FIN DE CLASE JAMBoard - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1200,800) + + self.setup() + self.Run() + + 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 = JAMBoard() + self.widgets.set_posicion(punto=(25,25)) + + 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 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 == 150: + # Activa la siguiente línea para provocar cambios en el tipo de botones en JAMBoard + contador= self.ejemplo_cambia_tipo_de_botones() + # Activa la siguiente línea para provocar cambios de colores en JAMBoard + contador= self.ejemplo_cambia_colors_Board() + # Activa la siguiente línea para provocar cambios de texto en Botones + contador= self.ejemplo_cambia_texto_en_JAMBoard() + # Activa la siguiente línea para provocar cambios de posicion en JAMBoard + contador= self.ejemplo_cambia_posicion_de_JAMBoard() + # Activa la siguiente línea para desconectar el sonido select sobre los botones + #self.widgets.set_reconnect_sound(None) + # Activa la siguiente línea para ver el contenido del buffer de JAMBoard + #print self.widgets.text_buffer + # Activa la siguiente línea para cambiar los estilos de colores en JAMBoard + contador= self.ejemplo_cambia_estilos() + contador= 0 + + 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_estilos(self): + import random + estilos= [VG.get_estilo_naranja(), VG.get_estilo_gris(), VG.get_estilo_celeste()] + a,b,c= random.choice(estilos) + cambios = ["simbolos", "letras", "numeros", "matematicas", "otros", "especiales", + "simbolos", "letras", "numeros", "matematicas", "otros", "especiales", "todos"] + tipo = random.choice(cambios) + self.widgets.set_estilo(tipo,a,b,c) + + def ejemplo_cambia_tipo_de_botones(self): + import random + cambios = ["rectangulo", "elipse"] + tipo = random.choice(cambios) + self.widgets.set_tipo_button(tipo) + + def ejemplo_cambia_texto_en_JAMBoard(self): + import random + cambios = ["tipo", "tamanio", "color"] + 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.set_text(tipo=random.choice(tipos), tamanio=None, color=None) + if modificar == "tamanio": + tamanios= [10,15,20,25] + tamanio=random.choice(tamanios) + self.widgets.set_text(tipo=None, tamanio=tamanio, color=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.set_text(tipo=None, tamanio=None, color=color) + return 0 + + def ejemplo_cambia_colors_Board(self): + import random + cambios = ["colorbas", "colorbor", "colorcara"] + modificar = random.choice(cambios) + + colores= [(10,20,100,255), (128,128,128,255), (255,255,255,255), (200,100,0,255), (240,150,0,255), (255,220,0,255)] + color=random.choice(colores) + + self.widgets.set_color_base(random.choice(colores), random.choice(colores)) + + if modificar == "colorbor": + self.widgets.set_colors_buttons(base=None, bordes=color, cara=None) + if modificar == "colorbas": + self.widgets.set_colors_buttons(base=color, bordes=None, cara=None) + if modificar == "colorcara": + self.widgets.set_colors_buttons(base=None, bordes=None, cara=color) + return 0 + + def ejemplo_cambia_posicion_de_JAMBoard(self): + import random + tipos= ["centro", "normal"] + tipo=random.choice(tipos) + if tipo == "centro": + posiciones= [(500,400), None] + posicion= (random.choice(posiciones)) + self.widgets.set_center(punto= posicion) + elif tipo == "normal": + return + posiciones= [(10,20),(25,25),(50,20), (85,100), (100,150)] + posicion=random.choice(posiciones) + self.widgets.set_posicion(punto=posicion) + return 0 + + 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): + print "\n" + self.widgets.Describe() + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMBoardEntryText.py b/BiblioJAM/JAMBoardEntryText.py new file mode 100644 index 0000000..e845717 --- /dev/null +++ b/BiblioJAM/JAMBoardEntryText.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 21/04/2011 - CeibalJAM! - Uruguay +# JAMBoardEntryText.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, tempfile +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG +from JAMBoard import JAMBoard +from JAMEntryText import JAMEntryText + +class JAMBoardEntryText(pygame.sprite.OrderedUpdates): + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + + self.posicion= (100,25) + self.text_buffer= [] + self.tamanio_buffer= 87 + self.tilde= False + self.tildes= VG.get_tildes_up() + self.callback_enter= None + + # Colores de la base + self.colores= {"base":VG.get_blanco(), "bordes":VG.get_negro()} + + self.board= None + self.entry= None + self.frame_entry= pygame.sprite.Sprite() + + self.Reconstruye_JAMBoardEntryText(["todo"]) + + self.JAMObjects= {"Buffer": self.text_buffer, "Frame": self.frame_entry, "Board": self.board, "EntryText": self.entry} + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.frame_entry.rect.w, self.frame_entry.rect.h) + + # ------------ SETEOS ----------------------- + def set_posicion(self, punto=(0,0)): + ''' Setea la posición de JAMBoardEntryText. ''' + if type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + self.posicion= punto + self.frame_entry.rect.x, self.frame_entry.rect.y= self.posicion + x,y= (self.posicion[0], self.posicion[1] + self.frame_entry.rect.h - self.board.grosor_borde1/2) + self.board.set_posicion(punto= (x,y)) + centro= (self.frame_entry.rect.centerx, self.frame_entry.rect.centery) + x,y= (centro[0]-self.entry.frame.rect.w/2, centro[1]-self.entry.frame.rect.h/2) + self.entry.set_posicion(punto= (x, y)) + + def set_center(self, punto= None): + ''' Centra JAMBoardEntryText en el punto indicado. ''' + w,h= (0,0) + if not punto or type(punto) != tuple or type(punto[0]) != int or type(punto[1]) != int: + w,h= (pygame.display.Info().current_w, pygame.display.Info().current_h) + posicion= (w/2-self.frame_entry.rect.w/2, h/2-self.frame_entry.rect.h/2-self.board.frame.rect.h/2) + self.set_posicion(punto=posicion) + elif type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + posicion= (punto[0]-self.frame_entry.rect.w/2, punto[1]-self.frame_entry.rect.h/2-self.board.frame.rect.h/2) + self.set_posicion(punto=posicion) + + def set_estilo(self, colorbase, colorborde, colorcara): + ''' Setea los colores del control a partir de un estilo predefinido. ''' + self.board.set_estilo("todos", colorbase, colorborde, colorcara) + self.entry.set_entry(tipo_letra=None, tamanio_letra=None, color_texto=None, color_fondo=colorborde) + self.Reconstruye_JAMBoardEntryText(["estilo"]) + + def connect_callback_enter(self, callback): + ''' Conecta click sobre el botón enter a una función que recibirá el texto en el buffer de JAMBoardEntryText.''' + self.callback_enter= callback + + # ------------ CONSTRUCCIÓN ----------------------- + def Reconstruye_JAMBoardEntryText(self, cambios): + '''Reconstruye JAMBoardEntryText cuando se setean valores en él. ''' + if "todo" in cambios: + self.board= JAMBoard() + self.entry= JAMEntryText() + self.frame_entry.image= self.get_frame_entry() + self.frame_entry.rect= self.frame_entry.image.get_rect() + + self.add(self.frame_entry) + self.add(self.board) + self.add(self.entry) + + # Reconectando Click sobre los botones de los JAMBoardTypes + self.board.board_simbolos.set_callback(self.handle_click) + self.board.board_letras.set_callback(self.handle_click) + self.board.board_numeros.set_callback(self.handle_click) + self.board.board_matematicas.set_callback(self.handle_click) + self.board.board_otros.set_callback(self.handle_click) + self.board.board_especiales.set_callback(self.handle_click) + + self.set_posicion(punto=self.posicion) + + if "estilo" in cambios: + self.frame_entry.image= self.get_frame_entry() + self.set_posicion(punto=self.posicion) + + def get_frame_entry(self): + w= self.board.frame.rect.w - (self.board.grosor_borde1 + self.board.separador1)*2 + h= self.entry.frame.rect.h + (self.board.grosor_borde2 + self.board.separador2)*2 + contenedor1= VG.get_Rectangulo(self.board.colores["base"], (w,h)) + contenedor1= VG.get_my_surface_whit_border(contenedor1, self.board.colores["bordes"], self.board.grosor_borde2) + a,b,w,h= contenedor1.get_rect() + w += (self.board.grosor_borde1 + self.board.separador1)*2 + h += (self.board.grosor_borde1 + self.board.separador1)*2 + contenedor2= VG.get_Rectangulo(self.board.colores["base"], (w,h)) + contenedor2= VG.pegar_imagenes_centradas(contenedor1, contenedor2) + contenedor2= VG.get_my_surface_whit_border(contenedor2, self.board.colores["bordes"], self.board.grosor_borde1) + return contenedor2 + # ------------ CONSTRUCCIÓN ----------------------- + + # ----------- DETECTOR DE EVENTOS ---------------- + def handle_click(self, boton=None): + ''' Detecta los click sobre los botones devolviendo la letra o simbolo que el mismo contiene. ''' + ''' Correcciones del 29 de mayo de 2011 tras modificar callback de JAMButton pasandose a si mismo en la llamada. ''' + ''' + posicion = pygame.mouse.get_pos() + for boton in self.board.board_letras.botones: + if boton.rect.collidepoint(posicion): + texto= boton.get_text() + if self.tilde: + if texto== "A": + texto= self.tildes[0] + elif texto== "E": + texto= self.tildes[1] + elif texto== "I": + texto= self.tildes[2] + elif texto== "O": + texto= self.tildes[3] + elif texto== "U": + texto= self.tildes[4] + + self.text_buffer.append( texto ) + self.tilde= False + return self.set_bufferentry() ''' + ''' + for boton in self.board.board_numeros.botones: + if boton.rect.collidepoint(posicion): + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry()''' + ''' + for boton in self.board.board_simbolos.botones: + if boton.rect.collidepoint(posicion): + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry()''' + ''' + for boton in self.board.board_otros.botones: + if boton.rect.collidepoint(posicion): + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry()''' + ''' + for boton in self.board.board_matematicas.botones: + if boton.rect.collidepoint(posicion): + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry()''' + ''' + for boton in self.board.board_especiales.botones: + if boton.rect.collidepoint(posicion): + texto= boton.get_text() + if texto== "Espacio": + # agrega un espacio en el buffer + self.text_buffer.append( " " ) + self.tilde= False + return self.set_bufferentry() + + elif texto== "Borrar": + # Borra el último caracter ingresado + if len(self.text_buffer) <= 1: + self.text_buffer= [ " " ] + else: + self.text_buffer= self.text_buffer[0:-1] + self.tilde= False + return self.set_bufferentry() + + elif texto== "Enter": + # Llama a la función conectada al click del botón enter, pasandole como parámetro el texto en el buffer + self.tilde= False + if self.callback_enter: + buf= "" + for x in self.text_buffer: + buf += x + return self.callback_enter(buf) + + elif texto== "´": + self.tilde= True ''' + + if boton in self.board.board_letras.botones: + texto= boton.get_text() + if self.tilde: + if texto== "A": + texto= self.tildes[0] + elif texto== "E": + texto= self.tildes[1] + elif texto== "I": + texto= self.tildes[2] + elif texto== "O": + texto= self.tildes[3] + elif texto== "U": + texto= self.tildes[4] + + self.text_buffer.append( texto ) + self.tilde= False + return self.set_bufferentry() + + elif boton in self.board.board_numeros.botones: + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry() + + elif boton in self.board.board_simbolos.botones: + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry() + + elif boton in self.board.board_otros.botones: + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry() + + elif boton in self.board.board_matematicas.botones: + self.text_buffer.append( boton.get_text() ) + self.tilde= False + return self.set_bufferentry() + + elif boton in self.board.board_especiales.botones: + texto= boton.get_text() + if texto== "Espacio": + # agrega un espacio en el buffer + self.text_buffer.append( " " ) + self.tilde= False + return self.set_bufferentry() + + elif texto== "Borrar": + # Borra el último caracter ingresado + if len(self.text_buffer) <= 1: + self.text_buffer= [ " " ] + else: + self.text_buffer= self.text_buffer[0:-1] + self.tilde= False + return self.set_bufferentry() + + elif texto== "Enter": + # Llama a la función conectada al click del botón enter, pasandole como parámetro el texto en el buffer + self.tilde= False + if self.callback_enter: + buf= "" + for x in self.text_buffer: + buf += x + return self.callback_enter(buf) + + elif texto== "´": + self.tilde= True + + + def set_bufferentry(self): + if len(self.text_buffer) < self.tamanio_buffer: + buf= "" + for x in self.text_buffer: + buf += x + self.entry.set_buffer(buf) + self.set_posicion(punto=self.posicion) + + def Describe(self): + ''' Describe la Estructura de Este Control. ''' + estructura = ''' + Estructura JAMBoardEntryText: + + JAMObject: + Frame + Text_Buffer + JAMBoard + EntryText''' + + print estructura, "\n" + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + +# ----- FIN DE CLASE JAMBoardEntryText - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1000,500) + + self.setup() + self.Run() + + 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 = JAMBoardEntryText() + self.widgets.connect_callback_enter(self.Imprime_buffer) + a,b,c= VG.get_estilo_naranja() + self.widgets.set_estilo(a, b, c) + self.widgets.set_center(punto= (500,250)) + + 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 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 == 150: + # Activa la siguiente línea para provocar cambios en el tipo de botones en JAMBoardEntryText + #contador= self.ejemplo_cambia_tipo_de_botones() + # Activa la siguiente línea para provocar cambios de colores en JAMBoardEntryText + #contador= self.ejemplo_cambia_colors_Board() + # Activa la siguiente línea para provocar cambios de texto en Botones + #contador= self.ejemplo_cambia_texto_en_JAMBoardEntryText() + # Activa la siguiente línea para provocar cambios de posicion en JAMBoardEntryText + #contador= self.ejemplo_cambia_posicion_de_JAMBoardEntryText() + # Activa la siguiente línea para desconectar el sonido select sobre los botones + #self.widgets.set_reconnect_sound(None) + # Activa la siguiente línea para ver el contenido del buffer de JAMBoardEntryText + #print self.widgets.text_buffer + # Activa la siguiente línea para cambiar los estilos de colores en JAMBoardEntryText + #contador= self.ejemplo_cambia_estilos() + contador= 0 + + 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_estilos(self): + import random + estilos= [VG.get_estilo_naranja(), VG.get_estilo_gris(), VG.get_estilo_celeste()] + a,b,c= random.choice(estilos) + cambios = ["simbolos", "letras", "numeros", "matematicas", "otros", "especiales", + "simbolos", "letras", "numeros", "matematicas", "otros", "especiales", "todos"] + tipo = random.choice(cambios) + self.widgets.set_estilo(tipo,a,b,c) + + def ejemplo_cambia_tipo_de_botones(self): + import random + cambios = ["rectangulo", "elipse"] + tipo = random.choice(cambios) + self.widgets.set_tipo_button(tipo) + + def ejemplo_cambia_texto_en_JAMBoardEntryText(self): + import random + cambios = ["tipo", "tamanio", "color"] + 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.set_text(tipo=random.choice(tipos), tamanio=None, color=None) + if modificar == "tamanio": + tamanios= [10,15,20,25] + tamanio=random.choice(tamanios) + self.widgets.set_text(tipo=None, tamanio=tamanio, color=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.set_text(tipo=None, tamanio=None, color=color) + return 0 + + def ejemplo_cambia_colors_Board(self): + import random + cambios = ["colorbas", "colorbor", "colorcara"] + modificar = random.choice(cambios) + + colores= [(10,20,100,255), (128,128,128,255), (255,255,255,255), (200,100,0,255), (240,150,0,255), (255,220,0,255)] + color=random.choice(colores) + + self.widgets.set_color_base(random.choice(colores), random.choice(colores)) + + if modificar == "colorbor": + self.widgets.set_colors_buttons(base=None, bordes=color, cara=None) + if modificar == "colorbas": + self.widgets.set_colors_buttons(base=color, bordes=None, cara=None) + if modificar == "colorcara": + self.widgets.set_colors_buttons(base=None, bordes=None, cara=color) + return 0 + + def ejemplo_cambia_posicion_de_JAMBoardEntryText(self): + import random + tipos= ["centro", "normal"] + tipo=random.choice(tipos) + if tipo == "centro": + posiciones= [(500,400), None] + posicion= (random.choice(posiciones)) + self.widgets.set_center(punto= posicion) + elif tipo == "normal": + return + posiciones= [(10,20),(25,25),(50,20), (85,100), (100,150)] + posicion=random.choice(posiciones) + self.widgets.set_posicion(punto=posicion) + return 0 ''' + + def Imprime_buffer(self, buf): + print buf + self.salir() + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill(VG.get_gris1()) + 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.Describe() + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMBoardTypes.py b/BiblioJAM/JAMBoardTypes.py new file mode 100644 index 0000000..a3ba06e --- /dev/null +++ b/BiblioJAM/JAMBoardTypes.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 19/04/2011 - CeibalJAM! - Uruguay +# JAMBoardTypes.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG +from JAMLabel import JAMLabel +from JAMButton import JAMButton + +class JAMBoardTypes(pygame.sprite.OrderedUpdates): + def __init__(self, tipo="letras"): + pygame.sprite.OrderedUpdates.__init__(self) + self.tipo= tipo + + if self.tipo == "letras" or self.tipo == "letras_down" or self.tipo == "simbolos": + self.columnas, self.filas= (9, 3) + elif self.tipo == "numeros": + self.columnas, self.filas= (5,2) + elif self.tipo == "otros": + self.columnas, self.filas= (6, 1) + elif self.tipo == "matematicas": + self.columnas, self.filas= (5,1) + elif self.tipo == "especiales": + self.columnas, self.filas= (4, 1) + else: + self.tipo= "letras" + self.columnas, self.filas= (9, 3) + + self.tipo_buttons= "rectangulo" + self.posicion= (0,0) + self.text_buffer= "" + + self.colores= {"base":VG.get_blanco(), "bordes":VG.get_negro(), "cara":VG.get_blanco(), "frame": VG.get_blanco()} + + self.botones= None + self.frame= pygame.sprite.Sprite() + self.grilla= None + + self.callback= self.handle_click + self.sonido= VG.get_sound_select() + + self.Reconstruye_JAMBoardTypes(["todo"]) + + self.JAMObjects= {"frame": self.frame, "grilla":self.grilla, "botones":self.botones, "text_buffer": self.text_buffer} + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.frame.rect.w, self.frame.rect.h) + + # ------------ SETEOS ----------------------- + def set_buffer(self, texto): + ''' Setea el buffer de texto. ''' + if texto != self.text_buffer: + self.text_buffer = texto + + def set_colors_buttons(self, base=None, bordes=None, cara=None): + ''' Setea los Colores de los botones. ''' + if not base: base= VG.get_blanco() + if not bordes: bordes= VG.get_negro() + if not cara: cara= VG.get_blanco() + + cambios= False + if base != self.colores["base"]: + self.colores["base"]= base + cambios= True + if bordes != self.colores["bordes"]: + self.colores["bordes"]= bordes + cambios= True + if cara != self.colores["cara"]: + self.colores["cara"]= cara + cambios= True + if cambios: + self.Reconstruye_JAMBoardTypes(["colores"]) + + def set_color_base(self, color): + ''' Setea el color de la base de JAMBoardTypes. ''' + if color and type(color) == tuple and color != self.colores["frame"]: + self.colores["frame"]= color + self.get_frame_and_grilla() + self.set_posicion(punto=self.posicion) + + def set_text(self, tipo=None, tamanio=None, color=None): + ''' Setea el tipo, tamaño y color de las letras en los botones. ''' + cambiosx= False + for button in self.botones: + cambios= False + if type(tipo) == str: + cambios= True + if type(tamanio) == int: + cambios= True + if type(color) == tuple: + cambios= True + if cambios: + button.set_text(tipo=tipo, tamanio=tamanio, color=color)#, texto=None) + cambiosx= True + if cambiosx: + self.Reconstruye_JAMBoardTypes(["texto"]) + + def set_font_from_file(self, direccion_archivo, tamanio= None): + ''' Setea la fuente desde un archivo. ''' + for button in self.botones: + button.set_font_from_file(direccion_archivo, tamanio) + self.Reconstruye_JAMBoardTypes(["texto"]) + + def set_reconnect_sound(self, sonido): + ''' Reconecta un sonido para "select" sobre el botón. ''' + self.sonido= sonido + for button in self.botones: + button.connect(callback= button.callback, sonido_select= self.sonido) + def set_callback(self, callback): + ''' Reconecta a una función para click sobre el botón. ''' + self.callback= callback + for button in self.botones: + button.connect(callback=self.callback, sonido_select=button.sonido_select) + + def set_center(self, punto= None): + ''' Centra JAMBoardTypes en el punto indicado. ''' + if not punto or type(punto) != tuple or type(punto[0]) != int or type(punto[1]) != int: + posicion= (pygame.display.Info().current_w/2, pygame.display.Info().current_h/2) + self.set_center(punto= posicion) + elif type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + posicion= (punto[0]-self.frame.rect.w/2, punto[1]-self.frame.rect.h/2) + self.set_posicion(punto=posicion) + + def set_posicion(self, punto=(0,0)): + ''' Setea la posición de cada sprite según la posición proporcionada por el usuario para todo el control. ''' + if type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + # SE MUEVE LA BASE DE LAS LETRAS + self.posicion= punto + x,y= self.posicion + self.frame.rect.x= x + self.frame.rect.y= y + # SE MUEVEN LAS LETRAS + for n in range (0, len(self.botones)): + xx, yy= (self.grilla[n][0]+x, self.grilla[n][1]+y) + self.botones[n].set_posicion(punto=(xx,yy)) + + def set_tipo_button(self, tipo): + ''' Cambia el tipo de los botones. (puede ser "rectangulo" o "elipse"). ''' + if tipo == "rectangulo" or tipo == "elipse" and tipo != self.tipo_buttons: + self.tipo_buttons= tipo + for button in self.botones: + button.set_tipo(self.tipo_buttons) + self.Reconstruye_JAMBoardTypes(["tipo"]) + # ------------ SETEOS ----------------------- + + # ------------ CONSTRUCCIÓN ----------------------- + def Reconstruye_JAMBoardTypes(self, cambios): + ''' Reconstruye JAMBoardTypes cuando se setean valores en él. ''' + if "todo" in cambios: + self.botones= self.get_botones_letras() + self.set_normaliza_tamanios_botones() + self.get_frame_and_grilla() + self.add(self.frame) + self.add(self.botones) + self.set_posicion(punto=self.posicion) + if "tipo" in cambios or "texto" in cambios: + self.set_normaliza_tamanios_botones() + self.get_frame_and_grilla() + self.set_posicion(punto=self.posicion) + if "colores" in cambios: + for button in self.botones: + button.set_colores(colorbas=self.colores["base"], colorbor=self.colores["bordes"], colorcara=self.colores["cara"]) + + def get_botones_letras(self): + ''' Construye y Devuelve los Botones. ''' + if self.tipo == "letras": + simbols= VG.get_letras_up() + elif self.tipo == "numeros": + simbols= VG.get_numeros() + elif self.tipo == "letras_down": + simbols= VG.get_letras_down() + elif self.tipo == "simbolos": + simbols= VG.get_simbols() + elif self.tipo == "otros": + simbols= VG.get_otros() + elif self.tipo == "matematicas": + simbols= VG.get_matematicas() + elif self.tipo == "especiales": + simbols= VG.get_especiales() + else: + self.tipo= "letras" + simbols= VG.get_letras_up() + botones_letras= [] + for letra in simbols: + boton= JAMButton(letra, None, tipo= self.tipo_buttons) + botones_letras.append(boton) + boton.connect(callback=self.callback, sonido_select=self.sonido) + return botones_letras + def set_normaliza_tamanios_botones(self): + ''' Normaliza los Tamaños de los botones. ''' + if self.tipo == "especiales": + alto= 0 + for button in self.botones: + button.set_tamanios(tamanio=(0,0)) # Para que queden lo más pequeño posible. + if button.rect.h > alto: alto= button.rect.h + for button in self.botones: + button.set_tamanios(tamanio=(button.rect.w,alto)) + else: + lado= 0 + for button in self.botones: + button.set_tamanios(tamanio=(0,0)) # Para que queden lo más pequeño posible. + if button.rect.w > lado: + lado= button.rect.w + if button.rect.h > lado: + lado= button.rect.h + for button in self.botones: + button.set_tamanios(tamanio=(lado,lado)) + + def get_frame_and_grilla(self): + ''' Construye el sprite base para los botones de letras y una lista de posiciones para cada botón. ''' + if self.tipo == "especiales": + ancho, alto= (0,0) + posiciones= [] + for button in self.botones: # es una sola fila + posiciones.append( (ancho,alto) ) + ancho += button.rect.w + alto= button.rect.h + self.frame.image= VG.get_Rectangulo(self.colores["frame"], (ancho, alto)) + self.frame.rect= self.frame.image.get_rect() + self.grilla= posiciones + else: + # Contenedor para los botones + ancho, alto=(0,0) + for x in range(self.columnas): + ancho+= self.botones[x].rect.w + for x in range(self.filas): + alto+= self.botones[x].rect.h + self.frame.image= VG.get_Rectangulo(self.colores["frame"], (ancho, alto)) + self.frame.rect= self.frame.image.get_rect() + self.grilla= VG.get_grilla(self.frame.image, self.columnas, self.filas) + # ------------ CONSTRUCCIÓN ----------------------- + + # ----------- DETECTOR DE EVENTOS (es el callback de los botones)---------------- + def handle_click(self, boton=None): + ''' Detecta los click sobre los botones devolviendo la letra o simbolo que el mismo contiene. ''' + ''' Modificaciones del 29 de Mayo tras modificar callback de JAMButton para pasarse a si mismo. ''' + ''' + posicion = pygame.mouse.get_pos() + for boton in self.botones: + if boton.rect.collidepoint(posicion): + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + #print self.text_buffer + return ''' + if self.text_buffer == " ": + self.text_buffer = "" + self.text_buffer += boton.get_text() + #print self.text_buffer + return + + def Describe(self): + ''' Describe la Estructura de Este Control. ''' + estructura = ''' + Estructura JAMBoardTypes: + + JAMObject: + Frame + Grilla + Botones + Text_Buffer + + Descripción: + + Frame es un sprite que sirve de imagen base sobre la que se dibujarán los botones. + Grilla es una lista de posiciones x,y para cada botón. + Botones son los botones con las letras. + Text_Buffer donde se guarda el texto que se genera al presionar los botones. + ''' + + print estructura, "\n" + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + +# ----- FIN DE CLASE JAMBoardTypes - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1000,800) + + self.setup() + self.Run() + + 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 = JAMBoardTypes(tipo="letras") + self.widgets.set_posicion(punto=(25,25)) + self.widgets.set_tipo_button("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 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 == 150: + # Activa la siguiente línea para provocar cambios en el tipo de botones en JAMBoardTypes + contador= self.ejemplo_cambia_tipo_de_botones() + # Activa la siguiente línea para provocar cambios de colores en JAMBoardTypes + contador= self.ejemplo_cambia_colors_Board() + # Activa la siguiente línea para provocar cambios de texto en Botones + contador= self.ejemplo_cambia_texto_en_JAMBoardTypes() + # Activa la siguiente línea para provocar cambios de posicion en JAMBoardTypes + contador= self.ejemplo_cambia_posicion_de_JAMBoardTypes() + # Activa la siguiente línea para desconectar el sonido select sobre los botones + #self.widgets.set_reconnect_sound(None) + # Activa la siguiente línea para ver el contenido del buffer de JAMBoardTypes + #print self.widgets.text_buffer + contador= 0 + + 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_tipo_de_botones(self): + import random + cambios = ["rectangulo", "elipse"] + tipo = random.choice(cambios) + self.widgets.set_tipo_button(tipo) + + def ejemplo_cambia_texto_en_JAMBoardTypes(self): + import random + cambios = ["tipo", "tamanio", "color"] + 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.set_text(tipo=random.choice(tipos), tamanio=None, color=None) + if modificar == "tamanio": + tamanios= [8,12,16,20,24,28] + tamanio=random.choice(tamanios) + self.widgets.set_text(tipo=None, tamanio=tamanio, color=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.set_text(tipo=None, tamanio=None, color=color) + return 0 + + def ejemplo_cambia_colors_Board(self): + import random + cambios = ["colorbas", "colorbor", "colorcara"] + modificar = random.choice(cambios) + + colores= [(10,20,100,255), (128,128,128,255), (255,255,255,255)] + color=random.choice(colores) + + if modificar == "colorbor": + self.widgets.set_colors_buttons(base=None, bordes=color, cara=None) + if modificar == "colorbas": + self.widgets.set_colors_buttons(base=color, bordes=None, cara=None) + if modificar == "colorcara": + self.widgets.set_colors_buttons(base=None, bordes=None, cara=color) + + self.widgets.set_color_base(random.choice(colores)) + return 0 + + def ejemplo_cambia_posicion_de_JAMBoardTypes(self): + import random + tipos= ["centro", "normal"] + tipo=random.choice(tipos) + if tipo == "centro": + posiciones= [(500,400), None] + posicion= (random.choice(posiciones)) + self.widgets.set_center(punto= posicion) + elif tipo == "normal": + return + posiciones= [(10,20),(25,25),(50,20), (85,100), (100,150)] + posicion=random.choice(posiciones) + self.widgets.set_posicion(punto=posicion) + return 0 + + 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): + print "\n" + self.widgets.Describe() + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMBook.py b/BiblioJAM/JAMBook.py new file mode 100644 index 0000000..f01e993 --- /dev/null +++ b/BiblioJAM/JAMBook.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 05/06/2011 - CeibalJAM! - Uruguay +# JAMBook.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, sys, gc, subprocess +from pygame.locals import * + +gc.enable() + +from JAMLabel import JAMLabel +from JAMButton import JAMButton + +import JAMGlobals as VG + +class JAMBook(pygame.sprite.OrderedUpdates): + ''' Libreta para lectura con los botones de navegación y motor de voz. ''' + def __init__(self, lectura): + pygame.sprite.OrderedUpdates.__init__(self) + + self.tamanio_hoja= (452,700) #(592,840) + self.margen= 0 + self.lectura= lectura + + self.hoja= None + self.rectangulo_texto= (0,0,0,0) + self.texto_sprite= None + self.botones= [] + + self.posicion= (0,0) + + self.Reconstruye(["todo"]) + + def Reconstruye(self, cambios): + ''' Reconstruye JAMBook según cambios. ''' + if "todo" in cambios: + self.hoja= pygame.sprite.Sprite() + self.hoja.image, self.margen= VG.get_hoja(self.tamanio_hoja) + self.hoja.rect= self.hoja.image.get_rect() + + self.rectangulo_texto= Rectangulo_Texto(self, (0,0,self.hoja.rect[2]-self.margen*1.5,self.hoja.rect[3]-self.margen*2)) + self.texto_sprite= Texto_sprite(self) + self.botones= self.get_botones() + + self.add(self.hoja) + self.add(self.texto_sprite) + self.add(self.botones) + + self.set_posicion(punto=self.posicion) + + # ----------------- SETEOS ----------------------------- + def set_posicion(self, punto=(0,0)): + ''' Setea la posicion de todos los sprites miembros. ''' + if not type(punto)== tuple or not len(punto)==2 or not type(punto[0])== int or not type(punto[0])== int: return + self.posicion= punto + self.hoja.rect.x, self.hoja.rect.y= self.posicion + self.rectangulo_texto.set_posicion(punto=(self.hoja.rect.x+self.margen,self.hoja.rect.y+self.margen/2)) + + x,y,w,h= self.hoja.rect # posicionar los botones + self.botones[0].set_posicion(punto=(x, y+h-self.botones[1].get_tamanio()[1])) + self.botones[1].set_posicion(punto=(x+w-self.botones[1].get_tamanio()[0], y+h-self.botones[1].get_tamanio()[1])) + self.botones[2].set_posicion(punto=(x+w-self.botones[2].get_tamanio()[0], y)) + + def set_callback_cerrar(self, callback): + ''' Setea una función para click sobre el boton cerrar. ''' + self.botones[2].connect(callback=callback) + + # ------------------ Construccion ---------------------------- + def get_botones(self): + ''' Construye los botones para cambiar de página y cerrar el libro. ''' + uno, dos, tres, cuatro= VG.get_boton_imagenes() + boton_previous= JAMButton("", uno) + boton_next= JAMButton("", dos) + boton_salir= JAMButton("", cuatro) + boton_previous.set_imagen(origen=uno , tamanio=(10,10)) + boton_previous.set_tamanios(tamanio=(0,0),grosorbor=1, espesor=1) + boton_next.set_imagen(origen=dos , tamanio=(10,10)) + boton_next.set_tamanios(tamanio=(0,0),grosorbor=1, espesor=1) + boton_salir.set_imagen(origen=cuatro , tamanio=(10,10)) + boton_salir.set_tamanios(tamanio=(0,0),grosorbor=1, espesor=1) + boton_previous.connect(callback=self.texto_sprite.previous) + boton_next.connect(callback=self.texto_sprite.next) + return [boton_previous, boton_next, boton_salir] + +class Rectangulo_Texto(pygame.rect.Rect): + ''' El rectángulo donde debe dibujarse el texto. ''' + def __init__(self, book, rectangulo): + self.book= book + pygame.rect.Rect.__init__(self, rectangulo) + + def set_posicion(self, punto=(0,0)): + self.x= punto[0] + self.y= punto[1] + self.book.texto_sprite.set_posicion() + +class Texto_sprite(pygame.sprite.OrderedUpdates): + ''' Grupo de JAMLabels por páginas con la lectura del libro. ''' + def __init__(self, book): + pygame.sprite.OrderedUpdates.__init__(self) + self.book= book + self.paginas= [] + self.set_leccion() + + def previous(self, button): + ''' Muestra la página anterior. ''' + indice= self.paginas.index(self.sprites()) + if indice > 0: + indice -= 1 + for sprites in self.sprites(): + self.book.remove(sprites) + self.empty() + self.add(self.paginas[indice]) + self.book.add(self) + + def next(self,button): + ''' Muestra la página siguiente. ''' + indice= self.paginas.index(self.sprites()) + if indice < len(self.paginas)-1: + indice += 1 + for sprites in self.sprites(): + self.book.remove(sprites) + self.empty() + self.add(self.paginas[indice]) + self.book.add(self) + + def set_posicion(self): + ''' Setea la posición del texto. ''' + x,y,w,h= self.book.rectangulo_texto + for pagina in self.paginas: + for renglon in pagina: + renglon.set_posicion(punto=(x,y)) + y+= renglon.get_tamanio()[1] + x,y,w,h= self.book.rectangulo_texto + + def set_leccion(self): + ''' Setea el texto en el libro. ''' + renglones= self.book.lectura.split("\n") + label_renglones= [] + for renglon in renglones: + label= JAMLabel(renglon) + label.set_text(tamanio=30, color=VG.get_negro()) + label_renglones.append(label) + self.set_posicion_renglones(label_renglones) + + def set_posicion_renglones(self, label_renglones): + ''' Posiciona los renglones, generando páginas. ''' + x,y,w,h= self.book.rectangulo_texto + pagina= [] + for renglon in label_renglones: + renglon.set_posicion(punto=(x,y)) + y+= renglon.get_tamanio()[1] + pagina.append(renglon) + if not self.book.rectangulo_texto.collidepoint(x, y): + self.paginas.append(pagina) + x,y,w,h= self.book.rectangulo_texto + pagina= [] + + if len(pagina)>0: self.paginas.append(pagina) + self.set_pagina_actual() + + def set_pagina_actual(self): + ''' Muestra la página 1. ''' + self.empty() + self.add(self.paginas[0]) + + + +# ----- FIN DE CLASE JAMBook - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + + # Variables obligatorias en tu juego para poder utilizar JAMatrix. + self.resolucion = (1200,800) + self.ventana = None + self.name= "Ejemplo JAMBook" + self.estado = False + + # Variables del juego + self.reloj = None + self.fondo = None + + self.jambook= None + + self.load() # crea la ventana principal + + self.estado= "menu_0" + self.run_menu_0() + + def run_menu_0(self): + ''' Tu juego corriendo. ''' + self.ventana.blit(self.fondo, (0,0)) + + self.jambook.draw(self.ventana) + + pygame.display.update() + + contador = 0 + while self.estado == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.jambook.clear(self.ventana, self.fondo) + + self.jambook.update() + + self.handle_event() + pygame.event.clear() + + if contador == 150: + self.jambook.set_posicion(punto=(50,50)) + if contador == 200: + self.jambook.set_posicion(punto=(10,10)) + contador = 0 + cambios.extend ( self.jambook.draw(self.ventana) ) + + pygame.display.update(cambios) + contador += 1 + + def load(self): + ''' Creando y seteando todos los objetos de tu juego. ''' + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + self.ventana = pygame.display.get_surface() + self.fondo = self.get_Fondo() + self.reloj = pygame.time.Clock() + + self.jambook= JAMBook(TEXTO) + self.jambook.set_callback_cerrar(self.salir) + + pygame.display.set_caption("Ejemplo de JAMBook") + 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) + self.estado= True # Todo se ha cargado y seteado, listo para correr el juego. + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill(VG.get_gris1()) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + self.salir(None) + pygame.event.clear() + + def salir(self, button): + pygame.quit() + sys.exit() + +TEXTO= ''' +El loro pelado + +Había una vez una bandada de loros +que vivía en el monte. + +De mañana temprano iban a comer +choclos a la chacra, y de tarde +comían naranjas. + +Hacían gran barullo con sus gritos, +y tenían siempre un loro de +centinela en los árboles más altos, +para ver si venía alguien. + +Los loros son tan dañinos como la +langosta, porque abren los choclos +para picotearlos, los cuales, +después se pudren con la Lluvia. +Y como al mismo tiempo los loros +son ricos para comerlos guisados, +los peones los cazaban a tiros. + +Un día un hombre bajó de un tiro a +un loro centinela, el que cayó +herido y peleó un buen rato antes +de dejarse agarrar. El peón lo +Llevó a la casa, para los hijos del +patrón; los chicos lo curaron porque +no tenía más que un ala rota. +El loro se curó muy bien, y se +amansó completamente. +Se Llamaba Pedrito. Aprendió a dar +la pata; le gustaba estar en el +hombro de las personas y les hacía +cosquillas en la oreja. ''' + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMButton.py b/BiblioJAM/JAMButton.py new file mode 100644 index 0000000..b302d51 --- /dev/null +++ b/BiblioJAM/JAMButton.py @@ -0,0 +1,560 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 16/04/2011 - CeibalJAM! - Uruguay +# JAMButton.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +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] 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 ----- +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() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMCalendar.py b/BiblioJAM/JAMCalendar.py new file mode 100644 index 0000000..1fefa1c --- /dev/null +++ b/BiblioJAM/JAMCalendar.py @@ -0,0 +1,816 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 28/05/2011 - CeibalJAM! - Uruguay +# JAMCalendar.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, gobject, time, datetime, os +from pygame.locals import * +gc.enable() +pygame.font.init() + +import JAMGlobals as VG +from JAMButton import JAMButton +from JAMLabel import JAMLabel + +class JAMCalendar(pygame.sprite.OrderedUpdates): + ''' Un Calendario hecho en pygame. ''' + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + + COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR= VG.get_default_jambutton_values() + + self.datos_fechas_text={"tipo": pygame.font.get_default_font(), "tamanio": 16, "color": VG.get_negro(), "font_from_file": False} + self.datos_fechas_color={"colorselect": COLORBAS, "colorcara": COLORCARA, "colorborde": COLORBOR} + + self.datos_dias_text={"tipo": pygame.font.get_default_font(), "tamanio": 16, "color": VG.get_negro(), "font_from_file": False} + self.datos_dias_color={"colorselect": COLORBAS, "colorcara": COLORCARA, "colorborde": COLORBOR} + + self.datos_cabecera_text={"tipo": pygame.font.get_default_font(), "tamanio": 16, "color": VG.get_negro(), "font_from_file": False} + self.datos_cabecera_color={"colorselect": COLORBAS, "colorcara": COLORCARA, "colorborde": COLORBOR} + + self.datos_base= {"colorborde": COLORBOR, "colorbase": COLORBAS, "retiro1": 2, "grosorborde1": 4,"retiro2": 1, "grosorborde2": 2} + + self.posicion= (0,0) + + self.anio, self.mes, self.dia= str(datetime.date.today()).split("-") # el dia de hoy + + self.botones_fechas= None + self.botones_dias= None + self.cabecera= None + self.base= None + + self.color_hoy= None + self.Reconstruye("todo") + + def Reconstruye(self, cambios): + ''' Reconstruye el calendario según cambios.''' + if "todo" in cambios: + self.empty() + datos_calendar= VG.get_calendar(int(self.mes), int(self.anio)) + self.color_hoy= VG.get_blanco() + + self.cabecera= Cabecera(self, datos_calendar[0]) + self.botones_dias= Botones_Dias(self, datos_calendar[1]) + self.botones_fechas= Botones_Fechas(self, datos_calendar[2:]) + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def reset_tamanios(self): + ''' Setea el tamanio de los botones de acuerdo al tamanio de la letra. ''' + # Botones de dias y fechas + botones= self.botones_dias.sprites() + botones.extend(self.botones_fechas.sprites()) + lado= 0 + for boton in botones: + boton.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + w,h = boton.get_tamanio() + if w > lado: lado= w + if h > lado: lado= h + for boton in botones: + boton.set_tamanios(tamanio=(lado,lado), grosorbor=1, detalle=1, espesor=1) + + # Botones de la Cabecera + ancho_cabecera= lado*7+6 + botones_cabecera= self.cabecera.sprites() + for boton in botones_cabecera: + boton.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + w,h = boton.get_tamanio() + #if w > lado: lado= w + if h > lado: lado= h + botones_cabecera[0].set_tamanios(tamanio=(h,h), grosorbor=1, detalle=1, espesor=1) + a,b= botones_cabecera[0].get_tamanio() + botones_cabecera[1].set_tamanios(tamanio=(ancho_cabecera-a*2,h), grosorbor=1, detalle=1, espesor=1) + botones_cabecera[2].set_tamanios(tamanio=(h,h), grosorbor=1, detalle=1, espesor=1) + + def get_base(self): + ''' Construye la base del Calendario. ''' + altura_total= 0 + ancho_total= 0 + + colorborde= self.datos_base["colorborde"] + colorbase= self.datos_base["colorbase"] + retiro1= self.datos_base["retiro1"] + grosorborde1= self.datos_base["grosorborde1"] + retiro2= self.datos_base["retiro2"] + grosorborde2= self.datos_base["grosorborde2"] + + margen1= retiro2+grosorborde2 + margen2= retiro1+grosorborde1 + # Cabecera + ancho_cabecera= 0 + for boton in self.cabecera.sprites(): + w,h= boton.get_tamanio() + ancho_cabecera+= w + altura_cabecera= h + + ancho_total= margen1*2 + ancho_cabecera + altura_total= margen1*2 + altura_cabecera + + # dias + w,altura_dias= self.botones_dias.sprites()[0].get_tamanio() + + altura_total+= altura_dias+1 + + # fechas + altura_total+= altura_dias*5+5 + + rectangulo_interno= (ancho_total, altura_total) + rectangulo_externo= (ancho_total+margen2*2, altura_total+margen2*2) + + base= pygame.sprite.Sprite() + base.image= VG.get_Rectangulo(colorbase, (rectangulo_interno)) + base.image= VG.get_my_surface_whit_border(base.image, colorborde, grosorborde2) + + fondo= VG.get_Rectangulo(colorbase, (rectangulo_externo)) + fondo= VG.get_my_surface_whit_border(fondo, colorborde, grosorborde1) + base.image= VG.pegar_imagenes_centradas(base.image, fondo) + base.rect= base.image.get_rect() + return base + # ------------------ Gets --------------------------- + def get_posicion(self): + x,y,w,h= self.get_rect() + return (x,y) + def get_tamanio(self): + x,y,w,h= self.get_rect() + return (w,h) + def get_rect(self): + return self.base.rect + # ------------------ Gets --------------------------- + + # ------------------ Seteos Externos ------------------ + # -----------------SETEOS Que afectan al tamaño ------------------- + def set_text_fechas(self, tipo= False, tamanio= False, color= False): + ''' Setea tipo, tamaño y color de la letra en los botones de fecha. ''' + cambios= False + if tipo: + self.datos_fechas_text["tipo"]= tipo + cambios= True + if tamanio: + self.datos_fechas_text["tamanio"]= tamanio + cambios= True + if color: + self.datos_fechas_text["color"]= color + cambios= True + + if cambios: + self.botones_fechas.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_font_from_file_fechas(self, fuente, tamanio= None): + ''' Setea el tipo de letra desde un archivo de fuentes. ''' + cambios= False + if fuente: + self.datos_fechas_text["font_from_file"]= fuente + cambios= True + if tamanio: + self.datos_fechas_text["tamanio"]= tamanio + cambios= True + + if cambios: + self.botones_fechas.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_text_dias(self, tipo= False, tamanio= False, color= False): + ''' Setea tipo, tamaño y color de la letra en los botones de dias. ''' + cambios= False + if tipo: + self.datos_dias_text["tipo"]= tipo + cambios= True + if tamanio: + self.datos_dias_text["tamanio"]= tamanio + cambios= True + if color: + self.datos_dias_text["color"]= color + cambios= True + + if cambios: + self.botones_dias.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_font_from_file_dias(self, fuente, tamanio= None): + ''' Setea el tipo de letra desde un archivo de fuentes. ''' + cambios= False + if fuente: + self.datos_dias_text["font_from_file"]= fuente + cambios= True + if tamanio: + self.datos_dias_text["tamanio"]= tamanio + cambios= True + + if cambios: + self.botones_dias.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + + def set_text_cabecera(self, tipo= False, tamanio= False, color= False): + ''' Setea tipo, tamaño y color de la letra en los botones de dias. ''' + cambios= False + if tipo: + self.datos_cabecera_text["tipo"]= tipo + cambios= True + if tamanio: + self.datos_cabecera_text["tamanio"]= tamanio + cambios= True + if color: + self.datos_cabecera_text["color"]= color + cambios= True + + if cambios: + self.cabecera.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_font_from_file_cabecera(self, fuente, tamanio= None): + ''' Setea el tipo de letra desde un archivo de fuentes. ''' + cambios= False + if fuente: + self.datos_cabecera_text["font_from_file"]= fuente + cambios= True + if tamanio: + self.datos_cabecera_text["tamanio"]= tamanio + cambios= True + + if cambios: + self.cabecera.set_text() + if tamanio: + self.empty() + self.reset_tamanios() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_text(self, tipo= False, tamanio= False, color= False): + ''' Setea tipo, tamaño y color de la letra en los botones de dias. ''' + self.set_text_fechas(tipo= tipo, tamanio= tamanio, color= color) + self.set_text_dias(tipo= tipo, tamanio= tamanio, color= color) + self.set_text_cabecera(tipo= tipo, tamanio= tamanio, color= color) + + def set_font_from_file(self, fuente, tamanio= None): + ''' Setea el tipo de letra desde un archivo de fuentes. ''' + self.set_font_from_file_fechas(fuente, tamanio= tamanio) + self.set_font_from_file_dias(fuente, tamanio= tamanio) + self.set_font_from_file_cabecera(fuente, tamanio= tamanio) + # -----------------SETEOS Que afectan al tamaño ------------------- + + # -----------------SETEOS Que no afectan al tamaño ------------------- + def set_posicion(self, punto= (0,0)): + if type(punto)== tuple and len(punto)== 2: + if type(punto[0])== int and type(punto[1])== int: + retiro1= self.datos_base["retiro1"] + grosorborde1= self.datos_base["grosorborde1"] + retiro2= self.datos_base["retiro2"] + grosorborde2= self.datos_base["grosorborde2"] + + self.posicion= punto + # base + self.base.rect.x, self.base.rect.y= self.posicion + + margen1= retiro2+grosorborde2 + margen2= retiro1+grosorborde1 + + # cabecera + posicion= (self.posicion[0]+margen1+margen2,self.posicion[1]+margen1+margen2) + self.cabecera.set_posicion(punto= posicion) + + x,y= posicion + w,h= self.cabecera.matriz_botones[0].get_tamanio() + + # dias + posicion= (x, y+h+1) + self.botones_dias.set_posicion(punto= posicion) + + x,y= posicion + w,h= self.botones_dias.matriz_botones[0].get_tamanio() + + # fechas + posicion= (x, y+h+1) + self.botones_fechas.set_posicion(punto= posicion) + + def set_calendar(self, mes, anio): + ''' Cuando se cambia el mes o año. ''' + if not type(mes)== int or not type(anio)== int or mes not in range(1,13) or not anio > 0: return + self.mes, self.anio= (mes, anio) + datos_calendar= VG.get_calendar(int(self.mes), int(self.anio)) + self.botones_fechas.set_mes(datos_calendar[2:]) + self.cabecera.set_mes(datos_calendar[0]) + + def set_colors_fechas(self, colorselect= False, colorbor= False, colorcara= False): + ''' Setea los colores de los botones de fecha. ''' + cambios= False + if colorselect: + self.datos_fechas_color["colorselect"]= colorselect + cambios= True + if colorbor: + self.datos_fechas_color["colorborde"]= colorbor + cambios= True + if colorcara: + self.datos_fechas_color["colorcara"]= colorcara + cambios= True + if cambios:self.botones_fechas.set_colors() + + def set_colors_dias(self, colorselect= False, colorbor= False, colorcara= False): + ''' Setea los colores de los botones de fecha. ''' + cambios= False + if colorselect: + self.datos_dias_color["colorselect"]= colorselect + cambios= True + if colorbor: + self.datos_dias_color["colorborde"]= colorbor + cambios= True + if colorcara: + self.datos_dias_color["colorcara"]= colorcara + cambios= True + if cambios:self.botones_dias.set_colors() + + def set_colors_cabecera(self, colorselect= False, colorbor= False, colorcara= False): + ''' Setea los colores de los botones de fecha. ''' + cambios= False + if colorselect: + self.datos_cabecera_color["colorselect"]= colorselect + cambios= True + if colorbor: + self.datos_cabecera_color["colorborde"]= colorbor + cambios= True + if colorcara: + self.datos_cabecera_color["colorcara"]= colorcara + cambios= True + if cambios:self.cabecera.set_colors() + + def set_colors_base(self, colorbase= False, colorborde= False): + ''' Setea los colores de la base. ''' + cambios= False + if colorbase: + if colorbase != self.datos_base["colorbase"]: + self.datos_base["colorbase"]= colorbase + cambios= True + if colorborde: + if colorborde != self.datos_base["colorborde"]: + self.datos_base["colorborde"]= colorborde + cambios= True + if cambios: + self.empty() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + + def set_gama_colors(self, colorselect= False, colorbor= False, colorcara= False): + ''' Setea los colores de la base. ''' + cambios= False + if colorselect: + self.datos_cabecera_color["colorselect"]= colorselect + self.datos_dias_color["colorselect"]= colorselect + self.datos_fechas_color["colorselect"]= colorselect + self.datos_base["colorbase"]= colorselect + cambios= True + if colorbor: + self.datos_cabecera_color["colorborde"]= colorbor + self.datos_dias_color["colorborde"]= colorbor + self.datos_fechas_color["colorborde"]= colorbor + self.datos_base["colorborde"]= colorbor + cambios= True + if colorcara: + self.datos_cabecera_color["colorcara"]= colorcara + self.datos_dias_color["colorcara"]= colorcara + self.datos_fechas_color["colorcara"]= colorcara + cambios= True + if cambios: + self.empty() + self.cabecera.set_colors() + self.botones_dias.set_colors() + self.botones_fechas.set_colors() + self.base= self.get_base() + self.set_posicion(punto= self.posicion) + self.add(self.base) + self.add(self.cabecera) + self.add(self.botones_dias) + self.add(self.botones_fechas) + # -----------------SETEOS Que no afectan al tamaño ------------------- + +class Botones_Fechas(pygame.sprite.OrderedUpdates): + ''' Botones para fechas. ''' + def __init__(self, calendar, datos_calendar): + pygame.sprite.OrderedUpdates.__init__(self) + self.calendar= calendar + self.datos_calendar= datos_calendar + + self.matriz_botones= [] + self.posicion=(0,0) + + self.Reconstruye(["todo"]) + + def Reconstruye(self, cambios): + ''' Reconstruye el objeto según cambios.''' + if "todo" in cambios: + self.empty() + self.insert_empty_value_in_datos_calendar() # Inserta elementos vacíos para emparejar con la matriz de botones. + self.get_matriz_botones() # Genera la matriz de botones de fechas. + self.set_text() # Seteos de texto en botones. + self.set_colors() # Setea los colores de los botones. + self.add(self.matriz_botones) + + def get_matriz_botones(self): + ''' Genera la matriz de botones de fechas. ''' + self.matriz_botones= [] + for x in range(5): + linea= [] + for y in range(7): + boton= JAMButton("", None) + boton.connect(callback= None, sonido_select= None) + linea.append(boton) + self.matriz_botones.append(linea) + + def insert_empty_value_in_datos_calendar(self): + ''' Inserta elementos vacíos para emparejar con la matriz de botones. ''' + while len(self.datos_calendar[0]) < 7: + self.datos_calendar[0].insert(0, " ") + while len(self.datos_calendar[-1]) < 7: + self.datos_calendar[-1].append(" ") + + # -------------- SETEOS (todos internos) ---------------- + def set_mes(self, datos_calendar): + ''' Setea el mes en el calendario. ''' + self.datos_calendar= datos_calendar + self.insert_empty_value_in_datos_calendar() + self.set_text() + self.set_colors() + + def set_text(self): + ''' Seteos de texto en botones. ''' + tipo= self.calendar.datos_fechas_text["tipo"] + tamanio= self.calendar.datos_fechas_text["tamanio"] + color= self.calendar.datos_fechas_text["color"] + fuente= self.calendar.datos_fechas_text["font_from_file"] + + for linea in self.matriz_botones: + indicea= self.matriz_botones.index(linea) + for boton in linea: + indiceb= linea.index(boton) + try: + texto= self.datos_calendar[indicea][indiceb] + except: + texto= " " + #if texto== " ": + # linea[indiceb]= ButtonLabel(" ") + boton.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=texto) + if fuente: + boton.set_font_from_file(fuente, tamanio= tamanio) + + def set_colors(self): + ''' Setea los colores de los botones. ''' + colorbas= self.calendar.datos_fechas_color["colorselect"] + colorbor= self.calendar.datos_fechas_color["colorborde"] + colorcara= self.calendar.datos_fechas_color["colorcara"] + for linea in self.matriz_botones: + for boton in linea: + boton.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + self.control_select_hoy(boton) + + def control_select_hoy(self, boton): + ''' Pinta la fecha de hoy. ''' + anio, mes, dia= str(datetime.date.today()).split("-") + try: + if int(boton.get_text()) == int(dia): + if int(anio) == int(self.calendar.anio) and int(mes)== int(self.calendar.mes): + colorbas= self.calendar.datos_fechas_color["colorselect"] + colorbor= self.calendar.datos_fechas_color["colorborde"] + colorcara= self.calendar.color_hoy + boton.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + return + except: + pass + + def set_posicion(self, punto= (0,0)): + if type(punto)== tuple and len(punto)== 2: + if type(punto[0])== int and type(punto[1])== int: + self.posicion= punto + x,y = self.posicion + yy= y + for linea in self.matriz_botones: + xx= x + for boton in linea: + boton.set_posicion(punto=(xx,yy)) + w,h = boton.get_tamanio() + xx+= w+1 + yy+= h+1 + +class Botones_Dias(pygame.sprite.OrderedUpdates): + ''' Botones para días. ''' + def __init__(self, calendar, datos_calendar): + pygame.sprite.OrderedUpdates.__init__(self) + self.calendar= calendar + self.datos_calendar= datos_calendar + + self.matriz_botones= [] + self.posicion=(0,0) + + self.Reconstruye(["todo"]) + + def Reconstruye(self, cambios): + ''' Reconstruye el objeto según cambios.''' + if "todo" in cambios: + self.empty() + self.get_matriz_botones() + self.set_text() + self.add(self.matriz_botones) + + def get_matriz_botones(self): + ''' Genera la matriz de botones de fechas. ''' + self.matriz_botones= [] + for dia in self.datos_calendar: + boton= ButtonLabel(dia) + boton.connect(callback= None, sonido_select= None) + self.matriz_botones.append(boton) + + def set_text(self): + ''' Seteos de texto en botones. ''' + tipo= self.calendar.datos_dias_text["tipo"] + tamanio= self.calendar.datos_dias_text["tamanio"] + color= self.calendar.datos_dias_text["color"] + fuente= self.calendar.datos_dias_text["font_from_file"] + + for boton in self.matriz_botones: + boton.set_text(tipo=tipo, tamanio=tamanio, color=color) + if fuente: + boton.set_font_from_file(fuente, tamanio= tamanio) + + def set_posicion(self, punto= (0,0)): + ''' Setea la posición de todos los botones. ''' + if type(punto)== tuple and len(punto)== 2: + if type(punto[0])== int and type(punto[1])== int: + self.posicion= punto + x,y= self.posicion + for boton in self.matriz_botones: + boton.set_posicion(punto= (x,y)) + w,h= boton.get_tamanio() + x+= w+1 + + def set_colors(self): + ''' Setea los colores de los botones. ''' + colorbas= self.calendar.datos_dias_color["colorselect"] + colorbor= self.calendar.datos_dias_color["colorborde"] + colorcara= self.calendar.datos_dias_color["colorcara"] + for boton in self.matriz_botones: + boton.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + + +class Cabecera(pygame.sprite.OrderedUpdates): + ''' Cabecera con boton previous, next y etiqueta con mes y año. ''' + def __init__(self, calendar, datos_calendar): + pygame.sprite.OrderedUpdates.__init__(self) + self.calendar= calendar + self.datos_calendar= datos_calendar + + self.matriz_botones= [] + self.boton_previous= None + self.label_calendar= None + self.boton_next= None + + self.posicion=(0,0) + + self.Reconstruye(["todo"]) + + def Reconstruye(self, cambios): + ''' Reconstruye el objeto según cambios.''' + if "todo" in cambios: + self.empty() + self.get_matriz_botones() + self.set_text() + self.add(self.matriz_botones) + + def set_mes(self, datos_calendar): + ''' Cambia la cabecera del calendario. ''' + self.datos_calendar= datos_calendar + self.label_calendar.set_text(texto= self.datos_calendar) + + def get_previous_mes(self, boton=None): + ''' Cambia el calendario al mes anterior.''' + mes= int(self.calendar.mes) + anio= int(self.calendar.anio) + if mes > 1: + mes-= 1 + else: + mes= 12 + anio= self.get_previous_anio() + self.calendar.set_calendar(mes, anio) + + def get_previous_anio(self): + ''' Baja un año. ''' + anio= int(self.calendar.anio) + if anio > 1: + anio-= 1 + else: + anio= 2100 + return anio + + def get_next_mes(self, boton=None): + ''' Cambia el calendario al mes siguiente.''' + mes= int(self.calendar.mes) + anio= int(self.calendar.anio) + if mes < 12: + mes+= 1 + else: + mes= 1 + anio+= 1 + self.calendar.set_calendar(mes, anio) + + def get_matriz_botones(self): + ''' Genera la matriz de botones de fechas. ''' + self.matriz_botones= [] + + self.boton_previous= JAMButton("<<", None) + self.matriz_botones.append(self.boton_previous) + self.boton_previous.connect(callback= self.get_previous_mes, sonido_select= None) + + self.label_calendar= ButtonLabel(self.datos_calendar) + self.matriz_botones.append(self.label_calendar) + self.label_calendar.connect(callback= None, sonido_select= None) + + self.boton_next= JAMButton(">>", None) + self.matriz_botones.append(self.boton_next) + self.boton_next.connect(callback= self.get_next_mes, sonido_select= None) + + def set_text(self): + ''' Seteos de texto en botones. ''' + tipo= self.calendar.datos_cabecera_text["tipo"] + tamanio= self.calendar.datos_cabecera_text["tamanio"] + color= self.calendar.datos_cabecera_text["color"] + fuente= self.calendar.datos_cabecera_text["font_from_file"] + + for boton in self.matriz_botones: + boton.set_text(tipo=tipo, tamanio=tamanio, color=color) + if fuente: + boton.set_font_from_file(fuente, tamanio= tamanio) + + def set_posicion(self, punto= (0,0)): + ''' Setea la posición de todos los botones. ''' + if type(punto)== tuple and len(punto)== 2: + if type(punto[0])== int and type(punto[1])== int: + self.posicion= punto + x,y= self.posicion + self.boton_previous.set_posicion(punto= (x,y)) + w,h= self.boton_previous.get_tamanio() + x+= w + self.label_calendar.set_posicion(punto= (x,y)) + w,h= self.label_calendar.get_tamanio() + x+= w + self.boton_next.set_posicion(punto= (x,y)) + + def set_colors(self): + ''' Setea los colores de los botones. ''' + colorbas= self.calendar.datos_cabecera_color["colorselect"] + colorbor= self.calendar.datos_cabecera_color["colorborde"] + colorcara= self.calendar.datos_cabecera_color["colorcara"] + for boton in self.matriz_botones: + boton.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + +class ButtonLabel(JAMButton): + ''' Etiqueta con la fecha. ''' + def __init__(self, texto): + JAMButton.__init__(self, texto, None) + + def update(self): + pass + + + + + +# ----- FIN DE CLASE JAMCalendar - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1024,758) + + self.setup() + self.Run() + + 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 = JAMCalendar() + #self.widgets.set_posicion(punto= (50,50)) + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def Run(self): + self.ventana.blit(self.fondo, (0,0)) + self.widgets.draw(self.ventana) + pygame.display.update() + + contador = 0 + mes= 0 + contador= 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.widgets.clear(self.ventana, self.fondo) + + self.widgets.update() + self.handle_event() + + if contador== 100: + self.widgets.set_text_fechas(tamanio= 50, color= (0,0,0,255)) + self.widgets.set_text_dias(tamanio= 50, color= (0,0,0,255)) + self.widgets.set_text_cabecera(tamanio= 50, color= (0,0,0,255)) + a,b,c= VG.get_estilo_naranja() + #self.widgets.set_colors_base(colorbase= b, colorborde= a) + self.widgets.set_gama_colors(colorselect= b, colorbor= a, colorcara= c) + #self.widgets.set_colors_dias(colorselect= b, colorbor= a, colorcara= c) + #self.widgets.set_colors_cabecera(colorselect= b, colorbor= a, colorcara= c) + #fuente, tamanio= VG.get_Font_KOMIKND() + #self.widgets.set_font_from_file_cabecera(fuente, tamanio= 15) + #self.widgets.set_calendar(6, 2012) + self.widgets.set_posicion(punto= (50,50)) + contador += 1 + + pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill((0,0,0,255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def salir(self): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMClock.py b/BiblioJAM/JAMClock.py new file mode 100644 index 0000000..7719586 --- /dev/null +++ b/BiblioJAM/JAMClock.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 21/05/2011 - CeibalJAM! - Uruguay +# JAMClock.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, gobject, time, datetime, os +from pygame.locals import * +gc.enable() +pygame.font.init() + +import JAMGlobals as VG +from JAMButton import JAMButton + +class JAMClock(pygame.sprite.OrderedUpdates): + ''' Un reloj hecho en pygame. ''' + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + COLORCARA, COLORBAS, COLORBOR, GROSORBOR, DETALLE, ESPESOR= VG.get_default_jambutton_values() + self.datos_base= {"color": VG.get_blanco(), "colorborde": COLORBAS, "tamanio": (225,225), "grosorborde": 4} + self.datos_agujas= {"segundero":1, "minutero":2, "hora":3, "color": VG.get_negro()} + self.datos_numeros={"tipo": pygame.font.get_default_font(), "tamanio": 16, "color": VG.get_negro(), "colorbase": None, + "colorborde": None, "colorcara": None} + self.retiro= 4 + self.posicion= (0,0) + + self.sonido= VG.get_sound_clock_tick1() + self.sonido.set_volume(1.0) + + self.sonido_alarma= None + self.alarma= (100,100) + self.duracion_alarma= 0 + + self.alarma_activada= False + + self.sonido.play(-1) + self.Reconstruye("todo") + + def Reconstruye(self, cambios): + ''' Reconstruye el reloj según cambios.''' + if "todo" in cambios: + self.empty() + self.label= Digital(self) + self.base_interna= Base_Interna(self) + self.numeros= Numeros(self) + self.base_externa= Base_Externa(self) + self.segundero= Aguja(self, self.datos_agujas["segundero"], self.datos_agujas["color"], self.retiro) + self.minutero= Aguja(self, self.datos_agujas["minutero"], self.datos_agujas["color"], self.retiro*2) + self.horario= Aguja(self, self.datos_agujas["hora"], self.datos_agujas["color"], self.retiro*5) + self.timer= Timer(self) + + self.add(self.base_externa) + self.add(self.base_interna) + self.add(self.label) + self.add(self.numeros) + self.add(self.horario) + self.add(self.minutero) + self.add(self.segundero) + self.add(self.timer) + + self.timer.update() + self.set_posicion(punto= self.posicion) + + def control_alarma(self, tiempo): + ''' Control de Alarma. ''' + if not self.sonido_alarma: return + h= tiempo[0] + m= tiempo[1] + if (h,m) == self.alarma and not self.alarma_activada and self.sonido_alarma: + self.alarma_activada= True + try: + self.sonido_alarma.set_volume(1.0) + self.sonido_alarma.play(self.duracion_alarma) + except: + pass + print "ALARMA SONANDO !!!" + elif h > self.alarma[0] or m > self.alarma[1] and self.alarma_activada: + self.alarma_activada= False + print "ALARMA DESACTIVADA - VOLVERÁ A SONAR EN 24 HORAS A MENOS QUE LA DESACTIVES !!!" + + # ---------------- SETEOS ------------------- + def set_alarma(self, tiempo, sound, duracion): + ''' Setea las alarmas, en (horas,minutos), sonido y duración. ''' + self.alarma= tiempo + self.duracion_alarma= duracion + self.sonido_alarma= sound + self.alarma_activada= False # 24/11/2011 De lo contrario sólo se puede configurar la alarma 1 vez. + + def set_sound(self, sound, play): + ''' Setea el sonido del segundero del reloj. ''' + if self.sonido: + try: + self.sonido.stop() + except: + pass + + self.sonido= sound + if self.sonido and play: + try: + self.sonido.set_volume(1.0) + self.sonido.play(-1) + except: + pass + + def set_tamanios(self, valor): + ''' Setea el tamaño del reloj segun valores predefinidos. ''' + if type(valor)== int and valor>0 and valor<5: + UNO= {"tamaniobase": (225,225), "tamanioletra": 16} + DOS= {"tamaniobase": (440,440), "tamanioletra": 35} + TRES= {"tamaniobase": (550,550), "tamanioletra": 45} + CUATRO= {"tamaniobase": (748,748), "tamanioletra": 70} + if valor== 1: + self.datos_base["tamanio"]= UNO["tamaniobase"] + self.datos_numeros["tamanio"]= UNO["tamanioletra"] + elif valor== 2: + self.datos_base["tamanio"]= DOS["tamaniobase"] + self.datos_numeros["tamanio"]= DOS["tamanioletra"] + if valor== 3: + self.datos_base["tamanio"]= TRES["tamaniobase"] + self.datos_numeros["tamanio"]= TRES["tamanioletra"] + elif valor== 4: + self.datos_base["tamanio"]= CUATRO["tamaniobase"] + self.datos_numeros["tamanio"]= CUATRO["tamanioletra"] + self.Reconstruye("todo") + + def set_colors_base(self, colorcara, colorborde): + ''' Setea los colores de la base y los bordes. ''' + self.datos_base["color"]= colorcara + self.datos_base["colorborde"]= colorborde + self.Reconstruye("todo") + + def set_colors_agujas(self, color): + ''' Setea los colores de las agujas. ''' + self.datos_agujas["color"]= color + self.Reconstruye("todo") + + def set_colors_numeros(self, colornum, colorbase, colorborde, colorcara): + '''Setea los colores de los números y sus bases. ''' + self.datos_numeros["color"]= colornum + self.datos_numeros["colorbase"]= colorbase + self.datos_numeros["colorborde"]= colorborde + self.datos_numeros["colorcara"]= colorcara + self.numeros.set_colors() + self.label.set_text(color= self.datos_numeros["color"]) + + self.label.set_colores(colorbas= self.datos_numeros["colorbase"], colorbor= self.datos_numeros["colorborde"], + colorcara= self.datos_numeros["colorcara"]) + + def set_posicion(self, punto= None): + ''' Setea la posición en pantalla. ''' + if len(punto)== 2 and type(punto)== tuple and type(punto[0])== int and type(punto[1])== int: + self.posicion= punto + self.base_externa.set_posicion(punto= self.posicion) + self.base_interna.rect.center= self.base_externa.rect.center + + x= self.base_interna.rect.x + self.base_interna.rect.w/2 - self.label.rect.w/2 + y= self.base_interna.rect.y + self.base_interna.rect.h/2 + self.retiro*2 + self.label.set_posicion(punto= (x,y)) + + self.segundero.rect.center= self.base_interna.rect.center + self.minutero.rect.center= self.base_interna.rect.center + self.horario.rect.center= self.base_interna.rect.center + self.timer.rect.center= self.base_interna.rect.center + self.numeros.set_posicion() + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.base_externa.rect.w, self.base_externa.rect.h) + +class Digital(JAMButton): + ''' Etiqueta con la hora en forma digital.''' + def __init__(self, clock): + JAMButton.__init__(self, "", None) + self.clock= clock + tipo= self.clock.datos_numeros["tipo"] + tamanio= self.clock.datos_numeros["tamanio"]/3+self.clock.datos_numeros["tamanio"] + color= self.clock.datos_numeros["color"] + self.set_text(tipo= tipo, tamanio= tamanio, color= color) + self.set_tamanios(tamanio=(0,0), grosorbor=1, espesor=1) + self.set_colores(colorbas= self.clock.datos_numeros["colorbase"], colorbor= self.clock.datos_numeros["colorborde"], + colorcara= self.clock.datos_numeros["colorcara"]) + + def update(self): + ''' Sobrecarga de update para anular la detección de eventos.''' + pass + +class Timer(pygame.sprite.Sprite): + ''' El centro del reloj - la máquina.''' + def __init__(self, clock): + pygame.sprite.Sprite.__init__(self) + self.clock= clock + self.hora= ("00:00:00") + superficie= VG.get_Elipse(self.clock.datos_agujas["color"], (self.clock.retiro*2,self.clock.retiro*2)) + self.image= VG.get_my_surface_whit_elipse_border(superficie, self.clock.datos_base["color"], self.clock.datos_base["grosorborde"]/2) + self.rect= self.image.get_rect() + + def update(self): + hora = time.strftime("%H:%M:%S") + fecha= str(datetime.date.today()) + if hora != self.hora: + self.clock.label.set_text(texto= hora) + h,m,s= hora.split(":") + hh, mm, ss= self.hora.split(":") + + if s != ss: + self.clock.segundero.rota(int(s)*6) + if m != mm: + self.clock.minutero.rota(int(m)*6) + self.clock.control_alarma( (int(h),int(m)) ) + self.clock.horario.rota(int(h)*30+int(m)/2) + #if h != hh: + # self.clock.horario.rota(int(h)*30) + self.hora= hora + +class Aguja(pygame.sprite.Sprite): + ''' Clase base para las agujas.''' + def __init__(self, clock, grosor, color, retiro): + pygame.sprite.Sprite.__init__(self) + self.clock= clock + + superficie= VG.get_Rectangulo(self.clock.datos_base["color"], self.clock.datos_base["tamanio"]) + superficie.set_colorkey(self.clock.datos_base["color"]) + x,y,w,h= superficie.get_rect() + punto= (w/2,h/2) + pygame.draw.line(superficie, color, punto, (w/2,y+retiro), grosor) + self.imagen_original= superficie + + self.image= self.imagen_original.copy() + self.rect= self.image.get_rect() + + def rota(self, valor): + self.image = pygame.transform.rotate(self.imagen_original, -valor) + self.rect= self.image.get_rect() + self.rect.center= self.clock.base_interna.rect.center + +class Base_Externa(pygame.sprite.Sprite): + def __init__(self, clock): + pygame.sprite.Sprite.__init__(self) + self.clock= clock + + w,h= self.clock.datos_base["tamanio"] + w+= self.clock.retiro*2+self.clock.datos_base["grosorborde"] + h+= self.clock.retiro*2+self.clock.datos_base["grosorborde"] + superficie= VG.get_Rectangulo(self.clock.datos_base["color"], (w,h)) + superficie= VG.get_my_surface_whit_border(superficie, self.clock.datos_base["colorborde"], self.clock.datos_base["grosorborde"]/2) + + w+= self.clock.retiro*2+self.clock.datos_base["grosorborde"]*2 + h+= self.clock.retiro*2+self.clock.datos_base["grosorborde"]*2 + superficie2= VG.get_Rectangulo(self.clock.datos_base["color"], (w,h)) + superficie2= VG.pegar_imagenes_centradas(superficie, superficie2) + self.image= VG.get_my_surface_whit_border(superficie2, self.clock.datos_base["colorborde"], self.clock.datos_base["grosorborde"]) + self.rect= self.image.get_rect() + + def set_posicion(self, punto= None): + ''' Setea la posición en pantalla. ES INTERNO''' + if len(punto)== 2 and type(punto)== tuple and type(punto[0])== int and type(punto[1])== int: + self.rect.x, self.rect.y= punto + +class Base_Interna(pygame.sprite.Sprite): + def __init__(self, clock): + pygame.sprite.Sprite.__init__(self) + self.clock= clock + + superficie= VG.get_Rectangulo(self.clock.datos_base["color"], self.clock.datos_base["tamanio"]) + self.image= superficie + self.rect= self.image.get_rect() + +class Numeros(pygame.sprite.OrderedUpdates): + ''' Los números en el fondo del reloj.''' + def __init__(self, clock): + pygame.sprite.OrderedUpdates.__init__(self) + self.clock= clock + self.numeros= [] + self.Reconstruye(["todo"]) + + def Reconstruye(self, cambios): + ''' Reconstruye el objeto según cambios.''' + if "todo" in cambios: + self.empty() + self.cuadricula= VG.get_cuadricula(self.clock.base_interna.image, 11, 11) + ancho, alto= (self.cuadricula[0][2],self.cuadricula[0][3]) + self.numeros= [] + for x in range(1,13): + numero= Numero(x) + numero.set_tamanios(tamanio=(ancho,alto)) + self.numeros.append(numero) + self.add(numero) + self.set_text() + self.set_colors() + self.set_posicion() + + def set_colors(self): + ''' Setea el color de los números y sus bases. ES INTERNO''' + for numero in self.numeros: + numero.set_text(color= self.clock.datos_numeros["color"]) + numero.set_colores(colorbas= self.clock.datos_numeros["colorbase"], colorbor= self.clock.datos_numeros["colorborde"], + colorcara= self.clock.datos_numeros["colorcara"]) + + def set_text(self): + ''' Setea los números en el fondo del reloj. ES INTERNO''' + tipo= self.clock.datos_numeros["tipo"] + tamanio= self.clock.datos_numeros["tamanio"] + color= self.clock.datos_numeros["color"] + lado= 0 + for numero in self.numeros: + numero.set_text(tipo= tipo, tamanio= tamanio, color= color) + numero.set_tamanios(tamanio=(0,0), grosorbor=1, espesor=1) + a,b,c,d= numero.rect + if lado< c: lado= c + if lado< d: lado= d + for numero in self.numeros: + numero.set_tamanios(tamanio=(lado,lado), grosorbor=1, espesor=1) + + def set_posicion(self): + ''' Setea la posición en pantalla. ES INTERNO''' + x,y= (self.clock.base_interna.rect.x, self.clock.base_interna.rect.y) + self.numeros[0].set_posicion(punto=(x+self.cuadricula[8][0],y+self.cuadricula[8][1])) + self.numeros[1].set_posicion(punto=(x+self.cuadricula[32][0],y+self.cuadricula[32][1])) + self.numeros[2].set_posicion(punto=(x+self.cuadricula[65][0],y+self.cuadricula[65][1])) + self.numeros[3].set_posicion(punto=(x+self.cuadricula[98][0],y+self.cuadricula[98][1])) + self.numeros[4].set_posicion(punto=(x+self.cuadricula[118][0],y+self.cuadricula[118][1])) + self.numeros[5].set_posicion(punto=(x+self.cuadricula[115][0],y+self.cuadricula[115][1])) + self.numeros[6].set_posicion(punto=(x+self.cuadricula[112][0],y+self.cuadricula[112][1])) + self.numeros[7].set_posicion(punto=(x+self.cuadricula[88][0],y+self.cuadricula[88][1])) + self.numeros[8].set_posicion(punto=(x+self.cuadricula[55][0],y+self.cuadricula[55][1])) + self.numeros[9].set_posicion(punto=(x+self.cuadricula[22][0],y+self.cuadricula[22][1])) + self.numeros[10].set_posicion(punto=(x+self.cuadricula[2][0],y+self.cuadricula[2][1])) + self.numeros[11].set_posicion(punto=(x+self.cuadricula[5][0],y+self.cuadricula[5][1])) + +class Numero(JAMButton): + def __init__(self, x): + JAMButton.__init__(self, x, None) + def update(self): + ''' Sobrecarga de update para anular la detección de eventos.''' + pass + +# ----- FIN DE CLASE JAMClock - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1024,768) + + self.setup() + self.Run() + + 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 = JAMClock() + self.widgets.set_posicion(punto= (50,50)) + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def Run(self): + self.ventana.blit(self.fondo, (0,0)) + self.widgets.draw(self.ventana) + pygame.display.update() + ALARMA= (19,50) + SUENA= 5 + self.widgets.set_alarma(ALARMA, VG.get_alarma_reloj2(), SUENA) + contador = 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.widgets.clear(self.ventana, self.fondo) + + self.widgets.update() + self.handle_event() + #pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + contador += 1 + if contador== 50: + colornum= VG.get_negro() + colorbase,colorborde,colorcara= VG.get_estilo_papel_quemado() + self.widgets.set_tamanios(2) + self.widgets.set_colors_base(colorborde, colorcara) + ''' + #self.widgets.set_colors_base(colorcara, colorborde) + #self.widgets.set_colors_agujas(colorbase) + self.widgets.set_colors_agujas(colornum) + self.widgets.set_colors_numeros(colornum, colorbase, colorborde, colorcara) + #self.widgets.set_tamanios(1) + + if contador== 200: + colornum= VG.get_negro() + colorbase,colorborde,colorcara= VG.get_estilo_celeste() + + self.widgets.set_colors_base(colorborde, colorcara) + #self.widgets.set_colors_base(colorcara, colorborde) + #self.widgets.set_colors_agujas(colorbase) + self.widgets.set_colors_agujas(colornum) + self.widgets.set_colors_numeros(colornum, colorbase, colorborde, colorcara) + self.widgets.set_tamanios(2) + + if contador== 300: + colornum= VG.get_negro() + colorbase,colorborde,colorcara= VG.get_estilo_gris() + + self.widgets.set_colors_base(colorborde, colorcara) + #self.widgets.set_colors_base(colorcara, colorborde) + #self.widgets.set_colors_agujas(colorbase) + self.widgets.set_colors_agujas(colornum) + self.widgets.set_colors_numeros(colornum, colorbase, colorborde, colorcara) + #self.widgets.set_tamanios(3) + if contador== 400: + contador= 0 + #self.widgets.set_tamanios(4) + self.widgets.set_alarma((22,1), VG.get_alarma_reloj2(), 10)''' + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill((0,0,0,255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def salir(self): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMComboBox.py b/BiblioJAM/JAMComboBox.py new file mode 100644 index 0000000..b0ec196 --- /dev/null +++ b/BiblioJAM/JAMComboBox.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 21/05/2011 - CeibalJAM! - Uruguay +# JAMComboBox.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, gobject, time, datetime, os +from pygame.locals import * +gc.enable() +pygame.font.init() + +import JAMGlobals as VG +from JAMButton import JAMButton + +class JAMComboBox(pygame.sprite.OrderedUpdates): + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + + self.buttoncaption= None + self.buttonaction= None + self.items= {} + self.buttonsitems= [] + + self.limitecaracteres= 40 + self.text= {"tipo": None, "tamanio": None, "color": None, "font_from_file": None} + self.colores= {"colorbas": None, "colorbor": None, "colorcara": None} + + self.posicion= (0,0) + + self.Reconstruye("todo") + + def Reconstruye(self, cambios): + ''' Reconstruye según cambios.''' + if "todo" in cambios: + self.buttoncaption= ButtonCaption(self) + self.buttonaction= ButtonAction(self) + + self.set_posicion(punto= self.posicion) + + self.add(self.buttoncaption) + self.add(self.buttonaction) + + def set_item_inicial(self): + ''' Pone el primer item en el caption del combo. ''' + self.set_item_in_caption(0) + + def set_item_in_caption(self, num): + ''' Pone el item indicado en el caption del combo. ''' + if self.buttonsitems and len(self.buttonsitems) >= num: + boton_item= self.buttonsitems[num] + self.buttoncaption.set_text(texto= boton_item.get_text()) + + def ordena_items(self): + ''' Todos del mismo tamanio. ''' + self.buttoncaption.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + self.buttonaction.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + for item in self.buttonsitems: + item.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + + + ancho, alto= self.buttoncaption.get_tamanio() + w,h= self.buttonaction.get_tamanio() + if alto < h: alto= h + for item in self.buttonsitems: + ww,hh= item.get_tamanio() + if ancho < ww: ancho= ww + if alto < hh: alto= hh + + self.buttoncaption.set_tamanios(tamanio=(ancho,alto), grosorbor=1, detalle=1, espesor=1) + self.buttonaction.set_tamanios(tamanio=(self.buttonaction.get_tamanio()[0],alto), grosorbor=1, detalle=1, espesor=1) + for item in self.buttonsitems: + item.set_tamanios(tamanio=(ancho,alto), grosorbor=1, detalle=1, espesor=1) + + if self.buttoncaption.get_text()== "JAMComboBox": + self.set_item_inicial() + self.set_posicion(punto= self.posicion) + + def show_items(self, buttonaction): + ''' Muestra los Items en el Combo. ''' + if self.buttonsitems: + self.empty() + self.add(self.buttonsitems) + else: + self.buttoncaption.set_text(texto= "JAMComboBox") + + def callback(self, button): + ''' Cuando se hace click sobre un item, la lista se contrae y muestra solo el elegido. + Luego ejecuta el callback de ese boton.''' + if button: + self.empty() + self.buttoncaption.set_text(texto= button.get_text()) + #self.buttoncaption.set_imagen(origen= button"direccion de archivo" , tamanio=(ancho,alto)) + self.add(self.buttoncaption) + self.add(self.buttonaction) + callback= self.items[button] + if callback: return callback(button) + else: + # cuando se borra un item mientras se está mostrando la lista de items + self.empty() + self.buttoncaption.set_text(texto= "JAMComboBox") + self.add(self.buttoncaption) + self.add(self.buttonaction) + + # ----------- SETEOS ------------------------------ + def add_item(self, item, callback): + ''' Agrega un Item y su callback al Combo. ''' + if len(item) > self.limitecaracteres: + item= "%s" % (item[:self.limitecaracteres]) + + # hay que verificar que el nuevo item no exista ya en el combo. + button= JAMButton(item, None) + button.set_text(tipo= self.text["tipo"], tamanio= self.text["tamanio"], color= self.text["color"]) + button.connect(callback= self.callback, sonido_select= None) + if self.colores["colorbas"] and self.colores["colorbor"] and self.colores["colorcara"]: + a= self.colores["colorbas"] + b= self.colores["colorbor"] + c= self.colores["colorcara"] + button.set_colores(colorbas= a, colorbor= b, colorcara= c) + + if self.text["font_from_file"]: + button.set_font_from_file(self.text["font_from_file"], tamanio= self.text["tamanio"]) + + self.items[button]= callback + + self.buttonsitems.append(button) + self.ordena_items() + + def remove_item(self, item): + ''' Elimina un item del combo segun caption. ''' + for boton in self.buttonsitems: + if boton.get_text()== item: + del self.items[boton] + self.buttonsitems.remove(boton) + boton.kill() + if not self.buttonsitems: + self.callback(None) + self.ordena_items() + + def remove_item_index(self, index): + ''' Elimina un item del combo segun indice. ''' + if len(self.buttonsitems) > 0 and index < len(self.buttonsitems): + boton= self.buttonsitems[index] + del self.items[boton] + self.buttonsitems.remove(boton) + boton.kill() + if not self.buttonsitems: + self.callback(None) + self.ordena_items() + + def clear_items(self): + ''' Elimina todos los items en el combo.''' + for boton in self.buttonsitems: + self.items.clear() + #self.buttonsitems.remove(boton) + self.buttonsitems= [] + boton.kill() + if not self.buttonsitems: + self.callback(None) + self.ordena_items() + + def connect_item(self, item, callback, sound): + ''' Conecta un item a una función. ''' + for boton in self.buttonsitems: + if boton.get_text()== item: + self.items[boton]= callback + boton.connect(callback=callback, sonido_select=sound) + + def set_colores(self, colorbas= None, colorbor= None, colorcara= None): + ''' Setea los colores de todos los items. ''' + if colorbas and type(colorbas)== tuple: + self.colores["colorbas"]= colorbas + if colorbor and type(colorbor)== tuple: + self.colores["colorbor"]= colorbor + if colorcara and type(colorcara)== tuple: + self.colores["colorcara"]= colorcara + + self.buttoncaption.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + self.buttonaction.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + for boton in self.buttonsitems: + boton.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + + def set_text(self, tipo= None, tamanio= None, color= None): + ''' Seteo de tipo, tamaño y color de letra. ''' + cambios= False + if tipo: + self.text["font_from_file"]= None + self.text["tipo"]= tipo + cambios= True + if tamanio and type(tamanio)== int: + self.text["tamanio"]= tamanio + cambios= True + if color: + self.text["color"]= color + cambios= True + + if not cambios: return + self.buttoncaption.set_text(tipo= self.text["tipo"], tamanio= self.text["tamanio"], color= self.text["color"]) + self.buttonaction.set_text(tipo= self.text["tipo"], tamanio= self.text["tamanio"], color= self.text["color"]) + for boton in self.buttonsitems: + boton.set_text(tipo= self.text["tipo"], tamanio= self.text["tamanio"], color= self.text["color"]) + + self.ordena_items() + + def set_font_from_file(self, fuente, tamanio= None): + ''' Seteo de tipo y tamaño de letra desde un archivo defuentes. ''' + if tamanio and type(tamanio)== int: + self.text["tamanio"]= tamanio + if fuente: + self.text["font_from_file"]= fuente + self.buttoncaption.set_font_from_file(self.text["font_from_file"], tamanio= self.text["tamanio"]) + self.buttonaction.set_font_from_file(self.text["font_from_file"], tamanio= self.text["tamanio"]) + for boton in self.buttonsitems: + boton.set_font_from_file(self.text["font_from_file"], tamanio= self.text["tamanio"]) + + self.ordena_items() + + def set_tamanios(self, tamanio=(0,0)): + ''' Setea el tamaño de los items. ''' + self.buttoncaption.set_tamanios(tamanio= tamanio)#, grosorbor=1, detalle=1, espesor=1) + self.buttonaction.set_tamanios(tamanio= (self.buttonaction.get_tamanio()[0],tamanio[1]) ) + for item in self.buttonsitems: + item.set_tamanios(tamanio= tamanio) + + ancho, alto= self.buttoncaption.get_tamanio() + w,h= self.buttonaction.get_tamanio() + if alto < h: alto= h + for item in self.buttonsitems: + ww,hh= item.get_tamanio() + if ancho < ww: ancho= ww + if alto < hh: alto= hh + + self.buttoncaption.set_tamanios(tamanio=(ancho,alto), grosorbor=1, detalle=1, espesor=1) + self.buttonaction.set_tamanios(tamanio=(self.buttonaction.get_tamanio()[0],alto), grosorbor=1, detalle=1, espesor=1) + for item in self.buttonsitems: + item.set_tamanios(tamanio=(ancho,alto), grosorbor=1, detalle=1, espesor=1) + + self.set_posicion(punto= self.posicion) + + def set_alineacion_text(self, alineacion): + ''' La alineación del texto en los items. ''' + for item in self.buttonsitems: + item.set_alineacion_label(alineacion) + + # ----------- SETEOS ------------------------------ + + # -----------------SETEOS Que no afectan al tamaño ------------------- + def set_posicion(self, punto= (0,0)): + if type(punto)== tuple and len(punto)== 2: + if type(punto[0])== int and type(punto[1])== int: + self.posicion= punto + self.buttoncaption.set_posicion(punto= self.posicion) + w,h= self.buttoncaption.get_tamanio() + self.buttonaction.set_posicion(punto= (self.posicion[0]+w, self.posicion[1]) ) + + x,y= self.posicion + for item in self.buttonsitems: + item.set_posicion(punto= (x,y)) + y+= item.get_tamanio()[1] + + def get_caption(self): + ''' Devuelve el texto del item en el caption de JAMComboBox. ''' + return self.buttoncaption.get_text() + + def get_tamanio_caption(self): + ''' Devuelve el ancho de caption y la altura de action.''' + w= self.buttoncaption.get_tamanio()[0] + h= self.buttonaction.get_tamanio()[1] + return (w,h) + + def get_tamanio(self): + ''' Devuelve el tamaño de JAMComboBox. ''' + alto= 0 + ancho= self.buttoncaption.get_tamanio()[0] + self.buttonaction.get_tamanio()[0] + if self.buttonsitems: + for item in self.buttonsitems: + alto+= item.get_tamanio()[1] + else: + alto= self.buttoncaption.get_tamanio()[1] + return (ancho, alto) + + def get_posicion(self): + ''' Devuelve la posicion de JAMComboBox. ''' + return self.posicion + +class ButtonCaption(JAMButton): + def __init__(self, main): + JAMButton.__init__(self, "JAMComboBox", None) + self.main= main + self.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + if self.main.colores["colorbas"] and self.main.colores["colorbor"] and self.main.colores["colorcara"]: + a= self.main.colores["colorbas"] + b= self.main.colores["colorbor"] + c= self.main.colores["colorcara"] + self.set_colores(colorbas= a, colorbor= b, colorcara= c) + if self.main.text["font_from_file"]: + self.set_font_from_file(self.main.text["font_from_file"], tamanio= self.main.text["tamanio"]) + + def update(self): + ''' Sobrecarga de update para anular la detección de eventos.''' + pass + +class ButtonAction(JAMButton): + def __init__(self, main): + JAMButton.__init__(self, ">", None) + self.main= main + self.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + self.connect(callback= main.show_items, sonido_select= None) + if self.main.colores["colorbas"] and self.main.colores["colorbor"] and self.main.colores["colorcara"]: + a= self.main.colores["colorbas"] + b= self.main.colores["colorbor"] + c= self.main.colores["colorcara"] + self.set_colores(colorbas= a, colorbor= b, colorcara= c) + if self.main.text["font_from_file"]: + self.set_font_from_file(self.main.text["font_from_file"], tamanio= self.main.text["tamanio"]) + +# ----- FIN DE CLASE JAMComboBox - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1024,768) + + self.setup() + self.Run() + + 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 = JAMComboBox() + self.widgets.add_item("Salir", callback= self.salir) + self.widgets.add_item("Prueba de Item 1", callback= None) + self.widgets.add_item("Ultima Prueba de Item", callback= None) + self.widgets.set_posicion(punto= (50,50)) + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + 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) + + self.widgets.update() + self.handle_event() + #pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + contador += 1 + if contador== 50: + colorbase,colorborde,colorcara= VG.get_estilo_papel_quemado() + self.widgets.set_colores(colorbas= colorbase, colorbor= colorborde, colorcara= colorcara) + #self.widgets.set_font_from_file(VG.get_Font_fawn()[0], tamanio= 20) + + if contador== 200: + self.widgets.set_tamanios(tamanio=(300,10)) + #self.widgets.set_text(tipo= "Purisa", tamanio= 10, color= VG.get_azul1()) + #self.widgets.remove_item("Prueba de Item 1") + self.widgets.remove_item_index(0) + #self.widgets.clear_items() + contador= 0 + ''' + if contador== 300: + self.widgets.set_alineacion_text("izquierda")''' + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill((0,0,0,255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir(None) + pygame.event.clear() + + def salir(self, button): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMCron.py b/BiblioJAM/JAMCron.py new file mode 100644 index 0000000..594a2e1 --- /dev/null +++ b/BiblioJAM/JAMCron.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 13/06/2011 - CeibalJAM! - Uruguay +# JAMCron.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, time, os +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG +from JAMButton import JAMButton + +class JAMCron(pygame.sprite.OrderedUpdates): + ''' Un Cronómetro. ''' + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + self.cron= None # el Cronómetro + + self.sonido= None # Sonido reloj tick + self.sonido_alarma= None # Sonido de la larma + self.duracion_alarma= 1 # cantidad de veces que debe sonar la alarma + self.callback= None # una función para ejecutar al finalizar la cuenta del cronómetro + + self.Construye() + + def Construye(self): + self.sonido= VG.get_sound_clock_tick1() + self.sonido_alarma= VG.get_alarma_reloj2() + self.duracion_alarma= 1 + self.callback= None + self.cron= Digital(self) + self.add(self.cron) + + def run_alarma(self): + ''' Control de Alarma. ''' + self.pause() + if self.sonido_alarma: + self.sonido_alarma.set_volume(1.0) + self.sonido_alarma.play(self.duracion_alarma-1) + if self.callback: + return self.callback(self) + + # ---------------- SETEOS ------------------- + def set_posicion(self, punto= (0,0)): + ''' Setea la posición en pantalla. ''' + self.cron.set_posicion(punto= punto) + + def set_alarma(self, tiempo= False, sound= False, duracion= False): + ''' Setea las alarmas, en (horas,minutos,segundos), sonido y duración. ''' + if tiempo and type(tiempo)== tuple and len(tiempo)==2: + if type(tiempo[0])== int and type(tiempo[1])== int: + self.cron.set_control(tiempo) + if sound: + self.sonido_alarma= sound + if sound== None: self.sonido_alarma= None + if duracion and type(duracion)== int: + self.duracion_alarma= duracion + + def set_sound(self, sound= None): + ''' Setea un sonido para el segundero del cronómetro. ''' + if self.sonido: + self.sonido.stop() + if sound and self.sonido!= sound: + self.sonido= sound + if sound== None: self.sonido= None + if self.cron.activado and self.sonido: + self.sonido.set_volume(1.0) + self.sonido.play(-1) + + def play(self): + ''' Activa y desactiva el cronómetro y las alarmas. ''' + self.cron.set_active_desactive(True) + def pause(self): + ''' Activa y desactiva el cronómetro y las alarmas. ''' + self.cron.set_active_desactive(False) + + def reset(self): + ''' Pone a 0 el cronómetro. ''' + self.cron.segundos_transcurridos= 0 + self.cron.segundos_faltan= None + + def set_callback(self, callback): + ''' Setea una función para la alarma. ''' + self.callback= callback + + def get_tiempo_restante(self): + return self.cron.segundos_faltan + + def get_tiempo_transcurrido(self): + return self.cron.segundos_transcurridos + +class Digital(JAMButton): + ''' Botón tipo etiqueta con el tiempo.''' + def __init__(self, main): + JAMButton.__init__(self, "00:00", None) + self.main= main + self.hora= "00:00:00" # La hora del sistema + + self.activado= False # Para pausa y play + self.segundos_transcurridos= 0 # Tiempo transcurrido, en segundos + self.segundos_faltan= None # Los segundos que faltan para terminar + self.segundos_final= None # Cuando se deja de contar, en segundos + + self.set_tamanios(tamanio=(0,0), grosorbor=1, detalle=1, espesor=1) + self.set_control((1,0)) + + def set_control(self, valor): + ''' Para setear el tiempo final del cronómetro. ''' + minutos, segundos= valor + self.segundos_final= minutos*60 + segundos + + def set_active_desactive(self, valor): + ''' pause/play. ''' + if self.main.sonido: self.main.sonido.stop() + #if valor!= self.activado: # para poder habilitar/desabilitar el sonido + self.activado= valor + if self.activado: + if self.main.sonido: + self.main.sonido.set_volume(1.0) + self.main.sonido.play(-1) + if not self.activado: + if self.main.sonido: + self.main.sonido.stop() + + def update(self): + ''' Reloj. ''' + if not self.activado: return + hora = time.strftime("%H:%M:%S") + if hora != self.hora: + self.hora= hora + self.segundos_transcurridos+= 1 + self.actualiza_cron() + + def actualiza_cron(self): + ''' Actualiza el Cronómetro. ''' + # Calcula el tiempo que falta + self.segundos_faltan = self.segundos_final - self.segundos_transcurridos + m= 0 + s= self.segundos_faltan + while s > 59: + s= s-60 + m+= 1 + texto= "%s:%s" % (m, s) + self.set_text(texto= texto) + if self.segundos_faltan < 1: + return self.main.run_alarma() + + +# ----- FIN DE CLASE JAMCron - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (400,400) + + self.setup() + self.Run() + + def setup(self): + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + pygame.display.set_caption("Ejemplo de JAMCron") + self.fondo = self.get_Fondo() + + self.widgets = JAMCron() + self.widgets.set_posicion(punto= (50,50)) + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def Run(self): + self.ventana.blit(self.fondo, (0,0)) + self.widgets.draw(self.ventana) + pygame.display.update() + + self.widgets.set_alarma(tiempo= (0,5), duracion= 1) + self.widgets.play() + + contador= 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.widgets.clear(self.ventana, self.fondo) + ''' + if contador == 200: + self.widgets.pause() + if contador == 400: + self.widgets.play() + contador= 0''' + contador+= 1 + self.widgets.update() + self.handle_event() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill((0,0,0,255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir(None) + pygame.event.clear() + + def salir(self, cron): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMDialog.py b/BiblioJAM/JAMDialog.py new file mode 100644 index 0000000..c3cec16 --- /dev/null +++ b/BiblioJAM/JAMDialog.py @@ -0,0 +1,413 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 18/04/2011 - CeibalJAM! - Uruguay +# JAMDialog.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG +from JAMLabel import JAMLabel +from JAMButton import JAMButton + +class JAMDialog(pygame.sprite.OrderedUpdates): + def __init__(self, mensaje="JAMDialog", funcion_ok=None, funcion_cancel=None): + ''' Es un grupo de sprite que contiene: JAMButton aceptar, JAMButton cancelar, Base.''' + pygame.sprite.OrderedUpdates.__init__(self) + self.resolucion= (800,600) + self.mensaje= mensaje + self.funcion_ok= None #funcion_ok + self.funcion_cancel= None #funcion_cancel + + self.separador= 20 + self.grosorbor_int= 3 + self.grosorbor_med= 2 + self.grosorbor_ext= 7 + + self.colores= {"base":VG.get_blanco(), "bordes":VG.get_negro()} + + # Botones + self.boton_aceptar, self.boton_cancelar= self.get_buttons() + self.connect(funcion_ok=funcion_ok, funcion_cancel=funcion_cancel) + # Etiqueta con mensaje + self.label = self.get_label() + # Base + self.base= pygame.sprite.Sprite() + self.base.image= self.get_base() + self.base.rect= self.base.image.get_rect() + + self.add(self.base) + self.add(self.boton_aceptar) + self.add(self.boton_cancelar) + + #self.set_center() + self.JAMObjects= {"base":self.base, "etiqueta":self.label, "botonaceptar":self.boton_aceptar, "botoncancelar": self.boton_cancelar} + + self.Reconstruye_JAMDialog(["todo"]) + + # ------------ SETEOS ----------------------- + # ------ Etiqueta + def set_text(self, tipo=None, tamanio=None, color=None, texto=None): + ''' Setea el Texto en JAMLabel. ''' + self.label.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=texto) + self.Reconstruye_JAMDialog(["texto"]) + + def set_font_from_file(self, direccion_archivo, tamanio= None): + ''' Setea la fuente desde un archivo en JAMLabel. ''' + self.label.set_font_from_file(direccion_archivo, tamanio) + self.Reconstruye_JAMDialog(["texto"]) + + def set_imagen(self, origen=None, tamanio=None): + ''' Setea el Imagen en JAMLabel. ''' + self.label.set_imagen(origen=origen, tamanio=tamanio) + self.Reconstruye_JAMDialog(["imagen"]) + # ------ Etiqueta + + # ------ Botones + def set_text_buttons(self, tipo=None, tamanio=None, color=None, textoaceptar=None, textocancelar=None): + ''' Setea el Texto en los JAMButtons. ''' + self.boton_aceptar.set_tamanios(tamanio=(0,0)) + self.boton_cancelar.set_tamanios(tamanio=(0,0)) + self.boton_aceptar.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=textoaceptar) + self.boton_cancelar.set_text(tipo=tipo, tamanio=tamanio, color=color, texto=textocancelar) + self.Reconstruye_JAMDialog(["tamaniosbuttons"]) + + def set_colors_buttons(self, colorbas=None, colorbor=None, colorcara=None): + ''' Setea los colores de los JAMButtons. ''' + self.boton_aceptar.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + self.boton_cancelar.set_colores(colorbas=colorbas, colorbor=colorbor, colorcara=colorcara) + self.Reconstruye_JAMDialog(["colorbuttons"]) + + def set_imagenes_buttons(self, imagenceptar=None, imagencancelar=None, tamanio=None): + ''' Setea las imágenes de los JAMButtons. ''' + self.boton_aceptar.set_tamanios(tamanio=(0,0)) + self.boton_cancelar.set_tamanios(tamanio=(0,0)) + self.boton_aceptar.set_imagen(origen=imagenceptar , tamanio=tamanio) + self.boton_cancelar.set_imagen(origen=imagencancelar , tamanio=tamanio) + self.Reconstruye_JAMDialog(["imagenbuttons"]) + + def connect(self, funcion_ok=None, funcion_cancel=None): + ''' Conecta los Botones a Funciones. ''' + if funcion_ok != self.funcion_ok: + self.funcion_ok= funcion_ok + self.boton_aceptar.connect(callback=self.funcion_ok, sonido_select=VG.get_sound_select()) + if funcion_cancel != self.funcion_cancel: + self.funcion_cancel= funcion_cancel + self.boton_cancelar.connect(callback=self.funcion_cancel, sonido_select=VG.get_sound_select()) + if not funcion_ok or not funcion_cancel: + self.boton_aceptar.connect(sonido_select=VG.get_sound_select()) + self.boton_cancelar.connect(sonido_select=VG.get_sound_select()) + # ------ Botones + + def set_colors_dialog(self, base=None, bordes=None): + ''' Setea los Colores del Contenedor de JAMDialog. ''' + if not base: base= VG.get_blanco() + if not bordes: bordes= VG.get_negro() + + if base != self.colores["base"]: + self.colores["base"]= base + if bordes != self.colores["bordes"]: + self.colores["bordes"]= bordes + self.label.set_contenedor(colorbas=self.colores["base"]) + self.Reconstruye_JAMDialog(["colorsdialog"]) + + def set_center(self): + ''' Centra la base y posiciona los botones. ''' + ''' + w,h= (800, 600) + try: + w,h= (pygame.display.Info().current_w, pygame.display.Info().current_h) + except: + w,h= (800, 600)''' + + w,h= self.resolucion + self.base.rect.center= (w/2,h/2) + x= self.base.rect.x+self.separador + y= self.base.rect.y+self.base.rect.h-self.separador-self.boton_aceptar.rect.h + self.boton_aceptar.set_posicion(punto=(x,y)) + x= self.base.rect.x+self.base.rect.w-self.separador-self.boton_cancelar.rect.w + self.boton_cancelar.set_posicion(punto=(x,y)) + + # ------------ CONSTRUCCIÓN ----------------------- + def Reconstruye_JAMDialog(self, cambios): + self.base.image= self.get_base() + self.base.rect= self.base.image.get_rect() + self.set_reset_tamanios_buttons() + self.set_center() + + def set_reset_tamanios_buttons(self): + ''' Los dos botones del mismo tamaño. ''' + botones= [self.boton_aceptar, self.boton_cancelar] + for boton in botones: + boton.set_tamanios(tamanio=(0,0)) + w,h= (0,0) + for boton in botones: + ww,hh= boton.get_tamanio() + if w < ww: w= ww + if h < hh: h= hh + for boton in botones: + boton.set_tamanios(tamanio=(w,h)) + + def get_label(self): + ''' Construye y Devuelve JAMLabel. ''' + label= JAMLabel(self.mensaje) + label.set_text(tipo=None, tamanio=50, color=None, texto=None) + label.set_contenedor(colorbas=self.colores["base"], grosor=None, colorbor=None) + return label + + def get_buttons(self): + ''' Construye y Devuelve los Botones. ''' + boton_aceptar = JAMButton ("Aceptar", None) + boton_cancelar = JAMButton ("Cancelar", None) + boton_aceptar.set_text(tipo=None, tamanio=30, color=None, texto=None) + boton_cancelar.set_text(tipo=None, tamanio=30, color=None, texto=None) + return boton_aceptar, boton_cancelar + + def get_base(self): + ''' Construye el sprite base. ''' + (a,b,c,d)= self.boton_aceptar.rect + (aa,bb,cc,dd)= self.boton_cancelar.rect + ancho_minimo= (c+cc+self.separador) + + (a,b,w,h)= self.label.rect + if w < ancho_minimo: w= ancho_minimo + + # Recuadro Interior con Etiqueta + tamanio_frame_interno= (self.grosorbor_int*2+w+self.separador*2, self.grosorbor_int*2+self.separador*2+h) + frame1= VG.get_Rectangulo(self.colores["base"], tamanio_frame_interno) + frame1= VG.get_my_surface_whit_border(frame1, self.colores["bordes"], self.grosorbor_int) + frame1= VG.pegar_imagenes_centradas(self.label.image, frame1) + + ww,hh= frame1.get_size() + # Recuadro pre-exterior con Recuadro Interior + tamanio_frame_externo= (ww+self.separador*2, hh+self.separador*2+d) + frame2= VG.get_Rectangulo(self.colores["base"], tamanio_frame_externo) + frame2= VG.get_my_surface_whit_border(frame2, self.colores["bordes"], self.grosorbor_med) + frame2.blit(frame1, (self.separador, self.separador)) + + ww,hh= frame2.get_size() + # Recuadro exterior - imagen final de la base + tamanio_frame_externo= (ww+self.grosorbor_ext*3,hh+self.grosorbor_ext*3) + base= VG.get_Rectangulo(self.colores["base"], tamanio_frame_externo) + base= VG.get_my_surface_whit_border(base, self.colores["bordes"], self.grosorbor_ext) + base= VG.pegar_imagenes_centradas(frame2, base) + return base + + def Describe(self): + ''' Describe la Estructura de Este Control. ''' + estructura = ''' + Estructura JAMDialog: + + JAMObject: + Base + Etiqueta + Boton Aceptar + Boton Cancelar + + Detalle Estructural: + Base: es una imagen construida en tiempo de ejecución sobre la cual se pega la imagen de la etiqueta + Etiqueta: JAMLabel con el texto del mensaje + Boton Aceptar: JAMButton para detectar evento click y responder con la función asignada mediante connect + Boton Cancelar: JAMButton para detectar evento click y responder con la función asignada mediante connect ''' + + print estructura, "\n" + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + +# ----- FIN DE CLASE JAMDialog - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1000,800) + + self.setup() + self.Run() + + 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 = JAMDialog(mensaje="Prueba JAMDialog", funcion_ok=None, funcion_cancel=None) + self.widgets.connect(funcion_ok=self.salir, funcion_cancel=self.salir) + + 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 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 == 150: + # Activa la siguiente línea para provocar cambios de texto en JAMLabel + contador= self.ejemplo_cambia_texto_en_Dialog() + # Activa la siguiente línea para provocar cambios de imagen en JAMLabel + contador= self.ejemplo_cambia_imagen_en_Dialog() + # Activa la siguiente línea para provocar cambios de contenedor en JAMLabel + contador= self.ejemplo_cambia_colors_Dialog() + + # Activa la siguiente línea para provocar cambios de texto en Botones + contador= self.ejemplo_cambia_texto_en_Buttons() + # Activa la siguiente línea para provocar cambios de imagen en Botones + contador= self.ejemplo_cambia_imagen_en_Buttons() + # Activa la siguiente línea para provocar cambios de color en los botones + contador= self.ejemplo_cambia_colors_Buttons() + pass + + 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_Dialog(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.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.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.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.set_text(tipo=None, tamanio=None, color=None, texto=texto) + return 0 + + def ejemplo_cambia_imagen_en_Dialog(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.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.set_imagen(origen=origen, tamanio=None) + return 0 + + def ejemplo_cambia_colors_Dialog(self): + import random + cambios = ["colorbas", "colorbor"] + modificar = random.choice(cambios) + + colores= [(10,20,100,255), (128,128,128,255), (255,255,255,255)] + color=random.choice(colores) + + if modificar == "colorbor": + self.widgets.set_colors_dialog(base=None, bordes=color) + if modificar == "colorbas": + self.widgets.set_colors_dialog(base=color, bordes=None) + return 0 + + def ejemplo_cambia_colors_Buttons(self): + import random + cambios = ["colorbas", "colorbor", "colorcara"] + modificar = random.choice(cambios) + + colores= [(10,20,100,255), (128,128,128,255), (255,255,255,255)] + color=random.choice(colores) + + if modificar == "colorbor": + self.widgets.set_colors_buttons(colorbas=None, colorbor=color, colorcara=None) + if modificar == "colorbas": + self.widgets.set_colors_buttons(colorbas=color, colorbor=None, colorcara=None) + if modificar == "colorcara": + self.widgets.set_colors_buttons(colorbas=None, colorbor=None, colorcara=color) + return 0 + + def ejemplo_cambia_texto_en_Buttons(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.set_text_buttons(tipo=tipo) + if modificar == "tamanio": + tamanios= [10,20,30,40,45] + tamanio=random.choice(tamanios) + self.widgets.set_text_buttons(tamanio=tamanio) + 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.set_text_buttons(color=color) + if modificar == "texto": + textos= ["JAMLabel", "Presiona escape cuando quieras salir", "Modificando Texto en JAMLabel", "CeibalJAM 2011"] + texto = random.choice(textos) + self.widgets.set_text_buttons(textoaceptar=texto, textocancelar=texto) + return 0 + + def ejemplo_cambia_imagen_en_Buttons(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.set_imagenes_buttons(imagenceptar=None, imagencancelar=None, tamanio=tamanio) + if modificar == "origen": + origenes= [VG.get_jamimagenes()[0], VG.get_jamimagenes()[1], -1] + origen = random.choice(origenes) + self.widgets.set_imagenes_buttons(imagenceptar=origen, imagencancelar=origen, tamanio=None) + return 0 + + 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.Describe() + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMDragAndDrop.py b/BiblioJAM/JAMDragAndDrop.py new file mode 100644 index 0000000..7134cd1 --- /dev/null +++ b/BiblioJAM/JAMDragAndDrop.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 29/05/2011 - CeibalJAM! - Uruguay +# JAMDragAndDrop.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG + +class JAMDragAndDrop(): + ''' Recibe un grupo de Sprites y hace drag and drop con el grupo entero. ''' + def __init__(self, objetivo): + self.objetivo= objetivo + self.rectangulo= (self.objetivo.posicion, self.busca_tamanio()) + self.select= False + self.callback_drop= None + self.callback_drag= None + + def busca_tamanio(self): + ''' Calcula el tamaño para un rectángulo que contenga a todos los rectángulos del objetivo. ''' + inicio= self.objetivo.posicion + ancho= 0 + alto= 0 + for sprite in self.objetivo.sprites(): + rectangulo= sprite.rect + x,y,w,h= rectangulo + if w > ancho: ancho= w + if h > alto: alto= h + return (ancho,alto) + + # ------------------ Sobrecargas para pygame.sprite.OrderedUpdates --------------------- + def draw(self, uno): + return self.objetivo.draw(uno) + def clear(self, uno, dos): + return self.objetivo.clear(uno, dos) + def update(self): + ''' Verifica cuando se selecciona o se suelta el objeto. ''' + self.rectangulo= pygame.Rect(self.objetivo.posicion, self.busca_tamanio()) + posicion = pygame.mouse.get_pos() + if self.rectangulo.collidepoint(posicion): + if pygame.event.get(pygame.MOUSEBUTTONDOWN): + if self.select: + self.select= False + if self.callback_drop: + return self.callback_drop(self, self.objetivo) + else: + self.select= True + if self.callback_drag: + return self.callback_drag(self, self.objetivo) + + x,y,w,h= self.rectangulo + xx,yy= (posicion[0]- w/2, posicion[1]- h/2) + if self.select: + self.objetivo.set_posicion(punto= (xx,yy)) + + # ------------------ SETEOS ------------------------------------------------- + def connect_drop(self, callback): + ''' Conecta el evento "soltar objetivo" a una función. La función a la que se llama debe tener 2 parámetros para + recibir self y self.objetivo, de esa manera se sabe cual es el DrangDrop y cual el grupo afectado por él.''' + self.callback_drop= callback + + def connect_drag(self, callback): + ''' Conecta el evento "soltar objetivo" a una función. La función a la que se llama debe tener 2 parámetros para + recibir self y self.objetivo, de esa manera se sabe cual es el DrangDrop y cual el grupo afectado por él.''' + self.callback_drag= callback + +# ----- FIN DE CLASE JAMDragAndDrop - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1024,758) + + self.setup() + self.Run() + + def setup(self): + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + pygame.display.set_caption("Ejemplo") + self.fondo = self.get_Fondo() + + from JAMCalendar import JAMCalendar + from JAMClock import JAMClock + self.calendario= JAMCalendar() # Mi grupo de Sprites. + self.draganddrop= JAMDragAndDrop(self.calendario) # JAMDragAndDrop con el grupo que se va a arrastrar. + self.draganddrop.connect_drop(self.reposiciona) # Callback para evento "soltar objetivo". + self.draganddrop.connect_drag(self.imprime_hola) # Callback para evento "tomar objetivo". + + self.widgets= self.draganddrop # Lo que se dibuja y actualiza es ahora JAMDragAndDrop + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + def Run(self): + self.ventana.blit(self.fondo, (0,0)) + self.widgets.draw(self.ventana) + pygame.display.update() + + self.contador = 0 + mes= 0 + while self.nivel == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.widgets.clear(self.ventana, self.fondo) + + self.widgets.update() + self.handle_event() + pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + if self.contador > 0: + self.contador += 1 + print "%s para reactivar JAMDragAndDrop sobre el Calendario" % (150 - self.contador) + if self.contador== 150: + print "JAMDragAndDrop reactivado" + self.widgets= self.draganddrop # Lo que se dibuja y actualiza es ahora JAMDragAndDrop + self.contador = 0 + + def imprime_hola(self, drag, group): + ''' Callback para tomar objetivo. ''' + print "Objeto seleccionado:", group, "en:", drag + def reposiciona(self, drag, group): + ''' Callback para soltar objetivo. + Cuando haces click sobre el grupo lo seleccionas y lo mueves, cuando vuelves a hacer click lo sueltas y + en este ejemplo, se intercambia JAMDragAndDrop por el grupo que contenía para de esa manera desabilitar el DragAndDrop y + habilitar los eventos sobre el grupo que contenía.''' + group.set_posicion(punto= (0,0)) + self.widgets= group#self.calendario # Lo que se dibuja y actualiza es ahora Mi grupo de Sprites. + self.contador= 1 + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill((0,0,0,255)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def salir(self): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMEntryText.py b/BiblioJAM/JAMEntryText.py new file mode 100644 index 0000000..47dc2da --- /dev/null +++ b/BiblioJAM/JAMEntryText.py @@ -0,0 +1,512 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 18/04/2011 - CeibalJAM! - Uruguay +# JAMEntryText.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys +from pygame.locals import * +gc.enable() +pygame.font.init() + +import JAMGlobals as VG +from JAMLabel import JAMLabel + +class JAMEntryText(pygame.sprite.OrderedUpdates): + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + self.buffertext= "" + + # teclas + self.handlekey= None + + #self.sensitive= False + + self.texto= {"fondo":VG.get_blanco(), "tipo":pygame.font.get_default_font(), "tamanio": 20, "color":VG.get_negro()} + + self.separador= 5 + self.posicion= (0,0) + + self.label_buffer= None + self.label_promp = None + self.frame= pygame.sprite.Sprite() + + self.JAMObjects= {"base":self.frame, "etiqueta_buffer":self.label_buffer, "promp":self.label_promp, + "buffertext": self.buffertext, "handle_key":self.handlekey} + + self.Reconstruye_JAMEntryText(["todo"]) + + # ------------- GETS ------------------------ + def get_tamanio(self): + return (self.frame.rect.w, self.frame.rect.h) + + # ------------ SETEOS ----------------------- + #def set_mouse_sensitive(self, valor): + # self.sensitive= bool(valor) + + def set_handle_key(self, valor): + ''' Habilita y desabilita la detección de eventos de tecla. + Por defecto no lo hace ya que JAMEntryText está pensado como objeto parte de JAMBoardEntryText. ''' + if bool(valor) == True: + self.handlekey= JAMHandleKeyEvent(self) + else: + self.handlekey= None + + def set_callback_enter(self, callback=None): + ''' Setea una función para ejecutarse cuando el usuario presione enter. + La función debe recibir un string para el buffer de texto de JAMEntryText''' + if self.handlekey: + self.handlekey.callback_enter= callback + + def set_buffer(self, texto): + ''' Setea el buffer de texto de JAMEntryText. ''' + if texto != self.buffertext: + self.buffertext = texto + self.label_buffer.set_text(tipo=self.texto["tipo"], tamanio=self.texto["tamanio"], color=self.texto["color"], texto=self.buffertext) + self.Reconstruye_JAMEntryText(["buffer"]) + + def set_entry(self, tipo_letra=None, tamanio_letra=None, color_texto=None, color_fondo=None): + ''' Setea colores, tamaño y tipo de letra. ''' + cambios= False + if tipo_letra and tipo_letra != self.texto["tipo"]: + self.texto["tipo"]= tipo_letra + cambios= True + if tamanio_letra and tamanio_letra != self.texto["tamanio"]: + self.texto["tamanio"]= tamanio_letra + cambios= True + if color_texto and color_texto != self.texto["color"]: + self.texto["color"]= color_texto + cambios= True + if color_fondo and color_fondo != self.texto["fondo"]: + self.texto["fondo"]= color_fondo + cambios= True + if cambios: + if self.texto["tipo"] and self.texto["tamanio"] and self.texto["color"] and self.texto["fondo"]: + self.label_buffer.set_text(tipo=self.texto["tipo"], tamanio=self.texto["tamanio"], color=self.texto["color"], texto=self.buffertext) + self.Reconstruye_JAMEntryText(["colores"]) + + def set_posicion(self, punto=(0,0)): + ''' Setea la posición de JAMEntryText. ''' + self.posicion= punto + self.frame.rect.x, self.frame.rect.y= self.posicion + x, y= (self.frame.rect.x + self.separador, self.frame.rect.y + self.separador) + self.label_buffer.set_posicion(punto=(x, y)) + x+= self.label_buffer.rect.w + self.label_promp.set_posicion(punto=(x, y)) + + def set_center(self, punto= None): + ''' Centra JAMEntryText en el punto indicado. ''' + w,h= (0,0) + if not punto or type(punto) != tuple or type(punto[0]) != int or type(punto[1]) != int: + w,h= (pygame.display.Info().current_w, pygame.display.Info().current_h) + posicion= (w/2-self.frame.rect.w/2, h/2-self.frame.rect.h/2) + self.set_posicion(punto=posicion) + elif type(punto) == tuple and type(punto[0]) == int and type(punto[1]) == int: + posicion= (punto[0]-self.frame.rect.w/2, punto[1]-self.frame.rect.h/2) + self.set_posicion(punto=posicion) + + # ------------ CONSTRUCCIÓN ----------------------- + def Reconstruye_JAMEntryText(self, cambios): + if "todo" in cambios: + self.label_buffer= JAMLabel(self.buffertext) + self.label_promp = Promp(self) + self.frame.image= self.get_base() + self.frame.rect= self.frame.image.get_rect() + self.add(self.frame) + self.add(self.label_buffer) + self.add(self.label_promp) + self.set_posicion(punto=self.posicion) + + if "colores" in cambios: + self.label_promp.Reconstruye_Promp(["todo"]) + self.frame.image= self.get_base() + self.frame.rect= self.frame.image.get_rect() + self.set_posicion(punto=self.posicion) + + if "buffer" in cambios: + self.frame.image= self.get_base() + self.frame.rect= self.frame.image.get_rect() + self.set_posicion(punto=self.posicion) + + def get_base(self): + ''' Construye el sprite base. ''' + (a,b,c,d)= self.label_buffer.rect + (aa,bb,cc,dd)= self.label_promp.rect + + ancho= c + cc + self.separador*2 + alto= 0 + if d > dd: + alto= d + else: + alto= dd + alto+= self.separador*2 + + frame1= VG.get_Rectangulo(self.texto["fondo"], (ancho,alto)) + return frame1 + + def Describe(self): + ''' Describe la Estructura de Este Control. ''' + estructura = ''' + Estructura JAMEntryText: + + JAMObject: + frame + etiqueta_buffer + promp + buffertext + handle_key + + Detalle Estructural: + frame: es una imagen construida en tiempo de ejecución sobre la cual se pegan las imágenes de las etiquetas + etiqueta_buffer: JAMLabel con el texto que el usuario va escribiendo + promp: Imagen que representa al promp con su efecto intermitente + buffertext: El texto que el usuario va ingresando + handle_key: Detector de eventos de teclado ''' + + print estructura, "\n" + print "Ejemplo, Configuración actual:\n" + print "\t", self.JAMObjects.keys(), "\n" + for k in self.JAMObjects.items(): + print k, "\n" + +class Promp(pygame.sprite.Sprite): + def __init__(self, entry): + pygame.sprite.Sprite.__init__(self) + ''' Es el promp. ''' + self.entry= entry + self.velocidad= 15 + self.contador= 0 + self.image= None + self.rect= None + self.imagen1= None + self.imagen2= None + + self.Reconstruye_Promp(["todo"]) + + def Reconstruye_Promp(self, cambios): + ''' Reconstruye las imágenes para efecto Titilar. ''' + if "todo" in cambios: + self.set_imagenes_promp() + self.image= self.imagen1 + self.rect= self.image.get_rect() + + def set_posicion(self, punto=(0,0)): + ''' Reposiciona el sprite. ''' + self.rect.x= punto[0] + self.rect.y= punto[1] + + def set_imagenes_promp(self): + ''' Construye las imagenes del promp. ''' + self.imagen1= self.get_promp(self.entry.texto["color"]) + self.imagen2= self.get_promp(self.entry.texto["fondo"]) + + def get_promp(self, color): + ''' Devuelve una Superficie con la Imagen del Texto. ''' + fuente = pygame.font.Font(pygame.font.match_font(self.entry.texto["tipo"], True, False), self.entry.texto["tamanio"]) + string_to_render = unicode( str("|".decode("utf-8")) ) + imagen_fuente = fuente.render(string_to_render, 1, (color)) + return imagen_fuente + + def update(self): + ''' Efecto Titilar. ''' + if self.entry.handlekey: + if self.contador == self.velocidad: + if self.image == self.imagen1: + self.image= self.imagen2 + else: + self.image= self.imagen1 + self.contador= 0 + else: + self.contador += 1 + else: + if self.image == self.imagen1: + self.image = self.imagen2 + + # teclas + if self.entry.handlekey: self.entry.handlekey.handle() + +class JAMHandleKeyEvent(): + def __init__(self, objeto_destino): + ''' Detecta eventos de teclado.''' + self.letras= VG.get_letras_down() + self.numeros= VG.get_numeros() + + self.objeto_destino= objeto_destino + self.text_buffer= [] + self.callback_enter= None + + def handle(self): + ''' Trata los eventos del teclado. ''' + eventos= pygame.event.get() + for event in eventos: + if event.type == pygame.KEYDOWN: + letra= pygame.key.name(event.key) + self.gestiona_event(letra) + + for event in eventos: + # Republica los Eventos. Porque se supone que hay un handle general para los eventos del programa mayor. + pygame.event.post(event) + + def gestiona_event(self, texto): + ''' Cuando el usuario presiona una espacio, borrar, enter o tilde. ''' + if texto in self.letras: + self.text_buffer.append( texto ) + return self.set_bufferentry() + + elif texto in self.numeros: + self.text_buffer.append( texto ) + return self.set_bufferentry() + + elif texto== "space": + # agrega un espacio en el buffer + self.text_buffer.append( " " ) + return self.set_bufferentry() + + elif texto== "backspace": + # Borra el último caracter ingresado + if len(self.text_buffer) <= 1: + self.text_buffer= [ " " ] + else: + self.text_buffer= self.text_buffer[0:-1] + return self.set_bufferentry() + + elif texto== "return": + # Llama a la función conectada al click del botón enter, pasandole como parámetro el texto en el buffer + if self.callback_enter: + buf= "" + try: + primercaracter= self.text_buffer[0] + if primercaracter != " ": + buf= primercaracter + else: + buf= "" + + for x in self.text_buffer[1:]: + buf += x + except: + return + if buf: + return self.callback_enter(buf) + + def set_bufferentry(self): + ''' Convierte el buffer en cadena de texto y lo devuelve a la función set_buffer del objeto destino. ''' + buf= "" + for x in self.text_buffer: + buf += x + self.objeto_destino.set_buffer(buf) + +''' +# Ejemplos para tratar los códigos de teclas posteriormente + def handle_key_enter(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + letra= pygame.key.name(event.key) + print letra + +teclas = pygame.key.get_pressed() + print teclas.index(1) + +All the keyboard event.key constants: + +Letters: + K_a ... K_z + +Numbers: + K_0 ... K_9 + +Control: + K_TAB + K_RETURN + K_ESCAPE + K_SCROLLOCK + K_SYSREQ + K_BREAK + K_DELETE + K_BACKSPACE + K_CAPSLOCK + K_CLEAR + K_NUMLOCK + +Punctuation: + K_SPACE + K_PERIOD + K_COMMA + K_QUESTION + K_AMPERSAND + K_ASTERISK + K_AT + K_CARET + K_BACKQUOTE + K_DOLLAR + K_EQUALS + K_EURO + K_EXCLAIM + K_SLASH, K_BACKSLASH + K_COLON, K_SEMICOLON + K_QUOTE, K_QUOTEDBL + K_MINUS, K_PLUS + K_GREATER, K_LESS + +Brackets: + K_RIGHTBRACKET, K_LEFTBRACKET + K_RIGHTPAREN, K_LEFTPAREN + +F-Keys: + K_F1 ... K_F15 + +Edit keys: + K_HELP + K_HOME + K_END + K_INSERT + K_PRINT + K_PAGEUP, K_PAGEDOWN + K_FIRST, K_LAST + +Keypad: + K_KP0 ... K_KP9 + K_KP_DIVIDE + K_KP_ENTER + K_KP_EQUALS + K_KP_MINUS + K_KP_MULTIPLY + K_KP_PERIOD + K_KP_PLUS + +SHF,CTL,ALT etc: + K_LALT, K_RALT + K_LCTRL, K_RCTRL + K_LSUPER, K_RSUPER + K_LSHIFT, K_RSHIFT + K_RMETA, K_LMETA + +Arrows: + K_LEFT + K_UP + K_RIGHT + K_DOWN + +Other: + K_MENU + K_MODE + K_PAUSE + K_POWER + K_UNDERSCORE + K_HASH + + K_UNKNOWN ''' + +# ----- FIN DE CLASE JAMEntryText - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (400,250) + + self.setup() + self.Run() + + 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 = JAMEntryText() + self.widgets.set_handle_key(True) + #self.widgets.set_mouse_sensitive(True) + self.widgets.set_callback_enter(self.print_buffer) + + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + 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 == 15: + # Activa la siguiente línea para provocar cambios de texto en JAMEntryText + #contador= self.ejemplo_cambia_texto_en_buffer() + # Activa la siguiente línea para provocar cambios de color en JAMEntryText + #contador= self.ejemplo_cambia_colors() + # Activa la siguiente línea para provocar cambios de Posición en JAMEntryText + #contador= self.ejemplo_cambia_posicion() + pass + + 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_posicion(self): + import random + valores= [100,205,130,140,150,180] + x, y= (random.choice(valores), random.choice(valores)) + self.widgets.set_center(punto= (x,y)) + return 0 + + def ejemplo_cambia_texto_en_buffer(self): + texto= "El usuario ingresa texto y el mismo aparece aqui . . ." + x= len(self.widgets.buffertext) + if len(texto) > x: + self.widgets.set_buffer(str(texto[0:x+1])) + else: + self.widgets.set_buffer("") + return 0 + + def ejemplo_cambia_colors(self): + import random + colores= [(128,128,128,255), (255,100,100,255), (255,255,100,255), (255,0,0,255)] + color=random.choice(colores) + self.widgets.set_entry(tipo_letra=None, tamanio_letra=None, color_texto=color, color_fondo=None) + return 0 + + 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: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def print_buffer(self, buffertext): + print self.widgets.buffertext + print buffertext + + def salir(self): + print "\n" + self.widgets.Describe() + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMFire.py b/BiblioJAM/JAMFire.py new file mode 100644 index 0000000..fc60983 --- /dev/null +++ b/BiblioJAM/JAMFire.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 31/05/2011 - CeibalJAM! - Uruguay +# JAMFire.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, os +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG + +class JAMFire(pygame.sprite.OrderedUpdates): + ''' Efecto Fuego. ''' + def __init__(self): + pygame.sprite.OrderedUpdates.__init__(self) + self.posicion= (0,0) + self.latencia= 6 + self.disminucion= 5 + self.deformacion= (0,0) + + self.fuego= Fuego(self) + self.add(self.fuego) + + def set_posicion(self, punto= (0,0)): + ''' Setea la posición desde donde se dibujará el efecto, es decir que punto es la base del fuego.''' + if type(punto)== tuple: + if len(punto)== 2 and type(punto[0])==int and type(punto[1]): + self.fuego.rect.x= punto[0]-self.fuego.rect.w/2 + self.fuego.rect.y= punto[1]-self.fuego.rect.h + self.posicion= punto + + def set_deforma_fire(self, valor): + ''' Divide por valor el tamaño del fuego. ''' + if type(valor)== tuple: + if len(valor)==2 and type(valor[0])== int and type(valor[1])== int: + self.deformacion= valor + self.fuego.deforma_imagenes() + self.set_posicion(punto= self.posicion) + + def set_disminuye_fire(self, valor): + ''' Divide por valor el tamaño del fuego. ''' + if type(valor)== int and valor > 0: + self.disminucion= valor + self.fuego.load_imagenes() + self.set_posicion(punto= self.posicion) + + def set_latencia(self, latencia): + ''' Setea la velocidad de secuenciación de imágenes para el fuego. ''' + if type(latencia)== int: self.latencia= latencia + + def get_tamanio(self): + ''' Devuelve el tamanio actual del fuego. ''' + return (self.fuego.rect.w, self.fuego.rect.h) + +class Fuego(pygame.sprite.Sprite): + ''' El Sprite para el efecto. ''' + def __init__(self, fire): + pygame.sprite.Sprite.__init__(self) + self.fire= fire + self.imagenes= [] + self.indice_actual= 0 + self.image= None + self.rect= None + self.contador= 0 + self.load_imagenes() + + def load_imagenes(self): + ''' carga las imagenes ajustando su tamaño según el indice de disminución especificado. ''' + self.imagenes= [] + for imagen in VG.get_fire(): + tam= imagen.get_size() + im= pygame.transform.scale(imagen, (tam[0]/self.fire.disminucion,tam[1]/self.fire.disminucion)) + self.imagenes.append(im) + self.indice_actual= 0 + self.image= self.imagenes[self.indice_actual] + self.rect= self.image.get_rect() + self.contador= 0 + + def deforma_imagenes(self): + ''' carga las imagenes ajustando su tamaño según la información en self.fire.deformacion. ''' + self.imagenes= [] + for imagen in VG.get_fire(): + im= pygame.transform.scale(imagen, self.fire.deformacion) + self.imagenes.append(im) + self.indice_actual= 0 + self.image= self.imagenes[self.indice_actual] + self.rect= self.image.get_rect() + self.contador= 0 + + def update(self): + ''' Secuencia las imágenes. ''' + if self.contador == self.fire.latencia: + try: + self.indice_actual += 1 + self.image= self.imagenes[self.indice_actual] + except: + self.indice_actual = 0 + self.image= self.imagenes[self.indice_actual] + self.contador = 0 + self.contador += 1 + +# ----- FIN DE CLASE JAMFire - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +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,600) + + self.setup() + self.Run() + + def setup(self): + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + pygame.display.set_caption("Ejemplo de Efecto JAMFire") + self.fondo = self.get_Fondo() + + #from JAMDragAndDrop import JAMDragAndDrop + #fire= JAMFire() + #self.widgets= JAMDragAndDrop(fire) + self.widgets = JAMFire() + self.widgets.set_posicion(punto= (400,300)) + #self.widgets.set_disminuye_fire(1) + #self.widgets.set_deforma_fire((50,100)) + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + 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==100: + self.widgets.set_posicion(punto= (200,300)) + self.widgets.set_disminuye_fire(2) + if contador==200: + self.widgets.set_posicion(punto= (400,300)) + self.widgets.set_disminuye_fire(3) + if contador==300: + self.widgets.set_posicion(punto= (200,300)) + self.widgets.set_disminuye_fire(4) + if contador==400: + self.widgets.set_posicion(punto= (400,300)) + self.widgets.set_disminuye_fire(5) + if contador==500: + self.widgets.set_posicion(punto= (200,300)) + self.widgets.set_disminuye_fire(6) + if contador==600: + self.widgets.set_posicion(punto= (400,300)) + self.widgets.set_disminuye_fire(7) + if contador==700: + self.widgets.set_posicion(punto= (200,300)) + self.widgets.set_disminuye_fire(8) + if contador==800: + self.widgets.set_posicion(punto= (400,300)) + self.widgets.set_disminuye_fire(9) + if contador==900: + self.widgets.set_posicion(punto= (200,300)) + self.widgets.set_disminuye_fire(1) + if contador==1000: + self.widgets.set_posicion(punto= (400,300)) + self.widgets.set_disminuye_fire(10) + contador= 0 + contador += 1''' + + self.widgets.update() + self.handle_event() + pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + + def get_Fondo(self): + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill(VG.get_gris1()) + #superficie.fill(VG.get_negro()) + #superficie.fill(VG.get_blanco()) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def salir(self): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMGlobals.py b/BiblioJAM/JAMGlobals.py new file mode 100644 index 0000000..eda39b0 --- /dev/null +++ b/BiblioJAM/JAMGlobals.py @@ -0,0 +1,375 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 16/04/2011 - CeibalJAM! - Uruguay +# JAMGlobals.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, os, platform +from pygame.locals import * +gc.enable() + +''' +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)''' + +#pygame.init() + +DIRECTORIO_BIBLIOJAM= os.path.dirname(__file__) + +# fuentes +def get_Font_fawn(): + return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/fawn.ttf", 43) +def get_Font_KOMIKND(): + return (DIRECTORIO_BIBLIOJAM + "/Recursos/Fuentes/KOMIKND.ttf", 43) + +# COLORES +def get_magenta(): + return (255, 0, 255, 255) +def get_blanco(): + return (255,255,255,255) +def get_negro(): + return (0,0,0,255) +def get_gris1(): + return (128,128,128,255) +def get_naranja1(): + return (240,150,0,255) +def get_celeste1(): + return (0,240,240,255) +def get_celeste_pastel_claro1(): + return (220,255,255,255) +def get_celeste_cielo1(): + return (51,121,183,255) +def get_celeste_cielo2(): + return (37,115,177,255) +def get_celeste_cielo3(): + return (91,152,209,255) +def get_celeste_cielo4(): + return (206,229,237,255) +def get_rojo1(): + return (255,0,0,255) +def get_amarillo1(): + return (255,255,0,255) +def get_verde1(): + return (0,183,0,255) +def get_bordo1(): + return (178,0,0,255) +def get_azul1(): + return (55,93,237,255) +def get_rojo1(): + return (255,0,0,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") +def get_terron(): + ''' 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") +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") +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") +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") + +# 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 +def get_icon_next(): + ''' 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 +def get_icon_exit(): + ''' 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 +def get_icon_cancel(): + ''' Devuelve las imágenes para botones ok y cancel. ''' + cancel= DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/tick_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 +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 +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 +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 +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 +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 +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 +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 + +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 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'] +def get_tildes_up(): + 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'] +def get_tildes_down(): + return ['á', 'é', 'í', 'ó', 'ú'] +def get_numeros(): + return ['1','2','3','4','5','6','7','8','9','0'] +def get_simbols(): + return ['^', '_', '~', '|', '\\', '#', '$', '€', '&', '@', '%', 'ª', 'º', '·', '¡', '!', '¿', '?', '\'', '\"', '(', ')', '{', '}', '[', ']'] +def get_otros(): + return [',', '.', ':', ';', '<', '>'] +def get_matematicas(): + return ['*', '+', '-', '/', '='] +def get_especiales(): + 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 + +# Estilos de colores para JAMBoard. +def get_estilo_naranja(): + 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) +def get_estilo_celeste(): + 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) + +# 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 + +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" + +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" + +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" + +# 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 + +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 + +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") + +''' +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 +''' + +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 + +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 diff --git a/BiblioJAM/JAMLabel.py b/BiblioJAM/JAMLabel.py new file mode 100644 index 0000000..7f5c7ef --- /dev/null +++ b/BiblioJAM/JAMLabel.py @@ -0,0 +1,383 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 16/04/2011 - CeibalJAM! - Uruguay +# JAMLabel.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, 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 ----- +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() + + + +if __name__ == "__main__": + Ejemplo() + diff --git a/BiblioJAM/JAMNubes.py b/BiblioJAM/JAMNubes.py new file mode 100644 index 0000000..0269127 --- /dev/null +++ b/BiblioJAM/JAMNubes.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 21/05/2011 - CeibalJAM! - Uruguay +# JAMNubes.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame, gc, sys, random +from pygame.locals import * +gc.enable() + +import JAMGlobals as VG + +class JAMNubes(pygame.sprite.OrderedUpdates): + ''' Un reloj hecho en pygame. ''' + def __init__(self, intensidad=5, rectangulo= (0,0,1200,300)): + pygame.sprite.OrderedUpdates.__init__(self) + + self.lluvia= False + self.nubes= pygame.sprite.OrderedUpdates() + + self.rectangulo= rectangulo + self.tamanios_posibles= [] + + self.redefine_tamanios() + + # cantidad de nubes + self.intensidad= intensidad + + # velocidades para las nubes + self.velocidades= [1, 2, 3, -1, -2, 3] + # latencia de actualización para las nubes + self.latencia= 1 + # genera nubes iniciales y las reposiciona + for c in range(0, self.intensidad+1): + self.genera_nube() + for x in range(self.rectangulo[2]/2): + self.update() + + self.sonido= VG.get_sound_lluvia() + self.suelo= self.rectangulo[1] + self.rectangulo[3] + self.rectangulo[3]/3 + + # ---------------- SETEOS ---------------------------- + def set_suelo(self, valor): + ''' Setea un valor y para el suelo (es donde desaparecen las gotas de lluvia). ''' + if not type(valor)== int: return + self.suelo= valor + + def set_lluvia(self, valor): + ''' Activa o desactiva la lluvia. ''' + if not type(valor)== bool: return + if valor == self.lluvia: + return + else: + self.lluvia= valor + if self.lluvia: + self.sonido.play(-1) + else: + self.sonido.stop() + + def set_intensidad(self, intensidad): + ''' Setea una nueva intensidad para las nubes. ''' + if not type(intensidad)== int: return + self.intensidad= intensidad + + def set_latencia(self, latencia): + ''' Setea una nueva latencia de actualización para las nubes. ''' + if not type(latencia)== int: return + self.latencia= latencia + + def set_rectangulo(self, rectangulo): + ''' Setea un nuevo rectángulo donde dibujar las nubes. ''' + if not type(rectangulo)== tuple: return + for x in rectangulo: + if not type(x)== int: return + self.rectangulo= rectangulo + self.redefine_tamanios() + + def set_velocidad(self, velocidades): + ''' Setea las velocidad de las nubes a partir de una lista de enteros. ''' + if not type(velocidades)== list: return + for nube in self.sprites(): + random.seed() + velocidad= random.choice(velocidades) + if not type(velocidad)== int: return + nube.velocidad= velocidad + self.velocidades= velocidades + + # ------------------ Construcción --------------------- + def redefine_tamanios(self): + ''' redefinición de tamaños para las nubes y el rectángulo general donde se dibujan. ''' + x,y,w,h= self.rectangulo + tamanio_base= self.rectangulo[2] + a= int(tamanio_base/4) + b= int(tamanio_base/3) + c= int(tamanio_base/2) + d= int(tamanio_base/1.5) + anchos= [a, b, b, c, c, c, d, d, d, d, d] + + altos= [2,3,4,5] + self.tamanios_posibles= [] + for ancho in anchos: + random.seed() + self.tamanios_posibles.append( (ancho,ancho/random.choice(altos)) ) + + def genera_nube(self): + ''' Nace una nube. ''' + nube= Nube(self) + x,y,w,h= nube.rect + + # posiciona la nube a derecha o izquierda según su dirección + random.seed() + if nube.velocidad > 0: + x= self.rectangulo[0]-w + 1 + elif nube.velocidad < 0: + x= self.rectangulo[0]+self.rectangulo[2] - 1 + + # posiciona la nube a una altura al azar + y= random.choice(range(self.rectangulo[1]-int(h/3 *2), self.rectangulo[1]+self.rectangulo[3]-h)) + + nube.set_posicion(punto= (x, y)) + self.nubes.add(nube) + self.add(nube) + + +class Nube(pygame.sprite.Sprite): + ''' Una nube. ''' + def __init__(self, nubes): + pygame.sprite.Sprite.__init__(self) + self.efecto= nubes + + self.posicion= (0,0) + self.latencia= self.efecto.latencia + self.cuenta= 0 + + random.seed() + self.velocidad= random.choice(self.efecto.velocidades) + + # define el tamanio de la nube + random.seed() + tamanio= random.choice(self.efecto.tamanios_posibles) + self.image= pygame.transform.scale(VG.get_nube(), tamanio) + random.seed() + if random.choice([True, False]): + self.image= pygame.transform.flip(self.image, True, False) + self.rect= self.image.get_rect() + + def set_posicion(self, punto=(0,0)): + ''' Setea la posicion de la nube. ''' + self.posicion= punto + self.rect.x, self.rect.y= self.posicion + + def update(self): + ''' Se mueve la nube según velocidad y orientacion. ''' + self.cuenta += 1 + if self.cuenta == self.latencia: + self.cuenta= 0 + self.set_posicion(punto=(self.posicion[0] + self.velocidad, self.posicion[1])) + if not self.rect.colliderect(self.efecto.rectangulo): + if len(self.efecto.nubes.sprites())-1 < self.efecto.intensidad: + while len(self.efecto.nubes.sprites())-1 != self.efecto.intensidad: + self.efecto.genera_nube() + self.kill() + else: + if self.efecto.lluvia: self.efecto.add(Gota(self.efecto, self.rect)) + + +class Gota(pygame.sprite.Sprite): + ''' Una gota de lluvia. ''' + def __init__(self, nubes, rect): + pygame.sprite.Sprite.__init__(self) + self.efecto= nubes + x,y,w,h= rect + + random.seed() + tamanio= random.randrange(1, 3) + colores= [VG.get_blanco(), VG.get_celeste_pastel_claro1()] + self.image= VG.get_Elipse(random.choice(colores), (tamanio,tamanio)) + self.rect= self.image.get_rect() + random.seed() + x= random.randrange(x, x+w) + y= y+h + self.posicion=(0,0) + self.set_posicion(punto=(x,y-1)) + + self.suelo= self.efecto.suelo + random.seed() + self.velocidad= random.randrange(3, 6) + + def set_posicion(self, punto=(0,0)): + self.posicion= punto + self.rect.x, self.rect.y= self.posicion + + def update(self): + x= self.rect.x + y= self.rect.y + self.velocidad + if y > self.suelo: + self.kill() + else: + self.set_posicion(punto=(x,y)) + +# ----- FIN DE CLASE JAMNube - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + self.ventana = None + self.reloj = None + self.nivel = "menu_0" + + self.fondo = None + self.widgets = None + + self.resolucion = (1200,700) + + self.setup() + self.Run() + + 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 = JAMNubes(rectangulo= (0,0,1200,400)) + self.ventana = pygame.display.get_surface() + self.reloj = pygame.time.Clock() + pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, + USEREVENT, QUIT, ACTIVEEVENT]) + pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, KEYUP, VIDEORESIZE, VIDEOEXPOSE]) + pygame.mouse.set_visible(True) + + 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) + + self.widgets.update() + self.handle_event() + pygame.event.clear() + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + + if contador== 200: + self.widgets.set_lluvia(True) + #self.widgets.set_intensidad(1) + if contador== 500: + #self.widgets.set_lluvia(False) + #self.widgets.set_intensidad(5) + contador= 0 + contador += 1 + + def get_Fondo(self): + import os + superficie = pygame.Surface( self.resolucion, flags=HWSURFACE ) + superficie.fill(VG.get_celeste_cielo3()) + im= os.getcwd() + "/Recursos/Praderas/pradera1.png" + imagen= pygame.transform.scale(pygame.image.load(im), (1200,300)) + superficie.blit(imagen, (0,400)) + return superficie + + def handle_event(self): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + teclas = pygame.key.get_pressed() + if teclas[pygame.K_ESCAPE]: + self.salir() + pygame.event.clear() + + def salir(self): + pygame.quit() + sys.exit() + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/JAMatrix.py b/BiblioJAM/JAMatrix.py new file mode 100644 index 0000000..8c0129e --- /dev/null +++ b/BiblioJAM/JAMatrix.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# BiblioJAM (Versión 2.0) - 31/05/2011 - CeibalJAM! - Uruguay +# JAMatrix.py por: Flavio Danesse fdanesse@gmail.com +# https://sites.google.com/site/flaviodanesse/ +# https://sites.google.com/site/sugaractivities/ +# http://codigosdeejemplo.blogspot.com/ + +import pygame +from pygame.locals import * + +import gc +gc.enable() + +import sys, os, random, threading + +from JAMLabel import JAMLabel +from JAMClock import JAMClock +from JAMCalendar import JAMCalendar + +import JAMGlobals as VG + +class JAMatrix(): + ''' Main de JAMatrix. ''' + def __init__(self, juego, ventana, resolucion): + self.juego= juego # el juego base + self.ventana= ventana # la ventana pygame + self.resolucion= resolucion # la resolucion de la pantalla + + self.widgets= None # grupo de terrones + self.interval= 0 # intervalo para agregar terrones + self.reloj= None # pygame.time + self.fondo= None # el fondo + self.etiqueta= None # el mensaje sobre lo que se está cargando + self.posicion_label= None # la posicion de la etiqueta para cambiar el mensaje + self.imagen_matrix= None # pygame.image.load(VG.get_terron()) + + try: + self.imagen_matrix= pygame.image.load(VG.get_terron()) + except: + pass + + self.callback_handle_event= None + self.latencia= 10 + self.setup() + #self.ventana.blit(self.fondo, (0,0)) + + # -------- SETEOS ---------------------- + def set_imagen_matrix(self, imagen): + ''' Setea una imagen para remplazar terron. ''' + if imagen: + self.imagen_matrix = pygame.image.load(imagen) + else: + self.imagen_matrix= None + + def set_callback_event(self, callback): + ''' Conecta una función para detectar eventos mientras se ejecuta JAMatrix. ''' + self.callback_handle_event= callback + def set_latencia(self, latencia): + ''' Setea la latencia de generación de terrones. ''' + if type(latencia)== int: self.latencia= latencia + # -------- SETEOS ---------------------- + + def carga_game(self): + ''' Carga este juego en un thread en segundo plano. ''' + thread = threading.Thread( target=self.juego.load ) + thread.start() + while not self.juego.estado: + self.run() + self.unload() # descarga todo lo que puede para liberar memoria + + def unload(self): + ''' Al cambiar el estado del juego porque se han cargado todos sus objetos, se descarga JAMatrix en un thread en segundo plano. ''' + thread = threading.Thread( target=self.descarga_todo ) + thread.start() + gc.collect() + + def run(self): + ''' JAMatrix corriendo. ''' + self.setup() + pygame.mouse.set_visible(False) + self.reloj.tick(35) + if self.interval == self.latencia: + self.genera_terrones() + self.interval = 0 + cambios=[] + self.widgets.clear(self.ventana, self.fondo) + self.widgets.update() + + cambios.extend ( self.widgets.draw(self.ventana) ) + pygame.display.update(cambios) + pygame.event.clear() + #pygame.time.wait(1) + self.interval += 1 + + if self.callback_handle_event: + return self.callback_handle_event() + + def descarga_todo(self): + ''' Libera memoria. ''' + self.widgets = None + self.interval = 0 + self.reloj = None + self.fondo = None + self.etiqueta = None + self.posicion_label = None + + def setup(self): + ''' Configura los objetos. ''' + if not self.widgets: + self.widgets = pygame.sprite.OrderedUpdates() + if not self.reloj: + self.reloj = pygame.time.Clock() + if not self.fondo: + self.fondo = self.get_fondo(color= VG.get_negro(), tamanio=self.resolucion) # superficie + if not self.etiqueta: + self.etiqueta = JAMLabel (texto="Cargando %s" % (self.juego.name)) + self.etiqueta.set_text(tamanio= 50, color= VG.get_blanco()) + if not self.posicion_label: + self.posicion_label = (self.resolucion[0]/2 - self.etiqueta.rect.w/2, self.resolucion[1]/2 - self.etiqueta.rect.h/2) + self.etiqueta.set_posicion(punto= self.posicion_label) + if not self.etiqueta in self.widgets.sprites(): + self.widgets.add(self.etiqueta) + + def get_fondo(self, color=(100,100,100,1), tamanio=(800,600)): + ''' El fondo de la ventana. ''' + superficie = pygame.Surface( tamanio, flags=HWSURFACE ) + superficie.fill(color) + return superficie + + def genera_terrones(self): + ''' Nace un Terron. ''' + if not self.imagen_matrix: return + x = random.randrange(0, self.resolucion[0], self.imagen_matrix.get_size()[0]) + terron = Terron(self) + terron.rect.x, terron.rect.y = (x,-50) + self.widgets.add(terron) + +class Terron(pygame.sprite.Sprite): + ''' Sprite Terron. ''' + def __init__(self, base): + pygame.sprite.Sprite.__init__(self) + self.base= base + self.imagen1 = self.base.imagen_matrix + self.image = self.imagen1 + self.rect = self.image.get_rect() + self.cuenta = 0 + def update(self): + ''' Terrón cae. ''' + self.rect.y += 4 + if self.rect.y > self.base.resolucion[1]: + self.kill() + +# ----- FIN DE CLASE JAMatrix - INICIO DE DEBUG Y EJEMPLO DE LA CLASE ----- +class Ejemplo(object): + def __init__(self): + + # Variables obligatorias en tu juego para poder utilizar JAMatrix. + self.resolucion = (800,600) + self.ventana = None + self.name= "Ejemplo JAMatrix" + self.estado = False + + # Variables del juego + self.reloj = None + self.fondo = None + + self.jamclock= None + self.jamcalendar= None + self.jamclock1= None + self.jamcalendar1= None + self.jamclock2= None + self.jamcalendar2= None + + self.preset() # crea la ventana principal + + # usando JAMatrix para cargar el juego + self.matrix= JAMatrix(self, self.ventana, self.resolucion) + self.matrix.set_callback_event(self.handle_event) # si quieres detectar eventos durante JAMatrix se ejecuta para cortar la carga. + #self.matrix.set_imagen_matrix(os.getcwd() + "/Recursos/Iconos/bandera_uruguay.png") + self.matrix.carga_game() # lanza JAMatrix + + # Comienza a ejecutar tu juego + self.estado= "menu_0" + self.run_menu_0() + + def run_menu_0(self): + ''' Tu juego corriendo. ''' + self.ventana.blit(self.fondo, (0,0)) + + self.jamclock.draw(self.ventana) + self.jamclock1.draw(self.ventana) + self.jamclock2.draw(self.ventana) + self.jamcalendar.draw(self.ventana) + self.jamcalendar1.draw(self.ventana) + self.jamcalendar2.draw(self.ventana) + + pygame.display.update() + + contador = 0 + while self.estado == "menu_0": + self.reloj.tick(35) + + cambios=[] + self.jamclock.clear(self.ventana, self.fondo) + self.jamclock1.clear(self.ventana, self.fondo) + self.jamclock2.clear(self.ventana, self.fondo) + self.jamcalendar.clear(self.ventana, self.fondo) + self.jamcalendar1.clear(self.ventana, self.fondo) + self.jamcalendar2.clear(self.ventana, self.fondo) + + self.jamclock.update() + self.jamclock1.update() + self.jamclock2.update() + self.jamcalendar.update() + self.jamcalendar1.update() + self.jamcalendar2.update() + + self.handle_event() + pygame.event.clear() + + cambios.extend ( self.jamclock.draw(self.ventana) ) + cambios.extend ( self.jamclock1.draw(self.ventana) ) + cambios.extend ( self.jamclock2.draw(self.ventana) ) + cambios.extend ( self.jamcalendar.draw(self.ventana) ) + cambios.extend ( self.jamcalendar1.draw(self.ventana) ) + cambios.extend ( self.jamcalendar2.draw(self.ventana) ) + + pygame.display.update(cambios) + contador += 1 + + def preset(self): + ''' Iniciando pygame y creando una ventana. ''' + pygame.init() + pygame.display.set_mode(self.resolucion , 0, 0) + self.ventana = pygame.display.get_surface() + + def load(self): + ''' Creando y seteando todos los objetos de tu juego. ''' + self.fondo = self.get_Fondo() + self.reloj = pygame.time.Clock() + + self.jamclock= JAMClock() + self.jamclock1= JAMClock() + self.jamclock2= JAMClock() + self.jamcalendar= JAMCalendar() + self.jamcalendar1= JAMCalendar() + self.jamcalendar2= JAMCalendar() + + # los tres de arriba + posicion= (25,25) + self.jamcalendar.set_posicion(punto= posicion) + + tamanio= self.jamcalendar.get_tamanio() + posicion= (posicion[0]+tamanio[0], posicion[1]) + self.jamclock.set_posicion(punto= posicion) + + tamanio= self.jamclock.get_tamanio() + posicion= (posicion[0]+tamanio[0], posicion[1]) + self.jamcalendar1.set_posicion(punto= posicion) + + # los tres de abajo + tamanio= self.jamcalendar.get_tamanio() + posicion= (self.jamcalendar.posicion[0], tamanio[1]+ posicion[1]) + self.jamclock1.set_posicion(punto= posicion) + + tamanio= self.jamclock1.get_tamanio() + posicion= (self.jamclock1.posicion[0]+tamanio[0], posicion[1]) + self.jamcalendar2.set_posicion(punto= posicion) + + tamanio= self.jamcalendar2.get_tamanio() + posicion= (self.jamclock.posicion[0]+tamanio[0], posicion[1]) + self.jamclock2.set_posicion(punto= posicion) + + + pygame.display.set_caption("Ejemplo de Carga de un Juego con JAMatrix") + 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) + self.estado= True # Todo se ha cargado y seteado, listo para correr el juego. + + 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): + pygame.quit() + sys.exit() + + + +if __name__ == "__main__": + Ejemplo() diff --git a/BiblioJAM/Recursos/Fuego/001.png b/BiblioJAM/Recursos/Fuego/001.png new file mode 100644 index 0000000..e06b63b --- /dev/null +++ b/BiblioJAM/Recursos/Fuego/001.png Binary files differ diff --git a/BiblioJAM/Recursos/Fuego/002.png b/BiblioJAM/Recursos/Fuego/002.png new file mode 100644 index 0000000..150a11a --- /dev/null +++ b/BiblioJAM/Recursos/Fuego/002.png Binary files differ diff --git a/BiblioJAM/Recursos/Fuego/004.png b/BiblioJAM/Recursos/Fuego/004.png new file mode 100644 index 0000000..f7e0cd0 --- /dev/null +++ b/BiblioJAM/Recursos/Fuego/004.png Binary files differ diff --git a/BiblioJAM/Recursos/Fuego/006.png b/BiblioJAM/Recursos/Fuego/006.png new file mode 100644 index 0000000..c8625ec --- /dev/null +++ b/BiblioJAM/Recursos/Fuego/006.png Binary files differ diff --git a/BiblioJAM/Recursos/Fuentes/KOMIKND.ttf b/BiblioJAM/Recursos/Fuentes/KOMIKND.ttf new file mode 100644 index 0000000..787333f --- /dev/null +++ b/BiblioJAM/Recursos/Fuentes/KOMIKND.ttf Binary files differ diff --git a/BiblioJAM/Recursos/Fuentes/fawn.ttf b/BiblioJAM/Recursos/Fuentes/fawn.ttf new file mode 100644 index 0000000..d7bd4ef --- /dev/null +++ b/BiblioJAM/Recursos/Fuentes/fawn.ttf Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/CeibalJAM.png b/BiblioJAM/Recursos/Iconos/CeibalJAM.png new file mode 100644 index 0000000..79b1dd4 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/CeibalJAM.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/anterior.png b/BiblioJAM/Recursos/Iconos/anterior.png new file mode 100644 index 0000000..ff6f2ae --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/anterior.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/audio.png b/BiblioJAM/Recursos/Iconos/audio.png new file mode 100644 index 0000000..17774dd --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/audio.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/bandera_uruguay.png b/BiblioJAM/Recursos/Iconos/bandera_uruguay.png new file mode 100644 index 0000000..5dec324 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/bandera_uruguay.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/cerrar.png b/BiblioJAM/Recursos/Iconos/cerrar.png new file mode 100644 index 0000000..3812628 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/cerrar.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/hoja.png b/BiblioJAM/Recursos/Iconos/hoja.png new file mode 100644 index 0000000..4f442e7 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/hoja.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/icono_jam.png b/BiblioJAM/Recursos/Iconos/icono_jam.png new file mode 100644 index 0000000..1ee0139 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/icono_jam.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/libreta.png b/BiblioJAM/Recursos/Iconos/libreta.png new file mode 100644 index 0000000..3470cd7 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/libreta.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/licencia.png b/BiblioJAM/Recursos/Iconos/licencia.png new file mode 100644 index 0000000..e94ef4d --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/licencia.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/play.png b/BiblioJAM/Recursos/Iconos/play.png new file mode 100644 index 0000000..66f32d8 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/play.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/siguiente.png b/BiblioJAM/Recursos/Iconos/siguiente.png new file mode 100644 index 0000000..a68e2db --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/siguiente.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/tick_cancel.png b/BiblioJAM/Recursos/Iconos/tick_cancel.png new file mode 100644 index 0000000..ee05d65 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/tick_cancel.png Binary files differ diff --git a/BiblioJAM/Recursos/Iconos/tick_ok.png b/BiblioJAM/Recursos/Iconos/tick_ok.png new file mode 100644 index 0000000..cb87c48 --- /dev/null +++ b/BiblioJAM/Recursos/Iconos/tick_ok.png Binary files differ diff --git a/BiblioJAM/Recursos/Nubes/nube1.png b/BiblioJAM/Recursos/Nubes/nube1.png new file mode 100644 index 0000000..d86cf37 --- /dev/null +++ b/BiblioJAM/Recursos/Nubes/nube1.png Binary files differ diff --git a/BiblioJAM/Recursos/Praderas/pradera1.png b/BiblioJAM/Recursos/Praderas/pradera1.png new file mode 100644 index 0000000..ce307a2 --- /dev/null +++ b/BiblioJAM/Recursos/Praderas/pradera1.png Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/alarma-reloj1.ogg b/BiblioJAM/Recursos/Sonidos/alarma-reloj1.ogg new file mode 100644 index 0000000..f53d476 --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/alarma-reloj1.ogg Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/alarma-reloj2.ogg b/BiblioJAM/Recursos/Sonidos/alarma-reloj2.ogg new file mode 100644 index 0000000..0ae9bed --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/alarma-reloj2.ogg Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/alarma1.mp3 b/BiblioJAM/Recursos/Sonidos/alarma1.mp3 new file mode 100644 index 0000000..79f944a --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/alarma1.mp3 Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/alarma2.mp3 b/BiblioJAM/Recursos/Sonidos/alarma2.mp3 new file mode 100644 index 0000000..1f78199 --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/alarma2.mp3 Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/clock_tick1.ogg b/BiblioJAM/Recursos/Sonidos/clock_tick1.ogg new file mode 100644 index 0000000..2b03dbe --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/clock_tick1.ogg Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/lluvia.ogg b/BiblioJAM/Recursos/Sonidos/lluvia.ogg new file mode 100644 index 0000000..1116e7b --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/lluvia.ogg Binary files differ diff --git a/BiblioJAM/Recursos/Sonidos/select.ogg b/BiblioJAM/Recursos/Sonidos/select.ogg new file mode 100644 index 0000000..0bd45a1 --- /dev/null +++ b/BiblioJAM/Recursos/Sonidos/select.ogg Binary files differ diff --git a/BiblioJAM/__init__.py b/BiblioJAM/__init__.py new file mode 100644 index 0000000..aa9b015 --- /dev/null +++ b/BiblioJAM/__init__.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +__version__ = "2" +__autor__ = "Flavio Danesse fdanesse@gmailcom" +__date__ = "Abril de 2011" +__copyright__ = "Copyright (c) 2010 Flavio Danesse" +__license__ = "GPL3" + -- cgit v0.9.1