Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorflavio <fdanesse@gmail.com>2011-12-07 23:10:50 (GMT)
committer flavio <fdanesse@gmail.com>2011-12-07 23:10:50 (GMT)
commit9d57ae40095b2928672b2f4b23a87b8d5927753e (patch)
treef36922e4cb1db2642d954a9fe71493fcdc55df23
CucaraSims Base
-rw-r--r--.gitignore3
-rw-r--r--Archivos_y_Directorios.py233
-rw-r--r--BiblioJAM/JAMBoard.py541
-rw-r--r--BiblioJAM/JAMBoardEntryText.py453
-rw-r--r--BiblioJAM/JAMBoardTypes.py430
-rw-r--r--BiblioJAM/JAMBook.py294
-rw-r--r--BiblioJAM/JAMButton.py560
-rw-r--r--BiblioJAM/JAMCalendar.py816
-rw-r--r--BiblioJAM/JAMClock.py445
-rw-r--r--BiblioJAM/JAMComboBox.py404
-rw-r--r--BiblioJAM/JAMCron.py228
-rw-r--r--BiblioJAM/JAMDialog.py413
-rw-r--r--BiblioJAM/JAMDragAndDrop.py166
-rw-r--r--BiblioJAM/JAMEntryText.py512
-rw-r--r--BiblioJAM/JAMFire.py213
-rw-r--r--BiblioJAM/JAMGlobals.py375
-rw-r--r--BiblioJAM/JAMLabel.py383
-rw-r--r--BiblioJAM/JAMNubes.py281
-rw-r--r--BiblioJAM/JAMatrix.py302
-rw-r--r--BiblioJAM/Recursos/Fuego/001.pngbin0 -> 24476 bytes
-rw-r--r--BiblioJAM/Recursos/Fuego/002.pngbin0 -> 29871 bytes
-rw-r--r--BiblioJAM/Recursos/Fuego/004.pngbin0 -> 25067 bytes
-rw-r--r--BiblioJAM/Recursos/Fuego/006.pngbin0 -> 21838 bytes
-rw-r--r--BiblioJAM/Recursos/Fuentes/KOMIKND.ttfbin0 -> 55372 bytes
-rw-r--r--BiblioJAM/Recursos/Fuentes/fawn.ttfbin0 -> 21068 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/CeibalJAM.pngbin0 -> 5476 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/anterior.pngbin0 -> 1267 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/audio.pngbin0 -> 6668 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/bandera_uruguay.pngbin0 -> 19454 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/cerrar.pngbin0 -> 3610 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/hoja.pngbin0 -> 210924 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/icono_jam.pngbin0 -> 1412 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/libreta.pngbin0 -> 3213 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/licencia.pngbin0 -> 2977 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/play.pngbin0 -> 1028 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/siguiente.pngbin0 -> 1219 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/tick_cancel.pngbin0 -> 2346 bytes
-rw-r--r--BiblioJAM/Recursos/Iconos/tick_ok.pngbin0 -> 2187 bytes
-rw-r--r--BiblioJAM/Recursos/Nubes/nube1.pngbin0 -> 26489 bytes
-rw-r--r--BiblioJAM/Recursos/Praderas/pradera1.pngbin0 -> 648516 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/alarma-reloj1.oggbin0 -> 13095 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/alarma-reloj2.oggbin0 -> 19194 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/alarma1.mp3bin0 -> 36746 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/alarma2.mp3bin0 -> 61857 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/clock_tick1.oggbin0 -> 45504 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/lluvia.oggbin0 -> 43092 bytes
-rw-r--r--BiblioJAM/Recursos/Sonidos/select.oggbin0 -> 12114 bytes
-rw-r--r--BiblioJAM/__init__.py9
-rw-r--r--Bicho.py359
-rw-r--r--CUCARACHA/Imagenes/agua.pngbin0 -> 17802 bytes
-rw-r--r--CUCARACHA/Imagenes/ciclo_vital1.pngbin0 -> 28483 bytes
-rw-r--r--CUCARACHA/Imagenes/ciclo_vital2.pngbin0 -> 71142 bytes
-rw-r--r--CUCARACHA/Imagenes/cucaracha1.pngbin0 -> 6073 bytes
-rw-r--r--CUCARACHA/Imagenes/cucaracha2.pngbin0 -> 5686 bytes
-rw-r--r--CUCARACHA/Imagenes/cucaracha3.pngbin0 -> 5077 bytes
-rw-r--r--CUCARACHA/Imagenes/cucaracha4.pngbin0 -> 5395 bytes
-rw-r--r--CUCARACHA/Imagenes/cucarasimsico.pngbin0 -> 511 bytes
-rw-r--r--CUCARACHA/Imagenes/fondo.pngbin0 -> 242006 bytes
-rw-r--r--CUCARACHA/Imagenes/fondo4.pngbin0 -> 414483 bytes
-rw-r--r--CUCARACHA/Imagenes/huevos.pngbin0 -> 2983 bytes
-rw-r--r--CUCARACHA/Imagenes/jarra.pngbin0 -> 7129 bytes
-rw-r--r--CUCARACHA/Imagenes/muda1.pngbin0 -> 32567 bytes
-rw-r--r--CUCARACHA/Imagenes/muda2.pngbin0 -> 30490 bytes
-rw-r--r--CUCARACHA/Imagenes/muerta.pngbin0 -> 5600 bytes
-rw-r--r--CUCARACHA/Imagenes/muerte1.pngbin0 -> 57284 bytes
-rw-r--r--CUCARACHA/Imagenes/pan.pngbin0 -> 13449 bytes
-rw-r--r--CUCARACHA/Imagenes/portada.pngbin0 -> 23088 bytes
-rw-r--r--CUCARACHA/Imagenes/reproduccion1.pngbin0 -> 46717 bytes
-rw-r--r--CUCARACHA/Imagenes/reproduccion2.pngbin0 -> 35986 bytes
-rw-r--r--CUCARACHA/Lectura.py247
-rw-r--r--CUCARACHA/Muda/muda_001805.pngbin0 -> 42967 bytes
-rw-r--r--CUCARACHA/Muda/muda_001815.pngbin0 -> 43628 bytes
-rw-r--r--CUCARACHA/Muda/muda_001825.pngbin0 -> 43775 bytes
-rw-r--r--CUCARACHA/Muda/muda_001835.pngbin0 -> 44684 bytes
-rw-r--r--CUCARACHA/Muda/muda_001845.pngbin0 -> 43228 bytes
-rw-r--r--CUCARACHA/Muda/muda_001855.pngbin0 -> 43364 bytes
-rw-r--r--CUCARACHA/Muda/muda_001865.pngbin0 -> 42885 bytes
-rw-r--r--CUCARACHA/Muda/muda_001875.pngbin0 -> 43252 bytes
-rw-r--r--CUCARACHA/Muda/muda_001885.pngbin0 -> 43545 bytes
-rw-r--r--CUCARACHA/Muda/muda_001895.pngbin0 -> 42693 bytes
-rw-r--r--CUCARACHA/Muda/muda_001905.pngbin0 -> 42837 bytes
-rw-r--r--CUCARACHA/Muda/muda_001915.pngbin0 -> 40527 bytes
-rw-r--r--CUCARACHA/Muda/muda_001925.pngbin0 -> 42204 bytes
-rw-r--r--CUCARACHA/Muda/muda_001935.pngbin0 -> 43286 bytes
-rw-r--r--CUCARACHA/Muda/muda_001945.pngbin0 -> 42308 bytes
-rw-r--r--CUCARACHA/Muda/muda_001955.pngbin0 -> 39294 bytes
-rw-r--r--CUCARACHA/Muda/muda_001965.pngbin0 -> 39557 bytes
-rw-r--r--CUCARACHA/Muda/muda_001975.pngbin0 -> 42238 bytes
-rw-r--r--CUCARACHA/Muda/muda_001985.pngbin0 -> 42521 bytes
-rw-r--r--CUCARACHA/Muda/muda_001995.pngbin0 -> 43395 bytes
-rw-r--r--CUCARACHA/Muda/muda_002005.pngbin0 -> 42656 bytes
-rw-r--r--CUCARACHA/Muda/muda_002015.pngbin0 -> 43123 bytes
-rw-r--r--CUCARACHA/Muda/muda_002025.pngbin0 -> 43009 bytes
-rw-r--r--CUCARACHA/Muda/muda_002035.pngbin0 -> 43201 bytes
-rw-r--r--CUCARACHA/Muda/muda_002045.pngbin0 -> 43352 bytes
-rw-r--r--CUCARACHA/Muda/muda_002055.pngbin0 -> 42852 bytes
-rw-r--r--CUCARACHA/Muda/muda_002065.pngbin0 -> 42672 bytes
-rw-r--r--CUCARACHA/Muda/muda_002075.pngbin0 -> 42716 bytes
-rw-r--r--CUCARACHA/Muda/muda_002085.pngbin0 -> 43636 bytes
-rw-r--r--CUCARACHA/Muda/muda_002095.pngbin0 -> 42864 bytes
-rw-r--r--CUCARACHA/Muda/muda_002105.pngbin0 -> 43427 bytes
-rw-r--r--CUCARACHA/Muda/muda_002115.pngbin0 -> 42669 bytes
-rw-r--r--CUCARACHA/Muda/muda_002125.pngbin0 -> 42826 bytes
-rw-r--r--CUCARACHA/Muda/muda_002135.pngbin0 -> 43438 bytes
-rw-r--r--CUCARACHA/Muda/muda_002145.pngbin0 -> 43262 bytes
-rw-r--r--CUCARACHA/Muda/muda_002155.pngbin0 -> 43291 bytes
-rw-r--r--CUCARACHA/Muda/muda_002165.pngbin0 -> 42059 bytes
-rw-r--r--CUCARACHA/Muda/muda_002175.pngbin0 -> 42628 bytes
-rw-r--r--CUCARACHA/Muda/muda_002185.pngbin0 -> 42184 bytes
-rw-r--r--CUCARACHA/Sonidos/cucaracha.oggbin0 -> 12198 bytes
-rw-r--r--CUCARACHA/Sonidos/musica.oggbin0 -> 3180827 bytes
-rw-r--r--CUCARACHA/Sonidos/musica2.oggbin0 -> 2922073 bytes
-rw-r--r--CUCARACHA/__init__.py2
-rw-r--r--Cria_Bichos_Main.py1046
-rw-r--r--CucaraSims.py187
-rw-r--r--Ficha_Bicho.py147
-rw-r--r--Globals.py110
-rw-r--r--Iconos/audio1.pngbin0 -> 6668 bytes
-rw-r--r--Iconos/audio2.pngbin0 -> 6447 bytes
-rw-r--r--Iconos/libreta.pngbin0 -> 3213 bytes
-rw-r--r--Interfaz.py161
-rw-r--r--Libreta_de_Lectura.py178
-rw-r--r--Main.py594
-rw-r--r--activity/CucaraSims.svg77
-rw-r--r--activity/activity.info7
-rw-r--r--setup.py3
126 files changed, 10179 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..81f8dd0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+*.pyc
+*.pyo
+*.??~
diff --git a/Archivos_y_Directorios.py b/Archivos_y_Directorios.py
new file mode 100644
index 0000000..9d8ac02
--- /dev/null
+++ b/Archivos_y_Directorios.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Archivos_y_Directorios.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import os, sqlite3, urllib, string, time
+
+class Archivos_y_Directorios():
+ def __init__(self, DIRECTORIO_DATOS):
+ self.directorio= DIRECTORIO_DATOS
+ self.set_directorio()
+
+ def set_directorio(self):
+ # Crear Directorio para la base de datos
+ if not os.path.exists(self.directorio):
+ os.mkdir(self.directorio)
+
+ def get_juegos(self):
+ return (self.directorio, os.listdir(self.directorio))
+
+ def CrearBasededatos (self):
+ # Crea la base de datos inicial
+ numero_de_juegos = time.time()
+ nombre = "Cucarasims%s.db" % (numero_de_juegos)
+ nombre_de_base = os.path.join(self.directorio, nombre)
+ try:
+ coneccion = sqlite3.connect(nombre_de_base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("""create table Cucas (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ sexo text, anios text, dias text, horas text, nutricion text, hidratacion text)""")
+ coneccion.commit()
+ basededatos.execute("""create table Juego (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ anios text, dias text, horas text, puntos text)""")
+ coneccion.commit()
+ basededatos.execute("""create table Ootecas (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ dias text, horas text, huevos text)""")
+ coneccion.commit()
+ basededatos.close()
+ coneccion.close()
+ os.chmod(os.path.join(self.directorio, nombre), 0666)
+ return nombre_de_base
+ except Exception, e:
+ return False
+
+ def RE_CrearBasededatos (self, base):
+ # Crea la base de datos inicial
+ nombre_de_base = os.path.join(self.directorio, base)
+ try:
+ coneccion = sqlite3.connect(nombre_de_base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("""create table Cucas (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ sexo text, anios text, dias text, horas text, nutricion text, hidratacion text)""")
+ coneccion.commit()
+ basededatos.execute("""create table Juego (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ anios text, dias text, horas text, puntos text)""")
+ coneccion.commit()
+ basededatos.execute("""create table Ootecas (id INTEGER PRIMARY KEY AUTOINCREMENT,
+ dias text, horas text, huevos text)""")
+ coneccion.commit()
+ basededatos.close()
+ coneccion.close()
+ os.chmod(os.path.join(self.directorio, nombre), 0666)
+ return nombre_de_base
+ except Exception, e:
+ return False
+
+ def guardar(self, base=None, datos=None):
+ #print "GUARDANDO DATOS"
+ datos_de_juego = datos[0] # [anios, dias, horas, puntos]
+ datos_de_cucas = datos[1] # [sexo, anios, dias, horas, hambre, sed]
+ datos_de_ootecas = datos[2] # [dias, horas, huevos]
+ self.borrar_tabla(base)
+ self.RE_CrearBasededatos(base)
+ # Guardando Datos de tiempo de juego en general
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ try:
+ coneccion.text_factory = str #(no funciona en sugar de uruguay)
+ except:
+ pass
+ anios, dias, horas, puntos = datos_de_juego
+ item = [0, anios, dias, horas, puntos]
+ basededatos.execute ("insert into %s values (?,?,?,?,?)" % ("Juego"), item)
+ coneccion.commit()
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Llenar la Tabla Juego"
+
+ # Guardando Datos de Cucas
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ try:
+ coneccion.text_factory = str #(no funciona en sugar de uruguay)
+ except:
+ pass
+ contador = 0
+ for x in range(0, len(datos_de_cucas)):
+ datos_bicho = datos_de_cucas[x] # [sexo, anios, dias, horas, hambre, sed]
+ sexo = datos_bicho[0]
+ anios = datos_bicho[1]
+ dias = datos_bicho[2]
+ horas = datos_bicho[3]
+ hambre = datos_bicho[4]
+ sed = datos_bicho[5]
+ item = [contador, sexo, anios, dias, horas, hambre, sed]
+ basededatos.execute ("insert into %s values (?,?,?,?,?,?,?)" % ("Cucas"), item)
+ coneccion.commit()
+ contador += 1
+ #print "Datos Guardados en Cucas:", item
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Llenar la Tabla Cucas"
+
+ # Guardando Datos de Ootecas
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ try:
+ coneccion.text_factory = str #(no funciona en sugar de uruguay)
+ except:
+ pass
+ contador = 0
+ for x in range(0, len(datos_de_ootecas)):
+ datos_ootecas = datos_de_ootecas[x] # [dias, horas, huevos]
+ dias = datos_ootecas[0]
+ horas = datos_ootecas[1]
+ huevos = datos_ootecas[2]
+ item = [contador, dias, horas, huevos]
+ basededatos.execute ("insert into %s values (?,?,?,?)" % ("Ootecas"), item)
+ coneccion.commit()
+ contador += 1
+ #print "Datos Guardados en Ootecas:", item
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Llenar la Tabla Ootecas"
+
+ #print "DATOS GUARDADOS"
+
+
+ def Leer_Base_de_Datos(self, nombre):
+ base = os.path.join(self.directorio, nombre)
+ datos_juego = None
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("select * from %s" % ("Juego"))
+ for dato in basededatos:
+ datos_juego = dato
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Carga Tabla Juego"
+ #print "Leyendo Base", datos_juego
+
+ cucas = []
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("select * from %s" % ("Cucas"))
+ for item in basededatos:
+ cucas.append(item)
+ #print item
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Carga Tabla Cucas"
+
+ Ootecas = []
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("select * from %s" % ("Ootecas"))
+ for item in basededatos:
+ Ootecas.append(item)
+ #print item
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Carga Tabla Ootecas"
+
+ #print "DATOS:\n", (base, datos_juego, cucas, Ootecas), "\nFIN DATOS:"
+ return (base, datos_juego, cucas, Ootecas)
+
+ #print "Base Leida"
+
+ def borrar_tabla(self, nombre):
+ #print "\n\n BORRRAR:", nombre
+ try:
+ nombre_de_base= os.path.join(self.directorio, nombre)
+ os.remove(nombre_de_base)
+ #print "Borrar: ", nombre_de_base
+ except Exception, e:
+ print "Ha Ocurrido un Error al Intentar Borarr un Juego"
+
+ def verifica(self, base_abrir=None):
+ base = os.path.join(self.directorio, base_abrir)
+ datos_juego = None
+ try:
+ coneccion = sqlite3.connect(base)
+ basededatos = coneccion.cursor()
+ basededatos.execute("select * from %s" % ("Juego"))
+ for dato in basededatos:
+ datos_juego = dato
+ basededatos.close()
+ coneccion.close()
+ except Exception, e:
+ print "Ha Ocurrido un Error al verifica Tabla Juego"
+
+ if not datos_juego:
+ os.remove(base)
+ #print "base eliminada"
+
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]<self.etiqueta_unselect.rect.w+self.base["detalle"]+self.etiqueta_unselect.rect.h:
+ w= self.etiqueta_unselect.rect.w+self.base["detalle"]+self.etiqueta_unselect.rect.h
+ self.cara["tamanio"] = (w, h)
+ if self.cara["tamanio"] and self.cara["tamanio"][1]<self.etiqueta_unselect.rect.h+self.base["detalle"]+self.etiqueta_unselect.rect.h:
+ h= self.etiqueta_unselect.rect.h+self.base["detalle"]+self.etiqueta_unselect.rect.h
+ self.cara["tamanio"] = (w, h)
+ unselect= VG.get_Elipse(self.cara["color"], self.cara["tamanio"])
+ select= VG.get_Elipse(self.base["colorbor"], self.cara["tamanio"])
+
+ # alineación desabilitada por bug
+ self.alineacion = "centro"
+ unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect)
+ select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select)
+ else:
+ w, h= (0,0)
+ # toma tamaño de etiqueta como referencia
+ if not self.cara["tamanio"]:
+ w= self.etiqueta_unselect.rect[2]+self.base["detalle"]
+ h= self.etiqueta_unselect.rect[3]+self.base["detalle"]
+ self.cara["tamanio"] = (w, h)
+ # la cara nunca puede ser menor que la etiqueta pero si mayor
+ if self.cara["tamanio"] and self.cara["tamanio"][0]<self.etiqueta_unselect.rect[2]+self.base["detalle"]:
+ w= self.etiqueta_unselect.rect[2]+self.base["detalle"]
+ self.cara["tamanio"] = (w, h)
+ if self.cara["tamanio"] and self.cara["tamanio"][1]<self.etiqueta_unselect.rect[3]+self.base["detalle"]:
+ h= self.etiqueta_unselect.rect[3]+self.base["detalle"]
+ self.cara["tamanio"] = (w, h)
+ unselect= VG.get_Rectangulo(self.cara["color"], self.cara["tamanio"])
+ select= VG.get_Rectangulo(self.base["colorbor"], self.cara["tamanio"])
+
+ if self.alineacion == "centro":
+ unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect)
+ select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select)
+ elif self.alineacion == "izquierda":
+ unselect= VG.pegar_imagenes_alineado_izquierda(self.etiqueta_unselect.image, unselect)
+ select= VG.pegar_imagenes_alineado_izquierda(self.etiqueta_select.image, select)
+ elif self.alineacion == "derecha":
+ unselect= VG.pegar_imagenes_alineado_derecha(self.etiqueta_unselect.image, unselect)
+ select= VG.pegar_imagenes_alineado_derecha(self.etiqueta_select.image, select)
+ else:
+ self.alineacion = "centro"
+ unselect= VG.pegar_imagenes_centradas(self.etiqueta_unselect.image, unselect)
+ select= VG.pegar_imagenes_centradas(self.etiqueta_select.image, select)
+
+ if self.borde_label["grosor"] > 1 and self.borde_label["grosor"] != None:
+ if not self.borde_label["color"]: self.borde_label["color"]= VG.get_negro()
+ if self.tipo == "elipse":
+ # desabilitado por bug
+ #unselect= VG.get_my_surface_whit_elipse_border(unselect, self.borde_label["color"], self.borde_label["grosor"])
+ #select= VG.get_my_surface_whit_elipse_border(select, self.borde_label["color"], self.borde_label["grosor"])
+ pass
+ else:
+ unselect= VG.get_my_surface_whit_border(unselect, self.borde_label["color"], self.borde_label["grosor"])
+ select= VG.get_my_surface_whit_border(select, self.borde_label["color"], self.borde_label["grosor"])
+ return unselect, select
+
+ def construye_boton(self):
+ ''' Construye las imagenes finales del botón. '''
+ unselect= None
+ select= None
+ if self.tipo == "elipse":
+ x= self.base["grosorbor"] + int(self.base["espesor"]/3)
+ ancho= x + self.cara["tamanio"][0] + self.base["espesor"] + self.base["grosorbor"]
+ y= self.base["grosorbor"] + int(self.base["espesor"]/3)
+ alto= y + self.cara["tamanio"][1] + self.base["espesor"] + self.base["grosorbor"]
+ self.base["tamanio"]= (ancho, alto)
+ unselect= VG.get_Elipse(self.base["colorbas"], self.base["tamanio"])
+ unselect= VG.get_my_surface_whit_elipse_border(unselect, self.base["colorbor"], self.base["grosorbor"])
+ select= VG.get_Elipse(self.base["colorbas"], self.base["tamanio"])
+ select= VG.get_my_surface_whit_elipse_border(select, self.base["colorbor"], self.base["grosorbor"])
+ else:
+ x= self.base["grosorbor"] + int(self.base["espesor"]/3)
+ ancho= x + self.cara["tamanio"][0] + self.base["espesor"] + self.base["grosorbor"]
+ y= self.base["grosorbor"] + int(self.base["espesor"]/3)
+ alto= y + self.cara["tamanio"][1] + self.base["espesor"] + self.base["grosorbor"]
+ self.base["tamanio"]= (ancho, alto)
+ unselect= VG.get_Rectangulo(self.base["colorbas"], self.base["tamanio"])
+ unselect= VG.get_my_surface_whit_border(unselect, self.base["colorbor"], self.base["grosorbor"])
+ select= VG.get_Rectangulo(self.base["colorbas"], self.base["tamanio"])
+ select= VG.get_my_surface_whit_border(select, self.base["colorbor"], self.base["grosorbor"])
+
+ unselect.blit(self.imagen_cara_unselect, (x, y))
+ select.blit(self.imagen_cara_select, (x, y))
+ return unselect, select
+ # -------------------- FIN DE METODOS DE CONSTRUCCION -------------------- #
+
+ # -------------------- INICIO DE METODOS INTERNOS AUTOMÁTICOS -------------------- #
+ def play_select(self):
+ # reproduce un sonido cuando pasas el mouse sobre el botón
+ if self.sonido_select:
+ self.sonido_select.play()
+
+ def update(self):
+ # responde a los eventos del mouse sobre el sprite
+ '''
+ posicion = pygame.mouse.get_pos()
+ # Selecciona el botón cuando el mouse pasa encima de él
+ if self.rect.collidepoint(posicion):
+ if self.select == False:
+ self.play_select()
+ self.image = self.final_select.copy()
+ self.select = True
+
+ if pygame.event.get(pygame.MOUSEBUTTONDOWN):
+ if self.callback:
+ return self.callback(self) # modificación 29 de mayo el boton se pasa a si mismo.
+ else:
+ if self.select == True:
+ self.image = self.final_unselect.copy()
+ self.select = False'''
+
+ ''' Reimplementación para Compatibilidad en Plug de gtk y mejora en rendimiento:
+ Los eventos se capturan por su tipo, se manejan y si es necesario se republican para habilitar la captura
+ de los mismos por parte de otros controles.'''
+ eventos_republicar= []
+ eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN)
+ for event in eventos:
+ posicion = event.pos
+ if self.rect.collidepoint(posicion):
+ # Si el mouse está presionado sobre el botón.
+ if self.callback:
+ # y si además hay callback para esta acción.
+ pygame.event.clear()
+ return self.callback(self)
+ else:
+ # Si el mouse no está presionado sobre el botón.
+ if not event in eventos_republicar: eventos_republicar.append(event)
+
+ eventos= pygame.event.get(pygame.MOUSEMOTION)
+ for event in eventos:
+ posicion = event.pos
+ if self.rect.collidepoint(posicion):
+ # Si el mouse está sobre el botón.
+ if self.select == False:
+ self.play_select()
+ self.image = self.final_select
+ self.select = True
+ else:
+ # Si el mouse no está sobre el botón.
+ if self.select == True:
+ self.image = self.final_unselect
+ self.select = False
+ if not event in eventos_republicar: eventos_republicar.append(event)
+
+ for event in eventos_republicar:
+ # Se republican todos los eventos que este control no debe manejar.
+ pygame.event.post(event)
+
+# ----- FIN DE CLASE JAMButton - INICIO DE DEBUG Y EJEMPLO DE LA CLASE -----
+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"
+
diff --git a/Bicho.py b/Bicho.py
new file mode 100644
index 0000000..ffd7f08
--- /dev/null
+++ b/Bicho.py
@@ -0,0 +1,359 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Bicho.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, gc, random
+from pygame.locals import *
+
+gc.enable()
+
+from math import sin, cos, radians
+import Globals as VG
+
+INDICE_ROTACION = 25
+
+class Bicho(pygame.sprite.Sprite):
+ def __init__(self, juego_main):
+ pygame.sprite.Sprite.__init__(self)
+ self.juego= juego_main
+ self.alimento_en_escenario= self.juego.alimento
+ self.agua_en_escenario= self.juego.agua
+
+ self.velocidad = 8
+
+ self.anios = 0
+ self.dias = 0
+ self.horas = 0
+
+ self.hambre = 0
+ self.sed = 0
+
+ self.sonido_bicho = self.juego.sonido_bicho
+ self.area_visible = self.juego.area_visible
+
+ random.seed()
+ self.tipo = random.choice(self.juego.imagenes_bicho)
+ self.imagen_original = self.get_imagen_original()
+ if self.juego.imagenes_bicho.index(self.tipo) == 2 or self.juego.imagenes_bicho.index(self.tipo) == 3:
+ self.sexo = "F"
+ else:
+ self.sexo = "M"
+
+ self.image = self.imagen_original.copy()
+ self.rect = self.image.get_rect()
+
+ acciones = ["camina", "gira", "quieto"]
+ self.accion = random.choice(acciones)
+
+ self.sent = 0
+ self.angulo = 0
+
+ self.contador = 0
+
+ self.escalas_mudas = VG.ESCALASMUDAS
+ self.dias_mudas = VG.DIASMUDAS
+ self.control_mudas = self.dias_mudas[0]
+
+ self.x, self.y = (0,0)
+ self.dx = 0
+ self.dy = 0
+ self.posicionar_al_azar()
+
+ self.dias_repro = VG.DIASREPRO
+ self.control_repro = self.dias_repro[0]
+
+ # Tamaños
+ def get_imagen_original(self):
+ return pygame.transform.scale(self.tipo, (60,50))
+
+ def set_muda(self, escala=(63,50)):
+ # cuando crece, muda el exoesqueleto
+ self.imagen_original = pygame.transform.scale(self.tipo, escala)
+ self.image = pygame.transform.rotate(self.imagen_original, -self.angulo)
+ x,y = self.rect.x, self.rect.y
+ self.rect = self.image.get_rect()
+ self.rect.x, self.rect.y = x, y
+ self.juego.event_muda(posicion=(self.rect.x, self.rect.y), tamanio=escala)
+
+ def posicionar_al_azar(self):
+ # elige una posicion inicial al azar para el bicho
+ lista_de_rectangulos = []
+ for bicho in self.juego.Bichos.sprites():
+ # los rectangulos de los otros bichos
+ rectangulo = (bicho.rect.x, bicho.rect.y, bicho.rect.w, bicho.rect.h)
+ lista_de_rectangulos.append(rectangulo)
+
+ random.seed()
+ x = random.randrange(self.area_visible[0]+10, self.area_visible[0]+self.area_visible[2]-10, 1)
+ y = random.randrange(self.area_visible[1]+10, self.area_visible[1]+self.area_visible[3]-10, 1)
+ self.x, self.y = (x,y)
+ self.dx = 0
+ self.dy = 0
+ self.actualizar_posicion()
+
+ while self.rect.collidelist(lista_de_rectangulos) != -1:
+ x = random.randrange(self.area_visible[0]+10, self.area_visible[0]+self.area_visible[2]-10, 1)
+ y = random.randrange(self.area_visible[1]+10, self.area_visible[1]+self.area_visible[3]-10, 1)
+ self.x, self.y = (x,y)
+ self.dx = 0
+ self.dy = 0
+ self.actualizar_posicion()
+
+ def play_sonido_bicho(self):
+ self.sonido_bicho.play()
+
+ def set_tiempo_de_vida(self):
+ self.horas += 1
+ if self.horas == 24:
+ self.dias += 1
+ self.horas = 0
+
+ if self.dias == 365:
+ self.anios += 1
+ self.dias = 0
+
+ def update(self):
+ # Actualiza el sprite
+ # determinar condiciones de vida
+ if self.hambre <= VG.LIMITEHAMBRE or self.sed <= VG.LIMITESED or self.dias >= VG.LIMITEVIDA:
+ comportamiento = "muere"
+ else:
+ comportamiento = "vive"
+
+ # Si está viva
+ if comportamiento == "vive":
+ # Mudas de exoesqueleto
+ if self.dias == self.control_mudas and self.horas == 0:
+
+ indice = self.dias_mudas.index(self.dias)
+ self.set_muda(escala=self.escalas_mudas[indice])
+ self.velocidad += int(self.velocidad/3)
+
+ if indice+1 < len(self.dias_mudas):
+ self.control_mudas = self.dias_mudas[indice+1]
+ else:
+ self.control_mudas = self.dias_mudas[0]
+
+ # Reproducción
+ if self.dias == self.control_repro and self.horas == 0 and self.sexo == "F":
+ indice = self.dias_repro.index(self.dias)
+
+ if indice+1 < len(self.dias_repro):
+ self.control_repro = self.dias_repro[indice+1]
+ else:
+ self.control_repro = self.dias_repro[0]
+
+ if self.juego.machos:
+ self.juego.event_reproduccion(posicion=(self.rect.centerx, self.rect.centery))
+
+ comportamiento = "normal"
+
+ elif comportamiento == "muere":
+ # se muere
+ self.juego.event_morir(posicion=(self.rect.centerx, self.rect.centery), dias=self.dias)
+ self.kill()
+ return
+
+ if not self.agua_en_escenario.sprites() or self.sed >= 100:
+ # Si no hay alimento en el escenario o el bicho no tiene sed
+ comportamiento = "normal"
+ elif self.agua_en_escenario.sprites() and self.sed < 100:
+ # si hay alimento y tiene hambre
+ comportamiento = "buscar agua"
+
+ if comportamiento == "normal":
+ if not self.alimento_en_escenario.sprites() or self.hambre >= 100:
+ # Si no hay alimento en el escenario o el bicho no tiene hambre
+ comportamiento = "normal"
+ elif self.alimento_en_escenario.sprites() and self.hambre < 100:
+ # si hay alimento y tiene hambre
+ comportamiento = "buscar comida"
+
+ self.comportamiento(comportamiento)
+
+ def comportamiento(self, comportamiento):
+ # decide el tipo de comportamiento según necesidades
+ if comportamiento == "normal":
+ if self.contador == 30:
+ # cada 30 pasadas, cambia acción
+ acciones = ["camina", "gira", "quieto"]
+ random.seed()
+ self.accion = random.choice(acciones)
+ self.contador = 0
+ self.contador += 1
+ self.decide()
+ elif comportamiento == "buscar comida":
+ self.alimentarse()
+ elif comportamiento == "buscar agua":
+ self.beber()
+ else:
+ print "comportamiento sin tratar: ", comportamiento
+
+ def beber(self):
+ # Busca el alimento, cuando lo encuentra se alimenta
+ agua = self.agua_en_escenario.sprites()[0]
+
+ if self.rect.colliderect(agua.rect):
+ # si ya llegamos al agua no nos movemos
+ self.accion = "quieto"
+
+ if self.contador >= 30:
+ # cada treinta pasadas bebe
+ self.sed += VG.RINDEAGUA
+ agua.cantidad -= VG.CONSUMOAGUA
+ self.contador = 0
+ if self.sed >= 100: self.sed = 150
+ if agua.cantidad <= 0:
+ agua.kill()
+ self.agua_en_escenario.empty()
+ self.contador += 1
+ return
+
+ else:
+ # Si no hemos llegado al agua
+ posicion_agua = agua.rect.center
+
+ # calcular la distancia al alimento
+ distancia_x = posicion_agua[0] - self.rect.x
+ distancia_y = posicion_agua[1] - self.rect.y
+
+ self.dx, self.dy = self.get_vector(self.angulo)
+
+ # calcular distancia si me muevo en el sentido actual
+ futura_posicion_x = self.rect.x + self.dx
+ futura_posicion_y = self.rect.y + self.dy
+
+ # Verificar si al moverme me acerco o me alejo del alimento
+ if ((futura_posicion_x - self.rect.x) <= distancia_x and (futura_posicion_y - self.rect.y) <= distancia_y):
+ # Si me acerco, camino
+ self.accion = "camina"
+ self.decide()
+ else:
+ # si no me acerco, giro
+ self.accion = "gira"
+ self.decide()
+
+ def alimentarse(self):
+ # Busca el alimento, cuando lo encuentra se alimenta
+ alimento = self.alimento_en_escenario.sprites()[0]
+
+ if self.rect.colliderect(alimento.rect):
+ # si ya llegamos al alimento no nos movemos
+ self.accion = "quieto"
+
+ if self.contador >= 30:
+ # cada treinta pasadas come
+ self.hambre += VG.RINDEALIMENTO
+ alimento.cantidad -= VG.CONSUMOALIMENTO
+ self.contador = 0
+ if self.hambre >= 100: self.hambre = 150
+ if alimento.cantidad <= 0:
+ # el que come de último limpia :P
+ alimento.kill()
+ self.alimento_en_escenario.empty()
+ self.contador += 1
+ return
+
+ else:
+ # Si no hemos llegado al alimento
+ posicion_alimento = alimento.rect.center
+
+ # calcular la distancia al alimento
+ distancia_x = posicion_alimento[0] - self.rect.x
+ distancia_y = posicion_alimento[1] - self.rect.y
+
+ self.dx, self.dy = self.get_vector(self.angulo)
+
+ # calcular distancia si me muevo en el sentido actual
+ futura_posicion_x = self.rect.x + self.dx
+ futura_posicion_y = self.rect.y + self.dy
+
+ # Verificar si al moverme me acerco o me alejo del alimento
+ if ((futura_posicion_x - self.rect.x) <= distancia_x and (futura_posicion_y - self.rect.y) <= distancia_y):
+ # Si me acerco, camino
+ self.accion = "camina"
+ self.decide()
+ else:
+ # si no me acerco, giro
+ self.accion = "gira"
+ self.decide()
+
+ def decide(self):
+ # gira, camina o se queda quieto
+ if self.accion == "gira":
+ self.gira()
+ self.accion = "camina"
+
+ if self.accion == "camina":
+ self.dx, self.dy = self.get_vector(self.angulo)
+ self.actualizar_posicion()
+
+ if self.accion == "quieto":
+ pass
+
+ def gira(self, sent=0):
+ # la cuca gira
+ random.seed()
+ if sent == 0: self.sent = random.randrange(1, 3, 1)
+
+ if self.sent == 1:
+ # hacia la izquierda
+ self.angulo -= int(0.7 * INDICE_ROTACION)
+ elif self.sent == 2:
+ # hacia la derecha
+ self.angulo += int(0.7 * INDICE_ROTACION)
+
+ self.image = pygame.transform.rotate(self.imagen_original, -self.angulo)
+
+ def actualizar_posicion(self):
+ # La cuca se mueve
+ x = self.x + self.dx
+ y = self.y + self.dy
+ posicion = (x,y)
+ if self.area_visible.collidepoint(posicion):
+ # Si no me salgo del area permitida
+ if not self.verificar_colision_en_grupo(posicion):
+ # Si no caminaré sobre otra cucaracha
+ self.x += self.dx
+ self.y += self.dy
+ self.rect.centerx = int(self.x)
+ self.rect.centery = int(self.y)
+ else:
+ self.gira(sent=self.sent)
+ self.accion = "quieto"
+ else:
+ self.gira(sent=self.sent)
+
+ def verificar_colision_en_grupo(self, posicion):
+ # evita que caminen unas sobre otras
+ grupo = self.groups()
+ for group in grupo:
+ for cuca in group.sprites():
+ if cuca != self:
+ if cuca.rect.collidepoint(posicion):
+ return True
+ return False
+
+ def get_vector(self, angulo):
+ # Recibe un ángulo que da orientación. Devuelve el incremento de puntos x,y
+ x = int(cos(radians(angulo)) * self.velocidad)
+ y = int(sin(radians(angulo)) * self.velocidad)
+ return x,y
+
diff --git a/CUCARACHA/Imagenes/agua.png b/CUCARACHA/Imagenes/agua.png
new file mode 100644
index 0000000..750c9ec
--- /dev/null
+++ b/CUCARACHA/Imagenes/agua.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/ciclo_vital1.png b/CUCARACHA/Imagenes/ciclo_vital1.png
new file mode 100644
index 0000000..9edcd76
--- /dev/null
+++ b/CUCARACHA/Imagenes/ciclo_vital1.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/ciclo_vital2.png b/CUCARACHA/Imagenes/ciclo_vital2.png
new file mode 100644
index 0000000..d54cd9b
--- /dev/null
+++ b/CUCARACHA/Imagenes/ciclo_vital2.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/cucaracha1.png b/CUCARACHA/Imagenes/cucaracha1.png
new file mode 100644
index 0000000..d38a032
--- /dev/null
+++ b/CUCARACHA/Imagenes/cucaracha1.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/cucaracha2.png b/CUCARACHA/Imagenes/cucaracha2.png
new file mode 100644
index 0000000..5d018eb
--- /dev/null
+++ b/CUCARACHA/Imagenes/cucaracha2.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/cucaracha3.png b/CUCARACHA/Imagenes/cucaracha3.png
new file mode 100644
index 0000000..ab51756
--- /dev/null
+++ b/CUCARACHA/Imagenes/cucaracha3.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/cucaracha4.png b/CUCARACHA/Imagenes/cucaracha4.png
new file mode 100644
index 0000000..14319d5
--- /dev/null
+++ b/CUCARACHA/Imagenes/cucaracha4.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/cucarasimsico.png b/CUCARACHA/Imagenes/cucarasimsico.png
new file mode 100644
index 0000000..33fc206
--- /dev/null
+++ b/CUCARACHA/Imagenes/cucarasimsico.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/fondo.png b/CUCARACHA/Imagenes/fondo.png
new file mode 100644
index 0000000..8ffb9c3
--- /dev/null
+++ b/CUCARACHA/Imagenes/fondo.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/fondo4.png b/CUCARACHA/Imagenes/fondo4.png
new file mode 100644
index 0000000..5c5d0ff
--- /dev/null
+++ b/CUCARACHA/Imagenes/fondo4.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/huevos.png b/CUCARACHA/Imagenes/huevos.png
new file mode 100644
index 0000000..9943ff4
--- /dev/null
+++ b/CUCARACHA/Imagenes/huevos.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/jarra.png b/CUCARACHA/Imagenes/jarra.png
new file mode 100644
index 0000000..e2866f7
--- /dev/null
+++ b/CUCARACHA/Imagenes/jarra.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/muda1.png b/CUCARACHA/Imagenes/muda1.png
new file mode 100644
index 0000000..f1d38ac
--- /dev/null
+++ b/CUCARACHA/Imagenes/muda1.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/muda2.png b/CUCARACHA/Imagenes/muda2.png
new file mode 100644
index 0000000..b1f1b0a
--- /dev/null
+++ b/CUCARACHA/Imagenes/muda2.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/muerta.png b/CUCARACHA/Imagenes/muerta.png
new file mode 100644
index 0000000..8bec8f9
--- /dev/null
+++ b/CUCARACHA/Imagenes/muerta.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/muerte1.png b/CUCARACHA/Imagenes/muerte1.png
new file mode 100644
index 0000000..65316c7
--- /dev/null
+++ b/CUCARACHA/Imagenes/muerte1.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/pan.png b/CUCARACHA/Imagenes/pan.png
new file mode 100644
index 0000000..f6e5c9e
--- /dev/null
+++ b/CUCARACHA/Imagenes/pan.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/portada.png b/CUCARACHA/Imagenes/portada.png
new file mode 100644
index 0000000..f206b56
--- /dev/null
+++ b/CUCARACHA/Imagenes/portada.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/reproduccion1.png b/CUCARACHA/Imagenes/reproduccion1.png
new file mode 100644
index 0000000..7dbf468
--- /dev/null
+++ b/CUCARACHA/Imagenes/reproduccion1.png
Binary files differ
diff --git a/CUCARACHA/Imagenes/reproduccion2.png b/CUCARACHA/Imagenes/reproduccion2.png
new file mode 100644
index 0000000..d3cf501
--- /dev/null
+++ b/CUCARACHA/Imagenes/reproduccion2.png
Binary files differ
diff --git a/CUCARACHA/Lectura.py b/CUCARACHA/Lectura.py
new file mode 100644
index 0000000..0623f74
--- /dev/null
+++ b/CUCARACHA/Lectura.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Lectura.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+# ----------------- Leccion sobre muda de exoesqueleto ----------------- #
+muda1 = ["MUDA DE EXOESQUELETO:",
+ " ",
+ "Una de tus cucarachas ha crecido y ha",
+ "realizado la muda de su exoesqueleto.",
+ " ",
+ "La cucaracha es un insecto y los",
+ "insectos son artrópodos.",
+ "Por eso, la cucaracha como todo",
+ "artrópodo, tiene esqueleto externo.",
+ " ",
+ "No son como nosotros que lo tenemos dentro",
+ "del cuerpo. Ellas lo tienen fuera.",
+ "Lo tienen donde nosotros tenemos",
+ "la piel. Por eso se llama exoesqueleto.",
+ " ",
+ "Esto les brinda protección, pero también",
+ "es un problema cuando crecen porque sus",
+ "esqueletos no lo hacen, entonces deben",
+ "cambiarlo por otro más grande.",
+ " ",
+ "Este proceso, de quitarse el esqueleto",
+ "y volver a crear uno más grande, se",
+ "llama MUDA.",
+ " ",
+ "Las cucarachas mudan 4 veces su",
+ "exoesqueleto para llegar a su tamaño",
+ "definitivo y convertirse en adultos."]
+
+MUDA = [muda1]
+
+# ----------------- Leccion sobre reproducción ----------------- #
+repro1 = [" ",
+ "REPRODUCCIÓN:",
+ " ",
+ "Una de tus Cucarachas se ha reproducido",
+ "depositando una ooteca llena de huevos.",
+ " ",
+ "Hay Cucarachas macho y cucarachas hembra.",
+ " ",
+ "Al reproducirse, la hembra deposita un",
+ "estuche llamado ooteca que contiene",
+ "hasta 40 huevos.",
+ " ",
+ "La hembra transporta la ooteca prendida y",
+ "escondida en el abdomen hasta su eclosion.",
+ " ",
+ "La ooteca tiene un tiempo de incubacion de",
+ "un mes, luego del cual nacen las ninfas.",
+ " ",
+ "El ciclo de vida de la cucarcha se compone",
+ "de tres fases: Huevo, Ninfa y Adulto.",
+ " ",
+ "Completa su ciclo de 7 semanas a 6 meses."]
+
+REPRODUCCION = [repro1]
+
+# ----------------- Leccion sobre el ciclo vital ----------------- #
+ciclo1 = ["CICLO VITAL:",
+ " ",
+ "Han nacido nuevas cucarachas en el",
+ "habitat.",
+ " ",
+ "El ciclo vital de estos animales, se",
+ "compone de tres fases: Huevo, Ninfa y Adulto.",
+ " ",
+ "Durante su vida, de aproximadamente un año",
+ "de duración, este animal cambiará varias",
+ "veces su exoesqueleto para crecer, hasta",
+ "llegar a adulto con un tamaño de tres a",
+ "veinticinco centímetros.",
+ " ",
+ "Se reproducirá varias veces poniendo estuches",
+ "llamados ootecas, que pueden contener hasta",
+ "cuarenta huevos y finalmente morirá,",
+ "completando así su ciclo vital.",
+ " ",
+ "En este Juego debes proveer de agua y",
+ "alimento a tus cucarachas para que puedan",
+ "crecer, reproducirse y así completar su",
+ "ciclo vital.",
+ " ",
+ "Cuanto tengas muchas, algunas se irán hacia",
+ "otros hábitats y serán contabilizadas",
+ "como puntaje para ti por haberlas ayudado a",
+ "completar su ciclo exitosamente."]
+
+LECTURACICLOVITAL = [ciclo1]
+
+# ----------------- Leccion sobre la muerte ----------------- #
+muerte1 = ["MUERTE:",
+ " ",
+ "Una de tus cucarachas ha muerto.",
+ " ",
+ "Nunca toques una cucaracha muerta.",
+ "Es muy probable que haya muerto envenenada",
+ "ya que es una plaga muy peligrosa que",
+ "transmite enfermedades capaces de matar",
+ "a las personas.",
+ " ",
+ "Por eso mismo, tampoco toques nunca una",
+ "cucaracha que esté viva.",
+ " ",
+ "Si hay cucarachas en tu hogar es necesario",
+ "eliminarlas antes de que contagien alguna",
+ "enfermedad peligrosa a alguno de los",
+ "miembros de tu familia.",
+ " ",
+ "Siempre mueren boca arriba debido a que",
+ "el endurecimiento de los músculos de",
+ "sus patas al morir la hacen volcar.",
+ " ",
+ "Vive aproximadamente un año, pero como",
+ "todo ser vivo puede ser afectado por",
+ "enfermedades que le causen la muerte y",
+ "necesita agua y alimento para mantenerse",
+ "con vida."]
+
+LECTURAMUERTE = [muerte1]
+
+# ----------------- Leccion sobre la plaga ----------------- #
+Plaga1 = [" ",
+ "PLAGA:",
+ " ",
+ "Tu habitat está repleto de cucarachas.",
+ "Muchas migrarán y colonizarán otros hogares.",
+ "Tu habitat funciona muy bien y obtienes",
+ "puntos por la migración de tus cucarachas.",
+ " ",
+ "Es extremadamente importante el",
+ "control de las cucarachas en tu hogar",
+ "debido a que estos animales transmiten",
+ "varias enfermedades como:",
+ " ",
+ "diarreas, tuberculosis, amibiasis,",
+ "disentería, gastroenteritis, fiebre",
+ "tifoidea, peste, gangrenas, lepra, cólera,",
+ "meningitis meningococosica y tétanos.",
+ " ",
+ "Además son huéspedes intermediarios de",
+ "parásitos que producen alergias y",
+ "cuadros de asma causados por excremento y",
+ "restos de sus cuerpos.",
+ " ",
+ "Si en tu casa hay cucarachas, deben ser",
+ "eliminadas cuanto antes para mantener",
+ "sana a tu familia."]
+
+LECTURAPLAGA = [Plaga1]
+
+# ----------------- Fin del Juego ----------------- #
+findejuego = ["EXTINCIÓN:",
+ " ",
+ "El Juego ha terminado.",
+ " ",
+ "En tu habitat ya no hay cucarachas machos",
+ "o no hay cucarachas hembras por lo cual",
+ "no podrán reproducirse.",
+ " ",
+ "Tampoco hay ootecas en el habitat así que",
+ "no habrán más nacimientos.",
+ " ",
+ "Has perdido ya que las cucarachas se",
+ "extinguirán de tu hábitat."]
+
+LECTURAENDGAME = [findejuego]
+
+# ----------------- Lecturas Extras ----------------- #
+extraa = ["Hábitat:",
+ " ",
+ "Para vivir, buscan grietas y hendiduras",
+ "que les proveen de humedad y temperatura",
+ "ambiental adecuada.",
+ " ",
+ "Durante el día es común encontrarlas",
+ "agrupadas en escondites oscuros ya que",
+ "no les gusta la luz.",
+ " ",
+ "Durante la noche se alimentan en grupo.",
+ " ",
+ "Ciclo de vida:",
+ " ",
+ "Presentan un desarrollo gradual que consta",
+ "de tres estados: huevo, ninfa y adulto.",
+ " ",
+ "En ninfa, el individuo se encuentra en",
+ "su estado juvenil produciendo diversas",
+ "mudas de su exoesqueleto hasta alcanzar",
+ "el estado adulto.",
+ " ",
+ "Reproducción:",
+ " ",
+ "Hay individuos macho y hay individuos hembra.",
+ "La hembra realiza la puesta de huevos",
+ "externamente en una ooteca, que es una",
+ "especie de estuche donde se encuentran sus",
+ "huevos."]
+
+extrab = [" ", " ", " ", " ",
+ "La ooteca de algunas cucarachas pueden",
+ "contener hasta 30 o 40 huevos.",
+ " ",
+ "La hembra puede producir hasta",
+ "ocho ootecas a lo largo de su ciclo",
+ "reproductor.",
+ " ",
+ "Cada hembra puede, en condiciones favorables,",
+ "producir entre 300 y 400 descendientes.",
+ " ",
+ "Las cucarachas pueden llegar a vivir un año.",
+ " ",
+ "Alimentación:",
+ " ",
+ "Son omnívoras, y en el ámbito doméstico",
+ "se alimentan de cualquier cosa que sea",
+ "orgánica, (pizcas de comida, grasa, basura,",
+ "telas de lana, algodón y cartón).",
+ "Pueden comer muchos otros materiales.",
+ " ",
+ "Son muy peligrosas para nuestra salud ya que",
+ "contagian diversas enfermedades muy",
+ "peligrosas para nosotros, tan solo por",
+ "contacto con nuestros alimentos o",
+ "utensilios de cocina."]
+
+LECTURASEXTRAS = [extraa, extrab]
diff --git a/CUCARACHA/Muda/muda_001805.png b/CUCARACHA/Muda/muda_001805.png
new file mode 100644
index 0000000..4c193a1
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001805.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001815.png b/CUCARACHA/Muda/muda_001815.png
new file mode 100644
index 0000000..88d15ba
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001815.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001825.png b/CUCARACHA/Muda/muda_001825.png
new file mode 100644
index 0000000..a21d7d0
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001825.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001835.png b/CUCARACHA/Muda/muda_001835.png
new file mode 100644
index 0000000..b3c7f7e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001835.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001845.png b/CUCARACHA/Muda/muda_001845.png
new file mode 100644
index 0000000..4413db8
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001845.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001855.png b/CUCARACHA/Muda/muda_001855.png
new file mode 100644
index 0000000..5a4c273
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001855.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001865.png b/CUCARACHA/Muda/muda_001865.png
new file mode 100644
index 0000000..7c032fd
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001865.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001875.png b/CUCARACHA/Muda/muda_001875.png
new file mode 100644
index 0000000..30de3b5
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001875.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001885.png b/CUCARACHA/Muda/muda_001885.png
new file mode 100644
index 0000000..5250590
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001885.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001895.png b/CUCARACHA/Muda/muda_001895.png
new file mode 100644
index 0000000..74fb42c
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001895.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001905.png b/CUCARACHA/Muda/muda_001905.png
new file mode 100644
index 0000000..02f6634
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001905.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001915.png b/CUCARACHA/Muda/muda_001915.png
new file mode 100644
index 0000000..5363f3a
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001915.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001925.png b/CUCARACHA/Muda/muda_001925.png
new file mode 100644
index 0000000..16bde68
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001925.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001935.png b/CUCARACHA/Muda/muda_001935.png
new file mode 100644
index 0000000..4702699
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001935.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001945.png b/CUCARACHA/Muda/muda_001945.png
new file mode 100644
index 0000000..3e1a6c4
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001945.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001955.png b/CUCARACHA/Muda/muda_001955.png
new file mode 100644
index 0000000..9602cd3
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001955.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001965.png b/CUCARACHA/Muda/muda_001965.png
new file mode 100644
index 0000000..94b710f
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001965.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001975.png b/CUCARACHA/Muda/muda_001975.png
new file mode 100644
index 0000000..bd5400f
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001975.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001985.png b/CUCARACHA/Muda/muda_001985.png
new file mode 100644
index 0000000..f7dec1e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001985.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_001995.png b/CUCARACHA/Muda/muda_001995.png
new file mode 100644
index 0000000..9ed3da8
--- /dev/null
+++ b/CUCARACHA/Muda/muda_001995.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002005.png b/CUCARACHA/Muda/muda_002005.png
new file mode 100644
index 0000000..5ee27ff
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002005.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002015.png b/CUCARACHA/Muda/muda_002015.png
new file mode 100644
index 0000000..fc5178e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002015.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002025.png b/CUCARACHA/Muda/muda_002025.png
new file mode 100644
index 0000000..ba99b10
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002025.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002035.png b/CUCARACHA/Muda/muda_002035.png
new file mode 100644
index 0000000..a74adcb
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002035.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002045.png b/CUCARACHA/Muda/muda_002045.png
new file mode 100644
index 0000000..97261f8
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002045.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002055.png b/CUCARACHA/Muda/muda_002055.png
new file mode 100644
index 0000000..e1c1673
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002055.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002065.png b/CUCARACHA/Muda/muda_002065.png
new file mode 100644
index 0000000..c351d6c
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002065.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002075.png b/CUCARACHA/Muda/muda_002075.png
new file mode 100644
index 0000000..28eba73
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002075.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002085.png b/CUCARACHA/Muda/muda_002085.png
new file mode 100644
index 0000000..b228e01
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002085.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002095.png b/CUCARACHA/Muda/muda_002095.png
new file mode 100644
index 0000000..87a0e8e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002095.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002105.png b/CUCARACHA/Muda/muda_002105.png
new file mode 100644
index 0000000..84026d1
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002105.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002115.png b/CUCARACHA/Muda/muda_002115.png
new file mode 100644
index 0000000..30197ba
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002115.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002125.png b/CUCARACHA/Muda/muda_002125.png
new file mode 100644
index 0000000..f5ad6a6
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002125.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002135.png b/CUCARACHA/Muda/muda_002135.png
new file mode 100644
index 0000000..202b46c
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002135.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002145.png b/CUCARACHA/Muda/muda_002145.png
new file mode 100644
index 0000000..6b14a2b
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002145.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002155.png b/CUCARACHA/Muda/muda_002155.png
new file mode 100644
index 0000000..db7b634
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002155.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002165.png b/CUCARACHA/Muda/muda_002165.png
new file mode 100644
index 0000000..2f17bb0
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002165.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002175.png b/CUCARACHA/Muda/muda_002175.png
new file mode 100644
index 0000000..c5db51e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002175.png
Binary files differ
diff --git a/CUCARACHA/Muda/muda_002185.png b/CUCARACHA/Muda/muda_002185.png
new file mode 100644
index 0000000..1bf491e
--- /dev/null
+++ b/CUCARACHA/Muda/muda_002185.png
Binary files differ
diff --git a/CUCARACHA/Sonidos/cucaracha.ogg b/CUCARACHA/Sonidos/cucaracha.ogg
new file mode 100644
index 0000000..a8f4013
--- /dev/null
+++ b/CUCARACHA/Sonidos/cucaracha.ogg
Binary files differ
diff --git a/CUCARACHA/Sonidos/musica.ogg b/CUCARACHA/Sonidos/musica.ogg
new file mode 100644
index 0000000..7fa4db7
--- /dev/null
+++ b/CUCARACHA/Sonidos/musica.ogg
Binary files differ
diff --git a/CUCARACHA/Sonidos/musica2.ogg b/CUCARACHA/Sonidos/musica2.ogg
new file mode 100644
index 0000000..e340921
--- /dev/null
+++ b/CUCARACHA/Sonidos/musica2.ogg
Binary files differ
diff --git a/CUCARACHA/__init__.py b/CUCARACHA/__init__.py
new file mode 100644
index 0000000..ab22959
--- /dev/null
+++ b/CUCARACHA/__init__.py
@@ -0,0 +1,2 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
diff --git a/Cria_Bichos_Main.py b/Cria_Bichos_Main.py
new file mode 100644
index 0000000..f2c3fd0
--- /dev/null
+++ b/Cria_Bichos_Main.py
@@ -0,0 +1,1046 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Cria_Bichos_Main.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, gc, sys, random, os, threading, gtk, pygtk
+from pygame.locals import *
+from math import sin, cos, radians
+
+gc.enable()
+
+import BiblioJAM
+from BiblioJAM.JAMLabel import JAMLabel
+from BiblioJAM.JAMDialog import JAMDialog
+import BiblioJAM.JAMGlobals as JAMG
+
+import Globals as VG
+
+from Bicho import Bicho
+from Interfaz import Interfaz
+from Ficha_Bicho import Ficha_Bicho
+from Libreta_de_Lectura import Libreta_de_Lectura
+
+def Traduce_posiciones(VA, VH):
+ eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN)
+ for event in eventos:
+ x, y = event.pos
+ xx= x/VA
+ yy= y/VH
+ event_pos= (xx, yy)
+ for event in eventos:
+ evt = pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos= event_pos, button=event.button)
+ pygame.event.post(evt)
+
+ eventos= pygame.event.get(pygame.MOUSEMOTION)
+ for event in eventos:
+ x, y = event.pos
+ xx= x/VA
+ yy= y/VH
+ event_pos= (xx, yy)
+ for event in eventos:
+ evt = pygame.event.Event(pygame.MOUSEMOTION, pos= event_pos, rel=event.rel, buttons=event.buttons)
+ pygame.event.post(evt)
+
+class Cria_Bichos_Main():
+ def __init__(self, cucarasims):
+ self.velocidad_juego = VG.VELOCIDADJUEGO
+ self.maximo_cucas = VG.MAXIMOCUCAS
+
+ self.cucarasims= cucarasims
+
+ self.ventana= self.cucarasims.ventana
+ self.reloj = self.cucarasims.reloj
+ self.fondo = None
+
+ self.sonido_bicho = None
+ self.imagenes_bicho = None
+ self.Bichos = None # cucarachas
+ self.interfaz = None # botones
+
+ self.nivel = None
+ self.area_visible = None # Donde pueden caminar las cucas
+
+ self.puntero = None # grupo para contener la imagen del puntero actual
+ self.pan_select = None # puntero del mouse para pan seleccionado
+ self.agua_select = None
+
+ self.alimento = None # grupo de alimento en escenario
+ self.unidad_alimento = None # imagen para alimento en escenario
+
+ self.agua = None # grupo de agua en escenario
+ self.unidad_agua = None # imagen para agua en escenario
+
+ self.tiempo_de_juego = 0
+ self.horas = 0
+ self.dias = 0
+ self.anios = 0
+
+ self.ficha_bicho = None # para mostrar los datos del bicho seleccionado
+ self.ficha = None
+
+ self.secuencia_muda = 0 # las veces que se ha reproducido automáticamente esta lección
+ self.lecciones = None # contenedor para leccion en pantalla
+ self.leccion_muda = None # leccion muda
+
+ self.reproduccion = 0
+ self.leccion_reproduccion = None
+ self.ootecas = None
+
+ self.nacimientos = 0
+ self.leccion_ciclo_vital = None
+
+ self.muertes = 0
+ self.leccion_muerte = None
+ self.cadaveres = None
+
+ self.leccion_generica = None # para cualquier lección sin imagenes extras
+ self.plaga = 0
+
+ self.machos, self.hembras = 0,0
+ self.mensajes = None
+ self.mensajes_emergentes = None
+ self.puntos = 0
+
+ self.dialog_cerrar = None
+ self.dialog_guardar = None
+
+ self.sonido_select = None
+
+ # Escalado
+ self.resolucionreal= self.cucarasims.resolucionreal
+ self.ventana_real= self.cucarasims.ventana_real
+ self.VA= self.cucarasims.VA
+ self.VH= self.cucarasims.VH
+
+ self.load()
+
+ def Run(self):
+ self.nivel = "Bichos"
+ self.ventana.blit(self.fondo, (0,0))
+ self.deselecciona_leccion(None)
+ self.Bichos.draw(self.ventana)
+ self.interfaz.draw(self.ventana)
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+ self.selecciona_leccion_ciclo(None)
+
+ while self.nivel == "Bichos":
+ self.reloj.tick(35)
+ while gtk.events_pending():
+ gtk.main_iteration(False)
+ Traduce_posiciones(self.VA, self.VH)
+
+ if self.lecciones:
+ self.pause_game_lecciones()
+
+ self.agua.clear(self.ventana, self.fondo)
+ self.alimento.clear(self.ventana, self.fondo)
+ self.cadaveres.clear(self.ventana, self.fondo)
+ self.ootecas.clear(self.ventana, self.fondo)
+ self.Bichos.clear(self.ventana, self.fondo)
+ self.interfaz.clear(self.ventana, self.fondo)
+ self.ficha.clear(self.ventana, self.fondo)
+ self.mensajes.clear(self.ventana, self.fondo)
+ self.puntero.clear(self.ventana, self.fondo)
+
+ self.agua.update()
+ self.alimento.update()
+ self.cadaveres.update()
+ self.ootecas.update()
+ self.Bichos.update()
+ self.interfaz.update()
+ self.ficha.update()
+ self.mensajes.update()
+ self.puntero.update()
+ self.handle_event()
+ pygame.event.clear()
+
+ self.agua.draw(self.ventana)
+ self.alimento.draw(self.ventana)
+ self.cadaveres.draw(self.ventana)
+ self.ootecas.draw(self.ventana)
+ self.Bichos.draw(self.ventana)
+ self.interfaz.draw(self.ventana)
+ self.ficha.draw(self.ventana)
+ self.mensajes.draw(self.ventana)
+ self.puntero.draw(self.ventana)
+
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+
+ self.set_tiempo_de_juego()
+
+ def get_end(self):
+ self.event_end_game() # cuando pierde nada más
+
+ def set_musica(self, button= None):
+ self.set_mensaje(texto= "Musica Activada.")
+ self.interfaz.boton_musica.set_imagen(origen= self.interfaz.imagenes_audio[0])
+ pygame.mixer.music.load(VG.MUSICA1)
+ pygame.mixer.music.play(-1, 0.0)
+
+ def set_pause_musica(self, button= None):
+ self.set_mensaje(texto="Musica Desactivada.")
+ self.interfaz.boton_musica.set_imagen(origen= self.interfaz.imagenes_audio[1])
+ if pygame.mixer.music.get_busy():
+ pygame.mixer.music.stop()
+ else:
+ self.set_musica()
+
+ def no_mensajes(self):
+ self.mensajes.clear(self.ventana, self.fondo)
+ pygame.display.update()
+ self.mensajes = pygame.sprite.OrderedUpdates()
+
+ if not self.ootecas.sprites():
+ # no habrán más naciemientos
+ if not self.machos or not self.hembras:
+ # faltan especímenes de uno de los sexos
+ self.get_end()
+ if self.machos + self.hembras >= self.maximo_cucas:
+ self.migrar()
+
+ def migrar(self):
+ # la mitad de los machos y de las hembras se van
+ migracion_machos = self.machos/2
+ migracion_hembras = self.hembras/2
+
+ for bicho in self.Bichos.sprites():
+ if bicho.sexo == "M" and migracion_machos > 0 and self.machos >= 2:
+ bicho.kill()
+ self.puntos += 1
+ migracion_machos -= 1
+
+ if bicho.sexo == "F" and migracion_hembras > 0 and self.hembras >= 2:
+ bicho.kill()
+ self.puntos += 1
+ migracion_hembras -= 1
+
+ self.set_mensaje(texto="Algunas Cucarachas han migrado hacia otros habitats.")
+
+ def set_mensaje(self, texto=""):
+ self.sonido_bicho.play()
+ if self.mensajes_emergentes.texto != texto:
+ self.mensajes_emergentes.set_mensaje(texto)
+ if self.mensajes != self.mensajes_emergentes:
+ self.mensajes = self.mensajes_emergentes
+
+ def get_nuevo_Juego(self):
+ # poner todo a cero y empezar de nuevo
+ self.Bichos.empty()
+ self.cadaveres.empty()
+ self.alimento.empty()
+ self.ootecas.empty()
+ self.agua.empty()
+ self.ficha = pygame.sprite.OrderedUpdates()
+ self.puntos = 0
+ self.tiempo_de_juego = 0
+ self.horas = 0
+ self.dias = 0
+ self.anios = 0
+ self.machos, self.hembras = 0,0
+
+ self.secuencia_muda = 0
+ self.reproduccion = 0
+ self.nacimientos = 0
+ self.muertes = 0
+ self.plaga = 0
+
+ while not self.machos or not self.hembras:
+ # asegurar un macho y una hembra
+ self.event_nacer()
+ self.machos, self.hembras = self.verificar_sexos_en_habitat()
+
+ def verificar_sexos_en_habitat(self):
+ # verifica si hay machos para reproducirse
+ machos = 0
+ hembras = 0
+ for cuca in self.Bichos.sprites():
+ if cuca.sexo == "M":
+ machos += 1
+ if cuca.sexo == "F":
+ hembras += 1
+ return machos, hembras
+
+ def event_morir(self, posicion=(0,0), dias=0, leccion=False):
+ # muere una cuca
+ if self.muertes == 0:
+ self.muertes = 1
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.lecciones = self.leccion_muerte
+ if not self.interfaz.boton_muerte in self.interfaz:
+ self.interfaz.add(self.interfaz.boton_muerte)
+ if leccion == False:
+ # Cuando es True se está llamando desde el botón para ver la lección
+ self.cadaveres.add(Cadaver(self, posicion=posicion, dias=dias))
+ self.set_mensaje(texto="Se han producido muertes en el habitat.")
+
+ def event_nacer(self, leccion=False):
+ # nace una cuca
+ if self.nacimientos == 0:
+ self.nacimientos = 1
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.lecciones = self.leccion_ciclo_vital
+ if not self.interfaz.boton_ciclo in self.interfaz:
+ self.interfaz.add(self.interfaz.boton_ciclo)
+ if leccion == False:
+ # Cuando es True se está llamando desde el botón para ver la lección
+ self.Bichos.add(Bicho(self))
+ self.set_mensaje(texto="Se han producido nacimientos en el habitat.")
+
+ def pause_game_lecciones(self):
+ # pausa el juego y reproduce las lecciones
+ while self.lecciones.sprites():
+ self.reloj.tick(35)
+ while gtk.events_pending():
+ gtk.main_iteration(False)
+ Traduce_posiciones(self.VA, self.VH)
+ self.lecciones.clear(self.ventana, self.fondo)
+ self.lecciones.update()
+ self.handle_event()
+ pygame.event.clear()
+ self.lecciones.draw(self.ventana)
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+
+ def event_muda(self, posicion=(0, 0), tamanio=(63,50)):
+ # dejar exoesqueleto
+ self.set_mensaje(texto="Algunas Cucarachas han realizado la muda de su exoesqueleto.")
+ if self.secuencia_muda == 0:
+ self.secuencia_muda = 1
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.lecciones = self.leccion_muda
+ if not self.interfaz.boton_muda in self.interfaz:
+ self.interfaz.add(self.interfaz.boton_muda)
+
+ def event_reproduccion(self, posicion=(0, 0)):
+ # dejar ooteca
+ if posicion != None:
+ self.ootecas.add(Ooteca(self, posicion=posicion))
+ self.set_mensaje(texto="Hay nuevas ootecas en el habitat.")
+
+ if self.reproduccion == 0:
+ # self.reproduccion es para verificar si se ha visto la leccion.
+ # la leccion se activa automaticamente la 1ª vez nada más y despues no se muestra automaticamente
+ # para no molestar al usuario
+ self.reproduccion = 1
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.lecciones = self.leccion_reproduccion
+ if not self.interfaz.boton_reproduccion in self.interfaz:
+ self.interfaz.add(self.interfaz.boton_reproduccion)
+
+ def event_end_game(self):
+ # lectura perder
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.leccion_generica.set_lectura(VG.LECTURAENDGAME)
+ x = VG.RESOLUCION[0]/2 - self.leccion_generica.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - self.leccion_generica.hoja_impresa.rect.h/2
+ self.leccion_generica.set_posicion(punto=(x,y))
+ self.lecciones = self.leccion_generica
+
+ def event_plaga(self):
+ # dejar exoesqueleto
+ if self.plaga == 0:
+ self.plaga = 1
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.leccion_generica.set_lectura(VG.LECTURAPLAGA)
+ x = VG.RESOLUCION[0]/2 - self.leccion_generica.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - self.leccion_generica.hoja_impresa.rect.h/2
+ self.leccion_generica.set_posicion(punto=(x,y))
+ self.lecciones = self.leccion_generica
+ if not self.interfaz.boton_plaga in self.interfaz:
+ self.interfaz.add(self.interfaz.boton_plaga)
+
+ def get_leccion_muerte(self):
+ # La lección sobre la muerte
+ libreta = Libreta_de_Lectura(VG.LECTURAMUERTE)
+ x = VG.RESOLUCION[0]/2 - libreta.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - libreta.hoja_impresa.rect.h/2
+ libreta.set_posicion(punto=(x,y))
+
+ muertea = pygame.sprite.Sprite()
+ muertea.image = pygame.transform.scale(pygame.image.load(VG.MUERTE), (400,252)).convert_alpha()
+ muertea.rect = muertea.image.get_rect()
+
+ y = (VG.RESOLUCION[1]/2) - (muertea.rect.h/2)
+ x = libreta.hoja_impresa.rect.x - muertea.rect.w - 20
+ muertea.rect.x, muertea.rect.y = x, y
+ y = muertea.rect.y + muertea.rect.h + 10
+
+ # frame contenedor
+ frame = pygame.sprite.Sprite()
+ ancho = 10 + muertea.rect.w + 10
+ altura = 10 + muertea.rect.h + 10
+ x, y = muertea.rect.x - 10, muertea.rect.y - 10
+ frame.image= pygame.Surface( (ancho,altura) )
+ frame.image.fill( (255,255,255,255) )
+ frame.rect = frame.image.get_rect()
+ frame.rect.x, frame.rect.y = x, y
+
+ libreta.add(frame)
+ libreta.add(muertea)
+
+ libreta.boton_cerrar.connect(callback=self.deselecciona_leccion, sonido_select= None)
+ libreta.boton_leeme.connect(callback=self.lee, sonido_select= None)
+ return libreta
+
+ def get_leccion_cilo_vital(self):
+ # La lección sobre el ciclo vital
+ libreta = Libreta_de_Lectura(VG.LECTURACICLOVITAL)
+ x = VG.RESOLUCION[0]/2 - libreta.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - libreta.hoja_impresa.rect.h/2
+ libreta.set_posicion(punto=(x,y))
+
+ cicloa = pygame.sprite.Sprite()
+ cicloa.image = pygame.transform.scale(pygame.image.load(VG.CICLO1), (400,398)).convert_alpha()
+ cicloa.rect = cicloa.image.get_rect()
+
+ ciclob = pygame.sprite.Sprite()
+ ciclob.image = pygame.transform.scale(pygame.image.load(VG.CICLO2), (400,270)).convert_alpha()
+ ciclob.rect = ciclob.image.get_rect()
+
+ y = VG.RESOLUCION[1]/2 - (cicloa.rect.h + 10 + ciclob.rect.h)/2
+ x = libreta.hoja_impresa.rect.x - cicloa.rect.w - 20
+ cicloa.rect.x, cicloa.rect.y = x, y
+ y = cicloa.rect.y + cicloa.rect.h + 10
+ ciclob.rect.x, ciclob.rect.y = x, y
+
+ # frame contenedor
+ frame = pygame.sprite.Sprite()
+ ancho = 10 + cicloa.rect.w + 10
+ altura = 10 + cicloa.rect.h + 10 + ciclob.rect.h + 10
+ x, y = cicloa.rect.x - 10, cicloa.rect.y - 10
+ frame.image= pygame.Surface( (ancho,altura) )
+ frame.image.fill( (255,255,255,255) )
+ frame.rect = frame.image.get_rect()
+ frame.rect.x, frame.rect.y = x, y
+
+ libreta.add(frame)
+ libreta.add(cicloa)
+ libreta.add(ciclob)
+
+ libreta.boton_cerrar.connect(callback=self.deselecciona_leccion, sonido_select= None)
+ libreta.boton_leeme.connect(callback=self.lee, sonido_select= None)
+ return libreta
+
+ def get_leccion_reproduccion(self):
+ # La lección sobre reproducción
+ libreta = Libreta_de_Lectura(VG.LECTURAREPRODUCCION)
+ x = VG.RESOLUCION[0]/2 - libreta.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - libreta.hoja_impresa.rect.h/2
+ libreta.set_posicion(punto=(x,y))
+
+ reproa = pygame.sprite.Sprite()
+ reproa.image = pygame.transform.scale(pygame.image.load(VG.REPRODUCCION1), (400,250)).convert_alpha()
+ reproa.rect = reproa.image.get_rect()
+
+ reprob = pygame.sprite.Sprite()
+ reprob.image = pygame.transform.scale(pygame.image.load(VG.REPRODUCCION2), (400,248)).convert_alpha()
+ reprob.rect = reprob.image.get_rect()
+
+ y = VG.RESOLUCION[1]/2 - (reproa.rect.h + 10 + reprob.rect.h)/2
+ x = libreta.hoja_impresa.rect.x - reproa.rect.w - 20
+ reproa.rect.x, reproa.rect.y = x, y
+ y = reproa.rect.y + reproa.rect.h + 10
+ reprob.rect.x, reprob.rect.y = x, y
+
+ # frame contenedor
+ frame = pygame.sprite.Sprite()
+ ancho = 10 + reproa.rect.w + 10
+ altura = 10 + reproa.rect.h + 10 + reprob.rect.h + 10
+ x, y = reproa.rect.x - 10, reproa.rect.y - 10
+ frame.image= pygame.Surface( (ancho,altura) )
+ frame.image.fill( (255,255,255,255) )
+ frame.rect = frame.image.get_rect()
+ frame.rect.x, frame.rect.y = x, y
+
+ libreta.add(frame)
+ libreta.add(reproa)
+ libreta.add(reprob)
+
+ libreta.boton_cerrar.connect(callback=self.deselecciona_leccion, sonido_select= None)
+ libreta.boton_leeme.connect(callback=self.lee, sonido_select= None)
+ return libreta
+
+ def get_leccion_muda(self):
+ # Leccion Muda de Exoesqueleto
+ libreta = Libreta_de_Lectura(VG.LECTURAMUDA)
+ x = VG.RESOLUCION[0]/2 - libreta.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - libreta.hoja_impresa.rect.h/2
+ libreta.set_posicion(punto=(x,y))
+
+ secuencia = Secuencia_muda()
+ mudaa = pygame.sprite.Sprite()
+ mudaa.image = pygame.transform.scale(pygame.image.load(VG.MUDA1), (400,192)).convert_alpha()
+ mudaa.rect = mudaa.image.get_rect()
+ mudab = pygame.sprite.Sprite()
+ mudab.image = pygame.transform.scale(pygame.image.load(VG.MUDA2), (400,140)).convert_alpha()
+ mudab.rect = mudab.image.get_rect()
+
+ y = VG.RESOLUCION[1]/2 - (secuencia.rect.h + 10 + mudaa.rect.h + 10 + mudab.rect.h)/2
+ x = libreta.hoja_impresa.rect.x - secuencia.rect.w - 20
+ secuencia.rect.x, secuencia.rect.y = x, y
+ y = secuencia.rect.y + secuencia.rect.h + 10
+ mudaa.rect.x, mudaa.rect.y = x, y
+ y = mudaa.rect.y + mudaa.rect.h + 10
+ mudab.rect.x, mudab.rect.y = x, y
+
+ # frame contenedor
+ frame = pygame.sprite.Sprite()
+ ancho = 10 + secuencia.rect.w + 10
+ altura = 10 + secuencia.rect.h + 10 + mudaa.rect.h + 10 + mudab.rect.h + 10
+ x, y = secuencia.rect.x - 10, secuencia.rect.y - 10
+ frame.image= pygame.Surface( (ancho,altura) )
+ frame.image.fill( (255,255,255,255) )
+ frame.rect = frame.image.get_rect()
+ frame.rect.x, frame.rect.y = x, y
+
+ libreta.add(frame)
+ libreta.add(secuencia)
+ libreta.add(mudaa)
+ libreta.add(mudab)
+ libreta.boton_cerrar.connect(callback=self.deselecciona_leccion, sonido_select= None)
+ libreta.boton_leeme.connect(callback=self.lee, sonido_select= None)
+ return libreta
+
+ def get_leccion_generica(self):
+ # La lección sobre reproducción
+ libreta = Libreta_de_Lectura(" ")
+ x = VG.RESOLUCION[0]/2 - libreta.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - libreta.hoja_impresa.rect.h/2
+ libreta.set_posicion(punto=(x,y))
+ libreta.boton_cerrar.connect(callback=self.deselecciona_leccion, sonido_select= None)
+ libreta.boton_leeme.connect(callback=self.lee, sonido_select= None)
+ return libreta
+
+ def deselecciona_leccion(self, button= None):
+ # deselecciona cualquier leccion que se este ejecutando para detenerla
+ self.lecciones.clear(self.ventana, self.fondo)
+ self.lecciones= pygame.sprite.OrderedUpdates()
+ pygame.display.update()
+
+ def selecciona_mensaje_salir(self, button= None):
+ self.deselecciona_leccion(None)
+ self.lecciones= self.dialog_cerrar
+ def selecciona_mensaje_guardar(self, button):
+ self.deselecciona_leccion(None)
+ self.lecciones = self.dialog_guardar
+
+ def guardar_juego(self, button= None):
+ base= self.cucarasims.base_de_datos
+ datos= self.get_datos_para_guardar()
+ self.cucarasims.Archivos_y_Directorios.guardar(base=base, datos=datos)
+ self.salir(None)
+
+ def get_datos_para_guardar(self):
+ datos_de_juego = [self.anios, self.dias, self.horas, self.puntos]
+ bichos = []
+ for bicho in self.Bichos.sprites():
+ sexo = bicho.sexo
+ anios = bicho.anios
+ dias = bicho.dias
+ horas = bicho.horas
+ hambre = bicho.hambre
+ sed = bicho.sed
+ dato_bicho = [sexo, anios, dias, horas, hambre, sed]
+ bichos.append(dato_bicho)
+
+ ootecas = []
+ for ooteca in self.ootecas.sprites():
+ dias = ooteca.dias
+ horas = ooteca.horas
+ huevos = ooteca.huevos
+ dato_ooteca = [dias, horas, huevos]
+ ootecas.append(dato_ooteca)
+
+ datos = (datos_de_juego, bichos, ootecas)
+ return datos
+
+ def selecciona_leccion_extra(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ self.sonido_bicho.play()
+ self.deselecciona_leccion(None)
+ self.leccion_generica.set_lectura(VG.LECTURASEXTRAS)
+ x = VG.RESOLUCION[0]/2 - self.leccion_generica.hoja_impresa.rect.w/5
+ y = VG.RESOLUCION[1]/2 - self.leccion_generica.hoja_impresa.rect.h/2
+ self.leccion_generica.set_posicion(punto=(x,y))
+ self.lecciones = self.leccion_generica
+
+ def selecciona_leccion_plaga(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ plaga = self.plaga
+ self.deselecciona_leccion(None)
+ self.plaga = 0
+ self.event_plaga()
+ self.plaga = plaga # para devolverlo al estado inicial
+
+ def selecciona_leccion_muerte(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ muertes = self.muertes
+ self.deselecciona_leccion(None)
+ self.muertes = 0
+ self.event_morir(leccion=True)
+ self.muertes = muertes # para devolverlo al estado inicial
+
+ def selecciona_leccion_ciclo(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ nacimientos = self.nacimientos
+ self.deselecciona_leccion(None)
+ self.nacimientos = 0
+ self.event_nacer(leccion=True)
+ self.nacimientos = nacimientos # para devolverlo al estado inicial
+
+ def selecciona_leccion_muda(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ mudas = self.secuencia_muda
+ self.deselecciona_leccion(None)
+ self.secuencia_muda = 0
+ self.event_muda()
+ self.secuencia_muda = mudas # para devolverlo al estado inicial
+
+ def selecciona_leccion_reproduccion(self, button= None):
+ # para conectar al boton de la leccion correspondiente
+ reproduccion = self.reproduccion
+ self.deselecciona_leccion(None)
+ self.reproduccion = 0
+ self.event_reproduccion(posicion=None)
+ self.reproduccion = reproduccion # para devolverlo al estado inicial
+
+ def set_tiempo_de_juego(self):
+ # calculos vitales de tiempo
+ self.tiempo_de_juego += 1
+ cambios = False
+ if self.tiempo_de_juego == self.velocidad_juego:
+ self.horas += 1
+ self.tiempo_de_juego = 0
+ for bicho in self.Bichos.sprites():
+ bicho.set_tiempo_de_vida()
+ for ooteca in self.ootecas.sprites():
+ ooteca.set_tiempo_de_vida()
+ for cadaver in self.cadaveres.sprites():
+ cadaver.set_tiempo_de_vida()
+ cambios = True
+
+ if self.horas == 1:
+ # ************************************* #
+ self.machos, self.hembras = self.verificar_sexos_en_habitat()
+ total = self.machos + self.hembras
+ ootecas = len(self.ootecas.sprites())
+ bichos = "Cucarachas: %s, Machos: %s, Hembras: %s, Ootecas: %s Migración: %s" % (total, self.machos,
+ self.hembras, ootecas, self.puntos)
+ self.interfaz.set_informacion_de_habitat(bichos)
+
+ if not self.machos and not ootecas:
+ self.set_mensaje(texto="No quedan Machos ni ootecas en el habitat, la Reproducción ya no será posible.")
+ elif not self.hembras and not ootecas:
+ self.set_mensaje(texto="No quedan Hembras ni ootecas en el habitat, la Reproducción ya no será posible.")
+ elif not self.machos and not self.hembras and not ootecas:
+ self.set_mensaje(texto="Todas las Cucarachas han muerto y no hay ootecas en el habitat.")
+ elif self.machos + self.hembras >= self.maximo_cucas:
+ self.event_plaga()
+ self.set_mensaje(texto="Hay Demasiadas Cucarachas en el habitat. Algunas migrarán. !!!")
+ # ************************************* #
+ if self.horas == 24:
+ self.dias += 1
+ self.horas = 0
+ self.aumenta_hambre()
+ self.aumenta_sed()
+
+ if self.dias == 365:
+ self.anios += 1
+ self.dias = 0
+
+ if cambios:
+ tiempo = "Tiempo de Juego = Años: %s Dias: %s Horas: %s" % (self.anios, self.dias, self.horas)
+ self.interfaz.set_tiempo_de_juego(tiempo)
+
+ def aumenta_hambre(self):
+ # cada 24 horas aumenta el hambre de los bichos
+ for bicho in self.Bichos.sprites():
+ bicho.hambre -= VG.AUMENTAHAMBRE
+ def aumenta_sed(self):
+ # cada 24 horas aumenta la sed de los bichos
+ for bicho in self.Bichos.sprites():
+ bicho.sed -= VG.AUMENTASED
+
+ # ------------------------------- CONFIGURACIONES ------------------------------------------------ #
+ def load(self):
+ if not self.sonido_select: self.sonido_select = JAMG.get_sound_select()
+ if not self.area_visible: self.area_visible = pygame.Rect(35,35,VG.RESOLUCION[0]-70,VG.RESOLUCION[1]-70)
+ if not self.reloj: self.reloj = pygame.time.Clock()
+ if not self.fondo: self.fondo = self.get_fondo()
+ if not self.imagenes_bicho:
+ self.imagenes_bicho = [pygame.transform.rotate(pygame.image.load(VG.CUCARACHA1), -90),
+ pygame.transform.rotate(pygame.image.load(VG.CUCARACHA2), -90),
+ pygame.transform.rotate(pygame.image.load(VG.CUCARACHA3), -90),
+ pygame.transform.rotate(pygame.image.load(VG.CUCARACHA4), -90)]
+
+ if not self.sonido_bicho: self.sonido_bicho = pygame.mixer.Sound(VG.SONIDOCUCARACHA)
+ if not self.puntero: self.puntero= pygame.sprite.OrderedUpdates()
+ if not self.pan_select: self.pan_select = Puntero(1)
+ if not self.agua_select: self.agua_select = Puntero(2)
+ if not self.interfaz:
+ self.interfaz= Interfaz()
+ self.interfaz.boton_pan.connect(callback=self.get_pan, sonido_select=self.sonido_select)
+ self.interfaz.boton_jarra.connect(callback=self.get_agua, sonido_select=self.sonido_select)
+ self.interfaz.boton_muda.connect(callback=self.selecciona_leccion_muda, sonido_select=self.sonido_select)
+ self.interfaz.boton_reproduccion.connect(callback=self.selecciona_leccion_reproduccion, sonido_select=self.sonido_select)
+ self.interfaz.boton_ciclo.connect(callback=self.selecciona_leccion_ciclo, sonido_select=self.sonido_select)
+ self.interfaz.boton_muerte.connect(callback=self.selecciona_leccion_muerte, sonido_select=self.sonido_select)
+ self.interfaz.boton_plaga.connect(callback=self.selecciona_leccion_plaga, sonido_select=self.sonido_select)
+ self.interfaz.boton_musica.connect(callback=self.set_pause_musica, sonido_select=self.sonido_select)
+ self.interfaz.boton_extras.connect(callback=self.selecciona_leccion_extra, sonido_select=self.sonido_select)
+ self.interfaz.boton_salir.connect(callback=self.selecciona_mensaje_salir, sonido_select=self.sonido_select)
+
+ if not self.lecciones: self.lecciones= pygame.sprite.OrderedUpdates()
+
+ if not self.leccion_muda: self.leccion_muda = self.get_leccion_muda()
+ if not self.leccion_generica: self.leccion_generica = self.get_leccion_generica()
+ if not self.leccion_reproduccion: self.leccion_reproduccion = self.get_leccion_reproduccion()
+ if not self.leccion_ciclo_vital: self.leccion_ciclo_vital = self.get_leccion_cilo_vital()
+ if not self.leccion_muerte: self.leccion_muerte = self.get_leccion_muerte()
+
+ if not self.alimento: self.alimento = pygame.sprite.OrderedUpdates()
+ if not self.mensajes: self.mensajes = pygame.sprite.OrderedUpdates()
+ if not self.mensajes_emergentes: self.mensajes_emergentes = Mensaje(self)
+ if not self.cadaveres: self.cadaveres = pygame.sprite.OrderedUpdates()
+ if not self.ootecas: self.ootecas = pygame.sprite.OrderedUpdates()
+ if not self.unidad_alimento: self.unidad_alimento = Alimento(self.interfaz)
+ if not self.agua: self.agua = pygame.sprite.OrderedUpdates()
+ if not self.unidad_agua: self.unidad_agua = Agua(self.interfaz)
+ if not self.Bichos: self.Bichos = pygame.sprite.OrderedUpdates()
+ if not self.ficha_bicho: self.ficha_bicho = Ficha_Bicho()
+ if not self.ficha: self.ficha = pygame.sprite.OrderedUpdates()
+
+ if not self.dialog_cerrar:
+ a,b,c= JAMG.get_estilo_celeste()
+ self.dialog_cerrar= JAMDialog(mensaje= "¿Deseas Salir del Juego?",
+ funcion_ok= self.selecciona_mensaje_guardar, funcion_cancel= self.deselecciona_leccion)
+ self.dialog_cerrar.set_colors_dialog(base= c, bordes= b)
+ self.dialog_cerrar.set_colors_buttons(colorbas= a, colorbor= b, colorcara= c)
+ if not self.dialog_guardar:
+ a,b,c= JAMG.get_estilo_naranja()
+ self.dialog_guardar= JAMDialog(mensaje= "¿Guardar Antes de Salir?",
+ funcion_ok= self.guardar_juego, funcion_cancel= self.Borrar_salir)
+ self.dialog_guardar.set_colors_dialog(base= c, bordes= b)
+ self.dialog_guardar.set_colors_buttons(colorbas= a, colorbor= b, colorcara= c)
+
+ def lee(self, button= None):
+ if pygame.mixer.music.get_busy():
+ self.set_pause_musica(None)
+ pygame.mixer.quit()
+ textbuffer = ""
+ for elem in self.lecciones.lectura[self.lecciones.indice_pagina_actual]:
+ textbuffer += (" " + elem)
+ self.lecciones.motor_de_voz.lee(textbuffer)
+ pygame.mixer.init()
+ self.set_pause_musica(None)
+
+ def get_agua(self, button= None):
+ # imagen pan para el puntero del mouse al seleccionar alimento
+ imagen= self.puntero.sprites()
+ if imagen:
+ self.puntero.empty()
+ pygame.mouse.set_visible(True)
+ elif not imagen:
+ self.puntero.add(self.agua_select)
+ pygame.mouse.set_visible(False)
+
+ def get_pan(self, button= None):
+ # imagen pan para el puntero del mouse al seleccionar alimento
+ imagen= self.puntero.sprites()
+ if imagen:
+ self.puntero.empty()
+ pygame.mouse.set_visible(True)
+ elif not imagen:
+ self.puntero.add(self.pan_select)
+ pygame.mouse.set_visible(False)
+
+ def get_fondo(self, color=(200,200,200,1), tamanio=VG.RESOLUCION):
+ # devuelve una superficie de color para el fondo de la ventana
+ superficie = pygame.transform.scale(pygame.image.load(VG.FONDO), (VG.RESOLUCION))
+ return superficie
+
+ def handle_event(self):
+ eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN)
+ for event in eventos:
+ posicion= event.pos
+ if self.pan_select in self.puntero.sprites():
+ # si tenemos seleccionado el alimento dejar el pan en el escenario
+ if not self.alimento.sprites():
+ self.unidad_alimento.cantidad = VG.UNIDADALIMENTO
+ self.unidad_alimento.rect.center = posicion
+ self.alimento.add(self.unidad_alimento)
+ self.puntero.empty()
+ pygame.mouse.set_visible(True)
+ self.set_mensaje(texto= "Las Cucarachas detectan con sus antenas, el alimento en el habitat.")
+ elif self.agua_select in self.puntero.sprites():
+ # si tenemos seleccionado el agua, dejar el agua en el escenario
+ if not self.agua.sprites():
+ self.unidad_agua.cantidad = VG.UNIDADAGUA
+ self.unidad_agua.rect.center = posicion
+ self.agua.add(self.unidad_agua)
+ self.puntero.empty()
+ pygame.mouse.set_visible(True)
+ self.set_mensaje(texto= "Las Cucarachas detectan con sus antenas, el agua en el habitat.")
+
+ elif not self.pan_select in self.puntero.sprites() and not self.agua_select in self.puntero.sprites():
+ # si no tenemos seleccionado el alimento, vemos si se ha seleccionado alguna cuca
+ posicion = posicion
+ bicho_select = None
+ for bicho in self.Bichos.sprites():
+ if bicho.rect.collidepoint(posicion):
+ # cuando seleccionamos una cucaracha
+ bicho.play_sonido_bicho()
+ bicho_select = bicho
+ break
+ if bicho_select:
+ self.ficha_bicho.set_bicho(bicho_select)
+ self.ficha = self.ficha_bicho
+ else:
+ self.ficha_bicho.bicho = None
+ self.ficha.clear(self.ventana, self.fondo)
+ self.ficha = pygame.sprite.OrderedUpdates()
+ # republicar evento ?
+
+ for event in pygame.event.get(pygame.KEYDOWN):
+ if event.key == pygame.K_ESCAPE:
+ self.selecciona_mensaje_salir(None)
+
+ def salir(self, button= None):
+ self.deselecciona_leccion(None)
+ self.cucarasims.nivel = "Menu"
+ self.cucarasims.RunMenu()
+
+ def Borrar_salir(self, button= None):
+ # Si no hay datos borra la base
+ self.cucarasims.Archivos_y_Directorios.verifica(base_abrir=self.cucarasims.base_de_datos)
+ self.cucarasims.nivel = "Menu"
+ self.cucarasims.RunMenu()
+
+class Agua(pygame.sprite.Sprite):
+# Agua en el escenario, recibe interfaz para informar de los cambios segun consumo
+ def __init__(self, interfaz):
+ pygame.sprite.Sprite.__init__(self)
+
+ self.interfaz = interfaz
+ self.cantidad = 0
+ self.ultima_cantidad = 0
+ imagen_original = pygame.transform.scale(pygame.image.load(VG.AGUA), (40,30)).convert_alpha()
+
+ self.imagen1 = imagen_original.copy()
+ self.imagen2 = pygame.transform.scale(imagen_original.copy(), (30,20)).convert_alpha()
+ self.imagen3 = pygame.transform.scale(imagen_original.copy(), (20,10)).convert_alpha()
+
+ self.image = self.imagen1
+ self.rect = self.image.get_rect()
+
+ def update(self):
+ parte = VG.UNIDADAGUA/3
+ if self.cantidad >= parte * 2:
+ if self.image != self.imagen1:
+ self.image = self.imagen1
+ if self.cantidad >= parte and self.cantidad < parte * 2:
+ if self.image != self.imagen2:
+ self.image = self.imagen2
+ if self.cantidad > 0 and self.cantidad < parte:
+ if self.image != self.imagen3:
+ self.image = self.imagen3
+
+ # informa sobre la cantidad de agua que hay en el escenario
+ if self.ultima_cantidad != self.cantidad:
+ self.interfaz.set_agua_en_escenario(self.cantidad)
+
+ self.ultima_cantidad = self.cantidad
+
+class Alimento(pygame.sprite.Sprite):
+# Alimento en el escenario, recibe interfaz para informar de los cambios segun consumo
+ def __init__(self, interfaz):
+ pygame.sprite.Sprite.__init__(self)
+
+ self.interfaz = interfaz
+ self.cantidad = 0
+ self.ultima_cantidad = 0
+ imagen_original = pygame.transform.scale(pygame.image.load(VG.PAN), (40,30)).convert_alpha()
+
+ self.imagen1 = imagen_original.copy()
+ self.imagen2 = imagen_original.copy().subsurface(0,0,27,30)
+ self.imagen3 = imagen_original.copy().subsurface(0,0,13,30)
+
+ self.image = self.imagen1
+ self.rect = self.image.get_rect()
+
+ def update(self):
+ parte = VG.UNIDADALIMENTO/3
+ if self.cantidad >= parte*2:
+ if self.image != self.imagen1:
+ self.image = self.imagen1
+ if self.cantidad >= parte and self.cantidad < parte*2:
+ if self.image != self.imagen2:
+ self.image = self.imagen2
+ if self.cantidad > 0 and self.cantidad < parte:
+ if self.image != self.imagen3:
+ self.image = self.imagen3
+
+ # informa sobre la cantidad de alimento que hay en el escenario
+ if self.ultima_cantidad != self.cantidad:
+ self.interfaz.set_pan_en_escenario(self.cantidad)
+
+ self.ultima_cantidad = self.cantidad
+
+class Puntero(pygame.sprite.Sprite):
+# El puntero del mouse, pan o agua
+ def __init__(self, tipo):
+ pygame.sprite.Sprite.__init__(self)
+ self.tipo = tipo
+ if self.tipo == 1:
+ # pan seleccionado
+ self.image = pygame.transform.scale(pygame.image.load(VG.PAN), (40,30)).convert_alpha()
+ elif self.tipo == 2:
+ # agua seleccionada
+ self.image = pygame.transform.scale(pygame.image.load(VG.AGUA), (40,30)).convert_alpha()
+ self.rect= self.image.get_rect()
+
+ def update(self):
+ for event in pygame.event.get(pygame.MOUSEMOTION):
+ self.rect.center= event.pos
+
+class Secuencia_muda(pygame.sprite.Sprite):
+ def __init__(self):
+ pygame.sprite.Sprite.__init__(self)
+ self.lista_de_imagenes = self.get_imagenes()
+ self.velocidad = 0
+ self.indice = 0
+ self.image = self.lista_de_imagenes[self.indice]
+ self.rect = self.image.get_rect()
+ self.pasadas = 0
+
+ def get_imagenes(self):
+ lista = []
+ for archivo in os.listdir(VG.MUDAS):
+ imagen = pygame.transform.scale(pygame.image.load(VG.MUDAS + archivo), (400,360)).convert_alpha()
+ lista.append(imagen)
+ return lista
+
+ def update(self):
+ if self.velocidad == 1:
+ # en la xo debe ser 1
+ self.pasadas += 1
+ self.velocidad = 0
+ self.image = self.lista_de_imagenes[self.indice]
+ if len(self.lista_de_imagenes)-1 > self.indice:
+ self.indice += 1
+ else:
+ self.indice = 0
+ self.velocidad += 1
+
+class Ooteca(pygame.sprite.Sprite):
+ def __init__(self, juego, posicion=(0,0)):
+ pygame.sprite.Sprite.__init__(self)
+
+ self.juego = juego
+ self.dias = 0
+ self.horas = 0
+ huevos = [1, 2, 3]
+ random.seed()
+ self.huevos = random.choice(huevos)
+ self.image = pygame.image.load(VG.OOTECA).convert_alpha()
+ self.rect = self.image.get_rect()
+ self.rect.centerx, self.rect.centery = posicion
+
+ def set_tiempo_de_vida(self):
+ self.horas += 1
+ if self.horas == 24:
+ self.dias += 1
+ self.horas = 0
+ if self.dias == VG.NACER:
+ # nacimiento 30 dias de incubacion
+ for huevo in range(self.huevos):
+ self.juego.event_nacer()
+ self.kill() # la ooteca desaparece
+
+class Cadaver(pygame.sprite.Sprite):
+ def __init__(self, juego, posicion=(0,0), dias=0):
+ pygame.sprite.Sprite.__init__(self)
+
+ self.juego = juego
+ self.dias = 0
+ self.horas = 0
+
+ if dias <= VG.DIASMUDAS[0]:
+ escala = (53,63)
+ elif dias >= VG.DIASMUDAS[0] and dias < VG.DIASMUDAS[1]:
+ escala = VG.ESCALASMUDAS[0]
+ elif dias >= VG.DIASMUDAS[1] and dias < VG.DIASMUDAS[2]:
+ escala = VG.ESCALASMUDAS[1]
+ elif dias >= VG.DIASMUDAS[2] and dias < VG.DIASMUDAS[3]:
+ escala = VG.ESCALASMUDAS[2]
+ elif dias >= VG.DIASMUDAS[3]:
+ escala = VG.ESCALASMUDAS[3]
+
+ self.image = pygame.transform.scale(pygame.image.load(VG.CADAVER), escala).convert_alpha()
+
+ self.rect = self.image.get_rect()
+ self.rect.centerx, self.rect.centery = posicion
+
+ def set_tiempo_de_vida(self):
+ self.horas += 1
+ if self.horas == 24:
+ self.dias += 1
+ self.horas = 0
+ if self.dias == VG.DIASCADAVER:
+ self.kill()
+
+class Mensaje(pygame.sprite.OrderedUpdates):
+# mensajes emergentes
+ def __init__(self, juego):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ self.juego = juego
+ self.texto = ""
+ self.contador = 0
+ self.etiqueta= JAMLabel("mensaje")
+ self.etiqueta. set_text(tamanio= 40, color= JAMG.get_celeste1())
+ self.add(self.etiqueta)
+
+ def set_mensaje(self, texto):
+ self.texto = texto
+ self.etiqueta.set_text(texto= texto)
+ self.set_posicion()
+
+ def set_posicion(self):
+ x = VG.RESOLUCION[0]/2 - self.etiqueta.get_tamanio()[0]/2
+ y = VG.RESOLUCION[1] - 40 - self.etiqueta.get_tamanio()[1]
+ self.etiqueta.set_posicion((x,y))
+
+ def update(self):
+ # Aparece y desaparece automáticamente al cabo de cierto tiempo
+ if self.juego.mensajes == self:
+ self.contador += 1
+ if self.contador == 100:
+ self.contador = 0
+ self.juego.no_mensajes()
+ return
+
diff --git a/CucaraSims.py b/CucaraSims.py
new file mode 100644
index 0000000..603ee74
--- /dev/null
+++ b/CucaraSims.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import pygame, gtk, pygtk, os, gtk, pygtk, gobject, sys, socket
+from pygame.locals import *
+from sugar.activity import activity
+
+from Main import Main
+
+class CucaraSims(activity.Activity):
+ def __init__(self, handle):
+ activity.Activity.__init__(self, handle, False)
+ self.set_title('CucaraSims')
+ #self.set_toolbox(activity.ActivityToolbox(self))
+ self.eventbox= PygameCanvas()
+ self.set_canvas(self.eventbox)
+
+ self.add_events(gtk.gdk.ALL_EVENTS_MASK)
+ self.connect("destroy", self.salir)
+
+ self.show_all()
+ self.realize()
+
+ os.putenv('SDL_WINDOWID', str(self.eventbox.socket.get_id()))
+ gobject.idle_add(self.get_run_game)
+
+ def get_run_game(self):
+ print "Lanzando CucaraSims."
+ pygame.init()
+ x, y, w, y= self.eventbox.get_allocation()
+ Main( (w,y) )
+ #Main()
+ return False
+
+ def salir(self, widget):
+ lambda w: gtk.main_quit()
+ sys.exit()
+
+class PygameCanvas(gtk.EventBox):
+ def __init__(self):
+ gtk.EventBox.__init__(self)
+ self.set_flags(gtk.CAN_FOCUS)
+ self.setup_events()
+ self.socket = gtk.Socket()
+ self.add(self.socket)
+ self.button_state = [0,0,0]
+ self.mouse_pos = (0,0)
+
+ def setup_events(self):
+ self.set_events(gtk.gdk.KEY_PRESS | gtk.gdk.EXPOSE | gtk.gdk.POINTER_MOTION_MASK | \
+ gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_MOTION_MASK | \
+ gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK)
+
+ self.connect("key-press-event", self.keypress)
+ self.connect("button_press_event", self.mousedown)
+ self.connect("motion-notify-event", self.mousemotion)
+ self.connect('expose-event', self.expose)
+ self.connect('configure-event', self.resize)
+ self.connect("focus-in-event", self.set_focus)
+
+ def keypress(self, selfmain, event, parametros= None):
+ nombre= gtk.gdk.keyval_name(event.keyval)
+ tipo= pygame.KEYDOWN
+ unic= str.lower(nombre)
+ valor= nombre
+ try:
+ valor= getattr(pygame, "K_%s" % (str.upper(nombre)))
+ except:
+ print "no has programado la traduccion de esta tecla: ", nombre
+ return False
+ evt = pygame.event.Event(tipo, key= valor, unicode= unic, mod=None)
+ try:
+ pygame.event.post(evt)
+ except:
+ pass
+ return False
+
+ def mousedown(self, widget, event):
+ evt = pygame.event.Event(pygame.MOUSEBUTTONDOWN, button= event.button, pos=(int(event.x), int(event.y)))
+ try:
+ pygame.event.post(evt)
+ except:
+ pass
+ return False
+
+ def mousemotion(self, widget, event):
+ x, y, state = event.window.get_pointer()
+ rel = (x - self.mouse_pos[0], y - self.mouse_pos[1])
+ self.mouse_pos= (int(x), int(y))
+ self.button_state = [
+ state & gtk.gdk.BUTTON1_MASK and 1 or 0,
+ state & gtk.gdk.BUTTON2_MASK and 1 or 0,
+ state & gtk.gdk.BUTTON3_MASK and 1 or 0,
+ ]
+ evt = pygame.event.Event(pygame.MOUSEMOTION, pos= self.mouse_pos, rel=rel, buttons=self.button_state)
+ try:
+ pygame.event.post(evt)
+ except:
+ pass
+ return False
+
+ def expose(self, event, widget):
+ if pygame.display.get_init():
+ try:
+ pygame.event.post(pygame.event.Event(pygame.VIDEOEXPOSE))
+ except:
+ pass
+ return False # continue processing
+
+ def resize(self, widget, event):
+ evt = pygame.event.Event(pygame.VIDEORESIZE, size=(event.width,event.height), width=event.width, height=event.height)
+ try:
+ pygame.event.post(evt)
+ except:
+ pass
+ return False # continue processing
+
+ def set_focus(self, container, widget):
+ try:
+ pygame.display.update()
+ except:
+ pass
+ self.queue_draw()
+ return False
+
+# -----------------------------------------------
+# ******** El Juego en gtk ********
+# -----------------------------------------------
+class VentanaGTK(gtk.Window):
+ def __init__(self):
+ gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
+ self.set_title("CucaraSims")
+ self.fullscreen()
+
+ #self.set_size_request(800,600)
+ self.socket = gtk.Socket()
+ self.add(self.socket)
+
+ self.gtkplug= gtkplug()
+ self.socket.add_id(self.gtkplug.get_id())
+
+ self.add_events(gtk.gdk.ALL_EVENTS_MASK)
+ self.connect("destroy", self.salir)
+ self.connect("set-focus-child", self.refresh)
+ self.show_all()
+
+ def refresh(self, widget, datos):
+ try:
+ pygame.display.update()
+ except:
+ pass
+ self.queue_draw()
+ return True
+
+ def salir(self, widget):
+ pygame.quit()
+ sys.exit()
+
+class gtkplug(gtk.Plug):
+ def __init__(self):
+ gtk.Plug.__init__(self, 0L)
+ self.set_title("CucaraSims")
+ self.eventbox= PygameCanvas()
+ self.add(self.eventbox)
+ self.ventana= None
+ self.show_all()
+
+ self.connect("embedded", self.embed_event)
+
+ os.putenv('SDL_WINDOWID', str(self.eventbox.socket.get_id()))
+ gobject.idle_add(self.get_run_game)
+
+ def get_run_game(self):
+ self.eventbox.socket.window.set_cursor(None)
+ print "Lanzando CucaraSims."
+ pygame.init()
+ #x, y, w, y= self.eventbox.get_allocation()
+ #Main( (w,y) )
+ Main()
+ return False
+
+ def embed_event(self, widget):
+ print "Juego embebido"
+
+if __name__=="__main__":
+ VentanaGTK()
+ gtk.main()
diff --git a/Ficha_Bicho.py b/Ficha_Bicho.py
new file mode 100644
index 0000000..19c0346
--- /dev/null
+++ b/Ficha_Bicho.py
@@ -0,0 +1,147 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Ficha_Bicho.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, gc
+from pygame.locals import *
+
+gc.enable()
+
+import BiblioJAM
+from BiblioJAM.JAMLabel import JAMLabel
+import BiblioJAM.JAMGlobals as JAMG
+
+import Globals as VG
+MAGENTA= (255, 0, 255)
+
+class Ficha_Bicho(pygame.sprite.OrderedUpdates):
+ def __init__(self):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ self.bicho= None
+ x, y, self.separador= (10, 70, 13)
+
+ self.label_tiempo= JAMLabel("Años: 0 Dias: 0 Horas: 0")
+ self.label_tiempo.set_text(tamanio= 30)
+ self.label_tiempo.set_posicion( (x,y) )
+ self.add(self.label_tiempo)
+
+ y += self.label_tiempo.get_tamanio()[1] + self.separador
+ self.label_hambre= JAMLabel("Nivel de Apetito: ")
+ self.label_hambre.set_text(tamanio= 25)
+ self.label_hambre.set_posicion( (x,y) )
+ self.add(self.label_hambre)
+
+ y += self.label_hambre.get_tamanio()[1] + self.separador
+ self.label_sed= JAMLabel("Nivel de Sed: ")
+ self.label_sed.set_text(tamanio= 25)
+ self.label_sed.set_posicion( (x,y) )
+ self.add(self.label_sed)
+
+ self.barra_nutricion= Barra()
+ self.barra_nutricion.rect.x= self.label_tiempo.get_posicion()[0] + 170
+ self.barra_nutricion.rect.centery= self.label_hambre.get_posicion()[1]+ (self.label_hambre.get_tamanio()[1]/2)
+ self.add(self.barra_nutricion)
+
+ self.barra_hidratacion= Barra()
+ self.barra_hidratacion.rect.x= self.label_tiempo.get_posicion()[0] + 170
+ self.barra_hidratacion.rect.centery= self.label_sed.get_posicion()[1]+ (self.label_sed.get_tamanio()[1]/2)
+ self.add(self.barra_hidratacion)
+
+ self.circulo= Circulo( (60,60) )
+ self.add(self.circulo)
+
+ def set_bicho(self, bicho):
+ tamanio= (bicho.rect.w, bicho.rect.h)
+ self.circulo.image= pygame.transform.scale(self.circulo.imagen_original, (tamanio))
+ self.bicho= bicho
+
+ def update(self):
+ if self.bicho:
+ self.actualizar_datos()
+
+ def actualizar_datos(self):
+ edad = "Dias: %s Horas: %s" % (self.bicho.dias, self.bicho.horas)
+ if edad != self.label_tiempo.get_text():
+ self.label_tiempo.set_text(texto= edad)
+
+ nutricion = "Nutrición: %s" % (self.bicho.hambre)
+ if nutricion != self.label_hambre.get_text():
+ self.label_hambre.set_text(texto= nutricion)
+ self.barra_nutricion.set_valor(self.bicho.hambre)
+
+ hidratacion = "Hidratación: %s" % (self.bicho.sed)
+ if hidratacion != self.label_sed.get_text():
+ self.label_sed.set_text(texto= hidratacion)
+ self.barra_hidratacion.set_valor(self.bicho.sed)
+
+ self.circulo.rect.center= self.bicho.rect.center
+
+class Barra(pygame.sprite.Sprite):
+# Barra de Progreso
+ def __init__(self):
+ pygame.sprite.Sprite.__init__(self)
+ self.imagen_original= self.get_barra()
+ self.image= self.imagen_original.copy()
+ self.rect= self.image.get_rect()
+ self.ultimo_valor= 0
+
+ def set_valor(self, valor):
+ # actualiza el progreso en la barra
+ if valor == self.ultimo_valor: return
+ if valor >= 0 and valor <= 100:
+ verde = (0,255,0,1)
+ amarillo = (255,255,0,1)
+ rojo = (255,0,0,1)
+ if valor <= 33:
+ color = rojo
+ if valor > 33 and valor <= 66:
+ color = amarillo
+ if valor > 66:
+ color = verde
+
+ rectangulo = (0,0,valor,10)
+ self.image = self.imagen_original.copy()
+ pygame.draw.rect(self.image, color, rectangulo, 0)
+ elif valor > 100:
+ verde = (0,255,0,1)
+ rectangulo = (0,0,100,10)
+ self.image = self.imagen_original.copy()
+ pygame.draw.rect(self.image, verde, rectangulo, 0)
+ else:
+ self.image = self.imagen_original.copy()
+ self.ultimo_valor = valor
+
+ def get_barra(self):
+ superficie= JAMG.get_Rectangulo_Transparente( (100, 10) )
+ superficie= JAMG.get_my_surface_whit_border(superficie, (255,255,0,255), 2)
+ return superficie
+
+class Circulo(pygame.sprite.Sprite):
+ def __init__(self, tamanio):
+ pygame.sprite.Sprite.__init__(self)
+ self.imagen_original = self.get_surface(tamanio)
+ self.image = self.imagen_original.copy()
+ self.rect = self.image.get_rect()
+
+ def get_surface(self, tamanio_panel):
+ superficie= JAMG.get_Rectangulo_Transparente( tamanio_panel )
+ superficie= JAMG.get_my_surface_whit_border(superficie, (255,255,0,255), 5)
+ return superficie
+
diff --git a/Globals.py b/Globals.py
new file mode 100644
index 0000000..f5fb3b6
--- /dev/null
+++ b/Globals.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# VariablesGlobales.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import os
+
+RESOLUCION = (1200,900)
+
+BASE= os.path.dirname(__file__)
+DIRECTORIO_DATOS= os.path.join(BASE, 'data')
+ICONOS= os.path.join(BASE, "Iconos")
+CUCARACHAIMAGENES= os.path.join(BASE, "CUCARACHA", "Imagenes")
+CUCARACHASONIDOS= os.path.join(BASE, "CUCARACHA", "Sonidos")
+
+# -------------------------------- Cria de Cucarachas -------------------------------- #
+VELOCIDADJUEGO = 3
+MAXIMOCUCAS = 15
+
+# Datos Vitales
+ESCALASMUDAS = [(73,60),(83,70),(93,80),(103,90)]
+DIASMUDAS = [9,21,32,43]
+DIASREPRO = [51, 62, 73]
+DIASCADAVER = 3
+UNIDADALIMENTO = 333
+UNIDADAGUA = 333
+AUMENTAHAMBRE = 2 # por dia
+AUMENTASED = 2 # por dia
+RINDEALIMENTO = 5 # cada 30 pasadas update
+RINDEAGUA = 5
+CONSUMOALIMENTO = 10 # resta cuando come
+CONSUMOAGUA = 10
+NACER = 9 # incubacion de ooteca en dias
+
+# Limites vitales
+LIMITEHAMBRE = -126
+LIMITESED = -126
+LIMITEVIDA = 84
+
+CUCARACHA1 = os.path.join(CUCARACHAIMAGENES, "cucaracha1.png")
+CUCARACHA2 = os.path.join(CUCARACHAIMAGENES, "cucaracha2.png")
+CUCARACHA3 = os.path.join(CUCARACHAIMAGENES, "cucaracha3.png")
+CUCARACHA4 = os.path.join(CUCARACHAIMAGENES, "cucaracha4.png")
+
+SONIDOCUCARACHA = os.path.join(CUCARACHASONIDOS, "cucaracha.ogg")
+
+MUDAS = os.path.join(BASE, "CUCARACHA/Muda/")
+
+MUDA1 = os.path.join(CUCARACHAIMAGENES, "muda1.png")
+MUDA2 = os.path.join(CUCARACHAIMAGENES, "muda2.png")
+
+OOTECA = os.path.join(CUCARACHAIMAGENES, "huevos.png")
+REPRODUCCION1 = os.path.join(CUCARACHAIMAGENES, "reproduccion1.png")
+REPRODUCCION2 = os.path.join(CUCARACHAIMAGENES, "reproduccion2.png")
+CICLO1 = os.path.join(CUCARACHAIMAGENES, "ciclo_vital1.png")
+CICLO2 = os.path.join(CUCARACHAIMAGENES, "ciclo_vital2.png")
+CADAVER = os.path.join(CUCARACHAIMAGENES, "muerta.png")
+MUERTE = os.path.join(CUCARACHAIMAGENES, "muerte1.png")
+
+MUSICA1 = os.path.join(CUCARACHASONIDOS, "musica.ogg")
+MUSICA2 = os.path.join(CUCARACHASONIDOS, "musica2.ogg")
+
+FONDO4 = os.path.join(CUCARACHAIMAGENES, "fondo4.png")
+LOGO = os.path.join(CUCARACHAIMAGENES, "portada.png")
+
+# Interfaz
+FONDO = os.path.join(CUCARACHAIMAGENES, "fondo.png")
+PAN = os.path.join(CUCARACHAIMAGENES, "pan.png")
+JARRA = os.path.join(CUCARACHAIMAGENES, "jarra.png")
+AGUA = os.path.join(CUCARACHAIMAGENES, "agua.png")
+
+# Libreta de lectura
+FONDO_LIBRO = os.path.join(ICONOS, "libreta.png")
+
+# Iconos generales
+ICONOSAUDIO = [os.path.join(ICONOS, "audio1.png"), os.path.join(ICONOS, "audio2.png")]
+
+# Lecturas
+import CUCARACHA
+from CUCARACHA.Lectura import MUDA as leccionmuda
+from CUCARACHA.Lectura import REPRODUCCION as leccionreproduccion
+from CUCARACHA.Lectura import LECTURACICLOVITAL as lecturaciclovital
+from CUCARACHA.Lectura import LECTURAMUERTE as lecturamuerte
+from CUCARACHA.Lectura import LECTURAPLAGA as LecturaPlaga
+from CUCARACHA.Lectura import LECTURAENDGAME as endgame
+from CUCARACHA.Lectura import LECTURASEXTRAS as lecturasextras
+
+LECTURAMUDA = leccionmuda
+LECTURAREPRODUCCION = leccionreproduccion
+LECTURACICLOVITAL = lecturaciclovital
+LECTURAMUERTE = lecturamuerte
+LECTURAPLAGA = LecturaPlaga
+LECTURAENDGAME = endgame
+LECTURASEXTRAS = lecturasextras
diff --git a/Iconos/audio1.png b/Iconos/audio1.png
new file mode 100644
index 0000000..17774dd
--- /dev/null
+++ b/Iconos/audio1.png
Binary files differ
diff --git a/Iconos/audio2.png b/Iconos/audio2.png
new file mode 100644
index 0000000..d4985e0
--- /dev/null
+++ b/Iconos/audio2.png
Binary files differ
diff --git a/Iconos/libreta.png b/Iconos/libreta.png
new file mode 100644
index 0000000..3470cd7
--- /dev/null
+++ b/Iconos/libreta.png
Binary files differ
diff --git a/Interfaz.py b/Interfaz.py
new file mode 100644
index 0000000..82433ec
--- /dev/null
+++ b/Interfaz.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Interfaz.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, gc
+from pygame.locals import *
+
+gc.enable()
+
+import BiblioJAM
+from BiblioJAM.JAMButton import JAMButton
+from BiblioJAM.JAMLabel import JAMLabel
+import BiblioJAM.JAMGlobals as JAMG
+
+import Globals as VG
+
+class Interfaz(pygame.sprite.OrderedUpdates):
+ def __init__(self):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ separador = 10
+ self.boton_pan= JAMButton("", VG.PAN)
+ self.boton_pan.set_imagen(origen= VG.PAN)
+ ancho_botones= self.boton_pan.get_tamanio()[0]
+ self.boton_jarra= JAMButton("", VG.JARRA)
+ self.boton_jarra.set_imagen(origen= VG.JARRA)
+
+ x, y= VG.RESOLUCION[0] - separador - ancho_botones, separador
+
+ self.boton_pan.set_posicion(punto=(x,y))
+ y += self.boton_pan.get_tamanio()[1] + separador
+ self.boton_jarra.set_posicion(punto=(x,y))
+
+ y += self.boton_jarra.get_tamanio()[1] + separador*2
+ self.boton_ciclo= JAMButton("Ciclo Vital", None)
+ self.boton_ciclo.set_text(tamanio= 20)
+ self.boton_ciclo.set_tamanios(tamanio= (ancho_botones, 50))
+ self.boton_ciclo.set_posicion(punto=(x,y))
+
+ y += self.boton_ciclo.get_tamanio()[1] + separador
+ self.boton_muda= JAMButton("Muda", None)
+ self.boton_muda.set_text(tamanio= 20)
+ self.boton_muda.set_tamanios(tamanio= (ancho_botones, 50))
+ self.boton_muda.set_posicion(punto=(x,y))
+
+ y += self.boton_muda.get_tamanio()[1] + separador
+ self.boton_reproduccion= JAMButton("Reproducción", None)
+ self.boton_reproduccion.set_text(tamanio= 20)
+ self.boton_reproduccion.set_tamanios(tamanio= (ancho_botones, 50))
+ self.boton_reproduccion.set_posicion(punto=(x,y))
+
+ y += self.boton_reproduccion.get_tamanio()[1] + separador
+ self.boton_muerte= JAMButton("Muerte", None)
+ self.boton_muerte.set_text(tamanio= 20)
+ self.boton_muerte.set_tamanios(tamanio= (ancho_botones, 50))
+ self.boton_muerte.set_posicion(punto=(x,y))
+
+ y += self.boton_reproduccion.get_tamanio()[1] + separador
+ self.boton_plaga= JAMButton("Plaga", None)
+ self.boton_plaga.set_text(tamanio= 20)
+ self.boton_plaga.set_tamanios(tamanio= (ancho_botones, 50))
+ self.boton_plaga.set_posicion(punto=(x,y))
+
+ self.boton_salir= JAMButton("Salir", None)
+ self.boton_salir.set_text(tamanio= 20)
+ self.boton_salir.set_tamanios(tamanio= (ancho_botones, 50))
+ y = VG.RESOLUCION[1] - separador - self.boton_salir.get_tamanio()[1]
+ self.boton_salir.set_posicion(punto=(x,y))
+
+ self.imagenes_audio= VG.ICONOSAUDIO
+ self.boton_musica= JAMButton("", self.imagenes_audio[0])
+ self.boton_musica.set_imagen(origen= self.imagenes_audio[0])
+ self.boton_musica.set_tamanios(tamanio= (ancho_botones, 70))
+ y -= separador + self.boton_musica.get_tamanio()[1]
+ self.boton_musica.set_posicion(punto=(x,y))
+ self.posicion_boton_audio = (x,y)
+
+ self.boton_extras= JAMButton("Lectura", None)
+ self.boton_extras.set_text(tamanio= 20)
+ self.boton_extras.set_tamanios(tamanio= (ancho_botones, 50))
+ y -= separador + self.boton_extras.get_tamanio()[1]
+ self.boton_extras.set_posicion(punto=(x,y))
+
+ self.add(self.boton_pan)
+ self.add(self.boton_jarra)
+ self.add(self.boton_extras)
+ self.add(self.boton_musica)
+ self.add(self.boton_salir)
+
+ a,b,c= JAMG.get_estilo_celeste()
+ self.boton_pan.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_jarra.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_extras.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_musica.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_salir.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_ciclo.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_muda.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_reproduccion.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_muerte.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_plaga.set_colores(colorbas= a, colorbor= b, colorcara= c)
+
+ self.label_pan= JAMLabel("000")
+ self.label_pan.set_text(tamanio= 25, color= (255,255,255,255))
+ self.label_pan.set_imagen(origen= VG.PAN, tamanio= (40, 30))
+ self.label_pan.set_contenedor(colorbas= (0,0,0,255))
+ self.label_pan.set_posicion( (10,10) )
+ self.add(self.label_pan)
+
+ self.label_agua= JAMLabel("000")
+ self.label_agua.set_text(tamanio= 25, color= (255,255,255,255))
+ self.label_agua.set_imagen(origen= VG.AGUA, tamanio= (40, 30))
+ self.label_agua.set_contenedor(colorbas= (0,0,0,255))
+ x, y= self.label_pan.get_posicion()
+ w, h= self.label_pan.get_tamanio()
+ self.label_agua.set_posicion( (x+w+10, y) )
+ self.add(self.label_agua)
+
+ self.label_tiempo= JAMLabel("Tiempo de Juego = Años: 0 Dias: 0 Horas: 0")
+ self.label_tiempo.set_text(tamanio= 25)
+ x, y= self.label_agua.get_posicion()
+ w, h= self.label_agua.get_tamanio()
+ self.label_tiempo.set_posicion( (x+w+10, y) )
+ self.add(self.label_tiempo)
+
+ self.informacion_cucas = "Cucarachas: 0, Machos: 0, Hembras: 0, Ootecas: 0, Migración: 0"
+ self.label_cucas_info= JAMLabel(self.informacion_cucas)
+ self.label_cucas_info.set_text(tamanio= 25)
+ x, y= (10, VG.RESOLUCION[1] - 10 - self.label_cucas_info.get_tamanio()[1])
+ self.label_cucas_info.set_posicion( (x, y) )
+ self.add(self.label_cucas_info)
+
+ def set_pan_en_escenario(self, cantidad):
+ self.label_pan.set_text(texto= cantidad)
+
+ def set_agua_en_escenario(self, cantidad):
+ self.label_agua.set_text(texto= cantidad)
+
+ def set_tiempo_de_juego(self, tiempo):
+ self.label_tiempo.set_text(texto= tiempo)
+
+ def set_informacion_de_habitat(self, bichos):
+ if self.informacion_cucas != bichos:
+ self.informacion_cucas= bichos
+ self.label_cucas_info.set_text(texto= self.informacion_cucas)
+
diff --git a/Libreta_de_Lectura.py b/Libreta_de_Lectura.py
new file mode 100644
index 0000000..905a07b
--- /dev/null
+++ b/Libreta_de_Lectura.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Libreta_de_Lectura.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, gc, subprocess
+from pygame.locals import *
+
+gc.enable()
+
+import BiblioJAM
+from BiblioJAM.JAMButton import JAMButton
+import BiblioJAM.JAMGlobals as JAMG
+
+import Globals as VG
+
+class Libreta_de_Lectura(pygame.sprite.OrderedUpdates):
+ def __init__(self, lectura):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ self.sonido_ambiente= None
+ #self.sonido_select= JAMG.get_sound_select()
+ self.motor_de_voz= Motor_de_voz()
+ self.posicion_hoja= None
+ self.hoja= self.get_hoja()
+ self.texto= None
+ self.pagina_actual= ""
+ self.hoja_impresa= pygame.sprite.Sprite()
+
+ self.lectura= lectura
+ self.paginas= []
+ self.indice_pagina_actual= 0
+ self.set_lectura(self.lectura)
+
+ self.frame= self.get_frame()
+ self.boton_anterior, self.boton_leeme, self.boton_siguiente, self.boton_cerrar = self.get_botones_lectura()
+
+ self.add(self.hoja_impresa)
+ self.add(self.frame)
+ self.add(self.boton_anterior)
+ self.add(self.boton_leeme)
+ self.add(self.boton_siguiente)
+ self.add(self.boton_cerrar)
+
+ def next_pagina(self, button= None):
+ if len(self.paginas)-1 > self.indice_pagina_actual:
+ self.indice_pagina_actual += 1
+ else:
+ self.indice_pagina_actual = 0
+ self.hoja_impresa.image = self.paginas[self.indice_pagina_actual]
+ self.hoja_impresa.rect = self.hoja_impresa.image.get_rect()
+ self.set_posicion(punto=self.posicion_hoja)
+
+ def previous_pagina(self, button= None):
+ if self.indice_pagina_actual > 0:
+ self.indice_pagina_actual -= 1
+ else:
+ self.indice_pagina_actual = len(self.paginas)-1
+ self.hoja_impresa.image = self.paginas[self.indice_pagina_actual]
+ self.hoja_impresa.rect = self.hoja_impresa.image.get_rect()
+ self.set_posicion(punto=self.posicion_hoja)
+
+ def audio_stop(self):
+ self.sonido_ambiente.stop()
+
+ def play(self, sonido_ambiente, valor):
+ self.sonido_ambiente= pygame.mixer.Sound(sonido_ambiente)
+ self.sonido_ambiente.play(valor)
+
+ def set_posicion(self, punto= (0,0)):
+ # posicion de la hoja impresa
+ x, y= punto
+ self.hoja_impresa.rect.x, self.hoja_impresa.rect.y = x, y
+ self.frame.rect.x, self.frame.rect.y= (x, y)
+ self.posicion_hoja = punto
+
+ # Posicion de los botones
+ y= self.hoja_impresa.rect.h + y - self.boton_anterior.get_tamanio()[1] - 20
+ x= self.hoja_impresa.rect.centerx + 20
+ x-= self.boton_leeme.get_tamanio()[0]/2
+ self.boton_leeme.set_posicion(punto= (x, y))
+ a= x - 20 - self.boton_anterior.get_tamanio()[0]
+ self.boton_anterior.set_posicion(punto= (a, y))
+ b= x + 20 + self.boton_siguiente.get_tamanio()[0]
+ self.boton_siguiente.set_posicion(punto= (b, y))
+
+ x= self.hoja_impresa.rect.x + self.hoja_impresa.rect.w - 10 - self.boton_cerrar.get_tamanio()[0]
+ y= self.hoja_impresa.rect.y + 10
+ self.boton_cerrar.set_posicion(punto= (x, y))
+
+ def set_lectura(self, lectura):
+ # pasas un texto y lo imprime en la hoja
+ self.indice_pagina_actual = 0
+ self.lectura= lectura
+ self.paginas= []
+ for pagina in self.lectura:
+ hoja_impresa= self.get_hoja_impresa(pagina, self.hoja.copy())
+ self.paginas.append(hoja_impresa)
+
+ self.hoja_impresa.image= self.paginas[self.indice_pagina_actual]
+ self.hoja_impresa.rect= self.hoja_impresa.image.get_rect()
+
+ def get_hoja(self):
+ # superficie de hoja vacía
+ fondo= pygame.image.load(VG.FONDO_LIBRO)
+ superficie= JAMG.get_Rectangulo_Transparente( (500,648) )
+ y = 0
+ for x in range(1,19):
+ superficie.blit(fondo, (0,y))
+ y+= 36
+ return superficie
+
+ def get_hoja_impresa(self,texto, superficie):
+ y = 20
+ for linea in texto:
+ fuente= pygame.font.Font(pygame.font.match_font(pygame.font.get_default_font(), False, False), 26)
+ string_to_render= unicode( str(linea).decode("utf-8") )
+ imagen_fuente= fuente.render(string_to_render, 1, (0,0,0,1))
+ rectangulo_fuente= imagen_fuente.get_rect()
+ superficie.blit(imagen_fuente, (80,y))
+ y += rectangulo_fuente.h
+ return superficie
+
+ def get_frame(self):
+ frame= pygame.sprite.Sprite()
+ frame.image= JAMG.get_Rectangulo_Transparente( (self.hoja_impresa.rect.w, self.hoja_impresa.rect.h) )
+ frame.rect= frame.image.get_rect()
+ return frame
+
+ def get_botones_lectura(self):
+ x, y = 0,0
+ boton1= JAMButton("", JAMG.get_icon_back())
+ boton1.set_imagen(origen= JAMG.get_icon_back())
+ boton1.connect(callback= self.previous_pagina, sonido_select= None)
+ boton1.set_posicion(punto= (x,y))
+
+ x+= 25 + boton1.get_tamanio()[0]
+ boton2= JAMButton("", JAMG.get_icon_play())
+ boton2.set_imagen(origen= JAMG.get_icon_play())
+ boton2.set_posicion(punto=(x,y))
+
+ x+= 25 + boton2.get_tamanio()[0]
+ boton3= JAMButton("", JAMG.get_icon_next())
+ boton3.set_imagen(origen= JAMG.get_icon_next())
+ boton3.connect(callback= self.next_pagina, sonido_select= None)
+ boton3.set_posicion(punto= (x,y))
+
+ x+= 25 + boton2.get_tamanio()[0]
+ boton4= JAMButton("", JAMG.get_icon_exit())
+ boton4.set_imagen(origen= JAMG.get_icon_exit())
+ x= self.hoja_impresa.rect.x + self.hoja_impresa.rect.w - 10 - boton4.get_tamanio()[0]
+ y= self.hoja_impresa.rect.y + 10
+ boton4.set_posicion(punto= (x,y))
+
+ return boton1, boton2, boton3, boton4
+
+class Motor_de_voz():
+ def __init__(self):
+ pass
+ def lee(self, textbuffer):
+ pass
+ #subprocess.call(['espeak', "-ves", "-a 200", "-g 5", "-p 10", "--punct=<>", textbuffer])
+
diff --git a/Main.py b/Main.py
new file mode 100644
index 0000000..53835f5
--- /dev/null
+++ b/Main.py
@@ -0,0 +1,594 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Main.py por:
+# Flavio Danesse <fdanesse@gmail.com>
+# CeibalJAM! - Uruguay
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+import pygame, sys, threading, random, gc, gtk, pygtk
+from pygame.locals import *
+
+gc.enable()
+
+import BiblioJAM
+from BiblioJAM.JAMButton import JAMButton
+from BiblioJAM.JAMLabel import JAMLabel
+from BiblioJAM.JAMDialog import JAMDialog
+import BiblioJAM.JAMGlobals as JAMG
+
+import Globals as VG
+from Cria_Bichos_Main import Cria_Bichos_Main, Ooteca
+from Archivos_y_Directorios import Archivos_y_Directorios
+from Bicho import Bicho
+
+def Traduce_posiciones(VA, VH):
+ eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN)
+ for event in eventos:
+ x, y = event.pos
+ xx= x/VA
+ yy= y/VH
+ event_pos= (xx, yy)
+ for event in eventos:
+ evt = pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos= event_pos, button=event.button)
+ pygame.event.post(evt)
+
+ eventos= pygame.event.get(pygame.MOUSEMOTION)
+ for event in eventos:
+ x, y = event.pos
+ xx= x/VA
+ yy= y/VH
+ event_pos= (xx, yy)
+ for event in eventos:
+ evt = pygame.event.Event(pygame.MOUSEMOTION, pos= event_pos, rel=event.rel, buttons=event.buttons)
+ pygame.event.post(evt)
+
+class Main():
+ def __init__(self, res= None):
+ self.resolucionreal= res
+ # Variables para JAMatrix
+ self.ventana= None
+ self.name= "CucaraSims"
+
+ # Variables del Juego
+ self.fondo= None
+ self.reloj= None
+
+ # Escalado
+ self.ventana_real= None
+ self.VA= None
+ self.VH= None
+
+ self.sonido_select = None
+ self.sprites = pygame.sprite.OrderedUpdates()
+ self.Archivos_y_Directorios = None
+ self.base_de_datos = None
+ self.creditos = None
+ self.dialog_cerrar = None
+ self.menu = None
+ self.mensaje = None
+ self.Cria_Bichos= None
+
+ self.interval = 0
+ self.nivel = None
+
+ self.Juegos_guardados = None
+
+ self.preset()
+ self.load()
+ self.run()
+
+ def run(self):
+ self.nivel = "Menu"
+ self.sprites= self.menu
+ self.RunMenu()
+
+ def RunMenu(self):
+ pygame.mouse.set_visible(True)
+ self.Cria_Bichos.set_musica()
+ self.fondo= self.get_fondo2()
+ self.ventana.blit(self.fondo, (0,0))
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+
+ while self.nivel == "Menu":
+ self.reloj.tick(35)
+ while gtk.events_pending():
+ gtk.main_iteration(False)
+ Traduce_posiciones(self.VA, self.VH)
+ if self.mensaje: self.pause_menu()
+ self.sprites.clear(self.ventana, self.fondo)
+ self.sprites.update()
+ self.handle_event()
+ pygame.event.clear()
+ self.sprites.draw(self.ventana)
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+
+ if self.nivel == "CucaraSims":
+ self.Cria_Bichos.Run()
+ if self.nivel == "Creditos":
+ self.RunCreditos()
+
+ def handle_event(self):
+ if pygame.event.get(pygame.VIDEORESIZE): print "OK"
+ for event in pygame.event.get(pygame.KEYDOWN):
+ tecla= event.key
+ if tecla== pygame.K_ESCAPE:
+ if self.nivel == "Menu" and not self.mensaje:
+ self.selecciona_mensaje_cerrar(None)
+ elif self.nivel == "Creditos":
+ self.nivel = "Menu"
+ elif self.mensaje:
+ self.deselecciona_mensaje(None)
+
+ def pause_menu(self):
+ self.ventana.blit(self.fondo, (0,0))
+ while self.mensaje.sprites():
+ self.reloj.tick(35)
+ while gtk.events_pending():
+ gtk.main_iteration(False)
+ Traduce_posiciones(self.VA, self.VH)
+ self.mensaje.clear(self.ventana, self.fondo)
+ self.mensaje.update()
+ self.handle_event()
+ pygame.event.clear()
+ self.mensaje.draw(self.ventana)
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+
+ def deselecciona_mensaje(self, button= None):
+ self.mensaje= pygame.sprite.OrderedUpdates()
+
+ def selecciona_mensaje_cerrar(self, button= None):
+ self.mensaje= self.dialog_cerrar
+
+ def selecciona_menu_cargar(self, button= None):
+ self.deselecciona_mensaje(None)
+ self.Juegos_guardados= Juegos_Guardados(self.Archivos_y_Directorios, self)
+ self.mensaje= self.Juegos_guardados
+
+ def cargar_juego(self, datos):
+ # Carga el juegon Juego guardado seleccionado
+ # poner todo a cero
+ self.Cria_Bichos.Bichos.empty()
+ self.Cria_Bichos.cadaveres.empty()
+ self.Cria_Bichos.alimento.empty()
+ self.Cria_Bichos.ootecas.empty()
+ self.Cria_Bichos.agua.empty()
+ self.Cria_Bichos.ficha = pygame.sprite.OrderedUpdates()
+ self.Cria_Bichos.puntos = 0
+ self.Cria_Bichos.tiempo_de_juego = 0
+ self.Cria_Bichos.horas = 0
+ self.Cria_Bichos.dias = 0
+ self.Cria_Bichos.anios = 0
+ self.Cria_Bichos.machos, self.Cria_Bichos.hembras = 0,0
+
+ self.Cria_Bichos.secuencia_muda = 0
+ self.Cria_Bichos.reproduccion = 0
+ self.Cria_Bichos.nacimientos = 0
+ self.Cria_Bichos.muertes = 0
+ self.Cria_Bichos.plaga = 0
+
+ # recuperar datos
+ (base, datos_juego, cucas, ootecas) = datos # return (base, datos_juego, cucas, Ootecas)
+
+ self.base_de_datos = base
+
+ # datos generales del juego
+ # datos 0 Tabla Juego [anios, dias, horas, puntos]
+ self.Cria_Bichos.anios = int(datos_juego[1])
+ self.Cria_Bichos.dias = int(datos_juego[2])
+ self.Cria_Bichos.horas = int(datos_juego[3])
+ self.Cria_Bichos.puntos = int(datos_juego[4])
+
+ for cuca in cucas:
+ # datos de cucarachas
+ # datos 1 Tabla Cucas [sexo, anios, dias, horas, hambre, sed]
+ contador, sexo, anios, dias, horas, hambre, sed = cuca
+ tipo = None
+ while tipo != sexo:
+ bicho = Bicho(self.Cria_Bichos)
+ tipo = bicho.sexo
+ self.Cria_Bichos.Bichos.add(bicho)
+
+ if bicho.sexo == "M":
+ self.Cria_Bichos.machos += 1
+ elif bicho.sexo == "F":
+ self.Cria_Bichos.hembras += 1
+
+ bicho.anios = int(anios)
+ bicho.dias = int(dias)
+ bicho.horas = int(horas)
+ bicho.hambre = int(hambre)
+ bicho.sed = int(sed)
+
+ # escalar
+ for dia in range (0, bicho.dias):
+ # desde dia cero hasta los dias que tiene el bicho
+ if dia == bicho.control_mudas: # bicho.control_mudas es una lista de dias de mudas
+
+ indice = bicho.dias_mudas.index(dia)
+ bicho.set_muda(escala=bicho.escalas_mudas[indice]) # se obtiene el tamaño
+ bicho.velocidad += int(bicho.velocidad/3)
+
+ if indice+1 < len(bicho.dias_mudas):
+ bicho.control_mudas = bicho.dias_mudas[indice+1]
+ else:
+ bicho.control_mudas = bicho.dias_mudas[0]
+
+ print "CUCA: ", bicho.anios, bicho.dias, bicho.horas, bicho.hambre, bicho.sed
+
+ if self.Cria_Bichos.hembras + self.Cria_Bichos.machos != len(cucas):
+ print "HAY INCOHERENCIAS DE CANTIDAD DE BICHOS ALMACENADOS/CARGADOS"
+
+ for ooteca in ootecas:
+ # datos de cucarachas
+ # datos 2 Tabla ootecas [dias, horas, huevos]
+ contador, dias, horas, huevos = ooteca
+ ooteca = Ooteca(self.Cria_Bichos, posicion=(0,0))
+ self.Cria_Bichos.ootecas.add(ooteca)
+ ooteca.dias = int(dias)
+ ooteca.horas = int(horas)
+ ooteca.huevos = int(huevos)
+ print "ooteca: ", ooteca.dias, ooteca.horas, ooteca.huevos
+
+ self.deselecciona_mensaje(None)
+ self.nivel = "CucaraSims"
+
+ def get_new_game(self, button):
+ self.base_de_datos= self.Archivos_y_Directorios.CrearBasededatos()
+ self.Cria_Bichos.get_nuevo_Juego()
+ if self.base_de_datos:
+ self.nivel = "CucaraSims"
+ else:
+ print "Error al crear la base de datos"
+ #self.nivel = "CucaraSims"
+
+ def RunCreditos(self):
+ pygame.mixer.music.load(VG.MUSICA2)
+ pygame.mixer.music.play(-1, 0.0)
+ self.ventana.blit(self.fondo, (0,0))
+ pygame.display.update()
+ while self.nivel == "Creditos":
+ self.reloj.tick(35)
+ while gtk.events_pending():
+ gtk.main_iteration(False)
+ Traduce_posiciones(self.VA, self.VH)
+ self.creditos.clear(self.ventana, self.fondo)
+ self.creditos.update()
+ self.handle_event()
+ pygame.event.clear()
+ self.creditos.draw(self.ventana)
+ self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0))
+ pygame.display.update()
+ if self.nivel == "Menu":
+ self.RunMenu()
+
+ def get_fondo2(self, tamanio=VG.RESOLUCION):
+ superficie = pygame.transform.scale(pygame.image.load(VG.FONDO4), (VG.RESOLUCION))
+ return superficie
+
+ def get_creditos(self, button):
+ self.nivel= "Creditos"
+
+ def preset(self):
+ pygame.mouse.set_visible(False)
+ pygame.display.set_mode( (0,0), pygame.DOUBLEBUF | pygame.FULLSCREEN, 0)
+ A, B= VG.RESOLUCION
+ self.ventana= pygame.Surface( (A, B), flags=HWSURFACE )
+ self.ventana_real= pygame.display.get_surface()
+ C, D= (0, 0)
+ if not self.resolucionreal:
+ C= pygame.display.Info().current_w
+ D= pygame.display.Info().current_h
+ self.resolucionreal= (C,D)
+ else:
+ C, D= self.resolucionreal
+ self.VA= float(C)/float(A)
+ self.VH= float(D)/float(B)
+ pygame.display.set_caption("CucaraSims")
+ pygame.event.set_blocked([JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN,
+ KEYUP, VIDEORESIZE, VIDEOEXPOSE, USEREVENT, QUIT, ACTIVEEVENT])
+ pygame.event.set_allowed([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN])
+
+ def load(self):
+ pygame.mixer.init()
+ if not self.Archivos_y_Directorios: self.Archivos_y_Directorios= Archivos_y_Directorios(VG.DIRECTORIO_DATOS)
+ if not self.sonido_select: self.sonido_select= JAMG.get_sound_select()
+ if not self.reloj: self.reloj= pygame.time.Clock()
+ if not self.fondo: self.fondo= self.get_fondo()
+ if not self.menu:
+ self.menu= Menu()
+ self.menu.boton_nuevo.connect(callback= self.get_new_game, sonido_select= self.sonido_select)
+ self.menu.boton_cargar.connect(callback= self.selecciona_menu_cargar, sonido_select= self.sonido_select)
+ self.menu.boton_creditos.connect(callback= self.get_creditos, sonido_select= self.sonido_select)
+ self.menu.boton_salir.connect(callback= self.selecciona_mensaje_cerrar, sonido_select= self.sonido_select)
+
+ if not self.creditos: self.creditos= Creditos(self)
+
+ if not self.dialog_cerrar:
+ a,b,c= JAMG.get_estilo_naranja()
+ self.dialog_cerrar= JAMDialog(mensaje= "¿Deseas Salir del Juego?",
+ funcion_ok= self.salir, funcion_cancel= self.deselecciona_mensaje)
+ self.dialog_cerrar.set_colors_dialog(base= c, bordes= b)
+ self.dialog_cerrar.set_colors_buttons(colorbas= a, colorbor= b, colorcara= c)
+
+ if not self.Cria_Bichos: self.Cria_Bichos= Cria_Bichos_Main(self)
+
+ def get_fondo(self, color=(0,0,0,1), tamanio=VG.RESOLUCION):
+ superficie = pygame.Surface( tamanio, flags=HWSURFACE )
+ superficie.fill(color)
+ return superficie
+
+ def salir(self, button):
+ pygame.quit()
+ sys.exit()
+
+class Menu(pygame.sprite.OrderedUpdates):
+ def __init__(self):
+ pygame.sprite.OrderedUpdates.__init__(self)
+
+ separador = 40
+ ancho = 500
+ alto = 100
+
+ a,b,c= JAMG.get_estilo_celeste()
+ self.boton_nuevo = JAMButton("Juego Nuevo", None)
+ self.boton_cargar = JAMButton("Cargar Juego", None)
+ self.boton_creditos = JAMButton("Creditos", None)
+ self.boton_salir = JAMButton("Salir", None)
+
+ self.boton_nuevo.set_text(tamanio= 50)
+ self.boton_cargar.set_text(tamanio= 50)
+ self.boton_creditos.set_text(tamanio= 50)
+ self.boton_salir.set_text(tamanio= 50)
+
+ self.boton_nuevo.set_tamanios(tamanio= (ancho,alto))
+ self.boton_cargar.set_tamanios(tamanio= (ancho,alto))
+ self.boton_creditos.set_tamanios(tamanio= (ancho,alto))
+ self.boton_salir.set_tamanios(tamanio= (ancho,alto))
+
+ self.boton_nuevo.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_cargar.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_creditos.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.boton_salir.set_colores(colorbas= a, colorbor= b, colorcara= c)
+
+ y = 150
+ x = VG.RESOLUCION[0]/2 - self.boton_nuevo.get_tamanio()[0]/2
+ self.boton_nuevo.set_posicion(punto=(x,y))
+
+ y += self.boton_nuevo.get_tamanio()[1] + separador
+ x = VG.RESOLUCION[0]/2 - self.boton_cargar.get_tamanio()[0]/2
+ self.boton_cargar.set_posicion(punto=(x,y))
+
+ y += self.boton_cargar.get_tamanio()[1] + separador
+ x = VG.RESOLUCION[0]/2 - self.boton_creditos.get_tamanio()[0]/2
+ self.boton_creditos.set_posicion(punto=(x,y))
+
+ y += self.boton_creditos.get_tamanio()[1] + separador
+ x = VG.RESOLUCION[0]/2 - self.boton_salir.get_tamanio()[0]/2
+ self.boton_salir.set_posicion(punto=(x,y))
+
+ self.add(self.boton_nuevo)
+ self.add(self.boton_cargar)
+ self.add(self.boton_creditos)
+ self.add(self.boton_salir)
+
+class Creditos(pygame.sprite.OrderedUpdates):
+ def __init__(self, main):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ self.grupo1 = {}
+ self.grupo2 = {}
+ self.get_sprites()
+ self.seleccion = 1
+ self.velocidad = 4
+
+ self.main= main
+ self.cerrar= JAMButton("", None)
+ self.cerrar.set_imagen(origen= JAMG.get_icon_exit())
+ self.cerrar.set_tamanios(grosorbor= 1, espesor= 1)
+ self.cerrar.set_posicion(punto= (VG.RESOLUCION[0] - self.cerrar.get_tamanio()[0], 0) )
+ self.cerrar.connect(callback= self.salir, sonido_select= None)
+ a,b,c= JAMG.get_estilo_celeste()
+ self.cerrar.set_colores(colorbas= a, colorbor= b, colorcara= c)
+ self.add(self.cerrar)
+
+ def salir(self, button):
+ self.main.nivel = "Menu"
+
+ def update(self):
+ if self.seleccion == 1:
+ for num in self.grupo1.keys():
+ etiqueta, (x,y) = self.grupo1[num]
+ x, y= etiqueta.get_posicion()
+ y -= self.velocidad
+ etiqueta.set_posicion((x,y))
+ if y < -50:
+ self.seleccion = 2
+ for num in self.grupo1.keys():
+ etiqueta, (x,y) = self.grupo1[num]
+ etiqueta.set_posicion((x,y))
+
+ if self.seleccion == 2:
+ for num in self.grupo2.keys():
+ etiqueta, (x,y) = self.grupo2[num]
+ x, y= etiqueta.get_posicion()
+ y -= self.velocidad
+ etiqueta.set_posicion((x,y))
+ if y < -50:
+ self.seleccion = 1
+ for num in self.grupo2.keys():
+ etiqueta, (x,y) = self.grupo2[num]
+ etiqueta.set_posicion((x,y))
+ self.cerrar.update()
+
+ def get_sprites(self):
+ Textos1 = ["CucaraSims.",
+ "El Sims de las Cucarachas.",
+ "Para Aprender Jugando y Jugar Aprendiendo.",
+ "Dedicado con Cariño a mis Compañeros Voluntarios de",
+ "CeibalJAM!, RAP Ceibal y a Todos los Niños y Jóvenes",
+ "del Uruguay y demás comunidades Sugar."]
+
+ Textos2 = ["Idea Original, Edición de Audio y Video,",
+ "Diseño Gráfico, Desarrollo y Contenidos:",
+ "Flavio Danesse - fdanesse@gmail.com",
+ "Imágenes e Información: Wikipedia - Wikiespecies",
+ "Música: MATI - ARUAL - http://www.jamendo.com"]
+
+ color= JAMG.get_celeste1()
+ contador= 1
+
+ #logo= JAMLabel("")
+ #logo.set_imagen(origen= VG.LOGO)
+ logo= Logo()
+ x, y = VG.RESOLUCION[0]/2 - logo.get_tamanio()[0]/2, VG.RESOLUCION[1]
+ logo.set_posicion((x,y))
+ self.add(logo)
+ self.grupo1[contador]= logo, (x,y)
+
+ y += 95
+ contador += 1
+ # textos1
+ for texto in Textos1:
+ etiqueta= JAMLabel(texto)
+ etiqueta.set_text(tamanio= 40, color= color)
+
+ x = VG.RESOLUCION[0]/2 - etiqueta.get_tamanio()[0]/2
+ etiqueta.set_posicion((x,y))
+ self.add(etiqueta)
+ self.grupo1[contador] = etiqueta, (x,y)
+ y += 100
+ contador += 1
+
+ contador = 1
+ y = VG.RESOLUCION[1]
+ for texto in Textos2:
+ etiqueta= JAMLabel(texto)
+ etiqueta.set_text(tamanio= 40, color= color)
+ x = VG.RESOLUCION[0]/2 - etiqueta.get_tamanio()[0]/2
+ etiqueta.set_posicion((x,y))
+ self.add(etiqueta)
+ self.grupo2[contador] = etiqueta, (x,y)
+ y += 100
+ contador += 1
+
+class Logo(pygame.sprite.Sprite):
+ def __init__(self):
+ pygame.sprite.Sprite.__init__(self)
+ self.image= pygame.image.load(VG.LOGO)
+ self.rect= self.image.get_rect()
+ def get_tamanio(self):
+ return (self.rect.w, self.rect.h)
+ def set_posicion(self, punto= (0,0)):
+ self.rect.x, self.rect.y= punto
+ def get_posicion(self, punto= (0,0)):
+ return (self.rect.x, self.rect.y)
+
+class Juegos_Guardados(pygame.sprite.OrderedUpdates):
+ def __init__(self, archivosydirectorios, main):
+ pygame.sprite.OrderedUpdates.__init__(self)
+ self.juego_base= main
+ self.Archivos_y_Directorios= archivosydirectorios
+ lista_juegos_guardados= self.Archivos_y_Directorios.get_juegos()
+ self.directorio= lista_juegos_guardados[0] # string
+ self.juegos= lista_juegos_guardados[1] # lista
+
+ y = 50
+ self.items = []
+ w, h= (0,0)
+ for juego in self.juegos:
+ item= Item_Juego(self.Archivos_y_Directorios, juego, self)
+ item.agregate(self)
+ if item.etiqueta_juego.get_tamanio()[1] > h: h= item.etiqueta_juego.get_tamanio()[1]
+ if item.etiqueta_juego.get_tamanio()[0] > w: w= item.etiqueta_juego.get_tamanio()[0]
+ self.items.append(item)
+ for item in self.items:
+ x= VG.RESOLUCION[0]/2 - w/2
+ item.set_posicion(punto= (x, y))
+ y+= h+ 30
+
+ self.cerrar= JAMButton("", None)
+ self.cerrar.set_imagen(origen= JAMG.get_icon_exit())
+ self.cerrar.set_tamanios(grosorbor= 1, espesor= 1)
+ self.cerrar.set_posicion(punto= (VG.RESOLUCION[0] - self.cerrar.get_tamanio()[0], 0) )
+ self.cerrar.connect(callback= self.salir, sonido_select= None)
+ a,b,c= JAMG.get_estilo_celeste()
+ self.cerrar.set_colores(colorbas= a, colorbor= b, colorcara= c)
+
+ self.add(self.cerrar)
+
+ def salir(self, button= None):
+ self.juego_base.deselecciona_mensaje(None)
+
+ def reordenar_juegos(self, item):
+ self.items.remove(item)
+ #y= 50
+ #for item in self.items:
+ # x = VG.RESOLUCION[0]/2 - item.etiqueta_juego.rect.w/2
+ # item.set_posicion(punto= (x, y))
+ # y += item.etiqueta_juego.get_tamanio()[1] + 30
+
+class Item_Juego():
+ def __init__(self, archivosydirectorios, juego, grupo):
+ self.grupo= grupo
+ self.Archivos_y_Directorios= archivosydirectorios
+ self.juego= juego
+ self.separador= 10
+
+ a,b,c= JAMG.get_estilo_celeste()
+ self.etiqueta_juego= JAMLabel(juego)
+ self.etiqueta_juego.set_text(tamanio= 40)
+ self.etiqueta_juego.set_text(color= c)
+
+ self.boton_borrar= JAMButton("Borrar", None)
+ self.boton_borrar.set_text(tamanio= 30)
+ self.boton_borrar.set_tamanios(tamanio= (50, self.etiqueta_juego.get_tamanio()[1]), grosorbor= 1, espesor= 1)
+ self.boton_borrar.set_colores(colorbas= a, colorbor= b, colorcara= c)
+
+ self.boton_load= JAMButton("Cargar", None)
+ self.boton_load.set_text(tamanio= 30)
+ self.boton_load.set_tamanios(tamanio= (50, self.etiqueta_juego.get_tamanio()[1]), grosorbor= 1, espesor= 1)
+ self.boton_load.set_colores(colorbas= a, colorbor= b, colorcara= c)
+
+ self.boton_borrar.connect(callback= self.delete_game, sonido_select= None)
+ self.boton_load.connect(callback= self.carga_game, sonido_select= None)
+
+ def agregate(self, grupo):
+ grupo.add(self.etiqueta_juego)
+ grupo.add(self.boton_borrar)
+ grupo.add(self.boton_load)
+
+ def set_posicion(self, punto= (0,0)):
+ (x,y)= punto
+ self.etiqueta_juego.set_posicion((x,y))
+ a= x - self.separador - self.boton_borrar.get_tamanio()[0]
+ self.boton_borrar.set_posicion((a,y))
+ b= x + self.separador + self.etiqueta_juego.get_tamanio()[0]
+ self.boton_load.set_posicion((b,y))
+
+ def delete_game(self, button= None):
+ self.Archivos_y_Directorios.borrar_tabla(self.juego)
+ self.etiqueta_juego.kill()
+ self.boton_borrar.kill()
+ self.boton_load.kill()
+ self.grupo.reordenar_juegos(self)
+ return
+
+ def carga_game(self, button= None):
+ self.grupo.juego_base.cargar_juego(self.Archivos_y_Directorios.Leer_Base_de_Datos(self.juego))
+
diff --git a/activity/CucaraSims.svg b/activity/CucaraSims.svg
new file mode 100644
index 0000000..aac9508
--- /dev/null
+++ b/activity/CucaraSims.svg
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Generator: Adobe Illustrator 12.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 51448) -->
+
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ enable-background="new 0 0 50.878 48.833"
+ height="48.833"
+ id="Icon"
+ inkscape:version="0.47pre4 r22446"
+ overflow="visible"
+ sodipodi:docname="CucaraSims.svg"
+ version="1.1"
+ viewBox="0 0 50.878 48.833"
+ width="50.878"
+ xml:space="preserve"><metadata
+ id="metadata17"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs15"><inkscape:perspective
+ id="perspective19"
+ inkscape:persp3d-origin="25.438999 : 16.277667 : 1"
+ inkscape:vp_x="0 : 24.4165 : 1"
+ inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_z="50.877998 : 24.4165 : 1"
+ sodipodi:type="inkscape:persp3d" /><inkscape:perspective
+ id="perspective2841"
+ inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
+ inkscape:vp_x="0 : 0.5 : 1"
+ inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_z="1 : 0.5 : 1"
+ sodipodi:type="inkscape:persp3d" /><inkscape:perspective
+ id="perspective2993"
+ inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
+ inkscape:vp_x="0 : 0.5 : 1"
+ inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_z="1 : 0.5 : 1"
+ sodipodi:type="inkscape:persp3d" /></defs><sodipodi:namedview
+ bordercolor="#666666"
+ borderopacity="1"
+ gridtolerance="10"
+ guidetolerance="10"
+ id="namedview13"
+ inkscape:current-layer="Icon"
+ inkscape:cx="-27.381568"
+ inkscape:cy="35.606862"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-height="690"
+ inkscape:window-maximized="1"
+ inkscape:window-width="1366"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:zoom="4.8327975"
+ objecttolerance="10"
+ pagecolor="#ffffff"
+ showgrid="false" />
+
+
+
+
+
+
+
+<path
+ d="m 22.242858,18.206438 -2.491466,0.34825 -0.02408,-0.04819 -0.444574,0.168574 -0.453831,0.129687 0.02034,0.03517 -2.115437,0.803935 -1.137364,0.657603 -1.198503,1.018815 -0.120396,0.657598 0.600177,0.600177 -0.957688,0.477917 -1.737547,0.359365 -3.9511519,0.300087 -3.2342782,0.477914 -4.1308275,1.018817 0.5983174,0.300089 3.591786,-0.779857 4.6717362,-0.598326 1.437461,-0.05929 -3.4139627,1.556009 -4.3105229,2.276589 0.1796824,0.118554 6.7649342,-3.232424 2.934186,-0.95769 1.496735,0.05928 -1.676417,1.617136 0,0.179681 -1.794966,0.896558 -2.395137,0.479776 -1.7375528,1.317051 0.359366,0.898411 0,-0.718736 1.0780883,-0.778001 1.3763325,-0.120412 0.779854,-0.17968 0.657603,-0.05929 2.096908,-1.437452 0.477917,-0.179685 1.557866,-1.257772 0,0.600175 -1.378179,1.078087 0.418632,0.179684 -0.179682,0.418639 1.018815,2.035784 0.778008,1.617137 0.300085,-0.659453 -0.659452,-1.257777 -1.016959,-1.617138 1.496734,-0.957681 0.957683,0.898408 1.137367,0.479771 1.137368,-0.06114 0.359365,-0.298237 -0.17968,-0.778005 0.479772,-1.018813 2.274744,1.137367 1.215167,0.25378 1.300378,1.124398 -0.598317,0.657604 -0.600177,1.557863 0.300079,0.298233 0.05929,1.078093 1.078101,4.610602 0.598317,-0.05926 0,-0.957691 -0.477914,-1.37818 -0.120397,-1.496733 -0.179682,-1.735693 0.24081,-0.179681 0.657603,-0.300089 0.659453,-0.65945 -0.06114,-0.837284 0.300094,-0.598322 0.777999,-1.378181 0.479778,0.179684 1.13736,0.300086 0.659454,-0.240813 0.957689,0.718734 0.837281,0.06114 1.617141,-0.47977 1.198498,-0.837282 1.794971,-1.318906 1.378176,-0.118555 1.078084,1.078096 0.837283,0.957686 0.778007,0.418643 0.300091,0 2.335863,0.778002 0.359367,-0.418641 1.435597,0.05929 0.06115,1.018812 0.477915,-1.018812 -0.598326,-0.47792 -1.735691,0.238958 -2.096905,-0.837283 -1.016964,-1.557864 -1.557864,-1.376323 1.078094,-1.018819 1.257777,1.437462 2.156184,1.437451 0.372326,-0.620548 -0.192648,1.1596 0.778008,0.179681 0.898405,0.35936 0.657604,0.537195 0.120412,1.257777 0.359371,-1.257777 1.018806,0.53905 3.17315,-0.05929 0,-0.598323 -1.018812,-0.12038 -0.539048,-0.238958 -1.196642,-0.05929 -1.737552,-0.959538 0.4205,-0.477913 0.539044,-0.600182 -0.839134,0.300096 -0.418641,0.479768 -0.83913,-0.718734 0.598319,-1.078091 -0.657595,0.120396 -0.939167,0.552015 -2.773026,-1.809792 -1.018824,-0.777999 1.137372,-1.917228 -1.556009,1.676416 -0.839133,0.120382 -1.317045,0.539048 -0.657603,-0.479778 -2.995319,-1.257769 -4.790292,-1.196646 -3.712194,-0.539045 -2.693378,-0.179682 z"
+ id="path2872"
+ inkscape:export-filename="/home/flavio3/Escritorio/logo.png"
+ inkscape:export-xdpi="25"
+ inkscape:export-ydpi="25"
+ style="fill:#000000;fill-opacity:1;stroke:none" />
+</svg> \ No newline at end of file
diff --git a/activity/activity.info b/activity/activity.info
new file mode 100644
index 0000000..ddfc4ff
--- /dev/null
+++ b/activity/activity.info
@@ -0,0 +1,7 @@
+[Activity]
+name = CucaraSims
+activity_version = 2
+service_name = org.laptop.CucaraSims
+icon = CucaraSims
+show_launcher = yes
+class = CucaraSims.CucaraSims
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..6ea61a6
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,3 @@
+#!/usr/bin/python
+from sugar.activity import bundlebuilder
+bundlebuilder.start()