diff options
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | JAMBoard.py | 13 | ||||
-rw-r--r-- | JAMBoardEntryText.py | 10 | ||||
-rw-r--r-- | JAMBoardTypes.py | 9 | ||||
-rw-r--r-- | JAMBook.py | 10 | ||||
-rw-r--r-- | JAMButton.py | 9 | ||||
-rw-r--r-- | JAMCalendar.py | 47 | ||||
-rw-r--r-- | JAMClock.py | 19 | ||||
-rw-r--r-- | JAMComboBox.py | 9 | ||||
-rw-r--r-- | JAMCron.py | 9 | ||||
-rw-r--r-- | JAMDialog.py | 9 | ||||
-rw-r--r-- | JAMDragAndDrop.py | 13 | ||||
-rw-r--r-- | JAMEntryText.py | 785 | ||||
-rw-r--r-- | JAMFire.py | 18 | ||||
-rw-r--r-- | JAMGlobals.py | 13 | ||||
-rw-r--r-- | JAMLabel.py | 10 | ||||
-rw-r--r-- | JAMNubes.py | 540 | ||||
-rw-r--r-- | JAMatrix.py | 6 | ||||
-rw-r--r-- | __init__.py | 11 |
19 files changed, 765 insertions, 776 deletions
@@ -1,3 +1,4 @@ *.pyc *.pyo +*.bak *.??~ diff --git a/JAMBoard.py b/JAMBoard.py index e15fc68..287bcab 100644 --- a/JAMBoard.py +++ b/JAMBoard.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() @@ -54,7 +51,7 @@ class JAMBoard(pygame.sprite.OrderedUpdates): # ------------ 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.''' + ''' 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: @@ -154,7 +151,7 @@ class JAMBoard(pygame.sprite.OrderedUpdates): ''' 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 + 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]) diff --git a/JAMBoardEntryText.py b/JAMBoardEntryText.py index e845717..fe97b96 100644 --- a/JAMBoardEntryText.py +++ b/JAMBoardEntryText.py @@ -1,13 +1,11 @@ #!/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 +import gc +import sys +import tempfile -import pygame, gc, sys, tempfile from pygame.locals import * gc.enable() diff --git a/JAMBoardTypes.py b/JAMBoardTypes.py index a3ba06e..953a823 100644 --- a/JAMBoardTypes.py +++ b/JAMBoardTypes.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() @@ -1,13 +1,11 @@ #!/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 +import sys +import gc +import subprocess -import pygame, sys, gc, subprocess from pygame.locals import * gc.enable() diff --git a/JAMButton.py b/JAMButton.py index b302d51..bd5666e 100644 --- a/JAMButton.py +++ b/JAMButton.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() diff --git a/JAMCalendar.py b/JAMCalendar.py index 1fefa1c..8737a6d 100644 --- a/JAMCalendar.py +++ b/JAMCalendar.py @@ -1,13 +1,14 @@ #!/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 +import gc +import sys +import gobject +import time +import datetime +import os -import pygame, gc, sys, gobject, time, datetime, os from pygame.locals import * gc.enable() pygame.font.init() @@ -152,13 +153,13 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): 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: + if tipo: self.datos_fechas_text["tipo"]= tipo cambios= True - if tamanio: + if tamanio: self.datos_fechas_text["tamanio"]= tamanio cambios= True - if color: + if color: self.datos_fechas_text["color"]= color cambios= True @@ -180,7 +181,7 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): if fuente: self.datos_fechas_text["font_from_file"]= fuente cambios= True - if tamanio: + if tamanio: self.datos_fechas_text["tamanio"]= tamanio cambios= True @@ -199,13 +200,13 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): 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: + if tipo: self.datos_dias_text["tipo"]= tipo cambios= True - if tamanio: + if tamanio: self.datos_dias_text["tamanio"]= tamanio cambios= True - if color: + if color: self.datos_dias_text["color"]= color cambios= True @@ -227,7 +228,7 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): if fuente: self.datos_dias_text["font_from_file"]= fuente cambios= True - if tamanio: + if tamanio: self.datos_dias_text["tamanio"]= tamanio cambios= True @@ -247,13 +248,13 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): 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: + if tipo: self.datos_cabecera_text["tipo"]= tipo cambios= True - if tamanio: + if tamanio: self.datos_cabecera_text["tamanio"]= tamanio cambios= True - if color: + if color: self.datos_cabecera_text["color"]= color cambios= True @@ -275,7 +276,7 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): if fuente: self.datos_cabecera_text["font_from_file"]= fuente cambios= True - if tamanio: + if tamanio: self.datos_cabecera_text["tamanio"]= tamanio cambios= True @@ -307,7 +308,7 @@ class JAMCalendar(pygame.sprite.OrderedUpdates): # -----------------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: + 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"] @@ -536,7 +537,7 @@ class Botones_Fechas(pygame.sprite.OrderedUpdates): 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: + if type(punto[0])== int and type(punto[1])== int: self.posicion= punto x,y = self.posicion yy= y @@ -591,7 +592,7 @@ class Botones_Dias(pygame.sprite.OrderedUpdates): 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: + if type(punto[0])== int and type(punto[1])== int: self.posicion= punto x,y= self.posicion for boton in self.matriz_botones: @@ -682,7 +683,7 @@ class Cabecera(pygame.sprite.OrderedUpdates): self.boton_next= JAMButton(">>", None) self.matriz_botones.append(self.boton_next) - self.boton_next.connect(callback= self.get_next_mes, sonido_select= None) + self.boton_next.connect(callback= self.get_next_mes, sonido_select= None) def set_text(self): ''' Seteos de texto en botones. ''' @@ -699,7 +700,7 @@ class Cabecera(pygame.sprite.OrderedUpdates): 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: + 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)) diff --git a/JAMClock.py b/JAMClock.py index 7719586..444718e 100644 --- a/JAMClock.py +++ b/JAMClock.py @@ -1,13 +1,14 @@ #!/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 +import gc +import sys +import gobject +import time +import datetime +import os -import pygame, gc, sys, gobject, time, datetime, os from pygame.locals import * gc.enable() pygame.font.init() @@ -174,7 +175,7 @@ class Digital(JAMButton): ''' Etiqueta con la hora en forma digital.''' def __init__(self, clock): JAMButton.__init__(self, "", None) - self.clock= clock + 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"] @@ -202,7 +203,7 @@ class Timer(pygame.sprite.Sprite): fecha= str(datetime.date.today()) if hora != self.hora: self.clock.label.set_text(texto= hora) - h,m,s= hora.split(":") + h,m,s= hora.split(":") hh, mm, ss= self.hora.split(":") if s != ss: @@ -223,7 +224,7 @@ class Aguja(pygame.sprite.Sprite): 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() + 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 diff --git a/JAMComboBox.py b/JAMComboBox.py index b0ec196..2b2301d 100644 --- a/JAMComboBox.py +++ b/JAMComboBox.py @@ -7,7 +7,14 @@ # https://sites.google.com/site/sugaractivities/ # http://codigosdeejemplo.blogspot.com/ -import pygame, gc, sys, gobject, time, datetime, os +import pygame +import gc +import sys +import gobject +import time +import datetime +import os + from pygame.locals import * gc.enable() pygame.font.init() @@ -7,7 +7,12 @@ # https://sites.google.com/site/sugaractivities/ # http://codigosdeejemplo.blogspot.com/ -import pygame, gc, sys, time, os +import pygame +import gc +import sys +import time +import os + from pygame.locals import * gc.enable() @@ -201,7 +206,7 @@ class Ejemplo(object): if contador == 400: self.widgets.play() contador= 0''' - contador+= 1 + contador+= 1 self.widgets.update() self.handle_event() cambios.extend ( self.widgets.draw(self.ventana) ) diff --git a/JAMDialog.py b/JAMDialog.py index c3cec16..e31f0fc 100644 --- a/JAMDialog.py +++ b/JAMDialog.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() diff --git a/JAMDragAndDrop.py b/JAMDragAndDrop.py index 7134cd1..d6a7e12 100644 --- a/JAMDragAndDrop.py +++ b/JAMDragAndDrop.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() @@ -49,7 +46,7 @@ class JAMDragAndDrop(): self.select= False if self.callback_drop: return self.callback_drop(self, self.objetivo) - else: + else: self.select= True if self.callback_drag: return self.callback_drag(self, self.objetivo) @@ -94,7 +91,7 @@ class Ejemplo(object): 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= 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". diff --git a/JAMEntryText.py b/JAMEntryText.py index 47dc2da..23bd90b 100644 --- a/JAMEntryText.py +++ b/JAMEntryText.py @@ -1,13 +1,10 @@ #!/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 +import gc +import sys -import pygame, gc, sys from pygame.locals import * gc.enable() pygame.font.init() @@ -16,298 +13,298 @@ 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" + 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() + 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) + 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 + 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) + print teclas.index(1) All the keyboard event.key constants: @@ -401,112 +398,112 @@ Other: # ----- 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() + 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() + Ejemplo() @@ -1,13 +1,11 @@ #!/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 +import gc +import sys +import os -import pygame, gc, sys, os from pygame.locals import * gc.enable() @@ -22,7 +20,7 @@ class JAMFire(pygame.sprite.OrderedUpdates): self.disminucion= 5 self.deformacion= (0,0) - self.fuego= Fuego(self) + self.fuego= Fuego(self) self.add(self.fuego) def set_posicion(self, punto= (0,0)): @@ -73,7 +71,7 @@ class Fuego(pygame.sprite.Sprite): 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)) + 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] @@ -84,7 +82,7 @@ class Fuego(pygame.sprite.Sprite): ''' 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) + im= pygame.transform.scale(imagen, self.fire.deformacion) self.imagenes.append(im) self.indice_actual= 0 self.image= self.imagenes[self.indice_actual] @@ -95,7 +93,7 @@ class Fuego(pygame.sprite.Sprite): ''' Secuencia las imágenes. ''' if self.contador == self.fire.latencia: try: - self.indice_actual += 1 + self.indice_actual += 1 self.image= self.imagenes[self.indice_actual] except: self.indice_actual = 0 diff --git a/JAMGlobals.py b/JAMGlobals.py index eda39b0..eb3fd24 100644 --- a/JAMGlobals.py +++ b/JAMGlobals.py @@ -1,13 +1,12 @@ #!/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 +import gc +import sys +import os +import platform -import pygame, gc, sys, os, platform from pygame.locals import * gc.enable() @@ -340,7 +339,7 @@ def get_sound_lluvia(): ''' def get_libro(): Libreta de lectura. - return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/libreta.png" + return DIRECTORIO_BIBLIOJAM + "/Recursos/Iconos/libreta.png" def get_hoja(): Devuelve la imagen para una hoja vacía. diff --git a/JAMLabel.py b/JAMLabel.py index 7f5c7ef..1f7df3b 100644 --- a/JAMLabel.py +++ b/JAMLabel.py @@ -1,13 +1,11 @@ #!/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 +import gc +import sys +import os -import pygame, gc, sys, os from pygame.locals import * gc.enable() pygame.font.init() diff --git a/JAMNubes.py b/JAMNubes.py index 0269127..43975a6 100644 --- a/JAMNubes.py +++ b/JAMNubes.py @@ -1,281 +1,289 @@ #!/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 os +import pygame +import gc +import sys +import random -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) - - + + 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)) - - + """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)) - + """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() - + 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): + 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() + Ejemplo() diff --git a/JAMatrix.py b/JAMatrix.py index 8c0129e..e11acef 100644 --- a/JAMatrix.py +++ b/JAMatrix.py @@ -1,12 +1,6 @@ #!/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 * diff --git a/__init__.py b/__init__.py index aa9b015..caba484 100644 --- a/__init__.py +++ b/__init__.py @@ -1,9 +1,8 @@ -#!/usr/bin/env python
+#!/usr/bin/env python # -*- coding: utf-8 -*- -__version__ = "2"
-__autor__ = "Flavio Danesse fdanesse@gmailcom"
-__date__ = "Abril de 2011"
-__copyright__ = "Copyright (c) 2010 Flavio Danesse"
+__version__ = "3" +__autor__ = "Flavio Danesse fdanesse@gmailcom" +__date__ = "Agosto de 2012" +__copyright__ = "Copyright (c) 2010 Flavio Danesse" __license__ = "GPL3" - |