Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/parentesis.activity/parentesis.py
blob: ecc905ed6f0d026f5deb7ea619805747263afef2 (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
#!/usr/bin/env python
# -*- coding: cp1252 -*-

# example-start buttons buttons.py

import pygtk
pygtk.require('2.0')
import gtk
import pango
import logica
try:
    from sugar.activity.activity import Activity, ActivityToolbox
except:
    pass

ESTADO_VACIO = 0
ESTADO_IZQ = 1
ESTADO_DER = 2

IGUAL = "="

class Controlador:
   def __init__(self):
      print "CONTROLADOR INICIADO!"
      #self.serie = logica.generarCasos() # obtiene una serie o el conjunto de casos a resolver
      #self.total_casos = len(self.serie) # los casos totales de la serie
      #self.total_casos_pasados = 0       # cuenta los casos resueltos
      self.level = 1
      self.siguienteSerie()

   def siguienteSerie(self):
      self.serie = logica.generarCasos(nivel = self.level)
      self.total_casos = len(self.serie) # los casos totales de la serie
      self.total_casos_pasados = 0       # cuenta los casos resueltos
      self.casoActual = self.serie.pop()
      self.resActual  = eval(self.casoActual)
      self.fraccion_pbar = 1.0 / self.total_casos # calculo cuanto tiene que avanzar la barra en base a los casos totales
      self.listaCasosResueltos = []

   def siguienteCaso(self):
      """Obtiene el siguiente caso, si no hay mas casos, genera una serie"""
      self.total_casos_pasados += 1
      if self.serie: ## si quedan casos
         self.casoActual = self.serie.pop()
         self.resActual  = eval(self.casoActual)

   def imprimirEstado(self):
      """Da un resumen de las variables del controlador - Es para DEBUGGEO"""
      print ""
      print "############## ESTADO DEL CONTROLADOR ###################"
      print "Serie actual:", self.serie
      print "Total Casos :", self.total_casos_pasados, "/", self.total_casos
      print "Caso actual :", self.casoActual
      print "Res  actual :", self.resActual
      print "Casos res   :", self.listaCasosResueltos
      print "############## -------o-------------- ###################"
      print ""

   def disclaimer(self):
      print "Esta es una version de desarrollo! :)"
      
class Vista:
   def crear_ventana_principal(self, w):
      w.set_title("PARENTESIS BETA! - CeibalJam - Montevideo - Uruguay - ")
      w.connect("destroy", lambda wid: gtk.main_quit())
      w.connect("delete_event", lambda a1, a2:gtk.main_quit())
      w.set_border_width(10)
      w.resize(SCREENSIZE[0], SCREENSIZE[1])
      
      return w

   def crear_combo_box_niveles(self):
      cbox = gtk.combo_box_new_text()
      cbox.append_text('Nivel 1 (1..6 < 200)')
      cbox.append_text('Nivel 2 (1..9 < 500)')
      cbox.append_text('Nivel 3 (4..9)')
      cbox.set_active(0)                    # Selecciona el primero como activo

      return cbox
    
   def __init__(self, toplevel_window):
      # Create a new window
      self.window = self.crear_ventana_principal(toplevel_window)
      self.contr = Controlador()
      self.contr.disclaimer()
      self.contr.imprimirEstado()

      self.contr.siguienteSerie() ## Creo una serie para poder tener datos del problema para desplegar en la VISTA
      print "EL CASO ACTUAL ES", self.contr.casoActual
      self.vbox = gtk.VBox()
      self.vbox.show()
      self.hbox = gtk.HBox()
      self.hbox.show()	  
      self.et_instruc = self.crear_etiqueta_instrucciones()
      self.et_instruc.show()
      self.et_estado = gtk.Label("Aqui van a ir mensajes de feedback")
      self.et_estado.show()
      

      self.combobox = self.crear_combo_box_niveles()
      self.combobox.connect("changed", self.level_changed)
      self.combobox.show()
 
      self.botonAyuda = self.crear_boton_ayuda()
      self.botonAyuda.show()

      self.hbox_niveles_y_ayuda = gtk.HBox()
      self.hbox_niveles_y_ayuda.show()
      
      self.hbox_niveles_y_ayuda.pack_start(self.combobox)
      self.hbox_niveles_y_ayuda.pack_start(self.botonAyuda)
      
      self.botonCambiar = self.crear_boton_cambiar()
      self.botonCambiar.show()

      self.botonSolucion = self.crear_boton_solucion()
      self.botonSolucion.show()

      self.hbox_cambiar_y_mensajes = gtk.HBox()
      self.hbox_cambiar_y_mensajes.show()
      self.hbox_cambiar_y_mensajes.pack_start(self.botonCambiar)

      self.pbar = gtk.ProgressBar()      
      self.pbar.show()

      self.et_sol = gtk.Label("La respuesta es **********")
      self.et_sol.show()
            
      self.vbox.pack_start(self.et_instruc)
      self.vbox.pack_start(self.hbox_niveles_y_ayuda)
      self.vbox.pack_start(self.hbox)
      self.vbox.pack_start(self.pbar)
      self.vbox.pack_start(self.hbox_cambiar_y_mensajes)
      self.vbox.pack_start(self.botonSolucion)
      self.vbox.pack_start(self.et_estado)
      self.vbox.pack_start(self.et_sol)
     
      global standalone_mode
      if not standalone_mode:
        toolbox = ActivityToolbox(self.window)
        self.window.set_toolbox(toolbox)
        toolbox.show()
        self.window.set_canvas(self.vbox)
      else:
        self.window.add(self.vbox)

      self.MostrarProblema(self.contr.casoActual)      
      self.window.show()

   def level_changed(self, combobox):
      self.contr.level = combobox.get_active() + 1
      self.contr.siguienteSerie()
      self.MostrarProblema(self.contr.casoActual)
    
   def crear_etiqueta_instrucciones(self):
      et = gtk.Label("Debes poner los parentesis para que el resultado sea " +
                     str(self.contr.resActual))
      et.show()
      return et
   
   def MostrarProblema(self, prob):
      self.solucion_izquierdos = set()
      self.solucion_derechos = set()
      self.et_instruc.set_text("Debes poner los parentesis para que el resultado sea " +
                     str(self.contr.resActual))
      self.et_sol.set_text("La respuesta es **********")
      
      for w in self.hbox.get_children(): 
         self.hbox.remove(w)

      prob = self.contr.casoActual  
      prob_str = prob
      prob = list(prob)
      pos = 0
      boton = self.crear_boton(pos)
      self.agregar_widget(boton)
      while pos < len(prob):
          car = prob[pos]
          if car == "(":
              self.solucion_izquierdos.add(pos)
              pos = pos + 1
          elif car == ")":
              self.solucion_derechos.add(pos)
              pos = pos + 1
          else:
              car_etiqueta = gtk.Label(car)
              self.agregar_widget(car_etiqueta)
              pos = pos + 1
              boton = self.crear_boton(pos)
              self.agregar_widget(boton)
              
      igual = self.crear_boton_igual()
      self.agregar_widget(igual)
      self.agregar_widget(gtk.Label(eval(prob_str)))
      
   def agregar_widget(self, widget):
      ''' Agrega el boton a la lista de botones '''
      self.hbox.pack_start(widget)
      widget.show()
      
   def crear_boton(self, pos):
      boton = BotonParentesis(pos)
      boton.connect('clicked', self.boton_activado)
      return boton
      
   def crear_boton_igual(self):
      boton = gtk.Button(IGUAL)
      boton.connect('clicked', self.boton_igual_activado)
      return boton

   def crear_boton_cambiar(self):
      boton = gtk.Button("Cambiar numeros")
      boton.connect('clicked', self.boton_cambiar_activado)
      return boton
   
   def crear_boton_ayuda(self):
      boton = gtk.Button(stock=gtk.STOCK_HELP)
      boton.connect('clicked', self.boton_ayuda_activado)
      return boton

   def crear_boton_solucion(self):
      boton = gtk.Button("Ver solucion")
      boton.connect('clicked', self.boton_solucion_activado)
      return boton
   
   def crear_dialogo_ayuda(self):
      dialogo = gtk.Dialog("Ayuda :)") #, parent=None, flags=0, buttons=None)   
      dialogo.resize(800,400)
      et = gtk.Label("Este es el texto para la ayuda, hay que ver que le ponemos")
      et.show()
      dialogo.vbox.pack_start(et)
      dialogo.show()
      return dialogo

   def boton_activado(self, boton):
      boton.iterarEstado()

   def boton_cambiar_activado(self, boton):
      self.pbar.set_fraction(0.0)
      self.contr.siguienteSerie()
      self.MostrarProblema(self.contr.casoActual)
      
   def boton_solucion_activado(self, boton):
      self.et_sol.set_text(self.contr.casoActual)
      
   def boton_ayuda_activado(self, boton):      
      dialog = self.crear_dialogo_ayuda()      
      
   def boton_igual_activado(self, boton):       
      respuesta_izquierdos = set()
      respuesta_derechos = set()
      for widget in self.hbox.get_children():
          if isinstance(widget,BotonParentesis):
              estado = widget.getEstado()
              if estado == ESTADO_IZQ:
                  respuesta_izquierdos.add(widget.getPos())
              if estado == ESTADO_DER:
                  respuesta_derechos.add(widget.getPos())
      
      if respuesta_izquierdos == self.solucion_izquierdos and respuesta_derechos == self.solucion_derechos:
          self.et_estado.set_label("Muy bien!")
          self.contr.listaCasosResueltos.append(self.contr.casoActual)
          new_val = self.pbar.get_fraction() + self.contr.fraccion_pbar
          if new_val > 1.0:
             new_val = 0.0
     
          self.pbar.set_fraction(new_val)
          
          self.contr.siguienteCaso()          
          self.contr.imprimirEstado()
          if self.contr.total_casos_pasados == self.contr.total_casos:
             self.contr.siguienteSerie()
             self.pbar.set_fraction(0.0)
          self.MostrarProblema(self.contr.casoActual)
      else:
          self.et_estado.set_label("INCORRECTO!: Esta mal. Muy feo.")
      ## Si no completo la serie
          ##Paso al caso siguiente
      ## ELSE: paso a la SERIE siguiente

class BotonParentesis(gtk.Button):
    
    def __init__(self, pos):
        gtk.Button.__init__(self, "")
        self._pos = pos
        self._estado = ESTADO_VACIO
    
    def getPos(self):
        return self._pos
    
    def setPos(self, pos):
        self._pos = pos
    
    def iterarEstado(self):
        if self._estado == ESTADO_VACIO:
            self._estado = ESTADO_IZQ
            self.set_label("(")
        elif self._estado == ESTADO_IZQ:
            self._estado = ESTADO_DER
            self.set_label(")")
        elif self._estado == ESTADO_DER:
            self._estado = ESTADO_VACIO
            self.set_label("")

    def getEstado(self):
        return self._estado

# This function is the common entry point for sugar and standalone mode
# standalone is a boolean indicating Standalone mode or Sugar mode.
def init(standalone, toplevel_window):
    # Sets a global variables
    global standalone_mode, SCREENSIZE, SCALE, FONT_SIZE
    standalone_mode = standalone
    if standalone:
        SCREENSIZE = (600,412)
        SCALE = (1./2, 1./2)
        FONT_SIZE = 18
        font_desc = pango.FontDescription("sans 72")
        if font_desc:
            toplevel_window.modify_font(font_desc)
    else:
        SCREENSIZE = (1200,825)
        SCALE = (1, 1)
        FONT_SIZE = 36
    Vista(toplevel_window)

# This is the main function in standalone mode
def main():
    toplevel_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    init(True, toplevel_window)
    gtk.main()
    return 0

if __name__ == "__main__":
   main()