Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Cria_Bichos_Main.py
blob: f2c3fd0dee86b30a4eb622b49b3040fcccc51854 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
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